Retrieves the foreign keys for the table
548537
private static void getForeignKeys(DatabaseMetaData md, DatabaseRelationDefinition relation, DBMetadata metadata) throws SQLException {

		QuotedIDFactory idfac = metadata.getQuotedIDFactory();

		RelationID relationId = relation.getID();
		try (ResultSet rs = md.getImportedKeys(null, relationId.getSchemaName(), relationId.getTableName())) {
            extractForeignKeys(relation, metadata, idfac, rs);
        }
        catch (Exception ex) {
            try (ResultSet rs = md.getImportedKeys(relationId.getSchemaName(),null, relationId.getTableName())) {
                extractForeignKeys(relation, metadata, idfac, rs);
            }
        }
	}
351404
def get_foreign_key(self, name):
        
        name = self._normalize_identifier(name)

        if not self.has_foreign_key(name):
            raise ForeignKeyDoesNotExist(name, self._name)

        return self._fk_constraints[name]
262346
protected function getRelationKey($table)
    {
        $foreignKeys = $table->getForeignKey();
        if (count($foreignKeys) != 2) {
            return [
                'parentKey' => '',
                'childKey'  => '',
            ];
        }
        $tables  = [];
        $columns = [];
        foreach ($foreignKeys as $foreignKey) {
            if (!$foreignKey->hasMany()) {
                return [
                    'parentKey' => '',
                    'childKey'  => '',
                ];
            }
            $tables[]  = $foreignKey->getReferenceTableName();
            $columns[] = $foreignKey->getColumns();
        }

        if (count($tables) === 2) {
            if ($table->getName() === implode('_', [singularize($tables[0]), $tables[1]])) {
                return [
                    'parentKey' => Arr::get($columns, '0.0') ? (Arr::get($columns, '0.0'))->getName() : '',
                    'childKey'  => Arr::get($columns, '1.0') ? (Arr::get($columns, '1.0'))->getName() : '',
                ];
            } elseif ($table->getName() === implode('_', [singularize($tables[1]), $tables[0]])) {
                return [
                    'parentKey' => Arr::get($columns, '1.0') ? (Arr::get($columns, '1.0'))->getName() : '',
                    'childKey'  => Arr::get($columns, '0.0') ? (Arr::get($columns, '0.0'))->getName() : '',
                ];
            }
        }

        return [
            'parentKey' => '',
            'childKey'  => '',
        ];
    }
1126416
def columns(self):
        """"""
        res = [col['name'] for col in self.column_definitions]
        res.extend([col['name'] for col in self.foreign_key_definitions])
        return res
1030429
protected function dropForeignKeys()
    {
        foreach ($this->sortedTables() as $table) {
            if ($table->exists()) {
                $table->save(HandlerInterface::DROP_FOREIGN_KEYS, false);
            }
        }
    }
1306664
def primary_keys(table_name) # :nodoc:
      pks = table_structure(table_name).select { |f| f["pk"] > 0 }
      pks.sort_by { |f| f["pk"] }.map { |f| f["name"] }
    end
1308977
def _get_foreign_keys_in_altered_table(self, diff):
        
        foreign_keys = diff.from_table.get_foreign_keys()
        column_names = self._get_column_names_in_altered_table(diff)

        for key, constraint in foreign_keys.items():
            changed = False
            local_columns = []
            for column_name in constraint.get_local_columns():
                normalized_column_name = column_name.lower()
                if normalized_column_name not in column_names:
                    del foreign_keys[key]
                    break
                else:
                    local_columns.append(column_names[normalized_column_name])
                    if column_name != column_names[normalized_column_name]:
                        changed = True

            if changed:
                foreign_keys[key] = ForeignKeyConstraint(
                    local_columns,
                    constraint.get_foreign_table_name(),
                    constraint.get_foreign_columns(),
                    constraint.get_name(),
                    constraint.get_options(),
                )

        for constraint in diff.removed_foreign_keys:
            constraint_name = constraint.get_name().lower()
            if constraint_name and constraint_name in foreign_keys:
                del foreign_keys[constraint_name]

        foreign_keys_diff = diff.changed_foreign_keys + diff.added_foreign_keys
        for constraint in foreign_keys_diff:
            constraint_name = constraint.get_name().lower()
            if constraint_name:
                foreign_keys[constraint_name] = constraint
            else:
                foreign_keys[len(foreign_keys)] = constraint

        return foreign_keys
532265
def basic_types(self):
        
        if not self.foreign_key_definitions:
            return self.standard_types
        else:
            tmp = self.standard_types
            tmp.append('ForeignKey')
            return tmp
601213
private List<ForeignKey> getForeignKeys(Entity entity) {
        List<ForeignKey> result = newArrayList();

        // get all tables involved in this entity fk.
        List<Table> involvedTables = newArrayList(); // use list to preserve fk ordering.
        for (Attribute a : entity.getCurrentAttributes()) {
            if (a.isInFk()) {
                String fkTableName = a.getColumnConfig().getTableName();
                Assert.notNull(fkTableName);
                Table t = topLevelCfg.getMetadata().getTableByName(fkTableName);
                if (!involvedTables.contains(t)) {
                    involvedTables.add(t);
                }
            }
        }

        // get all the imported key of the involved tables
        for (Table table : involvedTables) {
            // keep only the fk that are really bound to the passed entity
            for (ForeignKey fk : table.getForeignKeys()) {
                if (relationExists(entity, fk)) {
                    result.add(fk);
                }
            }
        }

        return result;
    }
1166951
public function getAllLocalForeignKeys()
    {
        $columns = array();
        foreach ($this->getColumns() as $column) {
            foreach ($column->getLocalForeignKeys() as $foreignKey) {
                if (array_key_exists($foreignKey->getId(), $columns)) {
                    continue;
                }
                $columns[$foreignKey->getId()] = $foreignKey;
            }
        }

        return $columns;
    }
1097111
def get_relations(self, cursor, table_name):
        
        # pylint:disable=global-statement,too-many-locals,too-many-nested-blocks,unused-argument
        def table2model(table_name):
            return SfProtectName(table_name).title().replace(' ', '').replace('-', '')
        global last_introspected_model, last_read_only, last_refs
        global last_with_important_related_name  # pylint:disable=invalid-name
        result = {}
        reverse = {}
        last_with_important_related_name = []
        last_read_only = {}
        last_refs = {}
        for _, field in enumerate(self.table_description_cache(table_name)['fields']):
            if field['type'] == 'reference' and field['referenceTo']:
                reference_to_name = SfProtectName(field['referenceTo'][0])
                relationship_order = field['relationshipOrder']
                if relationship_order is None:
                    relationship_tmp = set()
                    for rel in field['referenceTo']:
                        for chld in self.table_description_cache(rel)['childRelationships']:
                            if chld['childSObject'] == table_name and chld['field'] == field['name']:
                                relationship_tmp.add(chld['cascadeDelete'])
                    assert len(relationship_tmp) <= 1
                    if True in relationship_tmp:
                        relationship_order = '*'
                last_refs[field['name']] = (field['referenceTo'], relationship_order)
                result[field['name']] = ('Id', reference_to_name)
                reverse.setdefault(reference_to_name, []).append(field['name'])
                if not field['updateable'] or not field['createable']:
                    sf_read_only = (0 if field['updateable'] else 1) | (0 if field['createable'] else 2)
                    # use symbolic names NOT_UPDATEABLE, NON_CREATABLE, READ_ONLY instead of 1, 2, 3
                    last_read_only[field['name']] = reverse_models_names[sf_read_only]
        for ref, ilist in reverse.items():
            # Example of back_collision: a class Aaa has a ForeignKey to a class
            # Bbb and the class Bbb has any field with the name 'aaa'.
            back_name_collisions = [
                x['name'] for x in self.table_description_cache(ref)['fields']
                if re.sub('Id$' if x['type'] == 'reference' else '', '',
                          re.sub('__c$', '', x['name'])
                          ).replace('_', '').lower() == table2model(table_name).lower()]
            # add `related_name` only if necessary
            if len(ilist) > 1 or back_name_collisions:
                last_with_important_related_name.extend(ilist)
        last_introspected_model = table2model(table_name)
        return result
