微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL查询约束中允许值的列表?

如何解决PostgreSQL查询约束中允许值的列表?

您可以查询系统目录pg_constraint,例如:

select consrc
from pg_constraint
where conrelid = 'requests'::regclass
and consrc like '(status%';

                                  consrc                                   
---------------------------------------------------------------------------
 (status = ANY (ARRAY['pending'::text, 'success'::text, 'failure'::text]))
(1 row)

使用以下函数 解压缩 字符串:

create or replace function get_check_values(str text)
returns setof text language plpgsql as $$
begin
    return query
        execute format (
            'select * from unnest(%s)',
            regexp_replace(str, '.*(ARRAY\[.*\]).*', '\1'));
end $$;

select get_check_values(consrc)
from pg_constraint
where conrelid = 'requests'::regclass
and consrc like '(status%';

 get_check_values 
------------------
 pending
 success
 failure
(3 rows)

解决方法

给定一个PostgreSQL表requests,该表具有一个名为的列status和一个约束,如下所示:

ALTER TABLE requests ADD CONSTRAINT allowed_status_types
  CHECK (status IN (
    'pending',-- request has not been attempted
    'success',-- request succeeded
    'failure'  -- request failed
  ));

在这种情况下,psql我可以提取有关此约束的信息:

example-database=# \d requests
                                          Table "public.example-database"
        Column        |            Type             |                             Modifiers
----------------------+-----------------------------+-------------------------------------------------------------------
 id                   | integer                     | not null default nextval('requests_id_seq'::regclass)
 status               | character varying           | not null default 'pending'::character varying
 created_at           | timestamp without time zone | not null
 updated_at           | timestamp without time zone | not null

Indexes:
    "requests_pkey" PRIMARY KEY,btree (id)
Check constraints:
    "allowed_status_types" CHECK (status::text = ANY (ARRAY['pending'::character varying,'success'::character varying,'failure'::character varying]::text[]))

但是是否有可能编写一个专门返回allowed_status_types未决,成功,失败的查询?

能够在我的应用程序中记住此查询的结果,而不需要维护重复的副本,将是很棒的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。