Look for table definition modifications and apply to real table

@param $tableName
@param $definition
@param $foreignKeys
@return array
@throws Exception
511693
protected function _morphTable($tableName, $definition, $foreignKeys, $dbAdapter)
    {
        $ignoreDropForeignKeys = array();
        /** @var \Phalcon\Db\Adapter $connection */
        $connection = $this->getDI()->get($dbAdapter);
        if ($dbAdapter === 'dbCassandra') {
            $schema = $connection->getDescriptor()['keyspace'];
        } elseif ($dbAdapter === 'dbPostgresql') {
            $schema = $connection->getDescriptor()['schema'];
        } else {
            $schema = $connection->getDescriptor()['dbname'];
        }

        $sql = array();
        $tableExists = $connection->tableExists($tableName, $schema);
        if (isset($definition['columns'])) {

            if (count($definition['columns']) == 0) {
                throw new Exception('Table must have at least one column');
            }

            $fields = array();
            foreach ($definition['columns'] as $tableColumn) {
                if (!is_object($tableColumn)) {
                    throw new Exception('Table must have at least one column');
                }
                $fields[$tableColumn->getName()] = $tableColumn;
            }

            if ($tableExists) {

                $localFields = array();
                $description = $connection->describeColumns($tableName, $schema);
                foreach ($description as $field) {
                    $localFields[$field->getName()] = $field;
                }

                foreach ($fields as $fieldName => $tableColumn) {
                    if ($dbAdapter === 'dbPostgresql') {
                        $schema = $connection->getDescriptor()['schema'];
                    }


                    if (!isset($localFields[$fieldName])) {
                        /**
                         * ADD COLUMN
                         */
                        $rawSql = $connection->getDialect()->addColumn($tableName, $tableColumn->getSchemaName(), $tableColumn);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    } else {

                        /**
                         * ALTER TABLE
                         */
                        $changed = false;

                        if ($localFields[$fieldName]->getType() != $tableColumn->getType()) {
                            // If we are on MySQL DB, and the current column in DB is INT(1)
                            // and current annotation is "boolean", we don't notify change
                            // because when we save a boolean column in MySQL it's converted to INT(1)
                            // It prevents executing useless DB updates on each run
                            if ($dbAdapter !== 'dbMysql' || $localFields[$fieldName]->getType() !== \Phalcon\Db\Column::TYPE_INTEGER
                                || $localFields[$fieldName]->getSize() !== 1 || $tableColumn->getType() !== \Phalcon\Db\Column::TYPE_BOOLEAN
                            ) {
                                $changed = true;
                            }
                        }

                        if ($tableColumn->isNotNull() != $localFields[$fieldName]->isNotNull()) {
                            $changed = true;
                        }

                        if ($tableColumn->getSize() && $tableColumn->getSize() != $localFields[$fieldName]->getSize()) {
                            $changed = true;
                        }

                        if ($changed == true) {
                            $existingForeignKeys = [];

                            // We check if there is a foreign key constraint
                            if ($dbAdapter === 'dbMysql') {
                                $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $connection->getDescriptor()['dbname'] . "' AND REFERENCED_TABLE_NAME = '" . $tableName . "' AND REFERENCED_COLUMN_NAME = '" . $tableColumn->getName() . "'");
                                foreach ($results->fetchAll() as $r) {
                                    $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $r['CONSTRAINT_NAME'] . '" AND CONSTRAINT_SCHEMA ="' . $r['TABLE_SCHEMA'] . '"');
                                    $rules = $rules->fetch();
                                    $r['UPDATE_RULE'] = $rules['UPDATE_RULE'];
                                    $r['DELETE_RULE'] = $rules['DELETE_RULE'];

                                    /**
                                     * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN
                                     */
                                    $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                    $existingForeignKeys[] = $r;
                                }
                            } elseif ($dbAdapter === 'dbPostgresql') {
                                $sqlconstraint = $this->getPGSQLConstraint($tableName, $tableColumn->getName());
                                $results = $connection->query($sqlconstraint);
                                foreach ($results->fetchAll() as $r) {

                                    $r['UPDATE_RULE'] = $r['on_update'];
                                    $r['DELETE_RULE'] = $r['on_delete'];
                                    $r['TABLE_NAME'] = $r['table_name'];
                                    $r['TABLE_SCHEMA'] = $r['constraint_schema'];
                                    $r['CONSTRAINT_NAME'] = $r['constraint_name'];
                                    $r['REFERENCED_TABLE_SCHEMA'] = $r['constraint_schema'];
                                    $r['REFERENCED_TABLE_NAME'] = $r['references_table'];
                                    $r['REFERENCED_COLUMN_NAME'] = $r['references_field'];
                                    $r['COLUMN_NAME'] = $r['column_name'];

                                    /**
                                     * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN
                                     */
                                    $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                    $existingForeignKeys[] = $r;
                                }
                            }

                            /**
                             * ALTER TABLE
                             */
                            if ($dbAdapter === 'dbPostgresql') {
                                $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]);
                            } else {
                                $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn);
                            }
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';

                            if ($existingForeignKeys) {
                                foreach ($existingForeignKeys as $r) {
                                    /**
                                     * ADD FOREIGN KEY AFTER DROP ONE (TO CHANGE IT)
                                     */
                                    $rawSql = $connection->getDialect()->addForeignKey(
                                        $r['TABLE_NAME'],
                                        $r['TABLE_SCHEMA'],
                                        new Reference(
                                            $r['CONSTRAINT_NAME'],
                                            array(
                                                "referencedSchema" => $r['REFERENCED_TABLE_SCHEMA'],
                                                "referencedTable" => $r['REFERENCED_TABLE_NAME'],
                                                "columns" => array($r['COLUMN_NAME']),
                                                "referencedColumns" => array($r['REFERENCED_COLUMN_NAME']),
                                                'onUpdate' => $r['UPDATE_RULE'],
                                                'onDelete' => $r['DELETE_RULE']
                                            )
                                        ));
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                }
                            }
                        }
                    }
                }

                /**
                 * DROP COLUMN (and foreign key)
                 */
                foreach ($localFields as $fieldName => $localField) {
                    if (!isset($fields[$fieldName])) {
                        if ($dbAdapter === 'dbMysql') {
                            // We check if there is a foreign key constraint
                            $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $schema . "' AND TABLE_NAME = '" . $tableName . "' AND COLUMN_NAME = '" . $fieldName . "'");
                            foreach ($results->fetchAll() as $r) {
                                $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME'];
                                $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        } elseif ($dbAdapter === 'dbPostgresql') {
                            $sqlconstraint = $this->getPGSQLConstraint($tableName, $fieldName);
                            $results = $connection->query($sqlconstraint);
                            foreach ($results->fetchAll() as $r) {
                                $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME'];
                                $rawSql = $connection->getDialect()->dropForeignKey($r['table_name'], $r['constraint_schema'], $r['constraint_name']);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        }
                        $rawSql = $connection->getDialect()->dropColumn($tableName, $schema, $fieldName);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    }
                }
            } else {
                /**
                 * CREATE TABLE IF NOT EXISTS
                 */
                $rawSql = $connection->getDialect()->createTable($tableName, $schema, $definition);
                if ($dbAdapter === 'dbPostgresql') {
                    $sqlInstructions = explode(';', $rawSql);
                    foreach ($sqlInstructions as $instruction) {
                        if ($instruction !== "" && strpos($instruction, '_pkey" ON') === false) {
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $instruction . '\');';
                        }
                    }
                } else {
                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                }

            }
        }

        /**
         * DROP FOREIGN KEY
         */
        if ($tableExists === true && ($dbAdapter === 'dbMysql' || $dbAdapter === 'dbPostgresql')) {
            $actualReferences = $connection->describeReferences($tableName, $schema);
            /* @var $actualReference \Phalcon\Db\Reference */
            foreach ($actualReferences as $actualReference) {
                $foreignKeyExists = false;

                for ($i = count($foreignKeys) - 1; $i >= 0; --$i) {
                    if ($dbAdapter === 'dbMysql') {
                        $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $actualReference->getName() . '" AND CONSTRAINT_SCHEMA ="' . $actualReference->getReferencedSchema() . '"');
                        $rules = $rules->fetch();

                        if ($tableName === $foreignKeys[$i]['table']
                            && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable']
                            && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0
                            && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0
                            // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnUpdate() === $foreignKeys[$i]['action']
                            && $rules['UPDATE_RULE'] === $foreignKeys[$i]['action']
                            // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnDelete() === $foreignKeys[$i]['action']) {
                            && $rules['DELETE_RULE'] === $foreignKeys[$i]['action']
                        ) {
                            $foreignKeyExists = true;
                            array_splice($foreignKeys, $i, 1);
                            break;
                        }
                    } else {
                        if ($tableName === $foreignKeys[$i]['table']
                            && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable']
                            && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0
                            && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0
                        ) {
                            $foreignKeyExists = true;
                            array_splice($foreignKeys, $i, 1);
                            break;
                        }
                    }
                }

                if (!$foreignKeyExists && !in_array($actualReference->getName(), $ignoreDropForeignKeys)) {
                    $rawSql = $connection->getDialect()->dropForeignKey(
                        $tableName,
                        $actualReference->getReferencedSchema(),
                        $actualReference->getName()
                    );
                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                }
            }
        }

        /**
         * ADD FOREIGN KEY
         */
        if ($foreignKeys) {
            foreach ($foreignKeys as $foreignKey) {
                $rawSql = $connection->getDialect()->addForeignKey(
                    $tableName,
                    $connection->getDescriptor()['dbname'],
                    new Reference(
                        $foreignKey['name'],
                        array(
                            "referencedSchema" => $connection->getDescriptor()['dbname'],
                            "referencedTable" => $foreignKey['referencedTable'],
                            "columns" => $foreignKey['fields'],
                            "referencedColumns" => $foreignKey['referencedFields'],
                            'onUpdate' => $foreignKey['action'],
                            'onDelete' => $foreignKey['action']
                        )
                    ));
                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
            }
        }

        /**
         * INDEXES
         */
        if (isset($definition['indexes'])) {
            if ($tableExists == true) {

                $indexes = array();
                foreach ($definition['indexes'] as $tableIndex) {
                    $indexes[$tableIndex->getName()] = $tableIndex;
                }

                if ($dbAdapter === 'dbPostgresql') {
                    $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]);
                }

                $localIndexes = array();
                $actualIndexes = $connection->describeIndexes($tableName, $schema);
                foreach ($actualIndexes as $actualIndex) {
                    $deleted = true;

                    foreach ($definition['indexes'] as $tableIndex) {
                        // hack for encoging problem
                        $tableIndexName = $tableIndex->getName();
                        $actualIndexName = $actualIndex->getName();
                        if ($tableIndexName === $actualIndexName) {
                            $deleted = false;
                            $localIndexes[$actualIndex->getName()] = $actualIndex->getColumns();
                            break;
                        } elseif (substr($actualIndex->getName(), 0, 3) !== 'IDX' && ($dbAdapter !== 'dbCassandra') && ($dbAdapter !== 'dbPostgresql')) {
                            $deleted = false;
                            break;
                        }
                    }


                    if ($deleted) {
                        $rawSql = $connection->getDialect()->dropIndex($tableName, $tableColumn->getSchemaName(), $actualIndexName);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    }
                }

                foreach ($definition['indexes'] as $tableIndex) {
                    $tableIndexName = $tableIndex->getName();
                    if (!isset($localIndexes[$tableIndexName])) {
                        if ($tableIndexName == 'PRIMARY') {
                            $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex);
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                        } else {
                            $rawSql = $connection->getDialect()->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex);
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                        }
                    } else {
                        $changed = false;
                        if (count($tableIndex->getColumns()) != count($localIndexes[$tableIndexName])) {
                            $changed = true;
                        } else {
                            foreach ($tableIndex->getColumns() as $columnName) {
                                if (!in_array($columnName, $localIndexes[$tableIndexName])) {
                                    $changed = true;
                                    break;
                                }
                            }
                        }
                        if ($changed == true) {
                            if ($tableIndex->getName() == 'PRIMARY') {
                                $rawSql = $connection->getDialect()->dropPrimaryKey($tableName, $tableColumn->getSchemaName());
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';

                                $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        }
                    }
                }
            }

        }

        return $sql;

    }
