首页 > 解决方案 > 在 HSTORE 上创建检查约束以维护特定的数据连续性

问题描述

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

create table archives_seasonmodel
    (episodes      hstore)

这是我所拥有的表格的非常缩短的版本,但例如它还可以。

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

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

其中 key 始终是一个正数,而 value 是一个日期。

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

– 键/值对中的每个日期都应大于或等于由键 ASC 排序的先前键/值对。

好数据:

{ 
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-14has key 3 2020-06-07has key一样2。键的日期3应该大于或等于带有键的日期,2因为3 > 2.

是否有可能创造这样的约束,或者它只是脱离现实???

谢谢

标签: postgresqlaggregate-functionscheck-constraintshstore

解决方案


创建一个检查条件的函数。使用 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($1)
$$;

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

Db<>小提琴。


推荐阅读