specx SQLAlchemy Migrations
Use this skill whenever a specx project has SQLAlchemy models or persistence
adapters. Read references/alembic.md before editing migration files.
Workflow
- Add
alembic>=1.18.5as a runtime dependency when SQLAlchemy adapters exist, together with SQLAlchemy's asyncio extra and the selected driver. - Add
alembic.ini,migrations/env.py,migrations/script.py.mako, andmigrations/versions/. - Use Alembic's async pattern for async SQLAlchemy engines.
- Put app-wide SQLAlchemy settings/session factory under top-level
infrastructure/sqlalchemy/. - Keep scope-owned ORM models and repositories under
core/<scope>/infrastructure/sqlalchemy/. - Add a project-local SQLAlchemy declarative base under
src/<package>/foundation/sqlalchemy_model.py; do not use shared packaged metadata for generated services. - Put reusable model discovery under top-level
infrastructure/sqlalchemy/model_discovery.py. Use that same function frommigrations/env.pyand its guardrail test before assigningtarget_metadata; do not duplicate discovery or maintain hard-coded model module names. - Set
target_metadatato the project-localBaseSQLAlchemyModel.metadata. - Generate or hand-review an initial migration for current models.
- Add
make migrateandmake makemigrations. - Add tests that run
alembic upgrade headagainst an isolated database, check for pending autogenerate changes, and prove every core SQLAlchemy model file is included by the exact discovery function Alembic uses. Use the production database family when dialect behavior matters.
Guardrails
- Do not call
Base.metadata.create_all,metadata.create_all, ordrop_allfromsrc/. - Do not run migrations from FastAPI startup by default. Run migrations as an operational command before app startup.
- Do not put app-wide engine/session factory code inside one core scope.
- Do not let delivery controllers import ORM models, repositories, sessions, or migration helpers.
- Do not let Alembic drift checks depend on incomplete metadata. Model discovery
must include every
core/*/infrastructure/sqlalchemy/models/*.pyfile. - Do not trust autogenerated migrations without review.
- Do not edit, delete, or reorder a revision that may already have been applied; add a new corrective revision.
- Do not pass SQLite's
autocommitconnect argument on Python 3.11. For a savepoint-based SQLite test harness spanning Python versions, use SQLAlchemy'sconnectandbeginevent-hook recipe.
Code Style
Use blank lines as logical separators in all code. Keep related statements together, but separate independent setup, action, assertion, response, branch, and transformation groups so long blocks stay readable.
References
references/alembic.md- async Alembic layout, env.py, Makefile targets, initial migration, and migration tests.


