一個數據庫包含一個或多個模式,而模式又包含表、序列、函數等,不同的模式可以包含相同名稱的表、序列、函數等。模式本質上是命名空間,就像人的姓氏一樣。一個用戶只要有權限,連接到數據庫后,可一次訪問該數據庫的任何模式下的對象。新建一個數據庫會默認創建一個public模式,后續操作數據庫對象如果沒指定模式,則默認為public。例如之前創建的school數據庫
school=# \dn+
List of schemas
Name | Owner | Access privileges | Description
--------+----------+----------------------+------------------------
public | postgres | postgres=UC/postgres+| standard public schema
| | =UC/postgres |
(1 row)
一、創建模式
語法:
school=# \h create schema
Command: CREATE SCHEMA
Description: define a new schema
Syntax:
CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [ schema_element [ ... ] ]
CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ ... ] ]
CREATE SCHEMA IF NOT EXISTS schema_name [ AUTHORIZATION user_name ]
CREATE SCHEMA IF NOT EXISTS AUTHORIZATION user_name
參數:
schema_name
模式名稱,缺省使用user_name,且不能以pg_開頭。
user_name
模式屬於的用戶,缺省為執行命令的用戶。
schema_element
一條SQL語句,即創建模式后,在該模式下創建一個數據庫對象。當前支持的子句有CREATE
TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE, CREATE TRIGGER and GRANT。
IF NOT EXISTS
如果模式已存在,使用該選項不會拋出錯誤。使用此選項不能使用schema_element子句。
示例
create schema schema_test authorization test1 create table tbl_test(a int) create view view_test as select * from tbl_test;
訪問模式下數據庫對象在模式和數據庫對象之間加一個句點即可
school=# select * from schema_test.tbl_test ; a --- (0 rows) school=# select * from schema_test.view_test ; a --- (0 rows)
二、模式修改
語法:
school=# \h alter schema
Command: ALTER SCHEMA
Description: change the definition of a schema
Syntax:
ALTER SCHEMA name RENAME TO new_name
ALTER SCHEMA name OWNER TO new_owner
參數:
name
模式名稱
new_name
模式新的名稱,同樣新名稱也不能以pg_開頭
new_owner
模式新用戶名稱
示例
school=# alter schema schema_test owner to postgres ; ALTER SCHEMA school=# alter schema schema_test rename to test; ALTER SCHEMA school=# \dn+ List of schemas Name | Owner | Access privileges | Description --------+----------+----------------------+------------------------ public | postgres | postgres=UC/postgres+| standard public schema | | =UC/postgres | test | postgres | | (2 rows)
三、模式刪除
語法:
school=# \h drop schema
Command: DROP SCHEMA
Description: remove a schema
Syntax:
DROP SCHEMA [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
參數:
IF EXISTS
如果模式不存在,不會拋出錯誤。
name
模式名稱。
CASCADE
自動刪除該模式下數據庫對象。
RESTRICT
如果該模式下還存在數據庫對象,則不允許刪除該模式,RESTRICT為缺省值。
示例:
school=# drop schema test; ERROR: cannot drop schema test because other objects depend on it DETAIL: table test.tbl_test depends on schema test view test.view_test depends on schema test HINT: Use DROP ... CASCADE to drop the dependent objects too.
school=# drop schema test cascade; NOTICE: drop cascades to 2 other objects DETAIL: drop cascades to table test.tbl_test drop cascades to view test.view_test DROP SCHEMA