Skip to content

Commit 5ac2341

Browse files
committed
cast hstore values on write to be consistent with reading from the db.
1 parent 765b8aa commit 5ac2341

File tree

4 files changed

+34
-4
lines changed

4 files changed

+34
-4
lines changed

activerecord/CHANGELOG.md

+15
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1+
* Type cast hstore values on write, so that the value is consistent
2+
with reading from the database.
3+
4+
Example:
5+
6+
x = Hstore.new tags: {"bool" => true, "number" => 5}
7+
8+
# Before:
9+
x.tags # => {"bool" => true, "number" => 5}
10+
11+
# After:
12+
x.tags # => {"bool" => "true", "number" => "5"}
13+
14+
*Yves Senn* , *Severin Schoepke*
15+
116
* Fix multidimensional PG arrays containing non-string items.
217

318
*Yves Senn*

activerecord/lib/active_record/connection_adapters/postgresql/oid.rb

+4-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ class PostgreSQLAdapter < AbstractAdapter
66
module OID
77
class Type
88
def type; end
9-
10-
def type_cast_for_write(value)
11-
value
12-
end
139
end
1410

1511
class Identity < Type
@@ -224,6 +220,10 @@ def type_cast(value)
224220
end
225221

226222
class Hstore < Type
223+
def type_cast_for_write(value)
224+
ConnectionAdapters::PostgreSQLColumn.hstore_to_string value
225+
end
226+
227227
def type_cast(value)
228228
return if value.nil?
229229

activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb

+8
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,14 @@ def self.extract_value_from_default(default)
129129
end
130130
end
131131

132+
def type_cast_for_write(value)
133+
if @oid_type.respond_to?(:type_cast_for_write)
134+
@oid_type.type_cast_for_write(value)
135+
else
136+
super
137+
end
138+
end
139+
132140
def type_cast(value)
133141
return if value.nil?
134142
return super if encoded?

activerecord/test/cases/adapters/postgresql/hstore_test.rb

+7
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,13 @@ def test_change_table_supports_hstore
7070
Hstore.reset_column_information
7171
end
7272

73+
def test_cast_value_on_write
74+
x = Hstore.new tags: {"bool" => true, "number" => 5}
75+
assert_equal({"bool" => "true", "number" => "5"}, x.tags)
76+
x.save
77+
assert_equal({"bool" => "true", "number" => "5"}, x.reload.tags)
78+
end
79+
7380
def test_type_cast_hstore
7481
assert @column
7582

0 commit comments

Comments
 (0)