protected function addClosureColumn($name, Table $ct_table, Column $column) { $table = $this->getTable(); $id_fieldname = $column->getName(); $domain = $column->getDomain(); if (!$ct_table->hasColumn($name)) { $column = new Column($name); $column->setDomain($domain); $column->setPrimaryKey(true); $ct_table->addColumn($column); } else { $column = $ct_table->getColumn($name); } $ct_tablename_normalized = str_replace('_', '', $ct_table->getName()); $fk_name = $ct_tablename_normalized . '_' . $name . '_fk'; if (!$ct_table->getColumnForeignKeys($name)) { $column_fk = new ForeignKey($fk_name); $column_fk->addReference($name, $table->getColumn($id_fieldname)->getName()); $column_fk->setForeignTableCommonName($table->getName()); $column_fk->setOnUpdate('cascade'); $column_fk->setOnDelete('restrict'); $ct_table->addForeignKey($column_fk); } $column_idx_name = $fk_name . '_idx'; if (!$ct_table->hasIndex($column_idx_name)) { $column_idx = new Index($column_idx_name); $column_idx->addColumn(['name' => $column->getName()]); $ct_table->addIndex($column_idx); } }
protected function relateI18nTableToMainTable() { $table = $this->getTable(); $i18nTable = $this->i18nTable; $pks = $this->getTable()->getPrimaryKey(); if (count($pks) > 1) { throw new EngineException('The i18n behavior does not support tables with composite primary keys'); } foreach ($pks as $column) { if (!$i18nTable->hasColumn($column->getName())) { $column = clone $column; $column->setAutoIncrement(false); $i18nTable->addColumn($column); } } if (in_array($table->getName(), $i18nTable->getForeignTableNames())) { return; } $fk = new ForeignKey(); $fk->setForeignTableCommonName($table->getCommonName()); $fk->setForeignSchemaName($table->getSchema()); $fk->setDefaultJoin('LEFT JOIN'); $fk->setOnDelete(ForeignKey::CASCADE); $fk->setOnUpdate(ForeignKey::NONE); foreach ($pks as $column) { $fk->addReference($column->getName(), $column->getName()); } $i18nTable->addForeignKey($fk); }
/** * Adds all columns, indexes, constraints and additional tables. */ public function modifyTable() { $table = $this->getTable(); $tableName = $table->getName(); $foreignTableName = $this->getForeignTable(); // enable reload on insert to force the model to load the trigger generated id(s) $table->setReloadOnInsert(true); $foreignIdColumnName = $foreignTableName . '_id'; $compositeKeyColumnName = $foreignTableName . '_' . $tableName . '_id'; if ($table->hasBehavior('concrete_inheritance')) { // we're a child in a concrete inheritance $parentTableName = $table->getBehavior('concrete_inheritance')->getParameter('extends'); $parentTable = $table->getDatabase()->getTable($parentTableName); if ($parentTable->hasBehavior('\\' . __CLASS__)) { //we're a child of a concrete inheritance structure, so we're going to skip this //round here because this behavior has also been attached by the parent table. return; } } if ($table->hasColumn($foreignIdColumnName)) { $foreignIdColumn = $table->getColumn($foreignIdColumnName); } else { $foreignIdColumn = $table->addColumn(array('name' => $foreignIdColumnName, 'type' => 'integer', 'required' => true)); $compositeKeyForeignKeyName = $tableName . '_FK_' . $foreignIdColumnName; $foreignKey = new ForeignKey($compositeKeyForeignKeyName); $foreignKey->addReference($foreignIdColumnName, 'id'); $foreignKey->setForeignTableCommonName($foreignTableName); $foreignKey->setOnUpdate(ForeignKey::CASCADE); $foreignKey->setOnDelete(ForeignKey::CASCADE); $table->addForeignKey($foreignKey); } if ($table->hasColumn($compositeKeyColumnName)) { $compositeKeyColumn = $table->getColumn($compositeKeyColumnName); } else { $compositeKeyColumn = $table->addColumn(array('name' => $compositeKeyColumnName, 'type' => 'integer', 'required' => false)); } $index = new Unique($tableName . '_UQ_' . $foreignIdColumnName . '_' . $compositeKeyColumnName); $index->addColumn($foreignIdColumn); $index->addColumn($compositeKeyColumn); $table->addUnique($index); $database = $table->getDatabase(); $sequenceTableName = sprintf('%s_sequence', $foreignTableName); if (!$database->hasTable($sequenceTableName)) { $sequenceTable = $database->addTable(array('name' => $sequenceTableName, 'package' => $table->getPackage(), 'schema' => $table->getSchema(), 'namespace' => $table->getNamespace() ? '\\' . $table->getNamespace() : null, 'skipSql' => $table->isSkipSql())); $sequenceTable->addColumn(array('name' => 'table_name', 'type' => 'varchar', 'size' => 32, 'required' => true, 'primaryKey' => true)); $sequenceTable->addColumn(array('name' => $foreignIdColumnName, 'type' => 'integer', 'required' => true, 'primaryKey' => true)); $sequenceTable->addColumn(array('name' => $foreignTableName . '_max_sequence_id', 'type' => 'integer', 'required' => false, 'default' => null)); } }
protected function relateDelegateToMainTable($delegateTable, $mainTable) { $pks = $mainTable->getPrimaryKey(); foreach ($pks as $column) { $mainColumnName = $column->getName(); if (!$delegateTable->hasColumn($mainColumnName)) { $column = clone $column; $column->setAutoIncrement(false); $delegateTable->addColumn($column); } } // Add a one-to-one fk $fk = new ForeignKey(); $fk->setForeignTableCommonName($mainTable->getCommonName()); $fk->setForeignSchemaName($mainTable->getSchema()); $fk->setDefaultJoin('LEFT JOIN'); $fk->setOnDelete(ForeignKey::CASCADE); $fk->setOnUpdate(ForeignKey::NONE); foreach ($pks as $column) { $fk->addReference($column->getName(), $column->getName()); } $delegateTable->addForeignKey($fk); }
protected function addVersionTable() { $table = $this->getTable(); $database = $table->getDatabase(); $versionTableName = $this->getParameter('version_table') ? $this->getParameter('version_table') : $table->getName() . '_version'; if (!$database->hasTable($versionTableName)) { // create the version table $versionTable = $database->addTable(array('name' => $versionTableName, 'phpName' => $this->getVersionTablePhpName(), 'package' => $table->getPackage(), 'schema' => $table->getSchema(), 'namespace' => $table->getNamespace() ? '\\' . $table->getNamespace() : null, 'skipSql' => $table->isSkipSql())); $versionTable->isVersionTable = true; // every behavior adding a table should re-execute database behaviors foreach ($database->getBehaviors() as $behavior) { $behavior->modifyDatabase(); } // copy all the columns foreach ($table->getColumns() as $column) { $columnInVersionTable = clone $column; $columnInVersionTable->clearInheritanceList(); if ($columnInVersionTable->hasReferrers()) { $columnInVersionTable->clearReferrers(); } if ($columnInVersionTable->isAutoincrement()) { $columnInVersionTable->setAutoIncrement(false); } $versionTable->addColumn($columnInVersionTable); } // create the foreign key $fk = new ForeignKey(); $fk->setForeignTableCommonName($table->getCommonName()); $fk->setForeignSchemaName($table->getSchema()); $fk->setOnDelete('CASCADE'); $fk->setOnUpdate(null); $tablePKs = $table->getPrimaryKey(); foreach ($versionTable->getPrimaryKey() as $key => $column) { $fk->addReference($column, $tablePKs[$key]); } $versionTable->addForeignKey($fk); // add the version column to the primary key $versionColumn = $versionTable->getColumn($this->getParameter('version_column')); $versionColumn->setNotNull(true); $versionColumn->setPrimaryKey(true); $this->versionTable = $versionTable; } else { $this->versionTable = $database->getTable($versionTableName); } }
$fkAuthorPost->setOnDelete('CASCADE'); $fkCategoryPost = new ForeignKey('fk_post_has_category'); $fkCategoryPost->addReference('category_id', 'id'); $fkCategoryPost->setForeignTableCommonName('blog_category'); $fkCategoryPost->setRefPhpName('Posts'); $fkCategoryPost->setPhpName('Category'); $fkCategoryPost->setDefaultJoin('Criteria::INNER_JOIN'); $fkCategoryPost->setOnDelete('SETNULL'); $fkPostTag = new ForeignKey('fk_post_has_tags'); $fkPostTag->addReference('post_id', 'id'); $fkPostTag->setForeignTableCommonName('blog_post'); $fkPostTag->setPhpName('Post'); $fkPostTag->setDefaultJoin('Criteria::LEFT_JOIN'); $fkPostTag->setOnDelete('CASCADE'); $fkTagPost = new ForeignKey('fk_tag_has_posts'); $fkTagPost->addReference('tag_id', 'id'); $fkTagPost->setForeignTableCommonName('blog_tag'); $fkTagPost->setPhpName('Tag'); $fkTagPost->setDefaultJoin('Criteria::LEFT_JOIN'); $fkTagPost->setOnDelete('CASCADE'); /* Regular Indexes */ $pageContentFulltextIdx = new Index('page_content_fulltext_idx'); $pageContentFulltextIdx->setColumns([['name' => 'content']]); $pageContentFulltextIdx->addVendorInfo(new VendorInfo('mysql', ['Index_type' => 'FULLTEXT'])); /* Unique Indexes */ $authorUsernameUnique = new Unique('author_password_unique_idx'); $authorUsernameUnique->setColumns([['name' => 'username', 'size' => '8']]); /* Behaviors */ $timestampableBehavior = new TimestampableBehavior(); $timestampableBehavior->setName('timestampable'); $sluggableBehavior = new SluggableBehavior();
public function testCompareModifiedFks() { $db1 = new Database(); $db1->setPlatform($this->platform); $c1 = new Column('Foo'); $c2 = new Column('Bar'); $fk1 = new ForeignKey(); $fk1->addReference($c1, $c2); $t1 = new Table('Baz'); $t1->addForeignKey($fk1); $db1->addTable($t1); $t1->doNaming(); $db2 = new Database(); $db2->setPlatform($this->platform); $c3 = new Column('Foo'); $c4 = new Column('Bar2'); $fk2 = new ForeignKey(); $fk2->addReference($c3, $c4); $t2 = new Table('Baz'); $t2->addForeignKey($fk2); $db2->addTable($t2); $t2->doNaming(); $tc = new TableComparator(); $tc->setFromTable($t1); $tc->setToTable($t2); $nbDiffs = $tc->compareForeignKeys(); $tableDiff = $tc->getTableDiff(); $this->assertEquals(1, $nbDiffs); $this->assertEquals(1, count($tableDiff->getModifiedFks())); $this->assertEquals(array('Baz_FK_1' => array($fk1, $fk2)), $tableDiff->getModifiedFks()); }
public function testCompareSort() { $c1 = new Column('Foo'); $c2 = new Column('Bar'); $c3 = new Column('Baz'); $c4 = new Column('Faz'); $fk1 = new ForeignKey(); $fk1->addReference($c1, $c3); $fk1->addReference($c2, $c4); $t1 = new Table('Baz'); $t1->addForeignKey($fk1); $fk2 = new ForeignKey(); $fk2->addReference($c2, $c4); $fk2->addReference($c1, $c3); $t2 = new Table('Baz'); $t2->addForeignKey($fk2); $this->assertFalse(PropelForeignKeyComparator::computeDiff($fk1, $fk2)); }
public function testToString() { $tableA = new Table('A'); $tableB = new Table('B'); $diff = new TableDiff($tableA, $tableB); $diff->addAddedColumn('id', new Column('id', 'integer')); $diff->addRemovedColumn('category_id', new Column('category_id', 'integer')); $colFoo = new Column('foo', 'integer'); $colBar = new Column('bar', 'integer'); $tableA->addColumn($colFoo); $tableA->addColumn($colBar); $diff->addRenamedColumn($colFoo, $colBar); $columnDiff = new ColumnDiff($colFoo, $colBar); $diff->addModifiedColumn('foo', $columnDiff); $fk = new ForeignKey('category'); $fk->setTable($tableA); $fk->setForeignTableCommonName('B'); $fk->addReference('category_id', 'id'); $fkChanged = clone $fk; $fkChanged->setForeignTableCommonName('C'); $fkChanged->addReference('bla', 'id2'); $fkChanged->setOnDelete('cascade'); $fkChanged->setOnUpdate('cascade'); $diff->addAddedFk('category', $fk); $diff->addModifiedFk('category', $fk, $fkChanged); $diff->addRemovedFk('category', $fk); $index = new Index('test_index'); $index->setTable($tableA); $index->setColumns([$colFoo]); $indexChanged = clone $index; $indexChanged->setColumns([$colBar]); $diff->addAddedIndex('test_index', $index); $diff->addModifiedIndex('test_index', $index, $indexChanged); $diff->addRemovedIndex('test_index', $index); $string = (string) $diff; $expected = ' A: addedColumns: - id removedColumns: - category_id modifiedColumns: A.FOO: modifiedProperties: renamedColumns: foo: bar addedIndices: - test_index removedIndices: - test_index modifiedIndices: - test_index addedFks: - category removedFks: - category modifiedFks: category: localColumns: from ["category_id"] to ["category_id","bla"] foreignColumns: from ["id"] to ["id","id2"] onUpdate: from to CASCADE onDelete: from to CASCADE '; $this->assertEquals($expected, $string); }
private function addSnapshotTable() { $table = $this->getTable(); $primaryKeyColumn = $table->getFirstPrimaryKeyColumn(); $database = $table->getDatabase(); $snapshotTableName = $this->getParameter(self::PARAMETER_SNAPSHOT_TABLE) ?: $this->getDefaultSnapshotTableName(); if ($database->hasTable($snapshotTableName)) { $this->snapshotTable = $database->getTable($snapshotTableName); return; } $snapshotTable = $database->addTable(['name' => $snapshotTableName, 'phpName' => $this->getParameter(self::PARAMETER_SNAPSHOT_PHPNAME), 'package' => $table->getPackage(), 'schema' => $table->getSchema(), 'namespace' => $table->getNamespace() ? '\\' . $table->getNamespace() : null]); $addSnapshotAt = true; $hasTimestampableBehavior = 0 < count(array_filter($database->getBehaviors(), function (Behavior $behavior) { return 'timestampable' === $behavior->getName(); })); if ($hasTimestampableBehavior) { $addSnapshotAt = false; $timestampableBehavior = clone $database->getBehavior('timestampable'); $timestampableBehavior->setParameters(array_merge($timestampableBehavior->getParameters(), ['create_column' => $this->getParameter(self::PARAMETER_SNAPSHOT_AT_COLUMN), 'disable_updated_at' => 'true'])); $snapshotTable->addBehavior($timestampableBehavior); } $snapshotTable->isSnapshotTable = true; $idColumn = $snapshotTable->addColumn(['name' => 'id', 'type' => 'INTEGER']); $idColumn->setAutoIncrement(true); $idColumn->setPrimaryKey(true); $idColumn->setNotNull(true); $columns = $table->getColumns(); foreach ($columns as $column) { if ($column->isPrimaryKey()) { continue; } $columnInSnapshotTable = clone $column; $columnInSnapshotTable->setNotNull(false); if ($columnInSnapshotTable->hasReferrers()) { $columnInSnapshotTable->clearReferrers(); } if ($columnInSnapshotTable->isAutoincrement()) { $columnInSnapshotTable->setAutoIncrement(false); } $snapshotTable->addColumn($columnInSnapshotTable); } $foreignKeyColumn = $snapshotTable->addColumn(['name' => $this->getParameter(self::PARAMETER_REFERENCE_COLUMN), 'type' => $primaryKeyColumn->getType(), 'size' => $primaryKeyColumn->getSize()]); $index = new Index(); $index->setName($this->getParameter(self::PARAMETER_REFERENCE_COLUMN)); if ($primaryKeyColumn->getSize()) { $index->addColumn(['name' => $this->getParameter(self::PARAMETER_REFERENCE_COLUMN), 'size' => $primaryKeyColumn->getSize()]); } else { $index->addColumn(['name' => $this->getParameter(self::PARAMETER_REFERENCE_COLUMN)]); } $snapshotTable->addIndex($index); $foreignKey = new ForeignKey(); $foreignKey->setName(vsprintf('fk_%s_%s', [$snapshotTable->getOriginCommonName(), $this->getParameter(self::PARAMETER_REFERENCE_COLUMN)])); $foreignKey->setOnUpdate('CASCADE'); $foreignKey->setOnDelete('SET NULL'); $foreignKey->setForeignTableCommonName($this->getTable()->getCommonName()); $foreignKey->addReference($foreignKeyColumn, $primaryKeyColumn); $snapshotTable->addForeignKey($foreignKey); if ($this->getParameter(self::PARAMETER_LOG_SNAPSHOT_AT) == 'true' && $addSnapshotAt) { $snapshotTable->addColumn(['name' => $this->getParameter(self::PARAMETER_SNAPSHOT_AT_COLUMN), 'type' => 'TIMESTAMP']); } $indices = $table->getIndices(); foreach ($indices as $index) { $copiedIndex = clone $index; $snapshotTable->addIndex($copiedIndex); } // copy unique indices to indices // see https://github.com/propelorm/Propel/issues/175 for details $unices = $table->getUnices(); foreach ($unices as $unique) { $index = new Index(); $index->setName($unique->getName()); $columns = $unique->getColumns(); foreach ($columns as $columnName) { if ($size = $unique->getColumnSize($columnName)) { $index->addColumn(['name' => $columnName, 'size' => $size]); } else { $index->addColumn(['name' => $columnName]); } } $snapshotTable->addIndex($index); } $behaviors = $database->getBehaviors(); foreach ($behaviors as $behavior) { $behavior->modifyDatabase(); } $this->snapshotTable = $snapshotTable; }
/** * Adds a relation from logTable to origin table. * * @param Table $logTable */ protected function addForeignKey(Table $logTable) { $table = $this->getTable(); if ($table->getForeignKeysReferencingTable($table->getName())) { //if already a foreignKey exist to origin table then don't add a second. return; } // create the foreign key $fk = new ForeignKey(); $fk->setForeignTableCommonName($table->getCommonName()); $fk->setForeignSchemaName($table->getSchema()); $fk->setPhpName('Origin'); $fk->setOnDelete('CASCADE'); $fk->setOnUpdate('CASCADE'); foreach ($table->getPrimaryKey() as $column) { $fk->addReference($logTable->getColumn($column->getName()), $column); } $logTable->addForeignKey($fk); }
protected function addForeignKeys(Table $table) { $database = $table->getDatabase(); $stmt = $this->dbh->query('PRAGMA foreign_key_list("' . $table->getName() . '")'); $lastId = null; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if ($lastId !== $row['id']) { $fk = new ForeignKey(); $onDelete = $row['on_delete']; if ($onDelete && 'NO ACTION' !== $onDelete) { $fk->setOnDelete($onDelete); } $onUpdate = $row['on_update']; if ($onUpdate && 'NO ACTION' !== $onUpdate) { $fk->setOnUpdate($onUpdate); } $foreignTable = $database->getTable($row['table'], true); if (!$foreignTable) { continue; } // we need the reference earlier to build the FK name in Table class to prevent adding FK twice $fk->addReference($row['from'], $row['to']); $fk->setForeignTableCommonName($foreignTable->getCommonName()); $table->addForeignKey($fk); $fk->setForeignTableCommonName($foreignTable->getCommonName()); if ($table->guessSchemaName() != $foreignTable->guessSchemaName()) { $fk->setForeignSchemaName($foreignTable->guessSchemaName()); } $lastId = $row['id']; } else { $fk->addReference($row['from'], $row['to']); } } }
public function testAddSingleColumnReference() { $fk = new ForeignKey(); $fk->addReference($this->getColumnMock('author_id'), $this->getColumnMock('id')); $this->assertFalse($fk->isComposite()); $this->assertCount(1, $fk->getLocalColumns()); $this->assertCount(1, $fk->getForeignColumns()); $this->assertSame('author_id', $fk->getMappedLocalColumn('id')); }
public function startElement($parser, $name, $attributes) { $parentTag = $this->peekCurrentSchemaTag(); if (false === $parentTag) { switch ($name) { case 'database': if ($this->isExternalSchema()) { $this->currentPackage = isset($attributes['package']) ? $attributes['package'] : null; if (null === $this->currentPackage) { $this->currentPackage = $this->defaultPackage; } } else { $this->currDB = $this->schema->addDatabase($attributes); } break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('database' === $parentTag) { switch ($name) { case 'external-schema': $xmlFile = isset($attributes['filename']) ? $attributes['filename'] : null; // 'referenceOnly' attribute is valid in the main schema XML file only, // and it's ignored in the nested external-schemas if (!$this->isExternalSchema()) { $isForRefOnly = isset($attributes['referenceOnly']) ? $attributes['referenceOnly'] : null; $this->isForReferenceOnly = null !== $isForRefOnly ? 'true' === strtolower($isForRefOnly) : true; // defaults to TRUE } if ('/' !== $xmlFile[0]) { $xmlFile = realpath(dirname($this->currentXmlFile) . DIRECTORY_SEPARATOR . $xmlFile); if (!file_exists($xmlFile)) { throw new SchemaException(sprintf('Unknown include external "%s"', $xmlFile)); } } $this->parseFile($xmlFile); break; case 'domain': $this->currDB->addDomain($attributes); break; case 'table': if (!isset($attributes['schema']) && $this->currDB->getSchema() && $this->currDB->getPlatform()->supportsSchemas() && false === strpos($attributes['name'], $this->currDB->getPlatform()->getSchemaDelimiter())) { $attributes['schema'] = $this->currDB->getSchema(); } $this->currTable = $this->currDB->addTable($attributes); if ($this->isExternalSchema()) { $this->currTable->setForReferenceOnly($this->isForReferenceOnly); $this->currTable->setPackage($this->currentPackage); } break; case 'vendor': $this->currVendorObject = $this->currDB->addVendorInfo($attributes); break; case 'behavior': $this->currBehavior = $this->currDB->addBehavior($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('table' === $parentTag) { switch ($name) { case 'column': $this->currColumn = $this->currTable->addColumn($attributes); break; case 'foreign-key': $this->currFK = $this->currTable->addForeignKey($attributes); break; case 'index': $this->currIndex = new Index(); $this->currIndex->setTable($this->currTable); $this->currIndex->loadMapping($attributes); break; case 'unique': $this->currUnique = new Unique(); $this->currUnique->setTable($this->currTable); $this->currUnique->loadMapping($attributes); break; case 'vendor': $this->currVendorObject = $this->currTable->addVendorInfo($attributes); break; case 'id-method-parameter': $this->currTable->addIdMethodParameter($attributes); break; case 'behavior': $this->currBehavior = $this->currTable->addBehavior($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('column' === $parentTag) { switch ($name) { case 'inheritance': $this->currColumn->addInheritance($attributes); break; case 'vendor': $this->currVendorObject = $this->currColumn->addVendorInfo($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('foreign-key' === $parentTag) { switch ($name) { case 'reference': $this->currFK->addReference($attributes); break; case 'vendor': $this->currVendorObject = $this->currUnique->addVendorInfo($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('index' === $parentTag) { switch ($name) { case 'index-column': $this->currIndex->addColumn($attributes); break; case 'vendor': $this->currVendorObject = $this->currIndex->addVendorInfo($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('unique' === $parentTag) { switch ($name) { case 'unique-column': $this->currUnique->addColumn($attributes); break; case 'vendor': $this->currVendorObject = $this->currUnique->addVendorInfo($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ($parentTag == 'behavior') { switch ($name) { case 'parameter': $this->currBehavior->addParameter($attributes); break; default: $this->_throwInvalidTagException($parser, $name); } } elseif ('vendor' === $parentTag) { switch ($name) { case 'parameter': $this->currVendorObject->setParameter($attributes['name'], $attributes['value']); break; default: $this->_throwInvalidTagException($parser, $name); } } else { // it must be an invalid tag $this->_throwInvalidTagException($parser, $name); } $this->pushCurrentSchemaTag($name); }
public function modifyTable() { $table = $this->getTable(); $parentTable = $this->getParentTable(); if ($this->isCopyData()) { // tell the parent table that it has a descendant if (!$parentTable->hasBehavior('concrete_inheritance_parent')) { $parentBehavior = new ConcreteInheritanceParentBehavior(); $parentBehavior->setName('concrete_inheritance_parent'); $parentBehavior->addParameter(array('name' => 'descendant_column', 'value' => $this->getParameter('descendant_column'))); $parentTable->addBehavior($parentBehavior); // The parent table's behavior modifyTable() must be executed before this one $parentBehavior->getTableModifier()->modifyTable(); $parentBehavior->setTableModified(true); } } // Add the columns of the parent table foreach ($parentTable->getColumns() as $column) { if ($column->getName() == $this->getParameter('descendant_column')) { continue; } if ($table->hasColumn($column->getName())) { continue; } $copiedColumn = clone $column; if ($column->isAutoIncrement() && $this->isCopyData()) { $copiedColumn->setAutoIncrement(false); } $table->addColumn($copiedColumn); if ($column->isPrimaryKey() && $this->isCopyData()) { $fk = new ForeignKey(); $fk->setForeignTableCommonName($column->getTable()->getCommonName()); $fk->setForeignSchemaName($column->getTable()->getSchema()); $fk->setOnDelete('CASCADE'); $fk->setOnUpdate(null); $fk->addReference($copiedColumn, $column); $fk->isParentChild = true; $table->addForeignKey($fk); } } // add the foreign keys of the parent table foreach ($parentTable->getForeignKeys() as $fk) { $copiedFk = clone $fk; $copiedFk->setName(''); $copiedFk->setRefPhpName(''); $this->getTable()->addForeignKey($copiedFk); } // add the indices of the parent table foreach ($parentTable->getIndices() as $index) { $copiedIndex = clone $index; $copiedIndex->setName(''); $this->getTable()->addIndex($copiedIndex); } // add the unique indices of the parent table foreach ($parentTable->getUnices() as $unique) { $copiedUnique = clone $unique; $copiedUnique->setName(''); $this->getTable()->addUnique($copiedUnique); } // add the Behaviors of the parent table foreach ($parentTable->getBehaviors() as $behavior) { if ($behavior->getName() == 'concrete_inheritance_parent' || $behavior->getName() == 'concrete_inheritance') { continue; } //validate behavior. If validate behavior already exists, clone only rules from parent if ('validate' === $behavior->getName() && $table->hasBehavior('validate')) { $table->getBehavior('validate')->mergeParameters($behavior->getParameters()); continue; } $copiedBehavior = clone $behavior; $copiedBehavior->setTableModified(false); $this->getTable()->addBehavior($copiedBehavior); } }
public function providerForTestGetForeignKeysDDL() { $db = new Database(); $db->setIdentifierQuoting(true); $table1 = new Table('foo'); $db->addTable($table1); $column1 = new Column('bar_id'); $column1->getDomain()->copy(new Domain('FOOTYPE')); $table1->addColumn($column1); $table2 = new Table('bar'); $db->addTable($table2); $column2 = new Column('id'); $column2->getDomain()->copy(new Domain('BARTYPE')); $table2->addColumn($column2); $fk = new ForeignKey('foo_bar_fk'); $fk->setForeignTableCommonName('bar'); $fk->addReference($column1, $column2); $fk->setOnDelete('CASCADE'); $table1->addForeignKey($fk); $column3 = new Column('baz_id'); $column3->getDomain()->copy(new Domain('BAZTYPE')); $table1->addColumn($column3); $table3 = new Table('baz'); $db->addTable($table3); $column4 = new Column('id'); $column4->getDomain()->copy(new Domain('BAZTYPE')); $table3->addColumn($column4); $fk = new ForeignKey('foo_baz_fk'); $fk->setForeignTableCommonName('baz'); $fk->addReference($column3, $column4); $fk->setOnDelete('SETNULL'); $table1->addForeignKey($fk); return array(array($table1)); }
/** * Load foreign keys for this table. * * @param Table $table The Table model class to add FKs to */ protected function addForeignKeys(Table $table) { // local store to avoid duplicates $foreignKeys = array(); /* @var StatementInterface $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 StatementInterface $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(array('local' => $localReferenceInfo['COLUMN_NAME'], 'foreign' => $foreignReferenceInfo['COLUMN_NAME'])); $table->addForeignKey($fk); $foreignKeys[$row['CONSTRAINT_NAME']] = $fk; } } }
protected function relateI18nTableToMainTable() { $table = $this->getTable(); $i18nTable = $this->i18nTable; $pks = $this->getTable()->getPrimaryKey(); if (count($pks) > 1) { throw new EngineException('The i18n behavior does not support tables with composite primary keys'); } $column = $pks[0]; $i18nColumn = clone $column; if ($this->getParameter('i18n_pk_column')) { // custom i18n table pk name $i18nColumn->setName($this->getParameter('i18n_pk_column')); } else { if (in_array($table->getName(), $i18nTable->getForeignTableNames())) { // custom i18n table pk name not set, but some fk already exists return; } } if (!$i18nTable->hasColumn($i18nColumn->getName())) { $i18nColumn->setAutoIncrement(false); $i18nTable->addColumn($i18nColumn); } $fk = new ForeignKey(); $fk->setForeignTableCommonName($table->getCommonName()); $fk->setForeignSchemaName($table->getSchema()); $fk->setDefaultJoin('LEFT JOIN'); $fk->setOnDelete(ForeignKey::CASCADE); $fk->setOnUpdate(ForeignKey::NONE); $fk->addReference($i18nColumn->getName(), $column->getName()); $i18nTable->addForeignKey($fk); }