Search code examples
rubypostgresqlrubygemspg

how do I tell if a query failed in postgres with ruby?


here is some basic code for context

require 'pg'

conn = PG.connect(db_params)
# example query:
response = conn.exec("update employees set id = 0 where role = 'owner'")

puts response

whenever I try to print the response of a statement that isn't a select statement I get the address of the Result object that is created when the query is executed, as the previous code indicates.

is there a way to know if the query failed or not?

I went to the 'pg' gem documentation and it only mentions execution of select statements which doesnt help my case.


Solution

  • The documentation of PG::Connection#exec says:

    Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result instance with all result rows and columns. On failure, it raises a PG::Error.

    So if the query fails, it will raise an exception of type PG::Error. You can use a begin ... rescue block to catch it:

    begin
      conn.exec("update employees set id = 'invalid' where role = 'owner'")
    rescue PG::Error => e
      puts "#{e.class}: #{e.message}"
    end