aboutsummaryrefslogtreecommitdiffstats
path: root/config/initializers/postgresql_adapter_patch.rb
blob: 2e4d73f85834be3d6497088e59b8694cc5b0e1ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# module ::ArJdbc
#   module PostgreSQL
#     def quote_column_name(name)
#       if name.is_a?(Array)
#         name.collect { |n| %("#{n.to_s.gsub("\"", "\"\"")}") }.join(',')
#       else
#         %("#{name.to_s.gsub("\"", "\"\"")}")
#       end
#     end
#   end
# end
# ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:primary_key] = "bigserial primary key"

# Add missing double-quote to write array of daterange in SQL query
# See #1782

class ActiveRecord::ConnectionAdapters::PostgreSQLColumn

  def self.array_to_string(value, column, adapter)
    casted_values = value.map do |val|
      if String === val
        if val == "NULL"
          "\"#{val}\""
        else
          quote_and_escape(adapter.type_cast(val, column, true))
        end
      elsif Range === val
        casted_value = adapter.type_cast(val, column, true)
        "\"#{casted_value}\""
      else
        adapter.type_cast(val, column, true)
      end
    end
    "{#{casted_values.join(',')}}"
  end

end

module ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID
  class DateRange < Range
    # Unnormalize daterange
    # [2016-11-19,2016-12-26) -> 2016-11-19..2016-12-25
    def type_cast(value)
      result = super value

      if result.respond_to?(:exclude_end?) && result.exclude_end?
        ::Range.new(result.begin, result.end - 1, false)
      else
        result
      end
    end
  end
  register_type 'daterange', DateRange.new(:date)
end