拼接sql语句，并自动插入空格
@param string $sql 表达式
480528
public function appendSql($sql, $addSpace=true){
        if($this->sql == ''){
            $this->sql = $sql;
        }else{
            if($addSpace){
                $this->sql = $this->sql.' '.$sql;
            }else{
                $this->sql = $this->sql.$sql;
            }
        }
    }
547413
public function exec_script($sql)
    {
        $sql  = $this->fix_table_names($sql);
        $buff = '';
        $exec = '';

        foreach (explode("\n", $sql) as $line) {
            $trimmed = trim($line);
            if ($trimmed == '' || preg_match('/^--/', $trimmed)) {
                continue;
            }

            if ($trimmed == 'GO') {
                $exec = $buff;
            }
            else if ($trimmed[strlen($trimmed)-1] == ';') {
                $exec = $buff . substr(rtrim($line), 0, -1);
            }

            if ($exec) {
                $this->query($exec);
                $buff = '';
                $exec = '';
                if ($this->db_error) {
                    break;
                }
            }
            else {
                $buff .= $line . "\n";
            }
        }

        return !$this->db_error;
    }
1039303
public function load($sql)
    {
        $query = '';
        $delimiter = '//';
        $delimiterLength = 2;

        foreach ($sql as $sqlLine) {
            if (preg_match('/DELIMITER ([\;\$\|\\\\]+)/i', $sqlLine, $match)) {
                $delimiter = $match[1];
                $delimiterLength = strlen($delimiter);
                continue;
            }

            $parsed = $this->sqlLine($sqlLine);
            if ($parsed) {
                continue;
            }

            $query .= "\n" . rtrim($sqlLine);

            if (substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) {
                $this->sqlQuery(substr($query, 0, -1 * $delimiterLength));
                $query = "";
            }
        }

        if ($query !== '') {
            $this->sqlQuery($query);
        }
    }
1144470
public function prepareQuery($sql, $params = array())
	{
		// 如果参数为空则取链式操作传入的参数
		$params = $this->parseParams($params);
		// 记录sql语句和参数
		$this->lastSql = $sql;
		$this->lastSqlParams = $params;
		$beginTime = microtime(true);
		if(empty($params) && empty($this->bindValues))
		{
			// 没有参数的查询
			$result = $this->lastStmt = $this->handler->query($sql);
		}
		else
		{
			// 参数查询
			$result = $this->lastStmt = $this->handler->prepare($sql);
			if($result)
			{
				// 自动绑定的参数
				foreach($params as $key => $value)
				{
					if(is_int($key))
					{
						// 问号形式的参数
						$paramName = ($key) + 1;
					}
					else
					{
						// 名称形式的参数
						$paramName = ':' . $this->parseParamName($key);
					}
					// 绑定参数
					$this->lastStmt->bindValue($paramName, $value, $this->geetParamTypeByValue($value));
				}
				// 手动绑定的参数
				foreach($this->bindValues as $bindValue)
				{
					$this->lastStmt->bindValue($bindValue[0], $bindValue[1], $bindValue[2]);
				}
				// 执行
				$result = $this->lastStmt->execute();
			}
		}
		Event::trigger('ON_DB_QUERY', array(
			'handler'	=>	$this,
			'time'		=>	microtime(true) - $beginTime,
			'sql'		=>	$sql,
		));
		if(false === $result)
		{
			$GLOBALS['debug']['lastsql'] = $sql;
			throw new Exception($this->getError());
		}
		// 链式操作清空
		$this->operationOption = array();
		$this->randomParamNum = 0;
		$this->bindValues = array();
		return $this->lastStmt;
	}
1132133
public function query($sql)
    {
        if (!$this->DB) {
            throw  new Exception('您还没有连接数据库', Exception::CODE_DATABASE_ERROR);
        }
        $sql = str_replace('@#_', $this->prefix, $sql);
        /**
         * 只获取sql
         */
        if ($this->justSql) {
            return true;
        }
        $this->lastQueryAt = time();
        return $this->DB->query($sql);
    }
469119
public function setSQL($sql)
    {
        if ((is_string($sql) && (strlen($sql) <= 0)) || (!is_string($sql) && ($sql !== null))) {
            throw SchemaException::invalidViewSQL($this->getName());
        }

        $this->sql = $sql;
    }
1153388
public function addSql($sql)
    {
        if (is_array($sql)) {
            $this->sql = array_merge($this->sql, $sql);
        } else {
            $this->sql[] = $sql;
        }

        return $this;
    }
