2017-02-21 72 views
1

我在Postgres的9.6得到了一个ENUM柱:Postgres:添加ENUM值的描述?

CREATE TYPE my_type AS ENUM('foo', 'bar'); 

我想在枚举,例如添加人类可读的描述为每个值对于fooThis is the foo value and it does stuff

有没有办法在Postgres中做到这一点?我想要Django的choices field

回答

0

我觉得没有什么特别的。标准comment ..

t=# \x 
Expanded display is on. 
t=# comment on type my_type is 'foo: something fooish, bar: a place to avoid'; 
COMMENT 
t=# \dT+ my_type 
List of data types 
-[ RECORD 1 ]-----+--------------------------------------------- 
Schema   | public 
Name    | my_type 
Internal name  | my_type 
Size    | 4 
Elements   | foo           + 
        | bar 
Owner    | postgres 
Access privileges | 
Description  | foo: something fooish, bar: a place to avoid 

一些变态的幻想:

t=# comment on type my_type is '{"foo": "something fooish", "bar": "a place to avoid"}'; 
COMMENT 
t=# select pg_catalog.obj_description(t.oid, 'pg_type')::json->>'foo' from pg_type t where typname = 'my_type'; 
    ?column? 
------------------ 
something fooish 
(1 row) 
0

Teoretically您可以创建两个类型与尺寸相同,并使用这样的事:

CREATE TYPE my_type AS ENUM('foo', 'bar'); 
CREATE TYPE my_type_description AS ENUM('foo desc', 'bar desc'); 

CREATE FUNCTION show_desc(i my_type) RETURNS my_type_description AS $sql$ 
    SELECT ((enum_range(NULL::my_type_description))[array_length(enum_range(NULL, i), 1)])::my_type_description; 
$sql$ LANGUAGE SQL STABLE; 

SELECT show_desc('foo'); 

show_desc 
----------- 
foo desc 
(1 row) 

SELECT show_desc('bar'); 

show_desc 
----------- 
bar desc 
(1 row)