postgresql - 在 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-14
has key 3
2020-06-07
has key一样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($1)
$$;
create table archives_seasonmodel (
episodes hstore check (check_episodes(episodes))
);
推荐阅读
- kendo-ui - How to start kendo pdf viewer with 'FitToWidth' selected
- flutter - 打破 ForEach() 飞镖
- highcharts-editor - Can't set 'stops' values in highcharts editor
- android - Android BroadcastReceiver OnReceieve not hit
- reactjs - 如何使用 React.js 正确显示 JSON 记录的所有子值
- php - 限制没有变量的页面,仅在来自页面或站点时打开
- javascript - 如何使用 Websockets 连接到 MQTT 代理?
- java - 如何在迭代流期间使用丰富(外部)调用?
- regex - 如何使用 sed 和 Regex 在 Bash 中突出显示语法?
- reactjs - 在 React 中更改状态会导致 Azure SignalR 出现错误 429