1297828
protected function processViaSMI2(string $sql) : void
    {
        $sql = trim($sql);

        $this->rows =
            stripos($sql, 'select') === 0 ||
            stripos($sql, 'show') === 0 ||
            stripos($sql, 'describe') === 0 ?
                $this->smi2CHClient->select($sql)->rows() :
                $this->smi2CHClient->write($sql)->rows();
    }
361381
public function prepare( $sql, $values ) {
		/** @var \wpdb $wpdb */
		global $wpdb;

		return empty( $values ) ? $sql : $wpdb->prepare( $sql, $values );
	}
1014560
private function executeSqlQuery($sql)
    {
        try {
            $result = (bool) Database::statement($sql);
        } catch (\Exception $exception) {
            echo "\n\033[0;31m▶\033[00m $sql\n";
            throw $exception;
        }

        echo "\033[0;32m▶\033[00m $sql\n";

        return $this;
    }
12323
public function execute($sql) {
        //
        // TODO: check mysql_unbuffered_query() with mysql_free_result() for larger result sets
        //       @see  https://www.percona.com/blog/2006/06/26/handling-of-big-parts-of-data/
        //       @see  https://dev.mysql.com/doc/refman/5.7/en/mysql-use-result.html

        $result = $this->executeRaw($sql);
        if (is_resource($result))
            mysql_free_result($result);               // release the result
        return $this;
    }
1373875
public function log($sql)
    {
        $query = new LoggedQuery();
        $query->query = $sql;
        $this->getLogger()->log($query);
    }
1212412
protected function query ( $sql )
	{
		$sql = $this->sql_printf(func_get_args());
		if (!($res = mysql_query($sql, $this->conn)))
		{
			$this->sql_errcheck($sql);
		}
		if (is_resource($res))
		{
			mysql_free_result($res);
		}
	}
527235
public function format($sql)
    {
        $this->reset();
        $tab = "\t";

        $originalTokens = $this->tokenizer->tokenize((string) $sql);
        $tokens = WhiteSpace::removeTokenWhitespace($originalTokens);

        foreach ($tokens as $i => $token) {
            $queryValue = $token[Tokenizer::TOKEN_VALUE];
            $this->indentation->increaseSpecialIndent()->increaseBlockIndent();
            $addedNewline = $this->newLine->addNewLineBreak($tab);

            if ($this->comment->stringHasCommentToken($token)) {
                $this->formattedSql = $this->comment->writeCommentBlock($token, $tab, $queryValue);
                continue;
            }

            if ($this->parentheses->getInlineParentheses()) {
                if ($this->parentheses->stringIsClosingParentheses($token)) {
                    $this->parentheses->writeInlineParenthesesBlock($tab, $queryValue);
                    continue;
                }
                $this->newLine->writeNewLineForLongCommaInlineValues($token);
                $this->inlineCount += \strlen($token[Tokenizer::TOKEN_VALUE]);
            }

            switch ($token) {
                case $this->parentheses->stringIsOpeningParentheses($token):
                    $tokens = $this->formatOpeningParenthesis($token, $i, $tokens, $originalTokens);
                    break;

                case $this->parentheses->stringIsClosingParentheses($token):
                    $this->indentation->decreaseIndentLevelUntilIndentTypeIsSpecial($this);
                    $this->newLine->addNewLineBeforeToken($addedNewline, $tab);
                    break;

                case $this->stringIsEndOfLimitClause($token):
                    $this->clauseLimit = false;
                    break;

                case $token[Tokenizer::TOKEN_VALUE] === ',' && false === $this->parentheses->getInlineParentheses():
                    $this->newLine->writeNewLineBecauseOfComma();
                    break;

                case Token::isTokenTypeReservedTopLevel($token):
                    $queryValue = $this->formatTokenTypeReservedTopLevel($addedNewline, $tab, $token, $queryValue);
                    break;

                case $this->newLine->isTokenTypeReservedNewLine($token):
                    $this->newLine->addNewLineBeforeToken($addedNewline, $tab);

                    if (WhiteSpace::tokenHasExtraWhiteSpaces($token)) {
                        $queryValue = \preg_replace('/\s+/', ' ', $queryValue);
                    }
                    break;
            }

            $this->formatBoundaryCharacterToken($token, $i, $tokens, $originalTokens);
            $this->formatWhiteSpaceToken($token, $queryValue);
            $this->formatDashToken($token, $i, $tokens);
        }

        return \trim(\str_replace(["\t", " \n"], [$this->tab, "\n"], $this->formattedSql))."\n";
    }
