С версии: 2.0
Автор: Jonathan H. Wage (jonwage@gmail.com)
Пример #1
1
 public function indexAction()
 {
     $container = $this->container;
     $conn = $this->get('doctrine')->getConnection();
     $dir = $container->getParameter('doctrine_migrations.dir_name');
     if (!file_exists($dir)) {
         mkdir($dir, 0777, true);
     }
     $configuration = new Configuration($conn);
     $configuration->setMigrationsNamespace($container->getParameter('doctrine_migrations.namespace'));
     $configuration->setMigrationsDirectory($dir);
     $configuration->registerMigrationsFromDirectory($dir);
     $configuration->setName($container->getParameter('doctrine_migrations.name'));
     $configuration->setMigrationsTableName($container->getParameter('doctrine_migrations.table_name'));
     $versions = $configuration->getMigrations();
     foreach ($versions as $version) {
         $migration = $version->getMigration();
         if ($migration instanceof ContainerAwareInterface) {
             $migration->setContainer($container);
         }
     }
     $migration = new Migration($configuration);
     $migrated = $migration->migrate();
     // ...
 }
Пример #2
0
 public function generateMigrationSql($return, &$hasMigrations)
 {
     $config = \Config::getInstance();
     $modules = $config->getActiveModules();
     $connection = $GLOBALS['container']['doctrine.connection.default'];
     $output = new OutputWriter();
     foreach ($modules as $module) {
         $path = sprintf('%s/system/modules/%s/migrations', TL_ROOT, $module);
         if (is_dir($path)) {
             $namespace = preg_split('~[\\-_]~', $module);
             $namespace = array_map('ucfirst', $namespace);
             $namespace = implode('', $namespace);
             $configuration = new Configuration($connection, $output);
             $configuration->setName($module);
             $configuration->setMigrationsNamespace('DoctrineMigrations\\' . $namespace);
             $configuration->setMigrationsDirectory($path);
             $configuration->registerMigrationsFromDirectory($path);
             $migration = new Migration($configuration);
             $versions = $migration->getSql();
             if (count($versions)) {
                 foreach ($versions as $version => $queries) {
                     if (count($queries)) {
                         $_SESSION['TL_CONFIRM'][] = sprintf($GLOBALS['TL_LANG']['doctrine']['migration'], $module, $version);
                         $hasMigrations = true;
                         $return = $this->appendQueries($return, $queries);
                     }
                 }
             }
         }
     }
     return $return;
 }
Пример #3
0
 /**
  * @param Connection $connection
  * @param AppKernel  $kernel
  *
  * @throws \Claroline\MigrationBundle\Migrator\InvalidDirectionException
  * @throws \Claroline\MigrationBundle\Migrator\InvalidVersionException
  * @throws \Doctrine\DBAL\Migrations\MigrationException
  */
 protected function migrateBadgeTables(Connection $connection, AppKernel $kernel)
 {
     $portfolioBundle = $this->container->get('claroline.persistence.object_manager')->getRepository('ClarolineCoreBundle:Plugin')->findBy(array('vendorName' => 'Icap', 'bundleName' => 'PortfolioBundle'));
     $portfolioBundle = count($portfolioBundle) === 1 ? true : false;
     if (!$portfolioBundle && $connection->getSchemaManager()->tablesExist(['icap__portfolio_widget_badges'])) {
         $this->log('Deleting portfolios badges tables...');
         $connection->getSchemaManager()->dropTable('icap__portfolio_widget_badges_badge');
         $connection->getSchemaManager()->dropTable('icap__portfolio_widget_badges');
         $this->log('Portfolios badges tables deleted.');
     }
     if ($portfolioBundle && !$connection->getSchemaManager()->tablesExist(['icap__portfolio_widget_badges'])) {
         $badgeBundle = $kernel->getBundle('IcapBadgeBundle');
         $this->log('Executing migrations for portfolio interaction');
         $migrationsDir = "{$badgeBundle->getPath()}/Installation/Migrations";
         $migrationsName = "{$badgeBundle->getName()} migration";
         $migrationsNamespace = "{$badgeBundle->getNamespace()}\\Installation\\Migrations";
         $migrationsTableName = 'doctrine_' . strtolower($badgeBundle->getName()) . '_versions';
         $config = new Configuration($connection);
         $config->setName($migrationsName);
         $config->setMigrationsDirectory($migrationsDir);
         $config->setMigrationsNamespace($migrationsNamespace);
         $config->setMigrationsTableName($migrationsTableName);
         $config->registerMigrationsFromDirectory($migrationsDir);
         $migration = new Migration($config);
         $executedQueriesNumber = $migration->migrate('20150929141509');
         $this->log(sprintf('%d queries executed', $executedQueriesNumber));
     }
 }
Пример #4
0
 /**
  * Executes a bundle migration to a specified version. Version can be
  * either an explicit version string or Migrator::VERSION_* class constant.
  * Direction must be a Migrator::DIRECTION_* class constant.
  *
  * @param \Symfony\Component\HttpKernel\Bundle\Bundle   $bundle
  * @param string                                        $version
  * @param string                                        $direction
  *
  * @return array The sql queries executed during the migration
  *
  * @throws InvalidVersionException      if the specified version is not valid
  * @throws InvalidDirectionException    if the target version is not in the specified direction
  */
 public function migrate(Bundle $bundle, $version, $direction)
 {
     $config = $this->getConfiguration($bundle);
     $currentVersion = $config->getCurrentVersion();
     $migration = new Migration($config);
     if ($version === self::VERSION_FARTHEST) {
         return $migration->migrate($direction === self::DIRECTION_UP ? null : '0');
     } elseif ($version === self::VERSION_NEAREST) {
         $availableVersions = $config->getAvailableVersions($bundle);
         array_unshift($availableVersions, '0');
         $nearestVersion = false;
         if ($direction === self::DIRECTION_DOWN) {
             $availableVersions = array_reverse($availableVersions);
         }
         foreach ($availableVersions as $index => $availableVersion) {
             if ($currentVersion === $availableVersion) {
                 $nearestVersionIndex = ++$index;
                 if (isset($availableVersions[$nearestVersionIndex])) {
                     $nearestVersion = $availableVersions[$nearestVersionIndex];
                 }
                 break;
             }
         }
         return $nearestVersion === false ? array() : $migration->migrate($nearestVersion);
     } elseif (!is_numeric($version)) {
         throw new InvalidVersionException($version);
     } elseif ($version > $currentVersion && $direction === self::DIRECTION_DOWN || $version < $currentVersion && $direction === self::DIRECTION_UP) {
         throw new InvalidDirectionException($direction);
     } else {
         return $migration->migrate($version);
     }
 }
Пример #5
0
 /**
  * @see http://jamesmcfadden.co.uk/database-unit-testing-with-doctrine-2-and-phpunit/
  */
 public function getConnection()
 {
     // 別途 Application を生成しているような箇所があると動作しないので注意
     $app = EccubeTestCase::createApplication();
     // Get an instance of your entity manager
     $entityManager = $app['orm.em'];
     // Retrieve PDO instance
     $pdo = $entityManager->getConnection()->getWrappedConnection();
     // Clear Doctrine to be safe
     $entityManager->clear();
     // Schema Tool to process our entities
     $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager);
     $classes = $entityManager->getMetaDataFactory()->getAllMetaData();
     // Drop all classes and re-build them for each test case
     $tool->dropSchema($classes);
     $tool->createSchema($classes);
     $config = new Configuration($app['db']);
     $config->setMigrationsNamespace('DoctrineMigrations');
     $migrationDir = __DIR__ . '/../../../src/Eccube/Resource/doctrine/migration';
     $config->setMigrationsDirectory($migrationDir);
     $config->registerMigrationsFromDirectory($migrationDir);
     $migration = new Migration($config);
     $migration->migrate(null, false);
     self::$app = $app;
     // Pass to PHPUnit
     return $this->createDefaultDBConnection($pdo, 'db_name');
 }
Пример #6
0
 /**
  * データベースを初期化する.
  *
  * データベースを初期化し、マイグレーションを行なう.
  * 全てのデータが初期化されるため注意すること.
  *
  * @link http://jamesmcfadden.co.uk/database-unit-testing-with-doctrine-2-and-phpunit/
  */
 public function initializeDatabase()
 {
     // Get an instance of your entity manager
     $entityManager = $this->app['orm.em'];
     // Retrieve PDO instance
     $pdo = $entityManager->getConnection()->getWrappedConnection();
     // Clear Doctrine to be safe
     $entityManager->clear();
     // Schema Tool to process our entities
     $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager);
     $classes = $entityManager->getMetaDataFactory()->getAllMetaData();
     // Drop all classes and re-build them for each test case
     $tool->dropSchema($classes);
     $tool->createSchema($classes);
     $config = new Configuration($this->app['db']);
     $config->setMigrationsNamespace('DoctrineMigrations');
     $migrationDir = __DIR__ . '/../../../src/Eccube/Resource/doctrine/migration';
     $config->setMigrationsDirectory($migrationDir);
     $config->registerMigrationsFromDirectory($migrationDir);
     $migration = new Migration($config);
     $migration->migrate(null, false);
     // 通常は eccube_install.sh で追加されるデータを追加する
     $sql = "INSERT INTO dtb_member (member_id, login_id, password, salt, work, del_flg, authority, creator_id, rank, update_date, create_date,name,department) VALUES (2, 'admin', 'test', 'test', 1, 0, 0, 1, 1, current_timestamp, current_timestamp,'管理者','EC-CUBE SHOP')";
     $stmt = $pdo->prepare($sql);
     $stmt->execute();
     $sql = "INSERT INTO dtb_base_info (id, shop_name, email01, email02, email03, email04, update_date, option_product_tax_rule) VALUES (1, 'SHOP_NAME', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', current_timestamp, 0)";
     $stmt = $pdo->prepare($sql);
     $stmt->execute();
 }
Пример #7
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $version = $input->getArgument('version');
     $configuration = $this->getMigrationConfiguration($input, $output);
     $migration = new Migration($configuration);
     $this->outputHeader($configuration, $output);
     if ($path = $input->getOption('write-sql')) {
         $path = is_bool($path) ? getcwd() : $path;
         $migration->writeSqlFile($path, $version);
     } else {
         $dryRun = $input->getOption('dry-run') ? true : false;
         if ($dryRun === true) {
             $migration->migrate($version, true);
         } else {
             $noInteraction = $input->getOption('no-interaction') ? true : false;
             if ($noInteraction === true) {
                 $migration->migrate($version, $dryRun);
             } else {
                 $confirmation = $this->getHelper('dialog')->askConfirmation($output, '<question>WARNING! You are about to execute a database migration that could result in schema changes and data lost. Are you sure you wish to continue? (y/n)</question>', false);
                 if ($confirmation === true) {
                     $migration->migrate($version, $dryRun);
                 } else {
                     $output->writeln('<error>Migration cancelled!</error>');
                 }
             }
         }
     }
 }
 /**
  * @Route("/setup/_int_migrate_schema")
  */
 public function intMigrateSchemaAction()
 {
     $response = array("success" => true, "errors" => [], "message" => "Database schema successfully migrated");
     $configuration = $this->getMigrationConfiguration();
     $migration = new Migration($configuration);
     $version = $configuration->getLatestVersion();
     $migration->migrate($version);
     return new JsonResponse($response);
 }
Пример #9
0
 private function runMigrations()
 {
     $errors = [];
     $migration = new Migration($this->getMigrationConfig($errors));
     try {
         $migration->migrate();
     } catch (MigrationException $e) {
     }
     return $errors;
 }
Пример #10
0
 private function runMigrations(Connection $db)
 {
     $container = $this->getContainer();
     /** @var MigrationsConfiguration $migrationsConfig */
     $migrationsConfig = $container->getByType(MigrationsConfiguration::class);
     $migrationsConfig->__construct($container, $db);
     // necessary to disable output
     $migrationsConfig->registerMigrationsFromDirectory($migrationsConfig->getMigrationsDirectory());
     $migration = new Migration($migrationsConfig);
     $migration->migrate($migrationsConfig->getLatestVersion());
 }
 /**
  * @Route("/setup/_int_migrate_schema")
  */
 public function intMigrateSchemaAction(Request $request)
 {
     if (!$this->ensureAuthKey($request)) {
         return $this->getAuthKeyErrorResponse();
     }
     $response = ['success' => true, 'errors' => [], 'message' => 'Database schema successfully migrated'];
     $configuration = $this->getMigrationConfiguration();
     $migration = new Migration($configuration);
     $version = $configuration->getLatestVersion();
     $migration->migrate($version);
     return new JsonResponse($response);
 }
Пример #12
0
 public function migrationSchema($app, $migrationFilePath, $pluginCode, $version = null)
 {
     $config = new Configuration($app['db']);
     $config->setMigrationsNamespace('DoctrineMigrations');
     $config->setMigrationsDirectory($migrationFilePath);
     $config->registerMigrationsFromDirectory($migrationFilePath);
     $config->setMigrationsTableName(self::MIGRATION_TABLE_PREFIX . $pluginCode);
     $migration = new Migration($config);
     // null 又は 'last' を渡すと最新バージョンまでマイグレートする
     // 0か'first'を渡すと最初に戻る
     $migration->migrate($version, false);
 }
Пример #13
0
 /**
  * データベースを初期化する.
  *
  * データベースを初期化し、マイグレーションを行なう.
  * 全てのデータが初期化されるため注意すること.
  *
  * @link http://jamesmcfadden.co.uk/database-unit-testing-with-doctrine-2-and-phpunit/
  */
 public function initializeDatabase()
 {
     // Get an instance of your entity manager
     $entityManager = $this->app['orm.em'];
     // Retrieve PDO instance
     $pdo = $entityManager->getConnection()->getWrappedConnection();
     // Clear Doctrine to be safe
     $entityManager->getConnection()->getConfiguration()->setSQLLogger(null);
     $entityManager->clear();
     gc_collect_cycles();
     // Schema Tool to process our entities
     $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager);
     $classes = $entityManager->getMetaDataFactory()->getAllMetaData();
     // Drop all classes and re-build them for each test case
     $tool->dropSchema($classes);
     $tool->createSchema($classes);
     $config = new Configuration($this->app['db']);
     $config->setMigrationsNamespace('DoctrineMigrations');
     $migrationDir = __DIR__ . '/../../../src/Eccube/Resource/doctrine/migration';
     $config->setMigrationsDirectory($migrationDir);
     $config->registerMigrationsFromDirectory($migrationDir);
     $migration = new Migration($config);
     // initialize migrations.sql from bootstrap
     if (!file_exists(sys_get_temp_dir() . '/migrations.sql')) {
         $sql = $migration->migrate(null, false);
         file_put_contents(sys_get_temp_dir() . '/migrations.sql', json_encode($sql));
     } else {
         $migrations = json_decode(file_get_contents(sys_get_temp_dir() . '/migrations.sql'), true);
         foreach ($migrations as $migration_sql) {
             foreach ($migration_sql as $sql) {
                 if ($this->isSqliteInMemory()) {
                     // XXX #1199 の問題を無理矢理回避...
                     $sql = preg_replace('/CURRENT_TIMESTAMP/i', "datetime('now','-9 hours')", $sql);
                 }
                 $stmt = $pdo->prepare($sql);
                 $stmt->execute();
                 $stmt->closeCursor();
             }
         }
     }
     // 通常は eccube_install.sh で追加されるデータを追加する
     $sql = "INSERT INTO dtb_member (member_id, login_id, password, salt, work, del_flg, authority, creator_id, rank, update_date, create_date,name,department) VALUES (2, 'admin', 'test', 'test', 1, 0, 0, 1, 1, current_timestamp, current_timestamp,'管理者','EC-CUBE SHOP')";
     $stmt = $pdo->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $sql = "INSERT INTO dtb_base_info (id, shop_name, email01, email02, email03, email04, update_date, option_product_tax_rule) VALUES (1, 'SHOP_NAME', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', current_timestamp, 0)";
     $stmt = $pdo->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
 }
Пример #14
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $configuration = $this->getMigrationConfiguration($input, $output);
     $migration = new Migration($configuration);
     $this->outputHeader($configuration, $output);
     $noInteraction = !$input->isInteractive();
     $timeAllqueries = $input->getOption('query-time');
     $executedMigrations = $configuration->getMigratedVersions();
     $availableMigrations = $configuration->getAvailableVersions();
     $executedUnavailableMigrations = array_diff($executedMigrations, $availableMigrations);
     $versionAlias = $input->getArgument('version');
     $version = $configuration->resolveVersionAlias($versionAlias);
     if ($version === null) {
         switch ($versionAlias) {
             case 'prev':
                 $output->writeln('<error>Already at first version.</error>');
                 break;
             case 'next':
                 $output->writeln('<error>Already at latest version.</error>');
                 break;
             default:
                 $output->writeln('<error>Unknown version: ' . $output->getFormatter()->escape($versionAlias) . '</error>');
         }
         return 1;
     }
     if ($executedUnavailableMigrations) {
         $output->writeln(sprintf('<error>WARNING! You have %s previously executed migrations in the database that are not registered migrations.</error>', count($executedUnavailableMigrations)));
         foreach ($executedUnavailableMigrations as $executedUnavailableMigration) {
             $output->writeln('    <comment>>></comment> ' . $configuration->formatVersion($executedUnavailableMigration) . ' (<comment>' . $executedUnavailableMigration . '</comment>)');
         }
         if (!$noInteraction) {
             $question = 'Are you sure you wish to continue? (y/n)';
             $confirmation = $this->askConfirmation($question, $input, $output);
             if (!$confirmation) {
                 $output->writeln('<error>Migration cancelled!</error>');
                 return 1;
             }
         }
     }
     if ($path = $input->getOption('write-sql')) {
         $path = is_bool($path) ? getcwd() : $path;
         $migration->writeSqlFile($path, $version);
     } else {
         $dryRun = (bool) $input->getOption('dry-run');
         // warn the user if no dry run and interaction is on
         if (!$dryRun && !$noInteraction) {
             $question = 'WARNING! You are about to execute a database migration that could result in schema changes and data lost. Are you sure you wish to continue? (y/n)';
             $confirmation = $this->askConfirmation($question, $input, $output);
             if (!$confirmation) {
                 $output->writeln('<error>Migration cancelled!</error>');
                 return 1;
             }
         }
         $sql = $migration->migrate($version, $dryRun, $timeAllqueries);
         if (!$sql) {
             $output->writeln('<comment>No migrations to execute.</comment>');
         }
     }
 }
Пример #15
0
 public function prepareDatabaseTest()
 {
     $this->lock();
     $this->em->clear();
     /** @var Configuration $migrationConfig */
     $migration = new Migration($this->doctrineMigrationConfiguration);
     try {
         $migration->migrate();
     } catch (MigrationException $ex) {
         if ($ex->getCode() !== 4) {
             // no migrations found; this should not break tests in early stages of development,
             // the tests will fail when they require a model anyway
             throw $ex;
         }
     }
     $this->clearDatabase();
 }
 /**
  * @Route("/{connectionName}/execute/{version}")
  * @Method("POST")
  */
 public function executeAction($connectionName, $version)
 {
     $connection = $this->getDoctrine()->getConnection($connectionName);
     $outputWriter = new MemoryOutputWriter();
     $configuration = new Configuration($connection);
     $configuration->setName($this->container->getParameter('doctrine_migrations.name'));
     $configuration->setOutputWriter($outputWriter);
     $configuration->setMigrationsTableName($this->container->getParameter('doctrine_migrations.table_name'));
     $configuration->setMigrationsDirectory($this->container->getParameter('doctrine_migrations.dir_name'));
     $configuration->setMigrationsNamespace($this->container->getParameter('doctrine_migrations.namespace'));
     $migration = new Migration($configuration);
     $currentVersion = $configuration->getCurrentVersion();
     $dryRun = false;
     $migration->setNoMigrationException(true);
     $sql = $migration->migrate($version, $dryRun, true);
     return $this->render('MarkeiDoctrineMigrationWebBundle:Migrate:execute.html.twig', ['connectionName' => $connectionName, 'to' => $version, 'from' => $currentVersion, 'output' => $outputWriter->getMemory(), 'name' => $this->container->getParameter('doctrine_migrations.name')]);
 }
Пример #17
0
 /**
  * @param \Closure $outputWriter
  *
  * @return array
  *
  * @throws \Doctrine\DBAL\Migrations\MigrationException
  */
 public function migrate(\Closure $outputWriter = null)
 {
     $dir = $this->container->getParameter('doctrine_migrations.dir_name');
     if (!$this->filesystem->exists($dir)) {
         $this->filesystem->mkdir($dir);
     }
     $configuration = $this->getConfiguration($dir, $outputWriter);
     $versions = $configuration->getMigrations();
     foreach ($versions as $version) {
         $migration = $version->getMigration();
         if ($migration instanceof ContainerAwareInterface) {
             $migration->setContainer($this->container);
         }
     }
     $migration = new VersionMigration($configuration);
     return $migration->migrate();
 }
Пример #18
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $version = $input->getArgument('version');
     $configuration = $this->getMigrationConfiguration($input, $output);
     $migration = new Migration($configuration);
     $this->outputHeader($configuration, $output);
     $noInteraction = $input->getOption('no-interaction') ? true : false;
     $executedMigrations = $configuration->getMigratedVersions();
     $availableMigrations = $configuration->getAvailableVersions();
     $executedUnavailableMigrations = array_diff($executedMigrations, $availableMigrations);
     if ($executedUnavailableMigrations) {
         $output->writeln(sprintf('<error>WARNING! You have %s previously executed migrations in the database that are not registered migrations.</error>', count($executedUnavailableMigrations)));
         foreach ($executedUnavailableMigrations as $executedUnavailableMigration) {
             $output->writeln('    <comment>>></comment> ' . $configuration->formatVersion($executedUnavailableMigration) . ' (<comment>' . $executedUnavailableMigration . '</comment>)');
         }
         if ($noInteraction === false) {
             $confirmation = $this->getHelper('dialog')->askConfirmation($output, '<question>Are you sure you wish to continue? (y/n)</question>', false);
         }
     }
     if ($path = $input->getOption('write-sql')) {
         $path = is_bool($path) ? getcwd() : $path;
         $migration->writeSqlFile($path, $version);
     } else {
         $dryRun = $input->getOption('dry-run') ? true : false;
         if ($dryRun === true) {
             $sql = $migration->migrate($version, true);
         } else {
             if ($noInteraction === true) {
                 $sql = $migration->migrate($version, $dryRun);
             } else {
                 $confirmation = $this->getHelper('dialog')->askConfirmation($output, '<question>WARNING! You are about to execute a database migration that could result in schema changes and data lost. Are you sure you wish to continue? (y/n)</question>', false);
                 if ($confirmation === true) {
                     $sql = $migration->migrate($version, $dryRun);
                 } else {
                     $output->writeln('<error>Migration cancelled!</error>');
                 }
             }
         }
         if (!$sql) {
             $output->writeln('<comment>No migrations to execute.</comment>');
         }
     }
 }
Пример #19
0
 public function migrate()
 {
     $container = $this->container;
     $conn = $this->entityManager->getConnection();
     $SSoneCMSbundle = new SSoneCMSBundle();
     $dir = $SSoneCMSbundle->getPath() . "/Migrations";
     $configuration = new Configuration($conn);
     $configuration->setMigrationsNamespace('SSone\\CMSBundle\\Migrations');
     $configuration->setMigrationsDirectory($dir);
     $configuration->registerMigrationsFromDirectory($dir);
     $configuration->setName('One CMS Migrations');
     $configuration->setMigrationsTableName('cms_migrations');
     $versions = $configuration->getMigrations();
     foreach ($versions as $version) {
         $migration = $version->getMigration();
         if ($migration instanceof ContainerAwareInterface) {
             $migration->setContainer($container);
         }
     }
     $migration = new Migration($configuration);
     $migrated = $migration->migrate();
 }
Пример #20
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $configuration = $this->getMigrationConfiguration($input, $output);
     $migration = new Migration($configuration);
     $this->outputHeader($configuration, $output);
     $timeAllqueries = $input->getOption('query-time');
     $executedMigrations = $configuration->getMigratedVersions();
     $availableMigrations = $configuration->getAvailableVersions();
     $version = $this->getVersionNameFromAlias($input->getArgument('version'), $output, $configuration);
     if ($version === false) {
         return 1;
     }
     $executedUnavailableMigrations = array_diff($executedMigrations, $availableMigrations);
     if (!empty($executedUnavailableMigrations)) {
         $output->writeln(sprintf('<error>WARNING! You have %s previously executed migrations' . ' in the database that are not registered migrations.</error>', count($executedUnavailableMigrations)));
         foreach ($executedUnavailableMigrations as $executedUnavailableMigration) {
             $output->writeln(sprintf('    <comment>>></comment> %s (<comment>%s</comment>)', $configuration->getDateTime($executedUnavailableMigration), $executedUnavailableMigration));
         }
         $question = 'Are you sure you wish to continue? (y/n)';
         if (!$this->canExecute($question, $input, $output)) {
             $output->writeln('<error>Migration cancelled!</error>');
             return 1;
         }
     }
     if ($path = $input->getOption('write-sql')) {
         $path = is_bool($path) ? getcwd() : $path;
         $migration->writeSqlFile($path, $version);
     } else {
         $dryRun = (bool) $input->getOption('dry-run');
         // warn the user if no dry run and interaction is on
         if (!$dryRun) {
             $question = 'WARNING! You are about to execute a database migration' . ' that could result in schema changes and data lost.' . ' Are you sure you wish to continue? (y/n)';
             if (!$this->canExecute($question, $input, $output)) {
                 $output->writeln('<error>Migration cancelled!</error>');
                 return 1;
             }
         }
         $migration->setNoMigrationException($input->getOption('allow-no-migration'));
         $sql = $migration->migrate($version, $dryRun, $timeAllqueries);
         if (empty($sql)) {
             $output->writeln('<comment>No migrations to execute.</comment>');
         }
     }
 }
