{@inheritdoc}

This base implementation does a plain SQL sort by native value as defined by MySQL.
326324
public function sortIds($idList, $strDirection)
    {
        $countries = $this->getCountries();
        $metaModel = $this->getMetaModel();
        $statement = $this->connection->createQueryBuilder()
            ->select($this->getColName() . ' AS country,id')
            ->from($metaModel->getTableName())
            ->where('id IN (:ids)')
            ->setParameter('ids', $idList, Connection::PARAM_INT_ARRAY)
            ->execute();

        $sorted = [];
        while ($lookup = $statement->fetch(\PDO::FETCH_OBJ)) {
            $country            = isset($countries[$lookup->country]) ? $countries[$lookup->country] : $lookup->country;
            $sorted[$country][] = $lookup->id;
        }

        if ($strDirection === 'DESC') {
            \krsort($sorted);
        } else {
            \ksort($sorted);
        }

        return \call_user_func_array('array_merge', $sorted);
    }
150470
public function sort($sort = null)
    {
        if ($sort !== null && ! is_int($sort)) {
            throw new \InvalidArgumentException(
                'Invalid sort type. Sort type must ne integer.',
                E_USER_ERROR
            );
        }

        return $sort === null
            ? sort($this->storedData)
            : sort($this->storedData, $sort);
    }
963236
public function select($cols = null, $where = true, $order = null, $limit = null)
    {
        if ($this->map) {
            $cols = $this->map->cols($cols);
            $where = $this->map->where($where);
            $order = $this->map->order($order);
        }
        if ($cols === null) {
            $cols = true;
        }
        if ($this->fake) {
            $result = $this->fake->select($cols, $where, $order, $limit);
            if ($this->map) {
                return new ArrFetcher($this->map->assoc($result));
            }
            return $result;
        }
        $pattern = 'SELECT ?cols FROM ?t WHERE ?w';
        $data = array($cols, $this->name, $where);
        if ($order !== null) {
            $pattern .= ' ORDER BY ?o';
            $data[] = $order;
        }
        if ($limit !== null) {
            if (is_array($limit)) {
                $offset = isset($limit[1]) ? $limit[1] : 0;
                $limit = $limit[0];
            } else {
                $offset = 0;
            }
            $pattern .= ' LIMIT ?i,?i';
            $data[] = $offset;
            $data[] = $limit;
        }
        $fetcher = $this->db->query($pattern, $data);
        if ($this->map) {
            $data = $fetcher->assoc();
            $data = $this->map->assoc($data);
            $fetcher = new ArrFetcher($data);
        }
        return $fetcher;
    }
164621
public function makeSortable($db_field = null)
    {
        // reverse sorting
        $reverse = false;
        if ($db_field[0] == '-') {
            $reverse = true;
            $db_field = substr($db_field, 1);
        }

        // used db field
        if (!$db_field) {
            $db_field = $this->last_column;
        }

        switch ((string) $this->sortby) {

            // we are already sorting by this column
            case $db_field:
                $info = array('1', $reverse ? 0 : ('-'.$db_field));
                $this->sortby_db = $db_field;
                break;

            // We are sorted reverse by this column
            case '-'.$db_field:
                $info = array('2', $reverse ? $db_field : '0');
                $this->sortby_db = '-'.$db_field;
                break;

            // we are not sorted by this column
            default:
                $info = array('0', $reverse ? ('-'.$db_field) : $db_field);
        }

        $this->columns[$db_field]['sortable'] = $info;

        return $this;
    }
558175
static function createSortingSQLStrings( $sortList, $treeTableName = 'ezcontentobject_tree', $allowCustomColumns = false )
    {
        $sortingInfo = array( 'sortCount'           => 0,
                              'sortingFields'       => " path_string ASC",
                              'attributeJoinCount'  => 0,
                              'attributeFromSQL'    => "",
                              'attributeTargetSQL'  => "",
                              'attributeWhereSQL'   => "" );

        if ( $sortList and is_array( $sortList ) and count( $sortList ) > 0 )
        {
            if ( count( $sortList ) > 1 and !is_array( $sortList[0] ) )
            {
                $sortList = array( $sortList );
            }

            $sortingFields      = '';
            $sortCount          = 0;
            $attributeJoinCount = 0;
            $stateJoinCount     = 0;
            $attributeFromSQL   = "";
            $attributeWhereSQL  = "";
            $datatypeSortingTargetSQL = "";

            foreach ( $sortList as $sortBy )
            {
                if ( is_array( $sortBy ) and count( $sortBy ) > 0 )
                {
                    if ( $sortCount > 0 )
                    {
                        $sortingFields .= ', ';
                    }

                    $sortField = $sortBy[0];
                    switch ( $sortField )
                    {
                        case 'path':
                        {
                            $sortingFields .= 'path_string';
                        } break;
                        case 'path_string':
                        {
                            $sortingFields .= 'path_identification_string';
                        } break;
                        case 'published':
                        {
                            $sortingFields .= 'ezcontentobject.published';
                        } break;
                        case 'modified':
                        {
                            $sortingFields .= 'ezcontentobject.modified';
                        } break;
                        case 'modified_subnode':
                        {
                            $sortingFields .= 'modified_subnode';
                        } break;
                        case 'section':
                        {
                            $sortingFields .= 'ezcontentobject.section_id';
                        } break;
                        case 'node_id':
                        {
                            $sortingFields .= $treeTableName . '.node_id';
                        } break;
                        case 'contentobject_id':
                        {
                            $sortingFields .= 'ezcontentobject.id';
                        } break;
                        case 'depth':
                        {
                            $sortingFields .= 'depth';
                        } break;
                        case 'class_identifier':
                        {
                            $sortingFields .= 'ezcontentclass.identifier';
                        } break;
                        case 'class_name':
                        {
                            $classNameFilter = eZContentClassName::sqlFilter();
                            $sortingFields .= 'contentclass_name';
                            $datatypeSortingTargetSQL .= ", $classNameFilter[nameField] AS contentclass_name";
                            $attributeFromSQL .= " INNER JOIN $classNameFilter[from] ON ($classNameFilter[where])";
                        } break;
                        case 'priority':
                        {
                            $sortingFields .= $treeTableName . '.priority';
                        } break;
                        case 'visibility':
                        {
                            $sortingFields .= $treeTableName . '.is_invisible';
                        } break;
                        case 'name':
                        {
                            $sortingFields .= 'ezcontentobject_name.name';
                        } break;
                        case 'attribute':
                        {
                            $classAttributeID = $sortBy[2];
                            if ( !is_numeric( $classAttributeID ) )
                                $classAttributeID = eZContentObjectTreeNode::classAttributeIDByIdentifier( $classAttributeID );


                            $contentAttributeTableAlias = "a$attributeJoinCount";
                            $datatypeFromSQL = "ezcontentobject_attribute $contentAttributeTableAlias";
                            $datatypeWhereSQL = "
                                   $contentAttributeTableAlias.contentobject_id = ezcontentobject.id AND
                                   $contentAttributeTableAlias.contentclassattribute_id = $classAttributeID AND
                                   $contentAttributeTableAlias.version = ezcontentobject.current_version AND";
                            $datatypeWhereSQL .= eZContentLanguage::sqlFilter( $contentAttributeTableAlias, 'ezcontentobject' );

                            $dataType = eZDataType::create( eZContentObjectTreeNode::dataTypeByClassAttributeID( $classAttributeID ) );
                            if( is_object( $dataType ) && $dataType->customSorting() )
                            {
                                $params = array();
                                $params['contentobject_attr_id'] = "$contentAttributeTableAlias.id";
                                $params['contentobject_attr_version'] = "$contentAttributeTableAlias.version";
                                $params['table_alias_suffix'] = "$attributeJoinCount";

                                $sql = $dataType->customSortingSQL( $params );

                                $datatypeFromSQL .= " INNER JOIN $sql[from] ON ($sql[where])";
                                $datatypeSortingFieldSQL = $sql['sorting_field'];
                                $datatypeSortingTargetSQL .= ', ' . $sql['sorting_field'];
                            }
                            else
                            {
                                // Look up datatype for standard sorting
                                $sortKeyType = eZContentObjectTreeNode::sortKeyByClassAttributeID( $classAttributeID );
                                switch ( $sortKeyType )
                                {
                                    case 'string':
                                        {
                                            $sortKey = 'sort_key_string';
                                        } break;

                                    case 'int':
                                    default:
                                        {
                                            $sortKey = 'sort_key_int';
                                        } break;
                                }

                                $datatypeSortingFieldSQL = "a$attributeJoinCount.$sortKey";
                                $datatypeSortingTargetSQL .= ', ' . $datatypeSortingFieldSQL;
                            }

                            $sortingFields .= "$datatypeSortingFieldSQL";
                            $attributeFromSQL .= " INNER JOIN $datatypeFromSQL ON ($datatypeWhereSQL)";

                            $attributeJoinCount++;
                        }break;

                        case 'state':
                        {
                            $stateGroupID = $sortBy[2];
                            if ( !is_numeric( $stateGroupID ) )
                            {
                                $stateGroup = eZContentObjectStateGroup::fetchByIdentifier( $stateGroupID );
                                if ( $stateGroup )
                                {
                                    $stateGroupID = $stateGroup->attribute( 'id' );
                                }
                                else
                                {
                                    eZDebug::writeError( "Unknown content object state group '$stateGroupID'" );
                                    continue 2;
                                }
                            }

                            $stateAlias = "s$stateJoinCount";
                            $stateLinkAlias = "sl$stateJoinCount";
                            $sortingFields .= "$stateAlias.priority";
                            $datatypeSortingTargetSQL .= ", $stateAlias.priority";
                            $attributeFromSQL .=
                                " INNER JOIN ezcobj_state $stateAlias ON ($stateAlias.group_id = $stateGroupID)" .
                                " INNER JOIN ezcobj_state_link $stateLinkAlias" .
                                "     ON ($stateLinkAlias.contentobject_id = ezcontentobject.id AND $stateLinkAlias.contentobject_state_id = $stateAlias.id)";
                        } break;

                        default:
                        {
                            if ( $allowCustomColumns )
                            {
                                $sortingFields .= $sortField;
                            }
                            else
                            {
                                eZDebug::writeWarning( 'Unknown sort field: ' . $sortField, __METHOD__ );
                                continue 2;
                            }
                        }
                    }
                    $sortOrder = true; // true is ascending
                    if ( isset( $sortBy[1] ) )
                        $sortOrder = $sortBy[1];
                    $sortingFields .= $sortOrder ? " ASC" : " DESC";
                    ++$sortCount;
                }
            }

            $sortingInfo['sortCount']           = $sortCount;
            $sortingInfo['sortingFields']       = $sortingFields;
            $sortingInfo['attributeTargetSQL'] = $datatypeSortingTargetSQL;
            $sortingInfo['attributeJoinCount']  = $attributeJoinCount;
            $sortingInfo['attributeFromSQL']    = $attributeFromSQL;
            $sortingInfo['attributeWhereSQL']   = $attributeWhereSQL;
        }
        else if ( $sortList === array() )
        {
            $sortingInfo['sortingFields'] = '';
        }

        return $sortingInfo;
    }
