Esempio n. 1
0
    def test_starting_rev_context_runs_abbreviated(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
context.run_migrations()
""")
        command.upgrade(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b[0:4], a), sql=True)
Esempio n. 2
0
    def test_starting_rev_pre_context_abbreviated(self):
        env_file_fixture("""
assert context.get_starting_revision_argument() == '%s'
""" % b[0:4])
        command.upgrade(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.stamp(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b[0:4], a), sql=True)
Esempio n. 3
0
 def test_offline_inline_enum_drop(self):
     self._inline_enum_script()
     with capture_context_buffer() as buf:
         command.downgrade(self.cfg, "%s:base" % self.rid, sql=True)
     assert "DROP TABLE sometable" in buf.getvalue()
     # no drop since we didn't emit events
     assert "DROP TYPE pgenum" not in buf.getvalue()
Esempio n. 4
0
    def downgrade(self, revisions=None):
        revisions = revisions or ['head']
        if len(revisions) != 1:
            msg = ('Only supply a single revision for downgrade')
            raise AlembicCommandError(msg)

        command.downgrade(self.config, revisions[0], sql=self.offline)
Esempio n. 5
0
def setupPackage():
    os.environ['MONGO_URI'] = 'mongodb://localhost'
    os.environ['MONGO_DB_NAME'] = 'royal_example'
    os.environ['MONGO_DB_PREFIX'] = ''

    # sqla extentsion setup.
    global engine

    alembic_config = Config()
    alembic_config.set_main_option('script_location',
                                   'example/ext/sqla/db')
    alembic_config.set_main_option('sqlalchemy.url', mysql_uri)

    engine = create_engine(mysql_uri)

    try:
        command.downgrade(alembic_config, 'base')
    except:
        log.exception("Migration downgrade failed, clearing all tables")
        metadata = MetaData(engine)
        metadata.reflect()
        for table in metadata.tables.values():
            for fk in table.foreign_keys:
                engine.execute(DropConstraint(fk.constraint))
        metadata.drop_all()

    command.upgrade(alembic_config, 'head')
Esempio n. 6
0
def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None):
    """Revert to a previous version"""
    config = current_app.extensions['migrate'].migrate.get_config(directory,
                                                                  x_arg=x_arg)
    if sql and revision == '-1':
        revision = 'head:-1'
    command.downgrade(config, revision, sql=sql, tag=tag)
    def test_tag_cfg_arg(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', tag='there')
assert context.get_tag_argument() == 'there'
""")
        command.upgrade(self.cfg, b, sql=True, tag='hi')
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag='hi')
    def test_destination_rev_pre_context(self):
        env_file_fixture("""
assert context.get_revision_argument() == '%s'
""" % b)
        command.upgrade(self.cfg, b, sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b), sql=True)
Esempio n. 9
0
    def downgrade(self, rev):
        try:
            command.downgrade(self._config, rev)

        except sqlalchemy.exc.OperationalError, err:
            _log('DBUpdater: failed to downgrade release: {0}'.format(err), logLevel=logging.ERROR)
            raise err
Esempio n. 10
0
    def downgrade(self, rev):
        try:
            command.downgrade(self._config, rev)

        except sqlalchemy.exc.OperationalError, err:
            current_app.logger.error('DBUpdater: failed to downgrade release: {0}'.format(err))
            raise err
