Esempio n. 1
0
 public function execute($input_parameters = NULL)
 {
     if (APF::get_instance()->is_debug_enabled()) {
         APF::get_instance()->debug(__CLASS__ . '[' . $this->pdo->config['dsn'] . '|' . $this->pdo->get_name() . ']' . "->execute: " . $this->queryString);
     }
     $logger = APF::get_instance()->get_logger();
     $logger->debug(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString);
     APF::get_instance()->pf_benchmark_inc_begin('dbtime');
     $start = microtime(true);
     $ret = parent::execute($input_parameters);
     $end = microtime(true);
     APF::get_instance()->pf_benchmark_inc_end('dbtime');
     //add by hexin for record SQL execute time
     APF::get_instance()->pf_benchmark("sql_time", array($this->i => $end - $start));
     if (!$ret) {
         $error_info = parent::errorInfo();
         $logger->error(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString);
         $_error_info = preg_replace("#[\r\n \t]+#", ' ', print_r($error_info, true));
         $logger->error(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $_error_info);
         if (parent::errorCode() !== '00000') {
             trigger_error($this->queryString . ' | ' . join(' | ', $error_info), E_USER_ERROR);
         }
     }
     return $ret;
 }
Esempio n. 2
0
 public function errorCode()
 {
     if ($this->_statement instanceof \PDOStatement) {
         return $this->_statement->errorCode();
     }
     return null;
 }
Esempio n. 3
0
 /**
  * Returns the number of the last error.
  * 
  * @return integer
  */
 public function getErrorNumber()
 {
     if ($this->pdoStatement !== null) {
         return $this->pdoStatement->errorCode();
     }
     return 0;
 }
Esempio n. 4
0
 /**
  * Renvoi le code de la dernière erreur
  *
  */
 public function errorCode()
 {
     if (is_object($this->stmt)) {
         $code = $this->stmt->errorCode();
         return PDO::ERR_NONE == $code ? null : $code;
     }
 }
Esempio n. 5
0
 public function execute($input_parameters = NULL)
 {
     if (APF::get_instance()->is_debug_enabled()) {
         APF::get_instance()->debug(__CLASS__ . '[' . $this->pdo->config['dsn'] . '|' . $this->pdo->get_name() . ']' . "->execute: " . $this->queryString);
     }
     $logger = APF::get_instance()->get_logger();
     $logger->debug(__CLASS__, '[' . $this->pdo->get_name() . ']->execute: ', $this->queryString);
     APF::get_instance()->pf_benchmark_inc_begin('dbtime');
     $start = microtime(true);
     $ret = parent::execute($input_parameters);
     $end = microtime(true);
     APF::get_instance()->pf_benchmark_inc_end('dbtime');
     //add by hexin for record SQL execute time
     APF::get_instance()->pf_benchmark("sql_time", array($this->i => $end - $start));
     // 按照惯用格式记录sql执行时间和占用内存
     // added by htlv
     $tmp_time = $end - $start;
     $tmp_mem = memory_get_usage();
     apf_require_class('APF_Performance');
     APF::get_instance()->pf_benchmark("sql_time_af", array($this->i => array('sql' => $this->_sql, APF_Performance::MESSAGE_TIME => $tmp_time, APF_Performance::MESSAGE_MEMORY => $tmp_mem)));
     if (!$ret) {
         $error_info = parent::errorInfo();
         /**
          * remove duplicated error log
         $logger->error(__CLASS__, '['. $this->pdo->get_name() .']->execute: ', $this->queryString);
         $_error_info = preg_replace("#[\r\n \t]+#",' ',print_r($error_info,true));
         $logger->error(__CLASS__, '['. $this->pdo->get_name() .']->execute: ', $_error_info);
         */
         if (parent::errorCode() !== '00000') {
             throw new APF_Exception_SqlException($this->pdo->get_name() . ' | ' . $this->pdo->config['dsn'] . ' | ' . $this->queryString . ' | ' . join(' | ', $error_info), parent::errorCode());
         }
     }
     return $ret;
 }
 public function __construct($message, PDOStatement $statement)
 {
     $infos = array();
     foreach ($statement->errorInfo() as $key => $info) {
         $infos[] = $key . ': ' . $info;
     }
     parent::__construct($message . '. (ERRNO ' . $statement->errorCode() . ') ' . implode('<br />', $infos));
 }
