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

1

19

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?

Gilbert answered 16/12, 2013 at 19:12 Comment(0)
H
37

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
Heaviside answered 16/12, 2013 at 19:24 Comment(7)
What is db in this case and how do you access/instantiate it?Quaff
Is there anyway to get at this from an ActiveRecord Relation?Quaff
It's a Sequel connnection like db = Sequel.connect('sqlite://blog.db'). In ActiveRecord::Relation, you can just call to_sqlHeaviside
Thanks. :-) In the case of a particular Rails expression requiring multiple SQL statements to execute, do you know if .to_sql just gives the latest?Quaff
Not sure what you mean. It will show you the statement related to the relation you call it on (it will show joins etc but not includes and preloads).Heaviside
I'm not sure I know what I mean either, perhaps because I don't know what an include or preload is in this context. ;-) Is it sometimes necessary for Rails to execute a query in order to even construct a relation? I'm trying to understand the paragraphs starting with "Please note" at weblog.rubyonrails.org/2011/12/6/…Quaff
Is there a known way to do this for distinct? For example db[:table].distinct(:id).sql and db[:table].distinct_sql(:id) don't work.Cylinder

© 2022 - 2024 — McMap. All rights reserved.