갈루아의 반서재

How To Install and Use PostgreSQL on Ubuntu 14.04


Installation


우분투의 기본 저장소는 Postgres 패키지를 포함하고 있으므로, apt 패키징 시스템을 이용해서 설치할 수 있다. 로컬 apt 저장소를 업데이트하지 않았으므로, 먼저 apt 저장소를 업데이트한다. Postgres 패키지와 "contrib" 패키지를 가지고 와서 설치한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
(venv) root@localhost:~/lispworks# sudo apt-get update
 
(venv) root@localhost:~/lispworks# sudo apt-get install postgresql postgresql-contrib
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다
상태 정보를 읽는 중입니다... 완료
다음 패키지가 자동으로 설치되었지만 더 이상 필요하지 않습니다:
  gyp libc-ares-dev libc-ares2 libjs-node-uuid libv8-3.14-dev libv8-3.14.5
  node-abbrev node-ansi node-archy node-async node-block-stream
  node-combined-stream node-cookie-jar node-delayed-stream node-forever-agent
  node-form-data node-fstream node-fstream-ignore node-github-url-from-git
  node-glob node-graceful-fs node-gyp node-inherits node-ini
  node-json-stringify-safe node-lockfile node-lru-cache node-mime
  node-minimatch node-mkdirp node-mute-stream node-node-uuid node-nopt
  node-normalize-package-data node-npmlog node-once node-osenv node-qs
  node-read node-read-package-json node-request node-retry node-rimraf
  node-semver node-sha node-sigmund node-slide node-tar node-tunnel-agent
  node-which python3-chardet python3-colorama python3-distlib python3-html5lib
  python3-six python3-urllib3 python3-wheel
Use 'apt-get autoremove' to remove them.
다음 패키지를 더 설치할 것입니다:
  libossp-uuid16 libpq-dev libpq5 postgresql-9.3 postgresql-client-9.3
  postgresql-client-common postgresql-common postgresql-contrib-9.3
제안하는 패키지:
  uuid postgresql-doc-9.3 oidentd ident-server locales-all libdbd-pg-perl
다음 새 패키지를 설치할 것입니다:
  libossp-uuid16 postgresql postgresql-9.3 postgresql-client-9.3
  postgresql-client-common postgresql-common postgresql-contrib
  postgresql-contrib-9.3
다음 패키지를 업그레이드할 것입니다:
  libpq-dev libpq5
