Skip to content

Commit cbd8fb1

Browse files
committed
Preserve type when dumping bit and bit varying columns
Commits - rails/rails@fcd5e56 rails/rails@d5411fb
1 parent e28c751 commit cbd8fb1

File tree

2 files changed

+80
-1
lines changed

2 files changed

+80
-1
lines changed

lib/arjdbc/postgresql/adapter.rb

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ def type_cast(value, column, array_member = false)
241241
:int8range => { :name => "int8range" },
242242
}) if AR4_COMPAT
243243

244+
NATIVE_DATABASE_TYPES.update(
245+
:bit => { name: "bit" },
246+
:bit_varying => { name: "bit varying" }
247+
) if ActiveRecord::VERSION.to_s >= '4.2'
248+
244249
def native_database_types
245250
NATIVE_DATABASE_TYPES
246251
end
@@ -871,7 +876,22 @@ def quote(value, column = nil)
871876
else
872877
super
873878
end
874-
end
879+
end if ActiveRecord::VERSION.to_s < '4.2'
880+
881+
def quote(value, column = nil)
882+
return super unless column
883+
884+
case value
885+
when Float
886+
if value.infinite? || value.nan?
887+
"'#{value.to_s}'"
888+
else
889+
super
890+
end
891+
else
892+
super
893+
end
894+
end if ActiveRecord::VERSION.to_s >= '4.2'
875895

876896
# Quotes a string, escaping any ' (single quote) and \ (backslash) chars.
877897
# @return [String]
@@ -1414,6 +1434,14 @@ def uuid(name, options = {})
14141434
def json(name, options = {})
14151435
column(name, 'json', options)
14161436
end
1437+
1438+
def bit(name, options)
1439+
column(name, 'bit', options)
1440+
end
1441+
1442+
def bit_varying(name, options)
1443+
column(name, 'bit varying', options)
1444+
end
14171445
end
14181446

14191447
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition

lib/arjdbc/postgresql/base/oid.rb

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,57 @@ def type_cast(value)
6666
end
6767
end
6868

69+
class Bit < ActiveRecord::Type::Value
70+
def type
71+
:bit
72+
end
73+
74+
def type_cast(value)
75+
if ::String === value
76+
case value
77+
when /^0x/i
78+
value[2..-1].hex.to_s(2) # Hexadecimal notation
79+
else
80+
value # Bit-string notation
81+
end
82+
else
83+
value
84+
end
85+
end
86+
87+
def type_cast_for_database(value)
88+
Data.new(super) if value
89+
end
90+
91+
class Data
92+
def initialize(value)
93+
@value = value
94+
end
95+
96+
def to_s
97+
value
98+
end
99+
100+
def binary?
101+
/\A[01]*\Z/ === value
102+
end
103+
104+
def hex?
105+
/\A[0-9A-F]*\Z/i === value
106+
end
107+
108+
protected
109+
110+
attr_reader :value
111+
end
112+
end if ActiveRecord::VERSION.to_s >= '4.2'
113+
114+
class BitVarying < Bit
115+
def type
116+
:bit_varying
117+
end
118+
end if ActiveRecord::VERSION.to_s >= '4.2'
119+
69120
class Bytea < Type
70121
def type; :binary end
71122

0 commit comments

Comments
 (0)