Search code examples
rubysequel

Is there a way to see the raw SQL that a Sequel expression will generate?


Say I have a Sequel expression like:

db.select(:id).from(:some_table).where(:foo => 5)

Is there a way to get the SQL string that this will generate (i.e. "SELECT id FROM some_table WHERE foo = 5")? I notice that calling inspect or to_s on the result of the above expression includes that generated SQL, but not sure how to access it directly.

And how about Sequel expressions that do not return a dataset, like:

db.from(:some_table).update(:foo => 5)

Is it possible to see the SQL from this before it's executed?


Solution

  • You can call sql on dataset:

    db.select(:id).from(:some_table).where(:foo => 5).sql # => "SELECT `id` FROM `some_table` WHERE (`foo` = 5)"
    

    For update queries you can do this:

    db.from(:some_table).update_sql(:foo => 5) # => "UPDATE `some_table` SET `foo` = 5"
    

    Some similar useful methods:

    insert_sql
    delete_sql
    truncate_sql