Skip to content

Commit

Permalink
PostgreSQL hstore types are automatically deserialized from the datab…
Browse files Browse the repository at this point in the history
…ase.
  • Loading branch information
tenderlove committed Dec 20, 2011
1 parent 8cb7bc8 commit 776af48
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
## Rails 4.0.0 (unreleased) ##

* PostgreSQL hstore types are automatically deserialized from the database.

## Rails 3.2.0 (unreleased) ##

* Added ability to run migrations only for given scope, which allows
Expand Down
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/connection_adapters/column.rb
Expand Up @@ -83,6 +83,7 @@ def type_cast(value)
when :date then klass.value_to_date(value)
when :binary then klass.binary_to_string(value)
when :boolean then klass.value_to_boolean(value)
when :hstore then klass.cast_hstore(value)
else value
end
end
Expand All @@ -100,6 +101,7 @@ def type_cast_code(var_name)
when :date then "#{klass}.value_to_date(#{var_name})"
when :binary then "#{klass}.binary_to_string(#{var_name})"
when :boolean then "#{klass}.value_to_boolean(#{var_name})"
when :hstore then "#{klass}.cast_hstore(#{var_name})"
else var_name
end
end
Expand Down
Expand Up @@ -49,6 +49,10 @@ def string_to_time(string)
super
end
end

def cast_hstore(string)
Hash[[string.split('=>').map { |k| k[1...-1] }]]
end
end
# :startdoc:

Expand Down
16 changes: 16 additions & 0 deletions activerecord/test/cases/adapters/postgresql/hstore_test.rb
Expand Up @@ -21,4 +21,20 @@ def test_column
assert column
assert_equal :hstore, column.type
end

def test_type_cast_hstore
column = Hstore.columns.find { |c| c.name == 'tags' }
assert column

data = "\"1\"=>\"2\""
hash = column.class.cast_hstore data
assert_equal({'1' => '2'}, hash)
assert_equal({'1' => '2'}, column.type_cast(data))
end

def test_select
@connection.execute "insert into hstores (tags) VALUES ('1=>2')"
x = Hstore.find :first
assert_equal({'1' => '2'}, x.tags)
end
end

0 comments on commit 776af48

Please sign in to comment.