Highlights given SQL code.
@param string $sql
@return string
971351
public static function highlightSql($sql){
		$keywords1 = 'SELECT|UPDATE|INSERT\s+INTO|DELETE|FROM|VALUES|SET|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|(?:LEFT\s+|RIGHT\s+|INNER\s+)?JOIN';
		$keywords2 = 'RANDOM|RAND|ASC|DESC|USING|AND|OR|ON|IN|IS|NOT|NULL|LIKE|TRUE|FALSE|AS';

		$sql = str_replace("\\'", '\\&#39;', $sql);
		$sql = preg_replace_callback("~(/\\*.*\\*/)|($keywords1)|($keywords2)|('[^']+'|[0-9]+)~", 'self::_highlightCallback', $sql);
		$sql = str_replace('\\&#39;', "\\'", $sql);
		return '<pre style="color:#555" class="sql-dump">' . trim($sql) . "</pre>\n";
	}
272451
public function select(SQLStatement $select): string
    {
        $limit = $select->getLimit();

        if ($limit <= 0) {
            return parent::select($select);
        }

        $offset = $select->getOffset();

        if ($offset < 0) {
            $sql = $select->getDistinct() ? 'SELECT DISTINCT ' : 'SELECT ';
            $sql .= 'TOP ' . $limit . ' ';
            $sql .= $this->handleColumns($select->getColumns());
            $sql .= $this->handleInto($select->getIntoTable(), $select->getIntoDatabase());
            $sql .= ' FROM ';
            $sql .= $this->handleTables($select->getTables());
            $sql .= $this->handleJoins($select->getJoins());
            $sql .= $this->handleWheres($select->getWheres());
            $sql .= $this->handleGroupings($select->getGroupBy());
            $sql .= $this->handleOrderings($select->getOrder());
            $sql .= $this->handleHavings($select->getHaving());

            return $sql;
        }

        $order = trim($this->handleOrderings($select->getOrder()));

        if (empty($order)) {
            $order = 'ORDER BY (SELECT 0)';
        }

        $sql = $select->getDistinct() ? 'SELECT DISTINCT ' : 'SELECT ';
        $sql .= $this->handleColumns($select->getColumns());
        $sql .= ', ROW_NUMBER() OVER (' . $order . ') AS opis_rownum';
        $sql .= ' FROM ';
        $sql .= $this->handleTables($select->getTables());
        $sql .= $this->handleJoins($select->getJoins());
        $sql .= $this->handleWheres($select->getWheres());
        $sql .= $this->handleGroupings($select->getGroupBy());
        $sql .= $this->handleHavings($select->getHaving());

        $limit += $offset;
        $offset++;

        return 'SELECT * FROM (' . $sql . ') AS m1 WHERE opis_rownum BETWEEN ' . $offset . ' AND ' . $limit;
    }
177576
protected function _renderOrder($sql)
    {
        if ($this->_parts[self::ORDER]) {
            $order = array();
            foreach ($this->_parts[self::ORDER] as $term) {
                if (is_array($term)) {
                    if(is_numeric($term[0]) && strval(intval($term[0])) == $term[0]) {
                        $order[] = (int)trim($term[0]) . ' ' . $term[1];
                    } else {
                        $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1];
                    }
                } else if (is_numeric($term) && strval(intval($term)) == $term) {
                    $order[] = (int)trim($term);
                } else {
                    $order[] = $this->_adapter->quoteIdentifier($term, true);
                }
            }
            $sql .= ' ' . self::SQL_ORDER_BY . ' ' . implode(', ', $order);
        }

        return $sql;
    }
950727
public function getUpdateSql(array $sql)
    {
        $update = 'UPDATE';
        if (!empty($this->priority)) {
            $update .= ' ' . $this->priority;
        }
        if (!empty($this->ignore)) {
            $update .= ' ' . $this->ignore;
        }
        $sql[] = $update . ' ' . $this->quoter->quoteName($this->table);

        return $sql;
    }
288780
public function exec_script($sql)
    {
        $sql  = $this->fix_table_names($sql);
        $buff = '';
        $body = false;

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

            $buff .= $line . "\n";

            // detect PL/SQL function bodies, don't break on semicolon
            if ($body && $tok == 'end;') {
                $body = false;
            }
            else if (!$body && $tok == 'begin') {
                $body = true;
            }

            if (!$body && substr($tok, -1) == ';') {
                $this->query($buff);
                $buff = '';
                if ($this->db_error) {
                    break;
                }
            }
        }

        return !$this->db_error;
    }
