PostgreSQL におけるデータベース作成とは、既存のデータベースの複製を作ることです。デフォルトでは template1 という名前のデータベースが複製元となります。
さて、PostgreSQLのインストール直後に template1 のエンコーディングが SQL_ASCII になっていることがあります。
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------+----------+-----------+-------------+-------------+-----------------------
postgres | postgres | SQL_ASCII | C | C |
template0 | postgres | SQL_ASCII | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | SQL_ASCII | C | C |
Web アプリケーションのバックエンドとして使う場合、エンコーディングとして UTF-8 を採用することが多いので、このままだと不便です。
psql のコンソールで次のステートメントを発行すれば、template1 のエンコーディングを UTF-8 に(ついでに、ロケールをに ja_JP に)変更できます。
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1'; DROP DATABASE template1; CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF-8' LC_CTYPE = 'ja_JP.UTF-8'; UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1';
結果は、この通り:
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------+----------+-----------+-------------+-------------+-----------------------
postgres | postgres | SQL_ASCII | C | C |
template0 | postgres | SQL_ASCII | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | ja_JP.UTF-8 | ja_JP.UTF-8 |