Load foreign keys for this table.

@param Table $table The Table model class to add FKs to
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;
            }
        }
    }
731226
protected function _associated(Table $table, array $associations)
    {
        foreach ($associations as $key => $associated) {
            if (is_int($key)) {
                $this->_checkAssociation($table, $associated);
                continue;
            }
            $this->_checkAssociation($table, $key);
            if (isset($associated['associated'])) {
                $this->_associated($table->getAssociation($key)->getTarget(), $associated['associated']);
                continue;
            }
        }
    }
821708
protected function addColumns(Table $table)
	{
		$stmt = $this->dbh->query("sp_columns '" . $table->getName() . "'");

		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

			$name = $row['COLUMN_NAME'];
			$type = $row['TYPE_NAME'];
			$size = $row['LENGTH'];
			$is_nullable = $row['NULLABLE'];
			$default = $row['COLUMN_DEF'];
			$precision = $row['PRECISION'];
			$scale = $row['SCALE'];
			$autoincrement = false;
			if (
				strtolower($type) == 'int identity'
				|| strtolower($type) == 'bigint identity'
				|| strpos(strtolower($default), 'newid') !== false
				|| strpos(strtolower($default), 'newsequentialid') !== false
			) {
				$autoincrement = true;
			}

			$propelType = $this->getMappedPropelType($type);
			if (!$propelType) {
				$propelType = Column::DEFAULT_TYPE;
				$this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$type.") that Propel does not support.");
			}

			$column = new Column($name);
			$column->setTable($table);
			$column->setDomainForType($propelType);
			// We may want to provide an option to include this:
			// $column->getDomain()->replaceSqlType($type);
			$column->getDomain()->replaceSize($size);
			$column->getDomain()->replaceScale($scale);
			if ($default !== null) {
				$column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE));
			}
			$column->setAutoIncrement($autoincrement);
			$column->setNotNull(!$is_nullable);

			$table->addColumn($column);
		}
	}
848890
protected function createTable(Table $table): void
	{
		$table->addPrimaryKey('id')
			->int()
			->setAutoIncrement();
		$table->addForeignKey('pageId', PagesMapper::class);
		$table->addColumn('name')
			->varChar();
		$table->addColumn('position')
			->int(3);
	}
124391
protected function _getFields(Table $table)
    {
        $fields = explode(',', $this->args[1]);
        foreach ($fields as $field) {
            if (!$table->hasField($field)) {
                $this->abort(sprintf('Table `%s` is missing the field `%s`.', $table->table(), $field));
            }
        }

        return $fields;
    }
1103705
public static function getTableAssignationFields(Table $table): array
    {
        $fields = [];
        $assignationModels = Configure::read('RolesCapabilities.accessCheck.assignationModels');

        foreach ($table->associations() as $association) {
            // skip non-assignation models
            if (!in_array($association->className(), $assignationModels)) {
                continue;
            }

            $fields[] = $association->getForeignKey();
        }

        return $fields;
    }
369717
protected function addIndexes(Table $table)
    {
        $stmt = $this->dbh->query("sp_indexes_rowset '" . $table->getName() . "'");

        $indexes = array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $colName = $this->cleanDelimitedIdentifiers($row["COLUMN_NAME"]);
            $name = $this->cleanDelimitedIdentifiers($row['INDEX_NAME']);

            // FIXME -- Add UNIQUE support
            if (!isset($indexes[$name])) {
                $indexes[$name] = new Index($name);
                $table->addIndex($indexes[$name]);
            }

            $indexes[$name]->addColumn($table->getColumn($colName));
        }
    }
629546
public function addTable(AbstractTable $table)
    {
        $this->tables[$table->getName()] = $table;
        $this->dependencies[$table->getName()] = $table->getDependencies();

        $this->collectDrivers();
    }
254128
public void setTable(final Table table) {
        if (table != _tableRef.get()) {
            _tableRef.set(table);

            if (table == null) {
                _comboBox.setEmptyModel();
            } else {
                _comboBox.setModel(table);
            }
        }
    }
402674
protected function loadCacheInformation($table = null)
    {
        $schema = $this->schema;
        $this->checkTableArgument($table);

        if (!in_array($schema, self::$fullyCachedSchemas)) {
            if ($table !== null) {
                $this->getTableConfig($table);
            } else {
                $this->getSchemaConfig();
            }
        } elseif ($table !== null) {
            // Just in case to check if table exists
            $this->getTableConfig($table);
        }
    }
242630
protected function loadColumnListForTable($table)
    {
        if ($this->getDatabaseDriver() === 'sqlite') {
            $statement = "PRAGMA table_info(`{$table}`)";
        } else {
            $statement = "SHOW columns FROM `{$table}`";
        }

        $columnResults = DB::select($statement);
        $columns       = [];

        foreach ($columnResults as $columnObject) {

            $columns[] = array_get(array_values((array) $columnObject), '0');
        }

        return $columns;
    }
773342
protected function loadMetadataForTable(Table $table)
    {
        $tblName = $table->getName();

        if (isset($this->defaultAliases[$tblName])) {
            $className = $this->defaultAliases[$tblName];
        } else {
            $className = $tblName;
            $this->unmapped[] = $tblName;
        }

        $contentKey = $this->getContentTypeFromAlias($table->getOption('alias'));
        $this->metadata[$className] = [];
        $this->metadata[$className]['identifier'] = $table->getPrimaryKey();
        $this->metadata[$className]['table'] = $table->getName();
        $this->metadata[$className]['boltname'] = $contentKey;
        if (isset($this->contenttypes[$contentKey]['class'])) {
            $this->metadata[$className]['class'] = $this->contenttypes[$contentKey]['class'];
        }
        foreach ($table->getColumns() as $colName => $column) {
            $mapping = [
                'fieldname'        => $column->getName(),
                'attribute'        => $this->camelize($column->getName()),
                'type'             => $column->getType()->getName(),
                'fieldtype'        => $this->getFieldTypeFor($contentKey, $column),
                'length'           => $column->getLength(),
                'nullable'         => !$column->getNotnull(),
                'platformOptions'  => $column->getPlatformOptions(),
                'precision'        => $column->getPrecision(),
                'scale'            => $column->getScale(),
                'default'          => $column->getDefault(),
                'columnDefinition' => $column->getColumnDefinition(),
                'autoincrement'    => $column->getAutoincrement(),
            ];

            $this->metadata[$className]['fields'][$colName] = $mapping;

            if (isset($this->contenttypes[$contentKey]['fields'][$colName])) {
                $this->metadata[$className]['fields'][$colName]['data'] = $this->contenttypes[$contentKey]['fields'][$colName];
            }
        }

        // This loop checks the contenttypes definition for any non-db fields and adds them.
        if ($contentKey && isset($this->contenttypes[$contentKey])) {
            $this->setRelations($contentKey, $className);
            $this->setIncomingRelations($contentKey, $className);
            $this->setTaxonomies($contentKey, $className);
            $this->setTemplatefields($contentKey, $className);
            $this->setRepeaters($contentKey, $className);
        }

        foreach ($this->getAliases() as $alias => $tablename) {
            if (array_key_exists($tablename, $this->metadata)) {
                $this->metadata[$alias] = $this->metadata[$tablename];
            } elseif (
                array_key_exists($tablename, $this->defaultAliases) &&
                array_key_exists($this->defaultAliases[$tablename], $this->metadata)
            ) {
                $this->metadata[$alias] = $this->metadata[$this->defaultAliases[$tablename]];
            }
        }
    }
734572
protected function _loadBehavior(Table $table)
    {
        $behaviors = $table->behaviors();
        if (!Arr::in('Process', $behaviors->loaded())) {
            $behaviors->load('Core.Process');
        }
    }
449111
public function initialize(Table $table)
    {
        $this->table = $table;
        $this->table->setData($this->getData());
    }
753725
protected function truncate($table)
    {
        if ($this->db->connection()->getConfig('driver') === 'mysql') {
            $this->db->statement('SET FOREIGN_KEY_CHECKS=0;');
            $this->db->table($table)->truncate();
            $this->db->statement('SET FOREIGN_KEY_CHECKS=1;');
        }
    }
