-
jessehs
Developer
Working with queries in an abstracted manner (like the new D7 database abstraction layer) can be tricky. Even working in D6 with functions like db_placeholders() or db_rewrite_sql() can start to make your head spin. For those of us who want to see the *actual* query sent to MySQL (or whichever database backend you're using), here is a handy snippet of code. When the Devel module is enabled, you can add the following lines to your settings.php file:
// Devel Configuration $conf['dev_query'] = TRUE;
Note that this must be in the proper part of the file. The $conf array is used to override variables normally set via the UI, which are typically stored in the database in the "variable" table.
Now that Devel's query-logging feature is enabled, every database query -- the *actual* query itself, not the abstracted PDO syntax (Read more) -- is temporarily stored in a global variable $queries.
You can print out the latest query using the following snippet:
global $queries; $query = array_pop($queries); dd($query, 'descriptive text about the query being printed out -- this one is logged to /tmp/drupal_debug.txt'); dpm($query, 'descriptive text about the query being printed out -- this one is printed to the screen');
I've primarily used this in D6 development, although I'm fairly sure it works the same in D7. Insert this snippet immediately after the query you're wanting to see the raw version of.
You know the common Drupalism, "Don't hack core!" Well... during development it is *encouraged* to hack core, if it helps you debug a situation or understand better what's going on in a system. Just make sure to remove your hacks when you grok what's happening. With this technique you can get down to the most fundamental raw queries themselves... Hack away!
Tagged as: Drupal, Drupal Planet, tips and tricks
Useful trick
debug(strtr($query, $query->getArguments())); will show a query with arguments replaced in. It won't be quoted so it's not perfect but it integrates with the testing framework and doesn't require devel.
Thanks chx!
I'm adding this to my little black book of snippets :-)
Views Query Information
A lot of queries are properly done with the Views module. Here you can view query data if you enable it at admin/structure/views/settings. You can also enable performance statistics.
I prefer to use dpq() from
I prefer to use dpq() from Devel. In some cases Database::startLog/Database::getLog can help, as described here: https://licel.ru/2012/07/drupal-for-developers-debug-sql-queries/
Add your comment