When you run a large application (or many large applications), it is important
that you can effectively track down and investigate slow SQL queries when they
arise. MySQL doesn’t receive context of where the query is coming from so in
your logs you end up with something that will look like this:
Sure, if this is a specific query you might know which URL or method is sending
it, but what if someone not so familiar with the application needed to
investigate it - would they be able to find it?
One option is to add a comment to your query that contains some useful
information such as class name, method name or even a request ID. Consider the
To add a comment to a query, you can use Drupal’s Query::comment
method which will prepend your comment before sending the query. Below we add a
comment that contains the module and function names of the caller.
Now should the query pop up in your slow query logs, it will be annotated with
some helpful debugging information on it’s caller.
If Rails is your framework of choice, the marginalia gem adds
this feature to ActiveRecord and can be configured to capture any data you wish.