Use up()/down() to run migration code without a transaction.
2109
public function up()
    {
        $table = file_get_contents(dirname(__FILE__) . '/media.sql');
        return $this->db->createCommand($table)->execute();
    }
416719
def setup_migrate(app):
    """"""
    directory = path.join(path.dirname(__file__), 'migrations')
    migrate.init_app(app, db, directory=directory)
421005
def migrateUp(self):
        
        te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending)
        if te is not None:
            self._transientSchedule(te.time, None)
725063
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: https://alembic.sqlalchemy.org/en/latest/cookbook.html
    def process_revision_directives(context, revision, directives):
        if getattr(config.cmd_opts, 'autogenerate', False):
            script = directives[0]
            if script.upgrade_ops.is_empty():
                directives[:] = []
                logger.info('No changes in schema detected.')

    engine = engine_from_config(config.get_section(config.config_ini_section),
                                prefix='sqlalchemy.',
                                poolclass=pool.NullPool)

    connection = engine.connect()
    kwargs = {}
    if engine.name in ('sqlite', 'mysql'):
        kwargs = {
            'transaction_per_migration': True,
            'transactional_ddl': True,
        }
    configure_args = current_app.extensions['migrate'].configure_args
    if configure_args:
        kwargs.update(configure_args)

    context.configure(connection=connection,
                      target_metadata=target_metadata,
                      # compare_type=True,
                      process_revision_directives=process_revision_directives,
                      **kwargs)

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()
438133
public function down()
    {
        Schema::table('notifications', function ($table) {
            $driver = Config::get('database.driver');

            if ($driver === 'mysql' || $driver === 'sqlite') {
                DB::statement('ALTER TABLE notifications MODIFY COLUMN extra STRING(255)');
            } elseif ($driver === 'pgsql') {
                DB::statement('ALTER TABLE notifications ALTER COLUMN extra TYPE string USING code::json');
            }
        });
    }
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)
100865
def migrateUp(self):
        
        siteStore = self.store.parent
        def _():
            # No convenience method for the following because needing to do it is
            # *rare*.  It *should* be ugly; 99% of the time if you need to do this
            # you're making a mistake. -glyph
            siteStoreSubRef = siteStore.getItemByID(self.store.idInParent)
            self.cloneInto(siteStore, siteStoreSubRef)
            IScheduler(self.store).migrateUp()
        siteStore.transact(_)
1254820
def migrate(ctx, start_version, end_version):
    """"""
    if ctx.type == 'file':
        if ctx.data_file:
            file_path = ctx.data_file
        else:
            file_path = os.path.join(ctx.data_file, ctx.namespace + '.json')

        # todo make this more like alemebic and determine/load versions automatically
        with open(file_path, 'r') as f:
            data = json.loads(f.read())

        data = run_migration(data, start_version, end_version)
        with open(file_path, 'w') as f:
            f.write(json.dumps(data))
278434
def migrate(self, host, port, key, dest_db, timeout, *,
                copy=False, replace=False):
        """"""
        if not isinstance(host, str):
            raise TypeError("host argument must be str")
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if not isinstance(dest_db, int):
            raise TypeError("dest_db argument must be int")
        if not host:
            raise ValueError("Got empty host")
        if dest_db < 0:
            raise ValueError("dest_db must be greater equal 0")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")

        flags = []
        if copy:
            flags.append(b'COPY')
        if replace:
            flags.append(b'REPLACE')
        fut = self.execute(b'MIGRATE', host, port,
                           key, dest_db, timeout, *flags)
        return wait_ok(fut)
495487
private function runMigration()
    {
        $this->info("Running database migration...");
        $this->call('migrate', ['--force' => true]);

        $this->line('');
        $this->advanceBar();

        $this->clearCaches();
        return $this;
    }
1335057
public function migrateUp()
    {
        $this->builder->create(
            $this->table,
            function ($table) {
                $table->bigIncrements('id');

                $table->string('sha1', 40)->index();
                $table->text('statement');
                $table->double('time')->index();
                $table->integer('connection_id')->unsigned();

                $table->timestamps();
                $table->index('created_at');
                $table->index('updated_at');
            }
        );
    }
