functions allowed in CHECK constraints

From: Achilleas Mantzios <itdev(at)itdevel(dot)internal(dot)net>
To: pgsql-sql <pgsql-sql(at)postgresql(dot)org>
Subject: functions allowed in CHECK constraints
Date: 2018-02-09 08:37:18
Message-ID: 8d319874-ea46-d44f-29df-b6ecde7ce9c4@itdevel.internal.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello,

I just tried specifying a function in a check constraint, (not being able to use a subquery or otherwise referencing rows in another (parent) table) and this worked. However reading the docs do not
point to any such direction, on the contrary docs say that subselects are not allowed.
e.g. this fails as expected :

alter table crew_eval_rankset_rank ADD CONSTRAINT ranksetid_chk CHECK((SELECT NOT appliestoall FROM crew_eval_rankset cer WHERE cer.id=ranksetid));
ERROR:  cannot use subquery in check constraint

while this works unexpectedly :

create function crew_eval_ranksets_check_appliestoall (ranksetid int) RETURNS BOOLEAN LANGUAGE sql AS
$$
SELECT NOT appliestoall FROM crew_eval_rankset cer WHERE cer.id=ranksetid
$$;
alter table crew_eval_rankset_rank ADD CONSTRAINT ranksetid_chk CHECK(crew_eval_ranksets_check_appliestoall(ranksetid));

insert into crew_eval_rankset(setname,appliestoall) VALUES('all ranks','t');
insert into crew_eval_rankset_rank (ranksetid , rankid) VALUES(3,70);
ERROR:  new row for relation "crew_eval_rankset_rank" violates check constraint "ranksetid_chk"

So, what's the point in forbidding the use of subselects if one can use functions? And OTOH if effectively doing so is bad for some reason, why let it happen with a function?
Basically, I tried this after reading : https://stackoverflow.com/questions/21791675/foreign-key-constraint-with-some-column-values-residing-in-other-tables/22023533#22023533 , I wouldn't have thought
doing it after reading the docs.

--
Achilleas Mantzios

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Achilleas Mantzios 2018-02-09 09:04:07 functions allowed in CHECK constraints
Previous Message Olivier Leprêtre 2018-02-02 13:44:44 RE: search inside partitions