Добавить Миграцию в базу

@param Migration $migration
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);
    }
457335
protected function hasMigrationApplied(AbstractMigration $migration)
    {
        // if the "applied-flow-migrations" section doesn't exist, we fall back to checking the git log for applied migrations for backwards compatibility
        if (!isset($this->currentPackageData['composerManifest']['extra']['applied-flow-migrations'])) {
            return Git::logContains($this->currentPackageData['path'], 'Migration: ' . $migration->getIdentifier());
        }
        return in_array($migration->getIdentifier(), $this->currentPackageData['composerManifest']['extra']['applied-flow-migrations']);
    }
1091014
public static function guess($migration)
    {
        foreach (self::CREATE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[1], $create = true];
            }
        }

        foreach (self::CHANGE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[2], $create = false];
            }
        }
    }
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);
    }
143738
protected function runDown($migration, $pretend)
    {
        $file = $migration->migration;

        // First we will get the file name of the migration so we can resolve out an
        // instance of the migration. Once we get an instance we can either run a
        // pretend execution of the migration or we can run the real migration.
        $instance = $this->resolve($file);

        if ($pretend) {
            return $this->pretendToRun($instance, 'down');
        }

        $instance->down();

        // Once we have successfully run the migration "down" we will remove it from
        // the migration repository so it will be considered to have not been run
        // by the application then will be able to fire by any later operation.
        $this->repository->delete($migration);

        $this->note("<info>Rolled back:</info> $file");
    }
274684
public function addUF($fields)
    {
        if (!$fields['FIELD_NAME']) {
            throw new MigrationException('Не заполнен FIELD_NAME');
        }

        if (!$fields['ENTITY_ID']) {
            throw new MigrationException('Не заполнен код ENTITY_ID');
        }

        $oUserTypeEntity = new CUserTypeEntity();

        $fieldId = $oUserTypeEntity->Add($fields);

        if (!$fieldId) {
            throw new MigrationException("Не удалось создать пользовательское свойство с FIELD_NAME = {$fields['FIELD_NAME']} и ENTITY_ID = {$fields['ENTITY_ID']}");
        }

        return $fieldId;
    }
633865
protected function importMigration(Migration $migration) {
    // Run dependencies first.
    $dependencies = $migration->getMigrationDependencies();
    $required_ids = $dependencies['required'];
    if ($required_ids) {
      $required_migrations = $this->migrationManager->createInstances($required_ids);
      array_walk($required_migrations, [$this, 'importMigration']);
    }

    $message = new MigrateMessage();
    $executable = new MigrateExecutable($migration, $message);
    $executable->import();
  }
761418
def save_migration(connection, basename):
    

    # Prepare query
    sql = "INSERT INTO migrations_applied (name, date) VALUES (%s, NOW())"

    # Run
    with connection.cursor() as cursor:
        cursor.execute(sql, (basename,))
        connection.commit()

    return True
374507
protected function registerMigrateMakeCommand(): void
    {
        $this->app->singleton('command.migrate.make', function ($app) {
            // Once we have the migration creator registered, we will create the command
            // and inject the creator. The creator is responsible for the actual file
            // creation of the migrations, and may be extended by these developers.
            $creator = $app['migration.creator'];

            $composer = $app['composer'];

            return new MigrateMakeCommand($creator, $composer);
        });
    }
