This has been updated to work with Symfony 1.3/1.4 – Please go to the updated article: Raw SQL from Doctrine Query Object – Revised

As my use of Symfony is increasing I find myself frustrated that there doesn’t appear to be an easy way to get the raw SQL from a doctrine query object so I can simply output it and paste it into phpMyAdmin to debug problems with the SQL. I may be wrong about this but as yet I have not found a built in function to perform this operation.

Sure I am able to output the query with the “?” indicating where the necessary values are to go and I can also easily output the array of query parameters so I can substitute these manually but this takes time and it would be much much simpler and quicker to just output the whole query with the substitution already done so it’s a simply copy and paste of the raw SQL from the doctrine query object straight into phpMyAdmin.

I have wrote a quick function to do this and I had meant to post this for a while but I just have not had the chance to get round to it until now.

The code for this is can be found below:-

function get_raw_sql($query) {
    $query->limit(0);
 
    $queryStringParts = split('\?', $query->getSQL());
    $iQC = 0;
    $queryString = "";
 
    foreach($query->getParams() as $param) {
        if(is_numeric($param)) {
            $queryString .= $queryStringParts[$iQC] . $param;
        } elseif(is_bool($param)) {
            $queryString .= $queryStringParts[$iQC] . $param*1;
        } else {
            $queryString .= $queryStringParts[$iQC] . '\'' . $param . '\'';
        }
        $iQC++;
   }
 
   for($iQC;$iQC < count($queryStringParts);$iQC++) {
       $queryString .= $queryStringParts[$iQC];
   }
   echo $queryString;
}

In my case this is a global function but it could very well be written as a static function in a debug class.

$query is a Doctrine Query object and this function iterates round the parameters for the query string and replaces each instance of a “?” with the corresponding variable. It has a crude (but fairly effective so far) method of determine whether it’s a string, number or boolean when performing this substitution and so far this works well in all the cases I’ve used it.

The $query->limit(0); is very important as the $query->getSQL() function does not work properly in this context if a limit is specified on the query so as we are wanting to debug the SQL and a majority of the time we are not concerned with the limit I have opted to remove this from this routine.

Hopefully this will allow you to save some time and effort trying to get the raw SQL from your doctrine query objects and I would appreciated any comments, thoughts or ideas you may have for improvement.

Bookmark and Share