PostgreSQL: 综合项目:电商数据库系统从零搭建
最后更新:2026-08-26
1. 你将学到
- 完成电商数据库需求分析到上线的全流程
- 设计 8 大业务模块的 ER 图与表结构
- 综合运用索引、JSONB、全文搜索、物化视图、存储过程、RLS、分区、FDW、pgvector 等全部技术
- 编写完整的数据库初始化脚本
- 掌握 PG vs MySQL 选型报告的编写方法
2. 故事
Bob 和 Alice 创业做中东跨境电商平台。需求复杂:阿拉伯语全文搜索、JSONB 动态商品属性、按月分区订单表、行级安全隔离租户、AI 商品推荐。他们用 PostgreSQL 一站式解决——tsvector 处理阿拉伯语搜索、jsonb 存灵活 SKU、声明式分区管理亿级订单、pgvector 做语义推荐、postgres_fdw 从旧 PG 迁移数据。一个 PG 数据库替代了 MySQL + Elasticsearch + Redis + 推荐引擎。
3. Concept:需求分析与架构设计
(1) 业务模块划分
| 模块 | 核心表 | 关键特性 |
|---|---|---|
| 用户系统 | users, user_addresses | RLS 行级安全、bcrypt 密码 |
| 商品分类与商品 | categories, products | JSONB 动态属性、全文搜索 |
| 订单与订单项 | orders, order_items | 按月 RANGE 分区 |
| 购物车 | cart_items | UPSERT 高并发 |
| 支付记录 | payments | 枚举类型、审计追踪 |
| 物流跟踪 | shipments, shipment_events | 时序数据、JSONB 事件 |
| 评价与评分 | reviews | 星级聚合、GIN 索引 |
| 数据统计报表 | mv_daily_sales 等 | 物化视图、定时刷新 |
(2) 完整 ER 图
erDiagram
USERS ||--o{ USER_ADDRESSES : "has"
USERS ||--o{ ORDERS : "places"
USERS ||--o{ CART_ITEMS : "has"
USERS ||--o{ REVIEWS : "writes"
CATEGORIES ||--o{ CATEGORIES : "parent"
CATEGORIES ||--o{ PRODUCTS : "contains"
PRODUCTS ||--o{ ORDER_ITEMS : "included_in"
PRODUCTS ||--o{ CART_ITEMS : "added_to"
PRODUCTS ||--o{ REVIEWS : "reviewed_in"
ORDERS ||--o{ ORDER_ITEMS : "contains"
ORDERS ||--o{ PAYMENTS : "paid_by"
ORDERS ||--o{ SHIPMENTS : "shipped_via"
SHIPMENTS ||--o{ SHIPMENT_EVENTS : "tracked_by"
USERS {
bigint id PK
text email UK
text password_hash
text role
timestamptz created_at
}
USER_ADDRESSES {
bigint id PK
bigint user_id FK
text address_line
text city
text country
}
CATEGORIES {
int id PK
text name
int parent_id FK
int sort_order
}
PRODUCTS {
bigint id PK
text name
text name_ar
int category_id FK
numeric price
jsonb attributes
tsvector search_vector
vector embedding
}
ORDERS {
bigint id PK
bigint user_id FK
date order_date
numeric total_amount
text status
}
ORDER_ITEMS {
bigint id PK
bigint order_id FK
bigint product_id FK
int quantity
numeric unit_price
}
CART_ITEMS {
bigint id PK
bigint user_id FK
bigint product_id FK
int quantity
}
PAYMENTS {
bigint id PK
bigint order_id FK
text method
numeric amount
text status
timestamptz paid_at
}
SHIPMENTS {
bigint id PK
bigint order_id FK
text carrier
text tracking_code
text status
}
SHIPMENT_EVENTS {
bigint id PK
bigint shipment_id FK
text event_type
jsonb metadata
timestamptz event_time
}
REVIEWS {
bigint id PK
bigint user_id FK
bigint product_id FK
int rating
text comment
}
(3) PG vs MySQL 选型报告
| 维度 | PostgreSQL | MySQL |
|---|---|---|
| JSONB 动态属性 | 原生 jsonb + GIN 索引 + 运算符 | JSON 类型但索引弱 |
| 全文搜索 | 内置 tsvector/tsquery 多语言 | 无原生,需 Elasticsearch |
| 向量搜索 | pgvector 原生扩展 | 需外部服务 |
| 分区 | 声明式 RANGE/LIST/HASH | 8.0+ 支持,功能较弱 |
| 行级安全 | RLS 策略 | 不支持 |
| 物化视图 | 原生支持 + 定时刷新 | 不支持 |
| 扩展生态 | 丰富(PostGIS/pgcrypto/FDW) | 插件较少 |
| 复杂查询 | 窗口函数/CTE/LATERAL | 8.0+ 逐步支持 |
| 运维成熟度 | 高,autovacuum/PITR | 高,主从复制成熟 |
| 社区活跃度 | 增长最快 | 最大用户群 |
结论:本项目需要 JSONB 动态属性、全文搜索、向量搜索、RLS、分区、物化视图——PostgreSQL 全部原生支持,MySQL 需 4+ 个外部中间件,故选 PostgreSQL。
4. 操作:模块 1 - 用户系统
(1) 用户表与地址表
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'customer'
CHECK (role IN ('customer','vendor','admin')),
tenant_id BIGINT DEFAULT 1,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE user_addresses (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
address_line TEXT NOT NULL,
city TEXT NOT NULL,
country TEXT NOT NULL,
is_default BOOLEAN DEFAULT false
);
▶ 示例:RLS 行级安全隔离租户
-- Enable RLS on users table
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- Tenant isolation: users can only see same tenant
CREATE POLICY tenant_isolation ON users
USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- Admin can see all
CREATE POLICY admin_all_access ON users
USING (role = 'admin');
-- Set tenant context per session
SET app.tenant_id = '1';
SELECT * FROM users;
输出:
CREATE TABLE
▶ 示例:密码哈希注册
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Register with bcrypt hash
INSERT INTO users (email, password_hash, role, tenant_id)
VALUES (
'alice@example.com',
crypt('SecurePass123', gen_salt('bf')),
'customer',
1
);
-- Verify login
SELECT id, role FROM users
WHERE email = 'alice@example.com'
AND password_hash = crypt('SecurePass123', password_hash);
输出:
INSERT 0 1
5. 操作:模块 2 - 商品分类与商品
▶ 示例:自引用分类树
CREATE TABLE categories (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
name_ar TEXT,
parent_id INT REFERENCES categories(id),
sort_order INT DEFAULT 0
);
INSERT INTO categories (name, name_ar, parent_id, sort_order) VALUES
('Electronics', 'إلكترونيات', NULL, 1),
('Phones', 'هواتف', 1, 1),
('Laptops', 'حاسبات', 1, 2),
('Clothing', 'ملابس', NULL, 2);
-- Recursive query: category tree
WITH RECURSIVE cat_tree AS (
SELECT id, name, name_ar, parent_id, 0 AS level
FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.name_ar, c.parent_id, ct.level + 1
FROM categories c JOIN cat_tree ct ON c.parent_id = ct.id
)
SELECT repeat(' ', level) || name AS tree, name_ar
FROM cat_tree ORDER BY level, sort_order;
输出:
INSERT 0 1
▶ 示例:商品表 JSONB 动态属性
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL,
name_ar TEXT,
category_id INT NOT NULL REFERENCES categories(id),
price NUMERIC(12,2) NOT NULL,
attributes JSONB DEFAULT '{}',
search_vector TSVECTOR GENERATED ALWAYS AS (
setweight(to_tsvector('simple', coalesce(name, '')), 'A') ||
setweight(to_tsvector('simple', coalesce(name_ar, '')), 'B')
) STORED,
embedding vector(1536)
);
输出:
CREATE TABLE
▶ 示例:JSONB 属性查询
-- Insert with dynamic attributes
INSERT INTO products (name, name_ar, category_id, price, attributes) VALUES
('iPhone 15 Pro', 'آيفون 15 برو', 2, 1199.00,
'{"color": "titanium", "storage": "256GB", "5g": true}'::jsonb),
('MacBook Air M3', 'ماك بوك إير', 3, 1299.00,
'{"color": "midnight", "ram": "16GB", "screen": "15 inch"}'::jsonb);
-- Find 5G phones under 1200 USD
SELECT name, price, attributes->>'storage' AS storage
FROM products
WHERE attributes @> '{"5g": true}'::jsonb
AND price < 1200;
-- GIN index for JSONB containment queries
CREATE INDEX idx_products_attrs ON products USING GIN (attributes);
输出:
INSERT 0 1
▶ 示例:全文搜索(含阿拉伯语)
-- GIN index for full-text search
CREATE INDEX idx_products_search ON products USING GIN (search_vector);
-- Search in English or Arabic
SELECT name, name_ar, ts_rank(search_vector, q) AS rank
FROM products, plainto_tsquery('simple', 'iphone') q
WHERE search_vector @@ q
ORDER BY rank DESC;
-- Arabic search
SELECT name, name_ar
FROM products, plainto_tsquery('simple', 'آيفون') q
WHERE search_vector @@ q;
输出:
CREATE TABLE
▶ 示例:pgvector 相似商品推荐
-- HNSW index for vector search
CREATE INDEX idx_products_embedding ON products
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Find similar products
SELECT p2.name, p2.price,
p2.embedding <=> p1.embedding AS distance
FROM products p1
CROSS JOIN LATERAL (
SELECT * FROM products
WHERE id != p1.id
ORDER BY embedding <=> p1.embedding
LIMIT 3
) p2
WHERE p1.name = 'iPhone 15 Pro';
输出:
CREATE TABLE
6. 操作:模块 3 - 订单与订单项
▶ 示例:按月 RANGE 分区订单表
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY,
user_id BIGINT NOT NULL REFERENCES users(id),
order_date DATE NOT NULL DEFAULT current_date,
total_amount NUMERIC(12,2) DEFAULT 0,
status TEXT DEFAULT 'pending'
CHECK (status IN ('pending','paid','shipped','completed','cancelled')),
created_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (id, order_date)
) PARTITION BY RANGE (order_date);
CREATE TABLE orders_2024_01 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
CREATE TABLE orders_2024_02 PARTITION OF orders
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');
CREATE TABLE orders_2024_03 PARTITION OF orders
FOR VALUES FROM ('2024-03-01') TO ('2024-04-01');
CREATE TABLE orders_default PARTITION OF orders DEFAULT;
CREATE TABLE order_items (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL,
order_date DATE NOT NULL,
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INT NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(12,2) NOT NULL,
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
CREATE INDEX idx_orders_user ON orders (user_id, order_date);
CREATE INDEX idx_order_items_order ON order_items (order_id, order_date);
输出:
CREATE TABLE
▶ 示例:订单创建与金额计算
-- Create order
WITH new_order AS (
INSERT INTO orders (user_id, order_date, status)
VALUES (1, '2024-01-15', 'pending')
RETURNING id, order_date
)
INSERT INTO order_items (order_id, order_date, product_id, quantity, unit_price)
SELECT new_order.id, new_order.order_date, p.id, 2, p.price
FROM new_order, products p
WHERE p.name = 'iPhone 15 Pro';
-- Update order total
UPDATE orders o SET total_amount = (
SELECT SUM(quantity * unit_price)
FROM order_items oi
WHERE oi.order_id = o.id AND oi.order_date = o.order_date
)
WHERE o.id = 1 AND o.order_date = '2024-01-15';
输出:
result
----------
42.50
(1 row)
7. 操作:模块 4 - 购物车
▶ 示例:UPSERT 购物车
CREATE TABLE cart_items (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INT NOT NULL DEFAULT 1 CHECK (quantity > 0),
added_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (user_id, product_id)
);
-- Add or update cart item (UPSERT)
INSERT INTO cart_items (user_id, product_id, quantity)
VALUES (1, 1, 1)
ON CONFLICT (user_id, product_id)
DO UPDATE SET quantity = cart_items.quantity + EXCLUDED.quantity;
-- View cart with product details
SELECT p.name, p.price, ci.quantity,
p.price * ci.quantity AS line_total
FROM cart_items ci
JOIN products p ON ci.product_id = p.id
WHERE ci.user_id = 1;
输出:
INSERT 0 1
8. 操作:模块 5 - 支付记录
▶ 示例:支付表与枚举类型
CREATE TYPE payment_method AS ENUM ('credit_card', 'paypal', 'bank_transfer', 'cod');
CREATE TYPE payment_status AS ENUM ('pending', 'completed', 'failed', 'refunded');
CREATE TABLE payments (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL,
order_date DATE NOT NULL,
method payment_method NOT NULL,
amount NUMERIC(12,2) NOT NULL,
status payment_status DEFAULT 'pending',
paid_at TIMESTAMPTZ,
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
-- Record successful payment
INSERT INTO payments (order_id, order_date, method, amount, status, paid_at)
VALUES (1, '2024-01-15', 'credit_card', 2398.00, 'completed', now());
-- Update order status after payment
UPDATE orders SET status = 'paid'
WHERE id = 1 AND order_date = '2024-01-15';
输出:
INSERT 0 1
9. 操作:模块 6 - 物流跟踪
▶ 示例:物流表与 JSONB 事件
CREATE TABLE shipments (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL,
order_date DATE NOT NULL,
carrier TEXT NOT NULL,
tracking_code TEXT NOT NULL UNIQUE,
status TEXT DEFAULT 'created'
CHECK (status IN ('created','in_transit','delivered','failed')),
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
CREATE TABLE shipment_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
shipment_id BIGINT NOT NULL REFERENCES shipments(id),
event_type TEXT NOT NULL,
metadata JSONB DEFAULT '{}',
event_time TIMESTAMPTZ DEFAULT now()
);
-- Track shipment with events
INSERT INTO shipments (order_id, order_date, carrier, tracking_code)
VALUES (1, '2024-01-15', 'DHL Express', 'DHL123456789');
INSERT INTO shipment_events (shipment_id, event_type, metadata) VALUES
(1, 'picked_up', '{"location": "Dubai Warehouse"}'::jsonb),
(1, 'in_transit', '{"location": "Bahrain Hub", "eta": "2024-01-18"}'::jsonb),
(1, 'out_for_delivery', '{"location": "Riyadh"}'::jsonb);
-- Shipment timeline
SELECT se.event_time, se.event_type, se.metadata->>'location' AS location
FROM shipment_events se
WHERE se.shipment_id = 1
ORDER BY se.event_time;
输出:
INSERT 0 1
10. 操作:模块 7 - 评价与评分
▶ 示例:评价表与星级聚合
CREATE TABLE reviews (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
product_id BIGINT NOT NULL REFERENCES products(id),
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (user_id, product_id)
);
INSERT INTO reviews (user_id, product_id, rating, comment) VALUES
(1, 1, 5, 'Excellent phone, fast delivery'),
(2, 1, 4, 'Good but expensive'),
(3, 2, 5, 'Best laptop ever');
-- Product rating summary with window function
SELECT p.name,
COUNT(r.id) AS review_count,
AVG(r.rating)::numeric(3,2) AS avg_rating,
COUNT(r.id) FILTER (WHERE r.rating = 5) AS five_star,
COUNT(r.id) FILTER (WHERE r.rating = 4) AS four_star
FROM products p
LEFT JOIN reviews r ON r.product_id = p.id
GROUP BY p.id, p.name;
输出:
count
-------
5
(1 row)
11. 操作:模块 8 - 数据统计报表
▶ 示例:物化视图日报
CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT order_date,
COUNT(DISTINCT user_id) AS unique_buyers,
COUNT(*) AS order_count,
SUM(total_amount) AS daily_revenue,
AVG(total_amount)::numeric(12,2) AS avg_order_value
FROM orders
WHERE status = 'completed'
GROUP BY order_date
ORDER BY order_date;
CREATE UNIQUE INDEX idx_mv_daily_sales_date ON mv_daily_sales (order_date);
-- Refresh daily (can be scheduled with pg_cron)
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_sales;
-- Top revenue days
SELECT order_date, daily_revenue, order_count
FROM mv_daily_sales
ORDER BY daily_revenue DESC
LIMIT 10;
输出:
count
-------
5
(1 row)
▶ 示例:品类销售物化视图
CREATE MATERIALIZED VIEW mv_category_sales AS
SELECT c.name AS category,
p.name AS product_name,
SUM(oi.quantity) AS total_sold,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
JOIN categories c ON p.category_id = c.id
JOIN orders o ON oi.order_id = o.id AND oi.order_date = o.order_date
WHERE o.status = 'completed'
GROUP BY c.name, p.name
ORDER BY revenue DESC;
REFRESH MATERIALIZED VIEW mv_category_sales;
输出:
result
----------
42.50
(1 row)
12. 操作:存储过程与自动化
▶ 示例:订单创建存储过程
CREATE OR REPLACE PROCEDURE create_order(
p_user_id BIGINT,
p_items JSONB
)
LANGUAGE plpgsql AS
DECLARE
v_order_id BIGINT;
v_order_date DATE := current_date;
v_item JSONB;
BEGIN
INSERT INTO orders (user_id, order_date, status)
VALUES (p_user_id, v_order_date, 'pending')
RETURNING id INTO v_order_id;
FOR v_item IN SELECT * FROM jsonb_array_elements(p_items)
LOOP
INSERT INTO order_items (order_id, order_date, product_id, quantity, unit_price)
VALUES (v_order_id, v_order_date,
(v_item->>'product_id')::bigint,
(v_item->>'quantity')::int,
(SELECT price FROM products WHERE id = (v_item->>'product_id')::bigint));
END LOOP;
UPDATE orders SET total_amount = (
SELECT SUM(quantity * unit_price) FROM order_items
WHERE order_id = v_order_id AND order_date = v_order_date
) WHERE id = v_order_id AND order_date = v_order_date;
COMMIT;
END;
;
-- Call procedure
CALL create_order(1, '[
{"product_id": 1, "quantity": 1},
{"product_id": 2, "quantity": 2}
]'::jsonb);
输出:
result
----------
42.50
(1 row)
▶ 示例:自动生成分区的存储过程
CREATE OR REPLACE FUNCTION maintain_order_partitions()
RETURNS VOID AS
DECLARE
v_next_month DATE;
v_part_name TEXT;
BEGIN
v_next_month := date_trunc('month', current_date + interval '1 month')::date;
v_part_name := 'orders_' || to_char(v_next_month, 'YYYY_MM');
IF NOT EXISTS (
SELECT 1 FROM pg_class WHERE relname = v_part_name
) THEN
EXECUTE format(
'CREATE TABLE %I PARTITION OF orders
FOR VALUES FROM (%L) TO (%L)',
v_part_name,
v_next_month,
(v_next_month + interval '1 month')::date
);
END IF;
-- Detach partitions older than 2 years
FOR v_part_name IN
SELECT relname FROM pg_class
WHERE relname LIKE 'orders_20__%'
AND relkind = 'r'
AND relname < 'orders_' || to_char(current_date - interval '2 years', 'YYYY_MM')
LOOP
EXECUTE format('ALTER TABLE orders DETACH PARTITION %I', v_part_name);
END LOOP;
END;
LANGUAGE plpgsql;
输出:
CREATE TABLE
13. 操作:FDW 数据迁移与 PITR 备份
▶ 示例:postgres_fdw 从旧 PG 迁移
CREATE EXTENSION IF NOT EXISTS postgres_fdw;
CREATE SERVER legacy_pg FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '10.0.1.50', port '5432', dbname 'legacy_shop');
CREATE USER MAPPING FOR current_user SERVER legacy_pg
OPTIONS (user 'migrate_user', password 'secure_pass');
IMPORT FOREIGN SCHEMA public LIMIT TO (old_users, old_products)
FROM SERVER legacy_pg INTO legacy;
-- Migrate users with password re-hash
INSERT INTO users (email, password_hash, role, tenant_id, created_at)
SELECT email, crypt(raw_password, gen_salt('bf')), 'customer', 1, created_at
FROM legacy.old_users
ON CONFLICT (email) DO NOTHING;
输出:
INSERT 0 1
▶ 示例:PITR 备份策略
# Base backup
pg_basebackup -D /backup/base -Ft -z -P
# Archive WAL (postgresql.conf)
wal_level = replica
archive_mode = on
archive_command = 'cp %p /backup/wal/%f'
# Restore to point in time
pg_restore --target-time='2024-03-15 14:30:00' -d shop_db /backup/base
输出:
# 命令执行成功
| 策略 | 频率 | 保留 | 恢复时间 |
|---|---|---|---|
| pg_basebackup 全量 | 每日 | 7 天 | 30-60 min |
| WAL 归档 | 持续 | 7 天 | 任意时间点 |
| 逻辑备份 pg_dump | 每周 | 4 周 | 1-4 hours |
14. 综合示例
-- Complete e-commerce database initialization script
-- Module 1: User system
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'customer'
CHECK (role IN ('customer','vendor','admin')),
tenant_id BIGINT DEFAULT 1,
created_at TIMESTAMPTZ DEFAULT now()
);
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON users
USING (tenant_id = current_setting('app.tenant_id')::bigint);
CREATE TABLE user_addresses (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
address_line TEXT NOT NULL, city TEXT NOT NULL, country TEXT NOT NULL,
is_default BOOLEAN DEFAULT false
);
-- Module 2: Categories & Products
CREATE TABLE categories (
id SERIAL PRIMARY KEY, name TEXT NOT NULL,
name_ar TEXT, parent_id INT REFERENCES categories(id),
sort_order INT DEFAULT 0
);
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL, name_ar TEXT,
category_id INT NOT NULL REFERENCES categories(id),
price NUMERIC(12,2) NOT NULL,
attributes JSONB DEFAULT '{}',
search_vector TSVECTOR GENERATED ALWAYS AS (
setweight(to_tsvector('simple', coalesce(name,'')), 'A') ||
setweight(to_tsvector('simple', coalesce(name_ar,'')), 'B')
) STORED,
embedding vector(1536)
);
CREATE INDEX idx_products_attrs ON products USING GIN (attributes);
CREATE INDEX idx_products_search ON products USING GIN (search_vector);
CREATE INDEX idx_products_embedding ON products
USING hnsw (embedding vector_cosine_ops) WITH (m=16, ef_construction=64);
-- Module 3: Orders (monthly partitioned)
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY,
user_id BIGINT NOT NULL REFERENCES users(id),
order_date DATE NOT NULL DEFAULT current_date,
total_amount NUMERIC(12,2) DEFAULT 0,
status TEXT DEFAULT 'pending'
CHECK (status IN ('pending','paid','shipped','completed','cancelled')),
created_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (id, order_date)
) PARTITION BY RANGE (order_date);
CREATE TABLE orders_2024_q1 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
CREATE TABLE orders_default PARTITION OF orders DEFAULT;
CREATE TABLE order_items (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL, order_date DATE NOT NULL,
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INT NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(12,2) NOT NULL,
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
-- Module 4: Cart
CREATE TABLE cart_items (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
product_id BIGINT NOT NULL REFERENCES products(id),
quantity INT NOT NULL DEFAULT 1, added_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (user_id, product_id)
);
-- Module 5: Payments
CREATE TYPE payment_method AS ENUM ('credit_card','paypal','bank_transfer','cod');
CREATE TYPE payment_status AS ENUM ('pending','completed','failed','refunded');
CREATE TABLE payments (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL, order_date DATE NOT NULL,
method payment_method NOT NULL, amount NUMERIC(12,2) NOT NULL,
status payment_status DEFAULT 'pending', paid_at TIMESTAMPTZ,
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
-- Module 6: Shipping
CREATE TABLE shipments (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL, order_date DATE NOT NULL,
carrier TEXT NOT NULL, tracking_code TEXT NOT NULL UNIQUE,
status TEXT DEFAULT 'created'
CHECK (status IN ('created','in_transit','delivered','failed')),
FOREIGN KEY (order_id, order_date) REFERENCES orders(id, order_date)
);
CREATE TABLE shipment_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
shipment_id BIGINT NOT NULL REFERENCES shipments(id),
event_type TEXT NOT NULL, metadata JSONB DEFAULT '{}',
event_time TIMESTAMPTZ DEFAULT now()
);
-- Module 7: Reviews
CREATE TABLE reviews (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
product_id BIGINT NOT NULL REFERENCES products(id),
rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment TEXT, created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (user_id, product_id)
);
-- Module 8: Reporting materialized views
CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT order_date, COUNT(DISTINCT user_id) AS unique_buyers,
COUNT(*) AS order_count, SUM(total_amount) AS daily_revenue
FROM orders WHERE status = 'completed'
GROUP BY order_date;
CREATE UNIQUE INDEX idx_mv_daily ON mv_daily_sales (order_date);
❓ 常见问题
📖 小节
- 需求分析先行:8 大模块覆盖电商全链路
- ER 图是表结构设计的核心,外键关系决定建表顺序
- 用户系统:RLS 行级安全 + pgcrypto 密码哈希
- 商品模块:JSONB 动态属性 + tsvector 全文搜索 + pgvector 语义推荐
- 订单模块:按月 RANGE 分区 + 组合外键 + 存储过程自动化
- 物流模块:JSONB 事件流 + 时序追踪
- 报表模块:物化视图 + CONCURRENTLY 刷新
- PG vs MySQL:JSONB/全文搜索/向量/RLS/物化视图/扩展生态是 PG 核心优势
- FDW 实现零停机数据迁移,PITR 保障数据安全
📝 作业
-
⭐ 按照综合示例脚本,在本机 PG 实例上创建完整电商数据库,插入 10 条测试数据,验证每个模块的基本查询(用户登录、商品搜索、订单创建、购物车 UPSERT)。
-
⭐⭐ 扩展综合项目:(1) 添加优惠券模块(coupons 表 + JSONB 规则 + 存储过程校验);(2) 编写
search_products(keyword TEXT, min_price NUMERIC, max_price NUMERIC, category_id INT)函数,融合全文搜索 + JSONB 过滤 + 价格范围;(3) 创建月度自动分区的pg_cron定时任务。 -
⭐⭐⭐ 完成生产级优化报告:(1) 用
pg_stat_statements收集 Top 10 慢查询并给出优化方案;(2) 为所有分区表设计 autovacuum 策略;(3) 配置 PITR 备份并测试时间点恢复;(4) 编写postgres_fdw从一个 PG 实例迁移数据到另一个的完整脚本;(5) 用 EXPLAIN ANALYZE 验证所有关键查询走最优计划。