From f18ad0284db2509b4dc66870753f7e87bec89795 Mon Sep 17 00:00:00 2001 From: Andreas Motl Date: Thu, 18 Jul 2024 23:27:38 +0200 Subject: [PATCH] Tests: Test composite synthetic uniqueness constraints --- src/sqlalchemy_cratedb/support/polyfill.py | 3 +++ tests/test_support_polyfill.py | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/sqlalchemy_cratedb/support/polyfill.py b/src/sqlalchemy_cratedb/support/polyfill.py index 73177e5..f9a2760 100644 --- a/src/sqlalchemy_cratedb/support/polyfill.py +++ b/src/sqlalchemy_cratedb/support/polyfill.py @@ -38,7 +38,10 @@ def check_uniqueness_factory(sa_entity, *attribute_names): This is used by CrateDB's MLflow adapter. + TODO: Maybe add to some helper function? TODO: Maybe enable through a dialect parameter `crate_polyfill_unique` or such. + TODO: Maybe derive from the model definition itself? + __table_args__ = (sa.UniqueConstraint("name", "user_id", name="unique_name_user"),) """ # Synthesize a canonical "name" for the constraint, diff --git a/tests/test_support_polyfill.py b/tests/test_support_polyfill.py index d495fee..1770209 100644 --- a/tests/test_support_polyfill.py +++ b/tests/test_support_polyfill.py @@ -74,7 +74,7 @@ class FooBar(Base): name = sa.Column(sa.String) # Add synthetic UNIQUE constraint on `name` column. - listen(FooBar, "before_insert", check_uniqueness_factory(FooBar, "name")) + listen(FooBar, "before_insert", check_uniqueness_factory(FooBar, "id", "name")) Base.metadata.drop_all(engine, checkfirst=True) Base.metadata.create_all(engine, checkfirst=True) @@ -86,11 +86,11 @@ class FooBar(Base): session.execute(sa.text("REFRESH TABLE foobar")) # Insert second record, violating the uniqueness constraint. - bar_item = FooBar(id="bar", name="foo") + bar_item = FooBar(id="foo", name="foo") session.add(bar_item) with pytest.raises(IntegrityError) as ex: session.commit() - assert ex.match("DuplicateKeyException in table 'foobar' on constraint 'name'") + assert ex.match("DuplicateKeyException in table 'foobar' on constraint 'id-name'") @pytest.mark.skipif(SA_VERSION < SA_1_4, reason="Feature not supported on SQLAlchemy 1.3 and earlier")