Search code examples
rubysequel

How to give Sequel#execute a block on a simple select?


I'm executing a simple query vis Sequel like such:

result = db.execute("SELECT some_int_colum FROM some_system_table WHERE some_column = 'some_value';")

In a psql session, it returns the expected value but when run through the Sequel Postgres adapter it returns the number of resulting rows, not the value.

From the source (reference):

 # Execute the given SQL with this connection.  If a block is given,
 # yield the results, otherwise, return the number of changed rows.

That clearly explains the why, but how is a block given to the execute method in this scenario?


Solution

  • Dataset#fetch (reference) is a more appropriate method to execute arbitrary sql and return a single or set of values. In the above example, where only a single return value is expected it would look something like this:

    result = db.fetch("SELECT some_int_colum FROM some_system_table WHERE some_column = 'some_value'").all.first.values.first