Skip to content

Commit

Permalink
Tests: Test composite synthetic uniqueness constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
amotl committed Jul 18, 2024
1 parent d4adf08 commit f18ad02
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 3 additions & 0 deletions src/sqlalchemy_cratedb/support/polyfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions tests/test_support_polyfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")
Expand Down

0 comments on commit f18ad02

Please sign in to comment.