dbnexus 0.1.3

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
// Copyright (c) 2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! 元数据跟踪模块
//!
//! 用于跟踪数据库迁移的表快照信息,支持自动生成回滚SQL

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// 表快照,记录表的结构信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableSnapshot {
    /// 表名
    pub table_name: String,
    /// 列定义
    pub columns: Vec<ColumnDefinition>,
    /// 约束定义
    pub constraints: Vec<ConstraintDefinition>,
}

impl TableSnapshot {
    /// 创建新的表快照
    pub fn new(table_name: String) -> Self {
        Self {
            table_name,
            columns: Vec::new(),
            constraints: Vec::new(),
        }
    }
}

/// 列定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnDefinition {
    /// 列名
    pub name: String,
    /// 数据类型
    pub data_type: String,
    /// 是否可为空
    pub nullable: bool,
    /// 默认值
    pub default_value: Option<String>,
}

/// 约束定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstraintDefinition {
    /// 约束名称
    pub name: Option<String>,
    /// 约束类型
    pub constraint_type: String,
    /// 涉及的列
    pub columns: Vec<String>,
}

/// 迁移元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationMetadata {
    /// 迁移版本号
    pub version: u32,
    /// 迁移名称
    pub name: String,
    /// 向上迁移SQL
    pub up_sql: String,
    /// 向下迁移SQL(可选)
    pub down_sql: Option<String>,
    /// 表快照集合
    pub table_snapshots: HashMap<String, TableSnapshot>,
}

impl MigrationMetadata {
    /// 创建新的迁移元数据
    pub fn new(version: u32, name: String, up_sql: String) -> Self {
        Self {
            version,
            name,
            up_sql,
            down_sql: None,
            table_snapshots: HashMap::new(),
        }
    }

    /// 添加表快照
    pub fn add_table_snapshot(&mut self, snapshot: TableSnapshot) {
        self.table_snapshots.insert(snapshot.table_name.clone(), snapshot);
    }
}