Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine what Ruby-on-Rails code generated some SQL?

I have an application written in Ruby using Rails 2.3. We use ActiveRecord.

Occasionally, ActiveRecord generates some pretty hideously inefficient SQL. We can determine what SQL is problematic using slow-query logs and using new relic. However, it can be really difficult to determine the line of code in our software that generated the problematic SQL. It's generally a query built up using associations and named_scopes.

What I'd really like is some way to tag the SQL in our log files with the filename and line of our code that generated it (not the line of ActiveRecord that executed the query).

The information should be available via the caller array. I don't want to dump the entire array, I just want the filename and line of our code most directly responsible. Is there a gem which already does this? If not, any suggestions?

like image 207
ChrisInEdmonton Avatar asked Oct 03 '11 21:10

ChrisInEdmonton


People also ask

Does Ruby use SQL?

In SQLite Ruby module, first we prepare the SQL statement with the prepare method. The SQL string is sent to the database engine, which checks the statement validity, syntax and in some databases also the user permissions to perform certain queries. If all is OK, a statement object is returned to the Ruby script.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is Arel_table?

The Arel::Table object acts like a hash which contains each column on the table. The columns given by Arel are a type of Node , which means it has several methods available on it to construct queries. You can find a list of most of the methods available on Node s in the file predications.


2 Answers

you should find some inspiration along the active-record-query-trace gem

EDIT: wooops, read it too fast, this is for RoR 3+. >This< seems to work for rails 2.3. You may also find some inspiration here.

like image 193
m_x Avatar answered Nov 15 '22 05:11

m_x


rack-mini-profiler does include information on which line of ruby code generated which sql query.

like image 39
Dennis Krupenik Avatar answered Nov 15 '22 05:11

Dennis Krupenik