Migration utils [create, run, undo, redo].
489711
def migrate(action):
    "  "
    from flaskext.evolution import Evolution
    from flask import current_app
    evolution = Evolution(current_app)
    evolution.manager(action)
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)
750646
def compile_migrations(migrator, models, reverse=False):
    """"""
    source = migrator.orm.values()
    if reverse:
        source, models = models, source

    migrations = diff_many(models, source, migrator, reverse=reverse)
    if not migrations:
        return False

    migrations = NEWLINE + NEWLINE.join('\n\n'.join(migrations).split('\n'))
    return CLEAN_RE.sub('\n', migrations)
879674
def up(self, migration_id=None, fake=False):
        """"""
        if not self.check_directory():
            return

        for migration in self.get_migrations_to_up(migration_id):
            logger.info('Executing migration: %s' % migration.filename)

            migration_module = self.load_migration_file(migration.filename)
            if not fake:
                if hasattr(migration_module, 'up'):
                    migration_module.up(self.db)
                else:
                    logger.error('No up method on migration %s' % migration.filename)

            record = migration.as_dict()
            record['date'] = datetime.utcnow()
            self.collection.insert(record)
134188
public function up()
    {
        // We need a better way of handling data migrations...
        $system = app(System::class);
        $prefix = $system->getTablePrefix();
        DB::update("INSERT INTO {$prefix}schedules (name, message, scheduled_at, created_at, updated_at) SELECT name, message, scheduled_at, created_at, updated_at FROM {$prefix}incidents WHERE scheduled_at IS NOT NULL");

        DB::table('incidents')->whereNotNull('scheduled_at')->delete();

        Schema::table('incidents', function (Blueprint $table) {
            $table->dropColumn('scheduled_at');
        });
    }
764589
def create_migrations
      Dir["#{self.class.source_root}/migrations/*.rb"].sort.each do |filepath|
        name = File.basename(filepath)
        template "migrations/#{name}", "db/migrate/#{name}"
        sleep 1
      end
    end
33941
def execute(self, i, o):
        
        super(MigrateMakeCommand, self).execute(i, o)

        creator = MigrationCreator()

        name = i.get_argument('name')
        table = i.get_option('table')
        create = bool(i.get_option('create'))

        if not table and create is not False:
            table = create

        path = i.get_option('path')
        if path is None:
            path = self._get_migration_path()

        file_ = self._write_migration(creator, name, table, create, path)

        o.writeln('<info>Create migration: <comment>%s</comment></info>' % file_)
256231
public function migrateUp()
    {
        Schema::table('tddd_suites', function (Blueprint $table) {
            $table->string('coverage_enabled')->boolean(false);

            $table->string('coverage_index')->nullable();
        });
    }
1187239
public function runMigrations()
	{
		$migrations = Model::where('status', 'pending');

		if ($migrations->get()->size() > 0) {
			foreach($migrations->get()->all() as $migration) {
				$this->runSingleMigration($migration);
			}
		}
	}
1351003
public function up()
    {
        $this->table('phinxlog')
            ->addColumn('version', 'integer', [
                'limit'  => 11,
                'null'   => false,
                'signed' => false
            ])
            ->addColumn('migration_name', 'string', [
                'limit'   => 100,
                'default' => null,
                'null'    => true
            ])
            ->addColumn('start_time', 'datetime', [
                'limit'   => null,
                'null'    => true,
                'default' => 'CURRENT_TIMESTAMP'
            ])
            ->addColumn('end_time', 'datetime', [
                'limit'   => null,
                'null'    => true,
                'default' => 'CURRENT_TIMESTAMP'
            ])
            ->addColumn('breakpoint', 'boolean', [
                'limit'   => null,
                'default' => false,
                'null'    => false
            ]);

        $this->table('extensions')
            ->addColumn('id', 'integer', [
                'limit'         => 11,
                'autoIncrement' => true,
                'default'       => null,
                'null'          => false,
                'signed'        => false
            ])
            ->addPrimaryKey([
                'id'
            ])
            ->addColumn('name', 'string', [
                'limit'   => 150,
                'default' => null,
                'null'    => false
            ])
            ->addColumn('type', 'string', [
                'limit'   => 20,
                'default' => null,
                'null'    => false
            ])
            ->addColumn('ordering', 'integer', [
                'default' => 0,
                'limit'   => 11,
                'null'    => false
            ])
            ->addColumn('slug', 'string', [
                'limit'   => 150,
                'default' => null,
                'null'    => false
            ])
            ->addColumn('core', 'boolean', [
                'limit'   => null,
                'default' => false,
                'null'    => false
            ])
            ->addColumn('status', 'boolean', [
                'limit'   => null,
                'default' => false,
                'null'    => false
            ])
            ->addColumn('params', 'text', [
                'default' => null,
                'limit'   => null,
                'null'    => true
            ])
            ->create();

        // TODO: Write default loaded plugins.
    }
