在 HSTORE 上创建检查约束以维护特定的数据连续性

Create check constraint on HSTORE to maintain specific succession of data

问题是关于 Postgres 中 HSTORE 字段的检查约束。

create table archives_seasonmodel
    (episodes      hstore)

这是我拥有的 table 的非常简短的版本,但仅作为示例还可以。

剧集包含以下格式的数据:

{ 
1 => 2020-03-01, 2 => 2020-03-07,  5=> 2020-03-29, 3=> 2020-03-14
}

其中键始终为正数,值始终为日期。

我想创建一个约束来检查任何新数据是否符合以下条件:

– key/value 对中的每个日期应大于或等于按键 ASC 排序的前一个 key/value 对。

好数据:

{ 
1 => 2020-03-01, 2 => 2020-03-07,  5=> 2020-03-29, 3=> 2020-03-14
}
2020-03-29 >= 2020-03-14 >=   2020-03-07 >=  2020-03-01

5 >=3 >=2 >=1

错误数据:

{ 
1 => 2020-03-01, 2 => 2020-06-07,  5=> 2020-03-29, 3=> 2020-03-14
}
2020-03-29 >= 2020-03-14 not >=   2020-06-07 >=  2020-03-01

5 >=3 >=2 >=1

2020-03-14 not >= 2020-06-07 但它应该是因为 2020-03-14 有键 3 2020-06-07 有键 2。键 3 的日期应该大于或等于键 2 的日期,因为 3 > 2.

是否可以创建这样的约束,或者它只是脱离现实???

谢谢

创建一个函数来检查条件。使用hstore函数each()和聚合函数array_agg().

create or replace function check_episodes(hstore)
returns boolean language sql as $$
    select array_agg(key order by key::int) = array_agg(key order by value::date)
    from each()
$$;

create table archives_seasonmodel (
    episodes hstore check (check_episodes(episodes))
);

Db<>fiddle.