stamp' the revision table with the given revision; don't run any
    migrations
971495
def stamp(directory=None, revision='head', sql=False, tag=None):
    """'"""
    config = current_app.extensions['migrate'].migrate.get_config(directory)
    command.stamp(config, revision, sql=sql, tag=tag)
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()
642579
def absent(version,
           name):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    #check if cluster exists and remove it
    if __salt__['postgres.cluster_exists'](version, name):
        if __opts__.get('test'):
            ret['result'] = None
            msg = 'Cluster {0}/{1} is set to be removed'
            ret['comment'] = msg.format(version, name)
            return ret
        if __salt__['postgres.cluster_remove'](version, name, True):
            msg = 'Cluster {0}/{1} has been removed'
            ret['comment'] = msg.format(version, name)
            ret['changes'][name] = 'Absent'
            return ret

    # fallback
    ret['comment'] = 'Cluster {0}/{1} is not present, so it cannot ' \
                     'be removed'.format(version, name)
    return ret
488603
def get_changeset(self, revision=None):
        
        if isinstance(revision, GitChangeset):
            return revision
        revision = self._get_revision(revision)
        changeset = GitChangeset(repository=self, revision=revision)
        return changeset
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))
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
309454
def save(self):
        

        # TODO: Add option force_insert

        if not self.is_loaded and self.id is None or self.id == '':
            data = self.resource.post(data=self.data, collection=self.collection)
            self.id = data['_id']
            self.key = data['_key']
            self.revision = data['_rev']
            self.is_loaded = True
        else:
            data = self.resource(self.id).patch(data=self.data)
            self.revision = data['_rev']
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()
346784
public function upgrade(): void
    {
        // This table was previously created by the favorites module in 1.7.9.
        // These migrations are now part of the core code.

        if (!DB::schema()->hasTable('news')) {
            DB::schema()->create('news', static function (Blueprint $table): void {
                $table->integer('news_id', true);
                $table->integer('user_id')->nullable();
                $table->integer('gedcom_id')->nullable();
                $table->string('subject', 255);
                $table->text('body');
                $table->timestamp('updated')->useCurrent();
                
                $table->index(['user_id', 'updated']);
                $table->index(['gedcom_id', 'updated']);

                $table->foreign('user_id')->references('user_id')->on('user')->onDelete('cascade');
                $table->foreign('gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
            });
        }
    }
874840
public boolean updateVersion(final Migration migration) {
        final Statement insert = QueryBuilder.insertInto(SCHEMA_VERSION_CF).value(TYPE, migration.getType().name())
                .value(VERSION, migration.getVersion()).value(TIMESTAMP, System.currentTimeMillis())
                .value(DESCRIPTION, migration.getDescription()).setConsistencyLevel(ConsistencyLevel.ALL);

        try {
            session.execute(insert);
            return true;
        } catch (final Exception e) {
            LOGGER.error("Failed to execute update version statement", e);
            return false;
        }
    }
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)
1068404
def drop_alembic_version_table():
    """"""
    if _db.engine.dialect.has_table(_db.engine, 'alembic_version'):
        alembic_version = _db.Table('alembic_version', _db.metadata,
                                    autoload_with=_db.engine)
        alembic_version.drop(bind=_db.engine)
55982
def patch(patch, ids):
    """"""
    records_deprecation_warning()

    from .api import Record

    patch_content = patch.read()

    if ids:
        for id_ in ids:
            rec = Record.get_record(id_).patch(patch_content).commit()
            current_app.logger.info("Created new revision {0}".format(
                rec.revision_id))
            click.echo(rec.id)
        db.session.commit()
397271
@GET
    @Path("{dbName}/scripts/{revision}")
    public ScriptInfo script(@PathParam("dbName") String dbName, @PathParam("revision") String revision) {
        Migration migration = locator.getService(Migration.class, dbName);
        if (migration == null)
            throw new NotFoundException();
        return migration.getScript(revision);
    }
319044
def migrate_tables(tables, engine_name=None):
    
    from alembic.migration import MigrationContext
    engine = engine_manager[engine_name]
    mc = MigrationContext.configure(engine.session().connection)
    script =  get_migrate_script(mc, tables, engine.metadata)
    run_migrate_script(mc, script)
885477
def _cmd_create(self):
        
        assert self._message, "need to supply a message for the \"create\" command"
        if not self._revisions:
            self._revisions.append("1")

        # get the migration folder
        rev_folder = self._revisions[-1]
        full_rev_path = os.path.join(self._migration_path, rev_folder)
        if not os.path.exists(full_rev_path):
            os.mkdir(full_rev_path)
        else:
            count = len(glob.glob(os.path.join(full_rev_path, "*")))
            # create next revision folder if needed
            if count and self._rev and int(self._rev) == 0:
                rev_folder = str(int(rev_folder) + 1)
                full_rev_path = os.path.join(self._migration_path, rev_folder)
                os.mkdir(full_rev_path)
                self._revisions.append(rev_folder)

        # format file name
        filename = '_'.join([s.lower() for s in self._message.split(' ') if s.strip()])
        for p in string.punctuation:
            if p in filename:
                filename = filename.replace(p, '_')
        filename = "%s_%s" % (datetime.utcnow().strftime("%Y%m%d%H%M%S"), filename.replace('__', '_'))

        # create the migration files
        self._log(0, "creating files: ")
        for s in ('up', 'down'):
            file_path = os.path.join(full_rev_path, "%s.%s.sql" % (filename, s))
            with open(file_path, 'a+') as w:
                w.write('\n'.join([
                    '-- *** %s ***' % s.upper(),
                    '-- file: %s' % os.path.join(rev_folder, filename),
                    '-- comment: %s' % self._message]))
                self._log(0, file_path)
707368
def __lazy_migration(self, master_id):
        
        collection_name = self.request.headers.get("collection")

        if collection_name:
            stack = AsyncSchedulableDocumentRevisionStack(collection_name,
                                                          self.settings,
                                                          master_id=master_id,
                                                          )
            objects = yield stack._lazy_migration(meta=self._get_meta_data())
            raise Return(objects)

        self.raise_error(500, "This object %s/%s didn't exist as a revision, "
                         "we tried to create it but we failed... Sorry. "
                         "Please check this object" % (collection_name,
                                                       master_id))
        raise Return(None)