2개 업그레이드, 8개 새로 설치, 0개 제거 및 184개 업그레이드 안 함.
4,263 k바이트 아카이브를 받아야 합니다.
이 작업 후 17.3 M바이트의 디스크 공간을 더 사용하게 됩니다.
계속 하시겠습니까? [Y/n] y
받기:1 http://kr.archive.ubuntu.com/ubuntu/ trusty/main libossp-uuid16 amd64 1.6.2-1.3ubuntu1 [29.6 kB]
받기:2 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main libpq-dev amd64 9.3.19-0ubuntu0.14.04 [140 kB]
받기:3 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main libpq5 amd64 9.3.19-0ubuntu0.14.04 [78.2 kB]
받기:4 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-client-common all 154ubuntu1 [25.4 kB]
받기:5 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-client-9.3 amd64 9.3.19-0ubuntu0.14.04 [788 kB]
받기:6 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-common all 154ubuntu1 [103 kB]
받기:7 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-9.3 amd64 9.3.19-0ubuntu0.14.04 [2,686 kB]
받기:8 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql all 9.3+154ubuntu1 [5,038 B]
받기:9 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-contrib-9.3 amd64 9.3.19-0ubuntu0.14.04 [403 kB]
받기:10 http://kr.archive.ubuntu.com/ubuntu/ trusty-updates/main postgresql-contrib all 9.3+154ubuntu1 [5,058 B]
내려받기 4,263 k바이트, 소요시간 2초 (1,678 k바이트/초)
패키지를 미리 설정하는 중입니다...
Selecting previously unselected package libossp-uuid16.
(데이터베이스 읽는중 ...현재 146020개의 파일과 디렉터리가 설치되어 있습니다.)
Preparing to unpack .../libossp-uuid16_1.6.2-1.3ubuntu1_amd64.deb ...
Unpacking libossp-uuid16 (1.6.2-1.3ubuntu1) ...
Preparing to unpack .../libpq-dev_9.3.19-0ubuntu0.14.04_amd64.deb ...
Unpacking libpq-dev (9.3.19-0ubuntu0.14.04) over (9.3.16-0ubuntu0.14.04) ...
Preparing to unpack .../libpq5_9.3.19-0ubuntu0.14.04_amd64.deb ...
Unpacking libpq5 (9.3.19-0ubuntu0.14.04) over (9.3.16-0ubuntu0.14.04) ...
Selecting previously unselected package postgresql-client-common.
Preparing to unpack .../postgresql-client-common_154ubuntu1_all.deb ...
Unpacking postgresql-client-common (154ubuntu1) ...
Selecting previously unselected package postgresql-client-9.3.
Preparing to unpack .../postgresql-client-9.3_9.3.19-0ubuntu0.14.04_amd64.deb ...
Unpacking postgresql-client-9.3 (9.3.19-0ubuntu0.14.04) ...
Selecting previously unselected package postgresql-common.
Preparing to unpack .../postgresql-common_154ubuntu1_all.deb ...
'/usr/bin/pg_config의 /usr/bin/pg_config.libpq-dev(으)로 전환, postgresql-common 패키지' 추가하는 중
Unpacking postgresql-common (154ubuntu1) ...
Selecting previously unselected package postgresql-9.3.
Preparing to unpack .../postgresql-9.3_9.3.19-0ubuntu0.14.04_amd64.deb ...
Unpacking postgresql-9.3 (9.3.19-0ubuntu0.14.04) ...
Selecting previously unselected package postgresql.
Preparing to unpack .../postgresql_9.3+154ubuntu1_all.deb ...
Unpacking postgresql (9.3+154ubuntu1) ...
Selecting previously unselected package postgresql-contrib-9.3.
Preparing to unpack .../postgresql-contrib-9.3_9.3.19-0ubuntu0.14.04_amd64.deb ...
Unpacking postgresql-contrib-9.3 (9.3.19-0ubuntu0.14.04) ...
Selecting previously unselected package postgresql-contrib.
Preparing to unpack .../postgresql-contrib_9.3+154ubuntu1_all.deb ...
Unpacking postgresql-contrib (9.3+154ubuntu1) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for ureadahead (0.100.0-16) ...
libossp-uuid16 (1.6.2-1.3ubuntu1) 설정하는 중입니다 ...
libpq5 (9.3.19-0ubuntu0.14.04) 설정하는 중입니다 ...
libpq-dev (9.3.19-0ubuntu0.14.04) 설정하는 중입니다 ...
postgresql-client-common (154ubuntu1) 설정하는 중입니다 ...
postgresql-client-9.3 (9.3.19-0ubuntu0.14.04) 설정하는 중입니다 ...
update-alternatives: using /usr/share/postgresql/9.3/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in 자동 모드
postgresql-common (154ubuntu1) 설정하는 중입니다 ...
Adding user postgres to group ssl-cert
Creating config file /etc/logrotate.d/postgresql-common with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
Removing obsolete dictionary files:
 * No PostgreSQL clusters exist; see "man pg_createcluster"
Processing triggers for ureadahead (0.100.0-16) ...
postgresql-9.3 (9.3.19-0ubuntu0.14.04) 설정하는 중입니다 ...
Creating new cluster 9.3/main ...
  config /etc/postgresql/9.3/main
  data   /var/lib/postgresql/9.3/main
  locale ko_KR.UTF-8
  port   5432
update-alternatives: using /usr/share/postgresql/9.3/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmaster.1.gz (postmaster.1.gz) in 자동 모드
 * Starting PostgreSQL 9.3 database server                                                     [ OK ]
postgresql (9.3+154ubuntu1) 설정하는 중입니다 ...
postgresql-contrib-9.3 (9.3.19-0ubuntu0.14.04) 설정하는 중입니다 ...
postgresql-contrib (9.3+154ubuntu1) 설정하는 중입니다 ...
Processing triggers for libc-bin (2.19-0ubuntu6.11) ...
 
cs


설치된 PostgreSQL 버전 확인은 다음과 같이 할 수 있다. 

1
2
(venv) root@localhost:~/lispworks# pg_config --version
PostgreSQL 9.3.16
cs


Using PostgreSQL Roles and Databases


기본적으로 Postgres는 인증과 권한 관리를 위해 "roles" 이라고 불리는 컨셉을 사용한다. 통상적인 유닉스 스타일 계정과 유사하지만 Postgres 는 사용자와 그룹을 구별하지 않는다는 차이점이 있다. 

Postgres를 사용하기 위해서는 다음과 같이 해당 계정으로 로그인해야한다. 그리고 psql 을 통해 Postgres prompt 로 진입할 수 있다.

