PostgreSQL 데이터베이스를 dump 명령등을 사용해서 파일로 저장하면 이전에 insert 해놓은 자료들을 찾아보기가 어렵습니다. 이런 경우는 DB의 이름을 변경해서 그대로 복사해 놓으면 자료를 찾아보기도 쉽고 작업하기도 편리 합니다.  

postgresqldatabase를 복사하기 위한 작업을 해보겠습니다.

 

먼저 알고 있는 명령어를 사용해서 작업을 시작해 봅니다.

 

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 TestDB    | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 |
 postgres  | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 |
 template0 | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(4 rows)

 

리스트에 나오는 TestDB를 다른 이름으로 복사하는 명령어는 아래와 같습니다.

 

CREATE DATABASE [new database] WITH TEMPLATE [old database] OWNER [owner];

 

TestDBTestDB2022라는 DB로 복사하려면

 

CREATE DATABASE TestDB2022 WITH TEMPLATE TestDB OWNER postgres;

 

이렇게 명령어를 입력하면 되겠네요.

 

 

postgres=# CREATE DATABASE TestDB2022 WITH TEMPLATE TestDB OWNER postgres;
오류:  "TestDB" 템플릿 데이터베이스 없음
postgres=#

 

그렇지만 대부분 오류가 발생하게 됩니다.

이유는 오류 내용과 같이 템플릿 데이터베이스가 아니기 때문 입니다.

 

postgres=# select datname, datistemplate from pg_database;
  datname  | datistemplate
-----------+---------------
 postgres  | f
 TestDB    | f
 template1 | t
 template0 | t
(4 rows)

 

TestDBdatistemplate 값이 f(false)입니다.

true로 변경을 합니다.

 

postgres=# ALTER DATABASE "TestDB" WITH IS_TEMPLATE = true;
ALTER DATABASE
postgres=#

 

이제 다시 TestDB를 복사해 봅니다.

 

postgres=# CREATE DATABASE "TestDB2022" WITH TEMPLATE "TestDB";
CREATE DATABASE
postgres=# \l
                                  List of databases
    Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
------------+----------+----------+-------------+-------------+-----------------------
 TestDB     | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 |
 TestDB2022 | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 |
 postgres   | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 |
 template0  | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
 template1  | postgres | UTF8     | ko_KR.UTF-8 | ko_KR.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
(5 rows)

 

 

복사가 잘 진행 되었습니다.

명령문에 CREATE DATABASE "TestDB2022" WITH TEMPLATE "TestDB";

쌍따옴표를 붙인 이유는 대소문자에 따라 Database 이름을 찾지 못하는 경우가 있습니다.

 

ALTER DATABASE "TestDB" WITH IS_TEMPLATE = false;

 

복사가 완료되면 기존 데이터베이스는 다시 templatefalse로 변경해 놓으면 작업은 완료 됩니다.

 

- copy coding -


+ Recent posts