Code to run after a migration row has been saved.
549210
public function onMigrationPostRowSave(MigratePostRowSaveEvent $event) {
    // Landing Page logic.
    if ($event->getMigration()->id() == 'gcweb_node_landing_page' ||
        $event->getMigration()->id() == 'gcweb_node_landing_page_translation') {
      // Set front page to panelized "homepage".
      $name = $event->getRow()->getSourceProperty('name');
      // Bug in homepage detection logic prevents using alias.
      $destinationIds = $event->getDestinationIdValues();
      if ($name == 'homepage') {
        $this->config->getEditable('system.site')
          ->set('page.front', '/node/' . $destinationIds[0])
          ->save(TRUE);
      }
    }

    // Block logic for queue assignment.
    if ($event->getMigration()->id() == 'gcweb_block_spotlight') {
      $sourceBid = $event->getRow()->getSourceProperty('bid');
      $destBid = $event->getDestinationIdValues();
      if (!empty($sourceBid)) {
        switch ($sourceBid) {
          case 'feature_block_1':
          case 'feature_block_2':
          case 'feature_block_3':
            $this->entityQueueCreate('front_page', $destBid);
            break;
        }
      }
    }

  }
536348
def apply_migration(self, migration, **kwargs):
        '''
        
        '''
        cprint("\nAttempting to run %s" % migration, "cyan")
        # First check if the migration has already been applied
        exists = Migration.select().where(Migration.name == migration).limit(1).first()
        if exists and self.direction == 'up':
            cprint("This migration has already been run on this server", "red")
            if not self.force or self.fake:
                return False
            else:
                cprint("Force running this migration again", "yellow")

        # Load the module
        module_name = "%s.%s" % (self.module_name, migration)
        try:
            module = importlib.import_module(module_name)
            if not hasattr(module, self.direction):
                raise MigrationException("%s doesn't have %s migration defined" %
                    (migration, self.direction)
                )
            # Actually execute the direction method
            # Note that this doesn't actually run the migrations in the DB yet.
            # This merely collects the steps in the migration, so that if needed
            # we can just fake it and print out the SQL query as well.
            getattr(module, self.direction)(self)
            # Print out each migration and execute it
            for op in self.operations:
                self.execute_operation(op)

            if not self.fake:
                # If successful, create the entry in our log
                if self.direction == 'up' and not exists:
                    Migration.create(name=migration)
                elif self.direction == 'down' and exists:
                    exists.delete_instance()

            cprint("Done", "green")

        except ImportError:
            raise MigrationException("%s migration not found" % migration)
552079
private function createMigration(): void
    {
        try {

            $oNow    = Factory::factory('DateTime');
            $aFields = [
                'INDEX'      => $this->oInput->getArgument('index'),
                'DATE_START' => $oNow->format('Y-m-d'),
            ];

            if (is_null($aFields['INDEX'])) {

                //  Get the most recent migration and increment it by 1
                $sPattern    = \Nails\Common\Console\Command\Database\Migrate::VALID_MIGRATION_PATTERN;
                $aMigrations = [];
                foreach (new \DirectoryIterator(static::MIGRATION_PATH) as $oFileInfo) {

                    if ($oFileInfo->isDot()) {
                        continue;
                    }

                    //  In the correct format?
                    if (preg_match($sPattern, $oFileInfo->getFilename(), $aMatches)) {
                        $aMigrations[] = (int) $aMatches[1];
                    }
                }

                sort($aMigrations);

                if (!empty($aMigrations)) {
                    $aFields['INDEX'] = end($aMigrations) + 1;
                } else {
                    $aFields['INDEX'] = 0;
                }

            } elseif (!is_numeric($aFields['INDEX'])) {
                throw new NailsException('Specified migration index is not a numeric value.');
            } else {
                $aFields['INDEX'] = (int) $aFields['INDEX'];
            }

            $this->oOutput->write('Creating migration <comment>' . $aFields['INDEX'] . '</comment>... ');

            //  Check for existing controller
            $sPath = static::MIGRATION_PATH . $aFields['INDEX'] . '.php';
            if (file_exists($sPath)) {
                throw new MigrationExistsException(
                    'Migration "' . $aFields['INDEX'] . '" exists already at path "' . $sPath . '"'
                );
            }

            //  If we're making the first migration, get a dump of all the non-Nails tables
            $aFields['QUERIES'] = '';
            if ($aFields['INDEX'] === 0 && stringToBoolean($this->oInput->getOption('sql-on-zero'))) {

                $oDb      = Factory::service('Database');
                $aResult  = $oDb->query('SHOW TABLES')->result();
                $aCreates = [];

                foreach ($aResult as $oResult) {
                    $aResult = (array) $oResult;
                    $sTable  = reset($aResult);
                    if (!preg_match('/^' . NAILS_DB_PREFIX . '/', $sTable) || $sTable == NAILS_DB_PREFIX . 'user_meta_app') {
                        $aResult    = (array) $oDb->query('SHOW CREATE TABLE ' . $sTable)->row();
                        $aCreates[] = 'DROP TABLE IF EXISTS ' . $aResult['Table'] . ';' . "\n" . $aResult['Create Table'];
                    }
                }

                foreach ($aCreates as $sCreate) {

                    $aCreate = explode("\n", $sCreate);
                    $iCount  = count($aCreate);
                    array_walk(
                        $aCreate,
                        function (&$sLine, $iIndex) use ($iCount) {
                            $sLine = trim($sLine);
                            if ($iIndex > 1 && $iIndex < ($iCount - 1)) {
                                $sLine = $this->tabs(4) . $sLine;
                            } else {
                                $sLine = $this->tabs(3) . $sLine;
                            }
                        }
                    );

                    $aFields['QUERIES'] .= $this->tabs(2) . '$this->query(\'' . "\n";
                    $aFields['QUERIES'] .= str_replace("'", "\'", implode("\n", $aCreate)) . "\n";
                    $aFields['QUERIES'] .= $this->tabs(2) . '\');' . "\n";
                }

                $aFields['QUERIES'] = trim($aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(NAILS_DB_PREFIX, '{{NAILS_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(APP_DB_PREFIX, '{{APP_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = preg_replace('/AUTO_INCREMENT=\d+ /', '', $aFields['QUERIES']);

            } else {
                $aFields['QUERIES'] = '$this->query(\'\');';
            }

            $this->createFile($sPath, $this->getResource('template/migration.php', $aFields));
            $aCreated[] = $sPath;
            $this->oOutput->writeln('<info>done!</info>');

        } catch (\Exception $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            //  Clean up created models
            if (!empty($aCreated)) {
                $this->oOutput->writeln('<error>Cleaning up - removing newly created migration</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw new NailsException($e->getMessage());
        }
    }
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
1054019
def execute_save
      if @database.nil? then
        raise MigrationError.new("Migrator cannot save records since the database option was not specified.")
      end
      @database.open do |db|
        migrate do |tgt, rec|
          # Save the target object.
          save(tgt, db)
          # Ensure that each migrated object is created if necessary.
          @migrated.each { |obj| create(obj, db) unless db.exists?(obj) }
          yield(tgt, rec) if block_given?
          db.clear
        end
      end
    end
1259189
def execute(self, i, o):
        
        super(ResetCommand, self).execute(i, o)

        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            o,
            '<question>Are you sure you want to reset all of the migrations?</question> ',
            False
        )
        if not confirm:
            return

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        self._prepare_database(migrator, database, i, o)

        pretend = bool(i.get_option('pretend'))

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        while True:
            count = migrator.rollback(path, pretend)

            for note in migrator.get_notes():
                o.writeln(note)

            if count == 0:
                break
62763
public function process()
    {
        // Migrate init - to create migration table
        $name = $this->argument('name');

        if (!is_null($name)) {
            if (string_has($name, ',')) {
                $this->seeder()->executeOnly($name);
            } else {
                $this->seeder()->executeOnly($name);
            }
        }

        $this->seeder()->run();

        $this->info('Seeding Completed Successfully!');
    }
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_)
1174201
function migrate(cb) {

      // get all already executed migrations.
      db.query('SELECT "version" FROM "schema_migrations"', function(err, resp) {
        var migrations_run = 0;
        var executed = [];

        // if there is an error assume we are at the default state, and run root migration
        if (err) {

          // attempt to run file located at app_root/migrations/schema/root.sql -- good for previous data force load (e.g. Rails)
          var schema = fs.readFileSync(migrations_dir + "schema/root.sql").toString();
          db.query(schema); // populate with root schema if not populated.
        } else {
          // if no error, dump all versions into an array called executed for quick searching.
          for (var rl = resp.rows.length; rl > 0; rl--) {
            executed.push(resp.rows[rl - 1].version);
          }
        }


        // function loop to execute through the remainin "torun" migrations
        var run_migrations = (function(torun) {

          // get the next migration
          var current = torun.pop();

          // if there is a migration
          if (current) {

            // test if already executed
            if (executed.indexOf(current.id) < 0) {
              // alert of execution
              console.log("Executing migration: " + current.id);

              // check if migration is SQL
              if (current.sql) {

                // suffix with schema migrations insertion so we dont run again if successful.
                var sql = OPEN_TRANSACTION+current.sql + "; INSERT INTO schema_migrations VALUES (" + current.id + "); "+CLOSE_TRANSACTION;

                // execute the full query
                db.query(sql, function(e, r) {
                  if (e) {
                    db.query("ROLLBACK;", function () {
                      // if error, dump why we couldn't migrate and process no more.
                      console.log("Could not migrate database. Error provided below.")
                      console.log(e);
                      db.end();
                    });
                  } else {

                    // otherwise add to counter and run the rest of the "torun" array
                    migrations_run++;
                    run_migrations(torun);
                  }
                });

                // if migration is JS code
              } else if (current.js) {

                // pass our db object and execute with callback to insert into schema migration AND recurse with rest of "torun" array
                current.js(db, function() {
                  db.query("INSERT INTO schema_migrations VALUES (" + current.id + ")", function(err, results) {
                    migrations_run++;
                    run_migrations(torun);
                  });
                });
              }
            } else {

              // if no idea what to do, just skip!
              run_migrations(torun);

            }

            // if no more migrations
          } else {
            // only output if we done work.
            if (migrations_run > 0) console.log("Migrations run: " + migrations_run);

            // if there is a callback, exec it
            if (cb) {
              cb();
            }
          }
        });




        // populate all existing migrations by reading the migrations directory
        fs.readdir(migrations_dir, function(err, list) {
          var migrations = [];


          for (var li = 0, ll = list.length; li < ll; li++) {

            // if the file has a .sql extension, load it as a file read for sql schema updating
            if (m = list[li].match(/(.*)\.sql/)) {
              migrations.push({
                id: m[1],
                sql: fs.readFileSync(migrations_dir + m[0]).toString()
              });

              // if the file has a .js extension, load via require system and set js attribute as .migrate function
            } else if (j = list[li].match(/(.*)\.js/)) {
              migrations.push({
                id: j[1],
                js: require(migrations_dir + "/" + list[li]).migrate
              });
            }
          }

          //recursively run through all migrations after they have been sorted by ID in ascending order
          run_migrations(migrations.sort((function(a, b) {
            return (parseInt(b.id) - parseInt(a.id));
          })));
        });
      });
    }
1089466
def migration_creatr(migration_file, create, table):
    """"""
    if not check():
        click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:migration command')
        return

    migration = CreateMigration()
    if table is None:
        table = snake_case(migration_file)
    file = migration.create_file(snake_case(migration_file), table=table, create=create)
    click.echo(Fore.GREEN + 'Migration file created at %s' % file)
248834
public void postProcess() {
		if (foreignColumnName != null) {
			foreignAutoRefresh = true;
		}
		if (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {
			maxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;
		}
	}
751398
def run_migrations_online():
    

    # this callback is used to prevent an auto-migration from being generated
    # when there are no changes to the schema
    # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
    def process_revision_directives(context, revision, directives):
        if getattr(config.cmd_opts, 'autogenerate', False):
            script = directives[0]
            if len(script.upgrade_ops_list) >= len(bind_names) + 1:
                empty = True
                for upgrade_ops in script.upgrade_ops_list:
                    if not upgrade_ops.is_empty():
                        empty = False
                if empty:
                    directives[:] = []
                    logger.info('No changes in schema detected.')

    # for the direct-to-DB use case, start a transaction on all
    # engines, then run all migrations, then commit all transactions.
    engines = {
        '': {
            'engine': engine_from_config(
                config.get_section(config.config_ini_section),
                prefix='sqlalchemy.',
                poolclass=pool.NullPool,
            )
        }
    }
    for name in bind_names:
        engines[name] = rec = {}
        rec['engine'] = engine_from_config(
            context.config.get_section(name),
            prefix='sqlalchemy.',
            poolclass=pool.NullPool)

    for name, rec in engines.items():
        engine = rec['engine']
        rec['connection'] = conn = engine.connect()

        if USE_TWOPHASE:
            rec['transaction'] = conn.begin_twophase()
        else:
            rec['transaction'] = conn.begin()

    try:
        for name, rec in engines.items():
            logger.info("Migrating database %s" % (name or '<default>'))
            context.configure(
                connection=rec['connection'],
                upgrade_token="%s_upgrades" % name,
                downgrade_token="%s_downgrades" % name,
                target_metadata=get_metadata(name),
                process_revision_directives=process_revision_directives,
                **current_app.extensions['migrate'].configure_args
            )
            context.run_migrations(engine_name=name)

        if USE_TWOPHASE:
            for rec in engines.values():
                rec['transaction'].prepare()

        for rec in engines.values():
            rec['transaction'].commit()
    except:
        for rec in engines.values():
            rec['transaction'].rollback()
        raise
    finally:
        for rec in engines.values():
            rec['connection'].close()
107013
public function afterUpdate()
    {
        /** @var ActiveRecord $owner */
        $owner = $this->owner;

        if ($owner->isRelationPopulated('translations')) {
            $translations = $this->indexByLanguage($owner->getRelatedRecords()['translations']);
            $this->saveTranslations($translations);
        }
    }
432128
public function migrateDown()
    {
        Schema::table('tddd_runs', function (Blueprint $table) {
            $table->dropColumn('started_at');

            $table->dropColumn('ended_at');

            $table->dropColumn('notified_at');
        });
    }
191146
public function up()
    {
        $this->create('migrations', function ($table) {
            // Place table rows here
            $table->increments('id');
            $table->string('migration');
            $table->integer('migrated');
            $table->timestamps();
        });
    }
1263
def run_migration(data, version_start, version_end):
    """"""
    items = []
    if version_start == 1 and version_end == 2:
        for item in data['accounts']:
            items.append(v2.upgrade(item))

    if version_start == 2 and version_end == 1:
        for item in data:
            items.append(v2.downgrade(item))
        items = {'accounts': items}
    return items
528247
private void doRun() throws InterruptedException {
        boolean migrating = false;
        for (; ; ) {
            if (!migrationManager.areMigrationTasksAllowed()) {
                break;
            }
            MigrationRunnable runnable = queue.poll(1, TimeUnit.SECONDS);
            if (runnable == null) {
                break;
            }

            migrating |= runnable instanceof MigrationManager.MigrateTask;
            processTask(runnable);
            if (migrating && partitionMigrationInterval > 0) {
                Thread.sleep(partitionMigrationInterval);
            }
        }
        boolean hasNoTasks = !queue.hasMigrationTasks();
        if (hasNoTasks) {
            if (migrating) {
                logger.info("All migration tasks have been completed. ("
                        + migrationManager.getStats().formatToString(logger.isFineEnabled()) + ")");
            }
            Thread.sleep(sleepTime);
        } else if (!migrationManager.areMigrationTasksAllowed()) {
            Thread.sleep(sleepTime);
        }
    }