触发SQL事件
@access protected
@param string    $sql 语句
@param float     $runtime 运行时间
@param array     $options 参数
@return bool
426523
protected function trigger($sql, $runtime, $options = [])
    {
        if (!empty(self::$event)) {
            foreach (self::$event as $callback) {
                if (is_callable($callback)) {
                    call_user_func_array($callback, [$sql, $runtime, $options]);
                }
            }
        }
        return null;
    }
556094
private static function run_sql( $sql_cmd, $assoc_args = array(), $add_database = false ) {
		$default_assoc_args = array(
			'host' => self::$db_settings['dbhost'],
			'user' => self::$db_settings['dbuser'],
			'pass' => self::$db_settings['dbpass'],
		);
		if ( $add_database ) {
			$sql_cmd .= ' ' . escapeshellarg( self::$db_settings['dbname'] );
		}
		$start_time = microtime( true );
		Utils\run_mysql_command( $sql_cmd, array_merge( $assoc_args, $default_assoc_args ) );
		if ( self::$log_run_times ) {
			self::log_proc_method_run_time( 'run_sql ' . $sql_cmd, $start_time );
		}
	}
612068
function ExecuteSQLArray($sql, $continueOnError = true)
	{
		$rez = 2;
		$conn = $this->connection;
		$saved = $conn->debug;
		foreach($sql as $line) {

			if ($this->debug) $conn->debug = true;
			$ok = $conn->Execute($line);
			$conn->debug = $saved;
			if (!$ok) {
				if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
				if (!$continueOnError) return 0;
				$rez = 1;
			}
		}
		return $rez;
	}
554275
function select( $table, $options = array() ) {

        $options = array_merge( array(

            'expr' => null,
            'where' => array(),
            'orderBy' => array(),
            'limitCount' => null,
            'limitOffset' => null,
            'params' => array()

        ), $options );

        $query = "SELECT ";

        if ( empty( $options[ 'expr' ] ) ) {

            $query .= "*";

        } else if ( is_array( $options[ 'expr' ] ) ) {

            $query .= implode( ", ", $options[ 'expr' ] );

        } else {

            $query .= $options[ 'expr' ];

        }

        $table = $this->rewriteTable( $table );
        $query .= " FROM " . $this->quoteIdentifier( $table );

        $query .= $this->getSuffix( $options[ 'where' ], $options[ 'orderBy' ], $options[ 'limitCount' ], $options[ 'limitOffset' ] );

        $this->onQuery( $query, $options[ 'params' ] );

        $statement = $this->prepare( $query );
        $statement->setFetchMode( \PDO::FETCH_ASSOC );
        $statement->execute( $options[ 'params' ] );

        return $statement;

    }
483167
public function prepare(string $sql, array $driverOptions = [])
    {
        $isCache = !isset($driverOptions['IMI_NO_CACHE']) || $driverOptions['IMI_NO_CACHE'];
        if($isCache && $stmtCache = StatementManager::get($this, $sql))
        {
            $stmt = $stmtCache['statement'];
        }
        else
        {
            // 处理支持 :xxx 参数格式
            $this->lastSql = $sql;
            $this->lastStmt = $this->instance->prepare($sql, $driverOptions);
            if(false === $this->lastStmt)
            {
                throw new DbException('sql prepare error: [' . $this->errorCode() . '] ' . $this->errorInfo() . PHP_EOL . 'sql: ' . $sql . PHP_EOL);
            }
            $stmt = BeanFactory::newInstance(Statement::class, $this, $this->lastStmt);
            if($isCache)
            {
                $stmtCache = StatementManager::get($this, $sql);
                if($stmtCache)
                {
                    StatementManager::unUsingStatement($stmtCache['statement']);
                }
                else
                {
                    StatementManager::set($stmt, true);
                }
            }
        }

        return $stmt;
    }
712433
public function fetchColumnAll($sql, array $params=null, $column=0, $offset=0, $length=0)
	{
        if ($length > 0) {
            $sql .= " LIMIT " . (int)$offset . ', '. (int)$length;
        }

		if ($params) {
			$stmt = $this->prepare($sql);
			if (!$stmt) { return false; }

			$flag = $stmt->execute($params);
			if (!$flag) { return false; }
		} else {
			$stmt = $this->query($sql);
			if (!$stmt) { return false; }
		}

		return $stmt->fetchAll(PDO::FETCH_COLUMN, $column);
	}
