Menu

Sponsored By: Password Angel - Share passwords, API keys, credentials and more with secure, single-use links.

Raw SQL from Doctrine Query Object – Revised

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.

Originally published at https://chrisshennan.com/blog/raw-sql-from-doctrine-query-object-revised

Subscribe to my newsletter...

... and receive the musings of an aspiring #indiehacker directly to your inbox once a month.

These musings will encompass a range of subjects such as Web Development, DevOps, Startups, Bootstrapping, #buildinpublic, SEO, personal opinions, and experiences.

I won't send you spam and you can unsubscribe at any time.