Run Migrations

@param $version
@throws CommandsException
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);
        }

    }
946181
protected function executeMigrations(array $migrations)
	{
		if ( !$migrations ) {
			return;
		}

		$db = $this->_context->getDatabase();

		foreach ( $migrations as $migration ) {
			$db->beginTransaction();
			$migration_type = pathinfo($migration, PATHINFO_EXTENSION);

			$this->_migrationRunners[$migration_type]->run(
				$this->_migrationsDirectory . '/' . $migration,
				$this->_context
			);

			$sql = 'INSERT INTO Migrations (Name, ExecutedOn)
					VALUES (:name, :executed_on)';
			$db->perform($sql, array('name' => $migration, 'executed_on' => time()));
			$db->commit();
		}
	}
697602
public function up()
    {
        $driver = Schema::getConnection()->getDriverName();
        // Even though we take care of this scenario in the code,
        // SQL Server does not allow potential cascading loops,
        // so set the default no action and clear out created/modified by another user when deleting a user.
        $onDelete = (('sqlsrv' === $driver) ? 'no action' : 'set null');

        $output = new ConsoleOutput();
        $output->writeln("Migration driver used: $driver");

        // User table
        Schema::create(
            'user',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('name');
                $t->string('first_name')->nullable();
                $t->string('last_name')->nullable();
                $t->dateTime('last_login_date')->nullable();
                $t->string('email')->unique();
                $t->text('password')->nullable();
                $t->boolean('is_sys_admin')->default(0);
                $t->boolean('is_active')->default(1);
                $t->string('phone', 32)->nullable();
                $t->string('security_question')->nullable();
                $t->text('security_answer')->nullable();
                $t->string('confirm_code')->nullable();
                $t->integer('default_app_id')->unsigned()->nullable();
                $t->rememberToken();
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Password reset table
        Schema::create(
            'password_resets',
            function (Blueprint $t){
                $t->string('email')->index();
                $t->string('token')->index();
                $t->timestamp('created_date')->nullable();
            }
        );

        // Services
        Schema::create(
            'service',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('name', 40)->unique();
                $t->string('label', 80);
                $t->string('description')->nullable();
                $t->boolean('is_active')->default(0);
                $t->string('type', 40);
                $t->boolean('mutable')->default(1);
                $t->boolean('deletable')->default(1);
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Service API Docs
        Schema::create(
            'service_doc',
            function (Blueprint $t){
                $t->integer('service_id')->unsigned()->primary();
                $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                $t->integer('format')->unsigned()->default(0);
                $t->mediumText('content')->nullable();
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
            }
        );

        // Roles
        Schema::create(
            'role',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('name', 64)->unique();
                $t->string('description')->nullable();
                $t->boolean('is_active')->default(0);
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Roles to Services Allowed Accesses
        Schema::create(
            'role_service_access',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->integer('role_id')->unsigned();
                $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
                $t->integer('service_id')->unsigned()->nullable();
                $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                $t->string('component')->nullable();
                $t->integer('verb_mask')->unsigned()->default(0);
                $t->integer('requestor_mask')->unsigned()->default(0);
                $t->text('filters')->nullable();
                $t->string('filter_op', 32)->default('and');
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Email Templates
        Schema::create(
            'email_template',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('name', 64)->unique();
                $t->string('description')->nullable();
                $t->text('to')->nullable();
                $t->text('cc')->nullable();
                $t->text('bcc')->nullable();
                $t->string('subject', 80)->nullable();
                $t->text('body_text')->nullable();
                $t->text('body_html')->nullable();
                $t->string('from_name', 80)->nullable();
                $t->string('from_email')->nullable();
                $t->string('reply_to_name', 80)->nullable();
                $t->string('reply_to_email')->nullable();
                $t->text('defaults')->nullable();
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        //Cors config table
        Schema::create(
            'cors_config',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('path')->unique();
                $t->string('origin')->nullable();
                $t->text('header')->nullable();
                $t->integer('method')->unsigned()->default(0);
                $t->integer('max_age')->unsigned()->default(0);
                $t->boolean('enabled')->default(true);
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Applications
        Schema::create(
            'app',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->string('name', 64)->unique();
                $t->string('api_key')->nullable();
                $t->string('description')->nullable();
                $t->boolean('is_active')->default(0);
                $t->integer('type')->unsigned()->default(0);
                $t->text('path')->nullable();
                $t->text('url')->nullable();
                $t->integer('storage_service_id')->unsigned()->nullable();
                $t->foreign('storage_service_id')->references('id')->on('service')->onDelete('set null');
                $t->string('storage_container', 255)->nullable();
                $t->boolean('requires_fullscreen')->default(0);
                $t->boolean('allow_fullscreen_toggle')->default(1);
                $t->string('toggle_location', 64)->default('top');
                $t->integer('role_id')->unsigned()->nullable();
                $t->foreign('role_id')->references('id')->on('role')->onDelete('set null');
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // App relationship for user
        Schema::create(
            'user_to_app_to_role',
            function (Blueprint $t){
                $t->increments('id');
                $t->integer('user_id')->unsigned();
                $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
                $t->integer('app_id')->unsigned();
                $t->foreign('app_id')->references('id')->on('app')->onDelete('cascade');
                $t->integer('role_id')->unsigned();
                $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
            }
        );

        // JSON Web Token to system resources map
        Schema::create(
            'token_map',
            function (Blueprint $t){
                $t->integer('user_id')->unsigned();
                $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
                $t->text('token');
                $t->integer('iat')->unsigned();
                $t->integer('exp')->unsigned();
            }
        );

        Schema::create(
            'file_service_config',
            function (Blueprint $t){
                $t->integer('service_id')->unsigned()->primary();
                $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                $t->text('public_path')->nullable();
                $t->text('container')->nullable();
            }
        );

        Schema::create(
            'service_cache_config',
            function (Blueprint $t){
                $t->integer('service_id')->unsigned()->primary();
                $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                $t->boolean('cache_enabled')->default(0);
                $t->integer('cache_ttl')->unsigned()->default(0);
            }
        );

        // System Configuration
        Schema::create(
            'system_config',
            function (Blueprint $t) use ($onDelete){
                $t->integer('service_id')->unsigned()->primary();
                $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                $t->integer('default_app_id')->unsigned()->nullable();
                $t->foreign('default_app_id')->references('id')->on('app')->onDelete('set null');
                $t->integer('invite_email_service_id')->unsigned()->nullable();
                $t->foreign('invite_email_service_id')->references('id')->on('service')->onDelete($onDelete);
                $t->integer('invite_email_template_id')->unsigned()->nullable();
                $t->foreign('invite_email_template_id')->references('id')->on('email_template')->onDelete($onDelete);
                $t->integer('password_email_service_id')->unsigned()->nullable();
                $t->foreign('password_email_service_id')->references('id')->on('service')->onDelete($onDelete);
                $t->integer('password_email_template_id')->unsigned()->nullable();
                $t->foreign('password_email_template_id')->references('id')->on('email_template')->onDelete($onDelete);
            }
        );

        // create system customizations
        Schema::create(
            'system_custom',
            function (Blueprint $t) use ($onDelete){
                $t->string('name')->primary();
                $t->mediumText('value')->nullable();
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );

        // Lookups
        Schema::create(
            'lookup',
            function (Blueprint $t) use ($onDelete){
                $t->increments('id');
                $t->integer('app_id')->unsigned()->nullable();
                $t->foreign('app_id')->references('id')->on('app')->onDelete('cascade');
                $t->integer('role_id')->unsigned()->nullable();
                $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
                $t->integer('user_id')->unsigned()->nullable();
                $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
                $t->string('name');
                $t->text('value')->nullable();
                $t->boolean('private')->default(0);
                $t->text('description')->nullable();
                $t->timestamp('created_date')->nullable();
                $t->timestamp('last_modified_date')->useCurrent();
                $t->integer('created_by_id')->unsigned()->nullable();
                $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                $t->integer('last_modified_by_id')->unsigned()->nullable();
                $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
            }
        );
    }
978603
public static function up($version = null, $name = 'default', $type = 'app')
	{
		// get the current version info from the config
		$current = \Config::get('migrations.version.'.$type.'.'.$name);

		// get the last migration installed
		$current = empty($current) ? null : end($current);

		// get the available migrations after the current one
		$migrations = static::find_migrations($name, $type, $current, $version);

		// found any?
		if ( ! empty($migrations))
		{
			// if no version was given, only install the next migration
			is_null($version) and $migrations = array(reset($migrations));

			// install migrations found
			return static::run($migrations, $name, $type, 'up');
		}

		// nothing to migrate
		return array();
	}
861566
public function hasVersionMigrated(Version $version)
    {
        $this->createMigrationCollection();

        $record = $this->getCollection()->findOne(['v' => $version->getVersion()]);

        return null !== $record;
    }
1227237
public static function setApplicationVersion(string $version): void
    {
        if (self::isCliApp()) {
            self::$APPLICATION_VERSION = $version;
        } else {
            MSession::set(MCoreApplication::APPLICATION_VERSION, $version);
        }
    }
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;
    }
849190
public function setVersion(string $version)
    {
        if (Validation::isValidVersionRegex($version)) {
            $this->version = $version;
        } else {
            throw new CustomException('Malformed version');
        }
    }
479
public function savePreviousVersion($version)
    {
        if (!is_numeric($version)) {
            return;
        }

        try {
            $this->setVersionNumber($version);
            $this->owner->write();
        } catch (Exception $e) {
            throw new ValidationException(new ValidationResult(
                false,
                "Could not replace file #{$this->owner->ID} with version #$version."
            ));
        }
    }
1252544
public function run($path)
    {

        $this->createMigrationRepository();
        $repository = $this->migrator->getRepository();
        $migrations = $this->migrator->getMigrationFiles($path);
        $ran        = $repository->getRan();
        if (!empty($migrations)) {
            $files = array_keys($migrations);
            foreach ($files as $name) {
                if (!in_array($name, $ran)) {
                    continue;
                }
                $migration            = new stdClass();
                $migration->migration = $name;
                $repository->delete($migration);
            }
        }


        $this->migrator->run($path);
    }
1006020
protected function runClosureMigration($migration, $direction = 'up')
    {
        if (is_array($migration) && array_key_exists($direction, $migration)) {
            call_user_func($migration[$direction], $this->schemaBuilder);
        } else {
            throw new Exception('Migration file should contain an array with up/down.');
        }
    }
663212
protected function migrateUp(MigrationInterface $migration)
    {
        echo "\nm_".$migration->getTime()." ... ";
        $migration->up();
        $this->createManager($migration->getConnection())->completeUp($migration);
        echo "OK";
    }
686115
public function saveLastProcessedVersion($version)
    {
        $this->lastProcessedVersion = $version;
        $this->myCreateColumn       = null;
        $this->deleteFromSQL(['serverurl' => constant('FLEXIBEE_URL')]);
        if (is_null($this->insertToSQL(['serverurl' => constant('FLEXIBEE_URL'),
                    'changeid' => $version]))) {
            $this->addStatusMessage(_("Last Processed Change ID Saving Failed"),
                'error');
        } else {
            if ($this->debug === true) {
                $this->addStatusMessage(sprintf(_('Last Processed Change ID #%s Saved'),
                        $version));
            }
        }
    }
1180718
public function migrate($version = null, $message = null, $up = true)
    {
        return $this->execute($version, $message, $up);
    }
150453
public function generateMigration($version = null)
    {
        $path = dirname($this->getIdentifier()->filepath).'/migrations';
        $next = $this->getMaxVersion() + 1;
        $migration_file = "$path/$next.php";
        if (!file_exists($migration_file)) {
            //create the directory
            if (!file_exists(dirname($migration_file))) {
                mkdir(dirname($migration_file), 0755, true);
            }
            $class_name = 'Com'.ucfirst($this->getComponent()).'SchemaMigration'.$next;
            $component = ucfirst($this->getComponent());
            $content = <<<EOF
<?php

/**
 * LICENSE: ##LICENSE##
 *
 * @package    Com_{$component}
 * @subpackage Schema_Migration
 */

/**
 * Schema Migration
 *
 * @package    Com_{$component}
 * @subpackage Schema_Migration
 */
class $class_name extends ComMigratorMigrationVersion
{
   /**
    * Called when migrating up
    */
    public function up()
    {
        //add your migration here
    }

   /**
    * Called when rolling back a migration
    */
    public function down()
    {
        //add your migration here
    }
}
EOF;
            file_put_contents($migration_file, $content);
        }
    }
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;
    }
799042
public static function run($version, $deployFile)
    {
        // Init Deployer
        $console = new Application('Deployer', $version);
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        $deployer = new self($console);

        // Pretty-print uncaught exceptions in symfony-console
        set_exception_handler(function ($e) use ($input, $output, $deployer) {
            $io = new SymfonyStyle($input, $output);
            $io->block($e->getMessage(), get_class($e), 'fg=white;bg=red', ' ', true);
            $io->block($e->getTraceAsString());

            $deployer->logger->log('['. get_class($e) .'] '. $e->getMessage());
            $deployer->logger->log($e->getTraceAsString());
            exit(1);
        });

        // Require deploy.php file
        if (is_readable($deployFile)) {
            // Prevent variable leak into deploy.php file
            call_user_func(function () use ($deployFile) {
                require $deployFile;
            });
        }

        // Run Deployer
        $deployer->init();
        $console->run($input, $output);
    }