Example #1
0
 /**
  * @param Table $table
  * @return bool
  */
 public function isTableNotIgnored(Table $table)
 {
     if (!$this->config->hasTableConfig($table->getName())) {
         return true;
     }
     return !$this->config->getTableConfig($table->getName())->isTableIgnored();
 }
Example #2
0
 /**
  * Get the table's schema object.
  *
  * @param Schema $schema
  * @param string $tableName
  *
  * @return \Doctrine\DBAL\Schema\Table
  */
 public function buildTable(Schema $schema, $tableName)
 {
     $this->table = $schema->createTable($tableName);
     $this->tableName = $this->table->getName();
     $this->addColumns();
     $this->addIndexes();
     $this->setPrimaryKey();
     return $this->table;
 }
Example #3
0
 /**
  * Get the table's schema object.
  *
  * @param Schema $schema
  * @param string $tableName
  * @param string $aliasName
  * @param string $charset
  * @param string $collate
  *
  * @return \Doctrine\DBAL\Schema\Table
  */
 public function buildTable(Schema $schema, $tableName, $aliasName, $charset, $collate)
 {
     $this->table = $schema->createTable($tableName);
     $this->table->addOption('alias', $aliasName);
     $this->table->addOption('charset', $charset);
     $this->table->addOption('collate', $collate);
     $this->aliasName = $aliasName;
     $this->tableName = $this->table->getName();
     $this->addColumns();
     $this->addIndexes();
     $this->setPrimaryKey();
     return $this->table;
 }
 /**
  * @param Table $localTable
  * @param ForeignKeyConstraint $fkConstraint
  */
 public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
 {
     // Append the foreign key constraints SQL
     if ($this->_platform->supportsForeignKeyConstraints()) {
         $this->_createFkConstraintQueries = array_merge($this->_createFkConstraintQueries, (array) $this->_platform->getCreateForeignKeySQL($fkConstraint, $localTable->getName()));
     }
 }
Example #5
0
 /**
  * @param Table $table
  */
 protected function _addTable(Table $table)
 {
     $tableName = strtolower($table->getName());
     if (isset($this->_tables[$tableName])) {
         throw SchemaException::tableAlreadyExists($tableName);
     }
     $this->_tables[$tableName] = $table;
     $table->setSchemaConfig($this->_schemaConfig);
 }
Example #6
0
 /**
  * @param DBALTable $KeyTarget Foreign Key (Column: KeySource Name)
  * @param DBALTable $KeySource Foreign Data (Column: Id)
  */
 public function addForeignKey(DBALTable &$KeyTarget, DBALTable $KeySource)
 {
     if (!$this->Database->hasColumn($KeyTarget->getName(), $KeySource->getName())) {
         $KeyTarget->addColumn($KeySource->getName(), 'bigint');
         if ($this->Database->getPlatform()->supportsForeignKeyConstraints()) {
             $KeyTarget->addForeignKeyConstraint($KeySource, array($KeySource->getName()), array('Id'));
         }
     }
 }
 /**
  * Renames a column
  *
  * @param Schema   $schema
  * @param QueryBag $queries
  * @param Table    $table
  * @param string   $oldColumnName
  * @param string   $newColumnName
  */
 public function renameColumn(Schema $schema, QueryBag $queries, Table $table, $oldColumnName, $newColumnName)
 {
     $column = new Column(['column' => $table->getColumn($oldColumnName)]);
     $column->changeName($newColumnName);
     $diff = new TableDiff($table->getName());
     $diff->renamedColumns = [$oldColumnName => $column];
     $renameQuery = new SqlMigrationQuery($this->platform->getAlterTableSQL($diff));
     $queries->addQuery($renameQuery);
 }
Example #8
0
 public function __construct(SchemaInformation $schema, \Doctrine\DBAL\Schema\Table $table)
 {
     $this->table = $table;
     $this->schema = $schema;
     $this->name = $table->getName();
     foreach ($this->table->getColumns() as $column) {
         $this->columns[$column->getName()] = new ColumnInformation($this, $table, $column);
     }
 }
