Exemplo n.º 1
0
 def __init__(self, file, repository, echoresults):
     
     #for backward compatibelity
     if re.match('^\w+://', file) == None:
         file = 'sqlite:///'+file   
     
     self.version = 2
     self.dbfile = file
     self.repository = repository
     
  
     
     #migrate code
     try:
         dbversion = api.db_version(file, self.repository)
         #print dbversion
     except :
         dbversion = 0
         api.version_control(file, self.repository, dbversion)
     
     if dbversion < self.version:
         api.upgrade(file, self.repository, self.version)
     elif  dbversion > self.version:
         api.downgrade(file, self.repository, self.version)
     
     engine = create_engine(file , echo=False)#edit by hassan : echoresults to True
     
     metadata = Base.metadata
     metadata.create_all(engine)
 
     Session = sessionmaker(engine)
     self.session = Session()            
Exemplo n.º 2
0
    def execute(self, parsed_args):
        url = cfg.CONF['backend:powerdns'].database_connection

        if not os.path.exists(REPOSITORY):
            raise Exception('Migration Repository Not Found')

        try:
            target_version = int(parsed_args.to_version) \
                if parsed_args.to_version else None

            current_version = versioning_api.db_version(url=url,
                                                        repository=REPOSITORY)
        except DatabaseNotControlledError:
            raise Exception('PowerDNS database not yet initialized')

        LOG.info("Attempting to synchronize PowerDNS database from version "
                 "'%s' to '%s'",
                 current_version,
                 target_version if target_version is not None else "latest")

        if target_version and target_version < current_version:
            versioning_api.downgrade(url=url, repository=REPOSITORY,
                                     version=parsed_args.to_version)
        else:
            versioning_api.upgrade(url=url, repository=REPOSITORY,
                                   version=parsed_args.to_version)

        LOG.info('PowerDNS database synchronized successfully')
Exemplo n.º 3
0
    def sync(self, version=None):
        url = cfg.CONF['storage:sqlalchemy'].database_connection

        if not os.path.exists(REPOSITORY):
            raise Exception('Migration Repository Not Found')

        try:
            target_version = int(version) if version else None

            current_version = versioning_api.db_version(url=url,
                                                        repository=REPOSITORY)
        except DatabaseNotControlledError:
            raise Exception('Database not yet initialized')

        LOG.info("Attempting to synchronize database from version "
                 "'%s' to '%s'",
                 current_version,
                 target_version if target_version is not None else "latest")

        if target_version and target_version < current_version:
            versioning_api.downgrade(url=url, repository=REPOSITORY,
                                     version=version)
        else:
            versioning_api.upgrade(url=url, repository=REPOSITORY,
                                   version=version)

        LOG.info('Database synchronized successfully')
Exemplo n.º 4
0
    def execute(self, parsed_args):
        url = cfg.CONF['storage:sqlalchemy'].database_connection

        if not os.path.exists(REPOSITORY):
            raise Exception('Migration Respository Not Found')

        try:
            target_version = int(parsed_args.to_version) \
                if parsed_args.to_version else None

            current_version = versioning_api.db_version(url=url,
                                                        repository=REPOSITORY)
        except DatabaseNotControlledError:
            raise Exception('Database not yet initialized')

        LOG.info("Attempting to synchronize database from version '%s' to '%s'"
                 % (current_version, target_version))

        if target_version and target_version < current_version:
            versioning_api.downgrade(url=url, repository=REPOSITORY,
                                     version=parsed_args.to_version)
        else:
            versioning_api.upgrade(url=url, repository=REPOSITORY,
                                   version=parsed_args.to_version)

        LOG.info('Database synchronized sucessfully')
Exemplo n.º 5
0
def downgrade_db(*opts):
    '''
    Downgrades the Database 1 rev.
    '''
    v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
    api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1)
    print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, 
                                                            SQLALCHEMY_MIGRATE_REPO))
Exemplo n.º 6
0
def db_downgrade(version):
    """Downgrade the database"""
    v1 = get_db_version()
    migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
    v2 = get_db_version()

    if v1 == v2:
        print 'No changes made.'
    else:
        print 'Downgraded: %s ... %s' % (v1, v2)
