activerecord-jdbc-adapter icon indicating copy to clipboard operation
activerecord-jdbc-adapter copied to clipboard

Invalid SQL generated for UniquenessValidator on boolean attributes

Open fxgallego opened this issue 8 years ago • 0 comments

This applies to the mssql adapter, rails 4.2.6 When a validation is set on a boolean field (validate :my_boolean_field, uniqueness: true) the boolean parameter in the sql is generated as 't' instead of 1 which should be the correct parameter for mssql BIT datatype.

The problem is in ActiveRecord::ConnectionAdapters::Quoting#_type_cast. It's using #unquoted_true but the abstract one and it's defined to return 't'. Currently there is no specialization in mssql adapter for this abstract behavior.

The guys of https://github.com/rails-sqlserver/activerecord-sqlserver-adapter have implemented this as:

module ActiveRecord
  module ConnectionAdapters
    module SQLServer
      module Quoting

        QUOTED_TRUE  = '1'
        QUOTED_FALSE = '0'
        QUOTED_STRING_PREFIX = 'N'

        def quote_string(s)
          SQLServer::Utils.quote_string(s)
        end

        def quote_column_name(name)
          SQLServer::Utils.extract_identifiers(name).quoted
        end

        def quote_default_value(value, column)
          if column.type == :uuid && value =~ /\(\)/
            value
          else
            quote(value, column)
          end
        end

        def quoted_true
          QUOTED_TRUE
        end

        def unquoted_true
          1
        end

        def quoted_false
          QUOTED_FALSE
        end

        def unquoted_false
          0
        end

        def quoted_date(value)
          if value.acts_like?(:date)
            Type::Date.new.type_cast_for_database(value)
          else value.acts_like?(:time)
            Type::DateTime.new.type_cast_for_database(value)
          end
        end


        private

        def _quote(value)
          case value
          when Type::Binary::Data
            "0x#{value.hex}"
          when ActiveRecord::Type::SQLServer::Char::Data
            value.quoted
          when String, ActiveSupport::Multibyte::Chars
            "#{QUOTED_STRING_PREFIX}#{super}"
          else
            super
          end
        end

      end
    end
  end
end

Want to back this issue? Post a bounty on it!

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/40097870-invalid-sql-generated-for-uniquenessvalidator-on-boolean-attributes?utm_campaign=plugin&utm_content=tracker%2F136963&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F136963&utm_medium=issues&utm_source=github).

fxgallego avatar Dec 15 '16 14:12 fxgallego