/**
  * @param LoggerInterface $logger
  * @param bool            $dryRun
  */
 protected function runActivityLists(LoggerInterface $logger, $dryRun = false)
 {
     // @todo: this workaround should be removed in BAP-9156
     $this->configManager->clear();
     $targetEntities = $this->provider->getTargetEntityClasses(false);
     $toSchema = clone $this->schema;
     $hasSchemaChanges = false;
     foreach ($targetEntities as $targetEntity) {
         $associationName = ExtendHelper::buildAssociationName($targetEntity, ActivityListEntityConfigDumperExtension::ASSOCIATION_KIND);
         $relationTableName = $this->nameGenerator->generateManyToManyJoinTableName(ActivityListEntityConfigDumperExtension::ENTITY_CLASS, $associationName, $targetEntity);
         if (!$toSchema->hasTable($relationTableName)) {
             $hasSchemaChanges = true;
             $this->activityListExtension->addActivityListAssociation($toSchema, $this->metadataHelper->getTableNameByEntityClass($targetEntity));
         }
     }
     if ($hasSchemaChanges) {
         $comparator = new Comparator();
         $platform = $this->connection->getDatabasePlatform();
         $schemaDiff = $comparator->compare($this->schema, $toSchema);
         $queries = $schemaDiff->toSql($platform);
         foreach ($queries as $query) {
             $this->logQuery($logger, $query);
             if (!$dryRun) {
                 $this->connection->executeQuery($query);
             }
         }
     }
 }
Exemplo n.º 2
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $dumpSql = $input->getOption('dump-sql');
     $force = $input->getOption('force');
     $manager = $this->connection->getSchemaManager();
     $this->connection->connect();
     $fromSchema = $manager->createSchema();
     $toSchema = new Schema();
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     $sql = $schemaDiff->toSaveSql($this->connection->getDatabasePlatform());
     if (!$dumpSql && !$force) {
         $output->writeln(sprintf('%d sql statements would be executed. Use `--dump-sql` to show them and `--force` to execute them on the database.', count($sql)));
         return;
     }
     if ($dumpSql) {
         foreach ($sql as $line) {
             $output->writeln($line);
         }
     }
     if ($force) {
         $output->writeln('Updating database schema');
         foreach ($sql as $line) {
             $this->connection->exec($line);
         }
         $output->writeln(sprintf('%d sql statements executed.', count($sql)));
     }
 }
Exemplo n.º 3
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info('Retrieving schema differences...' . PHP_EOL);
     $this->createInMemoryDatabase();
     $defaultSm = $this->getSchemaManager();
     $inMemorySm = $this->getSchemaManager(self::CONNECTION_NAME);
     $fromSchema = $defaultSm->createSchema();
     $toSchema = $inMemorySm->createSchema();
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     $diffStatements = $schemaDiff->toSql($this->getDatabasePlatform());
     if (count($diffStatements) > 0) {
         $this->info('Statements that will be executed:' . PHP_EOL);
         foreach ($diffStatements as $statement) {
             $this->info('- ' . $statement);
         }
     } else {
         $this->info('The schema is up to date with the migrations.' . PHP_EOL);
     }
     if ($this->option('force')) {
         DB::transaction(function () use($diffStatements) {
             foreach ($diffStatements as $statement) {
                 DB::statement($statement);
             }
         });
     } else {
         $this->info(PHP_EOL . 'To apply diff statements use the --force option');
     }
 }
 /**
  * Updates DB Schema. Changes from Diamante only will be applied for current schema. Other bundles updating skips
  * @throws \Exception if there are no changes in entities
  */
 protected function updateDbSchema()
 {
     /**
      * @var $em \Doctrine\ORM\EntityManager
      */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     $event = $em->getEventManager();
     $sm = $em->getConnection()->getSchemaManager();
     $allMetadata = $em->getMetadataFactory()->getAllMetadata();
     $schemaTool = new SchemaTool($em);
     $entitiesMetadata = array($em->getClassMetadata(\Diamante\DeskBundle\Entity\Branch::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Ticket::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Comment::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Attachment::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\BranchEmailConfiguration::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\MessageReference::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\TicketHistory::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\WatcherList::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\TicketTimeline::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Audit::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\AuditField::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Article::getClassName()));
     $event->disableListeners();
     $currentSchema = $sm->createSchema();
     $schemaFromMetadata = $schemaTool->getSchemaFromMetadata($allMetadata);
     $entitiesSchema = $schemaTool->getSchemaFromMetadata($entitiesMetadata);
     $entitiesTables = $entitiesSchema->getTables();
     $entitiesTableName = array_keys($entitiesTables);
     $currentDiamanteSchema = $this->getTargetSchema($currentSchema, $entitiesTableName);
     $diamanteSchemaFromMetadata = $this->getTargetSchema($schemaFromMetadata, $entitiesTableName);
     $comparator = new Comparator();
     $diff = $comparator->compare($currentDiamanteSchema, $diamanteSchemaFromMetadata);
     $toUpdate = $diff->toSql($em->getConnection()->getDatabasePlatform());
     if (empty($toUpdate)) {
         throw new \Exception('No new updates found. DiamanteDesk is up to date!');
     }
     $conn = $em->getConnection();
     foreach ($toUpdate as $sql) {
         $conn->executeQuery($sql);
     }
 }
 /**
  * Updates DB Schema.
  * @throws \Exception if there are no changes in entities
  */
 protected function updateDbSchema()
 {
     /**
      * @var $em \Doctrine\ORM\EntityManager
      */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     $event = $em->getEventManager();
     $sm = $em->getConnection()->getSchemaManager();
     $allMetadata = $em->getMetadataFactory()->getAllMetadata();
     $schemaTool = new SchemaTool($em);
     $entitiesMetadata = array($em->getClassMetadata(ApiUser::getClassName()), $em->getClassMetadata(DiamanteUser::getClassName()));
     $event->disableListeners();
     $currentSchema = $sm->createSchema();
     $schemaFromMetadata = $schemaTool->getSchemaFromMetadata($allMetadata);
     $entitiesSchema = $schemaTool->getSchemaFromMetadata($entitiesMetadata);
     $entitiesTables = $entitiesSchema->getTables();
     $entitiesTableName = array_keys($entitiesTables);
     $currentDiamanteSchema = $this->getTargetSchema($currentSchema, $entitiesTableName);
     $diamanteSchemaFromMetadata = $this->getTargetSchema($schemaFromMetadata, $entitiesTableName);
     $comparator = new Comparator();
     $diff = $comparator->compare($currentDiamanteSchema, $diamanteSchemaFromMetadata);
     $toUpdate = $diff->toSql($em->getConnection()->getDatabasePlatform());
     if (empty($toUpdate)) {
         throw new \Exception('No new updates found. Diamante Api Bundle is up to date!');
     }
     $conn = $em->getConnection();
     foreach ($toUpdate as $sql) {
         $conn->executeQuery($sql);
     }
 }
Exemplo n.º 6
0
 /**
  * @param array $classes
  *
  * @return \Doctrine\DBAL\Schema\SchemaDiff
  * @throws \Doctrine\ORM\ORMException
  */
 protected function getSchemaDiff(array $classes)
 {
     $sm = $this->getConnection()->getSchemaManager();
     $fromSchema = $sm->createSchema();
     $toSchema = $this->getSchemaFromMetadata($classes);
     $comparator = new Comparator();
     return $comparator->compare($fromSchema, $toSchema);
 }
 /**
  * Makes sure oro_session table is up-to-date
  *
  * @param Schema   $schema
  * @param QueryBag $queries
  */
 public function oroSessionTable(Schema $schema, QueryBag $queries)
 {
     if (!$schema->hasTable('oro_session')) {
         $this->createOroSessionTable($schema);
     } else {
         $currentSchema = new Schema([clone $schema->getTable('oro_session')]);
         $requiredSchema = new Schema();
         $this->createOroSessionTable($requiredSchema);
         $comparator = new Comparator();
         $changes = $comparator->compare($currentSchema, $requiredSchema)->toSql($this->platform);
         if ($changes) {
             // force to recreate oro_session table as a result of dropTable/createTable pair
             // might be "ALTER TABLE" query rather than "DROP/CREATE" queries
             $dropTableSql = $comparator->compare($currentSchema, new Schema())->toSql($this->platform);
             $createTableSql = $comparator->compare(new Schema(), $requiredSchema)->toSql($this->platform);
             $queries->addQuery(new SqlMigrationQuery($dropTableSql));
             $queries->addQuery(new SqlMigrationQuery($createTableSql));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getUpdateSchema(Schema $toSchema, $noDrops = false)
 {
     $comparator = new Comparator();
     $sm = $this->conn->getSchemaManager();
     $fromSchema = $sm->createSchema();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     if ($noDrops) {
         return $schemaDiff->toSaveSql($this->platform);
     }
     return $schemaDiff->toSql($this->platform);
 }
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $url = $input->getArgument('url');
     $filename = $input->getArgument('filename');
     $apply = $input->getOption('apply');
     $dbmanager = new DatabaseManager();
     $databaseConfig = $dbmanager->getDatabaseConfig($url);
     $config = $databaseConfig->getConnectionConfig('default');
     $dsn = sprintf('%s:host=%s;port=%d', $config->getDriver(), $config->getHost(), $config->getPort());
     $dbname = $config->getDatabaseName();
     try {
         $pdo = new PDO($dsn, $config->getUsername(), $config->getPassword());
     } catch (\Exception $e) {
         throw new RuntimeException("Can't connect to server with provided address and credentials");
     }
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $stmt = $pdo->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" . $dbname . "'");
     if (!$stmt->fetchColumn()) {
         $output->writeln("<info>Creating database</info>");
         $stmt = $pdo->query("CREATE DATABASE " . $dbname . "");
     } else {
         $output->writeln("<error>Database exists...</error>");
     }
     $loader = LoaderFactory::getInstance()->getLoader($filename);
     $toSchema = $loader->loadSchema($filename);
     $config = new Configuration();
     $connectionParams = array('url' => $dbmanager->getUrlByDatabaseName($url));
     $connection = DriverManager::getConnection($connectionParams, $config);
     $connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
     $output->writeln(sprintf('<info>Loading file <comment>`%s`</comment> into database <comment>`%s`</comment></info>', $filename, $url));
     $schemaManager = $connection->getSchemaManager();
     $fromSchema = $schemaManager->createSchema();
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     $platform = $connection->getDatabasePlatform();
     $queries = $schemaDiff->toSaveSql($platform);
     if (!count($queries)) {
         $output->writeln("<info>No schema changes required</info>");
         return;
     }
     if ($apply) {
         $output->writeln("<info>APPLYING...</info>");
         foreach ($queries as $query) {
             $output->writeln(sprintf('<info>Running: <comment>%s</comment></info>', $query));
             $stmt = $connection->query($query);
         }
     } else {
         $output->writeln("<info>CHANGES: The following SQL statements need to be executed to synchronise the schema (use <comment>--apply</comment>)</info>");
         foreach ($queries as $query) {
             $output->writeln($query);
         }
     }
 }
 /**
  * Update database schema
  * @param bool $sqlOnly
  * @return array|null
  */
 public function updateSchema($sqlOnly = false)
 {
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($this->getCurrentSchema(), $this->getDesiredSchema());
     $sqls = $schemaDiff->toSql($this->getDBALPlatform());
     if ($sqlOnly) {
         return $sqls;
     }
     foreach ($sqls as $sql) {
         $this->connection->exec($sql);
     }
 }
Exemplo n.º 11
0
 /**
  * Update all tables.
  *
  * @param array $metadata
  * @param boolean $saveMode
  * @return array
  */
 public function update(array $metadata, $saveMode = false)
 {
     $fromSchema = $this->schemaManager->createSchema();
     $toSchema = $this->getSchemaFromMetadata($metadata);
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     if ($saveMode) {
         $statements = $schemaDiff->toSaveSql($this->platform);
     } else {
         $statements = $schemaDiff->toSql($this->platform);
     }
     $this->build($statements);
     return $statements;
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $sm = $this->connection->getSchemaManager();
     $schema = $this->schema->getSchema();
     $existing = new DoctrineSchema($sm->listTables(), []);
     $comparator = new Comparator();
     $difference = $comparator->compare($existing, $schema);
     $count = 0;
     if ($statements = $difference->toSql($sm->getDatabasePlatform())) {
         foreach ($statements as $statement) {
             $this->connection->exec($statement);
             $count++;
         }
         $output->writeln(sprintf('Executed <info>%d</info> queries', $count));
     } else {
         $output->writeln('<comment>Schema is already up to date.</comment>');
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $seed = base64_encode(hash('sha512', $input->getArgument('phrase'), true));
     if ($this->getContainer()->has('security.util.secure_random_seed_provider')) {
         $this->getContainer()->get('security.util.secure_random_seed_provider')->updateSeed($seed);
         $output->writeln('The CSPRNG has been initialized successfully.');
     } elseif ($this->getContainer()->has('security.util.secure_random_connection')) {
         if ($input->getOption('force') === $input->getOption('dump-sql')) {
             throw new \InvalidArgumentException('This command needs to be run with one of these options: --force, or --dump-sql');
         }
         $con = $this->getContainer()->get('security.util.secure_random_connection');
         $schema = $this->getContainer()->get('security.util.secure_random_schema');
         $comparator = new Comparator();
         $execute = $input->getOption('force');
         foreach ($comparator->compare($con->getSchemaManager()->createSchema(), $schema)->toSaveSql($con->getDatabasePlatform()) as $sql) {
             if ($execute) {
                 $con->executeQuery($sql);
             } else {
                 $output->writeln($sql);
             }
         }
         $table = $this->getContainer()->getParameter('security.util.secure_random_table');
         $sql = $con->getDatabasePlatform()->getTruncateTableSQL($table);
         if ($execute) {
             $con->executeQuery($sql);
         } else {
             $output->writeln($sql);
         }
         $sql = "INSERT INTO {$table} VALUES (:seed, :updatedAt)";
         if ($execute) {
             $con->executeQuery($sql, array(':seed' => $seed, ':updatedAt' => new \DateTime()), array(':updatedAt' => Type::DATETIME));
         } else {
             $output->writeln($sql);
         }
         if ($execute) {
             $output->writeln('The CSPRNG has been initialized successfully.');
         }
     } else {
         throw new \RuntimeException('No seed provider has been configured under path "security.util.secure_random".');
     }
 }
Exemplo n.º 14
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $schema_file = Schema::getFile($input->getArgument('schema'));
     $dumpSql = true === $input->getOption('dump-sql');
     $force = true === $input->getOption('force');
     if (empty($schema_file)) {
         throw new RuntimeException("Schema file not found.");
     }
     $config = new Config($schema_file);
     $db = $this->getDb($config);
     $toSchema = $config->getSchema($db);
     $comparator = new \Doctrine\DBAL\Schema\Comparator();
     $schemaDiff = $comparator->compare($db->getSchemaManager($db)->createSchema(), $toSchema);
     $sqls = $schemaDiff->toSql($db->getDatabasePlatform());
     if (0 == count($sqls)) {
         $output->writeln('Nothing to update - your database is already in sync with the current entity metadata.');
         return;
     }
     if ($dumpSql && $force) {
         throw new \InvalidArgumentException('You can pass either the --dump-sql or the --force option (but not both simultaneously).');
     }
     if ($dumpSql) {
         $output->writeln(implode(';' . PHP_EOL, $sqls));
     } elseif ($force) {
         $output->writeln('Updating database schema...');
         foreach ($schemaDiff->toSql($db->getDatabasePlatform()) as $sql) {
             $db->exec($sql);
         }
         $output->writeln(sprintf('Database schema updated successfully! "<info>%s</info>" queries were executed', count($sqls)));
     } else {
         $output->writeln('<comment>ATTENTION</comment>: This operation should not be executed in a production environment.');
         $output->writeln('           Use the incremental update to detect changes during development and use');
         $output->writeln('           the SQL provided to manually update your database in production.');
         $output->writeln('');
         $output->writeln(sprintf('The Schema-Tool would execute <info>"%s"</info> queries to update the database.', count($sqls)));
         $output->writeln('Please run the operation by passing one of the following options:');
         $output->writeln(sprintf('    <info>%s --force</info> to execute the command', $this->getName()));
         $output->writeln(sprintf('    <info>%s --dump-sql</info> to dump the SQL statements to the screen', $this->getName()));
     }
 }
Exemplo n.º 15
0
 /**
  * Executes UP method for the given migrations
  *
  * @param Migration[]     $migrations
  * @param bool            $dryRun
  * @throws InvalidNameException if invalid table or column name is detected
  */
 public function executeUp(array $migrations, $dryRun = false)
 {
     $platform = $this->queryExecutor->getConnection()->getDatabasePlatform();
     $sm = $this->queryExecutor->getConnection()->getSchemaManager();
     $fromSchema = $this->createSchemaObject($sm->listTables(), $platform->supportsSequences() ? $sm->listSequences() : [], $sm->createSchemaConfig());
     $queryBag = new QueryBag();
     foreach ($migrations as $migration) {
         $this->logger->notice(sprintf('> %s', get_class($migration)));
         $toSchema = clone $fromSchema;
         $this->setExtensions($migration);
         $migration->up($toSchema, $queryBag);
         $comparator = new Comparator();
         $schemaDiff = $comparator->compare($fromSchema, $toSchema);
         $this->checkTables($schemaDiff, $migration);
         $this->checkIndexes($schemaDiff, $migration);
         $queries = array_merge($queryBag->getPreQueries(), $schemaDiff->toSql($platform), $queryBag->getPostQueries());
         $fromSchema = $toSchema;
         $queryBag->clear();
         foreach ($queries as $query) {
             $this->queryExecutor->execute($query, $dryRun);
         }
     }
 }
 public function testExplicitRename()
 {
     $this->markTestSkipped('evauate concept for explicit field rename with doctrine2 schema tool');
     $em = Setup_SchemaTool::getEntityManager('Inventory');
     $sm = $em->getConnection()->getSchemaManager();
     // NOTE: the DBAL schema is stateless and 'just' describes a schema in a plattform independend way
     //       thus, all schema upgrade is based on schema comparisim
     $fromSchema = $sm->createSchema();
     $toSchema = clone $fromSchema;
     $table = $toSchema->getTable('tine20_inventory_item');
     // workaround -> might have problems?!
     $col = $table->getColumn('id');
     $table->dropColumn('id');
     $table->addColumn('ident', $col->getType()->getName(), $col->toArray());
     // better create, copy, delete?
     // @TODO ask some insider
     //  ? Schema tool can't rename cols, but schema diff with compare (at least with mysql plattform) alters table name correctly when col is renamed in annotations
     // non rename updates are a lot more easy
     $table->changeColumn('name', array('length' => 200));
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     $updateSql = $schemaDiff->toSql($em->getConnection()->getDatabasePlatform());
     //        print_r($updateSql);
 }
Exemplo n.º 17
0
 /**
  * @group DBAL-112
  */
 public function testChangedSequence()
 {
     $schema = new Schema();
     $sequence = $schema->createSequence('baz');
     $schemaNew = clone $schema;
     /* @var $schemaNew Schema */
     $schemaNew->getSequence('baz')->setAllocationSize(20);
     $c = new \Doctrine\DBAL\Schema\Comparator();
     $diff = $c->compare($schema, $schemaNew);
     $this->assertSame($diff->changedSequences[0], $schemaNew->getSequence('baz'));
 }
Exemplo n.º 18
0
 protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection)
 {
     $connection->getConfiguration()->setFilterSchemaAssetsExpression('/^' . $this->config->getSystemValue('dbtableprefix', 'oc_') . '/');
     $sourceSchema = $connection->getSchemaManager()->createSchema();
     // remove tables we don't know about
     /** @var $table \Doctrine\DBAL\Schema\Table */
     foreach ($sourceSchema->getTables() as $table) {
         if (!$targetSchema->hasTable($table->getName())) {
             $sourceSchema->dropTable($table->getName());
         }
     }
     // remove sequences we don't know about
     foreach ($sourceSchema->getSequences() as $table) {
         if (!$targetSchema->hasSequence($table->getName())) {
             $sourceSchema->dropSequence($table->getName());
         }
     }
     $comparator = new Comparator();
     return $comparator->compare($sourceSchema, $targetSchema);
 }
 /**
  * Gets the sequence of SQL statements that need to be performed in order
  * to bring the given class mappings in-synch with the relational schema.
  * If $saveMode is set to true the command is executed in the Database,
  * else SQL is returned.
  *
  * @param array   $classes  The classes to consider.
  * @param boolean $saveMode True for writing to DB, false for SQL string.
  *
  * @return array The sequence of SQL statements.
  */
 public function getUpdateSchemaSql(array $classes, $saveMode = false)
 {
     $sm = $this->em->getConnection()->getSchemaManager();
     $fromSchema = $sm->createSchema();
     $toSchema = $this->getSchemaFromMetadata($classes);
     foreach ($toSchema->getTables() as $table) {
         foreach ($table->getColumns() as $column) {
             if ($column->getAutoincrement()) {
                 continue;
             }
             if (!preg_match('/^(?P<column>(?P<table>.*)_id)$/', $column->getName(), $matches)) {
                 continue;
             }
             $referencedTable = 'oc_' . $matches['table'];
             if (!$toSchema->hasTable($referencedTable)) {
                 continue;
             }
             if ($toSchema->getTable($referencedTable) === $table) {
                 continue;
             }
             $table->addForeignKeyConstraint($toSchema->getTable($referencedTable), [$matches['column']], [$matches['column']]);
         }
     }
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     foreach ($schemaDiff->changedTables as $changedTable) {
         $changedTable->changedColumns = [];
     }
     if ($saveMode) {
         return $schemaDiff->toSaveSql($this->platform);
     }
     return $schemaDiff->toSql($this->platform);
 }
Exemplo n.º 20
0
 /**
  * Gets the sequence of SQL statements that need to be performed in order
  * to bring the given class mappings in-synch with the relational schema.
  * If $saveMode is set to true the command is executed in the Database,
  * else SQL is returned.
  *
  * @param array   $classes  The classes to consider.
  * @param boolean $saveMode True for writing to DB, false for SQL string.
  *
  * @return array The sequence of SQL statements.
  */
 public function getUpdateSchemaSql(array $classes, $saveMode = false)
 {
     $sm = $this->em->getConnection()->getSchemaManager();
     $fromSchema = $sm->createSchema();
     $toSchema = $this->getSchemaFromMetadata($classes);
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $toSchema);
     if ($saveMode) {
         return $schemaDiff->toSaveSql($this->platform);
     }
     return $schemaDiff->toSql($this->platform);
 }
Exemplo n.º 21
0
 /**
  * @param Schema $targetSchema
  * @param \Doctrine\DBAL\Connection $connection
  * @return \Doctrine\DBAL\Schema\SchemaDiff
  * @throws DBALException
  */
 protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection)
 {
     // adjust varchar columns with a length higher then getVarcharMaxLength to clob
     foreach ($targetSchema->getTables() as $table) {
         foreach ($table->getColumns() as $column) {
             if ($column->getType() instanceof StringType) {
                 if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
                     $column->setType(Type::getType('text'));
                     $column->setLength(null);
                 }
             }
         }
     }
     $filterExpression = $this->getFilterExpression();
     $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
     $sourceSchema = $connection->getSchemaManager()->createSchema();
     // remove tables we don't know about
     /** @var $table \Doctrine\DBAL\Schema\Table */
     foreach ($sourceSchema->getTables() as $table) {
         if (!$targetSchema->hasTable($table->getName())) {
             $sourceSchema->dropTable($table->getName());
         }
     }
     // remove sequences we don't know about
     foreach ($sourceSchema->getSequences() as $table) {
         if (!$targetSchema->hasSequence($table->getName())) {
             $sourceSchema->dropSequence($table->getName());
         }
     }
     $comparator = new Comparator();
     return $comparator->compare($sourceSchema, $targetSchema);
 }
Exemplo n.º 22
0
 protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection)
 {
     $sourceSchema = $connection->getSchemaManager()->createSchema();
     // remove tables we don't know about
     /** @var $table \Doctrine\DBAL\Schema\Table */
     foreach ($sourceSchema->getTables() as $table) {
         if (!$targetSchema->hasTable($table->getName())) {
             $sourceSchema->dropTable($table->getName());
         }
     }
     // remove sequences we don't know about
     foreach ($sourceSchema->getSequences() as $table) {
         if (!$targetSchema->hasSequence($table->getName())) {
             $sourceSchema->dropSequence($table->getName());
         }
     }
     $comparator = new Comparator();
     return $comparator->compare($sourceSchema, $targetSchema);
 }
 /**
  * @group DBAL-204
  */
 public function testFqnSchemaComparisionNoSchemaSame()
 {
     $config = new SchemaConfig();
     $config->setName("foo");
     $oldSchema = new Schema(array(), array(), $config);
     $oldSchema->createTable('bar');
     $newSchema = new Schema();
     $newSchema->createTable('bar');
     $c = new Comparator();
     $diff = $c->compare($oldSchema, $newSchema);
     $this->assertEquals(new SchemaDiff(), $c->compare($oldSchema, $newSchema));
 }
Exemplo n.º 24
0
 public function testSequencesCaseInsenstive()
 {
     $schemaA = new Schema();
     $schemaA->createSequence('foo');
     $schemaA->createSequence('BAR');
     $schemaA->createSequence('Baz');
     $schemaA->createSequence('new');
     $schemaB = new Schema();
     $schemaB->createSequence('FOO');
     $schemaB->createSequence('Bar');
     $schemaB->createSequence('baz');
     $schemaB->createSequence('old');
     $c = new Comparator();
     $diff = $c->compare($schemaA, $schemaB);
     $this->assertSchemaSequenceChangeCount($diff, 1, 0, 1);
 }