240605
protected function _prepareOrderByQuery($query = null)
    {
        // sorting
        $sortFields = $this->getListSorting();

        if (is_array($sortFields) && count($sortFields)) {
            // only add order by at full sql not for count(*)
            $query .= ' order by ';
            $addSeparator = false;

            $listItem = $this->getItemListBaseObject();
            $languageId = $listItem->isMultilang() ? $listItem->getLanguage() : \OxidEsales\Eshop\Core\Registry::getLang()->getBaseLanguage();

            $descending = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('adminorder');
            $descending = $descending !== null ? (bool)$descending : $this->_blDesc;

            foreach ($sortFields as $table => $fieldData) {
                $table = $table ? (getViewName($table, $languageId) . '.') : '';
                foreach ($fieldData as $column => $sortDirectory) {
                    $field = $table . $column;

                    //add table name to column name if no table name found attached to column name
                    $query .= ((($addSeparator) ? ', ' : '')) . \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteIdentifier($field);

                    //V oxActive field search always DESC
                    if ($descending || $column == "oxactive" || strcasecmp($sortDirectory, 'desc') == 0) {
                        $query .= ' desc ';
                    }

                    $addSeparator = true;
                }
            }
        }

        return $query;
    }
135096
final protected function build_query(){
        $select = empty($this->_select) ? $this->default_select() : implode(', ', $this->_select);
        $calc = $this->_calc_rows ? ' SQL_CALC_FOUND_ROWS' : '';
        $distinct = $this->_distinct ? sprintf('DISTINCT(%s)', $this->escape_column_name($this->_distinct)) : '';
        $from = empty($this->_from) ? $this->table : $this->_from;
        // Build query
        $sql = <<<SQL
          SELECT{$calc} {$distinct} {$select} FROM {$from}
SQL;
        // Add join
        $join = [];
        if( !empty($this->_join) ){
            $join = $this->_join;
        }else{
            $default_join = $this->default_join();
            if( !empty($default_join) ){
                $join = $default_join;
            }
        }
        foreach($join as list($table, $on, $method)){
            $method = 'INNER' === strtoupper($method) ? 'INNER' : 'LEFT';
            $sql .= <<<SQL
            {$method} JOIN {$table}
            ON {$on}
SQL;
        }
        // Add where
        if( !empty($this->_wheres) ){
            $where_clause = $this->build_where($this->_wheres);
            $sql .= <<<SQL
            WHERE {$where_clause}
SQL;
        }
        // Add group by
        if( !empty($this->_group_by) ){
            $group_by = implode(', ', $this->_group_by);
            $sql .= <<<SQL
            GROUP BY {$group_by}
SQL;
        }
        // Add order by
        if( !empty($this->_order_by) ){
            $order_by = implode(', ', $this->_order_by);
            $sql .= <<<SQL
            ORDER BY {$order_by}
SQL;
        }
        // Add limit
        if( !empty($this->_limit) ){
            list($per_page, $offset) = $this->_limit;
            $limit = <<<SQL
            LIMIT %d, %d
SQL;
            $sql .= sprintf($limit, $offset, $per_page);
        }
        return $sql;
    }
