{@inheritdoc}

Modifies column declaration order as it differs in Microsoft SQL Server.
185683
public function getColumnDeclarationSQL($name, array $field)
    {
        if (isset($field['columnDefinition'])) {
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
        } else {
            $collation = isset($field['collation']) && $field['collation'] ?
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';

            $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : '';

            $unique = isset($field['unique']) && $field['unique'] ?
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

            $check = isset($field['check']) && $field['check'] ?
                ' ' . $field['check'] : '';

            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
            $columnDef = $typeDecl . $collation . $notnull . $unique . $check;
        }

        return $name . ' ' . $columnDef;
    }
538167
public function sortColumnsByOrder()
    {
        $columns = $this->_columns;
        foreach ($this->getColumnsOrder() as $columnId => $after) {
            if ($after[0] === '-') {
                $before = substr($after, 1);
                $after = null;
            } else {
                $before = null;
            }
            if ($after !== null && isset($columns[$after])) {
                $currentPosition = array_search($columnId, array_keys($columns));
                $value = array_splice($columns, $currentPosition, 1);

                $destPosition = array_search($after, array_keys($columns)) + 1;
                $columns = array_slice($columns, 0, $destPosition) + $value + array_slice($columns, $destPosition);
            } elseif ($before !== null && $columns[$before]) {
                $currentPosition = array_search($columnId, array_keys($columns));
                $value = array_splice($columns, $currentPosition, 1);

                $destPosition = array_search($before, array_keys($columns));
                $columns = array_slice($columns, 0, $destPosition) + $value + array_slice($columns, $destPosition);
            }
        }

        $this->_columns = $columns;

        end($this->_columns);
        $this->_lastColumnId = key($this->_columns);
        return $this;
    }
52184
@Override
	public SqlEntityQuery<E> desc(final String... cols) {
		for (String col : cols) {
			this.sortOrders.add(new SortOrder(col, Order.DESCENDING));
		}
		return this;
	}
874880
public void setSortedColumn(String sortedColumn) throws CmsIllegalArgumentException {

        // check if the parameter is valid
        if ((getMetadata().getColumnDefinition(sortedColumn) == null)
            || !getMetadata().getColumnDefinition(sortedColumn).isSorteable()) {
            return;
        }
        // reset view
        setCurrentPage(1);
        // only reverse order if the column to sort is already sorted
        if (sortedColumn.equals(m_sortedColumn)) {
            if (m_currentSortOrder == CmsListOrderEnum.ORDER_ASCENDING) {
                m_currentSortOrder = CmsListOrderEnum.ORDER_DESCENDING;
            } else {
                m_currentSortOrder = CmsListOrderEnum.ORDER_ASCENDING;
            }
            if (!m_metadata.isSelfManaged()) {
                if (m_filteredItems == null) {
                    m_filteredItems = new ArrayList<CmsListItem>(getAllContent());
                }
                Collections.reverse(m_filteredItems);
            }
            return;
        }
        // sort new column
        m_sortedColumn = sortedColumn;
        m_currentSortOrder = CmsListOrderEnum.ORDER_ASCENDING;
        if (!m_metadata.isSelfManaged()) {
            if (m_filteredItems == null) {
                m_filteredItems = new ArrayList<CmsListItem>(getAllContent());
            }
            I_CmsListItemComparator c = getMetadata().getColumnDefinition(sortedColumn).getListItemComparator();
            Collections.sort(m_filteredItems, c.getComparator(sortedColumn, getWp().getLocale()));
        }
    }
