I’m trying to build pex that would run alembic upg...
# general
h
I’m trying to build pex that would run alembic upgrade head command, but its failing with message FAILED: No config file ‘alembic.ini’ found, or file has no ‘[alembic]’ section. This is BUILD file:
Copy code
resource(
    name="alembic_conf",
    source="alembic.ini"
)

python_sources(
    name="migrations",
    sources=[
        "alembic/**/*.py",
    ],
)

pex_binary(
    name="migration_bin",
    script="alembic",
    dependencies=[
        ":alembic_conf",
        ":poetry",
        ":migrations"
    ],
    args=[
    "upgrade",
    "head",
    ]
)
When I unpack pex, I can see alembic.ini in there. Could someont point me what am I doing wrong here ?
1
r
Where does alembic supposed to read the ini file from? Is there an expected path?
h
alembic.ini has to be in the same directory where u run alembic upgrade head command, or you can specify different path using -c “path_to_alembic.ini” This is how pex looks like when you unarchive it
e
The PEX does not run from the zip. It is unpacked 1st; then run. The unpack location != CWD and that is the issue.
It seems like you need one of: + Pex grows a feature to set CWD = unpack location + Pex grows a feature to ~template unpack location in args + You write a shim main to work around by inspecting its own
__file__
location and deriving a good
-c ...
from that info that it uses to re-exec with.
💯 1
b
I also use Alembic, and the way that I get around this is to run a Python script that executes the Alembic upgrade command, and set this script as the PEX entrypoint instead of the
alembic
executable. Here is my script:
Copy code
import os

from alembic.config import Config
from alembic import command


def run_alembic_migrations():
    # Get a string path to the file alembic.ini in the same directory as this file
    alembic_cfg = Config(os.path.join(os.path.dirname(__file__), "alembic.ini"))
    # Override script_location with environment variable if it's set
    alembic_script_location = os.getenv("ALEMBIC_EXECUTABLE_LOCATION")
    if alembic_script_location:
        alembic_cfg.set_main_option("script_location", alembic_script_location)

    command.upgrade(alembic_cfg, "head")
❤️ 3
h
Thank you! I was able to make it work.
b
Great! Glad I could help 😁