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

		$this->createTable('AuthItem', [
		            'name' => 'varchar(64) COLLATE utf8_bin NOT NULL',
		            'type' => Schema::TYPE_INTEGER . ' NOT NULL',
		            'description' => 'text COLLATE utf8_bin',
	                'bizrule' => 'text COLLATE utf8_bin',
	                'data' => 'text COLLATE utf8_bin',
	                'PRIMARY KEY (`name`)', // primary item
	        ], $tableOptions);
		$this->createTable('AuthItemChild', [
		            'parent' => 'varchar(64) COLLATE utf8_bin NOT NULL',
		            'child' => 'varchar(64) COLLATE utf8_bin NOT NULL',
	                'PRIMARY KEY (`parent`,`child`)', // primary item
	        ], $tableOptions);
		$this->addForeignKey('AuthItemChild_ibfk_1', 'AuthItemChild', 'parent', 'AuthItem', 'name', 'CASCADE', 'CASCADE');
		$this->addForeignKey('AuthItemChild_ibfk_2', 'AuthItemChild', 'child', 'AuthItem', 'name', 'CASCADE', 'CASCADE');

		$this->createTable('AuthAssignment', [
		            'itemname' => 'varchar(64) COLLATE utf8_bin NOT NULL',
		            'userid' => 'varchar(64) COLLATE utf8_bin NOT NULL',
	                'bizrule' => 'text COLLATE utf8_bin',
	                'data' => 'text COLLATE utf8_bin',
	                'PRIMARY KEY (`itemname`,`userid`)', // primary item
	        ], $tableOptions);
	}
994943
def revert(ctx, name, verbose):
    

    try:
        app_name, target_migration = name.split('/', 2)
    except ValueError:
        raise click.ClickException('NAME format is <app>/<migration>')

    apps = ctx.obj['config']['apps']
    if app_name not in apps.keys():
        raise click.ClickException('unknown app "{0}"'.format(app_name))

    app = apps[app_name]
    migrations = app['migrations']
    if target_migration not in migrations:
        raise click.ClickException('unknown migration "{0}"'.format(name))

    mig_idx = migrations.index(target_migration)
    migrations = migrations[-len(migrations) + mig_idx:]  # all migrations after target_migration
    migrations = migrations[::-1]  # in reversed order

    for migration in migrations:
        click.echo(
            click.style('Reverting {0}...'.format(click.style(app_name + '/' + migration, bold=True)), fg='blue'))

        if not ctx.obj['db'].is_migration_applied(app_name, migration):
            click.echo(click.style('  SKIPPED.', fg='green'))
            continue
        try:
            snaql_factory = Snaql(app['path'], '')
            queries = snaql_factory.load_queries(migration + '.revert.sql').ordered_blocks

            for query in queries:
                if verbose:
                    click.echo('    ' + query())

                ctx.obj['db'].query(query())

        except Exception as e:
            click.echo(click.style('  FAILED.', fg='red'))
            ctx.obj['db'].rollback()

            raise click.ClickException('migration execution failed\n{0}'.format(e))

        click.echo(click.style('  OK.', fg='green'))

        ctx.obj['db'].commit()

        ctx.obj['db'].revert_migration(app_name, migration)
480755
public function up()
	{
		$transaction=$this->getDbConnection()->beginTransaction();
		try
		{
			if($this->safeUp()===false)
			{
				$transaction->rollback();
				return false;
			}
			$transaction->commit();
		}
		catch(Exception $e)
		{
			echo "Exception: ".$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
			echo $e->getTraceAsString()."\n";
			$transaction->rollback();
			return false;
		}
	}
478050
def migrate(self, uuid, desturi):
        
        args = {
            'uuid': uuid,
            'desturi': desturi,
        }
        self._migrate_action_chk.check(args)

        self._client.sync('kvm.migrate', args)
342660
def migrate(record, dry_run=False):
    ''''''
    handler = record_migration if record else execute_migration
    success = True
    for plugin, package, filename in available_migrations():
        migration = get_migration(plugin, filename)
        if migration or not success:
            log_status(plugin, filename, cyan('Skipped'))
        else:
            status = magenta('Recorded') if record else yellow('Apply')
            log_status(plugin, filename, status)
            script = resource_string(package, join('migrations', filename))
            success &= handler(plugin, filename, script, dryrun=dry_run)
191491
def migrate(name=None, database=None, directory=None, verbose=None, fake=False):
    """"""
    router = get_router(directory, database, verbose)
    migrations = router.run(name, fake=fake)
    if migrations:
        click.echo('Migrations completed: %s' % ', '.join(migrations))
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
197153
def drop():
    
    # Ensure the connection is up
    _State.connection()
    _State.table.drop(checkfirst=True)
    _State.metadata.remove(_State.table)
    _State.table = None
    _State.new_transaction()
1055195
function(transaction, bucket, key, values){
		contract(arguments)
			.params('array', 'string', 'string|number','string|array|number')
			.end()
		;
		
		var self = this;
		var table = '';
		values = Array.isArray(values) ? values : [values]; // we always want to have an array for values
		
		transaction.push(function(cb){
			
			if (bucket.indexOf('allows') != -1) {
				table = self.prefix + self.buckets.permissions;
				self.db
					.select('key', 'value')
					.from(table)
					.where({'key': bucket})
					.then(function(result) {
						var json = {};
						
						if (result.length === 0) {
							
							// if no results found do a fresh insert
							json[key] = values;
							return self.db(table)
								.insert({key: bucket, value: json})
							;
						} else {
							
							// if we have found the key in the table then lets refresh the data
							if (_.has(result[0].value, key)) {
								result[0].value[key] = _.union(values, result[0].value[key]);
							} else {
								result[0].value[key] = values;
							}
							
							return self.db(table)
								.where('key', bucket)
								.update({key: bucket, value: result[0].value})
							;
						}
					})
					.then(function() {
						cb(undefined);
					})
				;
			} else {
				table = self.prefix + bucket;
				self.db
					.select('key', 'value')
					.from(table)
					.where({'key': key})
					.then(function(result) {
						
						if (result.length === 0) {
							
							// if no results found do a fresh insert
							return self.db(table)
								.insert({key: key, value: values})
							;
						} else {
							
							// if we have found the key in the table then lets refresh the data
							return self.db(table)
								.where('key', key)
								.update({value: _.union(values, result[0].value)})
							;
						}
					})
					.then(function() {
						cb(undefined);
					})
				;
			}
		});
	}
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))
113154
def handle(self):
        
        if not self.confirm_to_proceed(
            "<question>Are you sure you want to rollback the last migration?:</question> "
        ):
            return

        database = self.option("database")
        repository = DatabaseMigrationRepository(self.resolver, "migrations")

        migrator = Migrator(repository, self.resolver)

        self._prepare_database(migrator, database)

        pretend = self.option("pretend")

        path = self.option("path")

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

        migrator.rollback(path, pretend)

        for note in migrator.get_notes():
            self.line(note)
117409
def do_up(self, arg):
        """"""
        print "running up migration"
        self.manager.run(arg, Direction.UP)
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)
668976
def execute_remove(self, remove):
		''' 
		'''

		safe = self.safe
		if remove.safe is not None:
			safe = remove.safe

		self.queue.append(RemoveOp(self.transaction_id, self, remove.type, safe, remove))
		if self.autoflush:
			return self.flush()
500474
public function migrateUp()
    {
        Schema::table('tddd_runs', function (Blueprint $table) {
            $table->mediumText('log_new')->nullable()->after('was_ok');
        });

        Database::statement('update tddd_runs set log_new = log;');

        Schema::table('tddd_runs', function (Blueprint $table) {
            $table->dropColumn('log');
            $table->renameColumn('log_new', 'log');
        });
    }
929223
function applyTransaction(history, state, tr, options) {
  let historyTr = tr.getMeta(historyKey), rebased
  if (historyTr) return historyTr.historyState

  if (tr.getMeta(closeHistoryKey)) history = new HistoryState(history.done, history.undone, null, 0)

  let appended = tr.getMeta("appendedTransaction")

  if (tr.steps.length == 0) {
    return history
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history.done.addTransform(tr, null, options, mustPreserveItems(state)),
                              history.undone, rangesFor(tr.mapping.maps[tr.steps.length - 1]), history.prevTime)
    else
      return new HistoryState(history.done, history.undone.addTransform(tr, null, options, mustPreserveItems(state)),
                              null, history.prevTime)
  } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    // Group transforms that occur in quick succession into one event.
    let newGroup = history.prevTime < (tr.time || 0) - options.newGroupDelay ||
        !appended && !isAdjacentTo(tr, history.prevRanges)
    let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps[tr.steps.length - 1])
    return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : null,
                                                      options, mustPreserveItems(state)),
                            Branch.empty, prevRanges, tr.time)
  } else if (rebased = tr.getMeta("rebased")) {
    // Used by the collab module to tell the history that some of its
    // content has been rebased.
    return new HistoryState(history.done.rebased(tr, rebased),
                            history.undone.rebased(tr, rebased),
                            mapRanges(history.prevRanges, tr.mapping), history.prevTime)
  } else {
    return new HistoryState(history.done.addMaps(tr.mapping.maps),
                            history.undone.addMaps(tr.mapping.maps),
                            mapRanges(history.prevRanges, tr.mapping), history.prevTime)
  }
}
1039829
public function safeUp()
	{
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }        

		$this->createTable('Group', [
		            'id' => Schema::TYPE_PK,
		            'name' => Schema::TYPE_STRING . '',
		            'status' => Schema::TYPE_STRING . ' DEFAULT "active"',
		            'update_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
		            'update_by' => Schema::TYPE_STRING . ' DEFAULT NULL',
		            'create_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
		            'create_by' => Schema::TYPE_STRING . ' DEFAULT NULL',
	        ], $tableOptions);
		$this->execute('
			INSERT INTO `Group` (`id`, `name`, `status`, `update_time`, `update_by`, `create_time`, `create_by`) VALUES
			(1, "Super Admin", "active", NULL, NULL, NULL, NULL);');
		$this->execute('INSERT INTO `AuthItem` VALUES("1", 2, "", NULL, "N;");');

 		$this->insert('AuthAssignment', [
                'itemname' => "1",
                'userid' => "1",
                'bizrule' => NULL,
                'data' => NULL
        ]);

        $this->createAuthItems();
        $this->createAdminMenu();        
	}