Exemplo n.º 7
0
def downgraddb():
    v = api.db_version(Config.SQLALCHEMY_DATABASE_URI,
                       Config.SQLALCHEMY_MIGRATE_REPO)

    api.downgrade(Config.SQLALCHEMY_DATABASE_URI,
                  Config.SQLALCHEMY_MIGRATE_REPO, v - 1)
    v = api.db_version(Config.SQLALCHEMY_DATABASE_URI,
                       Config.SQLALCHEMY_MIGRATE_REPO)

    print 'Current database version: ' + str(v)
Exemplo n.º 8
0
def downgrade_db(v):
    """downgrade database schema to specified version"""
    from_version = db_version(url=db, repository=repo)
    to_version = int(v)

    print("Downgrading db from version %d to %d. " % (from_version, to_version))
    print("Schema upgrade ... ")
    downgrade(url=db, repository=repo, version=v)
    print("Data upgrade ... ")
    datamigrations.run_downgrade_scripts(app, from_version, to_version)
    print("Done!")
Exemplo n.º 9
0
    def _migrate_down(self, engine, version, with_data=False):
        migration_api.downgrade(engine, TestMigrations.REPOSITORY, version)
        self.assertEqual(version, migration_api.db_version(engine, TestMigrations.REPOSITORY))

        # NOTE(sirp): `version` is what we're downgrading to (i.e. the 'target'
        # version). So if we have any downgrade checks, they need to be run for
        # the previous (higher numbered) migration.
        if with_data:
            post_downgrade = getattr(self, "_post_downgrade_%03d" % (version + 1), None)
            if post_downgrade:
                post_downgrade(engine)
Exemplo n.º 10
0
def rollback(count):
    if (rollbacks > v) or (rollbacks < 0):
        print "Invalid rollbacks count. Current version is %d." % v
        rollbacks = int(raw_input("Input valid count:"))
        rollback(rollbacks)
    else:
        api.downgrade(SQLALCHEMY_DATABASE_URI,
                      SQLALCHEMY_MIGRATE_REPO,
                      v - count)
        print ('Current database version: ' + 
               str(api.db_version(SQLALCHEMY_DATABASE_URI,
                                  SQLALCHEMY_MIGRATE_REPO)))
Exemplo n.º 11
0
def _downgradeDB(expectedVersion, dryrun):
    if not dryrun:
        api.downgrade(SQLALCHEMY_DATABASE_URI,
                      SQLALCHEMY_MIGRATE_REPO,
                      expectedVersion)
    
    print 'Current database version: ' + \
          str(api.db_version(SQLALCHEMY_DATABASE_URI,
                         SQLALCHEMY_MIGRATE_REPO))
    if dryrun:
        print 'Dryrun'
        print '\tNew database version will be: ' + str(expectedVersion)
Exemplo n.º 12
0
def db_downgrade(version=None):
    # This is used to downgrade the database schema to a certain version or to one version before.
    # If you know exactly the version you wish to use then you can directly downgrade to that version.
    if not version:
        current_version = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
        downgrade_version = current_version - 1
    else:
        downgrade_version = version
    api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, downgrade_version)

    print 'Database downgrade completed!'
    print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
Exemplo n.º 13
0
def downgrade(args):
    """
    Restores the database one previous version, run multiple times to go
    back multiple versions if needed.
    """

    # Get the configruation
    config = get_config()
    DB_URI = config.DATABASE_URI
    M_REPO = config.MIGRATIONS

    v = api.db_version(DB_URI, M_REPO)
    api.downgrade(DB_URI, M_REPO, v - 1)
    v = api.db_version(DB_URI, M_REPO)
    return "Current database version: %i" % v
Exemplo n.º 14
0
def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param engine:       SQLAlchemy engine instance for a given database
    :param abs_path:     Absolute path to migrate repository.
    :param version:      Database will upgrade/downgrade until this version.
                         If None - database will update to the latest
                         available version.
    :param init_version: Initial database version
    :param sanity_check: Require schema sanity checking for all tables
    """

    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DbMigrationError(
                message=_("version should be an integer"))

    current_version = db_version(engine, abs_path, init_version)
    repository = _find_migrate_repo(abs_path)
    if sanity_check:
        _db_schema_sanity_check(engine)
    if version is None or version > current_version:
        return versioning_api.upgrade(engine, repository, version)
    else:
        return versioning_api.downgrade(engine, repository,
                                        version)
Exemplo n.º 15
0
def db_sync(engine, version=None, init_version=INIT_VERSION):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param engine:       SQLAlchemy engine instance for a given database
    :param version:      Database will upgrade/downgrade until this version.
                         If None - database will update to the latest
                         available version.
    :param init_version: Initial database version
    """

    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DbMigrationError(
                message='version should be an integer')

    current_version = db_version(engine, init_version)
    repository = _find_migrate_repo()
    if version is None or version > current_version:
        return versioning_api.upgrade(engine, repository, version)
    else:
        return versioning_api.downgrade(engine, repository, version)
