Skip to content

Commit 7e76a8e

Browse files
committed
Support string returning clause for AR#insert_all
[Rails added](rails/rails@c7613dd) support to string returning clause for `insert_all`. This PR port that behaviour. We are not manipulating the string in any way, which means that clients need to use `INSERTED.column_name`
1 parent 1965050 commit 7e76a8e

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@
1313

1414
- [#972](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/972) Support `ActiveRecord::QueryLogs`
1515
- [#981](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/981) Support `find_by` an encrypted attribute
16+
- [#985](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/985) Support string returning clause for `ActiveRecord#insert_all`
1617

1718
Please check [6-1-stable](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/blob/6-1-stable/CHANGELOG.md) for previous changes.

lib/active_record/connection_adapters/sqlserver/database_statements.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,12 @@ def build_insert_sql(insert) # :nodoc:
149149
sql = +"INSERT #{insert.into}"
150150

151151
if returning = insert.send(:insert_all).returning
152-
sql << " OUTPUT " << returning.map { |column| "INSERTED.#{quote_column_name(column)}" }.join(", ")
152+
returning_sql = if returning.is_a?(String)
153+
returning
154+
else
155+
returning.map { |column| "INSERTED.#{quote_column_name(column)}" }.join(", ")
156+
end
157+
sql << " OUTPUT #{returning_sql}"
153158
end
154159

155160
sql << " #{insert.values_list}"

test/cases/coerced_tests.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2082,3 +2082,14 @@ def test_disable_joins_through_with_enum_type_coerced
20822082
assert_match(/\[memberships\]\.\[type\]/, no_joins.first)
20832083
end
20842084
end
2085+
2086+
class InsertAllTest < ActiveRecord::TestCase
2087+
coerce_tests! :test_insert_all_returns_requested_sql_fields
2088+
# Same as original but using INSERTED.name as UPPER argument
2089+
def test_insert_all_returns_requested_sql_fields_coerced
2090+
skip unless supports_insert_returning?
2091+
2092+
result = Book.insert_all! [{ name: "Rework", author_id: 1 }], returning: Arel.sql("UPPER(INSERTED.name) as name")
2093+
assert_equal %w[ REWORK ], result.pluck("name")
2094+
end
2095+
end

0 commit comments

Comments
 (0)