Last active
January 18, 2023 16:14
-
-
Save SF-300/3916bd5e9a1dc339e50bdbb92926ab9e to your computer and use it in GitHub Desktop.
Any-of constraint building using SQLAlchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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