1
2
3
4
5
(venv) root@localhost:~/lispworks# sudo -i -u postgres
postgres@localhost:~$ psql
psql (9.3.19)
Type "help" for help.
postgres=#
cs

postgres 패스워드를 다음과 같이 변경한다.

1
2
3
4
5
6
7
8
9
10
11
 
postgres@localhost:~$ psql
psql (9.3.19)
Type "help" for help.
 
postgres=# \password
Enter new password:
Enter it again:
postgres=#
postgres=# \q
 
cs

How to safely change the “postgres” user password via “psql”

PostgreSQL 프롬프트는 다음과 같이 종료할 수 있다.

1
2
3
4
 
postgres-# \q
postgres@localhost:~$
 
cs


Create a New Role


postgres 리눅스 계정을 가지고 데이터베이스 시스템에 로그인할 수 있지만, 여기서 추가적인 role 을 어떻게 만드는지 알아본다.  Postgres 관리 role 과 연계된 postgres 리눅스 계정은 사용자와 데이터베이스를 생성할 수 있는 몇 가지 유틸리티에 접근할 수 있는 권한을 가지고 있다. 

새로운 role은 다음과 같이 만들 수 있다. 보는 바와 같이 2가지만 물어본다. 하나는 role 의 이름이고, 나머지 하나는 superuser 여부이다.   

1
2
3
4
5
6
 
postgres@localhost:~$ createuser --interactive
Enter name of role to add: alicia
Shall the new role be a superuser? (y/n) y
postgres@localhost:~$
 
cs

 PostgreSQL 9.3.20 Documentation - createuser


Create a New Database


기본값으로 Postgres 가 설치되면 role에 매칭되는 데이터베이스가 존재한다고 기본적으로 가정하게 된다. 예를 들어 test1 이라고 불리는 사용자를 가지고 있다면, 해당 role은 기본적으로 test1 이라고 불리는 데이터베이스에 접속할 수 있다. postgres 사용자로 접속하여 다음과 같이 간단하게 데이터베이스를 생성할 수 있다.

1
2
3
4
 
postgres@localhost:~$ createdb test1
postgres@localhost:~$
 
cs


Connect to Postgres with the New User


test1이라는 리눅스 계정을 가지고 있다고 가정하자. 만약 없다면 다음과 같이 만들면 된다. 그리고 Postgres 롤과 test1 이라는 데이터베이스를 만들었다고 하자. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
postgres@localhost:~$ su - root
암호:
root@localhost:~# adduser test1
'test1' 사용자를 추가 중...
새 그룹 'test1' (1003) 추가 ...
새 사용자 'test1' (1002) 을(를) 그룹 'test1' (으)로 추가 ...
'/home/test1' 홈 디렉터리를 생성하는 중...
'/etc/skel'에서 파일들을 복사하는 중...
새 UNIX 암호 입력:
새 UNIX 암호 재입력:
passwd: password updated successfully
Changing the user information for test1
Enter the new value, or press ENTER for the default
        Full Name []:
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
정보가 올바릅니까? [Y/n] y
root@localhost:~#
 
cs

그러면 방금 만든 test1 계정으로 접속해보자.

1
2
3
 
postgres@localhost:~$ sudo -- u test1
 
cs

접속과정에서 다음과 같은 오류 메시지가 발생하는 경우가 있다.

1
2
3
4
5
6
 
postgres@localhost:~$ sudo -- u test1
[sudo] password for postgres:
Sorry, try again.
[sudo] password for postgres:
 
cs

이 경우 http://www.antilibrary.org/1520 링크를 참조하여 postgres 계정을 등록해준다음 다음과 같이 해당 계정의 패스워드를 변경한다. 

1
2
3
4
5
6
7
8
 
root@localhost:~# sudo -u postgres psql postgres
psql (9.3.19)
Type "help" for help.
 
postgres=# alter user postgres with password '<New password>';
ALTER ROLE
 
cs

다시 접속해보면 정상적으로 연결이 됨을 알 수 있다.

1
2
3
4
 
root@localhost:~# sudo -i -u test1
test1@localhost:~$
 
cs

이제 test1 Postgres 롤을 통해  test1 데이터베이스에 접속할 수 있다.

1
2
3
4
5
6
7
 
test1@localhost:~$ psql
psql (9.3.19)
Type "help" for help.
 
test1=#
 
cs

다른 데이터베이스에 접속할 수 싶다면 다음과 같이 하면 된다.

1
2
test1=# psql -d postgres
 
