Render ORDER clause

@param string   $sql SQL query
@return string
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;
    }
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;
    }
959757
protected function getEmptiedQuery(string $sql): string
    {
        // see the reason why in Vision_Store_Adapter_ZendDbSelect::getMetaData
        //$sql = str_replace("('__innerselect'='__innerselect')", '(1=0)', $sql);

        $sql = preg_replace('/(\r\n|\r|\n|\t)+/', ' ', strtolower($sql));
        $sql = trim($sql ?: '');
        $sql = preg_replace('/\s+/', ' ', $sql) ?: '';

        $replace_regexp = "LIMIT[\s]+[\d]+((\s*,\s*\d+)|(\s+OFFSET\s+\d+)){0,1}";

        $search_regexp = "$replace_regexp";
        if (preg_match("/$search_regexp/i", $sql) < 1) {
            // Limit is not already present
            $sql .= ' LIMIT 0';
        } else {
            // replace first if offset exists, then if not
            //preg_match_all("/($search_regexp)/i", $sql, $matches, PREG_PATTERN_ORDER);
            //var_dump($matches);

            $sql = preg_replace("/($replace_regexp)/i", 'LIMIT 0', $sql) ?: '';
        }

        return $sql;
    }
247555
public function orderByRaw($sql, $bindings = array())
	{
		$type = 'raw';

		$this->orders[] = compact('type', 'sql');

		$this->bindings = array_merge($this->bindings, $bindings);

		return $this;
	}
963217
public function query($sql)
    {
        $result = $this->pdo->query($sql);
        $this->executed[] = $sql;
        return $result;
    }
1372555
public static function prepareStmt($sql) {
        self::init();
        $db = self::connect();
        return $db->prepare($sql);
    }
903651
function order($order)
    {
        if (!empty($order))
        {
            self::sql_safe($order);
            $this->order = "order by $order";
        }
        else
        {
            $this->order = '';
        }
    }
1016875
public function orderBy($query = [])
    {
        if (!empty($query))
        {
            $i = 0;

            foreach ($query as $key => $value) {
                $tableName = '';
                $orderBy   = $this->getOrderBy();

                if (strpos($key, '.') === false) {
                    $tableName = $this->table() . '.';
                }

                if ($i>0) {
                    $orderBy .= ', ' . $tableName . $key . ' ' . $value;
                } else {
                    $orderBy .= ' ORDER BY ' . $tableName . $key . ' ' . $value;
                }

                $this->setOrderBy($orderBy);
                $i++;
            }
        }

        return $this;
    }
811619
public static function preparedQuery($sql) {
        self::init();
        if(!empty($exclusions = self::$_ops->getExclusions())) {
            $prepared = self::prepareStmt($sql);
            $inserts = [];
            $types = '';
            foreach($exclusions as $i => $substitute) {
                $types .= $substitute['type'];
                $inserts[] = $substitute['value'];
            }
            return self::executeStmt($prepared, $types, $inserts);
        } else {
            return self::query($sql);
        }
    }
755432
public static function highlight(string $sql): string
	{
		static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|SHOW|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|COMMIT|ROLLBACK|(?:RELEASE\s+|ROLLBACK\s+TO\s+)?SAVEPOINT';
		static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|[RI]?LIKE|REGEXP|TRUE|FALSE';
		$sql = ' ' . $sql . ' ';
		$sql = htmlspecialchars($sql, ENT_IGNORE, 'UTF-8');
		$sql = preg_replace_callback(sprintf('#(/\\*.+?\\*/)|(?<=[\\s,(])(%s)(?=[\\s,)])|(?<=[\\s,(=])(%s)(?=[\\s,)=])#is', $keywords1, $keywords2), function ($matches) {
			if (!empty($matches[1])) { // comment
				return '<em style="color:gray">' . $matches[1] . '</em>';
			}

			if (!empty($matches[2])) { // most important keywords
				return '<strong style="color:#2D44AD">' . $matches[2] . '</strong>';
			}

			if (!empty($matches[3])) { // other keywords
				return '<strong>' . $matches[3] . '</strong>';
			}
		}, $sql);

		return trim((string) $sql);
	}
1297181
protected function buildOrderby() {
		if(!$this->orderBy || !$this->orderBy[0])
			return ['', []];

		$res = [];

		$orderBy = $this->orderBy;
		$orderBySql = $orderBy[0];
		$orderByParameters = $orderBy[1];

		foreach(explode(',', $orderBySql) as $orderbystr) {
			$orderbystr = trim($orderbystr);

			preg_match('/(.*?) (ASC|DESC)?$/i', $orderbystr, $matches);

			if(isset($matches[2])) {
				$direction = $matches[2];
				$column = $matches[1];

				if($this->isIdentifier($column))
					$res[] = $this->replace($column).' '.$direction;
				else
					$res[] = $column.' '.$direction;
			}
			else {
				$column = $orderbystr;

				if($this->isIdentifier($column))
					$res[] = $this->replace($column);
				else
					$res[] = $column;
			}
		}

		$sql = "\n".'ORDER BY '.implode(', ', $res);

		return [$sql, $orderByParameters];
	}
921594
protected static function generalizeSQL( $sql ) {
		// This does the same as the regexp below would do, but in such a way
		// as to avoid crashing php on some large strings.
		# $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );

		$sql = str_replace( "\\\\", '', $sql );
		$sql = str_replace( "\\'", '', $sql );
		$sql = str_replace( "\\\"", '', $sql );
		$sql = preg_replace( "/'.*'/s", "'X'", $sql );
		$sql = preg_replace( '/".*"/s', "'X'", $sql );

		// All newlines, tabs, etc replaced by single space
		$sql = preg_replace( '/\s+/', ' ', $sql );

		// All numbers => N
		$sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
		$sql = preg_replace( '/-?\d+/s', 'N', $sql );

		return $sql;
	}
717365
protected function _renderColumns($sql)
    {
        if (!count($this->_parts[self::COLUMNS])) {
            return null;
        }

        $columns = array();
        foreach ($this->_parts[self::COLUMNS] as $columnEntry) {
            list($correlationName, $column, $alias) = $columnEntry;
            if ($column instanceof Zend_Db_Expr) {
                $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
            } else {
                if ($column == self::SQL_WILDCARD) {
                    $column = new Zend_Db_Expr(self::SQL_WILDCARD);
                    $alias = null;
                }
                if (empty($correlationName)) {
                    $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
                } else {
                    $columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
                }
            }
        }

        return $sql .= ' ' . implode(', ', $columns);
    }
783677
public function sqlOrders()
    {
        if (!$this->hasOrders()) {
            return '';
        }

        $parts = [];
        foreach ($this->orders() as $order) {
            if (!$order instanceof DatabaseOrder) {
                $order = $this->createOrder($order->data());
            }

            $sql = $order->sql();
            if (strlen($sql) > 0) {
                $parts[] = $sql;
            }
        }

        if (empty($parts)) {
            return '';
        }

        return ' ORDER BY '.implode(', ', $parts);
    }
233614
private function formatSql($sql)
    {
        if (isset($this->options['auto_replace']) && !empty(trim($this->options['auto_replace']))) {
            $sql = str_replace($this->options['auto_replace'], $this->getDatabase() .'.'. $this->getTablePrefix(), $sql);
        }
        return $sql;
    }
535366
public function raw($sql)
    {
        $query = new Query\SqlQuery();

        if ($this->pdo) {
            $query->setPDO($this->pdo);
        }

        return $query->raw($sql);
    }
518303
protected function _renderHaving($sql)
    {
        if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
            $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
        }

        return $sql;
    }