Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.
761420
def run_migrations_online():
    
    engine = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool
    )

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()
1049018
def execute_migration(self, migration_file_relative):
        
        migration_file = os.path.join(self.db_config['migrations_dir'], migration_file_relative)
        m_type = self.repository.migration_type(migration_file)
        if m_type == 'native':
            return self.execute_native_migration(migration_file)
        if m_type == 'py':
            module = imp.load_source('migration_module', migration_file)
            return self.execute_python_migration(migration_file, module)
        assert False, 'Unknown migration type %s' % migration_file
1008322
def apply(config_override=None, tag_override=None, rollback=None, skip_missing=None):
    

    # Load config
    config = get_config(config_override)
    databases = config['databases']

    # If we are rolling back, ensure that we have a database tag
    if rollback and not tag_override:
        raise RuntimeError(
            'To rollback a migration you need to specify the database tag with `--tag`')

    for tag in sorted(databases):
        # If a tag is specified, skip other tags
        if tag_override and tag_override != tag:
            continue

        # Set vars
        engine = databases[tag].get('engine', 'mysql')
        host = databases[tag].get('host', 'localhost')
        port = databases[tag].get('port', 3306)
        user = databases[tag]['user']
        password = databases[tag]['password']
        db = databases[tag]['db']
        path = add_slash(databases[tag]['path'])
        pre_migration = databases[tag].get('pre_migration', None)
        post_migration = databases[tag].get('post_migration', None)

        # Check if the migration path exists
        if skip_missing:
            try:
                check_exists(path, 'dir')
            except RuntimeError:
                continue
        else:
            check_exists(path, 'dir')

        # Get database connection
        connection = get_connection(
            engine, host, user, port, password, db, get_ssl(databases[tag]))

        # Run pre migration queries
        if pre_migration:
            run_migration(connection, pre_migration, engine)

        if rollback:
            print(' * Rolling back %s (`%s` on %s)' % (tag, db, engine))

            rollback_migration(engine, connection, path, rollback)
        else:
            print(' * Applying migrations for %s (`%s` on %s)' %
                  (tag, db, engine))

            apply_migrations(engine, connection, path)

        # Run post migration queries
        if post_migration:
            run_migration(connection, post_migration, engine)

    return True
942664
public function up()
    {
        dbexec('delete from #__components where `option` IN ("com_installer","com_bazaar","com_tagmeta")');
        dbexec('delete from #__components where `option` IS NULL OR `option` = ""');
        dbexec('update #__components set admin_menu_link ="" where `option` IN ("com_search","com_todos","com_articles","com_pages","com_invites")');
        ///remove privacy_read_mode. some installation may still have it
        try {
            dbexec('alter table #__anahita_nodes drop column `privacy_read_mode`');
        } catch (Exception $e) {
        }

        dbexec('DROP TABLE IF EXISTS `#__core_log_items`');
        dbexec('DROP TABLE IF EXISTS `#__core_log_searches`');
        dbexec('DROP TABLE IF EXISTS `#__stats_agents`');
        dbexec('DROP TABLE IF EXISTS `#__tagmeta`');
        dbexec('DROP TABLE IF EXISTS `#__migration_backlinks`');
        dbexec('DROP TABLE IF EXISTS `#__migrations`');

        dbexec("DELETE FROM `#__modules_menu` WHERE `moduleid` IN (SELECT `id` FROM `#__modules` WHERE `module` IN ('mod_bazaar','mod_footer','mod_login','mod_rokquicklinks'))");
        dbexec("DELETE FROM `#__modules` WHERE `module` IN ('mod_bazaar','mod_footer','mod_login','mod_rokquicklinks')");

        $people = dbfetch('select id,person_username AS username,person_userid AS userid from #__anahita_nodes where type like "ComActorsDomainEntityActor,ComPeopleDomainEntityPerson,com:people.domain.entity.person" and person_username NOT REGEXP "^[A-Za-z0-9][A-Za-z0-9_-]*$"');
        foreach ($people as $person) {
            $username = $person['username'];
            $clean = $username = preg_replace('/(\s|\.|(@\w+))+/', '', $username);
            //add a randome number until the username becomes unique
            while (dbexists("select id from #__users where username like '$username'")) {
                $username = $clean.rand(0, 100);
            }
            dbexec("update #__anahita_nodes set person_username = '$username' where id = {$person['id']}");
            dbexec("update #__users set username = '$username' where id = {$person['userid']}");
        }
    }
836535
def init_or_migrate(self):
        
        assure_migrations_table_setup(self.session)

        # Find out what migration number, if any, this database data is at,
        # and what the latest is.
        migration_number = self.database_current_migration

        # Is this our first time?  Is there even a table entry for
        # this identifier?
        # If so:
        #  - create all tables
        #  - create record in migrations registry
        #  - print / inform the user
        #  - return 'inited'
        if migration_number is None:
            self.printer(u"-> Initializing %s... " % self.name_for_printing())

            self.init_tables()
            # auto-set at latest migration number
            self.create_new_migration_record()

            self.printer(u"done.\n")
            self.set_current_migration()
            return u'inited'

        # Run migrations, if appropriate.
        migrations_to_run = self.migrations_to_run()
        if migrations_to_run:
            self.printer(
                u'-> Updating %s:\n' % self.name_for_printing())
            for migration_number, migration_func in migrations_to_run:
                self.printer(
                    u'   + Running migration %s, "%s"... ' % (
                        migration_number, migration_func.func_name))
                migration_func(self.session)
                self.printer('done.\n')

            self.set_current_migration()
            return u'migrated'

        # Otherwise return None.  Well it would do this anyway, but
        # for clarity... ;)
        return None
1238716
def migrations_to_run(self):
        
        assert self.database_current_migration is not None

        db_current_migration = self.database_current_migration

        return [
            (migration_number, migration_func)
            for migration_number, migration_func in self.sorted_migrations
            if migration_number > db_current_migration]
145667
public function up() {

        ///////////////////////////////////////////////////////////////////////
        ////                     Main Table                                ////
        ///////////////////////////////////////////////////////////////////////

        if (!Schema::hasTable('email_messages'))
        {
            Schema::create('email_messages', function (Blueprint $table)
            {
                $table->engine = 'InnoDB';
                $table->increments('id')->unsigned();

                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users');

                // FROM https://github.com/lasallecrm/lasallecrm-l5-todo-pkg
                $table->integer('priority_id')->nullable()->unsigned();
                $table->foreign('priority_id')->references('id')->on('lookup_todo_priority_types');

                $table->string('from_email_address');
                $table->string('from_name')->nullable();
                $table->string('to_email_address');
                $table->string('to_name')->nullable();

                $table->string('subject');
                $table->string('slug');

                $table->text('body');

                $table->text('message_header')->nullable();

                $table->boolean('sent')->default(false);
                $table->timestamp('sent_timestamp')->nullable();
                $table->boolean('read')->default(false);
                $table->boolean('archived')->default(false);


                $table->timestamp('created_at');
                $table->integer('created_by')->unsigned();
                $table->foreign('created_by')->references('id')->on('users');
                $table->timestamp('updated_at');
                $table->integer('updated_by')->unsigned();
                $table->foreign('updated_by')->references('id')->on('users');
                $table->timestamp('locked_at')->nullable();
                $table->integer('locked_by')->nullable()->unsigned();
                $table->foreign('locked_by')->references('id')->on('users');
            });
        }


        ///////////////////////////////////////////////////////////////////////
        ////            Table Relating to the Main Table                   ////
        ///////////////////////////////////////////////////////////////////////

        if (!Schema::hasTable('email_attachments'))
        {
            Schema::create('email_attachments', function (Blueprint $table)
            {
                $table->engine = 'InnoDB';
                $table->increments('id')->unsigned();

                $table->integer('email_messages_id')->unsigned()->index();
                $table->foreign('email_messages_id')->references('id')->on('email_messages')->onDelete('cascade');

                $table->string('attachment_path');
                $table->string('attachment_filename');
                $table->string('alternate_sort_string1')->nullable()->index();
                $table->string('alternate_sort_string2')->nullable()->index();
                $table->text('comments')->nullable();
            });
        }
    }
