PostgreSQL里包含两个标准系统数据库,template0和template1。
创建数据库时,CREATE DATABASE通过拷贝一个已有数据库进行工作。默认情况下,它拷贝名为template1的标准系统数据库 ,所以template1是创建新数据库的模板,如果给template1数据库增加对象,这些对象将被拷贝到后续创建的用户数据库中。

postgres=# \c template1
You are now connected to database "template1" as user "postgres".
template1=# \dt
List of relations
Schema | Name | Type | Owner
--------+------+-------+----------
public | ysl | table | postgres
(1 row)
template1=# create database sarah;
CREATE DATABASE
template1=# \c sarah
You are now connected to database "sarah" as user "postgres".
sarah=# \dt
List of relations
Schema | Name | Type | Owner
--------+------+-------+----------
public | ysl | table | postgres
(1 row)
系统里还有名为template0的第二个标准系统数据库。这个数据库包含和template1初始内容一样的数据,也就是说,只包含你的PostgreSQL版本预定义的标准对象。在数据库被初始化之后,不应该对template0做任何修改。通过指示CREATE DATABASE使用template0取代template1进行拷贝,你可以创建一个“纯净的”用户数据库,它不会包含任何template1中的任何对象。 在恢复一个pg_dump转储时非常方便:在一个完全干净的数据库中恢复以确保我们重建被转储数据库的正确内容,而不会和任何现在可能已经被加入到template1中的对象冲突。
而且可以在复制template0时指定新的编码和区域设置,但是template1的副本必须使用和它相同的设置。这是因为的template1可能包含编码相关或区域相关的数据,而template0中没有。
通过拷贝template0来创建一个数据库的方法
1.SQL环境
sarah=# CREATE DATABASE dbname TEMPLATE template0;
2.shell
[postgres@ysla ~]$ createdb -T template0 dbname
对于每一个数据库在pg_database中存在两个有用的标志: datistemplate和datallowconn列。datistemplate可以被设置来指示该数据库是不是要作为CREATE DATABASE的模板。如果设置了这个标志,那么该数据库可以被任何有 CREATEDB权限的用户克隆;如果没有被设置,那么只有超级用户和该数据库的拥有者可以克隆它。如果datallowconn为f,那么将不允许与该数据库建立任何新的连接(但已有的会话不会因为把该标志设置为f而被中止)。template0通常被标记为datallowconn = f来阻止对它的修改。template0和template1通常总是被标记为datistemplate = t
sarah=# select * from pg_database;
oid | datname | datdba | encoding | datcollate | datctype | datistemplate | datallowconn | datconnlimit | datlastsysoid | datfrozenxid | datminmxid | dattablespace | datacl
-------+-----------+--------+----------+-------------+-------------+---------------+--------------+--------------+---------------+--------------+------------+---------------+--------------
13593 | postgres | 10 | 6 | en_US.UTF-8 | en_US.UTF-8 | f | t | -1 | 13592 | 480 | 1 | 1663 |
16385 | dcdpdb | 10 | 6 | en_US.UTF-8 | en_US.UTF-8 | f | t | -1 | 13592 | 480 | 1 | 1663 |
1 | template1 | 10 | 6 | en_US.UTF-8 | en_US.UTF-8 | t | t | -1 | 13592 | 480 | 1 | 1663 | {=c/postgres,postgres=CTc/postgres}
13592 | template0 | 10 | 6 | en_US.UTF-8 | en_US.UTF-8 | t | f | -1 | 13592 | 480 | 1 | 1663 | {=c/postgres,postgres=CTc/postgres}
24583 | sarah | 10 | 6 | en_US.UTF-8 | en_US.UTF-8 | f | t | -1 | 13592 | 480 | 1 | 1663 |
(5 rows)




