database-schema-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Database Schema Documentation

数据库架构文档

Overview

概述

Create comprehensive database schema documentation including entity relationship diagrams (ERD), table definitions, indexes, constraints, and data dictionaries.
创建全面的数据库架构文档,包括实体关系图(ERD)、表定义、索引、约束和数据字典。

When to Use

适用场景

  • Database schema documentation
  • ERD (Entity Relationship Diagrams)
  • Data dictionary creation
  • Table relationship documentation
  • Index and constraint documentation
  • Migration documentation
  • Database design specs
  • 数据库架构文档编写
  • ERD(实体关系图)创建
  • 数据字典生成
  • 表关系文档撰写
  • 索引与约束文档记录
  • 迁移文档编写
  • 数据库设计规范制定

Schema Documentation Template

架构文档模板

markdown
undefined
markdown
undefined

Database Schema Documentation

数据库架构文档

Database: PostgreSQL 14.x Version: 2.0 Last Updated: 2025-01-15 Schema Version: 20250115120000
数据库: PostgreSQL 14.x 版本: 2.0 最后更新时间: 2025-01-15 架构版本: 20250115120000

Overview

概述

This database supports an e-commerce application with user management, product catalog, orders, and payment processing.
本数据库支持电商应用,包含用户管理、产品目录、订单和支付处理模块。

Entity Relationship Diagram

实体关系图

