Skip to content

Instantly share code, notes, and snippets.

@SF-300
Last active January 18, 2023 16:14
Show Gist options
  • Select an option

  • Save SF-300/3916bd5e9a1dc339e50bdbb92926ab9e to your computer and use it in GitHub Desktop.

Select an option

Save SF-300/3916bd5e9a1dc339e50bdbb92926ab9e to your computer and use it in GitHub Desktop.
Any-of constraint building using SQLAlchemy
import operator as op
import sqlalchemy as sa
__all__ = "anyof_constraint",
def anyof_constraint(*cols, at_least_one: bool = False) -> sa.CheckConstraint:
if len(cols) < 2:
raise ValueError("At least 2 columns MUST be provided to create any-of constraint!")
# NOTE(zeronineseven): Inspired by https://hashrocket.com/blog/posts/modeling-polymorphic-associations-in-a-relational-database#exclusive-belongs-to-aka-exclusive-arc-
return sa.CheckConstraint(
(op.eq if at_least_one else op.le)(
functools.reduce(lambda acc, c: acc + c, (sa.cast(c.is_not(None), sa.Integer) for c in cols)), 1
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment