table inheritance(상속)

POSTGRESQL 2014. 10. 28. 10:40
postgreSQL은 테이블 생성시에 하나이상의 다른 테이블로부터의 상속기능을 제공합니다.
상속받은 테이블을 자식테이블, 상속대상 테이블을 부모테이블로 할때 자식테이블을 create table 시 INHERITS 옵션을 이용하여 부모테이블의 컬럼, check / not-null 제약조건을 상속받습니다.
아래는 자식테이블 생성 및 조회에 대한 예제입니다.

1. 부모테이블을 생성합니다.
postgres=# CREATE TABLE cities (
postgres(#     name            text,
postgres(#     population      float,
postgres(#     altitude        int     -- in feet
postgres(# );
CREATE TABLE
postgres=# \d+ cities
                       Table "public.cities"
   Column   |       Type       | Modifiers | Storage  | Description 
------------+------------------+-----------+----------+-------------
 name       | text             |           | extended | 
 population | double precision |           | plain    | 
 altitude   | integer          |           | plain    | 
Has OIDs: no


2. cities 테이블을 상속받는 자식테이블 capitals을 IHERIT 구문을 이용하여 생성합니다.
postgres=# CREATE TABLE capitals (
postgres(#     state           char(2)
postgres(# ) INHERITS (cities);
CREATE TABLE
postgres=# \d+ capitals;
                      Table "public.capitals"
   Column   |       Type       | Modifiers | Storage  | Description 
------------+------------------+-----------+----------+-------------
 name       | text             |           | extended | 
 population | double precision |           | plain    | 
 altitude   | integer          |           | plain    | 
 state      | character(2)     |           | extended | 
Inherits: cities
Has OIDs: no


3. 부모테이블에 대한 조회/수정/삭제 SQL은 자식테이블을 포함하여 조회/수정/삭제되며, only 옵션을 이용하여 하나의 테이블을 지정할 수 있습니다.
postgres=# insert into cities values('kms',10.23,1000);
INSERT 0 1
postgres=# insert into capitals values('kms',10.23,1000,'01');
INSERT 0 1
postgres=# select * from cities;
 name | population | altitude 
------+------------+----------
 kms  |      10.23 |     1000
 kms  |      10.23 |     1000
(2 rows)
                           ^
postgres=# select * from only cities;
 name | population | altitude 
------+------------+----------
 kms  |      10.23 |     1000
(1 row)


4. 상속받은 테이블을 부모테이블로 하는 또다른 자식테이블을 생성하면, 최상위 부모테이블에 대한 조회/수정/삭제질의는 전계층의 테이블을 포함합니다.
postgres=# create table streets(col1 char(1)) inherits(capitals);
insert into streets values ('kms',20.24,2100,02,'1');
INSERT 0 1

postgres=# select * from only cities;
 name | population | altitude 
------+------------+----------
 kms  |      10.23 |     1000
(1 row)

postgres=# select * from only capitals;
 name | population | altitude | state 
------+------------+----------+-------
 kms  |      10.23 |     1000 | 01
(1 row)

postgres=# select * from streets;
 name | population | altitude | state | col1 
------+------------+----------+-------+------
 kms  |      20.24 |     2100 | 2     | 1
(1 row)

postgres=# select * from cities;
 name | population | altitude 
------+------------+----------
 kms  |      10.23 |     1000
 kms  |      10.23 |     1000
 kms  |      20.24 |     2100
(3 rows)


※ 가독성을 높히기 위해 부모테이블을 대상으로 하는 쿼리를 작성할 때 테이블 후미에 *를 붙여 상속테이블이 포함될 것임을 표시하는 것을 권장합니다.
예시) select * from cities*;

max_connections 와 커널파라메터

POSTGRESQL 2014. 10. 27. 19:41
postgresql 의 max_connections 값을 증가시키고 나서 클러스터(인스턴스) 기동 시 다음과 같은 오류가 발생할 수 있습니다.
FATAL:  could not create semaphores: No space left on device
[2012-10-24 16:49:55.313 KST][][][][][20731]DETAIL:  Failed system call was semget(5433033, 17, 03600).
[2012-10-24 16:49:55.313 KST][][][][][20731]HINT:  This error does *not* mean that you have run out of disk space.
 It occurs when either the system limit for the maximum number of semaphore sets (SEMMNI), or the system wide maximum number
 of semaphores (SEMMNS), would be exceeded.  You need to raise the respective kernel parameterively, reduce PostgreSQL's 
consumption of semaphores by reducing its max_connections parameter (currently 510).
 The PostgreSQL documentation contains more information about configuring your system for PostgreSQL.
이러한 오류는 max_connections 파라메터가 SEMMNI라는 세마포어 관련 커널 파라메터값을 초과해서 발생되는 오류로 커널 제한값을 늘리거나 postgresql의 max_connections 값을 줄여서 해결할 수 있습니다.
아래는 커널파라메터 값을 수정하는 방법입니다.(root권한이 필요합니다.)

1. 커널파라메터 확인 : Semaphore Limits 부분의 max number of arrays 항목을 확인합니다.
$ ipcs -l

------ Shared Memory Limits --------
max number of segments = 4096
max seg size (kbytes) = 67108864
max total shared memory (kbytes) = 17179869184
min seg size (bytes) = 1

------ Semaphore Limits --------
max number of arrays = 128
max semaphores per array = 250
max semaphores system wide = 32000
max ops per semop call = 32
semaphore max value = 32767

------ Messages: Limits --------
max queues system wide = 16
max size of message (bytes) = 65536
default max size of queue (bytes) = 65536


2. 커널파라메터 수정
$ vi /etc/sysctl.conf
kerlel.sem=250 256000 32 128    ## 네번째 값이 SEMMNI이고 이 값을 증가시켜야 합니다.(세마포어 배열의 최대갯수).
$ sysctl -p /etc/sysctl.conf    ## 수정한 값으로 리로드 합니다.
파라메터를 구하는 공식 :
SEMMNI = (max_connections + autovacuum_max_workers + 4) / 16

postgresql DBLINK 예제

POSTGRESQL 2014. 10. 27. 11:18
postgreSQL 의 오브젝트 구조는 하나의 클러스터 안에 2개 이상의 데이터베이스를 운영할 수 있는 구조입니다.
하지만 데이터베이스간의 직접적인 접근을 불가능하므로 다른 데이터베이스에 접근하려면 dblink 또는 9.3 버젼이상에서 지원하는 foreign DATA wrapper 라는 contrib 모듈을 사용해야 합니다.
아래는 dblink 모듈에 대한 예제입니다.

1. dblink 라이브러리 파일 생성
$ cd .src/contrib/dblink
$ make
$ make install


2. extension 생성
test=# create extension dblink;
CREATE extension


3. dblink 커넥션 생성 및 해제
test=# select dblink_connect('db링크이름','hostaddr=호스트IP port=호스트PORT dbname=DB명 user=유저명 password=비밀번호');
 dblink_connect 
----------------
 OK
(1 row)
-- 조회(as 뒤에 select결과에 대한 type을 column별로 지정)
test=# select * from dblink('db2', 'select * from test') as t1(c1 char);
 c1 
----
 d
(1 row)
-- 접속해제
test=# select dblink_disconnect('db2');
 dblink_disconnect 
-------------------
 OK
(1 row)

'POSTGRESQL' 카테고리의 다른 글

table inheritance(상속)  (0) 2014.10.28
max_connections 와 커널파라메터  (0) 2014.10.27
gdb로 postgresql backend process 디버깅하기  (0) 2014.10.26
table/index bloat 점검하기  (0) 2014.10.26
pg_trgm 설치하기  (1) 2014.10.26