Alter a table by creating a new table and copying the old table's data to it.

@param array $alterDef The new definition.
@param array $options An array of options for the migration.
485156
private function alterTableMigrate(array $alterDef, array $options = []) {
        $table = $alterDef['name'];
        $currentDef = $this->fetchTableDef($table);

        // Merge the table definitions if we aren't dropping stuff.
        if (!self::val(Db::OPTION_DROP, $options)) {
            $tableDef = $this->mergeTableDefs($currentDef, $alterDef);
        } else {
            $tableDef = $alterDef['def'];
        }

        // Drop all of the indexes on the current table.
        foreach (self::val('indexes', $currentDef, []) as $indexDef) {
            if (self::val('type', $indexDef, Db::INDEX_IX) === Db::INDEX_IX) {
                $this->dropIndex($indexDef['name']);
            }
        }

        $tmpTable = $table.'_'.time();

        // Rename the current table.
        $this->renameTable($table, $tmpTable);

        // Create the new table.
        $this->createTableDb($tableDef, $options);

        // Figure out the columns that we can insert.
        $columns = array_keys(array_intersect_key($tableDef['columns'], $currentDef['columns']));

        // Build the insert/select statement.
        $sql = 'insert into '.$this->prefixTable($table)."\n".
            $this->bracketList($columns, '`')."\n".
            $this->buildSelect($tmpTable, [], ['columns' => $columns]);

        $this->queryDefine($sql);

        // Drop the temp table.
        $this->dropTable($tmpTable);
    }
283030
public function toFieldDefinition(StorageFieldDefinition $storageDef, FieldDefinition $fieldDef)
    {
        $fieldDef->fieldTypeConstraints->fieldSettings = new FieldSettings(
            array(
                'textRows' => $storageDef->dataInt1,
            )
        );
        $fieldDef->defaultValue->data = null;
        $fieldDef->defaultValue->sortKey = '';
    }
768364
public function alterTable($name, array $options = [])
    {
        $schema = isset($options['schema']) ? new Schema($options['schema']) : null;

        return (new TableApi($name, $schema, $this->manipulation, $this->actions))
            ->alterTable();
    }
381556
def modify_column_if_table_exists(self,
                                      tablename: str,
                                      fieldname: str,
                                      newdef: str) -> Optional[int]:
        """"""
        if not self.table_exists(tablename):
            return None
        sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format(
            t=tablename,
            field=fieldname,
            newdef=newdef
        )
        log.info(sql)
        return self.db_exec_literal(sql)
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);
                    }
                }
            }
        }
    }
239129
public function alterTableAdd($table, $field, $attributes)
    {
        //
        $column = $this->columnDefinition($attributes);

        //
        $sql = "ALTER TABLE `{$table}` ADD COLUMN `{$field}` {$column}";

        //
        return $sql;
    }
1368623
private function alterTable($tableDiff)
    {
        if ($this->getSqlStatements) {
            $this->addSql($this->getPlatform()->getAlterTableSQL($tableDiff));
        } else {
            $this->schemaManager->alterTable($tableDiff);
        }
    }
360227
public function setDiscriminatorColumn($columnDef)
    {
        if ($columnDef !== null) {
            if ( ! isset($columnDef['name'])) {
                throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name);
            }

            if (isset($this->fieldNames[$columnDef['name']])) {
                throw MappingException::duplicateColumnName($this->name, $columnDef['name']);
            }

            if ( ! isset($columnDef['fieldName'])) {
                $columnDef['fieldName'] = $columnDef['name'];
            }

            if ( ! isset($columnDef['type'])) {
                $columnDef['type'] = "string";
            }

            if (in_array($columnDef['type'], array("boolean", "array", "object", "datetime", "time", "date"))) {
                throw MappingException::invalidDiscriminatorColumnType($this->name, $columnDef['type']);
            }

            $this->discriminatorColumn = $columnDef;
        }
    }
684036
protected function copyFieldsFromInterface(InterfaceDefinition $intDef, FieldsAwareDefinitionInterface $fieldsAwareDefinition)
    {
        foreach ($intDef->getFields() as $field) {
            if (!$fieldsAwareDefinition->hasField($field->getName())) {
                $newField = clone $field;
                $newField->addInheritedFrom($intDef->getName());
                $fieldsAwareDefinition->addField($newField);
            } else {
                $fieldsAwareDefinition->getField($field->getName())->addInheritedFrom($intDef->getName());
            }
        }
    }
117611
public function alterTable()
    {
        if ($this->tableExists() === false) {
            return false;
        }

        $dbh    = $this->db();
        $table  = $this->table();
        $fields = $this->getModelFields($this->model());
        $cols   = $this->tableStructure();
        foreach ($fields as $field) {
            $ident = $field->ident();

            if (!array_key_exists($ident, $cols)) {
                // The key does not exist at all.
                $query = 'ALTER TABLE `'.$table.'` ADD '.$field->sql();
                $this->logger->debug($query);
                $dbh->query($query);
            } else {
                // The key exists. Validate.
                $col   = $cols[$ident];
                $alter = true;
                if (strtolower($col['Type']) !== strtolower($field->sqlType())) {
                    $alter = true;
                }

                if ((strtolower($col['Null']) === 'no') && !$field->allowNull()) {
                    $alter = true;
                }

                if ((strtolower($col['Null']) !== 'no') && $field->allowNull()) {
                    $alter = true;
                }

                if ($col['Default'] !== $field->defaultVal()) {
                    $alter = true;
                }

                if ($alter === true) {
                    $query = 'ALTER TABLE `'.$table.'` CHANGE `'.$ident.'` '.$field->sql();
                    $this->logger->debug($query);
                    $dbh->query($query);
                }
            }
        }

        return true;
    }