1070254
public function setTable(Table $table = null)
    {
        $this->table = $table;

        if ($table && !in_array($this, $table->getRows())) {
            $table->addRow($this);
        }

        return $this;
    }
983989
protected function addForeignKeys(Table $table, $oid)
    {
        $database = $table->getDatabase();
        $stmt = $this->dbh->prepare("SELECT
            conname,
            confupdtype,
            confdeltype,
            CASE nl.nspname WHEN 'public' THEN cl.relname ELSE nl.nspname||'.'||cl.relname END as fktab,
                array_agg(DISTINCT a2.attname) AS fkcols,
                CASE nr.nspname WHEN 'public' THEN cr.relname ELSE nr.nspname||'.'||cr.relname END as reftab,
                    array_agg(DISTINCT a1.attname) AS refcols
                    FROM pg_constraint ct
                    JOIN pg_class cl ON cl.oid=conrelid
                    JOIN pg_class cr ON cr.oid=confrelid
                    JOIN pg_namespace nl ON nl.oid = cl.relnamespace
                    JOIN pg_namespace nr ON nr.oid = cr.relnamespace
                    LEFT JOIN pg_catalog.pg_attribute a1 ON a1.attrelid = ct.confrelid
                    LEFT JOIN pg_catalog.pg_attribute a2 ON a2.attrelid = ct.conrelid
                    WHERE
                    contype='f'
                    AND conrelid = ?
                    AND a2.attnum = ANY (ct.conkey)
                    AND a1.attnum = ANY (ct.confkey)
                    GROUP BY conname, confupdtype, confdeltype, fktab, reftab
                    ORDER BY conname");
        $stmt->bindValue(1, $oid);
        $stmt->execute();

        $foreignKeys = [];
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {

            $name = $row['conname'];
            $localTable = $row['fktab'];
            $localColumns = explode(',', trim($row['fkcols'], '{}'));
            $foreignTableName = $row['reftab'];
            $foreignColumns = explode(',', trim($row['refcols'], '{}'));

            // On Update
            switch ($row['confupdtype']) {
                case 'c':
                    $onupdate = ForeignKey::CASCADE;
                    break;
                case 'd':
                    $onupdate = ForeignKey::SETDEFAULT;
                    break;
                case 'n':
                    $onupdate = ForeignKey::SETNULL;
                    break;
                case 'r':
                    $onupdate = ForeignKey::RESTRICT;
                    break;
                default:
                case 'a':
                    // NOACTION is the postgresql default
                    $onupdate = ForeignKey::NONE;
                    break;
            }
            // On Delete
            switch ($row['confdeltype']) {
                case 'c':
                    $ondelete = ForeignKey::CASCADE;
                    break;
                case 'd':
                    $ondelete = ForeignKey::SETDEFAULT;
                    break;
                case 'n':
                    $ondelete = ForeignKey::SETNULL;
                    break;
                case 'r':
                    $ondelete = ForeignKey::RESTRICT;
                    break;
                default:
                case 'a':
                    // NOACTION is the postgresql default
                    $ondelete = ForeignKey::NONE;
                    break;
            }

            $foreignTable = $database->getTable($foreignTableName);
            $localTable   = $database->getTable($localTable);

            if (!$foreignTable) {
                continue;
            }

            if (!isset($foreignKeys[$name])) {
                $fk = new ForeignKey($name);
                $fk->setForeignTableCommonName($foreignTable->getCommonName());
                if ($table->guessSchemaName() != $foreignTable->guessSchemaName()) {
                    $fk->setForeignSchemaName($foreignTable->getSchema());
                }
                $fk->setOnDelete($ondelete);
                $fk->setOnUpdate($onupdate);
                $table->addForeignKey($fk);
                $foreignKeys[$name] = $fk;
            }

            $max = count($localColumns);
            for ($i = 0; $i < $max; $i++) {
                $foreignKeys[$name]->addReference(
                    $localTable->getColumn($localColumns[$i]),
                    $foreignTable->getColumn($foreignColumns[$i])
                );
            }
        }
    }