Exemplo n.º 16
0
def db_sync(abs_path, version=None, init_version=0):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param abs_path:     Absolute path to migrate repository.
    :param version:      Database will upgrade/downgrade until this version.
                         If None - database will update to the latest
                         available version.
    :param init_version: Initial database version
    """
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DbMigrationError(
                message=_("version should be an integer"))

    current_version = db_version(abs_path, init_version)
    repository = _find_migrate_repo(abs_path)
    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(), repository, version)
    else:
        return versioning_api.downgrade(get_engine(), repository,
                                        version)
Exemplo n.º 17
0
def downgrade(version):
    """Downgrade the database's current migration level."""
    db_version()  # Ensure db is under migration control
    repo_path = get_migrate_repo_path()
    sql_connection = CFG.db.sql_connection
    logger.info("Downgrading %(sql_connection)s to version %(version)s" %
                locals())
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 18
0
def downgradedb():
    """ Downgrades the database from the current to the previous
        version contained in the SQLAlchemy-migrate repository.
    """

    # Obtain Current Version
    ver = api.db_version(app.config['SQLALCHEMY_DATABASE_URI'],
                         app.config['SQLALCHEMY_MIGRATE_REPO'])

    # Downgrade Database To Previous Revision
    api.downgrade(app.config['SQLALCHEMY_DATABASE_URI'],
                  app.config['SQLALCHEMY_MIGRATE_REPO'], ver-1)

    # Obtain & Display Current Version
    ver = api.db_version(app.config['SQLALCHEMY_DATABASE_URI'],
                         app.config['SQLALCHEMY_MIGRATE_REPO'])
    print("Current database version: " + str(ver))
Exemplo n.º 19
0
def migrate_repository(version, current_version, repo_path):
    if version is None or version > current_version:
        result = versioning_api.upgrade(CONF.sql.connection,
                                        repo_path, version)
    else:
        result = versioning_api.downgrade(
            CONF.sql.connection, repo_path, version)
    return result
Exemplo n.º 20
0
 def do_db(self, line=''):
     args = line.split()
     action = args[0]
     if not action in self.db_actions:
         self.help_db()
         return 1
     self._register_config()
     import shakespeare.model as model
     import shakespeare
     migrate_repository = 'shakespeare/migration/'
     if action == 'create':
         model.repo.create_db()
     elif action == 'clean':
         model.repo.clean_db()
     elif action == 'rebuild':
         model.repo.rebuild_db()
     elif action == 'upgrade':
         version = None
         if len(args) > 1:
             version = args[1]
         import migrate.versioning.exceptions
         import migrate.versioning.api
         import migrate.versioning.api as mig
         try:
             mig.version_control(model.meta.engine.url, migrate_repository)
         except migrate.versioning.exceptions.DatabaseAlreadyControlledError:
             pass
         mig.upgrade(model.meta.engine.url, migrate_repository,
                 version=version)
     elif action == 'downgrade':
         if len(args) < 2:
             print 'You need to supply a version to downgrade to'
             return 1
         version = args[1]
         import migrate.versioning.api
         import migrate.versioning.api as mig
         mig.downgrade(model.meta.engine.url, migrate_repository,
                 version=version)
     elif action.startswith('init_'):
         modname = action.strip()[5:]
         mod = __import__(modname+'.cli', fromlist='cli')
         mod.LoadTexts.load_texts()
     else:
         print self.help_db()
Exemplo n.º 21
0
def downgrade(version):
    """
    Downgrade the database's current migration level

    :param version: version to downgrade to
    :retval version number
    """
    db_version()  # Ensure db is under migration control
    repository = _get_migrate_repo()
    LOG.info(_("Downgrading database to version %s") % version)
    return versioning_api.downgrade(get_engine(), repository, version)