211233
def run_migrations(migrations):
    
    for resource, resource_migrations in migrations.items():
        for version in resource_migrations:
            to_migrate = yield resource_version.get(
                key=[resource.resource_type, version],
                include_docs=True)

            for x in to_migrate['rows']:
                instance = resource(**x['doc'])
                instance = _migrate_resource(
                    instance,
                    resource_migrations,
                    version
                )

                yield instance._save()
532683
public function migrateUp()
    {
        $this->builder->table(
            $this->table,
            function ($table) {
                $table->bigInteger('language_id')->unsigned()->nullable()->index();
            }
        );
    }
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
1238716
def migrations_to_run(self):
        
        assert self.database_current_migration is not None

        db_current_migration = self.database_current_migration

        return [
            (migration_number, migration_func)
            for migration_number, migration_func in self.sorted_migrations
            if migration_number > db_current_migration]
336022
public function migrateUp()
    {
        $this->builder->create(
            $this->table,
            function ($table) {
                $table->bigIncrements('id');

                $table->bigInteger('domain_id')->unsigned()->index();
                $table->string('url')->index();
                $table->string('host');

                $table->timestamps();
                $table->index('created_at');
                $table->index('updated_at');
            }
        );
    }
1288956
public function up()
    {
        // Create table for storing roles
        Schema::create('data_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->string('display_name_singular');
            $table->string('display_name_plural');
            $table->string('icon')->nullable();
            $table->string('model_name')->nullable();
            $table->string('description')->nullable();
            $table->boolean('generate_permissions')->default(false);
            $table->timestamps();
        });

        // Create table for storing roles
        Schema::create('data_rows', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('data_type_id')->unsigned();
            $table->string('field');
            $table->string('type');
            $table->string('display_name')->nullable();
            $table->boolean('required')->default(false);
            $table->boolean('browse')->default(true);
            $table->boolean('read')->default(true);
            $table->boolean('edit')->default(true);
            $table->boolean('add')->default(true);
            $table->boolean('delete')->default(true);
            $table->text('details')->nullable();

            $table->foreign('data_type_id')->references('id')->on('data_types')
                ->onUpdate('cascade')->onDelete('cascade');
        });
    }
