當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。