简体   繁体   中英

Postgres - array date column with constraint

I am trying to create a table test_table that has a column year which takes an array of 'years', like so:

CREATE TABLE avg_yearly_currencies_used (
    id serial PRIMARY KEY,
    year date[],
    CONSTRAINT first_jan_check CHECK ( date_trunc('year', year) = year )
);

The CONSTRAINT checks to see if the date is in the format such as: 2010-01-01 , or 2012-01-01 .

If the year column is not an array, then the above command works fine and the table is created. However, by making the date an array, and by having the CONSTRAINT , I get the following error:

ERROR: function date_trunc(unknown, date[]) does not exist

How do apply the CONSTRAINT to the array column year ?

You can use following approach

  1. Write a custom function to check whether all values in the array is complying with the condition:
create function check_date (
    date_ date[]) returns boolean as 
    $$
    declare
    result boolean;
    begin
    select bool_and (date_trunc('year', n) = n) into result
    from unnest(date_) s(n);
    return result;
    end;
    $$ 
    language plpgsql immutable;
  1. Add above function in check constraint
CREATE TABLE avg_yearly_currencies_used (
    id serial PRIMARY KEY,
    year date[],
    CONSTRAINT first_jan_check CHECK (check_date(year))
);

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM