Skip to content

Commit 663aaec

Browse files
authored
Enable identity insert on view's base table for fixtures (#1335)
1 parent 1c5fb1f commit 663aaec

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
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
@@ -17,9 +17,6 @@ def perform_query(raw_connection, sql, binds, type_casted_binds, prepare:, notif
1717
id_insert_table_name = query_requires_identity_insert?(sql)
1818

1919
result, affected_rows = if id_insert_table_name
20-
# If the table name is a view, we need to get the base table name for enabling identity insert.
21-
id_insert_table_name = view_table_name(id_insert_table_name) if view_exists?(id_insert_table_name)
22-
2320
with_identity_insert_enabled(id_insert_table_name, raw_connection) do
2421
internal_exec_sql_query(sql, raw_connection)
2522
end
@@ -264,11 +261,14 @@ def execute_procedure(proc_name, *variables)
264261
end
265262

266263
def with_identity_insert_enabled(table_name, conn)
267-
table_name = quote_table_name(table_name)
268-
set_identity_insert(table_name, conn, true)
264+
# If the table name is a view, we need to get the base table name for enabling identity insert.
265+
table_name = view_table_name(table_name) if view_exists?(table_name)
266+
quoted_table_name = quote_table_name(table_name)
267+
268+
set_identity_insert(quoted_table_name, conn, true)
269269
yield
270270
ensure
271-
set_identity_insert(table_name, conn, false)
271+
set_identity_insert(quoted_table_name, conn, false)
272272
end
273273

274274
def use_database(database = nil)

test/cases/view_test_sqlserver.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,16 @@ class ViewTestSQLServer < ActiveRecord::TestCase
5353
end
5454

5555
describe "identity insert" do
56-
it "identity insert works with views" do
57-
assert_difference("SSTestCustomersView.count", 1) do
56+
it "creates table record through a view" do
57+
assert_difference("SSTestCustomersView.count", 2) do
5858
SSTestCustomersView.create!(id: 5, name: "Bob")
59+
SSTestCustomersView.create!(id: 6, name: "Tim")
5960
end
6061
end
62+
63+
it "creates table records through a view using fixtures" do
64+
ActiveRecord::FixtureSet.create_fixtures(File.join(ARTest::SQLServer.test_root_sqlserver, "fixtures"), ["sst_customers_view"])
65+
assert_equal SSTestCustomersView.all.count, 2
66+
end
6167
end
6268
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)