Run migrate
@param MigrateController $migrateController
@param string $command either `up` or `down`
@throws ExtensionException
969672
protected function runMigration($migrateController, $command)
    {
        $filter = stream_filter_prepend(STDOUT, "block_stdout");
        ob_start();
        ob_implicit_flush();

        $migrateController->runAction($command);

        ob_clean();
        stream_filter_remove($filter);
    }
708285
private void doRun() {
        if (migrationInfo.startProcessing()) {
            try {
                if (firstFragment) {
                    executeBeforeMigrations();
                }

                for (Operation migrationOperation : fragmentMigrationState.getMigrationOperations()) {
                    runMigrationOperation(migrationOperation);
                }

                success = true;
            } catch (Throwable e) {
                failureReason = e;
                getLogger().severe("Error while executing replication operations " + migrationInfo, e);
            } finally {
                afterMigrate();
            }
        } else {
            logMigrationCancelled();
        }
    }
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);
        }

    }
1238385
public function execute( )
    {
        $this->doAction( self::ON_BEFORE_MIGRATE_CMD_EXECUTE_ACTION );
        
        if ( NULL === $this->migrator )
        {
            throw new MigrationException( 'You must set the migrator before executing this command.' );
        }
        
        $verbose   = self::getOption( $this, 'verbose' )->value;
        
        $direction = self::getOption( $this, 'direction' )->value;
        $levels    = self::getOption( $this, 'levels' )->value;
        
        $this->migrator->verbose = $verbose;
        
        switch( $direction )
        {
            case 'up':
                $this->migrator->migrateUp( $levels );
                break;
            
            case 'down':
                $this->migrator->migrateDown( $levels );
                break;
            
            default:
                // do nothing
                break;
        }
        
        $this->doAction( self::ON_AFTER_MIGRATE_CMD_EXECUTE_ACTION );
    }
101004
public function run(OperationHandlerContract $handler, ExtensionContract $extension, array $flags = []) {
        try {
            $name = $extension->getPackage()->getName();

            if($this->componentsRepository->isRequired($name)) {
                throw new ExtensionException('The package [' . $name . '] cannot be uninstalled due is required for whole system.');
            }

            $handler->operationInfo(new Operation('Uninstalling the [' . $name . '] extension.'));

            //$this->dispatcher->fire(new Uninstalling($extension));
            $this->dispatcher->fire(new ComponentUninstalling($extension));
            $this->migrateManager->uninstall($name);
            $this->assetManager->delete(str_replace('/', '_', $name));

            $this->extensionsRepository->save($extension, [
                'status'    => ExtensionContract::STATUS_AVAILABLE,
                'options'   => [],
            ]);

            if(in_array('purge', $flags, true)) {
                $command = 'composer remove ' . $name;

                $process = $this->composerHandler->run($command, function(Process $process, $type, $buffer) use($handler) {
                    if(Str::contains($buffer, 'Error Output')) {
                        throw new ExtensionException($process->getErrorOutput());
                    }

                    $handler->operationInfo(new Operation($buffer));
                });

                if( ! $process->isSuccessful() ) {
                    throw new ExtensionException($process->getErrorOutput());
                }
            }

            //$this->dispatcher->fire(new Uninstalled($extension));
            $this->dispatcher->fire(new ComponentUninstalled($extension));

            $operation = new Operation('The package [' . $name . '] has been successfully uninstalled.');

            return $handler->operationSuccess($operation);
        }
        catch(\Exception $e) {
            Log::error($e);
            $this->dispatcher->fire(new ComponentInstallationFailed($extension, $e));

            return $handler->operationFailed(new Operation($e->getMessage()));
        }
    }
1162709
public function addMigration(string $path, Migration $migrations): void{
        $name = basename($path);
        $this->migrations[$name] = $migrations;
    }
441852
protected function runUp($path, $file, Extension $extension = null)
    {
        $migration = $this->resolve($path, $file);

        $this->runClosureMigration($migration);

        // Once we have run a migrations class, we will log that it was run in this
        // repository so that we don't try to run it next time we do a migration
        // in the application. A migration repository keeps the migrate order.
        $this->repository->log($file, $extension ? $extension->getId() : null);

        $this->note("<info>Migrated:</info> $file");
    }
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
        );
    }
697401
protected function registerMigrateCommand(): void
    {
        $this->app->singleton('orchestra.commands.tenanti.migrate', function (Application $app) {
            return new MigrateCommand($app->make('orchestra.tenanti'));
        });
    }
729376
public function runMigrationList($path, $migrations, Extension $extension = null)
    {
        // First we will just make sure that there are any migrations to run. If there
        // aren't, we will just make a note of it to the developer so they're aware
        // that all of the migrations have been run against this database system.
        if (count($migrations) == 0) {
            $this->note('<info>Nothing to migrate.</info>');

            return;
        }

        // Once we have the array of migrations, we will spin through them and run the
        // migrations "up" so the changes are made to the databases. We'll then log
        // that the migration was run so we don't repeat it next time we execute.
        foreach ($migrations as $file) {
            $this->runUp($path, $file, $extension);
        }
    }
1019212
protected function registerMigrateCommand()
    {
        $this->app->singleton('command.module.migrate', function ($app) {
            return new \Caffeinated\Modules\Console\Commands\ModuleMigrateCommand($app['migrator'], $app['modules']);
        });

        $this->commands('command.module.migrate');
    }
1227716
public function up(Migration $migration)
    {
        if (!$migration->isNew()) {
            throw new \InvalidArgumentException(__METHOD__.": Expected NEW migration");
        }

        // Загрузить SQL
        $this->fileRepository->loadSql($migration);

        $func = function () use ($migration) {
            $this->_processMigrationSql($migration->getUp());
            $this->getDbRepository()->insert($migration);
        };

        $this->_processMigration($migration, $func);
    }
152373
public function executeMigrations($file, $migrations)
    {
        foreach ($migrations as $index => $migration) {
            $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration);
            $this->executeMigration($file, $migration);
        }
    }
1304085
public function exec()
    {
        $name = $this->argument('name');
        //
        $process = Migrations::add($name);
        //
        $this->show($process, $name);
    }
265203
protected function runMigrate($type)
    {
        if (FileHelper::isDir(Yii::getAlias($this->migrationPath))) {
            $action = "migrate/";
            switch ($type) {
                case 'up':
                    $action .= 'up';
                    break;
                case 'down':
                    $action .= 'down';
                    break;
                default:
                    throw new InvalidParamException('The "type" property is invalid.');
            }
            $cmd = "%s {$action} --migrationPath=%s --interactive=0 all";
            //执行
            WebConsoleHelper::run(sprintf($cmd,
                Yii::getAlias(WebConsoleHelper::getYiiCommand()),
                Yii::getAlias($this->migrationPath)
            ), false);
        }
    }
917981
public function handle(SingleCommand $command)
    {
        /** @var MigrationRunner $runner */
        $runner = $this->getRunner();
        $runner = $runner->withContext($command->getContext());
        $event = $runner->run(
            $command->getTarget(),
            $command->getOptions()
        );
        return $command->getVersionRepository()->update($event->getTarget());
    }
106350
private function executeMigrations()
    {
        if ($this->migrator->needsToRun()) {
            $latestVersion = $this->migrator->migrate();
            $this->logger->info('Migrate all migrations up to version ' . $latestVersion . '.');
        }
    }