1042447
public function select(SQLStatement $select): string
    {
        $limit = $select->getLimit();

        if ($limit <= 0) {
            return parent::select($select);
        }

        $sql = $select->getDistinct() ? 'SELECT DISTINCT ' : 'SELECT ';
        $sql .= $this->handleColumns($select->getColumns());
        $sql .= ' FROM ';
        $sql .= $this->handleTables($select->getTables());
        $sql .= $this->handleJoins($select->getJoins());
        $sql .= $this->handleWheres($select->getWheres());
        $sql .= $this->handleGroupings($select->getGroupBy());
        $sql .= $this->handleOrderings($select->getOrder());
        $sql .= $this->handleHavings($select->getHaving());

        $offset = $select->getOffset();

        if ($offset < 0) {
            return 'SELECT * FROM (' . $sql . ') M1 WHERE ROWNUM <= ' . $limit;
        }

        $limit += $offset;
        $offset++;

        return 'SELECT * FROM (SELECT M1.*, ROWNUM AS OPIS_ROWNUM FROM (' . $sql . ') M1 WHERE ROWNUM <= ' . $limit . ') WHERE OPIS_ROWNUM >= ' . $offset;
    }
760123
protected function _prep_query($sql)
	{
		// mysql_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
		// modifies the query so that it a proper number of affected rows is returned.
		if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
		{
			return trim($sql).' WHERE 1=1';
		}

		return $sql;
	}
532880
public function query($sql)
    {
        #鉴定是执行查询还是commit提交操作。如果是select、show，可以有后续操作。
        $_key = strtolower(substr($sql, 0, 4));
        if ($_key == 'sele' || $_key == 'show') {
            $this->query_sql = $sql;
            return $this;
        } else {
            return $this->conn('master')->query($sql);
        }
    }
948690
public function compose(SQL $SQL){

		$tokens = [];
		$query_string = '';

		foreach($this->_values as $name => $value){

			// Throws an exception on invalid name/value

			$this->_checkParameter($name, $value);

			assert('is_array($this->_parameters[$name])');

			$prepared_value = $this->_prepareValue($value, $SQL,
				$this->_parameters[$name]['identifier']);
			$tokens[$this->_parameters[$name]['uid']] = $prepared_value;
		}

		foreach($this->_query as $query_part){

			list($token, $value) = explode(' ', $query_part, 2);

			switch($token){

				case 'P':

					if(isset($tokens[$value])){

						$query_string .= $tokens[$value];
					}

					break;

				case 'T':

					$query_string .= $value;

					break;

				default: ExceptionHandler::notice("Invalid token $token");
			}
		}

		return $query_string;
	}
380321
protected function findOrdering($sql)
	{
		if(!preg_match('/ORDER BY/i', $sql))
			return array();
		$matches=array();
		$ordering=array();
		preg_match_all('/(ORDER BY)[\s"\[](.*)(ASC|DESC)?(?:[\s"\[]|$|COMPUTE|FOR)/i', $sql, $matches);
		if(count($matches)>1 && count($matches[2]) > 0)
		{
			$parts = explode(',', $matches[2][0]);
			foreach($parts as $part)
			{
				$subs=array();
				if(preg_match_all('/(.*)[\s"\]](ASC|DESC)$/i', trim($part), $subs))
				{
					if(count($subs) > 1 && count($subs[2]) > 0)
					{
						$name='';
						foreach(explode('.', $subs[1][0]) as $p)
						{
							if($name!=='')
								$name.='.';
							$name.='[' . trim($p, '[]') . ']';
						}
						$ordering[$name] = $subs[2][0];
					}
					//else what?
				}
				else
					$ordering[trim($part)] = 'ASC';
			}
		}

		// replacing column names with their alias names
		foreach($ordering as $name => $direction)
		{
			$matches = array();
			$pattern = '/\s+'.str_replace(array('[',']'), array('\[','\]'), $name).'\s+AS\s+(\[[^\]]+\])/i';
			preg_match($pattern, $sql, $matches);
			if(isset($matches[1]))
			{
				$ordering[$matches[1]] = $ordering[$name];
				unset($ordering[$name]);
			}
		}

		return $ordering;
	}
827270
public function sql(): string
    {
        if (empty($this->parts)) {
            return '1';
        }
        return (string) \array_reduce(
            $this->parts,
            function (string $sql, array $part): string {
                /** @var string|self $condition */
                $condition = $part['condition'];

                if ($this->isGroup($condition)) {
                    // (...)
                    if (\is_string($condition)) {
                        $statement = '(' . $condition . ')';
                    } else {
                        $statement = '(' . $condition->sql() . ')';
                    }
                } else {
                    // foo = ?
                    $statement = $condition;
                }
                /** @var string $statement */
                $statement = (string) $statement;
                $part['type'] = (string) $part['type'];

                if ($sql) {
                    switch ($part['type']) {
                        case 'AND':
                        case 'OR':
                            $statement = $part['type'] . ' ' . $statement;
                            break;
                        default:
                            throw new RuntimeException(
                                \sprintf('Invalid joiner %s', $part['type'])
                            );
                    }
                }

                return \trim($sql . ' ' . $statement);
            },
            ''
        );
    }
