Used for running multiple migrations up to or down to a certain value.
186095
def migrate_without_lock
        if invalid_target?
          raise UnknownMigrationVersionError.new(@target_version)
        end

        result = runnable.each do |migration|
          execute_migration_in_transaction(migration, @direction)
        end

        record_environment
        result
      end
1260747
def compile(self, name, migrate='', rollback='', num=None):
        """"""
        if num is None:
            num = len(self.todo)

        name = '{:03}_'.format(num + 1) + name
        filename = name + '.py'
        path = os.path.join(self.migrate_dir, filename)
        with open(path, 'w') as f:
            f.write(MIGRATE_TEMPLATE.format(migrate=migrate, rollback=rollback, name=filename))

        return name
117409
def do_up(self, arg):
        """"""
        print "running up migration"
        self.manager.run(arg, Direction.UP)
867621
def execute_migrations(self, show_traceback=True):
        
        all_migrations = get_pending_migrations(self.path, self.databases)
        
        if not len(all_migrations):
            sys.stdout.write("There are no migrations to apply.\n")
        
        for db, migrations in all_migrations.iteritems():
            connection = connections[db]
            
            # init connection
            cursor = connection.cursor()
            cursor.close()
                        
            for migration in migrations:
                migration_path = self._get_migration_path(db, migration)
                
                with Transactional():
                    sys.stdout.write(
                        "Executing migration %r on %r...." %
                        (migration, db)
                    )
                    created_models = self._execute_migration(
                        db,
                        migration_path,
                        show_traceback=show_traceback
                    )

                    emit_post_sync_signal(
                        created_models=created_models,
                        verbosity=self.verbosity,
                        interactive=self.interactive,
                        db=db,
                    )
            
            if self.load_initial_data:
                sys.stdout.write(
                    "Running loaddata for initial_data fixtures on %r.\n" % db
                )
                call_command(
                    "loaddata",
                    "initial_data",
                    verbosity=self.verbosity,
                    database=db,
                )
854218
def forwards_migration(apps, schema_editor):
    
    RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
    for rrule in RecurrenceRule.objects.all():
        if ';\n' in rrule.recurrence_rule:
            parts = rrule.recurrence_rule.split(';\n')
            rrule.recurrence_rule = '\n'.join(parts)
            rrule.save()
1187239
public function runMigrations()
	{
		$migrations = Model::where('status', 'pending');

		if ($migrations->get()->size() > 0) {
			foreach($migrations->get()->all() as $migration) {
				$this->runSingleMigration($migration);
			}
		}
	}
1118794
public function help()
	{
		$this
			->output
			->addOverview(
				'Run a migration. This includes searching for migration files,
				depending on the options provided.'
			)
			->addTasks($this)
			->addArgument(
				'-d: direction [up|down]',
				'If not specified, defaults to "up".',
				'Example: -d=up or -d=down'
			)
			->addArgument(
				'-r: document root',
				'Specify the document root through which the the application
				will search for migrations directories. The primary use case
				for this is specifying an alternate directory for testing.
				By default, it will use the PATH_CORE constant for
				the document root.',
				'Example: -r=/www/myhub/unittests/migrations'
			)
			->addArgument(
				'-e: extension',
				'Explicity give the extension on which the migration should be run.
				This could be one of "com_componentname", "mod_modulename",
				or "plg_plugingroup_pluginname". This option is required
				when using the force (--force) option and the log only option (-m).',
				'Example: -e=com_courses, -e=plg_members_dashboard'
			)
			->addArgument(
				'-a: list all',
				'List all will display all migrations found, not just those needing
				to be run. This allows you to see the files that need to be run in the
				context of the other files that have already been run. This differs from
				the prior -i argument which was needed because, by default, only new
				files were considered for a run. Now, all files needing to be run are
				included by default, irrespective of whether or not they are dated after
				the last run migration.'
			)
			->addArgument(
				'-i: ignore dates',
				'DEPRECATED: Now functions as if the -a option were given.
				Using this option will scan for and run all migrations that haven\'t
				previously been run, irrespective of the date of the migration.
				This differs from the default behavior in that normally, only files
				dated after the last run date will be eligable to be included in the
				migration. This option also differs from force mode (--force) in that it
				will find all migrations, but only run those that haven\'t been run
				before (whereas --force will run them irrespective of whether or not it
				thinks they\'ve already been run). You do not have to use -e with this
				option. This option is necessary when needing to run migrations that
				have been skipped for one reason or another.'
			)
			->addArgument(
				'-f: full run',
				'By default, using the migration command without any options will run
				in dry-run mode (meaning no changes will actually be made), displaying
				the migrations that would be run, were the command to be fully executed.
				Use the "-f" (full run) option to do the full migration run.'
			)
			->addArgument(
				'-m: log only',
				'Using this option, a migration will run as normal, and log entries
				will be created, but the SQL itself will not be run. As a general
				precaution, this should not be run without the extension option (-e).
				The primary use case for this option would be marking a migration
				as run in the event that it had already been run (manually), yet
				not logged in the database.'
			)
			->addArgument(
				'--file: run a provided filed',
				'Provide the filename to be run. This and only this file will be run.
				This will automatically place the migration in (-i) mode, ignoring dates.
				It will not, however, force it to be run, if a log entry for this file
				and direction already exists. Use the (--force) option to override this
				behavior or run the opposite direction first.',
				'Example: --file=Migration20130101000000ComMigrations.php'
			)
			->addArgument(
				'--force: force mode',
				'This option should be used carefully. It will run a migration,
				even if it thinks it has already been run. When using this option,
				you must also give a specific extension using the (-e) option.'
			)
			->addArgument(
				'--email: send email',
				'Specify an email address to receive the output of this run. If no
				files are executed during the migration, an email will not be sent.',
				'Example: --email=sampleuser@hubzero.org'
			);
	}
1002784
public function apply()
    {

        $files = $this->getMigrationsFiles();
        $lastMigration = null;

        asort($files);

        foreach ($files as $key => $value) {
            if ($key <= $this->getVersion()) continue;
            include $this->migrateManager->storagePath . '/' . $value;
            $className = "Migration_$key";
            $class = new $className();
            $class->up();
            $lastMigration = $key;
            unset($class);
        }

        if (!is_null($lastMigration)) {
            $this->setVersion($lastMigration);
            echo Utils::colorize("Done!", "SUCCESS");
        } else {
            echo Utils::colorize("The latest version is already installed.", "NOTE");
        }

    }
1094417
public function migrateDown()
    {
        Schema::table('tddd_runs', function (Blueprint $table) {
            $table->text('log_old')->nullable();
        });

        Database::statement('update tddd_runs set log_old = log;');

        Schema::table('tddd_runs', function (Blueprint $table) {
            $table->dropColumn('log');
            $table->renameColumn('log_old', 'log');
        });
    }
1009657
def run_one(self, name, migrator, fake=True, downgrade=False, force=False):
        """"""
        try:
            migrate, rollback = self.read(name)
            if fake:
                with mock.patch('peewee.Model.select'):
                    with mock.patch('peewee.Query._execute'):
                        migrate(migrator, self.database, fake=fake)

                if force:
                    self.model.create(name=name)
                    self.logger.info('Done %s', name)

                migrator.clean()
                return migrator

            with self.database.transaction():
                if not downgrade:
                    self.logger.info('Migrate "%s"', name)
                    migrate(migrator, self.database, fake=fake)
                    migrator.run()
                    self.model.create(name=name)
                else:
                    self.logger.info('Rolling back %s', name)
                    rollback(migrator, self.database, fake=fake)
                    migrator.run()
                    self.model.delete().where(self.model.name == name).execute()

                self.logger.info('Done %s', name)

        except Exception:
            self.database.rollback()
            operation = 'Migration' if not downgrade else 'Rollback'
            self.logger.exception('%s failed: %s', operation, name)
            raise
1171806
function previous(version, migrations) {
  function cmp(a, b) { return parseInt(a, 10) > parseInt(b, 10); }
  var regex = RegExp('^(' + version + '):?.*$');
  var keys = _.keys(migrations).sort(cmp);
  for (var i = 0, found; i < keys.length; i++) {
    if (keys[i].match(regex)) {
      found = keys[i - 1];
      break;
    }
  }
  return found || '0000';
}
124819
private <N, S extends State, SV> void migrateStateValues(
		StateDescriptor<S, SV> stateDesc,
		Tuple2<ColumnFamilyHandle, RegisteredKeyValueStateBackendMetaInfo<N, SV>> stateMetaInfo) throws Exception {

		if (stateDesc.getType() == StateDescriptor.Type.MAP) {
			throw new StateMigrationException("The new serializer for a MapState requires state migration in order for the job to proceed." +
				" However, migration for MapState currently isn't supported.");
		}

		LOG.info(
			"Performing state migration for state {} because the state serializer's schema, i.e. serialization format, has changed.",
			stateDesc);

		// we need to get an actual state instance because migration is different
		// for different state types. For example, ListState needs to deal with
		// individual elements
		StateFactory stateFactory = STATE_FACTORIES.get(stateDesc.getClass());
		if (stateFactory == null) {
			String message = String.format("State %s is not supported by %s",
				stateDesc.getClass(), this.getClass());
			throw new FlinkRuntimeException(message);
		}
		State state = stateFactory.createState(
			stateDesc,
			stateMetaInfo,
			RocksDBKeyedStateBackend.this);
		if (!(state instanceof AbstractRocksDBState)) {
			throw new FlinkRuntimeException(
				"State should be an AbstractRocksDBState but is " + state);
		}

		@SuppressWarnings("unchecked")
		AbstractRocksDBState<?, ?, SV> rocksDBState = (AbstractRocksDBState<?, ?, SV>) state;

		Snapshot rocksDBSnapshot = db.getSnapshot();
		try (
			RocksIteratorWrapper iterator = RocksDBOperationUtils.getRocksIterator(db, stateMetaInfo.f0);
			RocksDBWriteBatchWrapper batchWriter = new RocksDBWriteBatchWrapper(db, getWriteOptions())
		) {
			iterator.seekToFirst();

			DataInputDeserializer serializedValueInput = new DataInputDeserializer();
			DataOutputSerializer migratedSerializedValueOutput = new DataOutputSerializer(512);
			while (iterator.isValid()) {
				serializedValueInput.setBuffer(iterator.value());

				rocksDBState.migrateSerializedValue(
					serializedValueInput,
					migratedSerializedValueOutput,
					stateMetaInfo.f1.getPreviousStateSerializer(),
					stateMetaInfo.f1.getStateSerializer());

				batchWriter.put(stateMetaInfo.f0, iterator.key(), migratedSerializedValueOutput.getCopyOfBuffer());

				migratedSerializedValueOutput.clear();
				iterator.next();
			}
		} finally {
			db.releaseSnapshot(rocksDBSnapshot);
			rocksDBSnapshot.close();
		}
	}
1356141
def migrate(engine, database, module, **kwargs):
    '''
    
    '''
    validate_args(engine, database, module)

    options = {
        'direction': kwargs.get('direction', 'up'),
        'fake': kwargs.get('fake', False),
        'force': kwargs.get('force', False),
        'migration': kwargs.get('migration', None),
        'transaction': kwargs.get('transaction', True),
    }

    Migration._meta.database = database
    migrator = DATABASE_MAP[engine](database, module, **options)
    migrator.run()
1256674
def makemigrations(self):
        ''' 
        '''

        UNCHANGED = []

        with Session(self.settings) as conn:
            cursor = conn.cursor()
            for name, model in self.models.items():
                print("Running migrations... on table: %s"%model.__name__.lower())
                columns = self.description(model)
        
                table = name.lower()
                QUERY = "CREATE TABLE IF NOT EXISTS %s ("%table

                for field, FieldType in model.columns.items():
                    QUERY += "%s %s, " % (field, FieldType)
                    # If no columns --> Table not created yet
                    if columns:
                        self.UpdateColums(cursor, field, FieldType, 
                            model, columns, UNCHANGED)

                QUERY = QUERY[:-2] + ") ENGINE=InnoDB"
            
                print(QUERY)
                
                try:
                    cursor.execute(QUERY)
                except mysql.Error as e:
                    raise e

            return True
191491
def migrate(name=None, database=None, directory=None, verbose=None, fake=False):
    """"""
    router = get_router(directory, database, verbose)
    migrations = router.run(name, fake=fake)
    if migrations:
        click.echo('Migrations completed: %s' % ', '.join(migrations))
1296780
public function runMigrations()
    {
        // Check we havy any
        if (!file_exists(DIR_MIGRATIONS)) {
            return 0;
        }

        // Have DB already?
        new MigrationEntityRepository;

        // Check we have DB structure and any migration applied
        $migrated_files = [];
        if (SQL::getInstance()->getTables()) {
            $migrated_files = MigrationEntityRepository::getInstance()->getPairs('filename', 'filename');
        }

        $existing_files = FileSystem::scanDirs(DIR_MIGRATIONS);
        if (!$existing_files) {
            return 0;
        }

        $to_migrate = [];
        // Filters migrations that are already done
        foreach ($existing_files as $file) {
            if (isset($migrated_files[$file['name']])) {
                continue;
            }

            $to_migrate[] = $file['name'];
        }

        // Run new migrations
        foreach ($to_migrate as $file) {
            $this->runMigrationFile($file);

            $this->setMigrationFileAsCompleted($file);
        }

        return count($to_migrate);
    }
722569
def run_migration_list(self, path, migrations, pretend=False):
        
        if not migrations:
            self._note("<info>Nothing to migrate</info>")

            return

        batch = self._repository.get_next_batch_number()

        for f in migrations:
            self._run_up(path, f, batch, pretend)