@@ -217,6 +217,55 @@ def test_binds_are_logged_coerced
217217 coerce_tests! :test_statement_cache_with_find_by
218218 coerce_tests! :test_statement_cache_with_in_clause
219219 coerce_tests! :test_statement_cache_with_sql_string_literal
220+
221+ # Same as original coerced test except prepared statements include `EXEC sp_executesql` wrapper.
222+ coerce_tests! :test_bind_params_to_sql_with_prepared_statements , :test_bind_params_to_sql_with_unprepared_statements
223+ def test_bind_params_to_sql_with_prepared_statements_coerced
224+ assert_bind_params_to_sql_coerced ( prepared : true )
225+ end
226+
227+ def test_bind_params_to_sql_with_unprepared_statements_coerced
228+ @connection . unprepared_statement do
229+ assert_bind_params_to_sql_coerced ( prepared : false )
230+ end
231+ end
232+
233+ private
234+
235+ def assert_bind_params_to_sql_coerced ( prepared :)
236+ table = Author . quoted_table_name
237+ pk = "#{ table } .#{ Author . quoted_primary_key } "
238+
239+ # prepared_statements: true
240+ #
241+ # EXEC sp_executesql N'SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (@0, @1, @2) OR [authors].[id] IS NULL)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3
242+ #
243+ # prepared_statements: false
244+ #
245+ # SELECT [authors].* FROM [authors] WHERE ([authors].[id] IN (1, 2, 3) OR [authors].[id] IS NULL)
246+ #
247+ sql_unprepared = "SELECT #{ table } .* FROM #{ table } WHERE (#{ pk } IN (#{ bind_params ( 1 ..3 ) } ) OR #{ pk } IS NULL)"
248+ sql_prepared = "EXEC sp_executesql N'SELECT #{ table } .* FROM #{ table } WHERE (#{ pk } IN (#{ bind_params ( 1 ..3 ) } ) OR #{ pk } IS NULL)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3"
249+
250+ authors = Author . where ( id : [ 1 , 2 , 3 , nil ] )
251+ assert_equal sql_unprepared , @connection . to_sql ( authors . arel )
252+ assert_sql ( prepared ? sql_prepared : sql_unprepared ) { assert_equal 3 , authors . length }
253+
254+ # prepared_statements: true
255+ #
256+ # EXEC sp_executesql N'SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (@0, @1, @2)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3
257+ #
258+ # prepared_statements: false
259+ #
260+ # SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (1, 2, 3)
261+ #
262+ sql_unprepared = "SELECT #{ table } .* FROM #{ table } WHERE #{ pk } IN (#{ bind_params ( 1 ..3 ) } )"
263+ sql_prepared = "EXEC sp_executesql N'SELECT #{ table } .* FROM #{ table } WHERE #{ pk } IN (#{ bind_params ( 1 ..3 ) } )', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3"
264+
265+ authors = Author . where ( id : [ 1 , 2 , 3 , 9223372036854775808 ] )
266+ assert_equal sql_unprepared , @connection . to_sql ( authors . arel )
267+ assert_sql ( prepared ? sql_prepared : sql_unprepared ) { assert_equal 3 , authors . length }
268+ end
220269 end
221270end
222271
0 commit comments