542204
public function toStorageFieldDefinition(FieldDefinition $fieldDef, StorageFieldDefinition $storageDef)
    {
        $storageDef->dataText1 = $fieldDef->fieldTypeConstraints->fieldSettings['defaultValue'];
    }
435004
public void addColumn(String tableName, String columnName, String columnDef) {
		execSQL("ALTER TABLE " + CoreSQLUtils.quoteWrap(tableName)
				+ " ADD COLUMN " + CoreSQLUtils.quoteWrap(columnName) + " "
				+ columnDef + ";");
	}
1344161
function generateTableInsert( $tableName, $tableDef, $dataEntries, $params )
    {
        return $this->OtherSchema->generateTableInsert( $tableName, $tableDef, $dataEntries, $params );
    }
756244
public function modify($function, $params, $altertnaiveName = NULL) {
        $this->function = $function;
        $this->params = $params;
        $this->alternaiveName = $altertnaiveName;

        return $this;
    }
1004390
public function amend($data = null, $options = [])
    {
        if ($data !== null) {
            $count = $this->count();
            foreach ($data as $i => $value) {
                if (!isset($this[$i])) {
                    $this->setAt($i, $value, $options);
                } else {
                    $this[$i]->amend($value, $options);
                }
            }
            for ($i = count($data); $i < $count; $i++) {
                unset($this[$i]);
            }
        }
        $this->_original = $this->_data;
        $this->_modified = false;
        return $this;
    }
564385
public function getModifyTableDDL(TableDiff $tableDiff)
    {
        $ret = '';

        $toTable = $tableDiff->getToTable();

        // drop indices, foreign keys
        foreach ($tableDiff->getRemovedFks() as $fk) {
            $ret .= $this->getDropForeignKeyDDL($fk);
        }
        foreach ($tableDiff->getModifiedFks() as $fkModification) {
            list($fromFk) = $fkModification;
            $ret .= $this->getDropForeignKeyDDL($fromFk);
        }
        foreach ($tableDiff->getRemovedIndices() as $index) {
            $ret .= $this->getDropIndexDDL($index);
        }
        foreach ($tableDiff->getModifiedIndices() as $indexModification) {
            list($fromIndex) = $indexModification;
            $ret .= $this->getDropIndexDDL($fromIndex);
        }

        $columnChanges = '';

        // alter table structure
        if ($tableDiff->hasModifiedPk()) {
            $columnChanges .= $this->getDropPrimaryKeyDDL($tableDiff->getFromTable());
        }
        foreach ($tableDiff->getRenamedColumns() as $columnRenaming) {
            $columnChanges .= $this->getRenameColumnDDL($columnRenaming[0], $columnRenaming[1]);
        }
        if ($modifiedColumns = $tableDiff->getModifiedColumns()) {
            $columnChanges .= $this->getModifyColumnsDDL($modifiedColumns);
        }
        if ($addedColumns = $tableDiff->getAddedColumns()) {
            $columnChanges .= $this->getAddColumnsDDL($addedColumns);
        }
        foreach ($tableDiff->getRemovedColumns() as $column) {
            $columnChanges .= $this->getRemoveColumnDDL($column);
        }

        // add new indices and foreign keys
        if ($tableDiff->hasModifiedPk()) {
            $columnChanges .= $this->getAddPrimaryKeyDDL($tableDiff->getToTable());
        }

        if ($columnChanges) {
            //merge column changes into one command. This is more compatible especially with PK constraints.

            $changes = explode(';', $columnChanges);
            $columnChanges = [];

            foreach ($changes as $change) {
                if (!trim($change)) continue;
                $isCompatibleCall = preg_match(
                    sprintf('/ALTER TABLE %s (?!RENAME)/', $this->quoteIdentifier($toTable->getName())),
                    $change
                );
                if ($isCompatibleCall) {
                    $columnChanges[] = preg_replace(
                        sprintf('/ALTER TABLE %s /', $this->quoteIdentifier($toTable->getName())),
                        "\n\n  ",
                        trim($change)
                    );
                } else {
                    $ret .= $change.";\n";
                }
            }

            if (0 < count($columnChanges)) {
                $ret .= sprintf("
ALTER TABLE %s%s;
",
                    $this->quoteIdentifier($toTable->getName()), implode(',', $columnChanges));
            }
        }

        // create indices, foreign keys
        foreach ($tableDiff->getModifiedIndices() as $indexModification) {
            list($oldIndex, $toIndex) = $indexModification;
            $ret .= $this->getAddIndexDDL($toIndex);
        }
        foreach ($tableDiff->getAddedIndices() as $index) {
            $ret .= $this->getAddIndexDDL($index);
        }
        foreach ($tableDiff->getModifiedFks() as $fkModification) {
            list(, $toFk) = $fkModification;
            $ret .= $this->getAddForeignKeyDDL($toFk);
        }
        foreach ($tableDiff->getAddedFks() as $fk) {
            $ret .= $this->getAddForeignKeyDDL($fk);
        }

        return $ret;
    }
874083
protected function generateChangeFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition )
    {
        $this->queries[] = "ALTER TABLE '$tableName' CHANGE '$fieldName' " . $this->generateFieldSql( $fieldName, $fieldDefinition );
    }