931568
public function execute()
	{
		$this->connect();

		if (!is_object($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			// @TODO
			$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query.
		$this->executed = false;

		if ($this->prepared instanceof \PDOStatement)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				foreach ($bounded as $key => $obj)
				{
					$this->prepared->bindParam($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
				}
			}

			$this->executed = $this->prepared->execute();
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			// Get the error number and message before we execute any more queries.
			$errorNum = (int) $this->connection->errorCode();
			$errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) $this->connection->errorCode();
					$this->errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message from before we tried to reconnect.
				$this->errorNum = $errorNum;
				$this->errorMsg = $errorMsg;

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->prepared;
	}
681252
public function execute(Session $session, $sql, array $options = [])
    {
        $options += [
            'parameters' => [],
            'types' => [],
            'transactionContext' => null
        ];

        $parameters = $this->pluck('parameters', $options);
        $types = $this->pluck('types', $options);
        $options += $this->mapper->formatParamsForExecuteSql($parameters, $types);

        $context = $this->pluck('transactionContext', $options);

        $call = function ($resumeToken = null) use ($session, $sql, $options) {
            if ($resumeToken) {
                $options['resumeToken'] = $resumeToken;
            }

            return $this->connection->executeStreamingSql([
                'sql' => $sql,
                'session' => $session->name(),
                'database' => $session->info()['database']
            ] + $options);
        };

        return new Result($this, $session, $call, $context, $this->mapper);
    }
1171730
public function run($sql, array $params = array())
    {
        $sth = $this->pdo->prepare($sql);

        foreach ($params as $key => $value) {
            $key = is_numeric($key) ? $key + 1 : ":$key";
            $sth->bindValue($key, $value);
        }

        $sth->execute($params);
        $this->executed[] = $sql;
        return $sth;
    }
1235208
public function executeRaw($sql) {
        if (!is_string($sql)) throw new IllegalTypeException('Illegal type of parameter $sql: '.gettype($sql));
        if (!$this->isConnected())
            $this->connect();

        // execute statement
        $result = null;
        try {
            if ($this->skipResults) $result = $this->sqlite->exec($sql);        // TRUE on success, FALSE on error
            else                    $result = $this->sqlite->query($sql);       // bug: always SQLite3Result, never boolean
            if (!$result) trigger_error('Error '.$this->sqlite->lastErrorCode().', '.$this->sqlite->lastErrorMsg(), E_USER_ERROR);
        }
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            throw $ex->addMessage('Database: '.$this->file.NL.'SQL: "'.$sql.'"');
        }

        // track last_insert_id
        $this->lastInsertId = $this->sqlite->lastInsertRowID();

        // track last_affected_rows
        $this->lastAffectedRows = $this->sqlite->changes();

        return $result;
    }
415754
private function executeSql(PDO $pdo, $sql, array $parameters = null) {
        $this->lastPdo = $pdo;
        $this->lastSql = $sql;
        $this->lastParameters = $parameters;

        try {
            $pdoStmt = $pdo->prepare($sql);
            $pdoStmt->execute($parameters);
            return $pdoStmt;
        } catch (Exception $ex) {
            $errMsg = '执行SQL语句出错，错误消息：' . $ex->getMessage() . ', SQL：' . $this->getLastSql();
            $this->logger->error($errMsg);

            return false;
        }
    }
971354
public function alterTable($table, $options)
    {
        $table = $this->buildRealTableName($table);
        $sql = $this->getSchema()->getAlterTableSql($table, $options);
        if ($sql) {
            $ret = $this->query($sql);
        }
        return isset($ret) ? $ret : false;
    }
57323
function _query($sql,$inputarr=false)
	{
		if (is_array($sql)) {
			$stmt = $sql[1];
		} else {
			$stmt = $this->_connectionID->prepare($sql);
		}
		#adodb_backtrace();
		#var_dump($this->_bindInputArray);
		if ($stmt) {
			$this->_driver->debug = $this->debug;
			if ($inputarr) {
				$ok = $stmt->execute($inputarr);
			}
			else {
				$ok = $stmt->execute();
			}
		}


		$this->_errormsg = false;
		$this->_errorno = false;

		if ($ok) {
			$this->_stmt = $stmt;
			return $stmt;
		}

		if ($stmt) {

			$arr = $stmt->errorinfo();
			if ((integer)$arr[1]) {
				$this->_errormsg = $arr[2];
				$this->_errorno = $arr[1];
			}

		} else {
			$this->_errormsg = false;
			$this->_errorno = false;
		}
		return false;
	}
335910
public static function createDbo($driver, array $options)
    {
        // Sanitize the database connector options.
        $options['driver'] = preg_replace('/[^A-Z0-9_\.-]/i', '', $driver);
        $options['database'] = $options['database'] ?? null;
        $options['select'] = $options['select'] ?? true;

        // Use custom Resource
        $resource = $options['resource'] ?? null;

        // Derive the class name from the driver.
        $class = '\\Windwalker\\Database\\Driver\\' . ucfirst(strtolower($options['driver'])) . '\\'
            . ucfirst(strtolower($options['driver'])) . 'Driver';

        // If the class still doesn't exist we have nothing left to do but throw an exception.  We did our best.
        if (!class_exists($class)) {
            throw new \RuntimeException(sprintf('Unable to load Database Driver: %s', $options['driver']));
        }

        /** @var DatabaseDriverInterface $class */
        if (!$class::isSupported()) {
            throw new \RangeException('Database driver ' . $driver . ' not supported.');
        }

        // Create our new Driver connector based on the options given.
        try {
            $instance = new $class($resource, $options);
        } catch (\RuntimeException $e) {
            throw new \RuntimeException(sprintf('Unable to connect to the Database: %s', $e->getMessage()));
        }

        return $instance;
    }
844785
public function sql($sql, $val = false) {
        #$val为true时，返回执行结果
        $result = preg_split('/;(\r|\n)/is', $sql);
        if ($val) {
            foreach ((array) $result as $r) {
                if ($row = $this->connection->query($r)) {
                    return $row;
                } else {
                    return false;
                }
            }
        }
        foreach ((array) $result as $r) {
            if (!$this->connection->execute($r)) {
                return false;
            }
        }
        return true;
    }
827376
public function exec($sql)
    {
        $this->useConfiguredDatabase();
        $success = $this->getDbConnection()->exec($sql);
        $this->checkForDatabaseError($sql, 'exec');
        return $success;
    }
321066
public function query($sql = null,$params = array())
	{
		if(!isset($this->operationOption['params']))
		{
			$this->operationOption['params'] = array();
		}
		$this->prepareQuery($sql ? $sql : $this->buildSelectSQL(),$params);
		if(false === $this->lastStmt)
		{
			return false;
		}
		else
		{
			return $this->lastStmt->fetchAll(PDO::FETCH_ASSOC);
		}
	}