# database (数据库迁移与模式) ## 设计思想 数据库迁移使用 SeaORM Migration 框架,遵循以下原则: - **所有表必须包含标准字段** — `id`(UUIDv7), `tenant_id`, `created_at`, `updated_at`, `created_by`, `updated_by`, `deleted_at`, `version` - **软删除** — 不执行硬删除,设置 `deleted_at` 时间戳 - **乐观锁** — 更新时检查 `version` 字段 - **多租户隔离** — 所有业务表必须含 `tenant_id`,查询时自动过滤 - **幂等迁移** — 使用 `if_not_exists` 确保可重复执行 - **可回滚** — 每个迁移必须实现 `down()` 方法 ## 代码逻辑 ### 迁移文件命名规则 ``` m{YYYYMMDD}_{6位序号}_{描述}.rs 例: m20260410_000001_create_tenant.rs ``` ### 当前表结构 **tenant 表** (唯一已实现的表): | 列名 | 类型 | 约束 | |------|------|------| | id | UUID | PK, NOT NULL | | name | STRING | NOT NULL | | code | STRING | NOT NULL, UNIQUE | | status | STRING | NOT NULL, DEFAULT 'active' | | settings | JSON | NULLABLE | | created_at | TIMESTAMPTZ | NOT NULL, DEFAULT now() | | updated_at | TIMESTAMPTZ | NOT NULL, DEFAULT now() | | deleted_at | TIMESTAMPTZ | NULLABLE | ### 已知缺失字段 tenant 表缺少 `BaseFields` 要求的: - `created_by` — 创建人 - `updated_by` — 最后修改人 - `version` — 乐观锁版本号 ### 迁移执行 ``` erp-server 启动 → Migrator::up(&db_conn) → 自动运行所有 pending 迁移 ``` ## 关联模块 - **[[erp-core]]** — `BaseFields` 定义了标准字段规范,迁移表结构必须对齐 - **[[erp-server]]** — 启动时自动运行迁移 - **[[erp-auth]]** — Phase 2 将创建 users, roles, permissions 表 - **[[erp-config]]** — Phase 3 将创建 system_configs 表 - **[[erp-workflow]]** — Phase 4 将创建 workflow_definitions, workflow_instances 表 - **[[erp-message]]** — Phase 5 将创建 messages, notification_settings 表 ## 关键文件 | 文件 | 职责 | |------|------| | `crates/erp-server/migration/src/lib.rs` | Migrator 注册所有迁移 | | `crates/erp-server/migration/src/m20260410_000001_create_tenant.rs` | tenant 表迁移 | | `crates/erp-core/src/types.rs` | BaseFields 标准字段定义 | | `docker/docker-compose.yml` | PostgreSQL 16 服务定义 | ## 未来迁移计划 (按 Phase) | Phase | 表 | 说明 | |-------|-----|------| | Phase 2 | users, roles, permissions, user_roles, role_permissions | RBAC + ABAC | | Phase 3 | system_configs, config_histories | 层级配置 | | Phase 4 | workflow_definitions, workflow_instances, workflow_tasks | BPMN 工作流 | | Phase 5 | messages, notification_settings, message_templates | 多渠道消息 | | 持续 | domain_events | 事件 outbox 表 |