简体   繁体   English

Postgres - 带约束的数组日期列

[英]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:我正在尝试创建一个表test_table ,该表的year列采用“年”数组,如下所示:

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 . CONSTRAINT检查日期是否采用以下格式: 2010-01-012012-01-01

If the year column is not an array, then the above command works fine and the table is created.如果year列不是数组,则上述命令可以正常工作并创建表。 However, by making the date an array, and by having the CONSTRAINT , I get the following error:但是,通过将日期设为数组并使用CONSTRAINT ,我得到以下错误:

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

How do apply the CONSTRAINT to the array column year ?如何将CONSTRAINT应用于数组列year

You can use following approach您可以使用以下方法

  1. Write a custom function to check whether all values in the array is complying with the condition:编写一个自定义的 function 来检查数组中的所有值是否都符合条件:
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在检查约束中添加上面的 function
CREATE TABLE avg_yearly_currencies_used (
    id serial PRIMARY KEY,
    year date[],
    CONSTRAINT first_jan_check CHECK (check_date(year))
);

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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