Since: 2.0
Author: Jonathan H. Wage (jonwage@gmail.com)
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registered
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  *
  * @param Application $app
  */
 public function boot(Application $app)
 {
     $helperSet = new HelperSet(array('connection' => new ConnectionHelper($app['db']), 'dialog' => new DialogHelper()));
     if (isset($app['orm.em'])) {
         $helperSet->set(new EntityManagerHelper($app['orm.em']), 'em');
     }
     $this->console->setHelperSet($helperSet);
     $commands = array('Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\ExecuteCommand', 'Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\GenerateCommand', 'Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\MigrateCommand', 'Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\StatusCommand', 'Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\VersionCommand');
     // @codeCoverageIgnoreStart
     if (true === $this->console->getHelperSet()->has('em')) {
         $commands[] = 'Doctrine\\DBAL\\Migrations\\Tools\\Console\\Command\\DiffCommand';
     }
     // @codeCoverageIgnoreEnd
     $configuration = new Configuration($app['db'], $app['migrations.output_writer']);
     $configuration->setMigrationsDirectory($app['migrations.directory']);
     $configuration->setName($app['migrations.name']);
     $configuration->setMigrationsNamespace($app['migrations.namespace']);
     $configuration->setMigrationsTableName($app['migrations.table_name']);
     $configuration->registerMigrationsFromDirectory($app['migrations.directory']);
     foreach ($commands as $name) {
         /** @var AbstractCommand $command */
         $command = new $name();
         $command->setMigrationConfiguration($configuration);
         $this->console->add($command);
     }
 }
Example #2
0
 /**
  * @return Configuration
  */
 public function getSqliteConfiguration()
 {
     $config = new Configuration($this->getSqliteConnection());
     $config->setMigrationsDirectory(\sys_get_temp_dir());
     $config->setMigrationsNamespace('DoctrineMigrations');
     return $config;
 }
 /**
  * @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');
 }
 private function markVersionsMigrated()
 {
     foreach ($this->migrations->getAvailableVersions() as $versionIdentifier) {
         $version = $this->migrations->getVersion($versionIdentifier);
         $version->markMigrated();
     }
 }
 /**
  * read the input and return a Configuration, returns `false` if the config
  * is not supported
  * @return Connection|null
  */
 public function chosen()
 {
     if ($this->configuration) {
         return $this->configuration->getConnection();
     }
     return null;
 }
Example #6
0
 /**
  * @param Connection $connection
  * @param AppKernel  $kernel
  */
 public function preUpdate(Connection $connection, AppKernel $kernel)
 {
     /** @var \Symfony\Component\HttpKernel\Bundle\Bundle[] $bundles */
     $bundles = $kernel->getBundles();
     $isPortfolioBundleInstalled = false;
     foreach ($bundles as $bundle) {
         if ('IcapPortfolioBundle' === $bundle->getName()) {
             $isPortfolioBundleInstalled = true;
         }
     }
     if ($connection->getSchemaManager()->tablesExist(['icap__portfolio_widget_badges'])) {
         if ($isPortfolioBundleInstalled) {
             $this->log('Found existing database schema: skipping install migration...');
             $config = new Configuration($connection);
             $config->setMigrationsTableName('doctrine_icapbadgebundle_versions');
             $config->setMigrationsNamespace('claro_badge');
             // required but useless
             $config->setMigrationsDirectory('claro_badge');
             // idem
             try {
                 $version = new Version($config, '20150929141509', 'stdClass');
                 $version->markMigrated();
             } catch (\Exception $e) {
                 $this->log('Already migrated');
             }
         } else {
             $this->log('Deleting badges tables for portfolio...');
             $connection->getSchemaManager()->dropTable('icap__portfolio_widget_badges_badge');
             $connection->getSchemaManager()->dropTable('icap__portfolio_widget_badges');
             $this->log('badges tables for portfolio deleted.');
         }
     }
 }
Example #7
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();
 }
Example #8
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;
 }
 public function registerMigrations(ConsoleCommandEvent $event)
 {
     $command = $event->getCommand();
     if (!$this->isMigrationCommand($command)) {
         return;
     }
     $this->configuration->registerMigrationsFromDirectory($this->configuration->getMigrationsDirectory());
 }
 public function __construct(Version $version)
 {
     $this->configuration = $version->getConfiguration();
     $this->outputWriter = $this->configuration->getOutputWriter();
     $this->connection = $this->configuration->getConnection();
     $this->sm = $this->connection->getSchemaManager();
     $this->platform = $this->connection->getDatabasePlatform();
     $this->version = $version;
 }
Example #11
0
 protected function outputHeader(Configuration $configuration, OutputInterface $output)
 {
     $name = $configuration->getName();
     $name = $name ? $name : 'Doctrine Database Migrations';
     $name = str_repeat(' ', 20) . $name . str_repeat(' ', 20);
     $output->writeln('<question>' . str_repeat(' ', strlen($name)) . '</question>');
     $output->writeln('<question>' . $name . '</question>');
     $output->writeln('<question>' . str_repeat(' ', strlen($name)) . '</question>');
     $output->writeln('');
 }
Example #12
0
 public function __construct(Configuration $configuration, $version, $class)
 {
     $this->_configuration = $configuration;
     $this->_outputWriter = $configuration->getOutputWriter();
     $this->_version = $version;
     $this->_class = $class;
     $this->_connection = $configuration->getConnection();
     $this->_sm = $this->_connection->getSchemaManager();
     $this->_platform = $this->_connection->getDatabasePlatform();
     $this->_migration = new $class($this);
 }
Example #13
0
 private function showVersions($migrations, Configuration $configuration, OutputInterface $output)
 {
     $migratedVersions = $configuration->getMigratedVersions();
     foreach ($migrations as $version) {
         $isMigrated = in_array($version->getVersion(), $migratedVersions);
         $status = $isMigrated ? '<info>migrated</info>' : '<error>not migrated</error>';
         $migrationDescription = $version->getMigration()->getDescription() ? str_repeat(' ', 5) . $version->getMigration()->getDescription() : '';
         $formattedVersion = $configuration->getDateTime($version->getVersion());
         $output->writeln('    <comment>>></comment> ' . $formattedVersion . ' (<comment>' . $version->getVersion() . '</comment>)' . str_repeat(' ', 49 - strlen($formattedVersion) - strlen($version->getVersion())) . $status . $migrationDescription);
     }
 }
Example #14
0
 private function _buildCodeFromSql(Configuration $configuration, array $sql)
 {
     $code = array();
     foreach ($sql as $query) {
         if (strpos($query, $configuration->getMigrationsTableName()) !== false) {
             continue;
         }
         $code[] = "\$this->_addSql('" . $query . "');";
     }
     return implode("\n", $code);
 }
 private function buildVersion($bundle, $version)
 {
     $bundle = strtolower($bundle);
     $config = new Configuration($this->connection);
     $config->setMigrationsTableName('doctrine_' . $bundle . '_versions');
     $config->setMigrationsNamespace(ucfirst($bundle));
     // required but useless
     $config->setMigrationsDirectory(ucfirst($bundle));
     // idem
     return new Version($config, $version, 'stdClass');
 }
 private function buildCodeFromSql(Configuration $configuration, array $sql)
 {
     $currentPlatform = $configuration->getConnection()->getDatabasePlatform()->getName();
     $code = array("\$this->abortIf(\$this->connection->getDatabasePlatform()->getName() != \"{$currentPlatform}\", \"Migration can only be executed safely on '{$currentPlatform}'.\");", "");
     foreach ($sql as $query) {
         if (strpos($query, $configuration->getMigrationsTableName()) !== false) {
             continue;
         }
         $code[] = "\$this->addSql(\"{$query}\");";
     }
     return implode("\n", $code);
 }
 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);
 }
Example #18
0
    public function testSKipMigrateUp()
    {
        $version = new \Doctrine\DBAL\Migrations\Version($this->config, 1, 'Doctrine\DBAL\Migrations\Tests\Functional\MigrationSkipMigration');

        $this->assertFalse($this->config->hasVersionMigrated($version));
        $version->execute('up');
        
        $schema = $this->connection->getSchemaManager()->createSchema();
        $this->assertFalse($schema->hasTable('foo'));

        $this->assertTrue($this->config->hasVersionMigrated($version));
    }
Example #19
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();
 }
 private function skipInstallIfMigratingFromCore()
 {
     if ($this->conn->getSchemaManager()->tablesExist(['claro_event'])) {
         $this->log('Found existing database schema: skipping install migration...');
         $config = new Configuration($this->conn);
         $config->setMigrationsTableName('doctrine_clarolineagendabundle_versions');
         $config->setMigrationsNamespace('claro_event');
         // required but useless
         $config->setMigrationsDirectory('claro_event');
         // idem
         $version = new Version($config, '20150429110105', 'stdClass');
         $version->markMigrated();
     }
 }
 /**
  * Perform the actual check and return a ResultInterface
  *
  * @return ResultInterface
  */
 public function check()
 {
     $availableVersions = $this->migrationConfiguration->getAvailableVersions();
     $migratedVersions = $this->migrationConfiguration->getMigratedVersions();
     $notMigratedVersions = array_diff($availableVersions, $migratedVersions);
     if (!empty($notMigratedVersions)) {
         return new Failure('Not all migrations applied', $notMigratedVersions);
     }
     $notAvailableVersion = array_diff($migratedVersions, $availableVersions);
     if (!empty($notAvailableVersion)) {
         return new Failure('Migrations applied which are not available', $notMigratedVersions);
     }
     return new Success();
 }
 /**
  * @param HelperSet $helperSet
  *
  * @return array
  */
 public function getConsoleCommands(HelperSet $helperSet)
 {
     $configuration = new Configuration($this->em->getConnection());
     $configuration->setMigrationsNamespace($this->config->getMigrationsNamespace());
     $configuration->setMigrationsDirectory($this->config->getMigrationsPath());
     $configuration->setMigrationsTableName($this->config->getMigrationsTable());
     $commands = [new DiffCommand(), new ExecuteCommand(), new GenerateCommand(), new LatestCommand(), new MigrateCommand(), new StatusCommand(), new VersionCommand()];
     /** @var AbstractCommand $command */
     foreach ($commands as $command) {
         $command->setHelperSet($helperSet);
         $command->setMigrationConfiguration($configuration);
     }
     return $commands;
 }
 public function preInstall()
 {
     if ($this->conn->getSchemaManager()->tablesExist(['claro_message'])) {
         $this->log('Found existing database schema: skipping install migration...');
         $config = new Configuration($this->conn);
         $config->setMigrationsTableName('doctrine_clarolinemessagebundle_versions');
         $config->setMigrationsNamespace('claro_message');
         // required but useless
         $config->setMigrationsDirectory('claro_message');
         // idem
         $version = new Version($config, '20150429114010', 'stdClass');
         $version->markMigrated();
     }
 }
