Run a migration inside a transaction if the database supports it.

@param object $migration
@param string $method
502893
protected function runMigration($migration, $method)
    {
        $callback = function () use ($migration, $method) {
            if (method_exists($migration, $method)) {
                $migration->{$method}();
            }
        };

        $callback();
    }
1367146
public function down(Migration $migration, $loadFromFile = false)
    {
        if ($loadFromFile) {
            $this->fileRepository->loadSql($migration);
        } else {
            $this->dbRepository->loadSql($migration);
        }

        $func = function () use ($migration) {
            $this->_processMigrationSql($migration->getDown());
            $this->dbRepository->delete($migration);
        };

        $this->_processMigration($migration, $func);
    }
271966
private function checkFileBasedMigration(
        FileBasedMigration $migration,
        string $migrationName,
        OutputInterface $output
    ): int {
        $methods = ['upgrade' => 'preUp', 'downgrade' => 'preDown'];
        // the right way is to use the same schema that is passed to a real migration
        $schema = new Schema();
        foreach ($methods as $direction => $method) {
            $migration->{$method}($schema);
            if ($migration->getQueries()) {
                $output->writeln(
                    sprintf('<comment>%s by migration %s contains</comment>', ucfirst($direction), $migrationName)
                );
                $this->printQueries($migration->getQueries(), $output);
            } else {
                $output->writeln(
                    sprintf('<comment>%s by migration %s is empty</comment>', ucfirst($direction), $migrationName)
                );
            }
        }
        return 0;
    }
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);
    }
1116491
public static function prepareMigrationTable(App $app): void{
        $migration = new class($app) extends Migration{

            /**
             * Create the migration table if it does not exist yet
             */
            public function up(): void{
                $schema = $this->getSchema('default');
                if (!$schema->hasTable('migrations')) {
                    $schema->create('migrations', function (Blueprint $table){
                        $table->increments('id');
                        $table->string('name', 255);
                    });
                }
            }

            /**
             * Is not needed, but add it nevertheless
             */
            public function down(): void{
                $this->getSchema('default')->drop('migrations');
            }
        };
        $migration->up();
    }
1154022
private function executeRollBacks(array $migrations) : void
    {
        $this->connection->beginTransaction();

        foreach ($migrations as $migration) {
            $migration->down();
            $this->executedMigrations->delete(get_class($migration));
        }

        $this->connection->commit();
    }
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.');
        }
    }
1088709
public function deleteMigration(APIMigration $migration)
    {
        $this->createTableIfNeeded();
        $conn = $this->getConnection();
        $conn->delete($this->tableName, array('migration' => $migration->name));
    }
827854
def _pretend_to_run(self, migration, method):
        
        self._note("")
        names = []
        for query in self._get_queries(migration, method):
            name = migration.__class__.__name__
            bindings = None

            if isinstance(query, tuple):
                query, bindings = query

            query = highlight(query, SqlLexer(), CommandFormatter()).strip()

            if bindings:
                query = (query, bindings)

            if name not in names:
                self._note("[<info>{}</info>]".format(name))
                names.append(name)

            self._note(query)
152373
public function executeMigrations($file, $migrations)
    {
        foreach ($migrations as $index => $migration) {
            $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration);
            $this->executeMigration($file, $migration);
        }
    }
97247
protected function beforeProxy($method, $args)
    {
        // if method is defined as transaction method
        if (is_array($this->transactionMethods) && in_array($method, $this->transactionMethods)) {
            // begin transaction
            $this->db->beginTransaction();
        }
    }
1226887
protected function recordMigration(AbstractMigration $migration)
    {
        $query = 'INSERT INTO `app_migrations` (`timestamp`, `description`) VALUES ("%s", "%s")';
        $query = sprintf($query, $migration->getTimestamp(), $migration->getDescription());

        $this->db->query($query, DbAdapter::QUERY_MODE_EXECUTE);
    }
458360
public function addMethod(Method $method): void
    {
        $this->methods[(string) $method->getFqsen()] = $method;
    }
1135763
protected static function run($migrations, $name, $type, $method = 'up')
	{
		// storage for installed migrations
		$done = array();

		static::$connection === null or \DBUtil::set_connection(static::$connection);

		// Loop through the runnable migrations and run them
		foreach ($migrations as $ver => $migration)
		{
			logger(Fuel::L_INFO, 'Migrating to version: '.$ver);
			$result = call_user_func(array(new $migration['class'], $method));
			if ($result === false)
			{
				logger(Fuel::L_INFO, 'Skipped migration to '.$ver.'.');
				return false;
			}

			$file = basename($migration['path'], '.php');
			$method == 'up' ? static::write_install($name, $type, $file) : static::write_revert($name, $type, $file);
			$done[] = $file;
		}

		static::$connection === null or \DBUtil::set_connection(null);

		empty($done) or logger(Fuel::L_INFO, 'Migrated to '.$ver.' successfully.');

		return $done;
	}
1162603
private function checkMigrationExistance($migration)
    {
        $result = $this->getMigrationTable()
            ->where('migration', $migration)
            ->first();

        return !is_null($result);
    }
563559
protected function deleteMigrations(array $migrations)
	{
		if ( !$migrations ) {
			return;
		}

		$sql = 'DELETE FROM Migrations
				WHERE Name IN (:names)';
		$this->_context->getDatabase()->perform($sql, array('names' => $migrations));
	}
647658
private function alter($method)
	{
		$migration = new Migration(\App::get('db'));

		$name = null;
		if ($this->arguments->getOpt('name'))
		{
			$name = $this->arguments->getOpt('name');
		}

		if (!isset($name))
		{
			if ($this->output->isInteractive())
			{
				$name = $this->output->getResponse("What extension were you wanting to {$method}?");
			}
			else
			{
				$this->output = $this->output->getHelpOutput();
				$this->help();
				$this->output->render();
				return;
			}
		}

		$extensionType = substr($name, 0, 3);

		switch ($extensionType)
		{
			case 'com':
				if ($method == 'add' || $method == 'delete')
				{
					$extensionName = ucfirst(substr($name, 4));
					$mthd          = $method . 'ComponentEntry';
				}
				else
				{
					$extensionName = $name;
					$mthd          = $method . 'Component';
				}

				if (!method_exists($migration, $mthd))
				{
					$this->output->error('Sorry, components do not currently support the ' . $mthd . ' method');
				}

				$migration->$mthd($extensionName);
				break;

			case 'mod':
				$client = $this->arguments->getOpt('client', 'site');

				if ($method == 'install')
				{
					$mthd     = $method . 'Module';
					$position = $this->arguments->getOpt('position', null);

					if (!isset($position))
					{
						if ($this->output->isInteractive())
						{
							$position = $this->output->getResponse("Where should the module be positioned?");
						}
						else
						{
							$this->output->addLine('Please provide a position for the module', 'warning');
							return;
						}
					}

					if (!method_exists($migration, $mthd))
					{
						$this->output->error('Sorry, modules do not currently support the ' . $mthd . ' method');
					}

					$migration->$mthd(str_replace('mod_', '', $name), $position, true, '', (($client == 'admin') ? 1 : 0));
				}
				else
				{
					$mthd = $method . 'Module' . (($method == 'add' || $method == 'delete') ? 'Entry' : '');

					if (!method_exists($migration, $mthd))
					{
						$this->output->error('Sorry, modules do not currently support the ' . $mthd . ' method');
					}

					$migration->$mthd($name, 1, '', (($client == 'admin') ? 1 : 0));
				}
				break;

			case 'tpl':
				$mthd = $method . 'Template' . (($method == 'add' || $method == 'delete') ? 'Entry' : '');

				if (!method_exists($migration, $mthd))
				{
					$this->output->error('Sorry, templates do not currently support the ' . $mthd . ' method');
				}

				$element = $name = substr($name, 4);
				$name    = ucwords($name);
				$client  = $this->arguments->getOpt('client', 'site');
				$isCore  = $this->arguments->getOpt('core', false) ? 1 : 0;

				if ($method == 'delete')
				{
					$migration->$mthd($element, (($client == 'admin') ? 1 : 0));
				}
				else if ($method == 'add')
				{
					$migration->$mthd($element, $name, (($client == 'admin') ? 1 : 0), 1, 0, null, $isCore);
				}
				else
				{
					$migration->$mthd($element, $name, (($client == 'admin') ? 1 : 0), null, $isCore);
				}
				break;

			case 'plg':
				preg_match('/plg_([[:alnum:]]+)_([[:alnum:]]*)/', $name, $matches);

				if (!isset($matches[1]) || !isset($matches[2]))
				{
					$this->output->error('This does not appear to be a valid extension name.');
				}

				$folder  = $matches[1];
				$element = $matches[2];
				$mthd    = $method . 'Plugin' . (($method == 'add' || $method == 'delete') ? 'Entry' : '');

				if (!method_exists($migration, $mthd))
				{
					$this->output->error('Sorry, plugins do not currently support the ' . $mthd . ' method');
				}

				$migration->$mthd($folder, $element);
				break;

			default:
				$this->output->error('This does not appear to be a valid extension name.');
			break;
		}

		$this->output->addLine("Successfully {$method}" . ((substr($method, -1) == 'e') ? 'd' : 'ed') . " {$name}!", 'success');
	}