Python alembic.command.downgrade() Examples

The following are 30 code examples of alembic.command.downgrade(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module alembic.command , or try the search function .
Example #1
Source File: test_data_migrations.py    From alembic-quickstart with MIT License 6 votes vote down vote up
def test_data_migrations(
    alembic_config, postgres_engine, rev_base: str, rev_head: str,
    on_init: Callable, on_upgrade: Callable, on_downgrade: Callable
):
    # Upgrade to previous migration before target and add some data,
    # that would be changed by tested migration.
    upgrade(alembic_config, rev_base)
    on_init(engine=postgres_engine)

    # Perform upgrade in tested migration.
    # Check that data is migrated correctly in on_upgrade callback
    upgrade(alembic_config, rev_head)
    on_upgrade(engine=postgres_engine)

    # Perform downgrade in tested migration.
    # Check that changes are reverted back using on_downgrade callback
    downgrade(alembic_config, rev_base)
    on_downgrade(engine=postgres_engine) 
Example #2
Source File: test_command.py    From alembic with MIT License 6 votes vote down vote up
def test_err_correctly_raised_on_dupe_rows_no_pk(self):
        self._env_fixture(version_table_pk=False)
        command.revision(self.cfg)
        r2 = command.revision(self.cfg)
        db = _sqlite_file_db()
        command.upgrade(self.cfg, "head")
        with db.connect() as conn:
            conn.execute(
                text("insert into alembic_version values ('%s')" % r2.revision)
            )
        assert_raises_message(
            util.CommandError,
            "Online migration expected to match one row when "
            "updating .* in 'alembic_version'; 2 found",
            command.downgrade,
            self.cfg,
            "-1",
        ) 
Example #3
Source File: test_alembic_verify.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_upgrade_and_downgrade(uri_left, alembic_config_left):
    """Test all migrations up and down.

    Tests that we can apply all migrations from a brand new empty
    database, and also that we can remove them all.
    """
    ah.load_premigration_sql(uri_left)
    engine, script = prepare_schema_from_migrations(
        uri_left, alembic_config_left
    )

    head = get_head_revision(alembic_config_left, engine, script)
    current = get_current_revision(alembic_config_left, engine, script)

    assert head == current

    while current is not None:
        command.downgrade(alembic_config_left, '-1')
        current = get_current_revision(alembic_config_left, engine, script) 
Example #4
Source File: test_postgresql.py    From alembic with MIT License 6 votes vote down vote up
def _inline_enum_script(self):
        write_script(
            self.script,
            self.rid,
            """
revision = '%s'
down_revision = None

from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy import Column


def upgrade():
    op.create_table("sometable",
        Column("data", ENUM("one", "two", "three", name="pgenum"))
    )


def downgrade():
    op.drop_table("sometable")
"""
            % self.rid,
        ) 
Example #5
Source File: test_script_consumption.py    From alembic with MIT License 5 votes vote down vote up
def setUp(self):
        self.env = staging_env()
        self.cfg = cfg = _no_sql_testing_config()
        cfg.set_main_option("dialect_name", "sqlite")
        cfg.remove_main_option("url")
        self.a = util.rev_id()
        script = ScriptDirectory.from_config(cfg)
        script.generate_revision(self.a, "revision a", refresh=True)
        write_script(
            script,
            self.a,
            (
                compat.u(
                    """# coding: utf-8
from __future__ import unicode_literals
revision = '%s'
down_revision = None

from alembic import op

def upgrade():
    op.execute("« S’il vous plaît…")

def downgrade():
    op.execute("drôle de petite voix m’a réveillé")

"""
                )
                % self.a
            ),
            encoding="utf-8",
        ) 
Example #6
Source File: test_offline_environment.py    From alembic with MIT License 5 votes vote down vote up
def test_destination_rev_pre_context_abbreviated(self):
        env_file_fixture(
            """
assert context.get_revision_argument() == '%s'
"""
            % b[0:4]
        )
        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) 