1167935
public function execute(string $sql, array $params = []): bool
    {
        $t1   = microtime(true);
        $sql  = trim($sql); //去除两端空格
        $type = strtoupper(substr($sql, 0, 6));
        //根据操作类型选择服务器，只有非事务的select使用读服务器
        if ($type == 'SELECT' && !$this->isTrans) {
            $this->setDriver('r');
        } else {
            $this->setDriver('w');
        }

        $this->DriverStatement = $this->Driver->prepare($sql);
        if (!$this->DriverStatement) {
            $this->exception('预处理语句失败', $sql);
        }

        //绑定变量
        if (is_numeric(key($params))) {
            foreach ($params as $k => $v) {
                $this->DriverStatement->bindValue($k + 1, $v); //使用?占位符,索引从1开始
            }
        } else {
            foreach ($params as $k => $v) {
                $this->DriverStatement->bindValue($k, $v);
            }
        }

        //查询结果并记录时间
        $r    = $this->DriverStatement->execute();
        $time = microtime(true) - $t1;

        //抛出错误
        if ($r === false) {
            $error = $this->DriverStatement->errorInfo();
            $error = '[SQLSTATE ' . $error[0] . ']' . $error[1] . ' ' . $error[2];
            $this->exception($error);
            return false;
        }

        //调试打开，输送执行信息
        if ($this->Debug) {
            $type = $type == 'SELECT' ? 'read' : 'write';
            $this->Debug->execute($sql, $time, $this->index, $this->DriverStatement->rowCount(), $type, $params); //执行语句，绑定变量，执行时间，执行服务器索引
        }
        return true;
    }
907974
protected function applyLimit($sql){
		list($limit, $offset) = $this->stmt->getLimit();

		if((int) $limit > 0){
			$sql .= "\nLIMIT " . (int) $limit;
			if((int) $offset > 0)
				$sql .= ' OFFSET ' . (int) $offset;
		}
		return $sql;
	}
514268
protected function checkTableStatus(string $table, string $sql) : void
    {
        $sql = preg_replace("@^\s+@ms", '', $sql);
        $requestedColumns = [];
        foreach (preg_split("@,\n@m", $sql) as $reqCol) {
            if (preg_match("@^PRIMARY KEY\s*\((.*?)\)@", $reqCol, $pk)) {
                continue;
            }
            preg_match("@^[^\s]+@", $reqCol, $name);
            $name = $name[0];
            $requestedColumns[$name] = [
                'column_name' => $name,
                'column_default' => null,
                'is_nullable' => true,
                'column_type' => '',
                '_definition' => trim($reqCol),
            ];
            $reqCol = str_replace('PRIMARY KEY', '', $reqCol);
            $reqCol = preg_replace("@^$name\s+@", '', $reqCol);
            if (strpos($reqCol, 'NOT NULL')) {
                $requestedColumns[$name]['is_nullable'] = false;
                $reqCol = str_replace('NOT NULL', '', $reqCol);
            }
            if (preg_match("@DEFAULT\s+(.*?)$@", $reqCol, $default)) {
                $parsed = preg_replace("@(^'|'$)@", '', $default[1]);
                $requestedColumns[$name]['column_default'] = $parsed;
                $requestedColumns[$name]['_default'] = $default[1];
                $reqCol = str_replace($default[0], '', $reqCol);
            }
            $requestedColumns[$name]['column_type'] = trim($reqCol);
        }
        $this->columns->execute([$this->loader->getDatabase(), $table]);
        $currentColumns = [];
        foreach ($this->columns->fetchAll(PDO::FETCH_ASSOC) as $column) {
            if (!isset($requestedColumns[$column['column_name']])) {
                $this->addOperation("ALTER TABLE $table DROP COLUMN {$column['column_name']};");
            } else {
                $column['is_nullable'] = $column['is_nullable'] == 'YES';
                $column['column_type'] = strtoupper($column['column_type']);
                $currentColumns[$column['column_name']] = $column;
            }
        }
        foreach ($requestedColumns as $name => $col) {
            if (!isset($currentColumns[$name])) {
                $this->addOperation("ALTER TABLE $table ADD COLUMN {$col['_definition']};");
            } else {
                foreach ($this->modifyColumn($table, $name, $col, $currentColumns[$name]) as $sql) {
                    $this->addOperation($sql);
                }
            }
        }
    }