pg.ddx.io  pgsql-interfaces@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Michael Fuhr <mike@fuhr.org>
To: CSN <cool_screen_name90001@yahoo.com>
Cc: pgsql-interfaces@postgresql.org
Subject: Re: ruby/postgres - getting assoc array of rows?
Date: Sat, 19 Nov 2005 22:32:47 -0700
Message-ID: <20051120053247.GA31157@winnie.fuhr.org> (raw)
In-Reply-To: <20051120041440.29069.qmail@web52902.mail.yahoo.com>
References: <20051120041440.29069.qmail@web52902.mail.yahoo.com>

On Sat, Nov 19, 2005 at 08:14:40PM -0800, CSN wrote:
> Looking at the docs here:
> http://ruby.scripting.ca/postgres/reference.html
> 
> there doesn't appear to be an easy way to get an associative row
> of rows returns.

What exactly are you looking for?  The example you posted returns
an array of hashes, but depending on what you're doing all that
work might not be necessary.  PGconn#exec returns a PGresult object,
the PGresult#each iterator yields PGrow objects, and PGrow#[] accepts
both numeric and text indexes.  Example:

% psql -d test -c 'SELECT id, name FROM people'
 id | name  
----+-------
  1 | Alice
(1 row)

% cat test.rb
require 'postgres'
conn = PGconn.new('dbname=test')
res = conn.exec('SELECT id, name FROM people')
res.each do |row|
  puts "by name:     #{row['id']} #{row['name']}"
  puts "by position: #{row[0]} #{row[1]}"
end
res.clear
conn.close

% ruby test.rb
by name:     1 Alice
by position: 1 Alice

You could also convert the PGresult object into an array of PGrow
objects with a one-liner, although you wouldn't get automatic bytea
handling as in the function you posted:

rows = res.collect

Will any of this work for you?  If not then please provide more
detail.

-- 
Michael Fuhr



view thread (10+ messages)  latest in thread

Message-ID: <20051120053247.GA31157@winnie.fuhr.org>
Permalink:  ../20051120053247.GA31157@winnie.fuhr.org/
Also on:    postgresql.org/message-id/20051120053247.GA31157@winnie.fuhr.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-interfaces@postgresql.org
  Cc: mike@fuhr.org, cool_screen_name90001@yahoo.com
  Subject: Re: ruby/postgres - getting assoc array of rows?
  In-Reply-To: <20051120053247.GA31157@winnie.fuhr.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox