Execute migrate.

@param string $version The version of migration to rollback or migrate.

@return integer Number of executed migrations.
18648
private function execute($version = null, $message = null, $up = true)
    {
        $files = $this->migrationFiles->get($version, $up);
        if (null === $files) {
            return 0;
        }
        $this->schemaManipulation->execute('BEGIN');
        try {
            foreach ($files as $file) {

                require_once $file->getPath();

                $definition = $this->createMigrationApiInstance($file->getClassName());

                if ($message) {
                    $message($file->getName(), $file->getVersion());
                }
                if ($up) {
                    $definition->up();
                } else {
                    $definition->down();
                }
                foreach ($definition->getActions() as $action) {
                    if (!is_callable($action)) {
                        throw new \InvalidArgumentException('Migration must be callable');
                    }
                    $action = call_user_func_array($action, array());
                    if ($action instanceof MigrationApi) {
                        $action->execute();
                    }
                }
                $this->schemaTable->migrateToVersion($file->getVersion(), $up);
            }
            $this->schemaManipulation->execute('COMMIT');
        } catch (\Exception $e) {
            $this->schemaManipulation->execute('ROLLBACK');
            throw $e;
        }

        return count($files);
    }
901879
public function execute($exitCode = false): int
	{
		$migrations = $this->getOutstanding();

		if(($count = count($migrations)) > 0)
		{
			$message = $count === 1 ? 'There is %s outstanding migration:' : 'There are %s outstanding migrations:';

			$this->write(vsprintf($message, ['<yellow>' . $count . '</yellow>']) . PHP_EOL);

			$this->outputMigrationList($migrations);
		}
		else
		{
			$this->write('<green>There are no outstanding migrations.</green>');
		}

		return ($exitCode && $count > 0) ? static::STATUS_ERROR : static::STATUS_SUCCESS;
	}
502893
protected function runMigration($migration, $method)
    {
        $callback = function () use ($migration, $method) {
            if (method_exists($migration, $method)) {
                $migration->{$method}();
            }
        };

        $callback();
    }
841673
private function getLegacyMigrationDefinition($version, $bundle)
    {
        if (!isset($this->activeBundles[$bundle])) {
            return false;
        }

        $versionsDir = $this->activeBundles[$bundle] . '/' . $this->legacyMigrationsDir;
        $versionDefinitions = glob($versionsDir . "/$version*");

        if (!is_array($versionDefinitions)) {
            return false;
        }

        foreach ($versionDefinitions as $key => $versionDefinition) {
            if (!in_array(pathinfo($versionDefinition, PATHINFO_EXTENSION), array('php', 'yml', 'sql'))) {
                unset($versionDefinitions[$key]);
            }
        }

        if (empty($versionDefinitions)) {
            return false;
        }

        return $versionDefinitions[0];
    }
1128253
public function migrationClass($group, $version)
    {
        $versions = array_get($this->migrations, $group, []);

        return array_get($versions, $version, null);
    }
201783
public function migrate($version = null)
    {
        $migrations     = $this->getMigrations();
        $versions       = $this->getVersions();
        $currentVersion = $this->getCurrentVersion();

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

        if ($version === null) {
            $version = max(array_merge($versions, array_keys(iterator_to_array($migrations))));
        } else {
            if ($version != 0 && empty($migrations[$version])) {
                throw new \RuntimeException('Version is not valid.');
            }
        }

        // Prepare SQL logs
        if (is_file($this->getLogFile())) {
            File::delete($this->getLogFile());
        }

        Folder::create(dirname($this->getLogFile()));

        $queryLogStream = new Stream($this->getLogFile(), Stream::MODE_WRITE_ONLY_FROM_END);
        $logListener = function (Event $event) use ($queryLogStream) {
            $queryLogStream->write($event['query'] . ";\n\n");
        };
        Ioc::getDispatcher()->listen('onMigrationAfterQuery', $logListener);

        $direction = ($version > $currentVersion) ? AbstractMigration::UP : AbstractMigration::DOWN;

        $migrations = iterator_to_array($migrations);

        $count = 0;

        try {
            if ($direction === AbstractMigration::DOWN) {
                krsort($migrations);

                foreach ($migrations as $migration) {
                    if ($migration['version'] <= $version) {
                        break;
                    }

                    if (in_array($migration['version'], $versions)) {
                        $this->executeMigration($migration, AbstractMigration::DOWN);
                    }

                    $count++;
                }
            }

            ksort($migrations);

            foreach ($migrations as $migration) {
                if ($migration['version'] > $version) {
                    break;
                }

                if (!in_array($migration['version'], $versions, true)) {
                    $this->executeMigration($migration, AbstractMigration::UP);
                }

                $count++;
            }
        } catch (\PDOException $e) {
            $queryLogStream->write("-- ERROR: {$e->getMessage()}\n" . $this->db->getQuery());

            throw $e;
        }

        Ioc::getDispatcher()->removeListener($logListener);

        if (!$count) {
            $this->out('No change.');
        }
    }
1175692
public function rollback()
    {
        $migrations = $this->getLast($this->getMigrations(true));

        $this->requireFiles($migrations->toArray());

        $migrated = [];

        foreach ($migrations as $migration) {
            $data = $this->find($migration);

            if ($data->count()) {
                $migrated[] = $migration;

                $this->down($migration);

                $data->delete();
            }
        }

        return $migrated;
    }
924174
protected function addMigrationHistory(string $version, ?string $namespace = null): void
    {
        $this->stdout(' > Adding migration history entry ...', Console::FG_YELLOW);

        $this->db->createCommand()->insert(
            $this->migrationTable,
            [
                'version' => ($namespace ? $namespace . '\\' : '') . $version,
                'apply_time' => time(),
            ]
        )->execute();

        $this->stdout("DONE.\n", Console::FG_GREEN);
    }
204967
public static function down($version = null, $name = 'default', $type = 'app')
	{
		// get the current version info from the config
		$current = \Config::get('migrations.version.'.$type.'.'.$name);

		// any migrations defined?
		if ( ! empty($current))
		{
			// get the last entry
			$current = end($current);

			// get the available migrations before the last current one
			$migrations = static::find_migrations($name, $type, $version, $current, 'down');

			// found any?
			if ( ! empty($migrations))
			{
				// if no version was given, only revert the last migration
				if (is_null($version))
				{
					$migrations = array_slice($migrations, -1, 1, true);
				}
				else
				{
					// we're going down, so reverse the order of migrations
					$migrations = array_reverse($migrations, true);
				}

				// revert the installed migrations
				return static::run($migrations, $name, $type, 'down');
			}
		}

		// nothing to migrate
		return array();
	}
1095507
public function updateMigrationVersion($migration)
    {
        $date = new \DateTime('now');

        $date->setTimezone(new \DateTimeZone(SET_TIME_ZONE));

        $migrationName = $migration->getVersion().$migration->getMigrationClass();

        $this->connect(
            trim($this->getDefaultDatabaseConnection()),
            'migrations'
        );

        $sql = "INSERT INTO migrations (`migration`,  `version`)
                VALUES('".$migrationName."',
                          '".$migration->getVersion()."'
                      )";

        return $this->_connection->prepare($sql)->execute();
    }
1227253
public function perform()
    {
        if (!$this->verifyConfigured() || !$this->verifyEnvironment()) {
            return;
        }

        $found = false;
        $count = $this->option('one') ? 1 : PHP_INT_MAX;

        while ($count > 0 && ($migration = $this->migrator->run())) {
            $found = true;
            $count--;

            $this->sprintf(
                "<info>Migration <comment>%s</comment> was successfully executed.</info>",
                $migration->getState()->getName()
            );
        }

        if (!$found) {
            $this->writeln("<fg=red>No outstanding migrations were found.</fg=red>");
        }
    }
384761
public function migrateToVersion($version, $up = true)
    {
        $this->createIfNotExists();
        $currentVersion = $this->getCurrentVersion();
        if ($up) {
            $this->up($version);
        } else {
            $this->down($version);
        }
    }
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;
    }
123955
protected function loadConfiguration($version)
    {
        if (!$this->isVersionAvailable($version)) {
            throw new MigrationException('The requested YamlConfiguration was not available.', 1345822283);
        }

        $configuration = $this->yamlSourceImporter->load(substr($this->availableVersions[$version]['filePathAndName'], 0, -5));
        return $configuration;
    }
1226981
public function toggleBreakpoint($environment, $version)
    {
        $migrations = $this->getMigrations($environment);
        $this->getMigrations($environment);
        $env = $this->getEnvironment($environment);
        $versions = $env->getVersionLog();

        if (empty($versions) || empty($migrations)) {
            return;
        }

        if ($version === null) {
            $lastVersion = end($versions);
            $version = $lastVersion['version'];
        }

        if (0 != $version && !isset($migrations[$version])) {
            $this->output->writeln(sprintf(
                '<comment>warning</comment> %s is not a valid version',
                $version
            ));

            return;
        }

        $env->getAdapter()->toggleBreakpoint($migrations[$version]);

        $versions = $env->getVersionLog();

        $this->getOutput()->writeln(
            ' Breakpoint ' . ($versions[$version]['breakpoint'] ? 'set' : 'cleared') .
            ' for <info>' . $version . '</info>' .
            ' <comment>' . $migrations[$version]->getName() . '</comment>'
        );
    }
