If a migration is supplied, runs that migration and appends to state.
        If run_all==True, runs all migrations.
        Raises a ValueError if neither "migration" nor "run_all" are provided.
972181
def __apply(self, migration=None, run_all=False):
        
        out = StringIO()
        trace = None

        migrate_kwargs = {
            'interactive': False,
            'stdout': out,
            'database': self._database_name,
        }
        if migration is not None:
            migrate_kwargs.update({
                'app_label': migration[0],
                'migration_name': migration[1],
            })
        elif not run_all:
            raise ValueError('Either a migration must be provided or "run_all" must be True')

        start = self._timer()
        try:
            call_command("migrate", **migrate_kwargs)
        except Exception:
            trace = ''.join(traceback.format_exception(*sys.exc_info()))
        finally:
            end = self._timer()
            successes, failure = self._parse_migrate_output(out.getvalue())

            self._migration_state.append({
                'database': self._database_name,
                'migration': 'all' if run_all else (migration[0], migration[1]),
                'duration': end - start,
                'output': _remove_escape_characters(out.getvalue()),
                'succeeded_migrations': successes,        # [(app, migration), ...]
                'failed_migration': failure,              # (app, migration)
                'traceback': trace,
                'succeeded': failure is None and trace is None,
            })

        if failure is not None:
            raise CommandError("Migration failed for app '{}' - migration '{}'.\n".format(*failure))
        elif trace is not None:
            raise CommandError("Migrations failed unexpectedly. See self.state['traceback'] for details.")
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);
    }
401369
def migrate(app_name=None, revision=None):
    ""
    cmd = ['python bin/manage.py syncdb --migrate']
    if app_name:
        cmd.append(app_name)
        if revision:
            cmd.append(revision)
    verun(' '.join(cmd))
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;
    }
1006841
def do_migration
      migration_exists = Dir["db/migrate/*_create_user_queues.rb"].count > 0

      if migration_exists and installing?
        puts "UserQ is already installed. Maybe a 'rake db:migrate' command might help?"
        return
      end

      create_migration

      puts "Success! UserQ is installed. You can now use it in your application." if installing?
      puts "UserQ has already been uninstalled. Remember the 'user_queue' table needs to be manually destroyed." if destroying? and migration_exists == false
      puts "Success! UserQ is uninstalled. The table 'userq_queue' needs to be destroyed manually to complete removal." if destroying? and migration_exists
  end
657705
def merge(self, name='initial'):
        """"""
        migrator = Migrator(self.database)
        migrate = compile_migrations(migrator, self.migrator.orm.values())
        if not migrate:
            return self.logger.error("Can't merge migrations")

        self.clear()

        self.logger.info('Merge migrations into "%s"', name)
        rollback = compile_migrations(self.migrator, [])
        name = self.compile(name, migrate, rollback, 0)

        migrator = Migrator(self.database)
        self.run_one(name, migrator, fake=True, force=True)
        self.logger.info('Migrations has been merged into "%s"', name)
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
714091
protected function checkLessonsMigrationState()
    {
        $this->output->info('# Checkin lessons migration state... #');

        switch ($this->checkLessonMigrationStats()) {
            case 0:
                return true;
            case 1:
                $this->output->error(' Migration stats does not match!');
                if ($this->output->confirm('Do you wish to continue (lesson_migration and scool lesson tables will be truncated)?')) {
                    DB::connection('ebre_escool')->statement('DELETE FROM lesson_migration');
                    DB::connection('ebre_escool')->statement('ALTER TABLE lesson_migration AUTO_INCREMENT = 1');
                    DB::statement('DELETE FROM lessons');
                    DB::statement('ALTER TABLE lessons AUTO_INCREMENT = 1');
                    DB::statement('DELETE FROM lesson_user');
                    DB::statement('ALTER TABLE lesson_user AUTO_INCREMENT = 1');
                    DB::statement('DELETE FROM lesson_submodule');
                    DB::statement('ALTER TABLE lesson_submodule AUTO_INCREMENT = 1');
                    DB::statement('DELETE FROM classroom_submodule');
                    DB::statement('ALTER TABLE classroom_submodule AUTO_INCREMENT = 1');
                } else {
                    die();
                }
                return true;
            case 2:
                $this->output->info(' Lesson data seems already migrated. Skipping lessons migration...');
                return false;
        }
    }
1026423
def set_current_migration(self, migration_number=None):
        
        self.migration_data.version = migration_number or self.latest_migration
        self.session.commit()
300407
def run_migration(connection, queries, engine):
    

    # Execute query
    with connection.cursor() as cursorMig:
        # Parse statements
        queries = parse_statements(queries, engine)

        for query in queries:
            cursorMig.execute(query)
        connection.commit()

    return True
403691
def migrate_data(self, data, from_state):
        
        if not self.default:
            return

        self.default.prepare(data, from_state)
        for instance in data:
            value = self.default.get_default_for(instance, from_state)
            if not value and not self.schema.get('required', True):
                continue

            # Set default value.
            container = getattr(instance, self.schema_type, {})
            dict_dot(container, '.'.join(self.field), value)
            setattr(instance, self.schema_type, container)
            instance.save()
824269
def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None):
    
    from django.core.management import call_command

    apps = [application]
    if extra_applications:
        if isinstance(extra_applications, text_type):
            apps += [extra_applications]
        elif isinstance(extra_applications, list):
            apps += extra_applications

    for app in apps:
        call_command('makemigrations', *(app,), merge=merge, dry_run=dry_run, empty=empty)
592141
def record_migration(plugin, filename, script, **kwargs):
    ''''''
    db = get_db()
    db.eval(RECORD_WRAPPER, plugin, filename, script)
    return True
58131
def produce_upgrade_operations(
        ctx=None, metadata=None, include_symbol=None, include_object=None,
        **kwargs):
    """"""
    if metadata is None:
        # Note, all SQLAlchemy models must have been loaded to produce
        # accurate results.
        metadata = db.metadata
    if ctx is None:
        ctx = create_migration_ctx(target_metadata=metadata, **kwargs)

    template_args = {}
    imports = set()

    _produce_migration_diffs(
        ctx, template_args, imports,
        include_object=include_object,
        include_symbol=include_symbol,
        **kwargs
    )

    return template_args
52399
def _run_up(self, path, migration_file, batch, pretend=False):
        
        migration = self._resolve(path, migration_file)

        if pretend:
            return self._pretend_to_run(migration, 'up')

        migration.up()

        self._repository.log(migration_file, batch)

        self._note('<info>✓ Migrated</info> %s' % migration_file)
1262943
def run_migrations():
    
    with engine.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=Model.metadata)

        with context.begin_transaction():
            context.run_migrations()
858429
def run(*migration_classes)
      opts = migration_classes.extract_options!
      dir = opts[:direction] || :up
      dir = (dir == :down ? :up : :down) if opts[:revert]
      if reverting?
        # If in revert and going :up, say, we want to execute :down without reverting, so
        revert { run(*migration_classes, direction: dir, revert: true) }
      else
        migration_classes.each do |migration_class|
          migration_class.new.exec_migration(connection, dir)
        end
      end
    end