QAUP_Management/.kiro/specs/flyway-database-migration/design.md

369 lines
9.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Design Document
## Overview
本设计文档描述了为QAUP项目集成Flyway数据库迁移工具的技术方案。通过分析现有的SQL文件结构和部署流程设计一个完整的数据库版本管理系统包括基线迁移脚本的创建、Flyway配置集成、部署脚本修改以及开发流程规范。
## Architecture
### 系统架构图
```mermaid
graph TB
A[开发环境] --> B[Maven构建]
B --> C[Flyway迁移脚本]
C --> D[应用启动]
D --> E[Flyway自动迁移]
E --> F[PostgreSQL数据库]
G[现有SQL文件] --> H[脚本整理工具]
H --> I[基线迁移脚本]
I --> C
J[部署脚本] --> K[Docker容器]
K --> D
L[开发流程] --> M[新迁移脚本]
M --> C
```
### 核心组件
1. **Flyway Core**: 数据库迁移引擎
2. **Migration Scripts**: 版本化的SQL迁移脚本
3. **Baseline Migration**: 基于现有SQL文件的初始化脚本
4. **Configuration Management**: Spring Boot集成配置
5. **Deployment Integration**: 部署流程集成
## Components and Interfaces
### 1. Flyway配置组件
#### Maven依赖配置
```xml
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
```
#### Spring Boot配置
```yaml
spring:
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: true
baseline-version: 1.0.0
baseline-description: "Initial baseline from existing database"
validate-on-migrate: true
clean-disabled: true
out-of-order: false
```
### 2. 迁移脚本组件
#### 目录结构
```
src/main/resources/
└── db/
└── migration/
├── V1.0.0__Initial_baseline.sql
├── V1.0.1__Add_traffic_light_tables.sql
├── V1.0.2__Add_vehicle_filter_config.sql
└── V1.0.3__Update_geofence_schema.sql
```
#### 脚本命名规范
- 格式: `V{version}__{description}.sql`
- 版本号: 语义化版本控制 (major.minor.patch)
- 描述: 英文下划线分隔,简洁明了
### 3. 基线脚本生成组件
#### SQL文件分析器
```java
public class SqlFileAnalyzer {
public List<SqlScript> analyzeSqlFiles(Path sqlDirectory);
public SqlScript mergeScripts(List<SqlScript> scripts);
public void generateBaselineScript(SqlScript mergedScript, Path outputPath);
}
```
#### 脚本合并策略
1. **表结构优先**: 先创建所有表结构
2. **索引和约束**: 然后添加索引和外键约束
3. **初始数据**: 最后插入基础数据
4. **去重处理**: 移除重复的CREATE语句
### 4. 部署集成组件
#### Docker启动脚本修改
```bash
# 在应用启动前等待数据库就绪
wait_for_database() {
until pg_isready -h qaup-postgres -p 5432 -U qaup; do
echo "等待数据库启动..."
sleep 2
done
}
# 应用启动时自动执行Flyway迁移
start_application() {
wait_for_database
java -jar /app/app.jar --spring.config.location=/app/config.yml
}
```
## Data Models
### 1. Flyway元数据表
Flyway会自动创建 `flyway_schema_history` 表来跟踪迁移历史:
```sql
CREATE TABLE flyway_schema_history (
installed_rank INTEGER NOT NULL,
version VARCHAR(50),
description VARCHAR(200) NOT NULL,
type VARCHAR(20) NOT NULL,
script VARCHAR(1000) NOT NULL,
checksum INTEGER,
installed_by VARCHAR(100) NOT NULL,
installed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
execution_time INTEGER NOT NULL,
success BOOLEAN NOT NULL
);
```
### 2. 迁移脚本数据模型
```java
public class MigrationScript {
private String version;
private String description;
private String content;
private LocalDateTime createdAt;
private String author;
private List<String> dependencies;
}
```
### 3. 基线数据模型
基于现有SQL文件分析基线脚本将包含
- **系统核心表**: sys_user, sys_role, sys_dept等RuoYi框架表
- **业务表**: sys_vehicle_info, sys_driver_info, sys_vehicle_type等
- **空间数据表**: vehicle_location, airport_area等PostGIS表
- **配置表**: sys_config及其初始数据
- **索引和约束**: 所有必要的数据库索引和外键约束
## Error Handling
### 1. 迁移失败处理
```java
@Component
public class FlywayMigrationHandler {
@EventListener
public void handleMigrationFailure(FlywayMigrationFailureEvent event) {
log.error("数据库迁移失败: {}", event.getException().getMessage());
// 发送告警通知
alertService.sendMigrationFailureAlert(event);
// 记录详细错误信息
errorLogService.logMigrationError(event);
}
@EventListener
public void handleMigrationSuccess(FlywayMigrationSuccessEvent event) {
log.info("数据库迁移成功完成,当前版本: {}", event.getTargetVersion());
}
}
```
### 2. 版本冲突处理
- **检测机制**: 启动时检查是否有版本冲突
- **解决策略**:
- 开发环境: 允许out-of-order迁移
- 生产环境: 严格按版本顺序执行
- **回滚机制**: 提供手动回滚工具和脚本
### 3. 数据完整性保护
```sql
-- 在迁移脚本中添加数据验证
DO $$
BEGIN
-- 验证关键数据完整性
IF NOT EXISTS (SELECT 1 FROM sys_config WHERE config_key = 'sys.user.initPassword') THEN
RAISE EXCEPTION '关键配置数据缺失,迁移中止';
END IF;
END $$;
```
## Testing Strategy
### 1. 迁移脚本测试
#### 单元测试
```java
@SpringBootTest
@Testcontainers
class FlywayMigrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgis/postgis:17-3.5-alpine")
.withDatabaseName("qaup_test")
.withUsername("test")
.withPassword("test");
@Test
void testBaselineMigration() {
// 测试基线迁移脚本
Flyway flyway = Flyway.configure()
.dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())
.locations("classpath:db/migration")
.load();
MigrateResult result = flyway.migrate();
assertThat(result.migrationsExecuted).isGreaterThan(0);
}
@Test
void testIncrementalMigration() {
// 测试增量迁移
}
}
```
#### 集成测试
```java
@SpringBootTest
@TestPropertySource(properties = {
"spring.flyway.locations=classpath:db/migration,classpath:db/testdata"
})
class DatabaseIntegrationTest {
@Test
void testDatabaseSchemaAfterMigration() {
// 验证迁移后的数据库结构
}
@Test
void testDataIntegrityAfterMigration() {
// 验证数据完整性
}
}
```
### 2. 性能测试
#### 迁移性能测试
- **大数据量测试**: 模拟生产环境数据量
- **并发测试**: 测试多实例启动时的迁移行为
- **回滚性能**: 测试回滚操作的性能
#### 监控指标
```java
@Component
public class FlywayMetrics {
private final MeterRegistry meterRegistry;
public void recordMigrationTime(String version, Duration duration) {
Timer.Sample sample = Timer.start(meterRegistry);
sample.stop(Timer.builder("flyway.migration.duration")
.tag("version", version)
.register(meterRegistry));
}
}
```
### 3. 环境测试
#### 多环境验证
- **开发环境**: 频繁迁移测试
- **测试环境**: 完整迁移流程验证
- **预生产环境**: 生产数据迁移模拟
- **生产环境**: 蓝绿部署迁移测试
#### Docker环境测试
```yaml
# docker-compose.test.yml
services:
qaup-postgres-test:
image: postgis/postgis:17-3.5-alpine
environment:
POSTGRES_DB: qaup_test
POSTGRES_USER: test
POSTGRES_PASSWORD: test
volumes:
- ./test-data:/docker-entrypoint-initdb.d
```
## Implementation Plan
### Phase 1: 基础设施搭建
1. 添加Flyway依赖和配置
2. 创建迁移脚本目录结构
3. 开发SQL文件分析和合并工具
### Phase 2: 基线迁移创建
1. 分析现有SQL文件依赖关系
2. 生成统一的基线迁移脚本
3. 验证基线脚本的完整性和正确性
### Phase 3: 部署集成
1. 修改Docker配置支持Flyway
2. 更新部署脚本
3. 创建数据库初始化流程
### Phase 4: 开发流程规范
1. 制定迁移脚本开发规范
2. 创建代码审查检查清单
3. 建立版本管理流程
### Phase 5: 监控和维护
1. 实现迁移状态监控
2. 创建故障排除工具
3. 建立备份和回滚机制
## Security Considerations
### 1. 权限控制
- Flyway执行用户权限最小化
- 生产环境禁用clean操作
- 迁移脚本访问权限控制
### 2. 数据保护
- 敏感数据迁移加密
- 备份策略集成
- 审计日志记录
### 3. 环境隔离
- 不同环境使用不同的迁移配置
- 生产环境额外的安全检查
- 迁移脚本签名验证
## Performance Optimization
### 1. 迁移性能优化
- 批量操作优化
- 索引创建策略
- 大表迁移分批处理
### 2. 启动性能优化
- 并行迁移支持
- 增量检查优化
- 缓存机制集成
### 3. 资源使用优化
- 内存使用控制
- 连接池配置优化
- 临时空间管理