如何从 php 获取 postgres 约束检查的允许值列表

How can I get a list of allowed values for a postgres constraint check from php

CREATE TABLE public.tasks(
id integer NOT NULL DEFAULT nextval('tasks_id_seq'::regclass),
title character varying(255) NOT NULL,
status character varying(255) NOT NULL,
type character varying(255) NOT NULL,
CONSTRAINT tasks_pkey PRIMARY KEY (id),
CONSTRAINT tasks_status_check CHECK (status::text = ANY (ARRAY['Asignada'::character varying, 'Revision'::character varying, 'Cumplida'::character varying, 'Cancelada'::character varying, 'Diferida'::character varying, 'Retardada'::character varying]::text[])),
CONSTRAINT tasks_type_check CHECK (type::text = ANY (ARRAY['Academico-Docente'::character varying, 'Administrativas'::character varying, 'Creacion intelectual'::character varying, 'Integracion-Social'::character varying, 'Administrativo-Docente'::character varying, 'Produccion'::character varying]::text[])))
WITH ( OIDS=FALSE);
  ALTER TABLE public.tasks
  OWNER TO postgres;

鉴于此 table,我如何才能获得约束 tasks_status_check 和 task_type_check 的可用白名单值?

另外,我正在尝试从 Laravel 开始,Laravel 创建约束而不是枚举。我已经调查了一段时间,但找不到解决方案

我在 MySql 中做到了,但我们正在迁移到 PostgreSql

我的代码是这样的

trait EnumHelper {
   public static function getEnumValues($field){
    $instance = new static;
    $type = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$field.'"'))[0]->Type;
    preg_match('/^enum\((.*)\)$/', $type, $matches);
    $values = array();
    foreach(explode(',', $matches[1]) as $value){
        $values[] = trim($value, "'");
    }
    return $values;
  }
}

提前致谢

查询系统目录 consrcpg_constraint 以获得检查约束的文本表示。

如果您要查找文本文字(如本例),您可以使用正则表达式和函数 regexp_matches(),示例:

select conname, array_agg(matches[1]) as "white list"
from pg_constraint,
regexp_matches(consrc, '''(.+?)''', 'g') matches
where contype = 'c'
and conrelid = 'public.tasks'::regclass
group by 1;

      conname       |                                                   white list                                                    
--------------------+-----------------------------------------------------------------------------------------------------------------
 tasks_type_check   | {Academico-Docente,Administrativas,"Creacion intelectual",Integracion-Social,Administrativo-Docente,Produccion}
 tasks_status_check | {Asignada,Revision,Cumplida,Cancelada,Diferida,Retardada}
(2 rows)

我做到了,感谢 Klin!他的回答很有用

trait EnumHelper {
  public static function getEnumValues($field){
    $instance = new static;
    $types = DB::select("
        select matches[1]
        from pg_constraint,
        regexp_matches(consrc, '''(.+?)''', 'g') matches
        where contype = 'c'
        and conname = '".$instance->getTable()."_".$field."_check'
        and conrelid = 'public.tasks'::regclass;
    ");
    $values = array();
    foreach($types as $type){
        $values[] = $type->matches;
    }
    return $values;
  }
}

现在完美运行。