Exemplo n.º 22
0
def downgrade(version):
    """
    Downgrade the database's current migration level

    :param version: version to downgrade to
    :retval version number
    """
    db_version()  # Ensure db is under migration control
    repo_path = get_migrate_repo_path()
    sql_connection = CONF.sql_connection
    LOG.info(_("Downgrading database to version %s") % version)
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 23
0
def downgrade(options, version):
    """
    Downgrade the database's current migration level

    :param options: options dict
    :param version: version to downgrade to
    :retval version number
    """
    db_version(options)  # Ensure db is under migration control
    repo_path = get_migrate_repo_path()
    sql_connection = options["sql_connection"]
    logger.info(_("Downgrading %(sql_connection)s to version %(version)s") % locals())
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 24
0
def downgrade(sql_connection, version):
    """
    Downgrade the database's current migration level

    :param sql_connection: sqlalchemy connection string
    :param version: version to downgrade to
    :retval version number
    """
    db_version(sql_connection)  # Ensure db is under migration control
    repo_path = get_migrate_repo_path()
    logger.info(_("Downgrading %(sql_connection)s to version %(version)s") %
                locals())
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 25
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.Error(_("version should be an integer"))
    current_version = db_version()
    repository = _find_migrate_repo()
    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(), repository, version)
    else:
        return versioning_api.downgrade(get_engine(), repository,
                                        version)
Exemplo n.º 26
0
def downgrade(options, version, repo_path=None):
    """Downgrade the database's current migration level.

    :param options: options dict
    :param version: version to downgrade to
    :retval version number

    """
    db_version(options, repo_path)  # Ensure db is under migration control
    repo_path = get_migrate_repo_path(repo_path)
    sql_connection = options['database']['connection']
    logger.info("Downgrading %(sql_connection)s to version %(version)s" %
                {'sql_connection': sql_connection, 'version': version})
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 27
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise Exception('version should be an integer')

    current_version = db_version()
    repo_path = _find_migrate_repo()
    if version is None or version > current_version:
        return versioning_api.upgrade(CONF.sql.connection, repo_path, version)
    else:
        return versioning_api.downgrade(
            CONF.sql.connection, repo_path, version)
Exemplo n.º 28
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise Exception("version should be an integer")

    current_version = db_version()
    repo_path = _find_migrate_repo()
    if version is None or version > current_version:
        return versioning_api.upgrade(
                CONF.sql.connection, repo_path, version)
    else:
        return versioning_api.downgrade(
                CONF.sql.connection, repo_path, version)
Exemplo n.º 29
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.Error(_("version should be an integer"))

    current_version = db_version()
    repo_path = _find_migrate_repo()
    if version is None or version > current_version:
        versioning_api.upgrade(FLAGS.sql_connection, repo_path, version)
        return fix_dns_domains.run(get_engine())
    else:
        return versioning_api.downgrade(FLAGS.sql_connection, repo_path,
                                        version)
Exemplo n.º 30
0
    def _walk_versions(self, engine=None, snake_walk=False):
        # Determine latest version script from the repo, then
        # upgrade from 1 through to the latest, with no data
        # in the databases. This just checks that the schema itself
        # upgrades successfully.

        # Place the database under version control
        migration_api.version_control(engine, TestMigrations.REPOSITORY)
        self.assertEqual(0,
                migration_api.db_version(engine,
                                         TestMigrations.REPOSITORY))

        LOG.debug('latest version is %s' % TestMigrations.REPOSITORY.latest)

        for version in xrange(1, TestMigrations.REPOSITORY.latest + 1):
            # upgrade -> downgrade -> upgrade
            migration_api.upgrade(engine, TestMigrations.REPOSITORY, version)
            self.assertEqual(version,
                    migration_api.db_version(engine,
                                             TestMigrations.REPOSITORY))
            if snake_walk:
                migration_api.downgrade(engine,
                                        TestMigrations.REPOSITORY,
                                        version - 1)
                self.assertEqual(version - 1,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
                migration_api.upgrade(engine,
                                      TestMigrations.REPOSITORY,
                                      version)
                self.assertEqual(version,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))

        # Now walk it back down to 0 from the latest, testing
        # the downgrade paths.
        for version in reversed(
            xrange(0, TestMigrations.REPOSITORY.latest)):
            # downgrade -> upgrade -> downgrade
            migration_api.downgrade(engine, TestMigrations.REPOSITORY, version)
            self.assertEqual(version,
                    migration_api.db_version(engine,
                                             TestMigrations.REPOSITORY))
            if snake_walk:
                migration_api.upgrade(engine,
                                      TestMigrations.REPOSITORY,
                                      version + 1)
                self.assertEqual(version + 1,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
                migration_api.downgrade(engine,
                                        TestMigrations.REPOSITORY,
                                        version)
                self.assertEqual(version,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
Exemplo n.º 31
0
    def _walk_versions(self, engine=None, snake_walk=False):
        # Determine latest version script from the repo, then
        # upgrade from 1 through to the latest, with no data
        # in the databases. This just checks that the schema itself
        # upgrades successfully.

        # Place the database under version control
        migration_api.version_control(engine, TestMigrations.REPOSITORY)
        self.assertEqual(0,
                migration_api.db_version(engine,
                                         TestMigrations.REPOSITORY))

        LOG.debug('latest version is %s' % TestMigrations.REPOSITORY.latest)

        for version in xrange(1, TestMigrations.REPOSITORY.latest + 1):
            # upgrade -> downgrade -> upgrade
            migration_api.upgrade(engine, TestMigrations.REPOSITORY, version)
            self.assertEqual(version,
                    migration_api.db_version(engine,
                                             TestMigrations.REPOSITORY))
            if snake_walk:
                migration_api.downgrade(engine,
                                        TestMigrations.REPOSITORY,
                                        version - 1)
                self.assertEqual(version - 1,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
                migration_api.upgrade(engine,
                                      TestMigrations.REPOSITORY,
                                      version)
                self.assertEqual(version,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))

        # Now walk it back down to 0 from the latest, testing
        # the downgrade paths.
        for version in reversed(
            xrange(0, TestMigrations.REPOSITORY.latest)):
            # downgrade -> upgrade -> downgrade
            migration_api.downgrade(engine, TestMigrations.REPOSITORY, version)
            self.assertEqual(version,
                    migration_api.db_version(engine,
                                             TestMigrations.REPOSITORY))
            if snake_walk:
                migration_api.upgrade(engine,
                                      TestMigrations.REPOSITORY,
                                      version + 1)
                self.assertEqual(version + 1,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
                migration_api.downgrade(engine,
                                        TestMigrations.REPOSITORY,
                                        version)
                self.assertEqual(version,
                        migration_api.db_version(engine,
                                                 TestMigrations.REPOSITORY))
Exemplo n.º 32
0
def db_sync(version=None, database='main', context=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.NovaException(_("version should be an integer"))

    current_version = db_version(database, context=context)
    repository = _find_migrate_repo(database)
    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(database, context=context),
                                      repository, version)
    else:
        return versioning_api.downgrade(get_engine(database, context=context),
                                        repository, version)
Exemplo n.º 33
0
    def test_workflow(self):
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.script('First Version', self.repo)
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.upgrade(self.url, self.repo, 1)
        self.assertEqual(api.db_version(self.url, self.repo), 1)
        api.downgrade(self.url, self.repo, 0)
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.test(self.url, self.repo)
        self.assertEqual(api.db_version(self.url, self.repo), 0)

        # preview
        # TODO: test output
        out = api.upgrade(self.url, self.repo, preview_py=True)
        out = api.upgrade(self.url, self.repo, preview_sql=True)

        api.upgrade(self.url, self.repo, 1)
        api.script_sql('default', 'desc', self.repo)
        self.assertRaises(UsageError, api.upgrade, self.url, self.repo, 2, preview_py=True)
        out = api.upgrade(self.url, self.repo, 2, preview_sql=True)

        # cant upgrade to version 1, already at version 1
        self.assertEqual(api.db_version(self.url, self.repo), 1)
        self.assertRaises(KnownError, api.upgrade, self.url, self.repo, 0)
Exemplo n.º 34
0
def db_sync(version=None, database='main', context=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.NovaException(_("version should be an integer"))

    current_version = db_version(database, context=context)
    repository = _find_migrate_repo(database)
    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(database, context=context),
                repository, version)
    else:
        return versioning_api.downgrade(get_engine(database, context=context),
                repository, version)
Exemplo n.º 35
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.NovaException(_("version should be an integer"))

    current_version = db_version()
    repository = _find_migrate_repo()
    if version is None or version > current_version:
        return versioning_api.upgrade(session.get_engine(), repository,
                                      version)
    else:
        return versioning_api.downgrade(session.get_engine(), repository,
                                        version)
Exemplo n.º 36
0
    def test_workflow(self):
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.script('First Version', self.repo)
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.upgrade(self.url, self.repo, 1)
        self.assertEqual(api.db_version(self.url, self.repo), 1)
        api.downgrade(self.url, self.repo, 0)
        self.assertEqual(api.db_version(self.url, self.repo), 0)
        api.test(self.url, self.repo)
        self.assertEqual(api.db_version(self.url, self.repo), 0)

        # preview
        # TODO: test output
        out = api.upgrade(self.url, self.repo, preview_py=True)
        out = api.upgrade(self.url, self.repo, preview_sql=True)

        api.upgrade(self.url, self.repo, 1)
        api.script_sql('default', self.repo)
        self.assertRaises(UsageError, api.upgrade, self.url, self.repo, 2, preview_py=True)
        out = api.upgrade(self.url, self.repo, 2, preview_sql=True)

        # cant upgrade to version 1, already at version 1
        self.assertEqual(api.db_version(self.url, self.repo), 1)
        self.assertRaises(KnownError, api.upgrade, self.url, self.repo, 0)
Exemplo n.º 37
0
def downgrade(options, version, repo_path=None):
    """Downgrade the database's current migration level.

    :param options: options dict
    :param version: version to downgrade to
    :retval version number

    """
    db_version(options, repo_path)  # Ensure db is under migration control
    repo_path = get_migrate_repo_path(repo_path)
    sql_connection = options['database']['connection']
    logger.info("Downgrading %(sql_connection)s to version %(version)s" % {
        'sql_connection': sql_connection,
        'version': version
    })
    return versioning_api.downgrade(sql_connection, repo_path, version)
Exemplo n.º 38
0
def db_sync(version=None):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.Error(_("version should be an integer"))

    current_version = db_version()
    repository = _find_migrate_repo()
    migrate_engine = get_engine()
    if version is None or version > current_version:
        result = versioning_api.upgrade(migrate_engine, repository, version)
    else:
        result = versioning_api.downgrade(migrate_engine, repository, version)
    _ensure_reservations_index(migrate_engine)
    return result
Exemplo n.º 39
0
def db_sync(engine, abs_path, version=None, init_version=0):
    """
    Upgrade or downgrade a database.
    """
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DbMigrationError(
                message=_("version should be an integer"))

    current_version = db_version(engine, abs_path, init_version)
    repository = _find_migrate_repo(abs_path)
    _db_schema_sanity_check(engine)
    if version is None or version > current_version:
        return versioning_api.upgrade(engine, repository, version)
    else:
        return versioning_api.downgrade(engine, repository,
                                        version)
def db_sync(version=None, database='main'):
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.NovaException(_("version should be an integer"))

    current_version = db_version(database)
    repository = _find_migrate_repo(database)

    if _db_sync_locked(repository):
        msg = _("Cannot run 'db sync' until 'db contract' is run")
        raise exception.DatabaseMigrationError(reason=msg)

    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(database), repository,
                version)
    else:
        return versioning_api.downgrade(get_engine(database), repository,
                version)
Exemplo n.º 41
0
def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param engine:       SQLAlchemy engine instance for a given database
    :param abs_path:     Absolute path to migrate repository.
    :param version:      Database will upgrade/downgrade until this version.
                         If None - database will update to the latest
                         available version.
    :param init_version: Initial database version
    :param sanity_check: Require schema sanity checking for all tables
    """

    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DBMigrationError(_("version should be an integer"))

    current_version = db_version(engine, abs_path, init_version)
    repository = _find_migrate_repo(abs_path)
    if sanity_check:
        _db_schema_sanity_check(engine)
    if version is None or version > current_version:
        try:
            migration = versioning_api.upgrade(engine, repository, version)
        except Exception as ex:
            raise exception.DBMigrationError(ex)
    else:
        migration = versioning_api.downgrade(engine, repository,
                                             version)
    if sanity_check:
        _db_schema_sanity_check(engine)

    return migration
Exemplo n.º 42
0
def db_sync(abs_path, version=None, init_version=0):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param abs_path:     Absolute path to migrate repository.
    :param version:      Database will upgrade/downgrade until this version.
                         If None - database will update to the latest
                         available version.
    :param init_version: Initial database version
    """
    if version is not None:
        try:
            version = int(version)
        except ValueError:
            raise exception.DbMigrationError(
                message=_("version should be an integer"))

    current_version = db_version(abs_path, init_version)
    repository = _find_migrate_repo(abs_path)
    if version is None or version > current_version:
        return versioning_api.upgrade(get_engine(), repository, version)
    else:
        return versioning_api.downgrade(get_engine(), repository, version)
Exemplo n.º 43
0
    ./db_downgrade.py -1

To roll back to version 5:
    ./db_downgrade 5
"""
import sys
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI as URI
from config import SQLALCHEMY_MIGRATE_REPO as REPO

if __name__ == '__main__':
    v1 = api.db_version(URI, REPO)

    try:
        target_version = sys.argv[1]

        if target_version.startswith('-'):
            target_version = v1 - 1

    except IndexError:
        target_version = v1 - 1

    print("Attempting to downgrade from %s to %s" %
          (str(v1), str(target_version)))

    api.downgrade(URI, REPO, target_version)

    v2 = api.db_version(URI, REPO)

    print("Downgraded DB from %s to %s" % (str(v1), str(v2)))
Exemplo n.º 44
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/4/8 16:05
# @Author  : Jianfeng Ding
# @Site    :
# @File    : db_downgrade.py
# @Software: PyCharm

from migrate.versioning import api
from config import Config
v = api.db_version(Config.SQLALCHEMY_DATABASE_URI,
                   Config.SQLALCHEMY_MIGRATE_JEFF)
api.downgrade(Config.SQLALCHEMY_DATABASE_URI, Config.SQLALCHEMY_MIGRATE_JEFF,
              v - 1)
v = api.db_version(Config.SQLALCHEMY_DATABASE_URI,
                   Config.SQLALCHEMY_MIGRATE_JEFF)
print('Current database version: ' + str(v))
Exemplo n.º 45
0
#!/usr/bin/env python
# coding: utf-8

#**********************************
# author:   h3idan
# datetime: 2013-07-19 17:12
#**********************************
'''
回滚数据库,每次向前回滚一个版本
'''

import sys
sys.path.append('../')
from migrate.versioning import api
from app.models import app


v = api.db_version(app.config['SQLALCHEMY_DATABASE_URI'],\
        app.config['SQLALCHEMY_MIGRATE_REPO'])

if v == 1:
    print 'Current database version %d , only version 2 can downgrade' % v
else:
    api.downgrade(app.config['SQLALCHEMY_DATABASE_URI'], \
            app.config.get('SQLALCHEMY_MIGRATE_REPO'), v - 1)
    print 'Current database version: ' + str(api.db_version(app.config\
            ['SQLALCHEMY_DATABASE_URI'], app.config['SQLALCHEMY_MIGRATE_REPO']))
Exemplo n.º 46
0
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI as SDU
from config import SQLALCHEMY_MIGRATE_REPO as SMR

v = api.db_version(SDU, SMR)
api.downgrade(SDU, SMR, v - 1)
v = api.db_version(SDU, SMR)
print('Current database version: {}'.format(v))
Exemplo n.º 47
0
#!/usr/bin/env python

from app import app
from migrate.versioning import api

SQLALCHEMY_DATABASE_URI = app.config['SQLALCHEMY_DATABASE_URI']
SQLALCHEMY_MIGRATE_REPO = app.config['SQLALCHEMY_MIGRATE_REPO']

v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('Current database version: ' + str(v))
Exemplo n.º 48
0
#!flask/bin/python
from migrate.versioning import api
import config
v = api.db_version(
    config.SQLALCHEMY_DATABASE_URI,
    config.SQLALCHEMY_MIGRATE_REPO)
api.downgrade(
    config.SQLALCHEMY_DATABASE_URI,
    config.SQLALCHEMY_MIGRATE_REPO,
    v - 1)
print("Current database version: %s" % (api.db_version(
    config.SQLALCHEMY_DATABASE_URI,
    config.SQLALCHEMY_MIGRATE_REPO)))
Exemplo n.º 49
0
def DowngradeDB():
    v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
    api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1)
    print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
Exemplo n.º 50
0
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI as URI
from config import SQLALCHEMY_MIGRATE_REPO as REPO
v=api.db_version(URI,REPO)
api.downgrade(URI,REPO,v-1)
v=api.db_version(URI,REPO)
print('Current database version: '+str(v))
Exemplo n.º 51
0
 def _migrate_down(self, engine, version):
     """Migrate down to an old version of database."""
     migration_api.downgrade(engine, self.REPOSITORY, version)
     assert_equal(version, migration_api.db_version(engine,
                                                    self.REPOSITORY))
Exemplo n.º 52
0
def downgrade_database():
    v = api.db_version(c.SQLALCHEMY_DATABASE_URI, c.SQLALCHEMY_MIGRATE_REPO)
    api.downgrade(c.SQLALCHEMY_DATABASE_URI, c.SQLALCHEMY_MIGRATE_REPO, v - 1)
    print 'Current database version: ' + str(api.db_version(c.SQLALCHEMY_DATABASE_URI, c.SQLALCHEMY_MIGRATE_REPO))
Exemplo n.º 53
0
# -*- coding: utf-8 -*-
# @Author: Dang Kai
# @Email : [email protected]
# @Date:   2019-04-29 09:28:15
# @Last Modified time: 2019-04-29 09:28:15
#回滚数据库
from migrate.versioning import api
from Api_Manager.config.setting import Config, TestingConfig
v = api.db_version(TestingConfig.SQLALCHEMY_DATABASE_URI,
                   Config.SQLALCHEMY_MIGRATE_REPO)
api.downgrade(TestingConfig.SQLALCHEMY_DATABASE_URI,
              Config.SQLALCHEMY_MIGRATE_REPO, v - 1)
print('Current database version: ' + str(
    api.db_version(TestingConfig.SQLALCHEMY_DATABASE_URI,
                   Config.SQLALCHEMY_MIGRATE_REPO)))
Exemplo n.º 54
0
#!flask/bin/python
from migrate.versioning import api
from settings import settings

mrepo = settings.sqlalchemy_migrations_repo
db_url = settings.database.url

v = api.db_version(db_url, mrepo)
api.downgrade(db_url, mrepo, v - 1)
print 'Current database version: ' + str(api.db_version(db_url, mrepo))
Exemplo n.º 55
0
 def _migrate_down(self, engine, version):
     versioning_api.downgrade(engine, repository=self.REPOSITORY,
                              version=version)
Exemplo n.º 56
0
#!/home/gianluca/.virtualenvs/microblog/bin/python3

from migrate.versioning import api

from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO

version = api.db_version(url=SQLALCHEMY_DATABASE_URI,
                         repository=SQLALCHEMY_MIGRATE_REPO)
api.downgrade(url=SQLALCHEMY_DATABASE_URI,
              repository=SQLALCHEMY_MIGRATE_REPO,
              version=version - 1)
version = api.db_version(url=SQLALCHEMY_DATABASE_URI,
                         repository=SQLALCHEMY_MIGRATE_REPO)
print('Current database version: {}'.format(str(version)))
Exemplo n.º 57
0
 def tearDown(self):
     db.downgrade(os.environ['DATABASE_URL'], 'migrations', 0)
Exemplo n.º 58
0
#!/usr/bin/env python2

from migrate.versioning import api
from flask_app import config

v = api.db_version(config['SQLALCHEMY_DATABASE_URI'],
                   config['SQLALCHEMY_MIGRATE_REPO'])
api.downgrade(config['SQLALCHEMY_DATABASE_URI'],
              config['SQLALCHEMY_MIGRATE_REPO'], v - 1)
print 'Current database version: ' + str(
    api.db_version(config['SQLALCHEMY_DATABASE_URI'],
                   config['SQLALCHEMY_MIGRATE_REPO']))
Exemplo n.º 59
0
def downgrade_db():
    v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
    api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1)
    v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
    print('Current database version: ' + str(v))
Exemplo n.º 60
0
#!flask/bin/python
from migrate.versioning import api
from config import Config

v = api.db_version(Config.SQLALCHEMY_DATABASE_URI, Config.SQLALCHEMY_DATABASE_URI)
api.downgrade(Config.SQLALCHEMY_DATABASE_URI,Config.SQLALCHEMY_DATABASE_URI, v - 1)
print ('Current database version: ' + str(api.db_version(Config.SQLALCHEMY_DATABASE_URI, Config.SQLALCHEMY_DATABASE_URI)))