Example #9
0
 public function describe($namespace) : array
 {
     if (substr($namespace, -1) != "\\") {
         $namespace .= "\\";
     }
     $tableIdentifier = $this->dbalSchemaTable->getName();
     $methods = ['fetchAll' => $this->describeQueryMethod([], $this->describeQuerySelect('*', $tableIdentifier, []))];
     foreach ($this->dbalSchemaTable->getForeignKeys() as $foreignKeyIdentifier => $foreignKey) {
         $words = explode('_', $foreignKeyIdentifier);
         $camelCased = array_map('ucfirst', $words);
         $foreignKeyMethodIdentifier = join('', $camelCased);
         $where = array_map(function ($methodParameter) {
             return $methodParameter . ' = :' . $methodParameter;
         }, $foreignKey->getLocalColumns());
         $query = $this->describeQuerySelect('*', $tableIdentifier, $where);
         $methods["fetchBy" . $foreignKeyMethodIdentifier] = $this->describeQueryMethod($foreignKey->getLocalColumns(), $query);
     }
     return ['identifier' => $namespace . $this->dbalSchemaTable->getName(), 'properties' => ['columns' => array_keys($this->dbalSchemaTable->getColumns())], 'methods' => $methods];
 }
 public function checkForForeignKeySourceTable($columnName)
 {
     // @var Doctrine\DBAL\Schema\ForeignKeyConstraint[]
     $fks = $this->schema->listTableForeignKeys($this->table->getName());
     foreach ($fks as $f) {
         if (in_array($columnName, $f->getColumns())) {
             return $f->getForeignTableName();
         }
     }
     return '';
 }
 /**
  * @param Table $table
  */
 public function acceptTable(Table $table)
 {
     if (in_array($table->getName(), $this->excludedTables)) {
         return;
     }
     $table->addColumn($this->tenantColumnName, $this->tenantColumnType, array('default' => "federation_filtering_value('" . $this->distributionName . "')"));
     $clusteredIndex = $this->getClusteredIndex($table);
     $indexColumns = $clusteredIndex->getColumns();
     $indexColumns[] = $this->tenantColumnName;
     if ($clusteredIndex->isPrimary()) {
         $table->dropPrimaryKey();
         $table->setPrimaryKey($indexColumns);
     } else {
         $table->dropIndex($clusteredIndex->getName());
         $table->addIndex($indexColumns, $clusteredIndex->getName());
         $table->getIndex($clusteredIndex->getName())->addFlag('clustered');
     }
 }
Example #12
0
 /**
  * Add a table object to the schema
  *
  * @param Table $table table object to add
  *
  * @return void
  */
 public function addTable(Table $table)
 {
     //echo '<h2>addTable()</h2>';
     try {
         $name = $table->getName();
         $len = strlen($this->xPrefix);
         if (substr_compare($name, $this->xPrefix, 0, $len) === 0) {
             $name = substr($name, $len);
             if (empty($this->tableList) || in_array($name, $this->tableList)) {
                 $idGeneratorType = 0;
                 // how should we handle this?
                 $newtable = new Table($name, $table->getColumns(), $table->getIndexes(), $table->getForeignKeys(), $idGeneratorType, $table->getOptions());
                 $this->_addTable($newtable);
             }
         }
         //Debug::dump($table);
     } catch (\Exception $e) {
         \Xoops::getInstance()->events()->triggerEvent('core.exception', $e);
         throw $e;
     }
 }
Example #13
0
 /**
  * @param \Doctrine\DBAL\Schema\Table $table
  * @param \SimpleXMLElement $xml
  */
 private static function saveTable($table, $xml)
 {
     $xml->addChild('name', $table->getName());
     $declaration = $xml->addChild('declaration');
     foreach ($table->getColumns() as $column) {
         self::saveColumn($column, $declaration->addChild('field'));
     }
     foreach ($table->getIndexes() as $index) {
         if ($index->getName() == 'PRIMARY') {
             $autoincrement = false;
             foreach ($index->getColumns() as $column) {
                 if ($table->getColumn($column)->getAutoincrement()) {
                     $autoincrement = true;
                 }
             }
             if ($autoincrement) {
                 continue;
             }
         }
         self::saveIndex($index, $declaration->addChild('index'));
     }
 }