205258
@Override
    public void setGeneratedColumnInfo(int generate, ResultMetaData meta) {

        // can support INSERT_SELECT also
        if (type != StatementTypes.INSERT) {
            return;
        }

        int colIndex = baseTable.getIdentityColumnIndex();

        if (colIndex == -1) {
            return;
        }

        switch (generate) {

            case ResultConstants.RETURN_NO_GENERATED_KEYS :
                return;

            case ResultConstants.RETURN_GENERATED_KEYS_COL_INDEXES :
                int[] columnIndexes = meta.getGeneratedColumnIndexes();

                if (columnIndexes.length != 1) {
                    return;
                }

                if (columnIndexes[0] != colIndex) {
                    return;
                }

            // $FALL-THROUGH$
            case ResultConstants.RETURN_GENERATED_KEYS :
                generatedIndexes = new int[]{ colIndex };
                break;

            case ResultConstants.RETURN_GENERATED_KEYS_COL_NAMES :
                String[] columnNames = meta.getGeneratedColumnNames();

                if (columnNames.length != 1) {
                    return;
                }

                if (baseTable.findColumn(columnNames[0]) != colIndex) {
                    return;
                }

                generatedIndexes = new int[]{ colIndex };
                break;
        }

        generatedResultMetaData =
            ResultMetaData.newResultMetaData(generatedIndexes.length);

        for (int i = 0; i < generatedIndexes.length; i++) {
            ColumnSchema column = baseTable.getColumn(generatedIndexes[i]);

            generatedResultMetaData.columns[i] = column;
        }

        generatedResultMetaData.prepareData();
    }
132509
private void addColumn(StringBuilder builder, Column column) {
		builder.append(column.getColumnName());
		builder.append(" ");
		builder.append(column.getDataType().getType());
		Boolean optional = column.isOptional();
		if (optional != null) {
			builder.append(optional ? " NULL" : " NOT NULL");
		}
		String extraQualifier = column.getExtraQualifier();
		if (extraQualifier != null) {
			builder.append(" ");
			builder.append(extraQualifier);
		}
	}
106636
public function modifyTable()
    {
        $table = $this->getTable();

        if (!$table->containsColumn($this->getParameter('rank_column'))) {
            $table->addColumn(array(
                'name' => $this->getParameter('rank_column'),
                'type' => 'INTEGER'
            ));
        }
        if ($this->useScope() && !$this->hasMultipleScopes() &&
             !$table->containsColumn($this->getParameter('scope_column'))) {
            $table->addColumn(array(
                'name' => $this->getParameter('scope_column'),
                'type' => 'INTEGER'
            ));
        }

        if ($this->useScope()) {
            $scopes = $this->getScopes();
            if (0 === count($scopes)) {
                throw new \InvalidArgumentException(sprintf(
                    'The sortable behavior in `%s` needs a `scope_column` parameter.',
                    $this->getTable()->getName()
                ));
            }
            foreach ($scopes as $scope) {
                $keys = $table->getColumnForeignKeys($scope);
                foreach ($keys as $key) {
                    if ($key->isForeignPrimaryKey() && $key->getOnDelete() == ForeignKey::SETNULL) {
                        $foreignTable = $key->getForeignTable();
                        $relationBehavior = new SortableRelationBehavior();
                        $relationBehavior->addParameter(array('name' => 'foreign_table', 'value' => $table->getName()));
                        $relationBehavior->addParameter(array('name' => 'foreign_scope_column', 'value' => $scope));
                        $relationBehavior->addParameter(array('name' => 'foreign_rank_column', 'value' => $this->getParameter('rank_column')));
                        $foreignTable->addBehavior($relationBehavior);
                    }
                }
            }
        }
    }
228174
public function modifyTable()
    {
        $table = $this->getTable();

        if (!$table->hasColumn($this->getParameter('rank_column'))) {
            $table->addColumn([
                'name' => $this->getParameter('rank_column'),
                'type' => 'INTEGER'
            ]);
        }

        if ($this->useScope()) {
            if (!$this->hasMultipleScopes() && !$table->hasColumn($this->getParameter('scope_column'))) {
                $table->addColumn([
                    'name' => $this->getParameter('scope_column'),
                    'type' => 'INTEGER'
                ]);
            }

            $scopes = $this->getScopes();
            if (0 === count($scopes)) {
                throw new \InvalidArgumentException(sprintf(
                    'The sortable behavior in `%s` needs a `scope_column` parameter.',
                    $this->getTable()->getName()
                ));
            }
        }
    }
73329
public static IntComparator rowComparator(Column<?> column, Sort.Order order) {
        IntComparator rowComparator = column.rowComparator();
        if (order == Sort.Order.DESCEND) {
            return ReversingIntComparator.reverse(rowComparator);
        } else {
            return rowComparator;
        }
    }
