Skip to content

Commit

Permalink
Added type convertion for PG hstore array
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabriel Naiman committed Oct 24, 2016
1 parent 995c3af commit 927f050
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
7 changes: 4 additions & 3 deletions lib/rasti/db/type_converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ class TypeConverter

CONVERTIONS = {
postgres: {
/hstore/ => ->(value, match) { Sequel::Postgres::HStore.new value },
/([a-z]+)\[\]/ => ->(value, match) { Sequel::Postgres::PGArray.new value, match.captures[0] }
/^hstore$/ => ->(value, match) { Sequel::Postgres::HStore.new value },
/^hstore\[\]$/ => ->(value, match) { Sequel::Postgres::PGArray.new value.map { |v| Sequel::Postgres::HStore.new v }, 'hstore' },
/^([a-z]+)\[\]$/ => ->(value, match) { Sequel::Postgres::PGArray.new value, match.captures[0] }
}
}

Expand Down Expand Up @@ -36,7 +37,7 @@ def self.convertions_for(db, collection_name)
columns = Hash[db.schema(collection_name)]
@cache[key] = columns.each_with_object({}) do |(name, schema), hash|
CONVERTIONS.fetch(db.database_type, {}).each do |type, convertion|
if match = type.match(schema[:db_type])
if !hash.key?(name) && match = type.match(schema[:db_type])
hash[name] = {match: match, block: convertion}
end
end
Expand Down
15 changes: 14 additions & 1 deletion spec/type_converter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def pg.schema(table_name, opts={})
[
[:hash, {db_type: 'hstore'}],
[:text_array, {db_type: 'text[]'}],
[:integer_array, {db_type: 'integer[]'}]
[:integer_array, {db_type: 'integer[]'}],
[:hstore_array, {db_type: 'hstore[]'}]
]
end
end
Expand Down Expand Up @@ -57,6 +58,18 @@ def pg.schema(table_name, opts={})
attributes[:integer_array].must_equal [1,2,3]
end

it 'Hstore array' do
attributes = type_converter.apply_to hstore_array: [{key: 0}, {key: 1}]

attributes[:hstore_array].class.must_equal Sequel::Postgres::PGArray
attributes[:hstore_array].array_type.must_equal 'hstore'

2.times do |i|
attributes[:hstore_array][i].class.must_equal Sequel::Postgres::HStore
attributes[:hstore_array][i].must_equal 'key' => i.to_s
end
end

it 'Empty array' do
attributes = type_converter.apply_to integer_array: []

Expand Down

0 comments on commit 927f050

Please sign in to comment.