【问题标题】:Query for the allowed values in a constraint查询约束中的允许值
【发布时间】:2021-12-31 04:37:03
【问题描述】:

我想从数据库表上的CHECK 约束中提取值。代码是:

CONSTRAINT Shop_check_serviceType CHECK (service_type IN ('food or drink', 'entertainment', 'retail'))

在 Postgres 12 中,pg_catalog.pg_constraint 中有一个名为 consrc 的列。但我使用 Postgres 14,我不知道如何提取那里的值。我试图搜索手册没有成功。

【问题讨论】:

    标签: java postgresql constraints ddl


    【解决方案1】:

    使用专用函数pg_get_constraintdef()对约束定义的SQL-DDL代码进行逆向工程。

    SELECT pg_get_constraintdef(oid)
    FROM   pg_catalog.pg_constraint
    WHERE  contype  = 'c'                          -- CHECK constraint
    AND    conrelid = 'public.my_table'::regclass  -- your table name here
    AND    connname = 'shop_check_servicetype';    -- lower-cased?
    

    如果您没有用双引号将约束名称“Shop_check_serviceType”转换为小写。

    相关:

    顺便说一句,(冗余)列 consrc existed up to Postgres 11 已经从 Postgres 12 中的 pg_catalog.pg_constraint 中删除。pg_get_constraintdef() 复制了该列中的内容。

    引用release notes of Postgres 12

    • 删除过时的 pg_constraint.consrc 列 (Peter Eisentraut)

      此列已被弃用很长时间,因为它没有 更新以响应其他目录更改(例如列 重命名)。获取支票文本版本的推荐方法 来自 pg_constraint 的约束表达式是 pg_get_expr(conbin, conrelid)pg_get_constraintdef() 也是一个有用的替代方案。

    【讨论】:

    • 非常感谢!它的工作
    • @Στέφανος 如果正确回答了您的问题,请考虑接受。
    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多