813858
private function getChangedForeignKeys($tableName, TableDiff $diff)
    {
        foreach ($diff->changedForeignKeys as $foreignKey) {
            $this->addForeignKeysMessage($tableName, $foreignKey, 'changed foreign key on `%s`, it is now related to `%s.%s`');
        }
    }
1074170
private function appendForeignKeyNode(ForeignKey $foreignKey, \DOMNode $parentNode)
    {
        $foreignKeyNode = $parentNode->appendChild($this->document->createElement('foreign-key'));
        $foreignKeyNode->setAttribute('foreignTable', $foreignKey->getForeignTableCommonName());

        if ($schema = $foreignKey->getForeignSchemaName()) {
            $foreignKeyNode->setAttribute('foreignSchema', $schema);
        }

        $foreignKeyNode->setAttribute('name', $foreignKey->getName());

        if ($phpName = $foreignKey->getPhpName()) {
            $foreignKeyNode->setAttribute('phpName', $phpName);
        }

        if ($refPhpName = $foreignKey->getRefPhpName()) {
            $foreignKeyNode->setAttribute('refPhpName', $refPhpName);
        }

        if ($defaultJoin = $foreignKey->getDefaultJoin()) {
            $foreignKeyNode->setAttribute('defaultJoin', $defaultJoin);
        }

        if ($onDeleteBehavior = $foreignKey->getOnDelete()) {
            $foreignKeyNode->setAttribute('onDelete', $onDeleteBehavior);
        }

        if ($onUpdateBehavior = $foreignKey->getOnUpdate()) {
            $foreignKeyNode->setAttribute('onUpdate', $onUpdateBehavior);
        }

        for ($i = 0, $size = count($foreignKey->getLocalColumns()); $i < $size; $i++) {
            $refNode = $foreignKeyNode->appendChild($this->document->createElement('reference'));
            $refNode->setAttribute('local', $foreignKey->getLocalColumnName($i));
            $refNode->setAttribute('foreign', $foreignKey->getForeignColumnName($i));
        }

        foreach ($foreignKey->getVendorInformation() as $vendorInformation) {
            $this->appendVendorInformationNode($vendorInformation, $foreignKeyNode);
        }
    }
