fix: always use named constraints in SQLAlchemy

This commit is contained in:
ducklet 2024-05-18 23:35:07 +02:00
parent f102e07256
commit 0747ca5658
2 changed files with 51 additions and 0 deletions

View file

@ -0,0 +1,41 @@
"""use named constraints
See https://alembic.sqlalchemy.org/en/latest/naming.html
Revision ID: f17c7ca9afa4
Revises: 62882ef5e3ff
Create Date: 2024-05-18 17:06:27.696713+00:00
"""
from typing import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f17c7ca9afa4"
down_revision: str | None = "62882ef5e3ff"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("movies") as batch_op:
batch_op.create_unique_constraint(batch_op.f("uq_movies_imdb_id"), ["imdb_id"])
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.create_unique_constraint(batch_op.f("uq_users_imdb_id"), ["imdb_id"])
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_constraint(batch_op.f("uq_users_imdb_id"), type_="unique")
with op.batch_alter_table("movies", schema=None) as batch_op:
batch_op.drop_constraint(batch_op.f("uq_movies_imdb_id"), type_="unique")
# ### end Alembic commands ###

View file

@ -41,6 +41,16 @@ class Model(Protocol):
mapper_registry = registry()
metadata = mapper_registry.metadata
# An explicit naming convention helps Alembic do its job,
# see https://alembic.sqlalchemy.org/en/latest/naming.html.
metadata.naming_convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
def annotations(tp: Type) -> tuple | None:
return tp.__metadata__ if hasattr(tp, "__metadata__") else None # type: ignore