From 6f52a5380d9c769b831885fb249f9a25881df81c Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Tue, 19 Sep 2023 14:27:13 +0100 Subject: [PATCH] Fix creation of stored procedures that contain insert statements (#1088) --- CHANGELOG.md | 4 ++++ .../sqlserver/database_statements.rb | 2 +- test/cases/migration_test_sqlserver.rb | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 501714c3b..f57bdab0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ - [#1073](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1073) Improve performance of view default function lookup +#### Fixed + +- [#1088](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1088) Fix creation of stored procedures that contain insert statements + ## v7.0.3.0 #### Fixed diff --git a/lib/active_record/connection_adapters/sqlserver/database_statements.rb b/lib/active_record/connection_adapters/sqlserver/database_statements.rb index 5e154b6b2..522d9fac2 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_statements.rb @@ -406,7 +406,7 @@ def query_requires_identity_insert?(sql) end def insert_sql?(sql) - !(sql =~ /^\s*(INSERT|EXEC sp_executesql N'INSERT)/i).nil? + !(sql =~ /\A\s*(INSERT|EXEC sp_executesql N'INSERT)/i).nil? end def identity_columns(table_name) diff --git a/test/cases/migration_test_sqlserver.rb b/test/cases/migration_test_sqlserver.rb index 132d69115..74b14eb18 100644 --- a/test/cases/migration_test_sqlserver.rb +++ b/test/cases/migration_test_sqlserver.rb @@ -115,4 +115,22 @@ class MigrationTestSQLServer < ActiveRecord::TestCase refute_includes schemas, { "name" => "some schema" } end end + + describe 'creating stored procedure' do + it 'stored procedure contains inserts are created successfully' do + sql = <<-SQL + CREATE OR ALTER PROCEDURE do_some_task + AS + IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = 'U' AND name = 'SomeTableName') + BEGIN + CREATE TABLE SomeTableName (SomeNum int PRIMARY KEY CLUSTERED); + INSERT INTO SomeTableName(SomeNum) VALUES(1); + END + SQL + + assert_nothing_raised { connection.execute(sql) } + ensure + connection.execute("DROP PROCEDURE IF EXISTS dbo.do_some_task;") + end + end end