PostgreSql 数据库分配资源供新上线系统使用

213 阅读2分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

不同于 oracle 数据库,在数据库里新建一个用户就可以供新上线系统使用,即使不分配表空间也有默认表空间可使用, postgresql 数据库还需要创建数据库,schema,比如要新上线一个 OA 系统,如何在 postgresql 数据库中创建资源呢?
oracle 建用户可参考:可参考:juejin.cn/post/699239…

一、规划

postgresql 中,数据表是存放在 schema 下的,schema 是数据库下的,数据库是实例下的。

  • 确定要创建的数据库名:oa。
  • 确定要创建的 SCHEMA 名:oa 数据库下的不同模块的数据可以存放在不同的 SCHEMA 下,如:办公流程的数据表可以存放在 op SCHEMA 下,人员管理的数据表可以存放在 em SCHEMA 下,制度管理的数据存放在 rl SCHEMA 下。(当然不想分的这么细的话也可以直接在 oa 库下创建一个名为 oa 的 SCHEMA,用来存在所有数据表)
  • 确定连接管理 SCHEMA 下数据表的用户:op,em,rl(建议同 SCHEMA 名对应起来,这样创建表可以不用前缀 SCHEMA 名就创建在对应的 SCHEMA 下)

二、建用户

管理员连入数据库,创建用户。

CREATE USER op password '123';
CREATE USER em password '123';
CREATE USER rl password '123';


[postgres@dj ~]$ psql
psql (12.4)
Type "help" for help.
postgres=#CREATE USER op password '123';
CREATE ROLE
postgres=# CREATE USER em password '123';
CREATE ROLE
postgres=# CREATE USER rl password '123';
CREATE ROLE

三、建库

继续用管理员用户创建数据库,建议添加注释,方便后续人员维护。

CREATE DATABASE oa;
COMMENT ON DATABASE oa IS 'OA 数据库';

oa=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 oa        | 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)

四、建 SCHEMA

管理员用户连入 oa 数据库,创建 SCHEMA,建议添加注释,方便后续人员维护。

\c oa
CREATE SCHEMA op;
COMMENT ON SCHEMA op IS '办公流程 SCHEMA';
CREATE SCHEMA em;
COMMENT ON SCHEMA em IS '人员管理 SCHEMA';
CREATE SCHEMA rl;
COMMENT ON SCHEMA rl IS '制度管理 SCHEMA';
alter schema em owner to em;
alter schema op owner to op;
alter schema rl owner to rl;

oa=# \dn+
                          List of schemas
  Name  |  Owner   |  Access privileges   |      Description
--------+----------+----------------------+------------------------
 em     | em       |                      | 人员管理 SCHEMA
 op     | op       |                      | 办公流程 SCHEMA
 public | postgres | postgres=UC/postgres+| standard public schema
        |          | =U/postgres          |
 rl     | rl       |                      | 制度管理 SCHEMA
(4 rows)

五、回收 public SCHEMA 权限sql

revoke create on schema public from public;