Example #7
Source File: test_offline_environment.py    From alembic with MIT License 5 votes vote down vote up
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) 
Example #8
Source File: test_offline_environment.py    From alembic with MIT License 5 votes vote down vote up
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) 
Example #9
Source File: test_command.py    From alembic with MIT License 5 votes vote down vote up
def test_version_to_none(self):
        with capture_context_buffer() as buf:
            command.downgrade(self.cfg, "%s:base" % self.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() 
Example #10
Source File: test_command.py    From alembic with MIT License 5 votes vote down vote up
def test_help_text(self):
        commands = {
            fn.__name__
            for fn in [getattr(command, n) for n in dir(command)]
            if inspect.isfunction(fn)
            and fn.__name__[0] != "_"
            and fn.__module__ == "alembic.command"
        }
        # make sure we found them
        assert commands.intersection(
            {"upgrade", "downgrade", "merge", "revision"}
        )

        # catch help text coming intersection
        with mock.patch("alembic.config.ArgumentParser") as argparse:
            config.CommandLine()
            for kall in argparse().add_subparsers().mock_calls:
                for sub_kall in kall.call_list():
                    if sub_kall[0] == "add_parser":
                        cmdname = sub_kall[1][0]
                        help_text = sub_kall[2]["help"]
                        if help_text:
                            commands.remove(cmdname)
                            # more than two spaces
                            assert not re.search(r"   ", help_text)

                            # no markup stuff
                            assert ":" not in help_text

                            # no newlines
                            assert "\n" not in help_text

                            # ends with a period
                            assert help_text.endswith(".")

                            # not too long
                            assert len(help_text) < 80
        assert not commands, "Commands without help text: %s" % commands 
Example #11
Source File: test_postgresql.py    From alembic with MIT License 5 votes vote down vote up
def _distinct_enum_script(self):
        write_script(
            self.script,
            self.rid,
            """
revision = '%s'
down_revision = None

from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy import Column


def upgrade():
    enum = ENUM("one", "two", "three", name="pgenum", create_type=False)
    enum.create(op.get_bind(), checkfirst=False)
    op.create_table("sometable",
        Column("data", enum)
    )


def downgrade():
    op.drop_table("sometable")
    ENUM(name="pgenum").drop(op.get_bind(), checkfirst=False)

"""
            % self.rid,
        ) 
Example #12
Source File: test_postgresql.py    From alembic with MIT License 5 votes vote down vote up
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() 
Example #13
Source File: test_postgresql.py    From alembic with MIT License 5 votes vote down vote up
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() 
Example #14
Source File: test_script_consumption.py    From alembic with MIT License 5 votes vote down vote up
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") 
Example #15
Source File: test_offline_environment.py    From alembic with MIT License 5 votes vote down vote up
def test_downgrade_wo_colon(self):
        env_file_fixture(
            """
context.configure(dialect_name='sqlite')
"""
        )
        assert_raises_message(
            util.CommandError,
            "downgrade with --sql requires <fromrev>:<torev>",
            command.downgrade,
            self.cfg,
            b,
            sql=True,
        ) 
Example #16
Source File: test_script_consumption.py    From alembic with MIT License 5 votes vote down vote up
def test_option(self):
        self.cfg.set_main_option("file_template", "myfile_%%(slug)s")
        script = ScriptDirectory.from_config(self.cfg)
        a = util.rev_id()
        script.generate_revision(a, "some message", refresh=True)
        write_script(
            script,
            a,
            """
    revision = '%s'
    down_revision = None

    from alembic import op


    def upgrade():
        op.execute("CREATE TABLE foo(id integer)")


    def downgrade():
        op.execute("DROP TABLE foo")

    """
            % a,
        )

        script = ScriptDirectory.from_config(self.cfg)
        rev = script.get_revision(a)
        eq_(rev.revision, a)
        eq_(os.path.basename(rev.path), "myfile_some_message.py") 
Example #17
Source File: test_script_consumption.py    From alembic with MIT License 5 votes vote down vote up
def test_lookup_legacy(self):
        self.cfg.set_main_option("file_template", "%%(rev)s")
        script = ScriptDirectory.from_config(self.cfg)
        a = util.rev_id()
        script.generate_revision(a, None, refresh=True)
        write_script(
            script,
            a,
            """
    down_revision = None

    from alembic import op


    def upgrade():
        op.execute("CREATE TABLE foo(id integer)")


    def downgrade():
        op.execute("DROP TABLE foo")

    """,
        )

        script = ScriptDirectory.from_config(self.cfg)
        rev = script.get_revision(a)
        eq_(rev.revision, a)
        eq_(os.path.basename(rev.path), "%s.py" % a) 
Example #18
Source File: test_script_consumption.py    From alembic with MIT License 5 votes vote down vote up
def test_error_on_new_with_missing_revision(self):
        self.cfg.set_main_option("file_template", "%%(slug)s_%%(rev)s")
        script = ScriptDirectory.from_config(self.cfg)
        a = util.rev_id()
        script.generate_revision(a, "foobar", refresh=True)

        path = script.get_revision(a).path
        with open(path, "w") as fp:
            fp.write(
                """
down_revision = None

from alembic import op


def upgrade():
    op.execute("CREATE TABLE foo(id integer)")


def downgrade():
    op.execute("DROP TABLE foo")

"""
            )
        pyc_path = util.pyc_file_from_path(path)
        if pyc_path is not None and os.access(pyc_path, os.F_OK):
            os.unlink(pyc_path)

        assert_raises_message(
            util.CommandError,
            "Could not determine revision id from filename foobar_%s.py. "
            "Be sure the 'revision' variable is declared "
            "inside the script." % a,
            Script._from_path,
            script,
            path,
        ) 
Example #19
Source File: migrations.py    From lux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def downgrade(self, revision):
        alembic_cmd.downgrade(self.cfg, revision) 
Example #20
Source File: app.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def db_downgrade(self, revision):
        with self.app_context():
            command.downgrade(self._alembic_config, revision)
        return self 
Example #21
Source File: test_stairway.py    From alembic-quickstart with MIT License 5 votes vote down vote up
def test_migrations_stairway(alembic_config: Config, revision: Script):
    upgrade(alembic_config, revision.revision)

    # We need -1 for downgrading first migration (its down_revision is None)
    downgrade(alembic_config, revision.down_revision or '-1')
    upgrade(alembic_config, revision.revision) 
Example #22
Source File: alembic_wrapper.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def make_parser(self, subparsers):
        parser = subparsers.add_parser('downgrade', help=self.downgrade.__doc__)
        parser.add_argument('--tag', dest='tag', default=None,
                            help=("Arbitrary 'tag' name - can be used by custom "
                                  "env.py scripts"))
        parser.add_argument('--sql', dest='sql', action='store_true', default=False,
                            help=("Don't emit SQL to database - dump to standard "
                                  "output instead"))
        parser.add_argument('revision', nargs='?', default="-1",
                            help="revision identifier")
        parser.add_argument('-d', '--directory', dest='directory', default=None,
                            help=("migration script directory (default is "
                                  "'migrations')"))
        return parser 
Example #23
Source File: alembic_wrapper.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def run(self, parser, args):
        self.downgrade(**vars(args)) 
Example #24
Source File: alembic_wrapper.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
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) 
Example #25
Source File: test_offline_environment.py    From alembic with MIT License 5 votes vote down vote up
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) 
Example #26
Source File: sql.py    From ether_sql with Apache License 2.0 5 votes vote down vote up
def drop_tables(ctx):
    """ Alias for 'alembic downgrade base'.
    Downgrade to no database tables
    """
    current_session = get_current_session()
    command.downgrade(setup_alembic_config(url=current_session.url),
                      revision='base', sql=False, tag=None) 
Example #27
Source File: cli.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def downgrade(config, revision: str, sql: bool, tag: str):
    """Revert to a previous version."""

    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.downgrade(c, revision, sql=sql, tag=tag) 
Example #28
Source File: test_migrations.py    From a10-neutron-lbaas with Apache License 2.0 5 votes vote down vote up
def downgrade(self, revision):
        alembic_command.downgrade(self.config(), revision) 
Example #29
Source File: test_migrations.py    From a10-neutron-lbaas with Apache License 2.0 5 votes vote down vote up
def test_upgrade_heads_downgrade_base(self):
        self.upgrade('heads')
        self.downgrade('base') 
Example #30
Source File: test_migrations.py    From a10-neutron-lbaas with Apache License 2.0 5 votes vote down vote up
def test_upgrade_heads_downgrade_base_upgrade_heads(self):
        self.upgrade('heads')
        self.downgrade('base')
        self.upgrade('heads')