1. 模式
模式在PostgreSQL中,類似於目錄。同一數據庫,不同模式下,可以存放相同名稱的數據表。模式下,通常可以存放不同的數據對象,如表、視圖、函數、存儲過程、觸發器、索引等。默認情況下會使用系統創建的public作爲數據表的schema。
postgres=# \dn
List of schemas
Name | Owner
--------+----------
public | postgres
(1 row)
通常我們可以使用create
關鍵字直接創建模式,通過[schema_name].table_name
來指定需要將數據表創建在哪個模式下。
create schema myschema;
create table myschema.tb_user (
id serial primary key);
模式在刪除時使用drop
關鍵字,需要確保模式中不存在任何數據庫對象,否則需要使用cascade
進行級聯刪除。
2. Exclusion約束
PostgreSQL也提供了許多約束,如主鍵、唯一、不爲空等等。Exclusion是一種排他約束。
- 要獲得擴展支持,首先我們需要安裝PostgreSQL的另一組件,需要根據PostgreSQL的版本進行選擇。執行
yum -y install postgresql12-contrib.x86_64
即可。 - 爲數據庫創建擴展。
postgres=# create extension btree_gist;
CREATE EXTENSION
- 創建exclusion約束。
postgres=# create table public.tb_employee (
postgres(# id serial primary key,
postgres(# name text,
postgres(# age integer,
postgres(# exclude using gist (name with =, age with <>)
postgres(# );
CREATE TABLE
- name相同,age不相同則不允許插入
postgres=# insert into tb_employee(name, age) values('Zhangsan', 12);
INSERT 0 1
postgres=# insert into tb_employee(name, age) values('Zhangsan', 13);
ERROR: conflicting key value violates exclusion constraint "tb_employee_name_age_excl"
DETAIL: Key (name, age)=(Zhangsan, 13) conflicts with existing key (name, age)=(Zhangsan, 12).
postgres=# insert into tb_employee(name, age) values('Lisi', 12);
INSERT 0 1
3.存儲過程(procedure)
PostgreSQL官方支持PL/pgSQL、PL/Tcl、PL/Perl和PL/Python等過程語言,同時還支持第三方提供的過程語言,如PL/Java、PL/PHP、PL/Py、PL/R、PL/Ruby、PL/Scheme、PL/sh。