Question

I have a psql database that contains an hstore as a column, as such: column: "a" => "1", "b" => "2", "c" => "3"

In a standalone ruby script, I am correctly accessing my database, but I would like to output a specific value for "a", so that it only returns "1". When I attempt to do this from a loop it outputs "a" => "1" instead.

require 'rubygems'
require 'pg'
require 'open-uri'
require'activerecord-postgres-hstore'

conn = PGconn.connect("hostname", 1234, '', '', "x", "y", "z")

array = conn.exec('SELECT * FROM database')

  array.each do |uri|
    puts uri['column']
  end

The documentation on this page http://www.postgresql.org/docs/9.1/static/hstore.html shows that you can use hstore -> text to obtain the value, but I am unsure how to do this in ruby.

I have also seen this question how to parse and display hstore key/value in rails , but as I said the output gives me both key and value when I only want the value.

I should also say that while the database was created using rails, I do not want to use it for this script. Any help would be appreciated.

Was it helpful?

Solution

If you only want to extract the values for the 'a' keys in column then say exactly that and let the database do the work:

conn.exec(%q{SELECT column -> 'a' FROM database}).each do |_, a|
  # The value will be in `a`, `_` will be the made up column name.
end

or, if you want to work with other things:

conn.exec(%q{SELECT other_column, column -> 'a' as col_at_a FROM database}).each do |row|
  # Look at `row['other_column']` and `row['col_at_a']` ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top