문제

열에 대한 주석과 함께 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 열의 데이터 유형을 변경하는 더 큰 프로세스의 일부로 주석을 전송하는 작업을 자동화하는 프로그램 작성을 중상했습니다. 그것에 대해 읽을 수 있습니다 내 블로그에서.

도움이 되었습니까?

해결책

다음으로 알아야 할 것은 테이블 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 함수를 채찍질했습니다. 데이터베이스에서 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;

다른 팁

시스템 함수 col_description (table_oid, column_number)을 사용하여 열에서 주석을 검색 할 수 있습니다. 보다 이 페이지 자세한 내용은.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top