Files

数据库迁移指南

环境准备

1. 安装 PostgreSQL

# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib

# macOS
brew install postgresql

2. 创建数据库

# 切换到 postgres 用户
sudo -u postgres psql

# 在 psql 中执行
CREATE DATABASE xiaoxia_saas;
CREATE USER xiaoxia_user WITH PASSWORD 'your_password_here';
GRANT ALL PRIVILEGES ON DATABASE xiaoxia_saas TO xiaoxia_user;
\q

3. 配置连接字符串

.env 文件中配置:

DATABASE_URL=postgresql://xiaoxia_user:your_password_here@localhost:5432/xiaoxia_saas

执行迁移

方法 1: 使用 psql

# 执行初始化脚本
psql postgresql://xiaoxia_user:your_password_here@localhost:5432/xiaoxia_saas \
  -f migrations/001_initial_schema.sql

方法 2: 使用 Python 脚本

python scripts/run_migrations.py

迁移文件说明

  • 001_initial_schema.sql - 初始表结构
    • users - 用户表
    • workspaces - 工作空间表
    • workspace_members - 成员表
    • workspace_invitations - 邀请表
    • projects - 项目表(占位)

验证迁移

-- 查看所有表
\dt

-- 查看 users 表结构
\d users

-- 查看索引
\di

-- 查看外键约束
SELECT conname, conrelid::regclass AS table_name 
FROM pg_constraint 
WHERE contype = 'f';

回滚

如果需要重置数据库:

# ⚠️ 警告:这会删除所有数据
psql postgresql://xiaoxia_user:password@localhost:5432/xiaoxia_saas \
  -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"

# 然后重新执行迁移
psql ... -f migrations/001_initial_schema.sql

生产环境注意事项

  1. 使用强密码
  2. 配置 SSL 连接
  3. 定期备份数据
  4. 监控数据库性能
  5. 设置连接池(推荐使用 pgBouncer)

连接池配置(可选)

在 Python 中使用 psycopg2 连接池:

from psycopg2 import pool

connection_pool = pool.SimpleConnectionPool(
    minconn=1,
    maxconn=20,
    dsn="postgresql://..."
)

后续迁移

后续的 schema 变更应该创建新的迁移文件:

  • 002_add_xxx.sql
  • 003_alter_xxx.sql
  • ...

每个迁移文件应该是幂等的(可以多次执行而不出错)。