1. Home
  2. Blog
  3. Contact
Blogitems
16Dec

TYPO3: Debugging SQL queries

Posted on December 16th 2009 at 22:38 inside Extension DevelopmentPHP with 0 comments

Imagine all the time you will put into trying to reverse engineer what the DBAL wrapper function you use is trying to generate, when we could just print ANY query that was generated with ANY one of the DBAL wrappers!

So how do we do it?

Sounds too good to be true? Well it isn't, theres actually a little trick for this. When you are debugging you can set an option in TYPO3s DBAL that will store a query every time it is built. Every time you will use the TYPO3 DBAL wrappers from that point to generate or execute a query, it will store that query as a plain string (how it's send to your database server) into a local variable inside the global TYPO3_DB object.

The Code

The process with debugging a single query may look somewhat like this:

Using the built-in debug functionality 

  1. // First we need to enable the query storage
  2. $GLOBALS['TYPO3_DB']->store_lastBuiltQuery = true;
  3.  
  4. // Now we will execute a query to select all pages
  5. $a_pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
  6.     '*',
  7.     'pages'
  8. );
  9.  
  10. // Now we will print our query to see what just happened
  11. print_r($GLOBALS['TYPO3_DB']->debug_lastBuiltQuery);
  12.  
  13. // And we turn query storage off again (since it's not needed anymore)
  14. $GLOBALS['TYPO3_DB']->store_lastBuiltQuery = false;
// First we need to enable the query storage
$GLOBALS['TYPO3_DB']->store_lastBuiltQuery = true;

// Now we will execute a query to select all pages
$a_pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
    '*',
    'pages'
);

// Now we will print our query to see what just happened
print_r($GLOBALS['TYPO3_DB']->debug_lastBuiltQuery);

// And we turn query storage off again (since it's not needed anymore)
$GLOBALS['TYPO3_DB']->store_lastBuiltQuery = false;

Conclusion

That wasn't very hard, but if we wouldn't know about it, it would have taken us a lot more time and effort to generate the same query as the wrapper does. Especially in the case of a much more complex query including where, group by, order by and having statements, it can be a real pain to debug any problems without this.

Tags

typo3 sql dbal extension debug

Comments (0)

Your comment