创建新数据库时不会设置排序规则

lee*_*oon 2 postgresql collation postgresql-13

我正在尝试在 PostgreSQL 13 中设置新数据库的排序规则,但它似乎没有生效:

postgres=# CREATE DATABASE assets ENCODING 'UTF8' LC_COLLATE 'C' LC_CTYPE 'en_US.UTF-8';
CREATE DATABASE
postgres=# \l
                                      List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 assets    | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(4 rows)
Run Code Online (Sandbox Code Playgroud)

如何让新数据库反映我的排序规则更改?

Dan*_*ité 6

CREATE DATABASE问题中的语句将从默认模板数据库 复制新数据库 ,template1LC_COLLATEen_US.UTF-8。由于新数据库需要C排序规则,因此通常数据库创建会失败并出现以下错误:

CREATE DATABASE assets ENCODING 'UTF8' LC_COLLATE 'C' LC_CTYPE 'en_US.UTF-8';

ERROR:  new collation (C) is incompatible with the collation of the template database (en_US.UTF-8)
HINT:  Use the same collation as in the template database, or use template0 as template.
Run Code Online (Sandbox Code Playgroud)

这是因为 Postgres 不知道该template1数据库是否包含依赖于en_US.UTF-8字符串排序的对象(主要是索引)。如果它盲目地将其与C排序规则复制到新数据库中,这些索引将被损坏。

除了您没有收到该错误消息(这看起来很奇怪)这一事实之外,错误的提示部分中的建议正是您所需要的:添加TEMPLATE 'template0'CREATE DATABASE. template0与 相反template1,不能用自定义内容填充,因此它保证只包含与 Postgres 支持的任何排序规则和编码兼容的数据。