inspect_sql

Railsters:

When you use ActiveRecord, it conglomerates your has_many directives together to produce elaborate queries.

Sometimes these might be a little too elaborate.

I wrote a test helper function that lets you peek under the hood, like this:

     sql = inspect_sql do
       Post.find(:all, :include => { :user => :user_level },
                    :conditions => { :'user_levels.name' => 'Moderator' })
     end

   pp sql.statements

The method inspect_sql{} returns an array object full of data about your queries. It comes with accessors (.statements, .keys, .tables, [2], etc.) that let you drill down to specifics. The trace statement 'pp sql.statements' will emit all the SQL SELECT statements that inspect_sql collected.

To optimize those statements, you can use assert_no_match (or assert{ statement !~ /something/ } ) to catch and forbid inefficient or incorrect statements.

This helps you tune your database without writing brute-force tests that simply load thousands of records, query them, and time the results.

Get inspect_sql with the assert_efficient_sql gem, and read more about it here:

   http://www.oreillynet.com/ruby/blog/2008/09/inspect_sql.html

The method inspect_sql{} returns an array object full of data about your
queries. It comes with accessors (.statements, .keys, .tables, [2],
etc.) that
let you drill down to specifics. The trace statement 'pp sql.statements'
will
emit all the SQL SELECT statements that inspect_sql collected.

adding sql explain might be nice, too :stuck_out_tongue:
-=R

Will this work with db's other than MySQL?