mermaid
erDiagram
    users ||--o{ orders : places
    users ||--o{ addresses : has
    users ||--o{ payment_methods : has
    orders ||--|{ order_items : contains
    orders ||--|| payments : has
    products ||--o{ order_items : includes
    products }o--|| categories : belongs_to
    products ||--o{ product_images : has
    products ||--o{ inventory : tracks

    users {
        uuid id PK
        string email UK
        string password_hash
        string name
        timestamp created_at
        timestamp updated_at
    }

    orders {
        uuid id PK
        uuid user_id FK
        string status
        decimal total_amount
        timestamp created_at
        timestamp updated_at
    }

    order_items {
        uuid id PK
        uuid order_id FK
        uuid product_id FK
        int quantity
        decimal price
    }

    products {
        uuid id PK
        string name
        text description
        decimal price
        uuid category_id FK
        boolean active
    }

mermaid
erDiagram
    users ||--o{ orders : places
    users ||--o{ addresses : has
    users ||--o{ payment_methods : has
    orders ||--|{ order_items : contains
    orders ||--|| payments : has
    products ||--o{ order_items : includes
    products }o--|| categories : belongs_to
    products ||--o{ product_images : has
    products ||--o{ inventory : tracks

    users {
        uuid id PK
        string email UK
        string password_hash
        string name
        timestamp created_at
        timestamp updated_at
    }

    orders {
        uuid id PK
        uuid user_id FK
        string status
        decimal total_amount
        timestamp created_at
        timestamp updated_at
    }

    order_items {
        uuid id PK
        uuid order_id FK
        uuid product_id FK
        int quantity
        decimal price
    }

    products {
        uuid id PK
        string name
        text description
        decimal price
        uuid category_id FK
        boolean active
    }

Tables

表结构

users

users

Stores user account information.
Columns:
ColumnTypeNullDefaultDescription
iduuidNOgen_random_uuid()Primary key
emailvarchar(255)NO-User email (unique)
password_hashvarchar(255)NO-bcrypt hashed password
namevarchar(255)NO-User's full name
email_verifiedbooleanNOfalseEmail verification status
two_factor_enabledbooleanNOfalse2FA enabled flag
two_factor_secretvarchar(32)YES-TOTP secret
created_attimestampNOnow()Record creation time
updated_attimestampNOnow()Last update time
deleted_attimestampYES-Soft delete timestamp
last_login_attimestampYES-Last login timestamp
Indexes:
sql
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created_at ON users(created_at);
CREATE INDEX idx_users_deleted_at ON users(deleted_at) WHERE deleted_at IS NULL;
Constraints:
sql
ALTER TABLE users
  ADD CONSTRAINT users_email_format
  CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');

ALTER TABLE users
  ADD CONSTRAINT users_name_length
  CHECK (length(name) >= 2);
Triggers:
sql
-- Update updated_at timestamp
CREATE TRIGGER update_users_updated_at
  BEFORE UPDATE ON users
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
Sample Data:
sql
INSERT INTO users (email, password_hash, name, email_verified)
VALUES
  ('john@example.com', '$2b$12$...', 'John Doe', true),
  ('jane@example.com', '$2b$12$...', 'Jane Smith', true);

存储用户账户信息。
列信息:
列名类型是否可为空默认值描述
iduuidNOgen_random_uuid()主键
emailvarchar(255)NO-用户邮箱(唯一)
password_hashvarchar(255)NO-bcrypt加密后的密码
namevarchar(255)NO-用户全名
email_verifiedbooleanNOfalse邮箱验证状态
two_factor_enabledbooleanNOfalse双因素认证启用标记
two_factor_secretvarchar(32)YES-TOTP密钥
created_attimestampNOnow()记录创建时间
updated_attimestampNOnow()最后更新时间
deleted_attimestampYES-软删除时间戳
last_login_attimestampYES-最后登录时间戳
索引:
sql
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created_at ON users(created_at);
CREATE INDEX idx_users_deleted_at ON users(deleted_at) WHERE deleted_at IS NULL;
约束:
sql
ALTER TABLE users
  ADD CONSTRAINT users_email_format
  CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');

ALTER TABLE users
  ADD CONSTRAINT users_name_length
  CHECK (length(name) >= 2);
触发器:
sql
-- 更新updated_at时间戳
CREATE TRIGGER update_users_updated_at
  BEFORE UPDATE ON users
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
示例数据:
sql
INSERT INTO users (email, password_hash, name, email_verified)
VALUES
  ('john@example.com', '$2b$12$...', 'John Doe', true),
  ('jane@example.com', '$2b$12$...', 'Jane Smith', true);

products

products

Stores product catalog information.
Columns:
ColumnTypeNullDefaultDescription
iduuidNOgen_random_uuid()Primary key
namevarchar(255)NO-Product name
slugvarchar(255)NO-URL-friendly name (unique)
descriptiontextYES-Product description
pricedecimal(10,2)NO-Product price in USD
compare_at_pricedecimal(10,2)YES-Original price (for sales)
skuvarchar(100)NO-Stock keeping unit (unique)
category_iduuidNO-Foreign key to categories
brandvarchar(100)YES-Product brand
activebooleanNOtrueProduct visibility
featuredbooleanNOfalseFeatured product flag
metadatajsonbYES-Additional product metadata
created_attimestampNOnow()Record creation time
updated_attimestampNOnow()Last update time
Indexes:
sql
CREATE UNIQUE INDEX idx_products_slug ON products(slug);
CREATE UNIQUE INDEX idx_products_sku ON products(sku);
CREATE INDEX idx_products_category_id ON products(category_id);
CREATE INDEX idx_products_active ON products(active);
CREATE INDEX idx_products_featured ON products(featured) WHERE featured = true;
CREATE INDEX idx_products_metadata ON products USING gin(metadata);
Foreign Keys:
sql
ALTER TABLE products
  ADD CONSTRAINT fk_products_category
  FOREIGN KEY (category_id)
  REFERENCES categories(id)
  ON DELETE RESTRICT;
Full-Text Search:
sql
-- Add full-text search column
ALTER TABLE products ADD COLUMN search_vector tsvector;

-- Create full-text index
CREATE INDEX idx_products_search ON products USING gin(search_vector);

-- Trigger to update search vector
CREATE TRIGGER products_search_vector_update
  BEFORE INSERT OR UPDATE ON products
  FOR EACH ROW
  EXECUTE FUNCTION
    tsvector_update_trigger(
      search_vector, 'pg_catalog.english',
      name, description, brand
    );

存储产品目录信息。
列信息:
列名类型是否可为空默认值描述
iduuidNOgen_random_uuid()主键
namevarchar(255)NO-产品名称
slugvarchar(255)NO-URL友好名称(唯一)
descriptiontextYES-产品描述
pricedecimal(10,2)NO-产品价格(美元)
compare_at_pricedecimal(10,2)YES-原价(用于促销)
skuvarchar(100)NO-库存单位(唯一)
category_iduuidNO-关联categories表的外键
brandvarchar(100)YES-产品品牌
activebooleanNOtrue产品可见性
featuredbooleanNOfalse精选产品标记
metadatajsonbYES-额外产品元数据
created_attimestampNOnow()记录创建时间
updated_attimestampNOnow()最后更新时间
索引:
sql
CREATE UNIQUE INDEX idx_products_slug ON products(slug);
CREATE UNIQUE INDEX idx_products_sku ON products(sku);
CREATE INDEX idx_products_category_id ON products(category_id);
CREATE INDEX idx_products_active ON products(active);
CREATE INDEX idx_products_featured ON products(featured) WHERE featured = true;
CREATE INDEX idx_products_metadata ON products USING gin(metadata);
外键:
sql
ALTER TABLE products
  ADD CONSTRAINT fk_products_category
  FOREIGN KEY (category_id)
  REFERENCES categories(id)
  ON DELETE RESTRICT;
全文搜索:
sql
-- 添加全文搜索列
ALTER TABLE products ADD COLUMN search_vector tsvector;

-- 创建全文索引
CREATE INDEX idx_products_search ON products USING gin(search_vector);

-- 更新搜索向量的触发器
CREATE TRIGGER products_search_vector_update
  BEFORE INSERT OR UPDATE ON products
  FOR EACH ROW
  EXECUTE FUNCTION
    tsvector_update_trigger(
      search_vector, 'pg_catalog.english',
      name, description, brand
    );

orders

orders

Stores customer orders.
Columns:
ColumnTypeNullDefaultDescription
iduuidNOgen_random_uuid()Primary key
order_numbervarchar(20)NO-Human-readable order ID (unique)
user_iduuidNO-Foreign key to users
statusvarchar(20)NO'pending'Order status
subtotaldecimal(10,2)NO-Items subtotal
taxdecimal(10,2)NO0Tax amount
shippingdecimal(10,2)NO0Shipping cost
totaldecimal(10,2)NO-Total amount
currencychar(3)NO'USD'Currency code
notestextYES-Order notes
shipping_addressjsonbNO-Shipping address
billing_addressjsonbNO-Billing address
created_attimestampNOnow()Order creation time
updated_attimestampNOnow()Last update time
confirmed_attimestampYES-Order confirmation time
shipped_attimestampYES-Shipping time
delivered_attimestampYES-Delivery time
cancelled_attimestampYES-Cancellation time
Indexes:
sql
CREATE UNIQUE INDEX idx_orders_order_number ON orders(order_number);
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_created_at ON orders(created_at);
Constraints:
sql
ALTER TABLE orders
  ADD CONSTRAINT orders_status_check
  CHECK (status IN ('pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'));

ALTER TABLE orders
  ADD CONSTRAINT orders_total_positive
  CHECK (total >= 0);
Computed Columns:
sql
-- Total is computed from subtotal + tax + shipping
ALTER TABLE orders
  ADD CONSTRAINT orders_total_computation
  CHECK (total = subtotal + tax + shipping);

存储客户订单信息。
列信息:
列名类型是否可为空默认值描述
iduuidNOgen_random_uuid()主键
order_numbervarchar(20)NO-人类可读的订单ID(唯一)
user_iduuidNO-关联users表的外键
statusvarchar(20)NO'pending'订单状态
subtotaldecimal(10,2)NO-商品小计
taxdecimal(10,2)NO0税费
shippingdecimal(10,2)NO0运费
totaldecimal(10,2)NO-总金额
currencychar(3)NO'USD'货币代码
notestextYES-订单备注
shipping_addressjsonbNO-收货地址
billing_addressjsonbNO-账单地址
created_attimestampNOnow()订单创建时间
updated_attimestampNOnow()最后更新时间
confirmed_attimestampYES-订单确认时间
shipped_attimestampYES-发货时间
delivered_attimestampYES-送达时间
cancelled_attimestampYES-取消时间
索引:
sql
CREATE UNIQUE INDEX idx_orders_order_number ON orders(order_number);
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_created_at ON orders(created_at);
约束:
sql
ALTER TABLE orders
  ADD CONSTRAINT orders_status_check
  CHECK (status IN ('pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'));

ALTER TABLE orders
  ADD CONSTRAINT orders_total_positive
  CHECK (total >= 0);
计算列约束:
sql
-- 总金额由小计+税费+运费计算得出
ALTER TABLE orders
  ADD CONSTRAINT orders_total_computation
  CHECK (total = subtotal + tax + shipping);

order_items

order_items

Line items for each order.
Columns:
ColumnTypeNullDefaultDescription
iduuidNOgen_random_uuid()Primary key
order_iduuidNO-Foreign key to orders
product_iduuidNO-Foreign key to products
product_snapshotjsonbNO-Product data at order time
quantityintNO-Quantity ordered
unit_pricedecimal(10,2)NO-Price per unit
subtotaldecimal(10,2)NO-Line item total
created_attimestampNOnow()Record creation time
Indexes:
sql
CREATE INDEX idx_order_items_order_id ON order_items(order_id);
CREATE INDEX idx_order_items_product_id ON order_items(product_id);
Foreign Keys:
sql
ALTER TABLE order_items
  ADD CONSTRAINT fk_order_items_order
  FOREIGN KEY (order_id)
  REFERENCES orders(id)
  ON DELETE CASCADE;

ALTER TABLE order_items
  ADD CONSTRAINT fk_order_items_product
  FOREIGN KEY (product_id)
  REFERENCES products(id)
  ON DELETE RESTRICT;
Constraints:
sql
ALTER TABLE order_items
  ADD CONSTRAINT order_items_quantity_positive
  CHECK (quantity > 0);

ALTER TABLE order_items
  ADD CONSTRAINT order_items_subtotal_computation
  CHECK (subtotal = quantity * unit_price);

订单的明细项。
列信息:
列名类型是否可为空默认值描述
iduuidNOgen_random_uuid()主键
order_iduuidNO-关联orders表的外键
product_iduuidNO-关联products表的外键
product_snapshotjsonbNO-下单时的产品快照数据
quantityintNO-订购数量
unit_pricedecimal(10,2)NO-单价
subtotaldecimal(10,2)NO-明细项总金额
created_attimestampNOnow()记录创建时间
索引:
sql
CREATE INDEX idx_order_items_order_id ON order_items(order_id);
CREATE INDEX idx_order_items_product_id ON order_items(product_id);
外键:
sql
ALTER TABLE order_items
  ADD CONSTRAINT fk_order_items_order
  FOREIGN KEY (order_id)
  REFERENCES orders(id)
  ON DELETE CASCADE;

ALTER TABLE order_items
  ADD CONSTRAINT fk_order_items_product
  FOREIGN KEY (product_id)
  REFERENCES products(id)
  ON DELETE RESTRICT;
约束:
sql
ALTER TABLE order_items
  ADD CONSTRAINT order_items_quantity_positive
  CHECK (quantity > 0);

ALTER TABLE order_items
  ADD CONSTRAINT order_items_subtotal_computation
  CHECK (subtotal = quantity * unit_price);

Views

视图

active_products_view

active_products_view

Shows only active products with category information.
sql
CREATE VIEW active_products_view AS
SELECT
  p.id,
  p.name,
  p.slug,
  p.description,
  p.price,
  p.compare_at_price,
  p.sku,
  p.brand,
  c.name as category_name,
  c.slug as category_slug,
  (SELECT COUNT(*) FROM order_items oi WHERE oi.product_id = p.id) as times_ordered,
  (SELECT AVG(rating) FROM product_reviews pr WHERE pr.product_id = p.id) as avg_rating
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.active = true;
仅显示活跃产品及分类信息。
sql
CREATE VIEW active_products_view AS
SELECT
  p.id,
  p.name,
  p.slug,
  p.description,
  p.price,
  p.compare_at_price,
  p.sku,
  p.brand,
  c.name as category_name,
  c.slug as category_slug,
  (SELECT COUNT(*) FROM order_items oi WHERE oi.product_id = p.id) as times_ordered,
  (SELECT AVG(rating) FROM product_reviews pr WHERE pr.product_id = p.id) as avg_rating
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.active = true;

user_order_summary

user_order_summary

Aggregated order statistics per user.
sql
CREATE MATERIALIZED VIEW user_order_summary AS
SELECT
  u.id as user_id,
  u.email,
  u.name,
  COUNT(o.id) as total_orders,
  SUM(o.total) as total_spent,
  AVG(o.total) as average_order_value,
  MAX(o.created_at) as last_order_date,
  MIN(o.created_at) as first_order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id AND o.status != 'cancelled'
GROUP BY u.id, u.email, u.name;

-- Refresh strategy
CREATE INDEX idx_user_order_summary_user_id ON user_order_summary(user_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY user_order_summary;

按用户聚合的订单统计信息。
sql
CREATE MATERIALIZED VIEW user_order_summary AS
SELECT
  u.id as user_id,
  u.email,
  u.name,
  COUNT(o.id) as total_orders,
  SUM(o.total) as total_spent,
  AVG(o.total) as average_order_value,
  MAX(o.created_at) as last_order_date,
  MIN(o.created_at) as first_order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id AND o.status != 'cancelled'
GROUP BY u.id, u.email, u.name;

-- 刷新策略
CREATE INDEX idx_user_order_summary_user_id ON user_order_summary(user_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY user_order_summary;

Functions

函数

calculate_order_total

calculate_order_total

Calculates order total with tax and shipping.
sql
CREATE OR REPLACE FUNCTION calculate_order_total(
  p_subtotal decimal,
  p_tax_rate decimal,
  p_shipping decimal
)
RETURNS decimal AS $$
BEGIN
  RETURN ROUND((p_subtotal * (1 + p_tax_rate) + p_shipping)::numeric, 2);
END;
$$ LANGUAGE plpgsql IMMUTABLE;
计算包含税费和运费的订单总金额。
sql
CREATE OR REPLACE FUNCTION calculate_order_total(
  p_subtotal decimal,
  p_tax_rate decimal,
  p_shipping decimal
)
RETURNS decimal AS $$
BEGIN
  RETURN ROUND((p_subtotal * (1 + p_tax_rate) + p_shipping)::numeric, 2);
END;
$$ LANGUAGE plpgsql IMMUTABLE;

update_updated_at_column

update_updated_at_column

Trigger function to automatically update updated_at timestamp.
sql
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

自动更新updated_at时间戳的触发器函数。
sql
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Data Dictionary

数据字典

Enum Types

枚举类型

sql
-- Order status values
CREATE TYPE order_status AS ENUM (
  'pending',
  'confirmed',
  'processing',
  'shipped',
  'delivered',
  'cancelled',
  'refunded'
);

-- Payment status values
CREATE TYPE payment_status AS ENUM (
  'pending',
  'processing',
  'succeeded',
  'failed',
  'refunded'
);
sql
-- 订单状态值
CREATE TYPE order_status AS ENUM (
  'pending',
  'confirmed',
  'processing',
  'shipped',
  'delivered',
  'cancelled',
  'refunded'
);

-- 支付状态值
CREATE TYPE payment_status AS ENUM (
  'pending',
  'processing',
  'succeeded',
  'failed',
  'refunded'
);

JSONB Structures

JSONB结构

shipping_address format

shipping_address格式

json
{
  "street": "123 Main St",
  "street2": "Apt 4B",
  "city": "New York",
  "state": "NY",
  "postalCode": "10001",
  "country": "US"
}
json
{
  "street": "123 Main St",
  "street2": "Apt 4B",
  "city": "New York",
  "state": "NY",
  "postalCode": "10001",
  "country": "US"
}

product_snapshot format

product_snapshot格式

json
{
  "name": "Product Name",
  "sku": "PROD-123",
  "price": 99.99,
  "image": "https://cdn.example.com/product.jpg"
}

json
{
  "name": "Product Name",
  "sku": "PROD-123",
  "price": 99.99,
  "image": "https://cdn.example.com/product.jpg"
}

Migrations

迁移脚本

Migration: 20250115120000_add_two_factor_auth

迁移: 20250115120000_add_two_factor_auth

sql
-- Up
ALTER TABLE users ADD COLUMN two_factor_enabled BOOLEAN DEFAULT FALSE;
ALTER TABLE users ADD COLUMN two_factor_secret VARCHAR(32);

CREATE TABLE two_factor_backup_codes (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  code_hash VARCHAR(255) NOT NULL,
  used_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_2fa_backup_codes_user_id ON two_factor_backup_codes(user_id);

-- Down
DROP TABLE two_factor_backup_codes;
ALTER TABLE users DROP COLUMN two_factor_secret;
ALTER TABLE users DROP COLUMN two_factor_enabled;

sql
-- 升级脚本
ALTER TABLE users ADD COLUMN two_factor_enabled BOOLEAN DEFAULT FALSE;
ALTER TABLE users ADD COLUMN two_factor_secret VARCHAR(32);

CREATE TABLE two_factor_backup_codes (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  code_hash VARCHAR(255) NOT NULL,
  used_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_2fa_backup_codes_user_id ON two_factor_backup_codes(user_id);

-- 回滚脚本
DROP TABLE two_factor_backup_codes;
ALTER TABLE users DROP COLUMN two_factor_secret;
ALTER TABLE users DROP COLUMN two_factor_enabled;

Performance Optimization

性能优化

Recommended Indexes

推荐索引

sql
-- Frequently queried columns
CREATE INDEX CONCURRENTLY idx_users_email_verified ON users(email_verified);
CREATE INDEX CONCURRENTLY idx_products_price ON products(price);
CREATE INDEX CONCURRENTLY idx_orders_user_status ON orders(user_id, status);

-- Composite indexes for common queries
CREATE INDEX CONCURRENTLY idx_products_category_active
  ON products(category_id, active)
  WHERE active = true;

CREATE INDEX CONCURRENTLY idx_orders_user_created
  ON orders(user_id, created_at DESC);
sql
-- 频繁查询的列
CREATE INDEX CONCURRENTLY idx_users_email_verified ON users(email_verified);
CREATE INDEX CONCURRENTLY idx_products_price ON products(price);
CREATE INDEX CONCURRENTLY idx_orders_user_status ON orders(user_id, status);

-- 复合索引用于常见查询
CREATE INDEX CONCURRENTLY idx_products_category_active
  ON products(category_id, active)
  WHERE active = true;

CREATE INDEX CONCURRENTLY idx_orders_user_created
  ON orders(user_id, created_at DESC);

Query Optimization

查询优化

sql
-- EXPLAIN ANALYZE for slow queries
EXPLAIN ANALYZE
SELECT p.*, c.name as category_name
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.active = true
ORDER BY p.created_at DESC
LIMIT 20;

-- Add covering index if needed
CREATE INDEX idx_products_active_created
  ON products(active, created_at DESC)
  INCLUDE (name, price, slug);

sql
-- 对慢查询执行EXPLAIN ANALYZE
EXPLAIN ANALYZE
SELECT p.*, c.name as category_name
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.active = true
ORDER BY p.created_at DESC
LIMIT 20;

-- 如有需要,添加覆盖索引
CREATE INDEX idx_products_active_created
  ON products(active, created_at DESC)
  INCLUDE (name, price, slug);

Backup & Recovery

备份与恢复

Backup Schedule

备份计划

  • Full Backup: Daily at 2 AM UTC
  • Incremental Backup: Every 6 hours
  • WAL Archiving: Continuous
  • Retention: 30 days
  • 全量备份: 每日UTC时间2点
  • 增量备份: 每6小时一次
  • WAL归档: 持续进行
  • 保留期限: 30天

Backup Commands

备份命令

bash
undefined
bash
undefined

Full backup

全量备份

pg_dump -h localhost -U postgres -Fc database_name > backup.dump
pg_dump -h localhost -U postgres -Fc database_name > backup.dump

Restore

恢复

pg_restore -h localhost -U postgres -d database_name backup.dump
pg_restore -h localhost -U postgres -d database_name backup.dump

Backup specific tables

备份指定表

pg_dump -h localhost -U postgres -t users -t orders database_name > tables.sql

---
pg_dump -h localhost -U postgres -t users -t orders database_name > tables.sql

---

Data Retention Policy

数据保留策略

TableRetentionArchive Strategy
usersIndefiniteSoft delete after 2 years inactive
orders7 yearsMove to archive after 2 years
order_items7 yearsMove to archive with orders
logs90 daysDelete after retention period
undefined
表名保留期限归档策略
users永久闲置2年后软删除
orders7年2年后迁移至归档库
order_items7年随订单一起迁移至归档库
logs90天保留期限到期后删除
undefined

Best Practices

最佳实践

✅ DO

✅ 建议

  • Document all tables and columns
  • Create ERD diagrams
  • Document indexes and constraints
  • Include sample data
  • Document foreign key relationships
  • Show JSONB field structures
  • Document triggers and functions
  • Include migration scripts
  • Specify data types precisely
  • Document performance considerations
  • 记录所有表和列信息
  • 创建ERD图
  • 记录索引和约束
  • 包含示例数据
  • 记录外键关系
  • 展示JSONB字段结构
  • 记录触发器和函数
  • 包含迁移脚本
  • 精确指定数据类型
  • 记录性能考量因素

❌ DON'T

❌ 避免

  • Skip constraint documentation
  • Forget to version schema changes
  • Ignore performance implications
  • Skip index documentation
  • Forget to document enum values
  • 跳过约束文档
  • 忘记版本化架构变更
  • 忽略性能影响
  • 跳过索引文档
  • 忘记记录枚举值

Resources

参考资源