Execute migration.

@param   AbstractMigration $migration
@return  bool|null|string
967916
protected function _execute(AbstractMigration $migration)
    {
        $time          = Time::parse('now');
        $version       = $migration->getVersion();
        $migrationName = $this->_plugin . '::' . get_class($migration);

        $sqlInsert = sprintf(
            'INSERT INTO %s ('
            . 'version,'
            . 'migration_name,'
            . 'start_time'
            . ') VALUES ('
            . '\'%s\','
            . '\'%s\','
            . '\'%s\''
            . ');',
            self::SCHEMA_TABLE,
            $version,
            $migrationName,
            $time->toDateTimeString()
        );

        $this->_adapter->query($sqlInsert);

        $sqlCheck = sprintf(
            'SELECT version FROM %s WHERE version=\'%s\'',
            self::SCHEMA_TABLE,
            $version
        );

        $versionResult = $this->_adapter->fetchRow($sqlCheck);
        if (count((array) $versionResult) > 0) {
            return __d(
                'extensions',
                'The version «{0}» of plugin «{1}» has bin success migrated.',
                sprintf('<strong>%s</strong>', $version),
                sprintf('<strong>%s</strong>', __d(Str::low($this->_plugin), $this->_plugin))
            );
        }

        return false;
    }
834187
public function execute($command, callable $next)
    {
        $migration = $command->getMigration();
        if (!$migration instanceof TransactionAwareInterface) {
            $next($command);
            return;
        }

        $result = null;
        try {
            $migration->begin();
            $next($command);
            $migration->finish();
        } catch (\Exception $e) {
            $migration->abort($e);
        }
    }
20011
protected function doExecute()
    {
        $repository = $this->getRepository();

        $repository['path'] = $this->console->get('migration.dir');

        $migrations = $repository->getMigrations();

        if (!count($migrations)) {
            throw new \RuntimeException('No migrations found.');
        }

        $this->out();
        $this->out(' Status  Version         Migration Name ');
        $this->out('-----------------------------------------');

        $versions = $repository->getVersions();

        $migrations->ksort();

        foreach ($migrations as $migration) {
            $status = (in_array($migration['id'], $versions)) ? '    <info>up</info>' : '  <error>down</error>';

            $info = sprintf(
                '%s   %14.0f  %s',
                $status,
                $migration['id'],
                '<comment>' . $migration['name'] . '</comment>'
            );

            $this->out($info);

            // Remove printed versions
            $index = array_search($migration['id'], $versions);

            unset($versions[$index]);
        }

        foreach ($versions as $version) {
            $info = sprintf(
                '%s   %14.0f  %s',
                '    <info>up</info>',
                $version,
                '** Missing **'
            );

            $this->out($info);
        }

        $this->out();

        return true;
    }
1143697
public function migrationExists($migration, $destination)
	{
		$existing = $this->getExistingMigrationNames($destination);

		return in_array(substr(basename($migration), 18), $existing);
	}
428312
protected function executedMigrations()
    {
        $result = [];
        foreach ($this->getRepository()->get() as $row) {
            $result[] = $row['migration'];
        }

        return $result;
    }
