Raw SQL from Doctrine Query Object – Revised

7th December 2009

A few months ago I posted an article talking about how to get the raw SQL from a Doctrine Query Object but with the release of Symfony 1.3 and Symfony 1.4 it would appear that the code no longer works. As a result, I’ve updated the code to work with Symfony 1.2 – 1.4 and you can find the updated source below:-

function get_raw_sql($query) {
    if(!($query instanceof Doctrine_Query)) {
        throw new sfException('Not an instanse of a Doctrine Query');
    }

    $query->limit(0);

    if(is_callable(array($query, 'buildSqlQuery'))) {
        $queryString = $query->buildSqlQuery();
        $query_params = $query->getParams();
        $params = $query_params['where'];
    } else {
        $queryString = $query->getSql();
        $params = $query->getParams();
    }

    $queryStringParts = split('\?', $queryString);
    $iQC = 0;

    $queryString = "";

    foreach($params 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;
}

I hope that it proves useful.

Liked this article?

Subscribe to my newsletter and get the latest content direct to your inbox