Return an array of foreign key constraints columns
@param string $db Database Name
@param string $table Table Name
@return array
193674
public function getRelations ($db, $table)
	{
		
		// If there are no table constraints
		
		if (!isset ($this->relations[$db][$table]))
		{
			
			// Set blank array
			
			$this->relations[$db][$table]	= array ();
			
			// Query database
			
			$query	= $this->db->query ('SHOW CREATE TABLE ' . $db . '.' . $table);
			
			// get SQL
			
			$sql	= $query->fetchColumn (1);
			
			// For each line
			
			foreach (explode ("\n", $sql) as $line)
			{
				
				// Trim
				
				$line	= trim ($line);
				
				// If the line starts with CONSTRAINT
				
				if (strpos ($line, 'CONSTRAINT') === 0)
				{
					
					// Reset pattern
					
					$pattern	= array ();
					
					// Get necessary information out of the constraint
					
					preg_match ('/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/', 
						$line, $pattern);
					
					// Add to relations array
					
					$this->relations[$db][$table][]	= array (
						'attribute'		=> $pattern[1], 
						'table'			=> $pattern[2], 
						'column'		=> $pattern[3]
					);
					
				}
				
			}
			
		}
		
		// Return relations
		
		return $this->relations[$db][$table];
		
	}
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;
    }
420602
protected function addForeignKeys(Table $table)
    {
        // local store to avoid duplicates
        $foreignKeys = [];

        /* @var \PDOStatement $stmt */
        $stmt = $this->dbh->query("SELECT CONSTRAINT_NAME, DELETE_RULE, R_CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'R' AND TABLE_NAME = '" . $table->getName(). "'");
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            // Local reference
            /* @var \PDOStatement $stmt2 */
            $stmt2 = $this->dbh->query("SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '".$row['CONSTRAINT_NAME']."' AND TABLE_NAME = '" . $table->getName(). "'");
            $localReferenceInfo = $stmt2->fetch(\PDO::FETCH_ASSOC);

            // Foreign reference
            $stmt2 = $this->dbh->query("SELECT TABLE_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '".$row['R_CONSTRAINT_NAME']."'");
            $foreignReferenceInfo = $stmt2->fetch(\PDO::FETCH_ASSOC);

            if (!isset($foreignKeys[$row['CONSTRAINT_NAME']])) {
                $fk = new ForeignKey($row['CONSTRAINT_NAME']);
                $fk->setForeignTableCommonName($foreignReferenceInfo['TABLE_NAME']);
                $onDelete = ('NO ACTION' === $row['DELETE_RULE']) ? 'NONE' : $row['DELETE_RULE'];
                $fk->setOnDelete($onDelete);
                $fk->setOnUpdate($onDelete);
                $fk->addReference(['local' => $localReferenceInfo['COLUMN_NAME'], 'foreign' => $foreignReferenceInfo['COLUMN_NAME']]);
                $table->addForeignKey($fk);
                $foreignKeys[$row['CONSTRAINT_NAME']] = $fk;
            }
        }
    }
179093
protected function getTableFields(Table $table)
	{
		$fileds = [];

		foreach ($table->getColumns() as $column) {
			$fileds[] = [
	            'name' => $column->getName(),
	            'type' => $column->getType()->getName(),
	            'not_null' => $column->getNotnull(),
	            'length' => $column->getLength(),
	            'unsigned' => $column->getUnsigned(),
	            'autoincrement' => $column->getAutoincrement(),
	            'primary_key' => $this->isPrimaryKey($table, $column),
	            'foreign_key' => $this->isForeignKey($table, $column)
			];
		}

		return $fileds;
	}
691263
public function getTableKeys($table)
	{
		$this->connect();

		/** @var OracleQuery $query */
		$query = $this->getQuery(true);

		$fieldCasing = $this->getOption(\PDO::ATTR_CASE);

		$this->setOption(\PDO::ATTR_CASE, \PDO::CASE_UPPER);

		$table = strtoupper($table);
		$query->select('*');
		$query->from('ALL_CONSTRAINTS');
		$query->where('table_name = :tableName');

		$query->bind(':tableName', $table);

		$this->setQuery($query);
		$keys = $this->loadObjectList();

		$this->setOption(\PDO::ATTR_CASE, $fieldCasing);

		return $keys;
	}
353676
public function getDropAutoincrementSql($table)
    {
        $table                       = $this->normalizeIdentifier($table);
        $autoincrementIdentifierName = $this->getAutoincrementIdentifierName($table);
        $identitySequenceName        = $this->getIdentitySequenceName(
            $table->isQuoted() ? $table->getQuotedName($this) : $table->getName(),
            ''
        );

        return [
            'DROP TRIGGER ' . $autoincrementIdentifierName,
            $this->getDropSequenceSQL($identitySequenceName),
            $this->getDropConstraintSQL($autoincrementIdentifierName, $table->getQuotedName($this)),
        ];
    }