218341
public function createForeignKey($foreignKey, $table)
    {
        $changeSetElt = $this->createChangeSet('create-foreign-keys-' . $table->getName());
        $addForeignKeyConstraintElt = $this->document->createElement('addForeignKeyConstraint');

        $this->fillForeignKeyAttributes($addForeignKeyConstraintElt, $foreignKey, $table);

        $changeSetElt->appendChild($addForeignKeyConstraintElt);
        $this->root->appendChild($changeSetElt);
    }
1119861
function DropForeignKey($table, $foreignKey)
    {
        $escaper = $this->GetEscaper();
        $query = 'ALTER TABLE ' . $escaper->EscapeIdentifier($table) . 
                ' DROP FOREIGN KEY ' . $escaper->EscapeIdentifier($foreignKey);
        $this->ExecuteQuery($query);
    }
833092
protected function getGenericForeignKeys(array $foreignKeys)
    {
        $genericForeignKeys = array();

        foreach ($foreignKeys as $foreignKey) {
            $name = $foreignKey['name'];

            if (!isset($genericForeignKeys[$name])) {
                $genericForeignKeys[$name] = new ForeignKey(
                    $foreignKey['name'],
                    array($foreignKey['local_column_name']),
                    $foreignKey['foreign_table_name'],
                    array($foreignKey['foreign_column_name']),
                    $foreignKey['on_delete'],
                    $foreignKey['on_update']
                );
            } else {
                $genericForeignKeys[$name]->addLocalColumnName($foreignKey['local_column_name']);
                $genericForeignKeys[$name]->addForeignColumnName($foreignKey['foreign_column_name']);
            }
        }

        return array_values($genericForeignKeys);
    }