986137
private String getOrderByColumn(String[] orderByColumns, Attribute column)
    {

        if (orderByColumns != null)
        {
            for (String orderColumn : orderByColumns)
            {
                String[] orderValue = orderColumn.split("\\s");
                String orderColumnName = orderValue[0].substring(orderValue[0].lastIndexOf('.') + 1);
                String orderColumnValue = orderValue[1];

                if (orderColumnName.equals(((AbstractAttribute) column).getName())
                        || orderColumnName.equals(((AbstractAttribute) column).getJPAColumnName()))
                {
                    return orderColumnValue;
                }
            }
        }
        return null;

    }
293474
public function modifyColumn(
        $name,
        $type = 'text',
        $signed = true,
        $allowNull = true,
        $default = '',
        $comment = '',
        $options = []
    ) {
        if ($name instanceof Column) {
            $column = $name;
            $length = $column->getLength();
            $name = $column->getName();
            $type = $column->getType();
            $signed = $column->getSigned();
            $allowNull = $column->getAllowNull();
            $default = $column->getDefault();
            $position = $column->getPosition();
            $comment = $column->getComment();
            $suffix = $column->getSuffix();
        } else {
            $position = isset($options['position']) ? $options['position'] : null;
            $suffix = isset($options['suffix']) ? $options['suffix'] : null;
        }

        if (!$this->hasColumn($name)) {
            return $this;
        }

        $type = MysqlType::getType($type);
        $length = isset($length) ? $length : MysqlType::getLength($type);
        $length = $length ? '(' . $length . ')' : null;

        $query = MysqlGrammar::modifyColumn(
            $this->getName(),
            $name,
            $type . $length,
            $signed,
            $allowNull,
            $default,
            $position,
            $comment
        );

        // Add suffix
        $query = MysqlGrammar::build($query, $suffix);

        $this->db->setQuery($query)->execute();

        return $this->reset();
    }
43122
protected function _changedColumnsStatement()
    {
        $columns = $this->_sql->getChangedColumns();
        if (empty($columns)) {
            return null;
        }

        return $this->_parseChangedColumns();
    }
437128
public function setColumnOrder(
        $query_name = "",
        $order,
        $insert_before = true
    ) {
        //echo "=========================================<br>";
        //echo "set order $query_name - $order<br>";
        // Changes the display order of the column
        // by resetting display_order_set
        reset($this->display_order_set);

        $ct = count($this->display_order_set["itemno"]);
        $c = &$this->display_order_set;
        for ($i = 0; $i < $ct; $i++) {
            if ($c["column"][$i]->query_name == $query_name) {
                if ($c["itemno"][$i] < $order) {
                    //echo $c["itemno"][$i]." up1  ".$c["column"][$i]->query_name." $i<br>";
                    $c["itemno"][$i] = $order + 1;
                } else {
                    //echo $c["itemno"][$i]." set  ".$c["column"][$i]->query_name." $i<br>";
                    $c["itemno"][$i] = $order;
                }
            } else
            if (($c["itemno"][$i] >= $order && $insert_before)
                ||
                ($c["itemno"][$i] > $order && !$insert_before)) {
                //echo $c["itemno"][$i]." up5  ".$c["column"][$i]->query_name." $i<br>";
                $c["itemno"][$i] += 500;
            }
            //else
            //echo $c["itemno"][$i]." leave ".$c["column"][$i]->query_name." $i<br>";
        }

        // Now resort the list
        $n = array_multisort(
            $this->display_order_set["itemno"], SORT_ASC, SORT_NUMERIC,
            $this->display_order_set["column"]
        );

        for ($i = 0; $i < $ct; $i++) {
            $c["itemno"][$i] = $i + 1;
        }
        foreach ($this->display_order_set["itemno"] as $val) {
            $vv = $val - 1;
            //echo " SET $val ",  $this->display_order_set["column"][$vv]->query_name. " - ".$val."/". $this->display_order_set["itemno"][$vv]."<BR>";
            $ct++;
        }

    }