627220
def make_migrations(schema=None):
    """"""

    entrypoints = {}
    old = {}

    def apply_migrations(migrations, new_model):
        """Apply migration data to compile an up to date model"""

        def get_path(raw_path):
            """Get local path of schema definition"""

            print("RAW PATH:", raw_path, type(raw_path))
            path = []
            for item in raw_path.split("["):
                print(item)
                item = item.rstrip("]")
                item = item.replace('"', '')
                item = item.replace("'", '')
                try:
                    item = int(item)
                except ValueError:
                    pass
                path.append(item)
            path.remove('root')
            print("PATH:", path)
            return path

        def apply_entry(changetype, change, result):
            """Upgrade with a single migration"""

            def apply_removes(removes, result):
                """Delete removed fields"""

                for remove in removes:
                    path = get_path(remove)
                    amount = dpath.util.delete(result, path)
                    assert amount == 1
                return result

            def apply_additions(additions, result):
                """Add newly added fields"""

                for addition in additions:
                    path = get_path(addition)
                    entry = additions[addition]
                    hfoslog('Adding:', entry, 'at', path)
                    dpath.util.new(result, path, entry)
                return result

            if changetype == 'type_changes':
                hfoslog('Creating new object')
                result = change['root']['new_value']
                return result

            if changetype == 'dictionary_item_added':
                hfoslog('Adding items')
                result = apply_additions(change, result)
            elif changetype == 'dictionary_item_removed':
                hfoslog('Removing items')
                result = apply_removes(change, result)
            elif changetype == 'values_changed':
                hfoslog("Changing items' types")
                for item in change:
                    path = get_path(item)
                    hfoslog('Changing', path, 'from',
                            change[item]['old_value'], ' to',
                            change[item]['new_value'])
                    assert dpath.util.get(result, path) == change[item][
                        'old_value']
                    amount = dpath.util.set(result, path, change[item][
                        'new_value'])
                    assert amount == 1

            return result

        def get_renames(migrations):
            """Check migrations for renamed fields"""

            hfoslog('Checking for rename operations:')
            pprint(migrations)
            for entry in migrations:

                added = entry.get('dictionary_item_added', None)
                removed = entry.get('dictionary_item_removed', None)

            renames = []

            if added and removed:
                for addition in added:
                    path = get_path(addition)
                    for removal in removed:
                        removed_path = get_path(removal)
                        if path[:-1] == removed_path[:-1]:
                            hfoslog('Possible rename detected:', removal, '->',
                                    addition)
                            renames.append((removed_path, path))
            return renames

        result = {}
        for no, migration in enumerate(migrations):
            hfoslog('Migrating', no)
            hfoslog('Migration:', migration, lvl=debug)
            renamed = get_renames(migrations)

            for entry in migration:
                result = apply_entry(entry, migration[entry], result)

        pprint(result)
        return result

    def write_migration(schema, counter, path, previous, current):
        """Write out complete migration data"""

        filename = "%s_%04i.json" % (schema, counter)
        migration = DeepDiff(previous, current, verbose_level=2).json
        if migration == "{}":
            hfoslog('Nothing changed - no new migration data.', lvl=warn)
            return

        print('Writing migration: ', os.path.join(path, filename))
        pprint(migration)

        with open(os.path.join(path, filename), 'w') as f:
            f.write(migration)

    for schema_entrypoint in iter_entry_points(group='hfos.schemata',
                                               name=None):
        try:
            hfoslog("Schemata found: ", schema_entrypoint.name, lvl=debug,
                    emitter='DB')
            if schema is not None and schema_entrypoint.name != schema:
                continue

            entrypoints[schema_entrypoint.name] = schema_entrypoint
            pprint(schema_entrypoint.dist.location)
            schema_top = schema_entrypoint.dist.location
            schema_migrations = schema_entrypoint.module_name.replace(
                'schemata', 'migrations').replace('.', '/')
            path = os.path.join(schema_top, schema_migrations)
            new_model = schema_entrypoint.load()['schema']

            migrations = []

            try:
                for file in sorted(os.listdir(path)):
                    if not file.endswith('.json'):
                        continue
                    fullpath = os.path.join(path, file)
                    hfoslog('Importing migration', fullpath)
                    with open(fullpath, 'r') as f:
                        migration = DeepDiff.from_json(f.read())
                    migrations.append(migration)
                    hfoslog('Successfully imported')

                if len(migrations) == 0:
                    raise ImportError
                pprint(migrations)
                model = apply_migrations(migrations, new_model)
                write_migration(schema, len(migrations) + 1, path, model,
                                new_model)
            except ImportError as e:
                hfoslog('No previous migrations for', schema, e,
                        type(e), exc=True)

            if len(migrations) == 0:
                write_migration(schema, 1, path, None, new_model)

        except (ImportError, DistributionNotFound) as e:
            hfoslog("Problematic schema: ", e, type(e),
                    schema_entrypoint.name, exc=True, lvl=warn,
                    emitter='SCHEMATA')

    hfoslog("Found schemata: ", sorted(entrypoints.keys()), lvl=debug,
            emitter='SCHEMATA')

    pprint(entrypoints)

    def make_single_migration(old, new):
        pass