Exemplo n.º 25
0
 /**
  * @param LoggerInterface $logger
  * @param bool            $dryRun
  */
 protected function addActivityContactColumns(LoggerInterface $logger, $dryRun = false)
 {
     $hasSchemaChanges = false;
     $toSchema = clone $this->schema;
     $contactingActivityClasses = $this->activityContactProvider->getSupportedActivityClasses();
     $entities = $this->getConfigurableEntitiesData($logger);
     foreach ($entities as $entityClassName => $config) {
         if (isset($config['extend']['is_extend'], $config['activity']['activities']) && $config['extend']['is_extend'] == true && $config['activity']['activities'] && array_intersect($contactingActivityClasses, $config['activity']['activities'])) {
             if (isset($config['extend']['schema']['doctrine'][$entityClassName]['table'])) {
                 $tableName = $config['extend']['schema']['doctrine'][$entityClassName]['table'];
             } else {
                 $tableName = $this->metadataHelper->getTableNameByEntityClass($entityClassName);
             }
             // Process only existing tables
             if (!$toSchema->hasTable($tableName)) {
                 continue;
             }
             $table = $toSchema->getTable($tableName);
             $tableColumns = $table->getColumns();
             /**
              * Check if entity already has all needed columns.
              * If at least one is not present we should check and add it.
              */
             if (false === (bool) array_diff(array_keys(ActivityScope::$fieldsConfiguration), array_intersect(array_keys($tableColumns), array_keys(ActivityScope::$fieldsConfiguration)))) {
                 continue;
             }
             foreach (ActivityScope::$fieldsConfiguration as $fieldName => $fieldConfig) {
                 if (!$table->hasColumn($fieldName)) {
                     $hasSchemaChanges = true;
                     $table->addColumn($fieldName, $fieldConfig['type'], ['notnull' => false, OroOptions::KEY => array_merge([ExtendOptionsManager::MODE_OPTION => $fieldConfig['mode']], $fieldConfig['options'])]);
                 }
             }
         }
     }
     if ($hasSchemaChanges) {
         // Run schema related SQLs manually because this query run when diff is already calculated by schema tool
         $comparator = new Comparator();
         $platform = $this->connection->getDatabasePlatform();
         $schemaDiff = $comparator->compare($this->schema, $toSchema);
         foreach ($schemaDiff->toSql($platform) as $query) {
             $this->logQuery($logger, $query);
             if (!$dryRun) {
                 $this->connection->query($query);
             }
         }
     }
 }