217561
protected function sql($sql, array $orderBys = array(), $start = null, $limit = null)
    {
        if (!empty($orderBys)) {
            $sql .= ' ORDER BY ';
            $orderByStr = $separate = '';
            $declares = $this->declares();
            foreach ($orderBys as $order => $sort) {
                $this->checkOrderBy($order, $sort, $declares['orderbys']);
                $orderByStr .= sprintf('%s %s %s', $separate, $order, $sort);
                $separate = ',';
            }

            $sql .= $orderByStr;
        }

        if (null !== $start && !is_numeric($start)) {
            throw $this->createDaoException('SQL Limit must can be cast to integer');
        }

        if (null !== $limit && !is_numeric($limit)) {
            throw $this->createDaoException('SQL Limit must can be cast to integer');
        }

        $onlySetStart = null !== $start && null === $limit;
        $onlySetLimit = null !== $limit && null === $start;

        if ($onlySetStart || $onlySetLimit) {
            throw $this->createDaoException('start and limit need to be assigned');
        }

        if (is_numeric($start) && is_numeric($limit)) {
            $sql .= sprintf(' LIMIT %d, %d', $start, $limit);
        }

        return $sql;
    }
527289
static public function filterByLanguage(common_persistence_SqlPersistence $persistence, $dataset, $langColname, $selectedLanguage, $defaultLanguage)
    {
        $returnValue = array();
        
        $result = self::sortByLanguage($persistence, $dataset, $langColname, $selectedLanguage, $defaultLanguage);
        $returnValue = self::getFirstLanguage($result);
        
        return $returnValue;
    }
1062602
public function sqlFrom()
    {
        if (!$this->hasTable()) {
            throw new UnexpectedValueException(
                'Can not get SQL FROM clause. No table defined.'
            );
        }

        $table = $this->table();
        return '`'.$table.'` AS `'.self::DEFAULT_TABLE_ALIAS.'`';
    }
816399
public function orderBy($column = '', $sort = 'desc')
    {
        $column=self::sanitize($column);
        $sort=strtoupper(self::sanitize($sort));

        /*check if the sort method passed is valid */
        if (!(hash_equals('DESC',$sort) || hash_equals('ASC',$sort))){
            static::$response["status"] = "error";
            static::$response["response"] = "The sort order in order by clause is invalid";
            static::$response['code'] = 6050;
            return static::terminate(static::$response);
        }

        if ($this->order == null) {
            $this->order = " ORDER BY $column $sort";
        } else {
            $this->order .= ", $column $sort";
        }
        return $this;
    }
903651
function order($order)
    {
        if (!empty($order))
        {
            self::sql_safe($order);
            $this->order = "order by $order";
        }
        else
        {
            $this->order = '';
        }
    }