Esempio n. 7
0
 /**
  * Returns the last error code generated by the wrapped PDO object. Please
  * the PDOStatement::errorCode method for prepared statements.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return string
  */
 private function errorCode()
 {
     if ($this->preparedExec == false) {
         $returnValue = $this->dbConnector->errorCode();
     } else {
         $returnValue = $this->lastPreparedExecStatement->errorCode();
     }
     return (string) $returnValue;
 }
Esempio n. 8
0
 /**
  * Retrieves the error code, if any, associated with the last operation on
  * the statement handle.
  *
  * @return string error code.
  * @throws Zend_Db_Statement_Exception
  */
 public function errorCode()
 {
     try {
         return $this->_stmt->errorCode();
     } catch (PDOException $e) {
         require_once 'Zend/Db/Statement/Exception.php';
         throw new Zend_Db_Statement_Exception($e->getMessage());
     }
 }
Esempio n. 9
0
	/**
	 * Permet d'exécuter une requête.
	 *
	 * Aucun résultat n'est renvoyé par cette fonction. Elle doit être utilisé pour effectuer
	 * des insertions, des updates... Elle est de même utilisée par les
	 * autres fonction de la classe comme queryRow() et queryTab().
	 *
	 * @param string $query chaine SQL
	 * @param mixed $param variables bind de type array(":bind"=>"value")
	 * @return void
	 */
	public function query($query, $param = array()) {

		global $sysNbQuery;

		// execution de la requête
		$this->query = (isset($_SERVER['HOSTNAME']) ? '/*SIG'.$_SERVER['HOSTNAME'].'SIG*/ ' : '').$query;
		$this->param = $param;
		$this->errorParams = array();
		$this->errorParams['Request'] = $query;
		$this->errorParams['Bind'] = $param;

		$this->id->setAttribute(PDO::ATTR_AUTOCOMMIT, $this->getCommitMode());
		$this->id->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

		$sysNbQuery = (!isset($sysNbQuery) || $sysNbQuery<=0) ? 1 : $sysNbQuery+1;
		
		// Prepare de la requête
		$queryMD5 = md5($query);					
		if(!isset($this->aPrepare[$queryMD5])) {
    	$this->lPrepare = $this->id->prepare($this->query);
    	$this->aPrepare[$queryMD5] = $this->lPrepare;
		} else {
			$this->lPrepare = $this->aPrepare[$queryMD5];
		}  

		if ($this->lPrepare!==false) {
			// Bind des paramètres
			if($param) {
				foreach($param as $key => $val) {
					if (strpos($query, $key) !== false) {
						if($param[$key]===null) $this->lPrepare->bindParam(trim($key), $param[$key], PDO::PARAM_NULL);
						else $this->lPrepare->bindParam(trim($key), $param[$key]);
					}
				}
			}
			
			// Execution de la requête
			$rs = $this->lPrepare->execute();
			
			if ($this->lPrepare->errorCode() != PDO::ERR_NONE) {
				$this->errorParams['errorInfo'] = $this->lPrepare->errorInfo();
				//echo'<xmp>Erreur execute() de PDO : '.$this->errorParams['errorInfo'][2];print_r($query);echo'</xmp>';
				//Génération d'une DataBaseException
				//throw new DataBaseException("Erreur execute() de PDO",$error[2],$this->errorParams);
			}
			
			return $rs;
			
		}else{
			$this->errorParams['errorInfo'] = $this->lPrepare->errorInfo();
			//echo'<xmp>Erreur prepare() de PDO : '.$this->errorParams['errorInfo'][2];print_r($query);echo'</xmp>';
			//DatabaseManager::log($this, true);
			//throw new DataBaseException("Erreur prepare() de PDO",$this->id->errorInfo(),$this->errorParams);
		}
		return false;
	}
Esempio n. 10
0
 /**
  * @param PDOStatement|boolean $sth
  * @param mixed $result
  * @return boolean TRUE if $result indicates failure, FALSE otherwise
  */
 private function isFailure($sth, $result)
 {
     if ($result === false) {
         $error = $sth->errorInfo();
         $this->lastError = 'DB ERROR: [' . $sth->errorCode() . '] ' . $error[2];
         error_log($this->lastError);
         return true;
     }
     return false;
 }
