Skip to content

Commit 541b070

Browse files
committed
Enable identity insert on view's base table for fixtures
1 parent c429a1c commit 541b070

File tree

3 files changed

+21
-9
lines changed

3 files changed

+21
-9
lines changed

lib/active_record/connection_adapters/sqlserver/database_statements.rb

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@ def internal_exec_query(sql, name = "SQL", binds = [], prepare: false, async: fa
4242
log(sql, name, binds, async: async) do |notification_payload|
4343
with_raw_connection do |conn|
4444
result = if id_insert_table_name = query_requires_identity_insert?(sql)
45-
# If the table name is a view, we need to get the base table name for enabling identity insert.
46-
id_insert_table_name = view_table_name(id_insert_table_name) if view_exists?(id_insert_table_name)
47-
4845
with_identity_insert_enabled(id_insert_table_name, conn) do
4946
internal_exec_sql_query(sql, conn)
5047
end
@@ -194,11 +191,14 @@ def execute_procedure(proc_name, *variables)
194191
end
195192

196193
def with_identity_insert_enabled(table_name, conn)
197-
table_name = quote_table_name(table_name)
198-
set_identity_insert(table_name, conn, true)
194+
# If the table name is a view, we need to get the base table name for enabling identity insert.
195+
table_name = view_table_name(table_name) if view_exists?(table_name)
196+
quoted_table_name = quote_table_name(table_name)
197+
198+
set_identity_insert(quoted_table_name, conn, true)
199199
yield
200200
ensure
201-
set_identity_insert(table_name, conn, false)
201+
set_identity_insert(quoted_table_name, conn, false)
202202
end
203203

204204
def use_database(database = nil)

test/cases/view_test_sqlserver.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,17 @@ class ViewTestSQLServer < ActiveRecord::TestCase
4848
end
4949
end
5050

51-
describe 'identity insert' do
52-
it "identity insert works with views" do
53-
assert_difference("SSTestCustomersView.count", 1) do
51+
describe "identity insert" do
52+
it "creates table record through a view" do
53+
assert_difference("SSTestCustomersView.count", 2) do
5454
SSTestCustomersView.create!(id: 5, name: "Bob")
55+
SSTestCustomersView.create!(id: 6, name: "Tim")
5556
end
5657
end
58+
59+
it "creates table records through a view using fixtures" do
60+
ActiveRecord::FixtureSet.create_fixtures(File.join(ARTest::SQLServer.test_root_sqlserver, "fixtures"), ["sst_customers_view"])
61+
assert_equal SSTestCustomersView.all.count, 2
62+
end
5763
end
5864
end

test/fixtures/sst_customers_view.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
david:
2+
name: "David"
3+
balance: 2,004
4+
aidan:
5+
name: "Aidan"
6+
balance: 10,191

0 commit comments

Comments
 (0)