当前位置: 首页>>代码示例>>Python>>正文


Python command.stamp方法代码示例

本文整理汇总了Python中alembic.command.stamp方法的典型用法代码示例。如果您正苦于以下问题:Python command.stamp方法的具体用法?Python command.stamp怎么用?Python command.stamp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在alembic.command的用法示例。


在下文中一共展示了command.stamp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: build_database

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def build_database(echo=True, tests=False):
    """ Applies the schema to the database. Run this command once to build the database. """
    engine = session.get_engine(echo=echo)

    schema = config_get('database', 'schema', raise_exception=False)
    if schema:
        print('Schema set in config, trying to create schema:', schema)
        try:
            engine.execute(CreateSchema(schema))
        except Exception as e:
            print('Cannot create schema, please validate manually if schema creation is needed, continuing:', e)

    models.register_models(engine)

    # Put the database under version control
    alembic_cfg = Config(config_get('alembic', 'cfg'))
    command.stamp(alembic_cfg, "head") 
开发者ID:rucio,项目名称:rucio,代码行数:19,代码来源:util.py

示例2: create_all_or_upgrade_db

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def create_all_or_upgrade_db(engine, db_url):
    # alembic add a lot of import time, so we lazy import
    from alembic import command
    from alembic.config import Config
    from sqlalchemy import inspect

    alembic_config_file = os.path.join(os.path.dirname(__file__), 'alembic.ini')
    alembic_config = Config(alembic_config_file)
    alembic_config.set_main_option('sqlalchemy.url', db_url)

    inspector = inspect(engine)
    tables = inspector.get_table_names()

    if 'deployments' not in tables and 'bentos' not in tables:
        logger.debug('Creating tables')
        Base.metadata.create_all(engine)
        command.stamp(alembic_config, 'head')
    else:
        logger.debug('Upgrading tables to the latest revision')
        command.upgrade(alembic_config, 'heads') 
开发者ID:bentoml,项目名称:BentoML,代码行数:22,代码来源:db.py

示例3: main

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = load_full_settings(config_uri, options=options)

    engine = engine_from_config(settings, "sqlalchemy.")
    wait_for_db(engine)

    with engine.begin() as connection:
        initdb(connection, drop_all="--force" in options)

    app_name = urllib.parse.urlparse(config_uri).fragment

    # generate the Alembic version table and stamp it with the latest revision
    alembic_cfg = Config("alembic.ini", ini_section=app_name)
    command.stamp(alembic_cfg, "head") 
开发者ID:GFDRR,项目名称:thinkhazard,代码行数:21,代码来源:initializedb.py

示例4: create_schema

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def create_schema(config=None, engine=None):
    """Create database schema from models description.

    Can be used for initial installation instead of upgrade('head').
    """
    if engine is None:
        engine = enginefacade.writer.get_engine()

    # NOTE(viktors): If we will use metadata.create_all() for non empty db
    #                schema, it will only add the new tables, but leave
    #                existing as is. So we should avoid of this situation.
    if version(engine=engine) is not None:
        raise db_exc.DBMigrationError("DB schema is already under version"
                                      " control. Use upgrade() instead")

    models.Base.metadata.create_all(engine)
    stamp('head', config=config) 
开发者ID:openstack,项目名称:vitrage,代码行数:19,代码来源:__init__.py

示例5: init

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def init():
    from sqlalchemy import create_engine
    from moxie.models import Base
    from moxie.core import DATABASE_URL
    engine = create_engine(DATABASE_URL)
    for table in Base.metadata.tables:
        engine.execute("DROP TABLE IF EXISTS \"{}\" CASCADE;".format(table))
    Base.metadata.create_all(engine)
    import os
    from alembic.config import Config
    from alembic import command
    alembic_cfg = Config(os.path.join(
        os.path.abspath(os.path.dirname(__file__)),
        "..",
        "alembic.ini"
    ))
    command.stamp(alembic_cfg, "head") 
开发者ID:paultag,项目名称:moxie,代码行数:19,代码来源:cli.py

示例6: _upgrade_db_initialized_before_mlflow_1

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def _upgrade_db_initialized_before_mlflow_1(engine):
    """
    Upgrades the schema of an MLflow tracking database created prior to MLflow 1.0, removing
    duplicate constraint names. This method performs a one-time update for pre-1.0 users that we
    plan to make available in MLflow 1.0 but remove in successive versions (e.g. MLflow 1.1),
    after which we will assume that effectively all databases have been initialized using the schema
    in mlflow.store.dbmodels.initial_models (with a small number of special-case databases
    initialized pre-1.0 and migrated to have the same schema as mlflow.store.dbmodels.initial_models
    via this method).
    TODO: remove this method in MLflow 1.1.
    """
    # alembic adds significant import time, so we import it lazily
    from alembic import command
    _logger.info("Updating database tables in preparation for MLflow 1.0 schema migrations ")
    alembic_dir = os.path.join(_get_package_dir(), 'temporary_db_migrations_for_pre_1_users')
    config = _get_alembic_config(str(engine.url), alembic_dir)
    command.upgrade(config, 'heads')
    # Reset the alembic version to "base" (the 'first' version) so that a) the versioning system
    # is unaware that this migration occurred and b) subsequent migrations, like the migration to
    # add metric steps, do not need to depend on this one. This allows us to eventually remove this
    # method and the associated migration e.g. in MLflow 1.1.
    command.stamp(config, "base") 
开发者ID:mlflow,项目名称:mlflow,代码行数:24,代码来源:utils.py

示例7: run

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def run(self, parser, args):
        # alembic.ini uses relative paths, so set the working directory
        os.chdir(os.path.dirname(os.path.dirname(relengapi.__file__)))
        for dbname in current_app.db.database_names:
            logger.info("creating tables for database %s", dbname)
            meta = current_app.db.metadata[dbname]
            engine = current_app.db.engine(dbname)
            meta.create_all(bind=engine)

            # load the Alembic config and stamp it with the most recent rev
            config_path = os.path.join(os.path.dirname(relengapi.__file__),
                                       'alembic', dbname, 'alembic.ini')
            if os.path.isfile(config_path):
                logger.info("stamping database %s with head", dbname)
                alembic_cfg = Config(config_path)
                command.stamp(alembic_cfg, "head") 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:18,代码来源:__init__.py

示例8: upgrade_db

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def upgrade_db(url, py_file, engine, name=None):
    if name is None:
        name = 'alembic'
    packagedir = os.path.dirname(os.path.abspath(py_file))
    alembic_path = os.path.join(packagedir, name)
    if not os.path.isdir(alembic_path):
        logmessage(name + " directory not found in package directory " + packagedir)
        return
    ini_file = os.path.join(packagedir, name + '.ini')
    if not os.path.isfile(ini_file):
        logmessage(name + ".ini file not found at " + ini_file)
        return
    versions_path = os.path.join(alembic_path, 'versions')
    if not os.path.isdir(versions_path):
        os.makedirs(versions_path)
    from alembic.config import Config
    from alembic import command
    alembic_cfg = Config(ini_file)
    alembic_cfg.set_main_option("sqlalchemy.url", url)
    alembic_cfg.set_main_option("script_location", alembic_path)
    if not engine.has_table('alembic_version'):
        command.stamp(alembic_cfg, "head")
    command.upgrade(alembic_cfg, "head") 
开发者ID:jhpyle,项目名称:docassemble,代码行数:25,代码来源:sql.py

示例9: upgrade

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def upgrade(self, nocreate=False):
        from alembic import command
        from alembic import migration

        cfg = self._get_alembic_config()
        cfg.conf = self.conf
        if nocreate:
            command.upgrade(cfg, "head")
        else:
            with self.facade.writer_connection() as connection:
                ctxt = migration.MigrationContext.configure(connection)
                current_version = ctxt.get_current_revision()
                if current_version is None:
                    Base.metadata.create_all(connection)
                    command.stamp(cfg, "head")
                else:
                    command.upgrade(cfg, "head")

        try:
            with self.facade.writer() as session:
                session.add(
                    ResourceType(
                        name="generic",
                        tablename="generic",
                        state="active",
                        attributes=resource_type.ResourceTypeAttributes()))
        except exception.DBDuplicateEntry:
            pass

    # NOTE(jd) We can have deadlock errors either here or later in
    # map_and_create_tables(). We can't decorate create_resource_type()
    # directly or each part might retry later on its own and cause a
    # duplicate. And it seems there's no way to use the same session for
    # both adding the resource_type in our table and calling
    # map_and_create_tables() :-( 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:37,代码来源:sqlalchemy.py

示例10: oneshot

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def oneshot(cli_ctx, alembic_config):
    '''
    Set up your database with one-shot schema migration instead of
    iterating over multiple revisions if there is no existing database.
    It uses alembic.ini to configure database connection.

    Reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
               #building-an-up-to-date-database-from-scratch
    '''
    with cli_ctx.logger:
        alembic_cfg = Config(alembic_config)
        sa_url = alembic_cfg.get_main_option('sqlalchemy.url')

        engine = sa.create_engine(sa_url)
        engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')

        with engine.begin() as connection:
            context = MigrationContext.configure(connection)
            current_rev = context.get_current_revision()

        if current_rev is None:
            # For a fresh clean database, create all from scratch.
            # (it will raise error if tables already exist.)
            log.info('Detected a fresh new database.')
            log.info('Creating tables...')
            with engine.begin() as connection:
                alembic_cfg.attributes['connection'] = connection
                metadata.create_all(engine, checkfirst=False)
                log.info('Stamping alembic version to head...')
                command.stamp(alembic_cfg, 'head')
        else:
            # If alembic version info is already available, perform incremental upgrade.
            log.info('Detected an existing database.')
            log.info('Performing schema upgrade to head...')
            with engine.begin() as connection:
                alembic_cfg.attributes['connection'] = connection
                command.upgrade(alembic_cfg, 'head')

        log.info("If you don't need old migrations, delete them and set "
                 "\"down_revision\" value in the earliest migration to \"None\".") 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:42,代码来源:dbschema.py

