# pg_hstore.rb

Path: | lib/sequel/extensions/pg_hstore.rb
Last Update: | Sat Apr 20 16:47:06 +0000 2013

The pg_hstore extension adds support for the PostgreSQL hstore type to Sequel. hstore is an extension that ships with PostgreSQL, and the hstore type stores an arbitrary key-value table, where the keys are strings and the values are strings or NULL.

This extension integrates with Sequel‘s native postgres adapter, so that when hstore fields are retrieved, they are parsed and returned as instances of Sequel::Postgres::HStore. HStore is a DelegateClass of Hash, so it mostly acts like a hash, but not completely (is_a?(Hash) is false). If you want the actual hash, you can call Hstore#to_hash. This is done so that Sequel does not treat a HStore like a Hash by default, which would cause issues.

In addition to the parsers, this extension comes with literalizers for HStore using the standard Sequel literalization callbacks, so they work with on all adapters.

To turn an existing Hash into an HStore, use Sequel.hstore:

      Sequel.hstore(hash)

If you have loaded the core_extensions extension), you can also use Hash#hstore:

      hash.hstore

Since the hstore type only supports strings, non string keys and values are converted to strings

      {:foo=>1}.hstore.to_hash # {'foo'=>'1'}
      v = {}.hstore
      v[:foo] = 1
      v # {'foo'=>'1'}

However, to make life easier, lookups by key are converted to strings (even when accessing the underlying hash directly):

      {'foo'=>'bar'}.hstore[:foo] # 'bar'
      {'foo'=>'bar'}.hstore.to_hash[:foo] # 'bar'

HStore instances mostly just delegate to the underlying hash instance, so Hash methods that modify the receiver or returned modified copies of the receiver may not do string conversion. The following methods will handle string conversion, and more can be added later if desired:

- \[\]
- \[\]=
- assoc (ruby 1.9 only)
- delete
- fetch
- has_key?
- has_value?
- include?
- key (ruby 1.9 only)
- key?
- member?
- merge
- merge!
- rassoc (ruby 1.9 only)
- replace
- store
- update
- value?

If you want to insert a hash into an hstore database column:

      DB[:table].insert(:column=>{'foo'=>'bar'}.hstore)

If you would like to use hstore columns in your model objects, you probably want to modify the schema parsing/typecasting so that it recognizes and correctly handles the hstore columns, which you can do by:

      DB.extension :pg_hstore

If you are not using the native postgres adapter, you probably also want to use the typecast_on_load plugin in the model, and set it to typecast the hstore column(s) on load.

This extension requires the delegate and strscan libraries.

### Required files

delegate strscan

[Validate]