Пример #21
0
 /**
  * @expectedException \Doctrine\DBAL\Migrations\MigrationException
  */
 public function testMigrateWithNoMigrationsThrowsException()
 {
     $migration = new Migration($this->config);
     $sql = $migration->migrate();
 }
Пример #22
0
 /**
  * Execute all new migrations, up to $version if given.
  *
  * If $outputPathAndFilename is given, the SQL statements will be written to the given file instead of executed.
  *
  * @param string $version The version to migrate to
  * @param string $outputPathAndFilename A file to write SQL to, instead of executing it
  * @param boolean $dryRun Whether to do a dry run or not
  * @param boolean $quiet Whether to do a quiet run or not
  * @return string
  */
 public function executeMigrations($version = null, $outputPathAndFilename = null, $dryRun = false, $quiet = false)
 {
     $configuration = $this->getMigrationConfiguration();
     $migration = new Migration($configuration);
     if ($outputPathAndFilename !== null) {
         $migration->writeSqlFile($outputPathAndFilename, $version);
     } else {
         $migration->migrate($version, $dryRun);
     }
     if ($quiet === true) {
         $output = '';
         foreach ($this->output as $line) {
             $line = strip_tags($line);
             if (strpos($line, '  ++ migrating ') !== false || strpos($line, '  -- reverting ') !== false) {
                 $output .= substr($line, -15);
             }
         }
         return $output;
     } else {
         return implode(PHP_EOL, $this->output);
     }
 }
 /**
  * Run migrations
  */
 private function runMigrations()
 {
     if (!isset($this->migrations)) {
         return;
     }
     $connection = $this->entityManager->getConnection();
     $container = $this->kernel->getContainer();
     $namespace = $container->getParameter('doctrine_migrations.namespace');
     if ($namespace) {
         $directory = $container->getParameter('doctrine_migrations.dir_name');
         $outputWriter = new OutputWriter(function () {
         });
         $configuration = new Configuration($connection, $outputWriter);
         $configuration->setMigrationsNamespace($namespace);
         $configuration->setMigrationsDirectory($directory);
         $configuration->registerMigrationsFromDirectory($directory);
         $configuration->setName($container->getParameter('doctrine_migrations.name'));
         $configuration->setMigrationsTableName($container->getParameter('doctrine_migrations.table_name'));
         $migration = new Migration($configuration);
         $migration->migrate(null, false);
     }
     foreach ($this->migrations as $migration) {
         foreach (explode("\n", trim(file_get_contents($migration))) as $sql) {
             $connection->executeQuery($sql);
         }
     }
 }
 /**
  * Ensure that the migration with the specified version has been migrated up to.
  *
  * @param string $identifier
  */
 private function migrateUpTo($identifier = null)
 {
     $migration = new DBAL\Migrations\Migration($this->getMigrationConfiguration());
     $migration->migrate($identifier);
 }
Пример #25
0
 /**
  * migrates the schema in configured datastore to the newest version
  */
 public function migrateSchema()
 {
     //get instances
     $migrationConfig = $this->getMigrationsConfiguration();
     $schemaMigration = new Migration($migrationConfig);
     //run migration
     $schemaMigration->migrate();
 }
Пример #26
0
 public function testMigrateToCurrentVersionReturnsEmpty()
 {
     $migration = new Migration($this->config);
     $sql = $migration->migrate('0');
     $this->assertEquals(array(), $sql);
 }