示例11: stamp

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def stamp(directory=None, revision='head', sql=False, tag=None):
    """'stamp' the revision table with the given revision; don't run any
    migrations"""
    config = current_app.extensions['migrate'].migrate.get_config(directory)
    command.stamp(config, revision, sql=sql, tag=tag) 
开发者ID:jpush,项目名称:jbox,代码行数:7,代码来源:__init__.py

示例12: stamp

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def stamp(config, revision: str, sql: bool, tag: Optional[str]):
    """'stamp' the revision table with the given revision; don't run any
    migrations."""

    bot = Bot(config)

    directory = os.path.join('yui', 'migrations')
    c = Config(os.path.join(directory, 'alembic.ini'))
    c.set_main_option('script_location', directory)
    c.set_main_option('sqlalchemy.url', bot.config.DATABASE_URL)
    c.attributes['Base'] = bot.orm_base

    command.stamp(c, revision, sql=sql, tag=tag) 
开发者ID:item4,项目名称:yui,代码行数:15,代码来源:cli.py

示例13: init_db

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def init_db():
    """
    Initialize the database; call
    :py:meth:`sqlalchemy.schema.MetaData.create_all` on the metadata object.
    """
    logger.debug('Initializing database')
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    alembic_ini = pkg_resources.resource_filename(
        pkg_resources.Requirement.parse('biweeklybudget'),
        'biweeklybudget/alembic/alembic.ini'
    )
    topdir = os.path.abspath(
        os.path.join(os.path.dirname(alembic_ini), '..', '..')
    )
    logger.debug('Alembic configuration: %s', alembic_ini)
    with in_directory(topdir):
        alembic_config = Config(alembic_ini)
        script = ScriptDirectory.from_config(alembic_config)
        curr_rev = _alembic_get_current_rev(alembic_config, script)
        head_rev = script.get_revision("head").revision
        if curr_rev is None:
            # alembic not initialized at all; stamp with current version
            logger.warning(
                'Alembic not setup; creating all models and stamping'
            )
            logger.debug('Creating all models')
            Base.metadata.create_all(engine)
            command.stamp(alembic_config, "head")
            logger.debug("DB stamped at %s", head_rev)
        elif curr_rev != head_rev:
            logger.warning("Alembic head is %s but this DB is at %s; "
                           "running migrations", head_rev, curr_rev)
            command.upgrade(alembic_config, "head")
            logger.info("Migrations complete")
        else:
            logger.debug('Alembic is at the correct head version (%s)',
                         curr_rev)
    logger.debug('Done initializing DB')
    init_event_listeners(db_session, engine) 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:43,代码来源:db.py

示例14: setUp

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def setUp(self):
        from gengine.app.cache import clear_all_caches
        clear_all_caches()
        self.db = db.db()
        dsn = self.db.dsn()
        self.engine =  create_engine(
            "postgresql://%(user)s@%(host)s:%(port)s/%(database)s" % {
                "user": dsn["user"],
                "host": dsn["host"],
                "port": dsn["port"],
                "database": dsn["database"],
            }
        )
        init_session(override_session=scoped_session(get_sessionmaker(bind=self.engine)), replace=True)
        from gengine.metadata import Base
        Base.metadata.bind = self.engine

        Base.metadata.drop_all(self.engine)
        self.engine.execute("DROP SCHEMA IF EXISTS public CASCADE")
        self.engine.execute("CREATE SCHEMA IF NOT EXISTS public")

        from alembic.config import Config
        from alembic import command

        alembic_cfg = Config(attributes={
            'engine': self.engine,
            'schema': 'public'
        })
        script_location = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
            'app/alembic'
        )
        alembic_cfg.set_main_option("script_location", script_location)

        from gengine.app import model

        tables = [t for name, t in model.__dict__.items() if isinstance(t, Table)]
        Base.metadata.create_all(self.engine, tables=tables)

        command.stamp(alembic_cfg, "head") 
开发者ID:ActiDoo,项目名称:gamification-engine,代码行数:42,代码来源:base.py

示例15: run

# 需要导入模块: from alembic import command [as 别名]
# 或者: from alembic.command import stamp [as 别名]
def run(parser, options, args):
        if len(args) not in (1, 2):
            parser.error('Bad number of parameters')

        # Read the configuration of the application
        try:
            application = args[1]
        except IndexError:
            application = 'kansha'

        cfg = _build_alembic_config()
        _set_sqlalchemy_uri(cfg, application, parser.error)

        command.stamp(cfg, args[0]) 
开发者ID:Net-ng,项目名称:kansha,代码行数:16,代码来源:admin.py


注:本文中的alembic.command.stamp方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。