364176
public ForeignkeyDef getForeignkey(String name, String tableName)
    {
        String        realName = (name == null ? "" : name);
        ForeignkeyDef def      = null;

        for (Iterator it = getForeignkeys(); it.hasNext();)
        {
            def = (ForeignkeyDef)it.next();
            if (realName.equals(def.getName()) &&
                def.getTableName().equals(tableName))
            {
                return def;
            }
        }
        return null;
    }
1007879
protected function getForeignKeys($tableName)
    {
        $parts = $this->getSchemaName($tableName);
        $foreignKeys = [];
        $rows = $this->fetchAll(sprintf(
            "SELECT
                    tc.constraint_name,
                    tc.table_name, kcu.column_name,
                    ccu.table_name AS referenced_table_name,
                    ccu.column_name AS referenced_column_name
                FROM
                    information_schema.table_constraints AS tc
                    JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
                    JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_schema = %s AND tc.table_name = %s
                ORDER BY kcu.position_in_unique_constraint",
            $this->getConnection()->quote($parts['schema']),
            $this->getConnection()->quote($parts['table'])
        ));
        foreach ($rows as $row) {
            $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
            $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
            $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
            $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
        }

        return $foreignKeys;
    }
308553
public function getKeyUses($tablename, $keyname) {

        $uses = array();

        // Check if some foreign key in the whole structure is using it
        // (by comparing the reftable and reffields with the fields in the key)
        $mytable = $this->getTable($tablename);
        $mykey = $mytable->getKey($keyname);
        if ($this->tables && $mykey) {
            foreach ($this->tables as $table) {
                $allkeys = $table->getKeys();
                if ($allkeys) {
                    foreach ($allkeys as $key) {
                        if ($key->getType() != XMLDB_KEY_FOREIGN) {
                            continue;
                        }
                        if ($key->getRefTable() == $tablename &&
                            implode(',', $key->getRefFields()) == implode(',', $mykey->getFields())) {
                                $uses[] = 'table ' . $table->getName() . ' key ' . $key->getName();
                        }
                    }
                }
            }
        }

        // Return result
        if (!empty($uses)) {
            return $uses;
        } else {
            return false;
        }
    }
1193276
def _model_foreign(ins):
    
    fks = []
    for t in ins.tables:
        fks.extend([
            SaForeignkeyDoc(
                key=fk.column.key,
                target=fk.target_fullname,
                onupdate=fk.onupdate,
                ondelete=fk.ondelete
            )
            for fk in t.foreign_keys])
    return fks
271041
public function getDropForeignKeySQLQueries(ForeignKey $foreignKey, $table)
    {
        if (!$this->supportForeignKeys()) {
            throw PlatformException::methodNotSupported(__METHOD__);
        }

        return array($this->getAlterTableSQLQuery($table, 'DROP CONSTRAINT', $foreignKey->getName()));
    }
243829
protected function getRealtion($foreignTableName, $foreignColumn, $localColumn, $selfReferences)
    {
        $modelName = $this->getModelName($foreignTableName);
        $model = Helpers::guessModelFullName($modelName, Helpers::getModelsPath());

        $params = [
            $model,
            $foreignColumn,
            $localColumn,
        ];

        $relationName = ($selfReferences ? 'child_' : '');

        if ($this->isOneToMany($foreignTableName, $foreignColumn)) {
            return new ForeignRelationship('hasMany', $params, camel_case($relationName . Str::plural($foreignTableName)));
        }

        return new ForeignRelationship('hasOne', $params, camel_case($relationName . Str::singular($foreignTableName)));
    }
1148850
public static function add_foreign_key($table, $foreign_key)
	{
		if ( ! is_array($foreign_key))
		{
			throw new InvalidArgumentException('Foreign key for add_foreign_key() must be specified as an array');
		}

		$sql = 'ALTER TABLE ';
		$sql .= \DB::quote_identifier(\DB::table_prefix($table, static::$connection)).' ';
		$sql .= 'ADD ';
		$sql .= ltrim(static::process_foreign_keys(array($foreign_key)), ',');

		return \DB::query($sql, \DB::UPDATE)->execute();
	}
359895
public function getAddForeignKeyDDL(ForeignKey $fk)
    {
        if ($fk->isSkipSql() || $fk->isPolymorphic()) {
            return;
        }
        $pattern = "
ALTER TABLE %s ADD %s;
";

        return sprintf($pattern,
            $this->quoteIdentifier($fk->getTable()->getName()),
            $this->getForeignKeyDDL($fk)
        );
    }
884540
public function getForeignKeyFor(string $localColumn, string $relatedTableName, string $relatedColumn) : ForeignKey
    {
        foreach ($this->foreignKeys as $foreignKey) {
            if ($foreignKey->getLocalColumnNames() === [$localColumn] && $foreignKey->getReferencedTableName() === $relatedTableName && $foreignKey->getReferencedColumnNames() === [$relatedColumn]) {
                return $foreignKey;
            }
        }
        
        throw InvalidArgumentException::format('Cannot find matching foreign key');
    }
357965
private function getFieldNameForColumn($tableName, $columnName, $fk = false)
    {
        if (isset($this->fieldNamesForColumns[$tableName], $this->fieldNamesForColumns[$tableName][$columnName])) {
            return $this->fieldNamesForColumns[$tableName][$columnName];
        }

        $columnName = strtolower($columnName);

        // Replace _id if it is a foreignkey column
        if ($fk) {
            $columnName = str_replace('_id', '', $columnName);
        }

        return Inflector::camelize($columnName);
    }
725718
public function renameForeignKey($oldName, $newName)
    {
        if (!$this->hasForeignKey($oldName)) {
            throw SchemaException::tableForeignKeyDoesNotExist($this->getName(), $oldName);
        }

        if ($this->hasForeignKey($newName)) {
            throw SchemaException::tableForeignKeyAlreadyExists($this->getName(), $newName);
        }

        $this->foreignKeys[$oldName]->setName($newName);
        $this->foreignKeys[$newName] = $this->foreignKeys[$oldName];
        unset($this->foreignKeys[$oldName]);
    }