8

I'm using the pg gem to talk to PostgreSQL from Ruby. Is there a better way to check if there are no results than using res.ntuples == 0?

conn = PGconn.connect config

cmd = "select * from labels inner join labels_mail using(label_id) " + 
  "where labels_mail.mail_id = $1 and labels.name = $2"

res = conn.exec(cmd, [mail_id, mailbox])

if res.ntuples == 0  #  <=== is there a better way to check this?
  cmd = "insert into labels_mail (mail_id, label_id) values ($1, $2)"
  conn.exec(cmd, [mail_id, label_id(mailbox)])
end
dan
  • 43,914
  • 47
  • 153
  • 254
  • Just as a tip, I *highly* recommend using the [Sequel](http://sequel.rubyforge.org/) ORM gem with Postgres or MySQL, or almost any other database. It lets you use raw SQL, or data sets, or act as a full-blown modeling ORM similar to ActiveRecord. – the Tin Man Apr 20 '11 at 02:19
  • Thanks. But I want to stay close to the metal for performance reasons. I'm writing stuff with minimal overhead startup time. I've tried the active record approach and it was far to slow for startup time. – dan Apr 20 '11 at 16:23

1 Answers1

8

ntuples, a typo? It is faster and concise to use zero? than == 0

if res.num_tuples.zero?
sawa
  • 165,429
  • 45
  • 277
  • 381