Esempio n. 11
0
 def downgrade(self, directory=None, revision='-1', sql=False, tag=None,
               **kwargs):  # pragma: no cover
     """Revert to a previous version"""
     config = _get_config(directory)
     if sql and revision == '-1':
         revision = 'head:-1'
     command.downgrade(config, revision, sql=sql, tag=tag)
    def test_tag_None(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_tag_argument() is None
""")
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_upgrade_with_output_encoding(self):
        env_file_fixture("""
url = config.get_main_option('sqlalchemy.url')
context.configure(url=url, output_encoding='utf-8')
assert not context.requires_connection()
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_destination_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_revision_argument() == '%s'
""" % b)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b), sql=True)
        command.stamp(self.cfg, b, sql=True)
    def test_head_rev_pre_context(self):
        env_file_fixture("""
assert context.get_head_revision() == '%s'
""" % c)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
Esempio n. 16
0
 def downgrade(context, directory='migrations', revision='-1', sql=False, tag=None, x_arg=None):
     """Revert to a previous version"""
     from app import create_app
     with create_app().app_context():
         config = _get_config(directory, x_arg=x_arg)
         if sql and revision == '-1':
             revision = 'head:-1'
         command.downgrade(config, revision, sql=sql, tag=tag)
Esempio n. 17
0
    def test_tag_pre_context(self):
        env_file_fixture(
            """
assert context.get_tag_argument() == 'hi'
"""
        )
        command.upgrade(self.cfg, b, sql=True, tag="hi")
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag="hi")
Esempio n. 18
0
    def test_destination_rev_context_runs_abbreviated(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
context.run_migrations()
""")
        command.upgrade(self.cfg, "%s:%s" % (a, b[0:4]), sql=True)
        command.stamp(self.cfg, b[0:4], sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b[0:4]), sql=True)
Esempio n. 19
0
    def test_tag_pre_context_None(self):
        env_file_fixture(
            """
assert context.get_tag_argument() is None
"""
        )
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
Esempio n. 20
0
    def test_not_requires_connection(self):
        env_file_fixture(
            """
assert not context.requires_connection()
"""
        )
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
Esempio n. 21
0
    def test_requires_connection(self):
        env_file_fixture(
            """
assert context.requires_connection()
"""
        )
        command.upgrade(self.cfg, a)
        command.downgrade(self.cfg, a)
Esempio n. 22
0
    def test_starting_rev_pre_context(self):
        env_file_fixture(
            """
assert context.get_starting_revision_argument() == 'x'
"""
        )
        command.upgrade(self.cfg, "x:y", sql=True)
        command.downgrade(self.cfg, "x:y", sql=True)
Esempio n. 23
0
    def test_use_integer_column_for_amount(self):
        from sqlalchemy import Column
        from sqlalchemy import Integer
        from sqlalchemy import Numeric

        class Plan(self.declarative_base):
            __tablename__ = 'plan'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        class Subscription(self.declarative_base):
            __tablename__ = 'subscription'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        class Transaction(self.declarative_base):
            __tablename__ = 'transaction'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        self.declarative_base.metadata.create_all()

        with db_transaction.manager:
            for amount in ['12.34', '55.66', '10']:
                amount = decimal.Decimal(amount)
                plan = Plan(amount=amount)
                subscription = Subscription(amount=amount)
                transaction = Transaction(amount=amount)
                self.session.add(plan)
                self.session.add(subscription)
                self.session.add(transaction)

        from alembic import command
        command.stamp(self.alembic_cfg, 'base')

        command.upgrade(self.alembic_cfg, 'b3d4192b123')
        # Notice: this with statement here makes sure the database transaction
        # will be closed after querying, otherwise, we have two connections
        # to postgresql (one by testing code, one by Alembic), when we are
        # doing following downgrade, there is table alter, it appears
        # there will be a deadlock when there is a overlap of two transaction
        # scope
        with db_transaction.manager:
            for table in [Plan, Subscription, Transaction]:
                amounts = self.session.query(table.amount).all()
                amounts = map(lambda item: float(item[0]), amounts)
                # make sure all float dollars are converted into integer cents
                self.assertEqual(set(amounts), set([1234, 5566, 1000]))

        command.downgrade(self.alembic_cfg, 'base')
        with db_transaction.manager:
            for table in [Plan, Subscription, Transaction]:
                amounts = self.session.query(table.amount).all()
                amounts = map(lambda item: item[0], amounts)
                self.assertEqual(
                    set(amounts), 
                    set(map(decimal.Decimal, ['12.34', '55.66', '10']))
                )
Esempio n. 24
0
def test_version_to_none():
    with capture_context_buffer() as buf:
        command.downgrade(cfg, "%s:base" % c, sql=True)
    assert "CREATE TABLE alembic_version" not in buf.getvalue()
    assert "INSERT INTO alembic_version" not in buf.getvalue()
    assert "DROP TABLE alembic_version" in buf.getvalue()
    assert "DROP STEP 3" in buf.getvalue()
    assert "DROP STEP 2" in buf.getvalue()
    assert "DROP STEP 1" in buf.getvalue()
    def test_starting_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', starting_rev='x')
assert context.get_starting_revision_argument() == 'x'
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.current(self.cfg)
        command.stamp(self.cfg, a)
    def test_head_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_head_revision() == '%s'
""" % c)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
Esempio n. 27
0
 def test_version_to_middle(self):
     with capture_context_buffer() as buf:
         command.downgrade(self.cfg, "%s:%s" % (self.c, self.a), sql=True)
     assert "CREATE TABLE alembic_version" not in buf.getvalue()
     assert "INSERT INTO alembic_version" not in buf.getvalue()
     assert "DROP TABLE alembic_version" not in buf.getvalue()
     assert "DROP STEP 3" in buf.getvalue()
     assert "DROP STEP 2" in buf.getvalue()
     assert "DROP STEP 1" not in buf.getvalue()
Esempio n. 28
0
def migration_downgrade(commit):
    """Migrate database structure"""
    from alembic.config import Config
    from alembic.command import downgrade

    config = Config(os.path.normpath(os.path.abspath(__file__) + "/../alembic.ini"))
    config.set_main_option("script_location", "alembic")

    downgrade(config, commit)
Esempio n. 29
0
    def actionDowngradeDB(self, version=None):
        from alembic.config import Config
        from alembic import command

        if not version:
            self.parser.error("Downgrade DB requires version for migration")
        alembic_cfg = Config()
        alembic_cfg.set_main_option("script_location", "alembic")
        alembic_cfg.set_main_option("url", config.DB_URL)
        command.downgrade(alembic_cfg, version)
Esempio n. 30
0
def command_database(action=None):
    config_path = os.path.join(root_path, "alembic.ini")

    if not os.path.exists(config_path):
        config_path = "/usr/share/opmuse/alembic.ini"

    alembic_config = Config(config_path)

    database_type = get_database_type()

    if action == "create":
        if database_type == "mysql":
            try:
                engine = get_engine(no_database=True)
                engine.execute("CREATE DATABASE IF NOT EXISTS %s" % get_database_name())
            except ProgrammingError as e:
                parser.error('Error occured while creating database: %s' % e)

        engine = get_engine()
        Base.metadata.create_all(engine)
        command.stamp(alembic_config, "head")
    # TODO rename to upgrade
    elif action == "update":
        try:
            command.upgrade(alembic_config, "head")
        except ProgrammingError as e:
            parser.error('Error occured while updating database: %s' % e)
    elif action == "downgrade":
        try:
            command.downgrade(alembic_config, "-1")
        except ProgrammingError as e:
            parser.error('Error occured while downgrading database: %s' % e)
    elif action == "drop":
        if database_type == "sqlite":
            parser.error('Dropping is unsupported for sqlite.')

        engine = get_engine(no_database=True)
        engine.execute("DROP DATABASE IF EXISTS %s" % get_database_name())
        command_whoosh("drop")
    elif action == "fixtures":
        from opmuse.test.fixtures import run_fixtures
        run_fixtures()
    elif action == "reset":
        engine = get_engine()
        engine.execute(Queue.__table__.delete())
        engine.execute(TrackPath.__table__.delete())
        engine.execute(Track.__table__.delete())
        engine.execute(ListenedTrack.__table__.delete())
        engine.execute(UserAndAlbum.__table__.delete())
        engine.execute(Album.__table__.delete())
        engine.execute(Artist.__table__.delete())
        engine.execute(CacheObject.__table__.delete())
        command_whoosh("drop")
    else:
        parser.error('Needs to provide a valid action (create, update, downgrade, drop, fixtures, reset).')
Esempio n. 31
0
 def test_offline_distinct_enum_drop(self):
     self._distinct_enum_script()
     with capture_context_buffer() as buf:
         command.downgrade(self.cfg, "%s:base" % self.rid, sql=True)
     assert "DROP TABLE sometable" in buf.getvalue()
     assert "DROP TYPE pgenum" in buf.getvalue()
Esempio n. 32
0
 def test_downgrade(self):
     alembic_command.upgrade(self.config, '45a07fac3d38')
     with self.assertRaises(NotImplementedError):
         alembic_command.downgrade(self.config, '2748e48cee3a')
Esempio n. 33
0
 def test_downgrade(self):
     alembic_command.upgrade(self.config, '552b213c2b8c')
     with self.assertRaises(NotImplementedError):
         alembic_command.downgrade(self.config, '45a07fac3d38')
Esempio n. 34
0
def test_downgrade():
    downgrade(config, 'base')
def downgrade_database(engine: Engine, revision: str):
    config = get_alembic_config(engine)
    downgrade(config, revision)
Esempio n. 36
0
 def test_004_downgrade(self):
     command.downgrade(self.cfg, 'base')
     db = sqlite_db()
     assert not db.dialect.has_table(db.connect(), 'foo')
     assert not db.dialect.has_table(db.connect(), 'bar')
     assert not db.dialect.has_table(db.connect(), 'bat')
Esempio n. 37
0
 def _test_004_downgrade(self):
     command.downgrade(self.cfg, "base")
     db = self.bind
     assert not db.dialect.has_table(db.connect(), "foo")
     assert not db.dialect.has_table(db.connect(), "bar")
     assert not db.dialect.has_table(db.connect(), "bat")
Esempio n. 38
0
File: sql.py Progetto: sd2k/dagster
def run_alembic_downgrade(alembic_config, conn, rev, run_id=None):
    alembic_config.attributes["connection"] = conn
    alembic_config.attributes["run_id"] = run_id
    downgrade(alembic_config, rev)
Esempio n. 39
0
 def db_downgrade(self, revision):
     with self.app_context():
         command.downgrade(self._alembic_config, revision)
Esempio n. 40
0
def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None):
    """Revert to a previous version"""
    config = _get_config(directory, x_arg=x_arg)
    if sql and revision == '-1':
        revision = 'head:-1'
    command.downgrade(config, revision, sql=sql, tag=tag)
Esempio n. 41
0
def teardown():
    alc.downgrade(AlembicConfig('alembic.ini'), 'base')
Esempio n. 42
0
def cli(ctx):
    """
    Run setup after a fresh Vagrant installation.
    """
    log = logging.getLogger('ipsv.setup')
    assert isinstance(ctx, Context)

    lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck')
    if os.path.exists(lock_path):
        raise Exception('Setup is locked, please remove the setup lock file to continue')

    # Create our package directories
    p = Echo('Creating IPS Vagrant system directories...')
    dirs = ['/etc/ipsv', ctx.config.get('Paths', 'Data'), ctx.config.get('Paths', 'Log'),
            ctx.config.get('Paths', 'NginxSitesAvailable'), ctx.config.get('Paths', 'NginxSitesEnabled'),
            ctx.config.get('Paths', 'NginxSSL')]
    for d in dirs:
        if not os.path.exists(d):
            os.makedirs(d, 0o755)
    p.done()

    p = Echo('Copying IPS Vagrant configuration files...')
    with open('/etc/ipsv/ipsv.conf', 'w+') as f:
        ctx.config.write(f)
    p.done()

    # Set up alembic
    alembic_cfg = Config(os.path.join(ctx.basedir, 'alembic.ini'))
    alembic_cfg.set_main_option("script_location", os.path.join(ctx.basedir, 'migrations'))
    alembic_cfg.set_main_option("sqlalchemy.url", "sqlite:////{path}"
                                .format(path=os.path.join(ctx.config.get('Paths', 'Data'), 'sites.db')))

    command.current(alembic_cfg)
    command.downgrade(alembic_cfg, 'base')
    command.upgrade(alembic_cfg, 'head')

    # Update the system
    p = Echo('Updating package cache...')
    cache = apt.Cache()
    cache.update()
    cache.open(None)
    p.done()
    p = Echo('Upgrading system packages...')
    cache.upgrade()
    cache.commit()
    p.done()

    # Install our required packages
    requirements = ['nginx', 'php5-fpm', 'php5-curl', 'php5-gd', 'php5-imagick', 'php5-json', 'php5-mysql',
                    'php5-readline', 'php5-apcu', 'php5-xdebug']

    for requirement in requirements:
        # Make sure the package is available
        p = Echo('Marking package {pkg} for installation'.format(pkg=requirement))
        if requirement not in cache:
            log.warn('Required package {pkg} not available'.format(pkg=requirement))
            p.done(p.FAIL)
            continue

        # Mark the package for installation
        cache[requirement].mark_install()
        p.done()

    log.info('Committing package cache')
    p = Echo('Downloading and installing packages...')
    cache.commit()
    p.done()

    # Disable the default server block
    p = Echo('Configuring Nginx...')
    default_available = os.path.join(ctx.config.get('Paths', 'NginxSitesAvailable'), 'default')
    default_enabled = os.path.join(ctx.config.get('Paths', 'NginxSitesEnabled'), 'default')
    if os.path.isfile(default_available):
        os.remove(default_available)
    if os.path.islink(default_enabled):
        os.unlink(default_enabled)
    p.done()

    # Restart Nginx
    FNULL = open(os.devnull, 'w')
    p = Echo('Restarting Nginx...')
    subprocess.check_call(['service', 'nginx', 'restart'], stdout=FNULL, stderr=subprocess.STDOUT)
    p.done()

    # php.ini configuration
    p = Echo('Configuring php...')
    with open('/etc/php5/fpm/php.ini', 'a') as f:
        f.write('\n[XDebug]')
        f.write('\nxdebug.cli_color=1')

    temp_fh, temp_path = mkstemp()
    with open(temp_path, 'w') as nf:
        with open('/etc/php5/fpm/php.ini') as of:
            # Configuration options we are replacing
            upload_max_filesize = re.compile( '^upload_max_filesize\s+=\s+(\d+[a-zA-Z])\s*$' )
            post_max_size = re.compile( '^post_max_size\s+=\s+(\d+[a-zA-Z])\s*$' )

            for line in of:
                match = upload_max_filesize.match( line ) if upload_max_filesize is not True else False
                if match:
                    nf.write( 'upload_max_filesize = 1000M\n' )
                    upload_max_filesize = True
                    continue

                match = post_max_size.match( line ) if post_max_size is not True else False
                if match:
                    nf.write( 'post_max_size = 1000M\n' )
                    post_max_size = True
                    continue

                nf.write(line)
    os.close(temp_fh)
    os.remove('/etc/php5/fpm/php.ini')
    shutil.move(temp_path, '/etc/php5/fpm/php.ini')
    os.chmod('/etc/php5/fpm/php.ini', 0o644)
    p.done()

    # php5-fpm configuration
    p = Echo('Configuring php5-fpm...')
    if os.path.isfile('/etc/php5/fpm/pool.d/www.conf'):
        os.remove('/etc/php5/fpm/pool.d/www.conf')

    fpm_config = FpmPoolConfig().template
    with open('/etc/php5/fpm/pool.d/ips.conf', 'w') as f:
        f.write(fpm_config)
    p.done()

    # Restart php5-fpm
    p = Echo('Restarting php5-fpm...')
    subprocess.check_call(['service', 'php5-fpm', 'restart'], stdout=FNULL, stderr=subprocess.STDOUT)
    p.done()

    # Copy the man pages and rebuild the manual database
    p = Echo('Writing manual pages...')
    man_path = os.path.join(ctx.basedir, 'man', 'ipsv.1')
    sys_man_path = '/usr/local/share/man/man1'
    if not os.path.exists(sys_man_path):
        os.makedirs(sys_man_path)

    shutil.copyfile(man_path, os.path.join(sys_man_path, 'ipsv.1'))

    subprocess.check_call(['mandb'], stdout=FNULL, stderr=subprocess.STDOUT)

    # Enable the welcome message
    log.debug('Writing welcome message')
    wm_header = '## DO NOT REMOVE :: AUTOMATICALLY GENERATED BY IPSV ##'
    wm_remove = False

    # Remove old profile data
    for line in fileinput.input('/etc/profile', inplace=True):
        # Header / footer match?
        if line == wm_header:
            # Footer match (Stop removing)
            if wm_remove:
                wm_remove = False
                continue

            # Header match (Start removing)
            wm_remove = True
            continue

        # Removing lines?
        if wm_remove:
            continue

        # Print line and continue as normal
        sys.stdout.write(line)

    # Write new profile data
    with open('/etc/profile', 'a') as f:
        f.write("\n" + wm_header + "\n")
        fl_lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'first_login.lck')
        f.write('if [ ! -f "{lp}" ]; then'.format(lp=fl_lock_path) + "\n")
        f.write('  less "{wp}"'.format(wp=os.path.join(ctx.basedir, 'WELCOME.rst')) + "\n")
        f.write('  sudo touch "{lp}"'.format(lp=fl_lock_path) + "\n")
        f.write('fi' + "\n")
        f.write(wm_header + "\n")
    p.done()

    log.debug('Writing setup lock file')
    with open(os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck'), 'w') as f:
        f.write('1')
Esempio n. 43
0
def del_table_users_and_return_after_test():
    command.downgrade(alembic_cfg, 'base')
    yield None
    command.upgrade(alembic_cfg, 'head')
Esempio n. 44
0
def down_version(target='head', sql_mode=False):
    CABIN.info('Downgrade migration!')
    return downgrade(ini_configuration(os.getcwd()), target, sql=sql_mode)
Esempio n. 45
0
    def test_migrations_forward_backward(self):
        """
        This is a very broad test that checks that the migration mechanism
        works. More specifically, it checks that::

            - Alembic database migrations to specific versions work (upgrade &
              downgrade)

            - The methods that are checking the database schema version and perform
              the migration procedure to the last version work correctly.

        """
        from aiida.backends.sqlalchemy.tests.migration_test import versions
        from aiida.backends.sqlalchemy.utils import check_schema_version

        try:
            # Constructing the versions directory
            versions_dpath = os.path.join(
                os.path.dirname(versions.__file__))

            # Setting dynamically the the path to the alembic configuration
            # (this is where the env.py file can be found)
            alembic_cfg = Config()
            alembic_cfg.set_main_option('script_location', self.alembic_dpath)
            # Setting dynamically the versions directory. These are the
            # migration scripts to pass from one version to the other. The
            # default ones are overridden with test-specific migrations.
            alembic_cfg.set_main_option('version_locations', versions_dpath)

            # Using the connection initialized by the tests
            with sa.engine.begin() as connection:
                alembic_cfg.attributes['connection'] = connection

                self.assertIsNone(get_db_schema_version(alembic_cfg),
                                  "The initial database version should be "
                                  "None (no version) since the test setUp "
                                  "method should undo all migrations")
            # Migrate the database to the latest version
            check_schema_version(force_migration=True, alembic_cfg=alembic_cfg)
            with sa.engine.begin() as connection:
                alembic_cfg.attributes['connection'] = connection
                self.assertEquals(get_db_schema_version(alembic_cfg),
                                  get_migration_head(alembic_cfg),
                                  "The latest database version is not the "
                                  "expected one.")
            with sa.engine.begin() as connection:
                alembic_cfg.attributes['connection'] = connection
                # Migrating the database to the base version
                command.downgrade(alembic_cfg, "base")
                self.assertIsNone(get_db_schema_version(alembic_cfg),
                                  "The database version is not the expected "
                                  "one. It should be None (initial).")

        except Exception as test_ex:
            # If there is an exception, clean the alembic related tables
            from sqlalchemy.engine import reflection

            # Getting the current database table names
            inspector = reflection.Inspector.from_engine(
                sa.get_scoped_session().bind)
            db_table_names = set(inspector.get_table_names())
            # The alembic related database names
            alemb_table_names = set(['account', 'alembic_version'])

            # Get the intersection of the above tables
            tables_to_drop = set.intersection(db_table_names,
                                              alemb_table_names)
            # Delete only the tables that exist
            for table in tables_to_drop:
                from psycopg2 import ProgrammingError
                from sqlalchemy.orm import sessionmaker, scoped_session
                try:
                    with sa.engine.begin() as connection:
                        connection.execute('DROP TABLE {};'.format(table))
                except Exception as db_ex:
                    print("The following error occured during the cleaning of"
                          "the database: {}".format(db_ex.message))
            # Since the database cleaning is over, raise the test
            # exception that was caught
            raise test_ex
Esempio n. 46
0
def handle_db_downgrade_command(args):
    cfg = get_alembic_config(args)
    command.downgrade(cfg, "-1")
    handle_db_fixsequence_command(args)
    def test_tag_pre_context(self):
        env_file_fixture("""