Example #24
0
 protected function _generateMigration(Configuration $configuration, InputInterface $input, $version, $up = null, $down = null)
 {
     $placeHolders = array('<namespace>', '<version>', '<up>', '<down>');
     $replacements = array($configuration->getMigrationsNamespace(), $version, $up ? "        " . implode("\n        ", explode("\n", $up)) : null, $down ? "        " . implode("\n        ", explode("\n", $down)) : null);
     $code = str_replace($placeHolders, $replacements, self::$_template);
     $dir = $configuration->getMigrationsDirectory();
     $dir = $dir ? $dir : getcwd();
     $dir = rtrim($dir, '/');
     $path = $dir . '/Version' . $version . '.php';
     file_put_contents($path, $code);
     if ($editorCmd = $input->getOption('editor-cmd')) {
         shell_exec($editorCmd . ' ' . escapeshellarg($path));
     }
     return $path;
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
 {
     // truncate created tables
     $this->emptyTables($em);
     // rollback schema
     $this->alterTablesDown($em);
     $version = $conf->getVersion('20131118000007');
     if ($version->isMigrated()) {
         $version->execute('down');
     }
     $version = $conf->getVersion('20131118000009');
     if ($version->isMigrated()) {
         $version->execute('down');
     }
 }
Example #26
0
 protected function _before()
 {
     $credentials = new DbCredentials();
     $container = ContainerService::getInstance()->setDbCredentials($credentials)->addEntityPath('src/Entity')->getContainer();
     $em = $container['doctrine.entity_manager'];
     $helperSet = ConsoleRunner::createHelperSet($em);
     $helperSet->set(new DialogHelper(), 'dialog');
     $configuration = new Configuration($em->getConnection());
     $configuration->setMigrationsNamespace('Migrations');
     $configuration->setMigrationsTableName('Migration');
     $this->app = new Application();
     $mig = new Migration();
     $mig->setMigrationConfiguration($configuration);
     $this->app->add($mig);
     $this->app->add(new VersionCommand());
 }
Example #27
0
 /**
  * @param \Symfony\Component\Console\Input\InputInterface $input
  *
  * @return \Doctrine\DBAL\Connection
  * @throws \Doctrine\DBAL\DBALException
  */
 private function getConnection(InputInterface $input)
 {
     if (!$this->connection) {
         if ($input->getOption('db-configuration')) {
             if (!file_exists($input->getOption('db-configuration'))) {
                 throw new \InvalidArgumentException("The specified connection file is not a valid file.");
             }
             $params = (include $input->getOption('db-configuration'));
             if (!is_array($params)) {
                 throw new \InvalidArgumentException('The connection file has to return an array with database configuration parameters.');
             }
             $this->connection = \Doctrine\DBAL\DriverManager::getConnection($params);
         } elseif (file_exists('migrations-db.php')) {
             $params = (include 'migrations-db.php');
             if (!is_array($params)) {
                 throw new \InvalidArgumentException('The connection file has to return an array with database configuration parameters.');
             }
             $this->connection = \Doctrine\DBAL\DriverManager::getConnection($params);
         } elseif ($this->getHelperSet()->has('connection')) {
             $this->connection = $this->getHelper('connection')->getConnection();
         } elseif ($this->configuration) {
             $this->connection = $this->configuration->getConnection();
         } else {
             throw new \InvalidArgumentException('You have to specify a --db-configuration file or pass a Database Connection as a dependency to the Migrations.');
         }
     }
     return $this->connection;
 }
 /**
  * {@inheritdoc}
  */
 public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf)
 {
     $this->renameTable($em, 'down');
     // truncate created tables
     $this->emptyTables($em);
     // rollback schema
     $this->alterTablesDown($em);
     $version = $conf->getVersion('ftp-credential');
     if ($version->isMigrated()) {
         $version->execute('down');
     }
     $version = $conf->getVersion('user');
     if ($version->isMigrated()) {
         $version->execute('down');
     }
 }
 private function mark($version, $all = false)
 {
     if (!$this->configuration->hasVersion($version)) {
         throw MigrationException::unknownMigrationVersion($version);
     }
     $version = $this->configuration->getVersion($version);
     if ($this->markMigrated && $this->configuration->hasVersionMigrated($version)) {
         $marked = true;
         if (!$all) {
             throw new \InvalidArgumentException(sprintf('The version "%s" already exists in the version table.', $version));
         }
     }
     if (!$this->markMigrated && !$this->configuration->hasVersionMigrated($version)) {
         $marked = false;
         if (!$all) {
             throw new \InvalidArgumentException(sprintf('The version "%s" does not exists in the version table.', $version));
         }
     }
     if (!isset($marked)) {
         if ($this->markMigrated) {
             $version->markMigrated();
         } else {
             $version->markNotMigrated();
         }
     }
 }
Example #30
0
 /**
  * Write a migration SQL file to the given path
  *
  * @param string $path      The path to write the migration SQL file.
  * @param string $direction The direction to execute.
  *
  * @return boolean $written
  */
 public function writeSqlFile($path, $direction = 'up')
 {
     $queries = $this->execute($direction, true);
     $this->outputWriter->write("\n# Version " . $this->version . "\n");
     $sqlQueries = [$this->version => $queries];
     $sqlWriter = new SqlFileWriter($this->configuration->getMigrationsTableName(), $path, $this->outputWriter);
     return $sqlWriter->write($sqlQueries, $direction);
 }