320935
public function getTableConstraintsInfo($table)
    {
        preg_match_all(
            '/CONSTRAINT `\w+` FOREIGN KEY \(`(.+)`\) REFERENCES `(\w+)` \(`.+`\)/Us',
            $this->getSqlCreateTable($table),
            $matches
        );

        $constraintsInfo = [];

        foreach ($matches[0] as $index => $constraint) {
            $constraintsInfo[] = [
                'foreignKey'   => $matches[1][$index],
                'relatedTable' => $matches[2][$index]
            ];
        }

        return $constraintsInfo;
    }
227249
public function getCreateConstraintSQLQueries(ConstraintInterface $constraint, $table)
    {
        if ($constraint instanceof PrimaryKey) {
            return $this->getCreatePrimaryKeySQLQueries($constraint, $table);
        }

        if ($constraint instanceof ForeignKey) {
            return $this->getCreateForeignKeySQLQueries($constraint, $table);
        }

        if ($constraint instanceof Index) {
            return $this->getCreateIndexSQLQueries($constraint, $table);
        }

        if ($constraint instanceof Check) {
            return $this->getCreateCheckSQLQueries($constraint, $table);
        }

        throw PlatformException::constraintNotSupported(get_class($constraint));
    }
671193
public function getTableColumns(string $table): array {
		$query = <<<QUERY
			SELECT COLUMN_NAME
			FROM INFORMATION_SCHEMA.COLUMNS
			WHERE TABLE_SCHEMA = :database
			AND TABLE_NAME = :table
QUERY;
		
		$params = [
			"database" => $this->database,
			"table"    => $table,
		];
		
		try {
			$results = $this->getCol($query, $params);
			return is_array($results) ? $results : [];
		} catch (\PDOException $databaseException) {
			throw $this->prepareDatabaseException($databaseException, $query, $params);
		}
	}
1217133
protected function getMeta($table, $database)
    {
        $uid = spl_object_hash($database);
        if (isset(self::$meta[$uid][$table])) {
            return self::$meta[$uid][$table];
        }
        
        $columns = $database->getColumns($table);
        
        $meta = array();
        foreach ($columns as $i => $column) {
            $meta[self::COLUMNS][$column['Field']] = array(
                'type'      => $column['Type'],
                'key'       => $column['Key'],
                'default'   => $column['Default'],
                'empty'     => $column['Null'] == 'YES');
            
            if ($column['Key'] == 'PRI') {
                $meta[self::PRIMARY][] = $column['Field'];
            }
        }
        
        self::$meta[$uid][$table] = $meta;
        
        return $meta;
    }
1097061
public function getTableRelationships($table) {
        $table = $this->connection->getTablePrefix() . Util::camelTo_($table);
        $relationships = array();
        foreach ($this->references as $columnName => $info) {
            if ($info['constraintName'] == 'PRIMARY' || $info['refTable'] != $table)
                    continue;
            $this->setupRelationship($columnName, $info['refColumn'],
                    $info['refTable'], $relationships, false);
        }
        foreach ($this->backReferences as $columnName => $infoArray) {
            foreach ($infoArray as $info) {
                if ($info['refTable'] != $table) continue;
                $this->setupRelationship($columnName, $info['refColumn'],
                        $info['refTable'], $relationships, true);
            }
        }
        return $relationships[$table];
    }
1279499
public function getForeignKeys($tableName)
    {
        $sql = sprintf("SELECT
                cols.TABLE_NAME,
                cols.COLUMN_NAME,
                cRefs.CONSTRAINT_NAME,
                refs.REFERENCED_TABLE_NAME,
                refs.REFERENCED_COLUMN_NAME,
                cRefs.UPDATE_RULE,
                cRefs.DELETE_RULE
            FROM INFORMATION_SCHEMA.COLUMNS AS cols
            LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS refs
                ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
                AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
                AND refs.TABLE_NAME=cols.TABLE_NAME
                AND refs.COLUMN_NAME=cols.COLUMN_NAME
            LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS cons
                ON cons.TABLE_SCHEMA=cols.TABLE_SCHEMA
                AND cons.TABLE_NAME=cols.TABLE_NAME
                AND cons.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
            LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
                ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
                AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
            WHERE
                cols.TABLE_NAME = %s
                AND cols.TABLE_SCHEMA = DATABASE()
                AND refs.REFERENCED_TABLE_NAME IS NOT NULL
                AND cons.CONSTRAINT_TYPE = 'FOREIGN KEY'
            ;", $this->quote($tableName));
        $stm = $this->pdo->query($sql);
        $rows = $stm->fetchAll();
        if (empty($rows)) {
            return null;
        }

        $result = [];
        foreach ($rows as $row) {
            $result[$row['CONSTRAINT_NAME']] = $row;
        }

        return $result;
    }
269386
def get_constraints(self, cursor, table_name):
    
    constraints = {}
    # Loop over the key table, collecting things as constraints. The column
    # array must return column names in the same order in which they were
    # created.
    # The subquery containing generate_series can be replaced with
    # "WITH ORDINALITY" when support for PostgreSQL 9.3 is dropped.
    cursor.execute("""
        SELECT
            c.conname,
            array(
                SELECT attname
                FROM (
                    SELECT unnest(c.conkey) AS colid,
                           generate_series(1, array_length(c.conkey, 1)) AS arridx
                ) AS cols
                JOIN pg_attribute AS ca ON cols.colid = ca.attnum
                WHERE ca.attrelid = c.conrelid
                ORDER BY cols.arridx
            ),
            c.contype,
            (SELECT fkc.relname || '.' || fka.attname
            FROM pg_attribute AS fka
            JOIN pg_class AS fkc ON fka.attrelid = fkc.oid
            WHERE fka.attrelid = c.confrelid AND fka.attnum = c.confkey[1]),
            cl.reloptions
        FROM pg_constraint AS c
        JOIN pg_class AS cl ON c.conrelid = cl.oid
        JOIN pg_namespace AS ns ON cl.relnamespace = ns.oid
        WHERE ns.nspname = %s AND cl.relname = %s
    """, [self.connection.schema_name, table_name])
    for constraint, columns, kind, used_cols, options in cursor.fetchall():
        constraints[constraint] = {
            "columns": columns,
            "primary_key": kind == "p",
            "unique": kind in ["p", "u"],
            "foreign_key": tuple(used_cols.split(".", 1)) if kind == "f" else None,
            "check": kind == "c",
            "index": False,
            "definition": None,
            "options": options,
        }
    # Now get indexes
    # The row_number() function for ordering the index fields can be
    # replaced by WITH ORDINALITY in the unnest() functions when support
    # for PostgreSQL 9.3 is dropped.
    cursor.execute("""
        SELECT
            indexname, array_agg(attname ORDER BY rnum), indisunique, indisprimary,
            array_agg(ordering ORDER BY rnum), amname, exprdef, s2.attoptions
        FROM (
            SELECT
                row_number() OVER () as rnum, c2.relname as indexname,
                idx.*, attr.attname, am.amname,
                CASE
                    WHEN idx.indexprs IS NOT NULL THEN
                        pg_get_indexdef(idx.indexrelid)
                END AS exprdef,
                CASE am.amname
                    WHEN 'btree' THEN
                        CASE (option & 1)
                            WHEN 1 THEN 'DESC' ELSE 'ASC'
                        END
                END as ordering,
                c2.reloptions as attoptions
            FROM (
                SELECT
                    *, unnest(i.indkey) as key, unnest(i.indoption) as option
                FROM pg_index i
            ) idx
            LEFT JOIN pg_class c ON idx.indrelid = c.oid
            LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
            LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid
            LEFT JOIN pg_am am ON c2.relam = am.oid
            LEFT JOIN pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key
            WHERE c.relname = %s and n.nspname = %s
        ) s2
        GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions;
    """, [table_name, self.connection.schema_name])
    for index, columns, unique, primary, orders, type_, definition, options in cursor.fetchall():
        if index not in constraints:
            constraints[index] = {
                "columns": columns if columns != [None] else [],
                "orders": orders if orders != [None] else [],
                "primary_key": primary,
                "unique": unique,
                "foreign_key": None,
                "check": False,
                "index": True,
                "type": Index.suffix if type_ == 'btree' else type_,
                "definition": definition,
                "options": options,
            }
    return constraints
1289989
protected function _getConstraints($tableName)
    {

        $params = [
            ':schemaName' => $this->_adapter->getSchemaName(),
            ':tableName' => $tableName
        ];

        return $this->_adapter->query($this->_getConstraintsSql, $params);
    }
1254112
public function foreign(
        $table,
        $localColumnNames,
        $foreignColumnNames = 'id',
        $options = [],
        $constraintName = null
    ) {
        $localColumnNames   = is_array($localColumnNames) ? $localColumnNames : [$localColumnNames];
        $foreignColumnNames = is_array($foreignColumnNames) ? $foreignColumnNames : [$foreignColumnNames];

        return $this->table->addForeignKeyConstraint($table, $localColumnNames, $foreignColumnNames, $options,
            $constraintName);
    }
367847
public static function table($table, $db = 'default') {
        /**@var \wulaphp\db\SimpleTable[][] $tables */
        static $tables = [];
        try {
            $dbid = get_unique_id($db);
            if (!isset($tables[ $dbid ][ $table ])) {
                $tables[ $dbid ][ $table ] = new SimpleTable($table, $db);
            } else {
                $tables[ $dbid ][ $table ]->db(DatabaseConnection::connect($db));
            }

            return $tables[ $dbid ][ $table ];
        } catch (\Exception $e) {
            return null;
        }
    }
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;
    }