From 63b6854298d7d32d2a2698392f87dc41af0341a4 Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Wed, 16 Oct 2024 10:44:36 +0100 Subject: [PATCH] Fix queries with date and date-time placeholder conditions (#1247) --- CHANGELOG.md | 1 + .../sqlserver/database_statements.rb | 14 ++++---------- test/cases/adapter_test_sqlserver.rb | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da0510f09..2a2e40f0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ #### Fixed - [#1244](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1244) Allow INSERT statements with SELECT notation +- [#1247](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1247) Fix queries with date and date-time placeholder conditions ## v7.2.1 diff --git a/lib/active_record/connection_adapters/sqlserver/database_statements.rb b/lib/active_record/connection_adapters/sqlserver/database_statements.rb index 009d79a01..64a3ed22b 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_statements.rb @@ -339,7 +339,7 @@ def sp_executesql_sql_type(attr) end end - value = basic_attribute_type?(attr) ? attr : attr.value_for_database + value = active_model_attribute?(attr) ? attr.value_for_database : attr if value.is_a?(Numeric) value > 2_147_483_647 ? "bigint".freeze : "int".freeze @@ -349,7 +349,7 @@ def sp_executesql_sql_type(attr) end def sp_executesql_sql_param(attr) - return quote(attr) if basic_attribute_type?(attr) + return quote(attr) unless active_model_attribute?(attr) case value = attr.value_for_database when Type::Binary::Data, ActiveRecord::Type::SQLServer::Data @@ -359,14 +359,8 @@ def sp_executesql_sql_param(attr) end end - def basic_attribute_type?(type) - type.is_a?(Symbol) || - type.is_a?(String) || - type.is_a?(Numeric) || - type.is_a?(Time) || - type.is_a?(TrueClass) || - type.is_a?(FalseClass) || - type.is_a?(NilClass) + def active_model_attribute?(type) + type.is_a?(::ActiveModel::Attribute) end def sp_executesql_sql(sql, types, params, name) diff --git a/test/cases/adapter_test_sqlserver.rb b/test/cases/adapter_test_sqlserver.rb index 572f416e8..9921f23e6 100644 --- a/test/cases/adapter_test_sqlserver.rb +++ b/test/cases/adapter_test_sqlserver.rb @@ -580,4 +580,18 @@ def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes end end end + + describe "placeholder conditions" do + it 'using time placeholder' do + assert_equal Task.where("starting < ?", Time.now).count, 1 + end + + it 'using date placeholder' do + assert_equal Task.where("starting < ?", Date.today).count, 1 + end + + it 'using date-time placeholder' do + assert_equal Task.where("starting < ?", DateTime.current).count, 1 + end + end end