Run a migration

@param Migration $migration
@param bool $executeQueries
@param bool $forcedRollback

@throws \Exception
@throws Migration\Exception
@return void
511797
public function run(Migration $migration, $executeQueries = false, $forcedRollback = false)
    {
        $this->migration = $migration;

        try {
            $this->playQueries($executeQueries);
            if ($forcedRollback) {
                $this->playRollbackQueries($executeQueries);
            }
        } catch (Exception $e) {
            $this->playRollbackQueries($executeQueries);

            throw $e;
        }
    }
663212
protected function migrateUp(MigrationInterface $migration)
    {
        echo "\nm_".$migration->getTime()." ... ";
        $migration->up();
        $this->createManager($migration->getConnection())->completeUp($migration);
        echo "OK";
    }
616445
private function _processMigration(Migration $migration, callable $command)
    {
        if ($migration->isTransaction()) {
            $this->getDbRepository()->getAdapter()->transaction($command);
        } else {
            if ($this->logger) {
                $this->logger->alert('NO TRANSACTION!');
            }
            $command();
        }
    }
1356141
def migrate(engine, database, module, **kwargs):
    '''
    
    '''
    validate_args(engine, database, module)

    options = {
        'direction': kwargs.get('direction', 'up'),
        'fake': kwargs.get('fake', False),
        'force': kwargs.get('force', False),
        'migration': kwargs.get('migration', None),
        'transaction': kwargs.get('transaction', True),
    }

    Migration._meta.database = database
    migrator = DATABASE_MAP[engine](database, module, **options)
    migrator.run()
515070
public function addMigration(SQLMigration $migration) {
		if (!$migration instanceof MySQLMigration) {
			throw new InvalidMigrationType(\get_class($migration));
		}
		$this->migrations[\get_class($migration)] = $migration;
	}
972181
def __apply(self, migration=None, run_all=False):
        
        out = StringIO()
        trace = None

        migrate_kwargs = {
            'interactive': False,
            'stdout': out,
            'database': self._database_name,
        }
        if migration is not None:
            migrate_kwargs.update({
                'app_label': migration[0],
                'migration_name': migration[1],
            })
        elif not run_all:
            raise ValueError('Either a migration must be provided or "run_all" must be True')

        start = self._timer()
        try:
            call_command("migrate", **migrate_kwargs)
        except Exception:
            trace = ''.join(traceback.format_exception(*sys.exc_info()))
        finally:
            end = self._timer()
            successes, failure = self._parse_migrate_output(out.getvalue())

            self._migration_state.append({
                'database': self._database_name,
                'migration': 'all' if run_all else (migration[0], migration[1]),
                'duration': end - start,
                'output': _remove_escape_characters(out.getvalue()),
                'succeeded_migrations': successes,        # [(app, migration), ...]
                'failed_migration': failure,              # (app, migration)
                'traceback': trace,
                'succeeded': failure is None and trace is None,
            })

        if failure is not None:
            raise CommandError("Migration failed for app '{}' - migration '{}'.\n".format(*failure))
        elif trace is not None:
            raise CommandError("Migrations failed unexpectedly. See self.state['traceback'] for details.")
1162603
private function checkMigrationExistance($migration)
    {
        $result = $this->getMigrationTable()
            ->where('migration', $migration)
            ->first();

        return !is_null($result);
    }
761097
private function playQueries($executeQueries = false)
    {
        foreach ($this->migration->getQueries() as $idx => $query) {
            try {
                $this->runQuery($query, $executeQueries);
            } catch (\Exception $e) {
                // Only throw if more than one query is played
                if ($idx >= 1) {
                    throw new Exception($e->getMessage());
                }

                throw $e;
            }
        }
    }
956222
private function migration()
    {
        $action = $this->arg->getParameter('action');

        if (!in_array($action, ['migrate', 'rollback', 'reset'])) {
            $this->throwFailsCommand('This action is not exists!', 'help migration');
        }

        $target = $this->arg->getParameter('target');

        $this->command->call(
            $action,
            'migration',
            $target
        );
    }
1181659
protected function runMigration($migration, $method)
    {
        $connection = $this->resolveConnection(
            $migration->getConnection()
        );

        $callback = function () use ($migration, $method) {
            if (method_exists($migration, $method)) {
                $migration->{$method}();
            }
        };

        $this->getSchemaGrammar($connection)->supportsSchemaTransactions()
            && $migration->withinTransaction
                    ? $connection->transaction($callback)
                    : $callback();
    }
447021
protected function runRollback($database, $path, $step, $force)
    {
        $this->call('migrate:rollback', [
            '--database' => $database,
            '--path'     => $path,
            '--step'     => $step,
            '--force'    => $force,
        ]);
    }
1081644
private function executeMigration(
        array $migrationsToExecute,
        string $direction,
        MigratorConfiguration $migratorConfiguration
    ) : array {
        $dryRun = $migratorConfiguration->isDryRun();

        $connection = $this->configuration->getConnection();

        $allOrNothing = $migratorConfiguration->isAllOrNothing();

        if ($allOrNothing) {
            $connection->beginTransaction();
        }

        try {
            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrating, $direction, $dryRun);

            $sql  = [];
            $time = 0;

            foreach ($migrationsToExecute as $version) {
                $versionExecutionResult = $version->execute($direction, $migratorConfiguration);

                // capture the to Schema for the migration so we have the ability to use
                // it as the from Schema for the next migration when we are running a dry run
                // $toSchema may be null in the case of skipped migrations
                if (! $versionExecutionResult->isSkipped()) {
                    $migratorConfiguration->setFromSchema($versionExecutionResult->getToSchema());
                }

                $sql[$version->getVersion()] = $versionExecutionResult->getSql();
                $time                       += $versionExecutionResult->getTime();
            }

            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrated, $direction, $dryRun);
        } catch (Throwable $e) {
            if ($allOrNothing) {
                $connection->rollBack();
            }

            throw $e;
        }

        if ($allOrNothing) {
            $connection->commit();
        }

        return $sql;
    }
50585
protected function runRollback($database, $path, $step)
    {
        $this->call('migrate:rollback', array_filter([
            '--database' => $database,
            '--path' => $path,
            '--realpath' => $this->input->getOption('realpath'),
            '--step' => $step,
            '--force' => true,
        ]));
    }
1476
public function insert(Migration $migration)
    {
        $sql = sprintf("INSERT INTO {$this->tableName} (name, data) VALUES ('%s', '%s')",
            $this->adapter->escape($migration->getName()),
            $this->adapter->escape($migration->getSql())
        );
        $this->getAdapter()->execute($sql);
    }
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;
    }
4498
public function execute(): void
	{
		$migrations = $this->getOutstanding();

		if(empty($migrations))
		{
			$this->write('<blue>There are no outstanding migrations.</blue>');

			return;
		}

		$batch = $this->builder()->max('batch') + 1;

		foreach($migrations as $migration)
		{
			$this->runMigration($migration, 'up', $batch);
		}

		$this->write('Ran the following migrations:' . PHP_EOL);

		$this->outputMigrationList($migrations);
	}
888818
public function rollback(?int $batches = null): void
	{
		$migrations = $this->getMigrated($batches);

		if($migrations->isEmpty())
		{
			$this->write('<blue>There are no migrations to roll back.</blue>');

			return;
		}

		foreach($migrations as $migration)
		{
			$this->runMigration($migration, 'down');
		}

		$this->write('Rolled back the following migrations:' . PHP_EOL);

		$this->outputMigrationList($migrations->getItems());
	}