1311245
protected function runMigration(object $migration, string $method, ?int $batch = null): void
	{
		$migrationInstance = $this->resolve($migration);

		$migrationWrapper = $this->buildMigrationWrapper($migration, $migrationInstance, $method, $batch);

		if($migrationInstance->useTransaction())
		{
			$migrationInstance->getConnection()->transaction(function() use ($migrationWrapper): void
			{
				$migrationWrapper();
			});

			return;
		}

		$migrationWrapper();
	}
29440
public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setOutput($output);
        $this->setVerbosity($output->getVerbosity());

        if ($input->getOption('list-types')) {
            $this->listAvailableTypes($output);
            return 0;
        }

        $bundleName = $input->getArgument('bundle');
        if ($bundleName === null) {
            // throw same exception as SF would when declaring 'bundle' as mandatory arg
            throw new \RuntimeException('Not enough arguments (missing: "bundle").');
        }
        $name = $input->getArgument('name');
        $fileType = $input->getOption('format');
        $migrationType = $input->getOption('type');
        $matchType = $input->getOption('match-type');
        $matchValue = $input->getOption('match-value');
        $matchExcept = $input->getOption('match-except');
        $mode = $input->getOption('mode');
        $dbServer = $input->getOption('dbserver');

        if ($bundleName == $this->thisBundle) {
            throw new \InvalidArgumentException("It is not allowed to create migrations in bundle '$bundleName'");
        }

        // be kind to lazy users
        if ($migrationType == '') {
            if ($fileType == 'sql') {
                $migrationType = 'db';
            } elseif ($fileType == 'php') {
                $migrationType = 'php';
            } else {
                $migrationType = 'generic';
            }
        }

        if (!in_array($fileType, $this->availableMigrationFormats)) {
            throw new \InvalidArgumentException('Unsupported migration file format ' . $fileType);
        }

        if (!in_array($mode, $this->availableModes)) {
            throw new \InvalidArgumentException('Unsupported migration mode ' . $mode);
        }

        $migrationDirectory = $this->getMigrationDirectory($bundleName);

        if (!is_dir($migrationDirectory)) {
            $output->writeln(sprintf(
                "Migrations directory <info>%s</info> does not exist. I will create it now....",
                $migrationDirectory
            ));

            if (mkdir($migrationDirectory, self::DIR_CREATE_PERMISSIONS, true)) {
                $output->writeln(sprintf(
                    "Migrations directory <info>%s</info> has been created",
                    $migrationDirectory
                ));
            } else {
                throw new FileException(sprintf(
                    "Failed to create migrations directory %s.",
                    $migrationDirectory
                ));
            }
        }

        // allow to generate migrations for many entities
        if (strpos($matchValue, ',') !== false ) {
            $matchValue = explode(',', $matchValue);
        }

        $parameters = array(
            'dbserver' => $dbServer,
            'matchType' => $matchType,
            'matchValue' => $matchValue,
            'matchExcept' => $matchExcept,
            'mode' => $mode,
            'lang' => $input->getOption('lang'),
            'adminLogin' => $input->getOption('admin-login')
            /// @todo should we allow users to specify this ?
            //'forceSigchildEnabled' => null
        );

        $date = date('YmdHis');

        switch ($fileType) {
            case 'sql':
                /// @todo this logic should come from the DefinitionParser, really
                if ($name != '') {
                    $name = '_' . ltrim($name, '_');
                }
                $fileName = $date . '_' . $dbServer . $name . '.sql';
                break;

            case 'php':
                /// @todo this logic should come from the DefinitionParser, really
                $className = ltrim($name, '_');
                if ($className == '') {
                    $className = 'Migration';
                }
                // Make sure that php class names are unique, not only migration definition file names
                $existingMigrations = count(glob($migrationDirectory . '/*_' . $className . '*.php'));
                if ($existingMigrations) {
                    $className = $className . sprintf('%03d', $existingMigrations + 1);
                }
                $parameters = array_merge($parameters, array(
                    'class_name' => $className
                ));
                $fileName = $date . '_' . $className . '.php';
                break;

            default:
                if ($name == '') {
                    $name = 'placeholder';
                }
                $fileName = $date . '_' . $name . '.' . $fileType;
        }

        $path = $migrationDirectory . '/' . $fileName;

        $warning = $this->generateMigrationFile($path, $fileType, $migrationType, $parameters);

        $output->writeln(sprintf("Generated new migration file: <info>%s</info>", $path));

        if ($warning != '') {
            $output->writeln("<comment>$warning</comment>");
        }

        return 0;
    }