458761
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setOutput($output);
        $this->setVerbosity($output->getVerbosity());

        if (!$input->getOption('add') && !$input->getOption('delete') && !$input->getOption('skip') && !$input->getOption('info')) {
            throw new \InvalidArgumentException('You must specify whether you want to --add, --delete, --skip or --info the specified migration.');
        }

        $migrationService = $this->getMigrationService();
        $migrationNameOrPath = $input->getArgument('migration');

        if ($input->getOption('info')) {
            $output->writeln('');

            $migration = $migrationService->getMigration($migrationNameOrPath);
            if ($migration == null) {
                throw new \InvalidArgumentException(sprintf('The migration "%s" does not exist in the migrations table.', $migrationNameOrPath));
            }

            switch ($migration->status) {
                case Migration::STATUS_DONE:
                    $status = '<info>executed</info>';
                    break;
                case Migration::STATUS_STARTED:
                    $status = '<comment>execution started</comment>';
                    break;
                case Migration::STATUS_TODO:
                    // bold to-migrate!
                    $status = '<error>not executed</error>';
                    break;
                case Migration::STATUS_SKIPPED:
                    $status = '<comment>skipped</comment>';
                    break;
                case Migration::STATUS_PARTIALLY_DONE:
                    $status = '<comment>partially executed</comment>';
                    break;
                case Migration::STATUS_SUSPENDED:
                    $status = '<comment>suspended</comment>';
                    break;
                case Migration::STATUS_FAILED:
                    $status = '<error>failed</error>';
                    break;
            }

            $output->writeln('<info>Migration: ' . $migration->name . '</info>');
            $output->writeln('Status: ' . $status);
            $output->writeln('Executed on: <info>' . ($migration->executionDate != null ? date("Y-m-d H:i:s", $migration->executionDate) : '--'). '</info>');
            $output->writeln('Execution notes: <info>' . $migration->executionError . '</info>');

            if ($migration->status == Migration::STATUS_SUSPENDED) {
                /// @todo decode the suspension context: date, step, ...
            }

            $output->writeln('Definition path: <info>' . $migration->path . '</info>');
            $output->writeln('Definition md5: <info>' . $migration->md5 . '</info>');

            if ($migration->path != '') {
                // q: what if we have a loader which does not work with is_file? We could probably remove this check...
                if (is_file($migration->path)) {
                    try {
                        $migrationDefinitionCollection = $migrationService->getMigrationsDefinitions(array($migration->path));
                        if (count($migrationDefinitionCollection)) {
                            $migrationDefinition = reset($migrationDefinitionCollection);
                            $migrationDefinition = $migrationService->parseMigrationDefinition($migrationDefinition);

                            if ($migrationDefinition->status != MigrationDefinition::STATUS_PARSED) {
                                $output->writeln('Definition error: <error>' . $migrationDefinition->parsingError . '</error>');
                            }

                            if (md5($migrationDefinition->rawDefinition) != $migration->md5) {
                                $output->writeln('Notes: <comment>The migration definition file has now a different checksum</comment>');
                            }
                        } else {
                            $output->writeln('Definition error: <error>The migration definition file can not be loaded</error>');
                        }
                    } catch (\Exception $e) {
                        /// @todo one day we should be able to limit the kind of exceptions we have to catch here...
                        $output->writeln('Definition parsing error: <error>' . $e->getMessage() . '</error>');
                    }
                } else {
                    $output->writeln('Definition error: <error>The migration definition file can not be found any more</error>');
                }
            }

            $output->writeln('');
            return 0;
        }

        // ask user for confirmation to make changes
        if ($input->isInteractive() && !$input->getOption('no-interaction')) {
            $dialog = $this->getHelperSet()->get('question');
            if (!$dialog->ask(
                $input,
                $output,
                new ConfirmationQuestion('<question>Careful, the database will be modified. Do you want to continue Y/N ?</question>', false)
            )
            ) {
                $output->writeln('<error>Migration change cancelled!</error>');
                return 0;
            }
        }

        if ($input->getOption('add')) {
            // will throw if a file is passed and it is not found, but not if an empty dir is passed
            $migrationDefinitionCollection = $migrationService->getMigrationsDefinitions(array($migrationNameOrPath));

            if (!count($migrationDefinitionCollection))
            {
                throw new \InvalidArgumentException(sprintf('The path "%s" does not correspond to any migration definition.', $migrationNameOrPath));
            }

            foreach ($migrationDefinitionCollection as $migrationDefinition) {
                $migrationName = basename($migrationDefinition->path);

                $migration = $migrationService->getMigration($migrationNameOrPath);
                if ($migration != null) {
                    throw new \InvalidArgumentException(sprintf('The migration "%s" does already exist in the migrations table.', $migrationName));
                }

                $migrationService->addMigration($migrationDefinition);
                $output->writeln('<info>Added migration' . $migrationDefinition->path . '</info>');
            }

            return 0;
        }

        if ($input->getOption('delete')) {
            $migration = $migrationService->getMigration($migrationNameOrPath);
            if ($migration == null) {
                throw new \InvalidArgumentException(sprintf('The migration "%s" does not exist in the migrations table.', $migrationNameOrPath));
            }

            $migrationService->deleteMigration($migration);

            return 0;
        }

        if ($input->getOption('skip')) {
            // will throw if a file is passed and it is not found, but not if an empty dir is passed
            $migrationDefinitionCollection = $migrationService->getMigrationsDefinitions(array($migrationNameOrPath));

            if (!count($migrationDefinitionCollection))
            {
                throw new \InvalidArgumentException(sprintf('The path "%s" does not correspond to any migration definition.', $migrationNameOrPath));
            }

            foreach ($migrationDefinitionCollection as $migrationDefinition) {
                $migrationService->skipMigration($migrationDefinition);
                $output->writeln('<info>Migration' . $migrationDefinition->path . ' marked as skipped</info>');
            }

            return 0;
        }

        throw new \InvalidArgumentException("Please specify one action to be taken on the given migration");
    }
226397
protected function resolve(object $migration): Migration
	{
		return $this->container->get($this->getFullyQualifiedMigration($migration));
	}
867621
def execute_migrations(self, show_traceback=True):
        
        all_migrations = get_pending_migrations(self.path, self.databases)
        
        if not len(all_migrations):
            sys.stdout.write("There are no migrations to apply.\n")
        
        for db, migrations in all_migrations.iteritems():
            connection = connections[db]
            
            # init connection
            cursor = connection.cursor()
            cursor.close()
                        
            for migration in migrations:
                migration_path = self._get_migration_path(db, migration)
                
                with Transactional():
                    sys.stdout.write(
                        "Executing migration %r on %r...." %
                        (migration, db)
                    )
                    created_models = self._execute_migration(
                        db,
                        migration_path,
                        show_traceback=show_traceback
                    )

                    emit_post_sync_signal(
                        created_models=created_models,
                        verbosity=self.verbosity,
                        interactive=self.interactive,
                        db=db,
                    )
            
            if self.load_initial_data:
                sys.stdout.write(
                    "Running loaddata for initial_data fixtures on %r.\n" % db
                )
                call_command(
                    "loaddata",
                    "initial_data",
                    verbosity=self.verbosity,
                    database=db,
                )
227957
def execute(self, conn, migration_url="", migration_input="", create_by="", migration_request_id="", oldest= False, transaction=False):
        
        sql = self.sql
        binds = {}
	if migration_request_id:
	    sql += " WHERE MR.MIGRATION_REQUEST_ID=:migration_request_id"
	    binds['migration_request_id']=migration_request_id
        elif oldest:
            #FIXME: Need to write the sql.YG
            #current_date = dbsUtils().getTime()
            #we require waiting time for 
            #retry_count=0 is 1 minutes
            #retry_count=1 is 2 minutes
            #retyr_count=2 is 4 minutes

            sql += """
                       WHERE MR.MIGRATION_STATUS=0 
                       or (MR.migration_status=3 and MR.retry_count=0 and MR.last_modification_date <= :current_date-60)    
                       or (MR.migration_status=3 and MR.retry_count=1 and MR.last_modification_date <= :current_date-120)  
                       or (MR.migration_status=3 and MR.retry_count=2 and MR.last_modification_date <= :current_date-240)
                       ORDER BY MR.creation_date
                   """ 
            binds['current_date'] = dbsUtils().getTime()
            #print "time= " + str(binds['current_date'])
        else:    
	    if  migration_url or migration_input or create_by:
		sql += " WHERE "
	    if migration_url:
		sql += " MR.MIGRATION_URL=:migration_url"
		binds['migration_url']=migration_url
	    if  migration_input:
		if migration_url:
		    sql += " AND "
		op = ("=", "like")["%" in migration_input]
		sql += " MR.MIGRATION_INPUT %s :migration_input" % op
		binds['migration_input']=migration_input
	    if create_by:
		if  migration_url or migration_input:
		    sql += " AND "
		sql += " MR.CREATE_BY=:create_by" %create_by
		binds['create_by']=create_by
	cursors = self.dbi.processData(sql, binds, conn, transaction, returnCursor=True)
        result = []
        for c in cursors:
            result.extend(self.formatCursor(c, size=100))
        return result
741852
protected function processMigration(&$index, array $migrations, Migration $migration)
    {
        if (in_array($migration->getStatus(), [Migration::STATUS_MIGRATED, Migration::STATUS_RECURSIVE_FOREIGN_KEY], true)) {
            return;
        }
        $migration->setStatus(Migration::STATUS_IN_PROGRESS);

        // Check foreign keys
        $tableNames = $migration->getTable()->getForeignTableNames();
        foreach ($tableNames as $tableName) {
            if ($migration->getTable()->getTableName() === $tableName) {
                continue;
            }

            // Check recursive foreign key
            if (isset($migrations[$tableName]) && $migrations[$tableName]->getStatus() === Migration::STATUS_IN_PROGRESS) {
                $migration->setStatus(Migration::STATUS_RECURSIVE_FOREIGN_KEY);
                continue;
            }

            $this->processMigration($index, $migrations, $migrations[$tableName]);
        }

        $migration->writeTableOut($index, $this->output, $this->option('force'));

        if ($migration->getStatus() !== Migration::STATUS_RECURSIVE_FOREIGN_KEY) {
            $migration->setStatus(Migration::STATUS_MIGRATED);
        }

        $index++;
    }
199256
public function run($version)
    {
        $versions = array();
        $iterator = new \DirectoryIterator($this->migrationsDir);
        foreach ($iterator as $fileinfo) {
            if (!$fileinfo->isDir()) {
                $versions[] = str_replace('.php', '', $fileinfo->getFilename());
            }
        }

        /** @var Mysql $connection */
        $connection = $this->getDI()->get($this->migrationAdapter);
        try {
            $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC);
        } catch (\PDOException $ex) {
            if ($this->migrationAdapter === 'dbMysql') {
                $connection->query('CREATE TABLE migration (`id` INT NOT NULL AUTO_INCREMENT,`version` VARCHAR(45) NOT NULL,`run_at` DATETIME NOT NULL, PRIMARY KEY (`id`))');
            } else {
                $connection->query('CREATE TABLE "public"."migration" ("id" SERIAL NOT NULL,"version" CHARACTER VARYING(45),"run_at" TIMESTAMP,PRIMARY KEY ("id"));');
            }

        }

        if (isset($lastMig)) {
            $fromVersion = $lastMig['version'];
        } else {
            $fromVersion = '0';
        }

        $toZero = false;
        if (count($versions) == 0) {
            throw new CommandsException('Migrations were not found at ' . $this->migrationsDir);
        } else {
            if ($version === null) {
                $version = Version::maximum($versions);
            } else {
                if ($version == '0') {
                    $toZero = true;
                    $versionsSorted = Version::sortAsc($versions);
                    $version = $versionsSorted[0];

                } elseif ($version === 'up') {
                    $versionsSorted = Version::sortAsc($versions);
                    foreach ($versionsSorted as $k => $v) {
                        if ($v === $fromVersion) {
                            $currentK = $k;
                        }
                    }
                    $version = isset($versionsSorted[$currentK + 1]) ? $versionsSorted[$currentK + 1] : Version::maximum($versions);
                } elseif ($version === 'down') {
                    $versionsSorted = Version::sortAsc($versions);
                    foreach ($versionsSorted as $k => $v) {
                        if ($v === $fromVersion) {
                            $currentK = $k;
                        }
                    }
                    $version = isset($versionsSorted[$currentK - 1]) ? $versionsSorted[$currentK - 1] : $versionsSorted[0];
                }
                $migrationPath = $this->migrationsDir . '/' . $version . '.php';
                if (!file_exists($migrationPath)) {
                    throw new CommandsException('Migration class was not found ' . $migrationPath);
                }
            }
        }

        $versionsBetween = Version::between($fromVersion, $version, $versions);
        if ($toZero === true) {
            $theTwoFirstMigrations = [];
            $theTwoFirstMigrations[] = $versionsBetween[count($versionsBetween) - 1];
            $versionsBetween = $theTwoFirstMigrations;
        }


        try {
            $direction = 'up';
            foreach ($versionsBetween as $k => $v) {
                $migrationPath = $this->migrationsDir . '/' . $v['version'] . '.php';
                $this->_migrateFile((string)$v['version'], $migrationPath, $v['direction']);
                if ($v['direction'] === 'down' && $k === 0) {
                    $direction = $v['direction'];
                    continue;
                } else {
                    $connection->insert("migration", array((string)$v['version'], date('Y-m-d H:i:s')), array("version", "run_at"));
                }
                $direction = $v['direction'];

            }
            if (count($versionsBetween) > 0 && $direction === 'down') {
                $connection->insert("migration", array((string)$version, date('Y-m-d H:i:s')), array("version", "run_at"));
            } elseif (count($versionsBetween) === 0) {
                print Color::colorize('No migration to run' . PHP_EOL . PHP_EOL, Color::FG_GREEN);
            }
            exit(0);
        } catch (\Throwable $e){
            print PHP_EOL . Color::error($e->getMessage()) . PHP_EOL;
            exit(1);
        }

    }
1066134
public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->createAppMigrationsTable();

        $migrations = $this->migrationsToRun();

        usort($migrations, function ($a, $b) {
            return strcmp($a->getTimestamp(), $b->getTimestamp());
        });

        $count     = 0;
        $totalTime = 0;
        foreach ($migrations as $migration) {
            $output->writeln(sprintf(
                '  * STARTING *  %s (%s)',
                $migration->getDescription(),
                $migration->getTimestamp()
            ));
            $start = microtime(true);

            $migration->execute($this->db);

            $time = microtime(true) - $start;
            $totalTime += $time;
            $output->writeln(sprintf(
                '  * DONE *  %s (%s) - Took %.2fs',
                $migration->getDescription(),
                $migration->getTimestamp(),
                $time
            ));

            $this->recordMigration($migration);

            $count++;
        }

        if ($count === 0) {
            $message = '  No new migrations to run';
        } else {
            $message = sprintf('  Executed %d migrations in %.2fs', $count, $totalTime);
        }

        $output->writeln([$message, ''], true);
    }
1209727
protected function execute()
    {
        $this->bootstrap();

        // get the migration path from the config
        $path = $this->getMigrationPath();

        if (!file_exists($path) && $this->getPrompter()->confirm('Create migrations directory?', true)) {
            mkdir($path, 0755, true);
        }

        $this->verifyMigrationDirectory($path);

        $config = $this->getConfig();
        $namespace = $config->getMigrationNamespaceByPath($path);

        $path = realpath($path);
        $className = $this->getArgument('name');

        if (!Util::isValidPhinxClassName($className)) {
            throw new \InvalidArgumentException(sprintf(
                'The migration class name "%s" is invalid. Please use CamelCase format.',
                $className
            ));
        }

        if (!Util::isUniqueMigrationClassName($className, $path)) {
            throw new \InvalidArgumentException(sprintf(
                'The migration class name "%s%s" already exists',
                $namespace ? ($namespace . '\\') : '',
                $className
            ));
        }

        // Compute the file path
        $fileName = Util::mapClassNameToFileName($className);
        $filePath = $path . DIRECTORY_SEPARATOR . $fileName;

        if (is_file($filePath)) {
            throw new \InvalidArgumentException(sprintf(
                'The file "%s" already exists',
                $filePath
            ));
        }

        // Get the alternative template and static class options from the config, but only allow one of them.
        $defaultAltTemplate = $this->getConfig()->getTemplateFile();
        $defaultCreationClassName = $this->getConfig()->getTemplateClass();
        if ($defaultAltTemplate && $defaultCreationClassName) {
            throw new \InvalidArgumentException('Cannot define template:class and template:file at the same time');
        }

        // Get the alternative template and static class options from the command line, but only allow one of them.
        $altTemplate = $this->getOption('template');
        $creationClassName = $this->getOption('class');
        if ($altTemplate && $creationClassName) {
            throw new \InvalidArgumentException('Cannot use --template and --class at the same time');
        }

        // If no commandline options then use the defaults.
        if (!$altTemplate && !$creationClassName) {
            $altTemplate = $defaultAltTemplate;
            $creationClassName = $defaultCreationClassName;
        }

        // Verify the alternative template file's existence.
        if ($altTemplate && !is_file($altTemplate)) {
            throw new \InvalidArgumentException(sprintf(
                'The alternative template file "%s" does not exist',
                $altTemplate
            ));
        }

        // Verify that the template creation class (or the aliased class) exists and that it implements the required interface.
        $aliasedClassName = null;
        if ($creationClassName) {
            // Supplied class does not exist, is it aliased?
            if (!class_exists($creationClassName)) {
                $aliasedClassName = $this->getConfig()->getAlias($creationClassName);
                if ($aliasedClassName && !class_exists($aliasedClassName)) {
                    throw new \InvalidArgumentException(sprintf(
                        'The class "%s" via the alias "%s" does not exist',
                        $aliasedClassName,
                        $creationClassName
                    ));
                }

                if (!$aliasedClassName) {
                    throw new \InvalidArgumentException(sprintf(
                        'The class "%s" does not exist',
                        $creationClassName
                    ));
                }
            }

            // Does the class implement the required interface?
            if (!$aliasedClassName && !is_subclass_of($creationClassName, self::CREATION_INTERFACE)) {
                throw new \InvalidArgumentException(sprintf(
                    'The class "%s" does not implement the required interface "%s"',
                    $creationClassName,
                    self::CREATION_INTERFACE
                ));
            }

            if ($aliasedClassName && !is_subclass_of($aliasedClassName, self::CREATION_INTERFACE)) {
                throw new \InvalidArgumentException(sprintf(
                    'The class "%s" via the alias "%s" does not implement the required interface "%s"',
                    $aliasedClassName,
                    $creationClassName,
                    self::CREATION_INTERFACE
                ));
            }
        }

        // Use the aliased class.
        $creationClassName = $aliasedClassName ?: $creationClassName;

        // Determine the appropriate mechanism to get the template
        if ($creationClassName) {
            // Get the template from the creation class
            /** @var CreationInterface $creationClass */
            $creationClass = new $creationClassName($this);
            $contents = $creationClass->getMigrationTemplate();
        } else {
            // Load the alternative template if it is defined.
            $contents = file_get_contents($altTemplate ?: $this->getMigrationTemplateFilename());
        }

        // inject the class names appropriate to this migration
        $classes = [
            '$namespaceDefinition' => null !== $namespace ? ('namespace ' . $namespace . ';') : '',
            '$namespace' => $namespace,
            '$useClassName' => $this->getConfig()->getMigrationBaseClassName(false),
            '$className' => $className,
            '$version' => Util::getVersionFromFileName($fileName),
            '$baseClassName' => $this->getConfig()->getMigrationBaseClassName(true),
        ];
        $contents = strtr($contents, $classes);

        if (false === file_put_contents($filePath, $contents)) {
            throw new \RuntimeException(sprintf(
                'The file "%s" could not be written to',
                $path
            ));
        }

        // Do we need to do the post creation call to the creation class?
        if (isset($creationClass)) {
            $creationClass->postMigrationCreation($filePath, $className,
                $this->getConfig()->getMigrationBaseClassName());
        }

        $output = $this->getOutput();
        $output->write('using migration base class ', 'info');
        $output->writeln($classes['$useClassName']);

        if (!empty($altTemplate)) {
            $output->write('using alternative template ', 'info');
            $output->writeln($altTemplate);
        } elseif (!empty($creationClassName)) {
            $output->write('using template creation class ', 'info');
            $output->writeln($creationClassName);
        } else {
            $output->writeln('using default template', 'info');
        }

        $output->write('created ', 'info');
        $output->writeln(str_replace(getcwd() . DIRECTORY_SEPARATOR, '', $filePath));
    }
1187239
public function runMigrations()
	{
		$migrations = Model::where('status', 'pending');

		if ($migrations->get()->size() > 0) {
			foreach($migrations->get()->all() as $migration) {
				$this->runSingleMigration($migration);
			}
		}
	}
633865
protected function importMigration(Migration $migration) {
    // Run dependencies first.
    $dependencies = $migration->getMigrationDependencies();
    $required_ids = $dependencies['required'];
    if ($required_ids) {
      $required_migrations = $this->migrationManager->createInstances($required_ids);
      array_walk($required_migrations, [$this, 'importMigration']);
    }

    $message = new MigrateMessage();
    $executable = new MigrateExecutable($migration, $message);
    $executable->import();
  }
431888
public function resumeMigration(Migration $migration, $useTransaction = true)
    {
        if ($migration->status != Migration::STATUS_SUSPENDED) {
            throw new \Exception("Can not resume ".$this->getEntityName($migration)." '{$migration->name}': it is not in suspended status");
        }

        $migrationDefinitions = $this->getMigrationsDefinitions(array($migration->path));
        if (!count($migrationDefinitions)) {
            throw new \Exception("Can not resume ".$this->getEntityName($migration)." '{$migration->name}': its definition is missing");
        }

        $defs = $migrationDefinitions->getArrayCopy();
        $migrationDefinition = reset($defs);

        $migrationDefinition = $this->parseMigrationDefinition($migrationDefinition);
        if ($migrationDefinition->status == MigrationDefinition::STATUS_INVALID) {
            throw new \Exception("Can not resume ".$this->getEntityName($migration)." '{$migration->name}': {$migrationDefinition->parsingError}");
        }

        // restore context
        $this->contextHandler->restoreCurrentContext($migration->name);

        if (!isset($this->migrationContext[$migration->name])) {
            throw new \Exception("Can not resume ".$this->getEntityName($migration)." '{$migration->name}': the stored context is missing");
        }
        $restoredContext = $this->migrationContext[$migration->name];
        if (!is_array($restoredContext) || !isset($restoredContext['context']) || !isset($restoredContext['step'] )) {
            throw new \Exception("Can not resume ".$this->getEntityName($migration)." '{$migration->name}': the stored context is invalid");
        }

        // update migration status
        $migration = $this->storageHandler->resumeMigration($migration);

        // clean up restored context - ideally it should be in the same db transaction as the line above
        $this->contextHandler->deleteContext($migration->name);

        // and go
        // note: we store the current step counting starting at 1, but use offset starting at 0, hence the -1 here
        $this->executeMigrationInner($migration, $migrationDefinition, $restoredContext['context'],
            $restoredContext['step'] - 1, $useTransaction);
    }
836664
private function migrate()
    {
        $action = $this->arg->getParameter('action');

        if (!is_null($action)) {
            $this->throwFailsCommand('This action is not allow!', 'help migration');
        }

        $this->command->call(
            'migrate',
            'migration',
            null
        );
    }