Esempio n. 11
0
 /**
  * Constructor.
  *
  * @param \PDOStatement $pdoStatement
  * @param mixed $mapFunction
  * @param int $fetchStyle Controls how the row will be returned
  *
  * @throws \Quaver\Core\QException
  */
 public function __construct($pdoStatement, $mapFunction, $fetchStyle = \PDO::ATTR_DEFAULT_FETCH_MODE)
 {
     if ($pdoStatement->errorCode() != 0) {
         throw new QException('PDO statement with errors');
     }
     $this->stm = $pdoStatement;
     $this->mapFunction = $mapFunction;
     $this->fetchStyle = $fetchStyle;
     $this->cur = 0;
     $this->count = $pdoStatement->rowCount();
     $this->next();
 }
Esempio n. 12
0
 /**
  * Executes the statement.
  * 
  * @return boolean
  * @throws DBQueryException
  */
 public function execute()
 {
     $start = microtime(true);
     $this->query->execute();
     $end = microtime(true);
     $sql = (string) $this->query->queryString;
     $error_id = (int) $this->query->errorCode();
     if ($this->callback) {
         $time = ($end - $start) * 1000;
         call_user_func_array($this->callback, array($sql, $time));
     }
     if ($error_id) {
         $error = $this->query->errorInfo();
         $message = "Database query error: ({$error[0]}/{$error[1]}) {$error[2]} in query [{$sql}]";
         throw new DBQueryException($message, E_USER_WARNING);
         return false;
     }
     $this->key = 0;
     $this->count = $this->query->rowCount();
     $this->current = $this->query->fetch();
 }
Esempio n. 13
0
 public function execute($inputParameters = array())
 {
     $ret = parent::execute($inputParameters);
     Debugger::getInstance()->debug('SQL:' . $this->queryString . ';params:' . var_export($inputParameters, true));
     if (!$ret) {
         $error_info = parent::errorInfo();
         if (parent::errorCode() != '00000') {
             // 执行成功时返回五个零
             LoggerFactory::getLogger()->error('PDO executed failed,errors:' . var_export($error_info, true));
             trigger_error($this->queryString, E_USER_ERROR);
         }
     }
     return $ret;
 }
Esempio n. 14
0
 /**
  *
  * @see Iterator::rewind()
  */
 public function rewind()
 {
     //Dirty hack because rewind() is called before entering the loop
     //and on object creation we already have query executed
     if ($this->_needsRefresh) {
         $this->_refresh();
     } else {
         $this->_needsRefresh = true;
     }
     $this->_currentRowObj = $this->_statement->fetchObject('\\phpSweetPDO\\RecordsetRow');
     if ($this->_statement->errorCode() !== '00000') {
         throw new DbException($this->_statement->errorInfo(), $this->_statement->queryString);
     }
 }