cs

다음과 같이 현재 접속 정보를 조회할 수 있다. 

1
2
3
4
5
 
test1=# \conninfo
You are connected to database "test1" as user "test1" via socket in "/var/run/postgresql" at port "5432".
test1=#
 
cs


Create and Delete Tables


test1이라는 리눅스 계정을 가지고 있다고 가정하자. 만약 없다면 다음과 같이 만들면 된다. 그리고 Postgres 롤과 test1 이라는 데이터베이스를 만들었다고 하자. 

먼저 샘플로 사용할 테이블을 만들어보자. 기본 구조는 다음과 같다. 여기서 equipment ID의 경우 serial 타입을 갖도록 했는데, serial 타잎이라는 것은 자동으로 증가하는 정수를 의미한다. 그리고 equipment ID 에 PK 를 부여했다. 

그리고 생성된 테이블은 \d 를 통해 확인할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
test1=# CREATE TABLE playground (
 equip_id serial PRIMARY KEY,
 type varchar (50) NOT NULL,
 color varchar (25) NOT NULL,
 location varchar (25) check (location in ('north''south''west''east''northeast''southeast''northwest''southwest')),
 install_date date
);
CREATE TABLE
test1=# \d
                  List of relations
 Schema |          Name           |   Type   | Owner
--------+-------------------------+----------+-------
 public | playground              | table    | test1
 public | playground_equip_id_seq | sequence | test1
(2 rows)
 
test1=#
 
cs

보는 바와 같이 playground 테이블이 생성되었음을 알 수 있다. 그런데 여기 playground_equip_id_seq 라는 것도 보이는데, 이것은 equip_id 컬럼에 부여한 serial 타입을 의미하는 것이다. 이를 통해 시퀀스의 다음 번호를 추적한다. 테이블만 보려면 \dt 라고 타이핑하면 된다.

1
2
3
4
5
6
7
8
9
10
 
test1=# \dt
          List of relations
 Schema |    Name    | Type  | Owner
--------+------------+-------+-------
 public | playground | table | test1
(1 row)
 
test1=#
 
cs


Add, Query, and Delete Data in a Table


그럼 테이블에 데이터를 넣어보자. 아래와 같이 데이터를 넣을 수 있는데, 2가지를 조심해야 한다. 하나는 컬럼명에는 따옴표가 들어가서는 안되고, 값에만 따옴표가 들어가야 한다는 점이고, 다른 하나는 pk 인 equip_id 컬럼은 입력하지 않는다는 것이다. equip_id 는 자동적으로 값이 증가되면서 들어가는 serial 타입이기 때문이다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
test1=# INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2014-04-28');
INSERT 0 1
test1=# INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2010-08-16');
INSERT 0 1
test1=# select * from playground;
 equip_id | type  | color  | location  | install_date
----------+-------+--------+-----------+--------------
        1 | slide | blue   | south     | 2014-04-28
        2 | swing | yellow | northwest | 2010-08-16
(2 rows)
 
test1=#
 
cs

이제 타입이 slide 인 데이터를 삭제해보자. 

1
2
3
4
5
6
7
8
9
10
11
 
test1=# delete from playground where type = 'slide';
DELETE 1
test1=# select * from playground;
 equip_id | type  | color  | location  | install_date
----------+-------+--------+-----------+--------------
        2 | swing | yellow | northwest | 2010-08-16
(1 row)
 
test1=#
 
cs


How To Add and Delete Columns from a Table


컬럼의 추가, 삭제는 다음과 같이 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
test1=# alter table playground add last_maint date;
ALTER TABLE
test1=# select * from playground;
 equip_id | type  | color  | location  | install_date | last_maint
----------+-------+--------+-----------+--------------+------------
        2 | swing | yellow | northwest | 2010-08-16   |
(1 row)
 
test1=# alter table playground drop last_maint;
ALTER TABLE
test1=# select * from playground;
 equip_id | type  | color  | location  | install_date
----------+-------+--------+-----------+--------------
        2 | swing | yellow | northwest | 2010-08-16
(1 row)
 
test1=#
 
cs


How To Update Data in a Table


업데이트는 다음과 같이 할 수 있다. 

1
2
3
4
5
6
7
8
9
10
11
 
test1=# update playground set color = 'red' where type = 'swing';
UPDATE 1
test1=# select * from playground;
 equip_id | type  | color | location  | install_date
----------+-------+-------+-----------+--------------
        2 | swing | red   | northwest | 2010-08-16
(1 row)
 
test1=#
 
cs