Exemplo n.º 26
0
 /**
  * @param Schema           $schema
  * @param AbstractPlatform $platform
  * @param Migration        $migration
  * @param bool             $dryRun
  *
  * @return bool
  */
 public function executeUpMigration(Schema &$schema, AbstractPlatform $platform, Migration $migration, $dryRun = false)
 {
     $result = true;
     $this->logger->notice(sprintf('> %s', get_class($migration)));
     $toSchema = clone $schema;
     $this->setExtensions($migration);
     try {
         $queryBag = new QueryBag();
         $migration->up($toSchema, $queryBag);
         $comparator = new Comparator();
         $schemaDiff = $comparator->compare($schema, $toSchema);
         $this->checkTables($schemaDiff, $migration);
         $this->checkIndexes($schemaDiff, $migration);
         $queries = array_merge($queryBag->getPreQueries(), $schemaDiff->toSql($platform), $queryBag->getPostQueries());
         $schema = $toSchema;
         foreach ($queries as $query) {
             $this->queryExecutor->execute($query, $dryRun);
         }
     } catch (\Exception $ex) {
         $result = false;
         $this->logger->error(sprintf('  ERROR: %s', $ex->getMessage()));
     }
     return $result;
 }
Exemplo n.º 27
0
 protected function getDiffSchema($fromSchema, $toSchema)
 {
     $comparator = new Comparator();
     $diffSchema = $comparator->compare($fromSchema, $toSchema);
     return $diffSchema;
 }
Exemplo n.º 28
0
 /**
  * You can get multiple drops for a FK when a table referenced by a foreign
  * key is deleted, as this FK is referenced twice, once on the orphanedForeignKeys
  * array because of the dropped table, and once on changedTables array. We
  * now check that the key is present once.
  */
 public function testAvoidMultipleDropForeignKey()
 {
     $oldSchema = new Schema();
     $tableForeign = $oldSchema->createTable('foreign');
     $tableForeign->addColumn('id', 'integer');
     $table = $oldSchema->createTable('foo');
     $table->addColumn('fk', 'integer');
     $table->addForeignKeyConstraint($tableForeign, array('fk'), array('id'));
     $newSchema = new Schema();
     $table = $newSchema->createTable('foo');
     $c = new Comparator();
     $diff = $c->compare($oldSchema, $newSchema);
     $this->assertCount(0, $diff->changedTables['foo']->removedForeignKeys);
     $this->assertCount(1, $diff->orphanedForeignKeys);
 }
Exemplo n.º 29
0
 /**
  * @param \Doctrine\DBAL\Schema\Schema              $fromSchema
  * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
  *
  * @return array
  */
 public function getMigrateFromSql(Schema $fromSchema, AbstractPlatform $platform)
 {
     $comparator = new Comparator();
     $schemaDiff = $comparator->compare($fromSchema, $this);
     return $schemaDiff->toSql($platform);
 }
Exemplo n.º 30
0
 /**
  * @group DBAL-669
  */
 public function testComparesNamespaces()
 {
     $comparator = new Comparator();
     $fromSchema = $this->getMock('Doctrine\\DBAL\\Schema\\Schema', array('getNamespaces', 'hasNamespace'));
     $toSchema = $this->getMock('Doctrine\\DBAL\\Schema\\Schema', array('getNamespaces', 'hasNamespace'));
     $fromSchema->expects($this->once())->method('getNamespaces')->will($this->returnValue(array('foo', 'bar')));
     $fromSchema->expects($this->at(0))->method('hasNamespace')->with('bar')->will($this->returnValue(true));
     $fromSchema->expects($this->at(1))->method('hasNamespace')->with('baz')->will($this->returnValue(false));
     $toSchema->expects($this->once())->method('getNamespaces')->will($this->returnValue(array('bar', 'baz')));
     $toSchema->expects($this->at(1))->method('hasNamespace')->with('foo')->will($this->returnValue(false));
     $toSchema->expects($this->at(2))->method('hasNamespace')->with('bar')->will($this->returnValue(true));
     $expected = new SchemaDiff();
     $expected->fromSchema = $fromSchema;
     $expected->newNamespaces = array('baz' => 'baz');
     $expected->removedNamespaces = array('foo' => 'foo');
     $this->assertEquals($expected, $comparator->compare($fromSchema, $toSchema));
 }