紀錄一下處理 postgresql 的編碼操作。
第一次安裝
在 Debian 下安裝 postgresql 的時候會根據系統預設的語系 (locale) 建立預設的編碼,包含 encoding、LC_COLATE、LC_CTYPE。如果希望指定資料庫預設的編碼(這邊以 zh_TW.UTF-8 為例),那就照以下步驟處理:
1. 產生對應的語系
編輯 /etc/locale.gen 取消 zh_TW.UTF-8 UTF-8 這一行的註解後,執行指令產生對應的語系:
locale-gen2. 安裝 postgresql-common
執行:
apt install postgresql-common -y修改 /etc/postgresql-common/createcluster.conf
# 將被註解的 initdb_options = '' 取消註解並改成
initdb_options = '--locale=zh_TW.UTF-8 --encoding=UTF8'3. 安裝 postgresql:
apt install postgresql -y使用 psql 執行 \l 查看即可確認:
postgres=# \l
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
-----------+----------+----------+-----------------+-------------+-------------+--------+-----------+-----------------------
postgres | postgres | UTF8 | libc | zh_TW.UTF-8 | zh_TW.UTF-8 | | |
template0 | postgres | UTF8 | libc | zh_TW.UTF-8 | zh_TW.UTF-8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | libc | zh_TW.UTF-8 | zh_TW.UTF-8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
(3 rows)
postgres=#已經安裝,想重建資料庫
如果因為各種意外,不小心安裝了 postgresql 卻忘記先設定語系,也可以照下面的步驟重建。我略過了建立語系的步驟,請參考前面步驟…
1. 停止 postgresql 服務
systemctl stop postgresql.service2. 刪除 postgresql cluster
# 17 指的是你的 postgresql 的版本
pg_dropcluster 17 main --stop3. 修改 createcluster.conf
# 將被註解的 initdb_options = '' 取消註解並改成
initdb_options = '--locale=zh_TW.UTF-8 --encoding=UTF8'4. 建立 postgresql cluster
# 17 指的是你的 postgresql 的版本
pg_createcluster 17 main --start5. 啟動 postgresql 服務
systemctl start postgresql.service