将列的注释设置为Postgresql中另一列的注释

时间:2008-11-07 15:29:19

标签: postgresql ddl comments

假设我在Postgresql中创建了一个表,其中包含对列的注释:

create table t1 (
   c1 varchar(10)
);
comment on column t1.c1 is 'foo';

一段时间后,我决定添加另一栏:

alter table t1 add column c2 varchar(20);

我想查找第一列的评论内容,并与新列关联:

select comment_text from (what?) where table_name = 't1' and column_name = 'c1'

(什么?)将成为一个系统表,但在浏览了pgAdmin并在网上搜索之后我还没有学到它的名字。

理想情况下,我希望能够:

comment on column t1.c1 is (select ...);

但我有一种感觉,这种感觉有点紧张。谢谢你的任何想法。

更新:根据我在这里收到的建议,我最终编写了一个程序来自动完成传输注释的任务,这是更改Postgresql列数据类型的更大过程的一部分。您可以阅读on my blog

2 个答案:

答案 0 :(得分:5)

接下来要知道的是如何获取表oid。我认为,将此作为评论的一部分将无效,正如您所怀疑的那样。

    postgres=# create table comtest1 (id int, val varchar);
    CREATE TABLE
    postgres=# insert into comtest1 values (1,'a');
    INSERT 0 1
    postgres=# select distinct tableoid from comtest1;
     tableoid
    ----------
        32792
    (1 row)

    postgres=# comment on column comtest1.id is 'Identifier Number One';
    COMMENT
    postgres=# select col_description(32792,1);
        col_description
    -----------------------
     Identifier Number One
    (1 row)

无论如何,我掀起了一个快速的plpgsql函数,将注释从一个表/列对复制到另一个。你必须在数据库上createlang plpgsql并使用它:

    Copy the comment on the first column of table comtest1 to the id 
    column of the table comtest2. Yes, it should be improved but 
    that's left as work for the reader.

    postgres=# select copy_comment('comtest1',1,'comtest2','id');
     copy_comment
    --------------
                1
    (1 row)
CREATE OR REPLACE FUNCTION copy_comment(varchar,int,varchar,varchar) RETURNS int AS $PROC$
DECLARE
        src_tbl ALIAS FOR $1;
        src_col ALIAS FOR $2;
        dst_tbl ALIAS FOR $3;
        dst_col ALIAS FOR $4;
        row RECORD;
        oid INT;
        comment VARCHAR;
BEGIN
        FOR row IN EXECUTE 'SELECT DISTINCT tableoid FROM ' || quote_ident(src_tbl) LOOP
                oid := row.tableoid;
        END LOOP;

        FOR row IN EXECUTE 'SELECT col_description(' || quote_literal(oid) || ',' || quote_literal(src_col) || ')' LOOP
                comment := row.col_description;
        END LOOP;

        EXECUTE 'COMMENT ON COLUMN ' || quote_ident(dst_tbl) || '.' || quote_ident(dst_col) || ' IS ' || quote_literal(comment);

        RETURN 1;
END;
$PROC$ LANGUAGE plpgsql;

答案 1 :(得分:1)

您可以使用系统函数col_description(table_oid,column_number)检索有关列的注释。有关详细信息,请参阅this page