667404
function orderBy($column, $dir = null) {
		if (null !== $dir && '' !== $dir) {
			$dir = strtoupper($dir);
			if ($dir !== self::ASC && $dir !== self::DESC) {
				throw new RuntimeException("$dir is not a valid sorting direction.");
			}
			$column .= ' ' . $dir;
		}
		$this->orders[] = trim($column);
		return $this;
	}
1313908
private void setUniqueWhere(Where<DataColumnConstraints, Void> where,
			String constraintName, DataColumnConstraintType constraintType,
			String value) throws SQLException {

		where.eq(DataColumnConstraints.COLUMN_CONSTRAINT_NAME, constraintName)
				.and()
				.eq(DataColumnConstraints.COLUMN_CONSTRAINT_TYPE,
						constraintType.getValue());
		if (value == null) {
			where.and().isNull(DataColumnConstraints.COLUMN_VALUE);
		} else {
			where.and().eq(DataColumnConstraints.COLUMN_VALUE, value);
		}

	}
956116
public function alterColumn(
        AbstractTable $table,
        AbstractColumn $initial,
        AbstractColumn $column
    ) {
        if (!$initial instanceof SQLServerColumn || !$column instanceof SQLServerColumn) {
            throw new SchemaException('SQlServer handler can work only with SQLServer columns');
        }

        //In SQLServer we have to drop ALL related indexes and foreign keys while
        //applying type change... yeah...

        $indexesBackup = [];
        $foreignBackup = [];
        foreach ($table->getIndexes() as $index) {
            if (in_array($column->getName(), $index->getColumns())) {
                $indexesBackup[] = $index;
                $this->dropIndex($table, $index);
            }
        }

        foreach ($table->getForeignKeys() as $foreign) {
            if ($column->getName() == $foreign->getColumn()) {
                $foreignBackup[] = $foreign;
                $this->dropForeignKey($table, $foreign);
            }
        }

        //Column will recreate needed constraints
        foreach ($column->getConstraints() as $constraint) {
            $this->dropConstrain($table, $constraint);
        }

        //Rename is separate operation
        if ($column->getName() != $initial->getName()) {
            $this->renameColumn($table, $initial, $column);

            //This call is required to correctly built set of alter operations
            $initial->setName($column->getName());
        }

        foreach ($column->alterOperations($this->driver, $initial) as $operation) {
            $this->run("ALTER TABLE {$this->identify($table)} {$operation}");
        }

        //Restoring indexes and foreign keys
        foreach ($indexesBackup as $index) {
            $this->createIndex($table, $index);
        }

        foreach ($foreignBackup as $foreign) {
            $this->createForeignKey($table, $foreign);
        }
    }
1075863
private void alterCommitIdColumnIfNeeded() {
        ColumnType commitIdColType = getTypeOf(getCommitTableNameWithSchema(), "commit_id");

        if (commitIdColType.precision == 12) {
            logger.info("migrating db schema from JaVers 2.5 to 2.6 ...");
            if (dialect instanceof PostgresDialect) {
                executeSQL("ALTER TABLE " + getCommitTableNameWithSchema() + " ALTER COLUMN commit_id TYPE numeric(22,2)");
            } else if (dialect instanceof H2Dialect) {
                executeSQL("ALTER TABLE " + getCommitTableNameWithSchema() + " ALTER COLUMN commit_id numeric(22,2)");
            } else if (dialect instanceof MysqlDialect) {
                executeSQL("ALTER TABLE " + getCommitTableNameWithSchema() + " MODIFY commit_id numeric(22,2)");
            } else if (dialect instanceof OracleDialect) {
                executeSQL("ALTER TABLE " + getCommitTableNameWithSchema() + " MODIFY commit_id number(22,2)");
            } else if (dialect instanceof MsSqlDialect) {
                executeSQL("drop index jv_commit_commit_id_idx on " + getCommitTableNameWithSchema());
                executeSQL("ALTER TABLE " + getCommitTableNameWithSchema() + " ALTER COLUMN commit_id numeric(22,2)");
                executeSQL("CREATE INDEX jv_commit_commit_id_idx ON " + getCommitTableNameWithSchema() + " (commit_id)");
            } else {
                handleUnsupportedDialect();
            }
        }
    }