如何使用Template创建数据库?

数据库关系型数据库技术服务知识库
问题描述

CREATE DATABASE 实际上是通过复制现有数据库来实现的,默认的安装后有两个模板数据库:template0 和 template1,那么两个模板在具体的使用上有什么区别?

问题分析

当用户创建数据库时,默认是从模板数据库 "template1" 克隆来的,所以通常我们可以定制 template1 数据库中的内容,后续创建的数据库就可以继承。 "template0" 是一个最简化的数据库模板,默认不接受任何客户连接。在极端场景下,如果所有数据库模板损坏,依旧可以使用 template0 来作为数据库模板。我们熟知的 pg_dump 逻辑备份工具,就使用了 template0 来作为模板。

问题验证

验证 template1 的使用场景

  1. 在 template1 中创建数据表 t1
postgres=# \c template1
You are now connected to database "template1" as user "postgres".
template1=# \d
Did not find any relations.
template1=# create table t1(id int);
CREATE TABLE
  1. 使用 create database 创建数据库 demo,发现里面会自动继承 template1 中的表 t1
postgres=# create database demo;
CREATE DATABASE

postgres=# \c demo
You are now connected to database "demo" as user "postgres".

# 继承template1中的数据表t1
postgres=# \d
        List of relations
 Schema | Name | Type  |  Owner   
--------+------+-------+----------
 public | t1   | table | postgres
(1 row)

验证 template0 的使用场景

  1. 使用如下命令备份数据库 demo
pg_dump -p 5436 -d demo -C -c -f demo_pg5436.sql

参数说明:
  -d, --dbname=DBNAME          database to dump
  -t, --table=PATTERN          dump the specified table(s) only
  -c, --clean                  clean (drop) database objects before recreating
  -C, --create                 include commands to create database in dump

  1. 查看备份文件内容,可以看出备份出来的 CREATE DATABASE 语句显示的指定了 template0 模板
[postgres@ip-10-0-0-22 ~]$ cat demo_pg5436.sql 
……
……
CREATE DATABASE demo WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


ALTER DATABASE demo OWNER TO postgres;

\connect demo
……
……
参考文档

https://www.postgresql.org/docs/12/manage-ag-templatedbs.html 如果您有其他问题,欢迎您联系火山引擎技术支持服务

23
0
0
0
相关产品
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论