Esempio n. 15
0
 /**
  * Executes the query that was previously passed to the constructor.
  *
  * @param mixed  $arg      Query arguments to escape and insert at ? placeholders in $query
  * @param mixed  ...       Additional arguments
  **/
 public function execute()
 {
     // We can't very well perform a query wtihout an active connection.
     if (!is_object($this->dbh)) {
         $this->db->error('Lost connection to database.');
         return;
     }
     // end if
     // Finish any previous statements
     $this->finish();
     // We need to pre-process the arguments for literals and bytefields.  We
     // can't safely pass them into the PDO placeholder system, so we'll
     // have to stick them into the query at the right places before then.
     $args = Database::smart_args(func_get_args());
     list($query, $nargs, $nargn) = $this->reprocess_query($args);
     if (!$query) {
         return;
     }
     $this->last_query = $this->unprocess_query($query, $nargn);
     // Wrap the actual query execution in a bit of benchmarking.
     $before = microtime(true);
     $this->last_exception = null;
     try {
         // We will always create a new statement.  The possibility of missing
         // & pre-replaced placeholders breaks our ability to work with actual
         // prepared statements.  Additionally, PDO tends to break easily when
         // working on prepared statements that return multiple result sets
         // combined with multiple concurrent statement handles.  See the
         // comments on the PDOStatement::closeCursor() manual page.
         // Skip preparing the query if there are no args in the query.
         if ($nargn == 0) {
             $this->sh = $this->dbh->query($this->last_query);
         } else {
             $this->sh = $this->dbh->prepare($this->last_query);
             $this->sh->execute($nargs);
         }
     } catch (PDOException $e) {
         $this->last_exception = $e;
         $this->db->error('SQL Error:');
         return false;
     }
     // end try
     $after = microtime(true);
     $this->db->mysql_time += $after - $before;
     // The other adapters handle these here.  Fun times.
     // Problem 1:
     //  PDO does not provide a clear way to get the last inserted primary key.
     //  There's PDO::lastInsertId(), but it's poorly supported and sometimes
     //  requires extra arguments be passed.  There's undoubtedly a better
     //  way to deal with this than to not deal with it.
     $this->insert_id = null;
     // Problem 2:
     //  PDOStatement::rowCount()'s manual page says:
     //   "If the last SQL statement executed by the associated PDOStatement
     //    was a SELECT statement, some databases may return the number of
     //    rows returned by that statement. However, this behaviour is not
     //    guaranteed for all databases and should not be relied on for
     //    portable applications."
     //  So, unlike the other adapters, there's no separate call for getting
     //  the number of returned rows vs the number of affected rows.
     //  We'll just use it here and hope it works and that calling code doesn't
     //  care too much.
     // Overall, PDO kind of sucks for this kind of thing.
     $this->affected_rows = $this->sh->rowCount();
     $this->num_rows = $this->sh->rowCount();
     // PDO has no way to check warnings.  We won't try.
     $this->warnings = array();
     // But we do have errors, though this *should* never be called thanks to the
     // exception catching above.
     $last_notice = $this->sh->errorCode();
     if ($last_notice == '00000' || empty($last_notice)) {
         $last_notice = null;
     }
     if ($last_notice) {
         $this->db->error('SQL Error:');
         return false;
     }
     return true;
 }
Esempio n. 16
0
 /**
  * 获得错误码
  *
  * @access public
  * @return string $code 错误码
  */
 public function get_error_code()
 {
     return parent::errorCode();
 }
Esempio n. 17
0
 /**
  * 获取statement Error Code
  * @return string
  */
 public function statementErrorCode()
 {
     return $this->_PDOStatement->errorCode();
 }
Esempio n. 18
0
 private function recordError(\PDOStatement $stmt, array $params = null)
 {
     $errorCode = $stmt->errorCode();
     if (isset($errorCode) && $errorCode !== '00000') {
         $this->errorCode = $errorCode;
         $this->errorInfo = $stmt->errorInfo();
         throw new DatabaseException($this->errorInfo[2]);
     }
 }
Esempio n. 19
0
 /**
  * Executes PDOStatement and checks for errors
  *
  * @throws DbException
  * @param  \PDOStatement $statement
  * @param  string $sql
  * @param  array $params
  * @return void
  */
 protected function _executeStatement($statement, $sql, $params)
 {
     if (!$statement->execute($params) and $statement->errorCode() != '00000') {
         throw new DbException($statement->errorInfo(), $sql, $params);
     }
 }
Esempio n. 20
0
 /**
  * Execute a PDO statement, with additional error handling
  * 
  * @param PDOStatement $query
  * @param bool $throw Whether or not to throw exception on query error (default=true)
  * @param int $maxTries Max number of times it will attempt to retry query on error
  * @return bool
  * 
  */
 public function executeQuery(PDOStatement $query, $throw = true, $maxTries = 3)
 {
     $tryAgain = 0;
     $_throw = $throw;
     do {
         try {
             $result = $query->execute();
         } catch (PDOException $e) {
             $result = false;
             $error = $e->getMessage();
             $throw = false;
             // temporarily disable while we try more
             if ($tryAgain === 0) {
                 // setup retry loop
                 $tryAgain = $maxTries;
             } else {
                 // decrement retry loop
                 $tryAgain--;
             }
             if (stripos($error, 'MySQL server has gone away') !== false) {
                 // forces reconection on next query
                 $this->wire('database')->closeConnection();
             } else {
                 if ($query->errorCode() == '42S22') {
                     // unknown column error
                     $errorInfo = $query->errorInfo();
                     if (preg_match('/[\'"]([_a-z0-9]+\\.[_a-z0-9]+)[\'"]/i', $errorInfo[2], $matches)) {
                         $this->unknownColumnError($matches[1]);
                     }
                 } else {
                     // some other error that we don't have retry plans for
                     // tryAgain=0 will force the loop to stop
                     $tryAgain = 0;
                 }
             }
             if ($tryAgain < 1) {
                 // if at end of retry loop, restore original throw state
                 $throw = $_throw;
             }
             if ($throw) {
                 throw $e;
             } else {
                 $this->error($error);
             }
         }
     } while ($tryAgain && !$result);
     return $result;
 }