705921
public function down()
    {
        // Disable foreign key constraints or these DROPs will not work
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');


        ///////////////////////////////////////////////////////////////////////
        ////                       Lookup Tables                           ////
        ///////////////////////////////////////////////////////////////////////

        Schema::table('kb_lookup_categories', function($table){
            $table->dropIndex('kb_lookup_categories_title_unique');
            $table->dropForeign('kb_lookup_categories_created_by_foreign');
            $table->dropForeign('kb_lookup_categories_updated_by_foreign');
            $table->dropForeign('kb_lookup_categories_locked_by_foreign');
        });
        Schema::dropIfExists('kb_lookup_categories');


        ///////////////////////////////////////////////////////////////////////
        ////                    Main Tables                                ////
        ///////////////////////////////////////////////////////////////////////

        Schema::table('kb_items', function($table){
            $table->dropForeign('kb_items_kb_category_id_foreign');
            $table->dropForeign('kb_items_created_by_foreign');
            $table->dropForeign('kb_items_updated_by_foreign');
            $table->dropForeign('kb_items_locked_by_foreign');
        });
        Schema::dropIfExists('kb_items');

        // Enable foreign key constraints
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }
233582
function onupgradeneeded() {
            self.db = request.result;
            self.transaction = request.transaction;

            // NB! in case of a version conflict, we don't try to migrate,
            // instead just throw away the old store and create a new one.
            // this happens if somebody changed the 
            try {
                self.db.deleteObjectStore(self.record);
            } catch (e) { /* ignore */ }

            // create object store.
            var objectStoreOptions = {
                autoIncrement: useAutoIncrement()
            }
            if( typeof( self.keyPath )) {
                objectStoreOptions.keyPath = self.keyPath;
            }
            self.db.createObjectStore(self.record, objectStoreOptions);
        }
1026133
def migrate(direction)
      return unless respond_to?(direction)

      announce "migrating seeds"

      time   = nil
      ActiveRecord::Base.connection_pool.with_connection do |conn|
        time = Benchmark.measure do
          exec_migration(conn, direction)
        end
      end

      case direction
      when :up   then announce "migrated (%.4fs)" % time.real; write
      when :down then announce "reverted (%.4fs)" % time.real; write
      end
    end
942611
public function safeUp()
    {
        // Rename the FK columns
        // ---------------------------------------------------------------------

        if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale__siteId')) {
            MigrationHelper::renameColumn('{{%supertableblocks}}', 'ownerLocale__siteId', 'ownerSiteId');
        }

        // Drop the old FKs
        // ---------------------------------------------------------------------

        MigrationHelper::dropForeignKeyIfExists('{{%supertableblocks}}', ['ownerLocale'], $this);

        // Drop the old indexes
        // ---------------------------------------------------------------------

        MigrationHelper::dropIndexIfExists('{{%supertableblocks}}', ['ownerLocale'], false, $this);

        // Drop the locale columns
        // ---------------------------------------------------------------------

        if ($this->db->columnExists('{{%supertableblocks}}', 'ownerLocale')) {
            $this->dropColumn('{{%supertableblocks}}', 'ownerLocale');
        }

        // Super Table content tables
        // ---------------------------------------------------------------------

        $superTableTablePrefix = $this->db->getSchema()->getRawTableName('{{%stc_}}');

        foreach ($this->db->getSchema()->getTableNames() as $tableName) {
            if (StringHelper::startsWith($tableName, $superTableTablePrefix)) {
                // There's actually an issue here in the MigrationHelper::dropAllIndexesOnTable class, not using the current migration
                // as context to find existing indexes. This is important, because the indexes have changed from their current names
                $this->dropAllForeignKeysOnTable($tableName);
                $this->dropAllIndexesOnTable($tableName);

                // Rename column
                if ($this->db->columnExists($tableName, 'locale__siteId')) {
                    $this->renameColumn($tableName, 'locale__siteId', 'siteId');
                }

                // Add them back (like creating a new Matrix would)
                $this->createIndex(null, $tableName, ['elementId', 'siteId'], true);
                $this->addForeignKey(null, $tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null);
                $this->addForeignKey(null, $tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE');

                // Delete the old column
                if ($this->db->columnExists($tableName, 'locale')) {
                    $this->dropColumn($tableName, 'locale');
                }
            }
        }

        Craft::$app->getDb()->getSchema()->refresh();

        // Update Super Table/relationship field settings
        // ---------------------------------------------------------------------

        $fields = (new Query())
            ->select(['id', 'type', 'translationMethod', 'settings'])
            ->from(['{{%fields}}'])
            ->where([
                'type' => [
                    SuperTableField::class,
                ]
            ])
            ->all($this->db);

        foreach ($fields as $field) {

            $settings = Json::decodeIfJson($field['settings']);

            if (!is_array($settings)) {
                echo 'Field '.$field['id'].' ('.$field['type'].') settings were invalid JSON: '.$field['settings']."\n";
                $settings = [];
            }

            $localized = ($field['translationMethod'] === 'site');

            $settings['localizeBlocks'] = $localized;

            $this->update(
                '{{%fields}}',
                [
                    'translationMethod' => 'none',
                    'settings' => Json::encode($settings),
                ],
                ['id' => $field['id']],
                [],
                false);
        }
    }
474509
def run(self, *args):
        """"""

        params = self.parser.parse_args(args)

        from_id = params.from_id
        to_uuid = params.to_uuid

        code = self.move(from_id, to_uuid)

        return code
441706
def migrate(self):
        """"""
        with io.open(self.json_file, 'rt', encoding='utf8') as fh:
            threads = json.load(fh)
        progress = Progress(len(threads))

        for i, thread in enumerate(threads):
            progress.update(i, str(i))
            self.insert(thread)

        progress.finish("{0} threads, {1} comments".format(len(threads), self.count))