733847
public function build($sql='')
    {

        $sql .= "\n";
        if (!empty($this->selectParams[self::SELECT])) {
            $sql = "SELECT ".implode(",\n", $this->selectParams[self::SELECT]);
        }
        if (!empty($this->selectParams[self::FROM])) {
            $sql .= "\nFROM ".implode(",\n", $this->selectParams[self::FROM]);
        }
        if (!empty($this->selectParams[self::JOIN])) {
            $sql .= " ".implode("\n ", $this->selectParams[self::JOIN]);
        }
        if (!empty($this->selectParams[self::WHERE])) {
            $sql .= "\nWHERE (".implode(")\n\t AND (", $this->selectParams[self::WHERE]). ") ";
            $sql .= "\n";
        }
        if (!empty($this->selectParams[self::ORWHERE])) {
            if(!empty($this->selectParams[self::WHERE]))
                $sql .= " AND ";
            else
                $sql .= "\nWHERE ";
            $sql .= " (".implode(" OR ", $this->selectParams[self::ORWHERE]). ") ";
            $sql .= "\n";
        }
        if (!empty($this->selectParams[self::GROUPBY])) {
            $sql .= "\nGROUP BY ".implode(",", $this->selectParams[self::GROUPBY]);
        }
        if (!empty($this->selectParams[self::ORDERBY])) {
            $sql .= "\nORDER BY ".implode(",", $this->selectParams[self::ORDERBY]);
        }

        if (isset($this->selectParams[self::LIMIT])) {
            if ($this->selectParams[self::LIMIT] != 0) {
                $sql .= "\nLIMIT ";
                if (!empty($this->selectParams[self::OFFSET])) {
                    if ($this->selectParams[self::OFFSET] < 0) $this->selectParams[self::OFFSET] = 0;
                    $sql .= $this->selectParams[self::OFFSET] .",";
                }
                $sql .= $this->selectParams[self::LIMIT];
            }
        }

        if($this->forUpdate)
            $sql .= " FOR UPDATE";

        return $sql;
    }
769073
public function ifNotExists(string $sql): string
    {
        $sql = $this->c::mbTrim($sql);

        if (!preg_match('/^CREATE\s+TABLE\b/ui', $sql)) {
            return $sql; // Not applicable.
        }
        if (!preg_match('/^CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\b/ui', $sql)) {
            $sql = preg_replace('/^CREATE\s+TABLE\b/ui', 'CREATE TABLE IF NOT EXISTS', $sql);
        }
        return $sql;
    }
1112690
public function query($sql = null)
    {
        if (!$sql) {
            $sqlWhere = '';
            if (!empty($this->getWhere())) {
                $sqlWhere = $this->getWhere();
            }

            $sqlLimit = '';
            if (!empty($this->getLimit())) {
                $sqlLimit = $this->getLimit();
            }

            $sqlOrder = '';
            $orderBy = $this->getOrderBy();
            if (!empty($orderBy)) {
                $sqlOrder = $orderBy;
            }

            $sqlSelect = "SELECT " . $this->getSelect();
            $sqlFrom = " FROM " . $this->getTable();

            $sql = $sqlSelect . $sqlFrom . $sqlWhere . $sqlOrder . $sqlLimit;
        }
        $this->setLastQuery($sql);

        try {
            $stmt = $this->db->prepare($sql);
            $this->setLastQuery($stmt->queryString, $this->getParameters());
            $stmt->execute($this->getParameters());
        } catch (\PDOException $e) {
            throw new DatabaseException($e->getMessage() . '<br>' . $this->getLastQuery()[0]);
        }

        $this->setResult($stmt);
        $this->clearQuery();

        return $this;
    }
497488
public function charsetCompat(string $sql): string
    {
        $sql = $this->c::mbTrim($sql);

        if (!preg_match('/^CREATE\s+TABLE\b/ui', $sql)) {
            return $sql; // Not applicable.
        }
        $sql = preg_replace('/\bDEFAULT\s+CHARSET\=[%a-z0-9_\-]*/ui', '', $sql);
        $sql = preg_replace('/\bCOLLATE\=[%a-z0-9_\-]*/ui', '', $sql);

        if (!empty($this->wp->charset) && !empty($this->wp->collate)) {
            $sql = preg_replace('/;$/u', ' DEFAULT CHARSET='.$this->wp->charset.' COLLATE='.$this->wp->collate.';', $sql);
        }
        return $sql;
    }
1254602
protected function getStatement($sql)
    {
        if (!isset($this->statements[$sql])) {
            $this->statements[$sql] = $this->adapter->prepare($sql);
        }
        return $this->statements[$sql];
    }
541259
private String trimSlash(final String sql) {
		String trimedSql = sql.trim();
		if (trimedSql.endsWith(PATH_SEPARATOR) && !trimedSql.endsWith("*/")) {
			return StringUtils.stripEnd(trimedSql, PATH_SEPARATOR);
		} else {
			return sql;
		}
	}