Save a migration in `migrations_applied` table
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
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
1371676
private function makeRollback($current_migrations, $migrations)
    {
        if (count($current_migrations) == 0) {
            echo Color::green('Nothing to rollback.');

            return;
        }

        // We sort current migration by created date value
        usort($current_migrations, function ($first, $second) {
            return strtotime($first->created_at) < strtotime($second->created_at);
        });

        foreach ($current_migrations as $value) {
            foreach ($migrations as $file => $migration) {
                if (!($value->batch == 1
                    && $migration == $value->migration)
                ) {
                    continue;
                }

                // Include the migration file
                require $file;

                // Rollabck migration
                try {
                    (new $migration)->rollback();
                } catch (\Exception $exception) {
                    $this->throwMigrationException($exception, $migration);
                }

                break;
            }
        }

        // Rollback in migration table
        $this->getMigrationTable()->where('batch', 1)->delete();

        foreach ($current_migrations as $value) {
            if ($value->batch != 1) {
                $this->updateMigrationStatus(
                    $value->migration,
                    $value->batch - 1
                );
            }
        }

        // Print console information
        echo Color::green('Migration rollback.');
    }
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
125842
protected function migrate()
    {
        if (! $this->container['migrator']->repositoryExists()) {
            throw new Exception('Migration table not found.');
        }

        $this->container['migrator']->run($this->getAttribute('path').'/database/migrations');
    }
56074
def apply_all(self):
        
        if self.__closed:
            raise MigrationSessionError("Can't apply applied session")
        if self._to_apply:
            raise MigrationSessionError("Can't apply_all with migrations added to session")

        try:
            self.__apply(run_all=True)
        except:
            raise
        finally:
            self.__closed = True
559228
protected function createMigration()
    {
        $table = $this->option('pivot') ?
            Str::snake(class_basename($this->argument('name'))) :
            Str::plural(Str::snake(class_basename($this->argument('name'))));

        $this->call('make:migration', [
            'name' => "create_{$table}_table",
            '--create' => $table,
        ]);
    }
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()
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)
1280471
private function migrate()
    {
        /**
         * create table for sentry user
         */
        if (!Capsule::schema()->hasTable('users')){
            Capsule::schema()->create('users', function($table)
            {
                $table->increments('id');
                $table->string('email');
                $table->string('password');
                $table->text('permissions')->nullable();
                $table->boolean('activated')->default(0);
                $table->string('activation_code')->nullable();
                $table->timestamp('activated_at')->nullable();
                $table->timestamp('last_login')->nullable();
                $table->string('persist_code')->nullable();
                $table->string('reset_password_code')->nullable();
                $table->string('first_name')->nullable();
                $table->string('last_name')->nullable();
                $table->timestamps();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->unique('email');
                $table->index('activation_code');
                $table->index('reset_password_code');
            });
        }

        /**
         * create table for sentry group
         */
        if (!Capsule::schema()->hasTable('groups')){
            Capsule::schema()->create('groups', function($table)
            {
                $table->increments('id');
                $table->string('name');
                $table->text('permissions')->nullable();
                $table->timestamps();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->unique('name');
            });
        }

        /**
         * create user-group relation
         */
        if (!Capsule::schema()->hasTable('users_groups')){
            Capsule::schema()->create('users_groups', function($table)
            {
                $table->integer('user_id')->unsigned();
                $table->integer('group_id')->unsigned();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->primary(array('user_id', 'group_id'));
            });
        }

        /**
         * create throttle table
         */
        if (!Capsule::schema()->hasTable('throttle')){
            Capsule::schema()->create('throttle', function($table)
            {
                $table->increments('id');
                $table->integer('user_id')->unsigned();
                $table->string('ip_address')->nullable();
                $table->integer('attempts')->default(0);
                $table->boolean('suspended')->default(0);
                $table->boolean('banned')->default(0);
                $table->timestamp('last_attempt_at')->nullable();
                $table->timestamp('suspended_at')->nullable();
                $table->timestamp('banned_at')->nullable();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->index('user_id');
            });
        }
    }
748754
public function makeMigration()
    {
        $tableName = $this->ask('Table Name (Example: users)');

        if ($this->confirm('Are you creating a new table')) {
            $this->info('Setting create option for table '. $tableName);

            $this->options['--create'] = $tableName;
            $this->options['name'] = 'create_'. $tableName .'_table';
        } else {
            $this->info('Setting table option for table '. $tableName);

            $this->options['--table'] = $this->options['name'];
            $this->options['name'] = $this->ask('Migration Name (Example: alter_user_table_add_column_is_admin)', 'alter_'. $tableName .'_table_'. rand(0, 100));
        }

        if (! $this->confirm('Use default migration folder?', 'yes')) {
            $this->options['path'] = $this->ask('Path for Migration');
        }
    }
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");
        }

    }
887300
private function migration()
    {
        $migrationContent = "<?php\n\n".view('scaffold-interface::template.ManyToMany.migration', $this->tables)->render();

        $migrationFileName = date('Y').'_'.date('m').'_'.date('d').'_'.date('his').'_'.ucfirst($this->tables['first']).ucfirst($this->tables['second']).'.php';

        $this->make(config('amranidev.config.migration').'/'.$migrationFileName, $migrationContent);
    }
328434
def dry_run(self):
        
        if self.database_current_migration is None:
            self.printer(
                    u'~> Woulda initialized: %s\n' % self.name_for_printing())
            return u'inited'

        migrations_to_run = self.migrations_to_run()
        if migrations_to_run:
            self.printer(
                u'~> Woulda updated %s:\n' % self.name_for_printing())

            for migration_number, migration_func in migrations_to_run():
                self.printer(
                    u'   + Would update %s, "%s"\n' % (
                        migration_number, migration_func.func_name))

            return u'migrated'
1026772
def exec_migrations(is_up=true)
      Log.info("Executing migrations...")
      migrations = yield @db.current_version

      if migrations.count == 0
        Log.warn("Migrations not found")
        return
      end

      migrations.each do |migration|
        self.exec_migration(migration, is_up)
      end
      Log.success("Migrations executed. Current version: #{@db.current_version}")
    end
793829
def delete_migration(connection, basename):
    

    # Prepare query
    sql = "DELETE FROM migrations_applied WHERE name = %s"

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

    return True
1116491
public static function prepareMigrationTable(App $app): void{
        $migration = new class($app) extends Migration{

            /**
             * Create the migration table if it does not exist yet
             */
            public function up(): void{
                $schema = $this->getSchema('default');
                if (!$schema->hasTable('migrations')) {
                    $schema->create('migrations', function (Blueprint $table){
                        $table->increments('id');
                        $table->string('name', 255);
                    });
                }
            }

            /**
             * Is not needed, but add it nevertheless
             */
            public function down(): void{
                $this->getSchema('default')->drop('migrations');
            }
        };
        $migration->up();
    }