Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres check constraint using function with 'record/' type argument

Tags:

sql

postgresql

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?

like image 725
Oliver Rice Avatar asked Oct 25 '25 19:10

Oliver Rice


1 Answers

Use the table name:

alter table some_table 
   add constraint ck_three_key 
   check (count_non_null(some_table) = 3);