I'm attempting to build a pytest fixture that drops my test database, recreates it, and then runs my alembic migrations. When I run it, I get errors that my relationships don't exist, which seems to indicate alembic never ran:
@pytest.fixture(scope="session", autouse=True)
def setup_database():
database_url = f"postgresql+psycopg://{configs.DATABASE_USER}:{configs.DATABASE_PASSWORD}@{configs.DATABASE_HOST}"
engine: Engine = create_engine(database_url)
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
connection.execute(
text(f"DROP DATABASE IF EXISTS {configs.DATABASE_DATABASE}_test")
)
connection.execute(text(f"CREATE DATABASE {configs.DATABASE_DATABASE}_test"))
alembic_cfg = AlembicConfig()
alembic_cfg.attributes["connection"] = connection
alembic_cfg.set_main_option("script_location", "/app/src/alembic")
alembic_cfg.set_main_option(
"sqlalchemy.url", f"{database_url}/{configs.DATABASE_DATABASE}_test"
)
alembic_command.upgrade(alembic_cfg, "head")
yield
connection.execute(text(f"DROP DATABASE {configs.DATABASE_DATABASE}_test"))
So I took the alembic code and moved it to a script, watching the database via a gui.
from alembic import command as alembic_command
from alembic.config import Config as AlembicConfig
from app.configs import configs
def main():
database_url = f"postgresql+psycopg://{configs.DATABASE_USER}:{configs.DATABASE_PASSWORD}@{configs.DATABASE_HOST}/{configs.DATABASE_DATABASE}_test"
alembic_cfg = AlembicConfig("/app/src/alembic.ini")
alembic_cfg.set_main_option("sqlalchemy.url", database_url)
alembic_command.upgrade(alembic_cfg, "head")
main()
And I get an output:
/app/src # python app/test_alembic.py
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
/app/src #
Which seems to indicate alembic ran, but couldn't find any migrations to run. If I don't pass the ini file (using only alembic_cfg.set_main_option("script_location", "/app/src/alembic")
), I get no output. I set up a gist with my alembic.ini and env.py files, which I feel are where the problem is.