Example #14
0
    /**
     * @param \Doctrine\DBAL\Schema\Table $table
     *
     * @return bool|int
     * @todo convert to Blade stub
     */
    protected function _generateModel(Table $table)
    {
        $_props = [];
        $_name = $table->getName();
        $_modelName = $this->_getModelName($_name);
        try {
            foreach ($table->getColumns() as $_column) {
                $_type = $_column->getType()->getName();
                $_type == 'datetime' && ($_type = 'Carbon');
                $_props[] = ' * @property ' . $_type . ' $' . $_column->getName();
            }
            $_payload = ['tableName' => $_name, 'modelName' => $_modelName, 'namespace' => $this->option('namespace') ?: 'App\\Models', 'props' => $_props];
            $_filename = $this->destination . DIRECTORY_SEPARATOR . $_modelName . '.php';
            $_props = implode(PHP_EOL, $_props);
            $_php = <<<TEXT
<?php namespace {$_payload['namespace']};

use Carbon\\Carbon;
use Illuminate\\Database\\Eloquent\\Model;

/**
{$_props}
*/
class {$_payload['modelName']} extends Model
{
    //******************************************************************************
    //* Members
    //******************************************************************************

    protected \$table = '{$_payload['tableName']}';
}
TEXT;
            return file_put_contents($_filename, $_php);
        } catch (\Exception $_ex) {
            $this->_writeln('  * error examining table "' . $_name . '": ' . $_ex->getMessage());
            return false;
        }
    }
Example #15
0
 /**
  * @param \Doctrine\DBAL\Schema\Table $table
  *
  * @return string
  */
 private function createTableLabel(Table $table)
 {
     // Start the table
     $label = '<<TABLE CELLSPACING="0" BORDER="1" ALIGN="LEFT">';
     // The title
     $label .= '<TR><TD BORDER="1" COLSPAN="3" ALIGN="CENTER" BGCOLOR="#fcaf3e"><FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="12">' . $table->getName() . '</FONT></TD></TR>';
     // The attributes block
     foreach ($table->getColumns() as $column) {
         $columnLabel = $column->getName();
         $label .= '<TR>';
         $label .= '<TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec">';
         $label .= '<FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="12">' . $columnLabel . '</FONT>';
         $label .= '</TD><TD BORDER="0" ALIGN="LEFT" BGCOLOR="#eeeeec"><FONT COLOR="#2e3436" FACE="Helvetica" POINT-SIZE="10">' . strtolower($column->getType()) . '</FONT></TD>';
         $label .= '<TD BORDER="0" ALIGN="RIGHT" BGCOLOR="#eeeeec" PORT="col' . $column->getName() . '">';
         if ($table->hasPrimaryKey() && in_array($column->getName(), $table->getPrimaryKey()->getColumns())) {
             $label .= "✷";
         }
         $label .= '</TD></TR>';
     }
     // End the table
     $label .= '</TABLE>>';
     return $label;
 }
Example #16
0
 /**
  * Drop and create a new table.
  *
  * @param Table $table
  */
 public function dropAndCreateTable(Table $table)
 {
     $this->tryMethod('dropTable', $table->getName());
     $this->createTable($table);
 }