1227280
private function createMigration($migration, $manifest = array(), $migrationName = '')
    {
        $empty = is_null($migration);
        $date = new DateTime();
        $name = 'm%s_migration';
        $description = [];

        if ($migrationName == '') {

            foreach ($manifest as $key => $value) {
                $description[] = $key;
                foreach ($value as $item) {
                    $description[] = $item;
                }
            }
        } else {
            $description[] = $migrationName;
        }

        if (!$empty || count($description)>0) {
            $description = implode('_', $description);
            $name .= '_' . MigrationManagerHelper::slugify($description);
        }

        $filename = sprintf($name, $date->format('ymd_His'));
        $filename = substr($filename, 0, 250);
        $filename = str_replace('-', '_', $filename);

        $migrator = Craft::$app->getContentMigrator();
        $migrationPath = $migrator->migrationPath;

        $path = sprintf($migrationPath . '/%s.php', $filename);

        $pathLen = strlen($path);
        if ($pathLen > 255) {
            $migrationPathLen = strlen($migrationPath);
            $filename = substr($filename, 0, 250 - $migrationPathLen);
            $path = sprintf($migrationPath . '/%s.php', $filename);
        }

        $migration = json_encode($migration, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        //escape backslashes
        //$migration = str_replace('\\', '\\\\', $migration);

        $content = Craft::$app->view->renderTemplate('migrationmanager/_migration', array('empty' => $empty, 'migration' => $migration, 'className' => $filename, 'manifest' => $manifest, true));

        FileHelper::writeToFile($path, $content);

        // mark the migration as completed if it's not a blank one
        if (!$empty) {
            $migrator->addMigrationHistory($filename);
        }
    }
1107415
public function migrates($migrate)
    {
        $token = $this->addTokenCallback($migrate['callback']);
        sd_call_user_func($migrate['callback'], new CoroutineChangeToken($token));
        unset($migrate['callback']);
        $migrate['token'] = $token;
        $this->execute($migrate);
    }
8515
public function completeUp(MigrationInterface $migration)
    {
        $query = (new InsertQueryBuilder())->into(static::tableName())->set([
            'id' => $migration->getTime(),
            'comment' => $migration->comment(),
        ]);

        $parsed = $query->parse($this->connection->getDialect());
        $this->connection->prepare($parsed->getSql())->execute($parsed->getArguments());
    }
1143697
public function migrationExists($migration, $destination)
	{
		$existing = $this->getExistingMigrationNames($destination);

		return in_array(substr(basename($migration), 18), $existing);
	}
1332406
protected function setContext(MigrationContext $context)
	{
		$this->_context = $context;
		$this->_context->setContainer($this->_container);
	}
1341001
public function storeMigrationContext($migrationName, array $context)
    {
        $this->createTableIfNeeded();

        // select for update

        // annoyingly enough, neither Doctrine nor EZP provide built in support for 'FOR UPDATE' in their query builders...
        // at least the doctrine one allows us to still use parameter binding when we add our sql particle
        $conn = $this->getConnection();

        $qb = $conn->createQueryBuilder();
        $qb->select('*')
            ->from($this->tableName, 'm')
            ->where('migration = ?');
        $sql = $qb->getSQL() . ' FOR UPDATE';

        $conn->beginTransaction();

        $stmt = $conn->executeQuery($sql, array($migrationName));
        $existingMigrationData = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (is_array($existingMigrationData)) {
            // context exists

            $conn->update(
                $this->tableName,
                array(
                    'context' => $this->contextToString($context),
                    'insertion_date' => time(),
                ),
                array('migration' => $migrationName)
            );
            $conn->commit();

        } else {
            // context did not exist. Create it!

            // commit immediately, to release the lock and avoid deadlocks
            $conn->commit();

            $conn->insert($this->tableName, array(
                'migration' => $migrationName,
                'context' => $this->contextToString($context),
                'insertion_date' => time(),
            ));
        }
    }
1233948
public function runSingleMigration($migration)
	{
		require_once $migration->path;
		$migrationClass = $migration->class_name;
		
		if (!class_exists($migrationClass)) {
			throw new MigrationClassNotFoundException(
				sprintf(
					'Migration class [%s] does not exist',
					$migrationClass
				)
			);
		}

		$class = new $migrationClass();

		if (Migration::migrationType() == Attribute::DOWNGRADE) {
			$class->down();
		}else{
			$class->up();
		}

		$migration = Model::findById($migration->id);
		$migration->status = 'migrated';
		$migration->save();

		$this->env->sendOutput(
			sprintf(
				'[%s] migration was successful',
				$migration->class_name
			),
			'green'
		);
	}
873117
public function log($file, $version)
	{
		$record = array('migration' => $file, 'version' => $version);

		$this->table()->insert($record);
	}