Doctrine - How to print out the real sql, not just the prepared statement?

后端 未结 19 2433
自闭症患者
自闭症患者 2020-11-30 18:59

We\'re using Doctrine, a PHP ORM. I am creating a query like this:

$q = Doctrine_Query::create()->select(\'id\')->from(\'MyTable\');

19条回答
  •  萌比男神i
    2020-11-30 19:37

    I have created a Doctrine2 Logger that does exactly this. It "hydrates" the parametrized sql query with the values using Doctrine 2 own data type conversors.

    dbPlatform=$dbPlatform;
            $this->loggedQueryTypes=$loggedQueryTypes;
        }
        /**
         * {@inheritdoc}
         */
        public function startQuery($sql, array $params = null, array $types = null)
    
        {
            if($this->isLoggable($sql)){
                if(!empty($params)){
                    foreach ($params as $key=>$param) {
                        $type=Type::getType($types[$key]);
                        $value=$type->convertToDatabaseValue($param,$this->dbPlatform);
                        $sql = join(var_export($value, true), explode('?', $sql, 2));
                    }
    
                }
                echo $sql . " ;".PHP_EOL;
            }
        }
    
        /**
         * {@inheritdoc}
         */
        public function stopQuery()
        {
    
        }
        private function isLoggable($sql){
            if (empty($this->loggedQueryTypes)) return true;
            foreach($this->loggedQueryTypes as $validType){
                if (strpos($sql, $validType) === 0) return true;
            }
            return false;
        }
    }
    

    Usage Example:; The following peace of code will echo on standard output any INSERT,UPDATE,DELETE SQL sentences generated with $em Entity Manager,

    /**@var  \Doctrine\ORM\EntityManager $em */
    $em->getConnection()
                    ->getConfiguration()
                    ->setSQLLogger(
                        new EchoWriteSQLWithoutParamsLogger(
                            $em->getConnection()->getDatabasePlatform(),
                            array(
                                EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_UPDATE,
                                EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_INSERT,
                                EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_DELETE
                            )
                        )
                    );
    

提交回复
热议问题