From 0747ca5658f02e410aa3145a0db6c2c9fe1a4cb8 Mon Sep 17 00:00:00 2001 From: ducklet Date: Sat, 18 May 2024 23:35:07 +0200 Subject: [PATCH] fix: always use named constraints in SQLAlchemy --- ...1987-f17c7ca9afa4_use_named_constraints.py | 41 +++++++++++++++++++ unwind/models.py | 10 +++++ 2 files changed, 51 insertions(+) create mode 100644 alembic/versions/1716051987-f17c7ca9afa4_use_named_constraints.py diff --git a/alembic/versions/1716051987-f17c7ca9afa4_use_named_constraints.py b/alembic/versions/1716051987-f17c7ca9afa4_use_named_constraints.py new file mode 100644 index 0000000..be21664 --- /dev/null +++ b/alembic/versions/1716051987-f17c7ca9afa4_use_named_constraints.py @@ -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 ### diff --git a/unwind/models.py b/unwind/models.py index 594635c..4867599 100644 --- a/unwind/models.py +++ b/unwind/models.py @@ -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