1077538
def migrate(config):
    
    webapp = WebApp(config.web_host, config.web_port,
                    custom_maintenance_file=config.web_custom_html)

    webserver = WebServer(webapp)
    webserver.daemon = True
    webserver.start()

    migration_parser = YamlParser.parse_from_file(config.migration_file)
    migration = migration_parser.parse()

    database = Database(config)

    with database.connect() as lock_connection:
        application_lock = ApplicationLock(lock_connection)
        application_lock.start()

        while not application_lock.acquired:
            time.sleep(0.5)
        else:
            if application_lock.replica:
                # when a replica could finally acquire a lock, it
                # means that the concurrent process has finished the
                # migration or that it failed to run it.
                # In both cases after the lock is released, this process will
                # verify if it has still to do something (if the other process
                # failed mainly).
                application_lock.stop = True
                application_lock.join()
            # we are not in the replica or the lock is released: go on for the
            # migration

        try:
            table = MigrationTable(database)
            runner = Runner(config, migration, database, table)
            runner.perform()
        finally:
            application_lock.stop = True
            application_lock.join()
488754
public function migrate()
    {
        $fs = new Filesystem;
        $finder = new ClassFinder;
        $path = env('MIGRATIONS_PATH', 'database/migrations');

        if ($fs->exists($path)) {
            foreach ($fs->files($path) as $file) {
                $fs->requireOnce($file);
                $class = $finder->findClass($file);

                (new $class)->up();
            }
        }
    }
1094190
def run_migrations_online():
    
    set_mysql_engine()
    engine = session.create_engine(neutron_config.database.connection)

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        include_object=include_object,
        version_table=alembic_migrations.VERSION_TABLE
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()
        engine.dispose()
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))
827854
def _pretend_to_run(self, migration, method):
        
        self._note("")
        names = []
        for query in self._get_queries(migration, method):
            name = migration.__class__.__name__
            bindings = None

            if isinstance(query, tuple):
                query, bindings = query

            query = highlight(query, SqlLexer(), CommandFormatter()).strip()

            if bindings:
                query = (query, bindings)

            if name not in names:
                self._note("[<info>{}</info>]".format(name))
                names.append(name)

            self._note(query)
182
def add_migrations(self, migrations):
        
        if self.__closed:
            raise MigrationSessionError("Can't change applied session")
        self._to_apply.extend(migrations)
1007811
public static function _init()
	{
		logger(\Fuel::L_DEBUG, 'Migrate class initialized');

		// load the migrations config
		\Config::load('migrations', true);

		// set the name of the table containing the installed migrations
		static::$table = \Config::get('migrations.table', static::$table);

		// set the name of the connection group to use
		static::$connection = \Config::get('migrations.connection', static::$connection);

		// installs or upgrades the migration table to the current schema
		static::table_version_check();

		//get all installed migrations from db
		$migrations = \DB::select()
			->from(static::$table)
			->order_by('type', 'ASC')
			->order_by('name', 'ASC')
			->order_by('migration', 'ASC')
			->execute(static::$connection)
			->as_array();

		// convert the db migrations to match the config file structure
		foreach($migrations as $migration)
		{
			isset(static::$migrations[$migration['type']]) or static::$migrations[$migration['type']] = array();
			static::$migrations[$migration['type']][$migration['name']][] = $migration['migration'];
		}
	}
679184
def run_migrations_online():
    
    alembic_config = config.get_section(config.config_ini_section)
    alembic_config['sqlalchemy.url'] = os.environ['DATABASE_URI']

    connectable = engine_from_config(
        alembic_config,
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()
414131
def run_migrations_online():
    
    engine = create_engine(get_url())

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        version_table="alembic_ziggurat_foundations_version",
        transaction_per_migration=True,
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()
13838
def execute(self, conn, daoinput, transaction = False):
        	
        if not conn:
	    dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/MigrationRequests/UpdateRequestStatus. Expects db connection from upper layer.", 
                                self.logger.exception)
        if daoinput['migration_status'] == 1:
           sql = self.sql2 
        elif daoinput['migration_status'] == 2:
            sql = self.sql + " and MIGRATION_STATUS = 1 "
        elif daoinput['migration_status'] == 3:
            sql = self.sql3 + " and MIGRATION_STATUS = 1 " 
        else:
            dbsExceptionHandler("dbsException-conflict-data", "Oracle/MigrationRequest/UpdateRequestStatus. Expected migration status to be 1, 2 or 3",
                                self.logger.exception)
        
	result = self.dbi.processData(sql, daoinput, conn, transaction)