assert context.get_tag_argument() == 'hi'
""")
        command.upgrade(self.cfg, b, sql=True, tag='hi')
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag='hi')
 def _reverse_migration(self, rev, alembic_conf):
     """Reverse the migration specified by rev"""
     downgrade(alembic_conf, rev)
Esempio n. 49
0
def downgrade(directory=None, revision='-1', sql=False, tag=None):
    """Revert to a previous version"""
    config = _get_config(directory)
    command.downgrade(config, revision, sql=sql, tag=tag)
Esempio n. 50
0
def test_migrations_stairway(alembic_config: Config, revision: Script):
    upgrade(alembic_config, revision.revision)
    downgrade(alembic_config, revision.down_revision or "-1")
    upgrade(alembic_config, revision.revision)
    def test_tag_pre_context_None(self):
        env_file_fixture("""
assert context.get_tag_argument() is None
""")
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
Esempio n. 52
0
def db_downgrade(context, revision):
    command.downgrade(context.obj['alembic'], revision)
 def _test_003_downgrade(self):
     command.downgrade(self.cfg, self.a)
     db = self.bind
     assert db.dialect.has_table(db.connect(), 'foo')
     assert not db.dialect.has_table(db.connect(), 'bar')
     assert not db.dialect.has_table(db.connect(), 'bat')
    def test_not_requires_connection(self):
        env_file_fixture("""
assert not context.requires_connection()
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_requires_connection(self):
        env_file_fixture("""
assert context.requires_connection()
""")
        command.upgrade(self.cfg, a)
        command.downgrade(self.cfg, a)
    def test_starting_rev_pre_context(self):
        env_file_fixture("""
assert context.get_starting_revision_argument() == 'x'
""")
        command.upgrade(self.cfg, "x:y", sql=True)
        command.downgrade(self.cfg, "x:y", sql=True)
Esempio n. 57
0
 def teardown():
     print('Downgrading alembic migrations...\n')
     command.downgrade(alembic_config, 'base')
Esempio n. 58
0
 def test_downgrade(self):
     alembic_command.upgrade(self.config, '2748e48cee3a')
     with self.assertRaises(NotImplementedError):
         alembic_command.downgrade(self.config, '1284c81cf727')
Esempio n. 59
0
 def tearDown(self):
     command.downgrade(get_alembic_config(), 'base')
     return super().tearDown()
Esempio n. 60
0
def migrate(direction):
    """Migrate db revision"""
    if direction == "up":
        command.upgrade(alembic_config, "head")
    elif direction == "down":
        command.downgrade(alembic_config, "-1")