From 86655aa503d5fcac1994ca460c8730dba9acf906 Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Tue, 1 Oct 2024 14:27:00 +0100 Subject: [PATCH] Enable identity insert on view's base table --- CHANGELOG.md | 6 ++++++ .../connection_adapters/sqlserver/database_statements.rb | 3 +++ test/cases/view_test_sqlserver.rb | 8 ++++++++ 3 files changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 079a70ba0..af4b7b9b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +#### Unreleased + +#### Fixed + +- [#1231](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1231) Enable identity insert on view's base table + ## v7.1.7 #### Fixed diff --git a/lib/active_record/connection_adapters/sqlserver/database_statements.rb b/lib/active_record/connection_adapters/sqlserver/database_statements.rb index 308b7050e..fdc1a82a2 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_statements.rb @@ -45,6 +45,9 @@ def internal_exec_query(sql, name = "SQL", binds = [], prepare: false, async: fa log(sql, name, binds, async: async) do with_raw_connection do |conn| if id_insert_table_name = query_requires_identity_insert?(sql) + # If the table name is a view, we need to get the base table name for enabling identity insert. + id_insert_table_name = view_table_name(id_insert_table_name) if view_exists?(id_insert_table_name) + with_identity_insert_enabled(id_insert_table_name, conn) do result = internal_exec_sql_query(sql, conn) end diff --git a/test/cases/view_test_sqlserver.rb b/test/cases/view_test_sqlserver.rb index b371bd0b1..04f14b957 100644 --- a/test/cases/view_test_sqlserver.rb +++ b/test/cases/view_test_sqlserver.rb @@ -47,4 +47,12 @@ class ViewTestSQLServer < ActiveRecord::TestCase assert_equal 1, klass.count end end + + describe 'identity insert' do + it "identity insert works with views" do + assert_difference("SSTestCustomersView.count", 1) do + SSTestCustomersView.create!(id: 5, name: "Bob") + end + end + end end