Names new foreign key by convention.
@param $table
@param $columns
@param $refTable
@return string
355163
public static function createForeignKeyName($table, $columns, $refTable)
    {
        $column = is_array($columns) ? implode('_', $columns) . '_' : '';
        return preg_replace('/[^\w_-]/', '', "FK_{$table}_{$column}{$refTable}");
    }
1137849
protected function addForeignKeyColumn($column, Table $table, $key = null)
        {
            $add_table = clone $table;
            $key = ($key !== null) ? $key : $add_table->getIdColumn();
            $foreign_column = $add_table->getColumn($key);
            switch ($foreign_column['type']) {
                case 'integer':
                    $this->addInteger($column, $foreign_column['length'], $foreign_column['default_value'], false, false, $foreign_column['unsigned']);
                    break;
                case 'float':
                    $this->addFloat($column, $foreign_column['precision'], $foreign_column['default_value'], false, false, $foreign_column['unsigned']);
                    break;
                case 'varchar':
                    $this->addVarchar($column, $foreign_column['length'], $foreign_column['default_value'], false);
                    break;
                case 'text':
                case 'boolean':
                case 'blob':
                    throw new Exception('Cannot use a text, blob or boolean column as a foreign key');
            }
            $this->foreign_columns[$column] = array('class' => '\\'.get_class($table), 'key' => $key, 'name' => $column);
        }
1151224
public function getPrimaryKey($table)
	{
		$keys = $this->getTableKeys($table);
		$key  = false;

		if ($keys && count($keys) > 0)
		{
			foreach ($keys as $k)
			{
				if ($k->Key_name == 'PRIMARY')
				{
					$key = $k->Column_name;
				}
			}
		}

		return $key;
	}
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();
	}
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);
    }
1373895
public function foreign($table, $column = 'id', $onUpdate = 'cascade', $onDelete = 'cascade')
    {
        if (DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
            $this->context->markTestIncomplete('Foreign keys cannot be tested with a SQLite database.');

            return $this;
        }

        $name = $this->getIndexName('foreign');
        $this->assertTrue($this->table->hasForeignKey($name), "The foreign key {$name} does not exist.");

        $key = $this->table->getForeignKey($name);
        $onUpdate && $this->context->assertEquals(strtoupper($onUpdate), $key->onUpdate());
        $onDelete && $this->context->assertEquals(strtoupper($onDelete), $key->onDelete());

        $this->context->assertEquals($table, $key->getForeignTableName());
        $this->context->assertContains($column, $key->getForeignColumns());

        return $this;
    }
100835
public function PrimaryKey($Table, $Database = NULL) {
      $Schema = $this->Fetch($Table, $Database);
      $PrimaryKeys = array();
      foreach ($Schema as $FieldName => $Properties) {
         if ($Properties->PrimaryKey === TRUE)
            $PrimaryKeys[] = $FieldName;
      }
      
      if (count($PrimaryKeys) == 0)
         return '';
      elseif (count($PrimaryKeys) == 1)
         return $PrimaryKeys[0];
      else
         return $PrimaryKeys;
   }
987789
protected function findForeignKeys($table)
	{
		$rc='INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS';
		$kcu='INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
		if (isset($table->catalogName))
		{
			$kcu=$table->catalogName.'.'.$kcu;
			$rc=$table->catalogName.'.'.$rc;
		}

		//From http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
		$sql = <<<EOD
		SELECT
		     KCU1.CONSTRAINT_NAME AS 'FK_CONSTRAINT_NAME'
		   , KCU1.TABLE_NAME AS 'FK_TABLE_NAME'
		   , KCU1.COLUMN_NAME AS 'FK_COLUMN_NAME'
		   , KCU1.ORDINAL_POSITION AS 'FK_ORDINAL_POSITION'
		   , KCU2.CONSTRAINT_NAME AS 'UQ_CONSTRAINT_NAME'
		   , KCU2.TABLE_NAME AS 'UQ_TABLE_NAME'
		   , KCU2.COLUMN_NAME AS 'UQ_COLUMN_NAME'
		   , KCU2.ORDINAL_POSITION AS 'UQ_ORDINAL_POSITION'
		FROM {$this->quoteTableName($rc)} RC
		JOIN {$this->quoteTableName($kcu)} KCU1
		ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
		   AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
		   AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
		JOIN {$this->quoteTableName($kcu)} KCU2
		ON KCU2.CONSTRAINT_CATALOG =
		RC.UNIQUE_CONSTRAINT_CATALOG
		   AND KCU2.CONSTRAINT_SCHEMA =
		RC.UNIQUE_CONSTRAINT_SCHEMA
		   AND KCU2.CONSTRAINT_NAME =
		RC.UNIQUE_CONSTRAINT_NAME
		   AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
		WHERE KCU1.TABLE_NAME = :table
EOD;
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':table', $table->name);
		$fkeys=array();
		foreach($command->queryAll() as $info)
		{
			$fkeys[$info['FK_COLUMN_NAME']]=array($info['UQ_TABLE_NAME'],$info['UQ_COLUMN_NAME'],);

		}
		return $fkeys;
	}
74272
function addForeignKey($table, $pkname, $tables)
	{
		if ( is_string($tables) )
			$tables = array($tables);
			
		
		$this->_foreignKeys[$table] = array(
					'primaryKey' => $pkname,
					'tables' => $tables
				);
	}
744941
public static function renameColumn(string $table, string $oldColumn, string $newColumn): string
    {
        $query = self::getQuery(true);

        return (string) $query->element(
            'exec sp_rename',
            $query->quote([
                $table . '.' . $oldColumn,
                $newColumn,
                'COLUMN'
            ])
        );
    }
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;
    }
345493
protected function createIndexName($table, array $columns, $unique = false)
    {
        $index = strtolower($table . '_' . implode('_', $columns) . '_' . ($unique ? 'unique' : 'index'));

        return str_replace(['-', '.'], '_', $index);
    }
81241
protected function getCreateColumnCommentSQLQuery(Column $column, $table)
    {
        return 'COMMENT ON COLUMN '.$table.'.'.$column->getName().' IS '.$this->getColumnCommentSQLDeclaration($column);
    }
611638
protected function isPrimaryKey(Table $table, Column $column)
	{
		if ($table->hasPrimaryKey()) {
			$primaryKeys = $table->getPrimaryKey()->getColumns();

			return in_array($column->getName(), $primaryKeys);
		}

		return false;
	}
629747
public function getColumnsLabel($columns, $table)
    {
        /** @var \yii\db\ActiveRecord $model */
        $model = $this->_currentModel;
        /** @var Module $module */
        $module = $this->module;
        $attributeLabels = $model->attributeLabels();
        $relations = $module->tables[$table]['relations'];
        $columnsLabel = [];
        foreach ($columns as $attribute) {
            if (isset($attributeLabels[$attribute])) {
                $columnsLabel[] = $attributeLabels[$attribute];
            } elseif (isset($relations[$attribute]['label'])) {
                $columnsLabel[] = $relations[$attribute]['label'];
            } else {
                $columnsLabel[] = $attribute;
            }
        }

        return $columnsLabel;
    }
1257833
public function findForeignKey(string $column): ?AbstractForeignKey
    {
        foreach ($this->foreignKeys as $reference) {
            if ($reference->getColumn() == $column) {
                return $reference;
            }
        }

        return null;
    }
183066
public static function build(Table $table, array $columns = [])
    {
        $index = new Index();
        $index->setColumns($columns);

        return new static($table, $index);
    }