-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Primary flag helper column type needed #133
Comments
Caveat: using this structure gives us an at most one scenario, but not the corresponding at least one scenario that is also required. |
Additional caveat: Flagging one row as primary does not remove the primary flag from other rows unless all rows are loaded from database (or updated in the database without loading), as in scenario 3 above. An app-side validator on the parent object is still needed. The only difference is that the database will catch errors. Scenario 4, despite its cumbersomeness, is the most foolproof method. |
Using foreign keys from the parent breaks normalisation. The parent may refer to a child that does not refer back to the parent, and SQL does not provide a direct way to validate that. |
From Stack Overflow: the correct approach is to use a secondary join table to record the default. This is worth examining. Some things remain the same from scenario 4:
One improvement:
One regression (seemingly):
One remaining problem:
|
Counterpoint: Because of the unique index, having flags on each row still makes it easy to discover which one is set to default. |
Using the foreign key method, (a) an app-side validator and (b) a PostgreSQL trigger can do an |
Implementation and additional discussion in #134. |
We often have use cases where in a set of objects of the same type, one—and only one—of them needs to be designated primary or default. For example, if a user has multiple email addresses and one of them is the default for them to receive email at.
SQL does not provide an obvious way to do this:
CHECK
constraint on the column cannot examine the flag on other rows.ALTER TABLE
(SQLAlchemy'suse_alter
flag does this), and importing data into the table requires temporarily suspending foreign key validation or importing in two passes. In particular, this breakspg_dump
's data-only import.Fortunately, SQL's tendency to treat
NULL
values as unique and distinct from otherNULL
values can be exploited to make such a flag:True
andNULL
, transparently cast into Python booleans on the way in and out.CHECK
constraint on the column to ensure the value is neverFalse
.True
value, but any number of rows can have aNULL
value.A new column type derived from boolean can automate all of this except the multi-column unique constraint.
The text was updated successfully, but these errors were encountered: