Skip to content

Instantly share code, notes, and snippets.

@wasdee
Forked from utek/Exclude_tables.md
Last active November 21, 2020 07:36
Show Gist options
  • Save wasdee/52413943c489759422300a3b7d59f444 to your computer and use it in GitHub Desktop.
Save wasdee/52413943c489759422300a3b7d59f444 to your computer and use it in GitHub Desktop.
Define ignored tables in alembic.ini

Add this in your ini file:

[alembic]
exclude_tables =
  spatial_ref_sys,
  foo, bar

In env.py:

def get_list_from_config(config, key):
arr = config.get_main_option(key, None)
if arr is not None:
    # split on newlines and commas, then trim (I mean strip)
    arr = [token for a in arr.split('\n') for b in a.split(',') if (token := b.strip())]
return arr

exclude_tables = get_list_from_config(config, "exclude_tables")

def include_object(obj, name, type_, reflected, compare_to):
    if type_ == "table" and name in exclude_tables:
        return False
    else:
        return True

def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    # url = config.get_main_option("sqlalchemy.url")
    context.configure(url=engine.url, include_object=include_object)

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    if isinstance(engine, Engine):
        connection = engine.connect()
    else:
        raise Exception('Expected engine instance got %s instead' % type(engine))

    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        include_object=include_object
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment