From 3739c573eab6f73b88ff2d96198b558e96ccf0c8 Mon Sep 17 00:00:00 2001 From: Leo Hemsted Date: Tue, 25 Sep 2018 14:06:36 +0100 Subject: [PATCH] fix null check in constraint There are two fun quirks of postgres/sql that we need to work around: * any `x = y` where x or y is NULL returns NULL, rather than false. * check constraints accept NULL or true values as good. so, the check `postage in ('first', 'second')` returns `null` rather than `false` when postage is null itself. This surprisingly passes the check constraint. To get around this, we have to add an explicit not null check as well. --- app/models.py | 4 ++-- migrations/versions/0230_noti_postage_constraint.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/models.py b/app/models.py index cf58a6867..5df7730bf 100644 --- a/app/models.py +++ b/app/models.py @@ -1193,7 +1193,7 @@ class Notification(db.Model): postage = db.Column(db.String, nullable=True) CheckConstraint(""" CASE WHEN notification_type = 'letter' THEN - postage in ('first', 'second') + postage is not null and postage in ('first', 'second') ELSE postage is null END @@ -1453,7 +1453,7 @@ class NotificationHistory(db.Model, HistoryModel): postage = db.Column(db.String, nullable=True) CheckConstraint(""" CASE WHEN notification_type = 'letter' THEN - postage in ('first', 'second') + postage is not null and postage in ('first', 'second') ELSE postage is null END diff --git a/migrations/versions/0230_noti_postage_constraint.py b/migrations/versions/0230_noti_postage_constraint.py index 118d51b39..a8c40d7ec 100644 --- a/migrations/versions/0230_noti_postage_constraint.py +++ b/migrations/versions/0230_noti_postage_constraint.py @@ -17,7 +17,7 @@ def upgrade(): ALTER TABLE notifications ADD CONSTRAINT "chk_notifications_postage_null" CHECK ( CASE WHEN notification_type = 'letter' THEN - postage in ('first', 'second') + postage is not null and postage in ('first', 'second') ELSE postage is null END @@ -28,7 +28,7 @@ def upgrade(): ALTER TABLE notification_history ADD CONSTRAINT "chk_notification_history_postage_null" CHECK ( CASE WHEN notification_type = 'letter' THEN - postage in ('first', 'second') + postage is not null and postage in ('first', 'second') ELSE postage is null END