96879
def get_relations(self, cursor, table_name):
        
        # CONSTRAINT_COLUMN_USAGE: http://msdn2.microsoft.com/en-us/library/ms174431.aspx
        # CONSTRAINT_TABLE_USAGE:  http://msdn2.microsoft.com/en-us/library/ms179883.aspx
        # REFERENTIAL_CONSTRAINTS: http://msdn2.microsoft.com/en-us/library/ms179987.aspx
        # TABLE_CONSTRAINTS:       http://msdn2.microsoft.com/en-us/library/ms181757.aspx

        table_index = self._name_to_index(cursor, table_name)
        sql = """
SELECT e.COLUMN_NAME AS column_name,
  c.TABLE_NAME AS referenced_table_name,
  d.COLUMN_NAME AS referenced_column_name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS a
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS b
  ON a.CONSTRAINT_NAME = b.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS c
  ON b.UNIQUE_CONSTRAINT_NAME = c.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS d
  ON c.CONSTRAINT_NAME = d.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS e
  ON a.CONSTRAINT_NAME = e.CONSTRAINT_NAME
WHERE a.TABLE_NAME = %s AND a.CONSTRAINT_TYPE = 'FOREIGN KEY'"""
        cursor.execute(sql, (table_name,))
        return dict([(table_index[item[0]], (self._name_to_index(cursor, item[1])[item[2]], item[1]))
                     for item in cursor.fetchall()])
652445
protected function getForeignKeyRelations() {
    if ($this->fkRelations == null) {
      $this->fkRelations = [];
      $relationDescs = $this->getRelations();
      foreach($relationDescs as $relationDesc) {
        if ($relationDesc instanceof RDBManyToOneRelationDescription) {
          $this->fkRelations[] = $relationDesc;
        }
      }
    }
    return $this->fkRelations;
  }
869333
protected function filterAndSeparateForeignKeys($foreignKeys, $table)
    {
        $results = ['local' => [], 'remote' => []];
        foreach ($foreignKeys as $foreignKey) {
            if ($foreignKey->TABLE_NAME == $table) {
                $results['local'][] = $foreignKey;
            }
            if ($foreignKey->REFERENCED_TABLE_NAME == $table) {
                $results['remote'][] = $foreignKey;
            }
        }

        return $results;
    }
467804
public static function tableForeignKeys($tableName)
    {
        $result = ['inner' => [], 'outer' => []];
        foreach (Yii::$app->db->schema->tableSchemas as $table) {
            $foreignKeys = static::findConstraints($table);
            /** @var TableSchema $table */
            if ($table->name == $tableName) {
                $result['inner'] = $foreignKeys;
                continue;
            }
            foreach ($foreignKeys as $foreignKey) {
                if ($foreignKey['ftable'] == $tableName) {
                    $result['outer'][] = $foreignKey;
                }
            }
        }
        return $result;
    }
1168775
protected function collectForeignKeys()
    {
        $keys = [];

        foreach ($this->info->relations as $relation) {

            if ( ! in_array(
                $relation->type,
                [ RelationType::BELONGS_TO, RelationType::MORPH_TO, RelationType::BELONGS_TO_THROUGH ]
            )) {
                continue;
            }

            $keys = array_merge($keys, $relation->foreign_keys);
        }

        return $keys;
    }
217767
public function getOtherFks()
    {
        $fks = [];
        foreach ($this->parentTable->getForeignKeys() as $fk) {
            if ($fk !== $this) {
                $fks[]= $fk;
            }
        }

        return $fks;
    }