1227769
protected function setSort()
    {
        $this->sort = Input::get($this->sortName, []);
        if (!is_array($this->sort)) {
            return;
        }

        if (empty($this->sort['column']) || empty($this->sort['type'])) {
            return;
        }

        if (str_contains($this->sort['column'], '.')) {
            $this->setRelationSort($this->sort['column']);
        } else {
            $this->resetOrderBy();

            $this->queries->push([
                'method' => 'orderBy',
                'arguments' => [$this->sort['column'], $this->sort['type']],
            ]);
        }
    }
960981
protected function order_sql(?string $fieldname = null, string $order = 'ASC', ?string $tablealias = null) {

        if (!$tablealias) {
            $tablealias = 'analysable';
        }

        if ($order != 'ASC' && $order != 'DESC') {
            throw new \coding_exception('The order can only be ASC or DESC');
        }

        $ordersql = ' ORDER BY (CASE WHEN aua.timeanalysed IS NULL THEN 0 ELSE aua.timeanalysed END) ASC';
        if ($fieldname) {
            $ordersql .= ', ' . $tablealias . '.' . $fieldname .' ' . $order;
        }

        return $ordersql;
    }
151142
public function getSort($format = 'native')
    {
        if (!is_null($this->suppliedSort)) {
            $nativeSort = $this->suppliedSort;
        } elseif (!is_null($this->entitySort)) {
            $nativeSort = $this->entitySort;
        } else {
            // no explicit sort supplied, return false
            return false;
        }

        // convert to sql dialect if asked
        if ($format == 'sql') {
            // first_name,-last_name
            $sortFields = explode(',', $nativeSort);
            $parsedSorts = array(); // the final Phalcon friendly sort array

            foreach ($sortFields as $order) {
                if (substr($order, 0, 1) == '-') {
                    $subOrder = substr($order, 1);
                    if (!empty($subOrder)) {
                        $parsedSorts[] = $subOrder . " DESC";
                    }
                } else {
                    $parsedSorts[] = $order;
                }
            }
            $nativeSort = implode(',', $parsedSorts);
        }

        return $nativeSort;
    }
315860
public function mysqlReOrder()
    {
        $group = $this->getGroup();

        $res = $this->query("SELECT `".$this->row_id."`
                             FROM `".$this->table."`
                             ".$group."
                             ORDER BY `".$this->cell."`
                            ");
        $query = [];
        $i = $this->reorder;
        while($row = $res->fetch_assoc())
            $query[] = "UPDATE `".$this->table."` SET `".$this->cell."` = ".$i++." WHERE `".$this->row_id."`= ".$row[$this->row_id];

        return ($this->query($query)) ? 9 : 10;
    }
603283
function _query($sql,$iarr=false)
	{

		if (!$this->autoCommit && $this->_transactionID) {
			$conn = $this->_transactionID;
			$docommit = false;
		} else {
			$conn = $this->_connectionID;
			$docommit = true;
		}
		if (is_array($sql)) {
			$fn = 'ibase_execute';
			$sql = $sql[1];
			if (is_array($iarr)) {
				if  (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
					if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
					$fnarr = array_merge( array($sql) , $iarr);
					$ret = call_user_func_array($fn,$fnarr);
				} else {
					switch(sizeof($iarr)) {
					case 1: $ret = $fn($sql,$iarr[0]); break;
					case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
					case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
					case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
					case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
					case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
					case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
					default: ADOConnection::outp( "Too many parameters to ibase query $sql");
					case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
					}
				}
			} else $ret = $fn($sql);
		} else {
			$fn = 'ibase_query';

			if (is_array($iarr)) {
				if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
					if (sizeof($iarr) == 0) $iarr[0] = ''; // PHP5 compat hack
					$fnarr = array_merge( array($conn,$sql) , $iarr);
					$ret = call_user_func_array($fn,$fnarr);
				} else {
					switch(sizeof($iarr)) {
					case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
					case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
					case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
					case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
					case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
					case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
					case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
					default: ADOConnection::outp( "Too many parameters to ibase query $sql");
					case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
					}
				}
			} else $ret = $fn($conn,$sql);
		}
		if ($docommit && $ret === true) {
			ibase_commit($this->_connectionID);
		}

		$this->_handleerror();
		return $ret;
	}