Esempio n. 21
0
 public function getErrorCode()
 {
     return $this->pdoStatement ? $this->pdoStatement->errorCode() : ($this->pdo ? $this->pdo->errorCode() : null);
 }
Esempio n. 22
0
 /**
  * @return string
  * @throws \Compeek\PDOWrapper\NotConnectedException
  */
 public function errorCode()
 {
     $this->requireConnection();
     return $this->pdoStatement->errorCode();
 }
Esempio n. 23
0
 /**
  * {@inheritDoc}
  */
 public function errorCode()
 {
     return $this->lastStatement === null ? null : $this->lastStatement->errorCode();
 }
 /**
  * {@inheritdoc}
  */
 public function errorCode()
 {
     return $this->statement->errorCode();
 }
Esempio n. 25
0
 protected function getStatementExecutionException(\PDOStatement $stmt)
 {
     return new StatementExecutionException(sprintf('[%s] %s: %s', $stmt->errorCode(), $stmt->errorInfo()[1], $stmt->errorInfo()[2]));
 }
 /**
  * Determine if a resource has an attached error
  *
  * @param PDOStatement|PDO $resource the resource to check
  * @return boolean Flag indicating true if the resource has an error
  */
 protected function hasError($resource)
 {
     // No error if no resource
     if (empty($resource)) {
         return false;
     }
     // If the error code is empty the statement / connection has not been run yet
     $code = $resource->errorCode();
     if (empty($code)) {
         return false;
     }
     // Skip 'ok' and undefined 'warning' types.
     // @see http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm
     return $code !== '00000' && $code !== '01000';
 }
 /**
  * @return string
  */
 public function errorCode()
 {
     $archLog = array('method' => 'PDOStatement::errorCode', 'input' => array(), 'output' => $this->PDOStatement->errorCode(), 'pointer' => $this->assignPointerString());
     return self::setLogReturnOutput($archLog);
 }
Esempio n. 28
0
 /**
  * Executes the given statement
  * 
  * @throws \Knid\Mapper\Exception
  * @param \PDOStatement $stmt
  */
 protected function executeStatement(\PDOStatement $stmt)
 {
     if (false === $stmt->execute()) {
         throw new Mapper\Exception($stmt->errorCode(), $stmt->errorInfo());
     }
 }
 /**
  * Will execute the passed statement and return the result as an array of TpOudeRechten instances
  *
  * @param PDOStatement $stmt
  * @return TpOudeRechten[]
  */
 public static function fromStatement(PDOStatement $stmt)
 {
     $affected = $stmt->execute();
     if (false === $affected) {
         $stmt->closeCursor();
         throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
     }
     return self::fromExecutedStatement($stmt);
 }
Esempio n. 30
0
 /**
 * @static
 * @throws Exception
 * @param	PDOStatement $statement
 * @param	string $query
 * @param	array $parameters
 @ @param	bool  $reportErrors
 * @return void
 */
 public static function processError($statement, $query, $parameters = array(), $reportErrors = true)
 {
     if ($reportErrors == false) {
         return;
     }
     $errorCode = $statement->errorCode();
     $errorInfo = $statement->errorInfo();
     self::log("{$errorCode} - " . $errorInfo[2] . "\n{$query}", $parameters, 1000);
     throw new Exception($errorInfo[0] . " - " . $errorInfo[1] . " - " . $errorInfo[2]);
 }