Postgres check constraints may refer to columns in the current row, but it isn't clear how to refer to the entire record to use functions that take a record as an argument
For example, a generic check constraint to count the number of non-null entries in a record:
-- Function that counts the number of non-null entries in a row
create function count_non_null(rec record) returns int as $$
begin
return count(v) from json_each(row_to_json(rec)) x(k_, v) where json_typeof(x.v) <> 'null';
end;
$$ language plpgsql immutable strict;
-- Check constraint asserting that only 3 values may be set on each row
alter table some_table add constraint ck_three_key check (
count_non_null(CURRENT_ROW) = 3 -- invalid
);
CURRENT_ROW is not permitted in this context. Any ideas how to pass the current row to a function inside a check constraint?
Use the table name:
alter table some_table
add constraint ck_three_key
check (count_non_null(some_table) = 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With