Example #17
0
 /**
  * Gets the SQL statement(s) to create a table with the specified name, columns and constraints
  * on this platform.
  *
  * @param string $table The name of the table.
  * @param int $createFlags
  * @return array The sequence of SQL statements.
  */
 public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES)
 {
     if (!is_int($createFlags)) {
         throw new \InvalidArgumentException("Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.");
     }
     if (count($table->getColumns()) == 0) {
         throw DBALException::noColumnsSpecifiedForTable($table->getName());
     }
     $tableName = $table->getQuotedName($this);
     $options = $table->getOptions();
     $options['uniqueConstraints'] = array();
     $options['indexes'] = array();
     $options['primary'] = array();
     if (($createFlags & self::CREATE_INDEXES) > 0) {
         foreach ($table->getIndexes() as $index) {
             /* @var $index Index */
             if ($index->isPrimary()) {
                 $options['primary'] = $index->getColumns();
             } else {
                 $options['indexes'][$index->getName()] = $index;
             }
         }
     }
     $columnSql = array();
     $columns = array();
     foreach ($table->getColumns() as $column) {
         /* @var \Doctrine\DBAL\Schema\Column $column */
         if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
             $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
             $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
             $columnSql = array_merge($columnSql, $eventArgs->getSql());
             if ($eventArgs->isDefaultPrevented()) {
                 continue;
             }
         }
         $columnData = array();
         $columnData['name'] = $column->getQuotedName($this);
         $columnData['type'] = $column->getType();
         $columnData['length'] = $column->getLength();
         $columnData['notnull'] = $column->getNotNull();
         $columnData['fixed'] = $column->getFixed();
         $columnData['unique'] = false;
         // TODO: what do we do about this?
         $columnData['version'] = $column->hasPlatformOption("version") ? $column->getPlatformOption('version') : false;
         if (strtolower($columnData['type']) == "string" && $columnData['length'] === null) {
             $columnData['length'] = 255;
         }
         $columnData['unsigned'] = $column->getUnsigned();
         $columnData['precision'] = $column->getPrecision();
         $columnData['scale'] = $column->getScale();
         $columnData['default'] = $column->getDefault();
         $columnData['columnDefinition'] = $column->getColumnDefinition();
         $columnData['autoincrement'] = $column->getAutoincrement();
         $columnData['comment'] = $this->getColumnComment($column);
         if (in_array($column->getName(), $options['primary'])) {
             $columnData['primary'] = true;
         }
         $columns[$columnData['name']] = $columnData;
     }
     if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
         $options['foreignKeys'] = array();
         foreach ($table->getForeignKeys() as $fkConstraint) {
             $options['foreignKeys'][] = $fkConstraint;
         }
     }
     if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
         $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
         $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
         if ($eventArgs->isDefaultPrevented()) {
             return array_merge($eventArgs->getSql(), $columnSql);
         }
     }
     $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
     if ($this->supportsCommentOnStatement()) {
         foreach ($table->getColumns() as $column) {
             if ($this->getColumnComment($column)) {
                 $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getName(), $this->getColumnComment($column));
             }
         }
     }
     return array_merge($sql, $columnSql);
 }
Example #18
0
 /**
  * Check that a single table's columns and indices are valid.
  *
  * @param Table $fromTable
  * @param Table $toTable
  */
 protected function checkTable(Table $fromTable, Table $toTable)
 {
     $tableName = $fromTable->getName();
     $diff = (new Comparator())->diffTable($fromTable, $toTable);
     if ($diff !== false) {
         $this->diffs[$tableName] = $diff;
     }
 }
 /**
  * @group DBAL-177
  */
 public function testQuoteSchemaPrefixed()
 {
     $table = new Table("`test`.`test`");
     $this->assertEquals("test.test", $table->getName());
     $this->assertEquals("`test`.`test`", $table->getQuotedName(new \Doctrine\DBAL\Platforms\MySqlPlatform()));
 }
Example #20
0
 public function testGetName()
 {
     $table = new Table("foo", array(), array(), array());
     $this->assertEquals("foo", $table->getName());
 }
Example #21
0
 /**
  * Check that a single table's columns and indices are present in the DB.
  *
  * @param Table         $table
  * @param CheckResponse $response
  *
  * @return boolean
  */
 protected function checkTableIntegrity(Table $table, CheckResponse $response)
 {
     $comparator = new Comparator();
     $currentTables = $this->getTableObjects();
     $tableName = $table->getName();
     // Create the users table.
     if (!isset($currentTables[$tableName])) {
         $response->addTitle($tableName, sprintf('Table `%s` is not present.', $tableName));
     } else {
         $diff = $comparator->diffTable($currentTables[$tableName], $table);
         $this->addResponseDiff($tableName, $diff, $response);
     }
     // If we are using the debug logger, log the diffs
     foreach ($response->getDiffDetails() as $diff) {
         $this->app['logger.system']->debug('Database update required', $diff);
     }
     // If a table still has messages return a false to flick the validity check
     return !$response->hasResponses();
 }
Example #22
0
 /**
  * Gathers columns and fk constraints that are required for one part of relationship.
  *
  * @param array         $joinColumns
  * @param Table         $theJoinTable
  * @param ClassMetadata $class
  * @param array         $mapping
  * @param array         $primaryKeyColumns
  * @param array         $addedFks
  * @param array         $blacklistedFks
  *
  * @return void
  *
  * @throws \Doctrine\ORM\ORMException
  */
 private function gatherRelationJoinColumns($joinColumns, $theJoinTable, $class, $mapping, &$primaryKeyColumns, &$addedFks, &$blacklistedFks)
 {
     $localColumns = array();
     $foreignColumns = array();
     $fkOptions = array();
     $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform);
     $uniqueConstraints = array();
     foreach ($joinColumns as $joinColumn) {
         list($definingClass, $referencedFieldName) = $this->getDefiningClass($class, $joinColumn['referencedColumnName']);
         if (!$definingClass) {
             throw new \Doctrine\ORM\ORMException("Column name `" . $joinColumn['referencedColumnName'] . "` referenced for relation from " . $mapping['sourceEntity'] . " towards " . $mapping['targetEntity'] . " does not exist.");
         }
         $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
         $quotedRefColumnName = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $class, $this->platform);
         $primaryKeyColumns[] = $quotedColumnName;
         $localColumns[] = $quotedColumnName;
         $foreignColumns[] = $quotedRefColumnName;
         if (!$theJoinTable->hasColumn($quotedColumnName)) {
             // Only add the column to the table if it does not exist already.
             // It might exist already if the foreign key is mapped into a regular
             // property as well.
             $fieldMapping = $definingClass->getFieldMapping($referencedFieldName);
             $columnDef = null;
             if (isset($joinColumn['columnDefinition'])) {
                 $columnDef = $joinColumn['columnDefinition'];
             } elseif (isset($fieldMapping['columnDefinition'])) {
                 $columnDef = $fieldMapping['columnDefinition'];
             }
             $columnOptions = array('notnull' => false, 'columnDefinition' => $columnDef);
             if (isset($joinColumn['nullable'])) {
                 $columnOptions['notnull'] = !$joinColumn['nullable'];
             }
             if (isset($fieldMapping['options'])) {
                 $columnOptions['options'] = $fieldMapping['options'];
             }
             if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) {
                 $columnOptions['length'] = $fieldMapping['length'];
             } elseif ($fieldMapping['type'] == "decimal") {
                 $columnOptions['scale'] = $fieldMapping['scale'];
                 $columnOptions['precision'] = $fieldMapping['precision'];
             }
             $theJoinTable->addColumn($quotedColumnName, $fieldMapping['type'], $columnOptions);
         }
         if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) {
             $uniqueConstraints[] = array('columns' => array($quotedColumnName));
         }
         if (isset($joinColumn['onDelete'])) {
             $fkOptions['onDelete'] = $joinColumn['onDelete'];
         }
     }
     // Prefer unique constraints over implicit simple indexes created for foreign keys.
     // Also avoids index duplication.
     foreach ($uniqueConstraints as $indexName => $unique) {
         $theJoinTable->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
     }
     $compositeName = $theJoinTable->getName() . '.' . implode('', $localColumns);
     if (isset($addedFks[$compositeName]) && ($foreignTableName != $addedFks[$compositeName]['foreignTableName'] || 0 < count(array_diff($foreignColumns, $addedFks[$compositeName]['foreignColumns'])))) {
         foreach ($theJoinTable->getForeignKeys() as $fkName => $key) {
             if (0 === count(array_diff($key->getLocalColumns(), $localColumns)) && ($key->getForeignTableName() != $foreignTableName || 0 < count(array_diff($key->getForeignColumns(), $foreignColumns)))) {
                 $theJoinTable->removeForeignKey($fkName);
                 break;
             }
         }
         $blacklistedFks[$compositeName] = true;
     } elseif (!isset($blacklistedFks[$compositeName])) {
         $addedFks[$compositeName] = array('foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns);
         $theJoinTable->addUnnamedForeignKeyConstraint($foreignTableName, $localColumns, $foreignColumns, $fkOptions);
     }
 }
 protected function renameOneToManyExtendField(Schema $schema, QueryBag $queries, Table $table, $associationName, $targetEntityClassName, EntityMetadataHelper $entityMetadataHelper)
 {
     $entityClassName = $entityMetadataHelper->getEntityClassByTableName($table->getName());
     $targetTableName = $entityMetadataHelper->getTableNameByEntityClass($targetEntityClassName);
     if ($schema->hasTable($targetTableName)) {
         $targetTable = $schema->getTable($targetTableName);
         $oldTargetColumnName = sprintf('field_%s_%s_id', strtolower(ExtendHelper::getShortClassName($entityClassName)), $associationName);
         if ($targetTable->hasColumn($oldTargetColumnName)) {
             $newTargetColumnName = $this->nameGenerator->generateOneToManyRelationColumnName($entityClassName, $associationName);
             $oldIndexName = $this->nameGenerator->generateIndexName($targetTableName, [$oldTargetColumnName], false, true);
             if ($targetTable->hasIndex($oldIndexName)) {
                 $targetTable->dropIndex($oldIndexName);
             }
             $oldForeignKeyName = $this->nameGenerator->generateForeignKeyConstraintName($targetTableName, [$oldTargetColumnName], true);
             if ($targetTable->hasForeignKey($oldForeignKeyName)) {
                 $targetTable->removeForeignKey($oldForeignKeyName);
             }
             $this->renameExtension->renameColumn($schema, $queries, $targetTable, $oldTargetColumnName, $newTargetColumnName);
             $this->renameExtension->addIndex($schema, $queries, $targetTable->getName(), [$newTargetColumnName]);
             $this->renameExtension->addForeignKeyConstraint($schema, $queries, $targetTable->getName(), $table->getName(), [$newTargetColumnName], $table->getPrimaryKeyColumns(), ['onDelete' => 'SET NULL']);
         }
     }
 }
Example #24
0
 /**
  * Add a foreign key constraint with a given name
  *
  * @param string $name
  * @param Table $foreignTable
  * @param array $localColumns
  * @param array $foreignColumns
  * @param array $options
  * @return Table
  */
 public function addNamedForeignKeyConstraint($name, $foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = array())
 {
     if ($foreignTable instanceof Table) {
         $foreignTableName = $foreignTable->getName();
         foreach ($foreignColumnNames as $columnName) {
             if (!$foreignTable->hasColumn($columnName)) {
                 throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
             }
         }
     } else {
         $foreignTableName = $foreignTable;
     }
     foreach ($localColumnNames as $columnName) {
         if (!$this->hasColumn($columnName)) {
             throw SchemaException::columnDoesNotExist($columnName, $this->_name);
         }
     }
     $constraint = new ForeignKeyConstraint($localColumnNames, $foreignTableName, $foreignColumnNames, $name, $options);
     $this->_addForeignKeyConstraint($constraint);
     return $this;
 }
 /**
  * @return string
  */
 public function getLocalTableName()
 {
     return $this->_localTable->getName();
 }
 public function acceptTable(Table $table)
 {
     $this->addViolation('Table ' . $table->getName(), $this->isReservedWord($table->getName()));
 }
Example #27
0
 /**
  * @param \Doctrine\DBAL\Schema\Table $table
  *
  * @return \Doctrine\DBAL\Schema\Index
  *
  * @throws \RuntimeException
  */
 private function getClusteredIndex($table)
 {
     foreach ($table->getIndexes() as $index) {
         if ($index->isPrimary() && !$index->hasFlag('nonclustered')) {
             return $index;
         } elseif ($index->hasFlag('clustered')) {
             return $index;
         }
     }
     throw new \RuntimeException("No clustered index found on table " . $table->getName());
 }
Example #28
0
 /**
  * Returns the difference between the tables $table1 and $table2.
  *
  * If there are no differences this method returns the boolean false.
  *
  * @param \Doctrine\DBAL\Schema\Table $table1
  * @param \Doctrine\DBAL\Schema\Table $table2
  *
  * @return boolean|\Doctrine\DBAL\Schema\TableDiff
  */
 public function diffTable(Table $table1, Table $table2)
 {
     $changes = 0;
     $tableDifferences = new TableDiff($table1->getName());
     $tableDifferences->fromTable = $table1;
     $table1Columns = $table1->getColumns();
     $table2Columns = $table2->getColumns();
     /* See if all the fields in table 1 exist in table 2 */
     foreach ($table2Columns as $columnName => $column) {
         if (!$table1->hasColumn($columnName)) {
             $tableDifferences->addedColumns[$columnName] = $column;
             $changes++;
         }
     }
     /* See if there are any removed fields in table 2 */
     foreach ($table1Columns as $columnName => $column) {
         // See if column is removed in table 2.
         if (!$table2->hasColumn($columnName)) {
             $tableDifferences->removedColumns[$columnName] = $column;
             $changes++;
             continue;
         }
         // See if column has changed properties in table 2.
         $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
         if (!empty($changedProperties)) {
             $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
             $columnDiff->fromColumn = $column;
             $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
             $changes++;
         }
     }
     // #BUG-2317 Avoid column renaming when both enable and disable different modules
     // $this->detectColumnRenamings($tableDifferences);
     $table1Indexes = $table1->getIndexes();
     $table2Indexes = $table2->getIndexes();
     foreach ($table2Indexes as $index2Name => $index2Definition) {
         foreach ($table1Indexes as $index1Name => $index1Definition) {
             if ($this->diffIndex($index1Definition, $index2Definition) === false) {
                 /*if ( ! $index1Definition->isPrimary() && $index1Name != $index2Name) {
                       $tableDifferences->renamedIndexes[$index1Name] = $index2Definition;
                       $changes++;
                   }*/
                 unset($table1Indexes[$index1Name]);
                 unset($table2Indexes[$index2Name]);
             } else {
                 if ($index1Name == $index2Name) {
                     $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
                     unset($table1Indexes[$index1Name]);
                     unset($table2Indexes[$index2Name]);
                     $changes++;
                 }
             }
         }
     }
     foreach ($table1Indexes as $index1Name => $index1Definition) {
         $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
         $changes++;
     }
     foreach ($table2Indexes as $index2Name => $index2Definition) {
         $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
         $changes++;
     }
     $fromFkeys = $table1->getForeignKeys();
     $toFkeys = $table2->getForeignKeys();
     foreach ($fromFkeys as $key1 => $constraint1) {
         foreach ($toFkeys as $key2 => $constraint2) {
             if ($this->diffForeignKey($constraint1, $constraint2) === false) {
                 unset($fromFkeys[$key1]);
                 unset($toFkeys[$key2]);
             } else {
                 if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
                     $tableDifferences->changedForeignKeys[] = $constraint2;
                     $changes++;
                     unset($fromFkeys[$key1]);
                     unset($toFkeys[$key2]);
                 }
             }
         }
     }
     foreach ($fromFkeys as $constraint1) {
         $tableDifferences->removedForeignKeys[] = $constraint1;
         $changes++;
     }
     foreach ($toFkeys as $constraint2) {
         $tableDifferences->addedForeignKeys[] = $constraint2;
         $changes++;
     }
     return $changes ? $tableDifferences : false;
 }
Example #29
0
 /**
  * Load the metadata for a table.
  *
  * @param Table $table
  */
 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->schemaManager->getKeyForTable($tblName);
     $this->metadata[$className] = [];
     $this->metadata[$className]['identifier'] = $table->getPrimaryKey();
     $this->metadata[$className]['table'] = $table->getName();
     $this->metadata[$className]['boltname'] = $contentKey;
     foreach ($table->getColumns() as $colName => $column) {
         $mapping = ['fieldname' => $colName, 'type' => $column->getType()->getName(), 'fieldtype' => $this->getFieldTypeFor($table->getName(), $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) {
         $this->setRelations($contentKey, $className, $table);
         $this->setTaxonomies($contentKey, $className, $table);
         $this->setTemplatefields($contentKey, $className, $table);
         $this->setRepeaters($contentKey, $className, $table);
     }
     foreach ($this->getAliases() as $alias => $table) {
         if (array_key_exists($table, $this->metadata)) {
             $this->metadata[$alias] = $this->metadata[$table];
         }
     }
 }
Example #30
0
 /**
  * Check the migration of a table on a copy so we can detect errors before messing with the real table
  *
  * @param \Doctrine\DBAL\Schema\Table $table
  * @throws \OC\DB\MigrationException
  */
 protected function checkTableMigrate(Table $table)
 {
     $name = $table->getName();
     $tmpName = $this->generateTemporaryTableName($name);
     $this->copyTable($name, $tmpName);
     //create the migration schema for the temporary table
     $tmpTable = $this->renameTableSchema($table, $tmpName);
     $schemaConfig = new SchemaConfig();
     $schemaConfig->setName($this->connection->getDatabase());
     $schema = new Schema(array($tmpTable), array(), $schemaConfig);
     try {
         $this->applySchema($schema);
         $this->dropTable($tmpName);
     } catch (DBALException $e) {
         // pgsql needs to commit it's failed transaction before doing anything else
         if ($this->connection->isTransactionActive()) {
             $this->connection->commit();
         }
         $this->dropTable($tmpName);
         throw new MigrationException($table->getName(), $e->getMessage());
     }
 }