Magento – Display full query in the Exception

When there is a SQL error, Magento just prints the error without including the query.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Ok, thanks, but we need to see what is wrong with the query, XDebug does not print any useful information to find where and what is wrong with the query.

To locate the error, I have changed Zend_Db_Statement_Prod::_execute() method and replaced add the support to print the full query to the text of the exception. That way, I can see the query and understand at least where is the class Model involved.

In case you are displaying errors on the production environment (do not do that!!), consider to use a conditional statement, may be IS_DEVELOPER_MODE set in .htaccess for development mode.

Ok, enough talking, lets write the final snippet, inside Zend_Db_Statement_Pdo::_execute()

/**
     * Executes a prepared statement.
     *
     * @param array $params OPTIONAL Values to bind to parameter placeholders.
     * @return bool
     * @throws Zend_Db_Statement_Exception
     */
    public function _execute(array $params = null)
    {
        try {
            if ($params !== null) {
                return $this->_stmt->execute($params);
            } else {
                return $this->_stmt->execute();
            }
        } catch (PDOException $e) {
            #require_once 'Zend/Db/Statement/Exception.php';
            //throw new Zend_Db_Statement_Exception($e->getMessage(), (int) $e->getCode(), $e);
            throw new Zend_Db_Statement_Exception($e->getMessage() . '
| <strong style="color: black; background-color: #99ff99;">query</strong> (<span style="color: maroon;">' . $this->_stmt->queryString.'</span>)', (int) $e->getCode(), $e);
        }
    }

Leave a comment