Use safeUp/safeDown to do migration with transaction
438701
public function safeUp()
	{
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }        

		$this->createTable('User', [
		            'id' => Schema::TYPE_PK,
		            'Group_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
		            'type' => Schema::TYPE_STRING . ' NOT NULL DEFAULT "Contact"',
		            'password' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'password_reset_token' => Schema::TYPE_STRING . '(32)',
		            'auth_key' => Schema::TYPE_STRING . '(128)',
		            'name' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'firstname' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'lastname' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'picture' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'email' => Schema::TYPE_STRING . ' NOT NULL',
		            'phone' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'mobile' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'validation_key' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'login_attempts' => 'int(10) NOT NULL DEFAULT "0"',
		            'status' => Schema::TYPE_STRING . ' NOT NULL DEFAULT "active"',
		            'update_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
		            'update_by' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
		            'create_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
		            'create_by' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
	        ], $tableOptions);
		
		$this->addForeignKey('User_Group_id', 'User', 'Group_id', 'Group', 'id', 'CASCADE', 'SET NULL');

        $this->insert('User', [
                'id' => 1,
                'Group_id' => 1,
                'type' => "Administrator",
                'password' => Yii::$app->getSecurity()->generatePasswordHash("admin"),
                'auth_key' => Yii::$app->getSecurity()->generateRandomString(),
                'name' => 'Firstname Lastname',
                'firstname' => 'Firstname',
                'lastname' => 'Lastname',
                'email' => 'webmaster@2ezweb.com.au',
        ]);

        $this->menu = 'Administrators'; $this->controller = 'Administrator'; $this->privileges = ['create', 'delete', 'read', 'update', 'update own'];
        $this->createAuthItems();
        $this->createAdminMenu();

        $this->menu = 'Contacts'; $this->controller = 'Contact'; $this->singleMenu = true; $this->privileges = ['create', 'delete', 'read', 'update'];
        $this->createAuthItems();
        $this->createAdminMenu();

	}
1123846
def get_migrations_to_down(self, migration_id):
        """"""
        migration_id = MigrationFile.validate_id(migration_id)
        if not migration_id:
            return []

        migrations = self.get_migration_files()
        last_migration_id = self.get_last_migrated_id()

        if migration_id in (m.id for m in self.get_unregistered_migrations()):
            logger.error('Migration is not applied %s' % migration_id)
            return []

        try:
            migration = [m for m in migrations if m.id == migration_id][0]
        except IndexError:
            logger.error('Migration does not exists %s' % migration_id)
            return []

        return list(reversed([m for m in migrations
                              if migration.id <= m.id <= last_migration_id]))
120916
public static function rollbackMigrations() {
    $migration = \Drupal::service('plugin.manager.migration')->createInstance('gxp_offerings_import');
    $executable = new MigrateExecutable($migration, new MigrateMessage());
    $executable->rollback();
    $migration->setStatus(\Drupal\migrate\Plugin\MigrationInterface::STATUS_IDLE);
  }
688919
def migrate(self, migrations_package_name, up_to=9999):
        '''
        
        '''
        from .migrations import MigrationHistory
        logger = logging.getLogger('migrations')
        applied_migrations = self._get_applied_migrations(migrations_package_name)
        modules = import_submodules(migrations_package_name)
        unapplied_migrations = set(modules.keys()) - applied_migrations
        for name in sorted(unapplied_migrations):
            logger.info('Applying migration %s...', name)
            for operation in modules[name].operations:
                operation.apply(self)
            self.insert([MigrationHistory(package_name=migrations_package_name, module_name=name, applied=datetime.date.today())])
            if int(name[:4]) >= up_to:
                break
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)
550917
def allow_migrate(self, db, model):
        
        if model._meta.app_label in self._apps:
            return getattr(model, '_db_alias', model._meta.app_label) == db
        return None
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
801588
def migration(resource, version, previous_version=''):
    """"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            migrated = func(*args, **kwargs)

            return migrated

        m = Migration(wrapper, resource, version, previous_version)
        m.register()

        return m

    return decorator
154268
def _migrate_single(self, conn, migration):
        """"""
        with contextlib.ExitStack() as stack:
            for wrapper in self._wrappers:
                stack.enter_context(wrapper(conn))
            migration.func(conn)
540922
def create_operations(ctx=None, **kwargs):
    """"""
    if ctx is None:
        ctx = create_migration_ctx(**kwargs)
    operations = Operations(ctx)
    operations.has_table = has_table
    return operations
289756
def update_migration_info(direction)
      save, @verbose = @verbose, false

      create_migration_info_table_if_needed

      if direction.to_sym == :up
        execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})")
      elsif direction.to_sym == :down
        execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
      end
      @verbose = save
    end
118805
function performMigration(direction, migrateTo, next) {
		if (!next &&
	    Object.prototype.toString.call(migrateTo) === '[object Function]') {
	    next = migrateTo;
	    migrateTo = undefined;
	  }

		if (!next) {
			next = function(err) {
				if (err) {
					console.error(err);
					process.exit(1);
				} else {
					process.exit();
				}
			}
		}

		var db = require('./lib/db');
		db.getConnection(dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) {
			if (err) {
				return next(new verror.WError(err, 'Error connecting to database'));
			}
			var migrationCollection = db.migrationCollection,
					dbConnection = db.connection;

			migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) {
				if (err) {
					return next(new verror.WError(err, 'Error querying migration collection'));
				}

				var lastMigration = migrationsRun[0],
					lastMigrationNum = lastMigration ? lastMigration.num : 0;

				migrate({
					migrationTitle: 'migrations/.migrate',
					db: dbConnection,
					migrationCollection: migrationCollection
				});
				migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){
					var mod = require(process.cwd() + '/' + path);
					migrate({
						num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10),
						title: path,
						up: mod.up,
						down: mod.down});
				});

				//Revert working directory to previous state
				process.chdir(previousWorkingDirectory);

				var set = migrate();

				set.on('migration', function(migration, direction){
					log(direction, migration.title);
				});

				set.on('save', function(){
					log('migration', 'complete');
					return next();
				});

				set[direction](null, lastMigrationNum);
			});
		});
	}
1361356
public function safeUp()
    {
        $this->addColumnAfter('oauth_tokens', 'accessToken', array(ColumnType::Varchar, 'required' => false), 'pluginHandle');

        $this->addColumnAfter('oauth_tokens', 'secret', array(ColumnType::Varchar, 'required' => false), 'accessToken');

        $this->addColumnAfter('oauth_tokens', 'endOfLife', array(ColumnType::Varchar, 'required' => false), 'secret');

        $this->addColumnAfter('oauth_tokens', 'refreshToken', array(ColumnType::Varchar, 'required' => false), 'endOfLife');

        require_once(CRAFT_PLUGINS_PATH.'oauth/vendor/autoload.php');

        $rows = craft()->db->createCommand()
            ->select('*')
            ->from('oauth_tokens')
            ->queryAll();

        foreach($rows as $row)
        {
            $token = $row['encodedToken'];
            $token = @unserialize(base64_decode($token));

            if($token && is_object($token))
            {
                $attributes = array();
                $attributes['accessToken'] = $token->getAccessToken();

                if(method_exists($token, 'getAccessTokenSecret'))
                {
                    $attributes['secret'] = $token->getAccessTokenSecret();
                }

                $attributes['endOfLife'] = $token->getEndOfLife();
                $attributes['refreshToken'] = $token->getRefreshToken();


                $this->update('oauth_tokens', $attributes, 'id = :id', array(':id' => $row['id']));
            }
        }

        OauthPlugin::log('Dropping the encodedToken column from the structures table...', LogLevel::Info, true);

        $this->dropColumn('oauth_tokens', 'encodedToken');

        OauthPlugin::log('Done dropping the encodedToken column from the structures table.', LogLevel::Info, true);



        return true;
    }
1162022
public function safeUp()
    {
        $tokensTable = $this->dbConnection->schema->getTable('{{oauth_tokens}}');

        if ($tokensTable)
        {
            if (($userMappingColumn = $tokensTable->getColumn('userMapping')) == null)
            {
                OauthPlugin::log('Adding `userMapping` column to the `oauth_tokens` table.', LogLevel::Info, true);

                $this->addColumnAfter('oauth_tokens', 'userMapping', array(AttributeType::String, 'required' => false), 'userId');

                OauthPlugin::log('Added `userMapping` column to the `oauth_tokens` table.', LogLevel::Info, true);
            }
            else
            {
                OauthPlugin::log('Tried to add a `userMapping` column to the `oauth_tokens` table, but there is already one there.', LogLevel::Warning);
            }
        }
        else
        {
            OauthPlugin::log('Could not find an `oauth_tokens` table. Wut?', LogLevel::Error);
        }

        return true;
    }
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()
192401
def downgrade():
    """"""
    op.drop_table('transaction')
    if op._proxy.migration_context.dialect.supports_sequences:
        op.execute(DropSequence(Sequence('transaction_id_seq')))
924650
def migrate1():
    ""

    initial = [
    "create table Chill (version integer);",
    "insert into Chill (version) values (1);",
    "alter table SelectSQL rename to Query;",
    "alter table Node add column template integer references Template (id) on delete set null;",
    "alter table Node add column query integer references Query (id) on delete set null;"
    ]


    cleanup = [
    "drop table SelectSQL_Node;",
    "drop table Template_Node;"
    ]

    c = db.cursor()
    try:
        c.execute("select version from Chill limit 1;")
    except sqlite3.DatabaseError as err:
        pass
    result = c.fetchone()
    if result:
        version = result[0]
        if version == 1:
            current_app.logger.warn("Migration from version 0 to 1 is not needed.")
        else:
            current_app.logger.warn("Migration from version 0 to {0} is not supported.".format(version))
        return

    try:
        for query in initial:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    try:
        c.execute(fetch_query_string('select_all_nodes.sql'))
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)
    result = c.fetchall()
    if result:
        (result, col_names) = rowify(result, c.description)
        for kw in result:

            try:
                c.execute("""
                update Node set template = (
                select t.id from Template as t
                join Template_Node as tn on ( tn.template_id = t.id )
                join Node as n on ( n.id = tn.node_id )
                where n.id is :node_id
                group by t.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)

            try:
                c.execute("""
                update Node set query = (
                select s.id from Query as s
                join SelectSQL_Node as sn on ( sn.selectsql_id = s.id )
                join Node as n on ( n.id = sn.node_id )
                where n.id is :node_id
                group by s.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)
    try:
        for query in cleanup:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    db.commit()