Skip to main content

yang_base/database/
initializer.rs

1//! 声明式数据库结构同步入口。
2//!
3//! [`DatabaseInitializer`] 持有运行时容器 [`super::AnyDatabase`],具体方言与
4//! 连接类型由 schema 同步驱动按后端分派。
5
6use super::AnyDatabase;
7use crate::datasource::DatasourceId;
8use crate::error::BaseError;
9use crate::table::TableDefinition;
10use crate::tools::Tools;
11use std::collections::BTreeMap;
12
13/// 按表声明的逻辑数据源分组执行只读 schema 预检。
14///
15/// 每个数据源使用独立连接与独立锁;返回逐源结果。任一源失败不会丢失其它源的
16/// 结果,调用方必须逐源判断。
17pub async fn preflight_table_definitions_grouped_outcomes(
18    tools: &Tools,
19    definitions: &[&TableDefinition],
20) -> BTreeMap<DatasourceId, Result<super::SchemaPreflightReport, BaseError>> {
21    let mut outcomes = BTreeMap::new();
22    for (source, group) in group_definitions(definitions) {
23        let outcome = match tools.database_named(&source) {
24            Ok(database) => {
25                DatabaseInitializer::from_any(database.clone())
26                    .preflight_table_definitions(&group)
27                    .await
28            }
29            Err(error) => Err(error),
30        };
31        outcomes.insert(source, outcome);
32    }
33    outcomes
34}
35
36/// 按表声明的逻辑数据源分组执行只读 schema 预检;任一源失败立即返回错误。
37pub async fn preflight_table_definitions_grouped(
38    tools: &Tools,
39    definitions: &[&TableDefinition],
40) -> Result<BTreeMap<DatasourceId, super::SchemaPreflightReport>, BaseError> {
41    collect_outcomes(preflight_table_definitions_grouped_outcomes(tools, definitions).await)
42}
43
44/// 按表声明的逻辑数据源分组执行 schema 同步。
45///
46/// 每个数据源使用独立连接、锁与事务;返回逐源结果,调用方必须把部分成功
47/// 当成逐源结果处理,不能假设跨源整体回滚。
48pub async fn sync_table_definitions_grouped_outcomes(
49    tools: &Tools,
50    definitions: &[&TableDefinition],
51) -> BTreeMap<DatasourceId, Result<super::SchemaSyncReport, BaseError>> {
52    let mut outcomes = BTreeMap::new();
53    for (source, group) in group_definitions(definitions) {
54        let outcome = match tools.database_named(&source) {
55            Ok(database) => {
56                DatabaseInitializer::from_any(database.clone())
57                    .sync_table_definitions(&group)
58                    .await
59            }
60            Err(error) => Err(error),
61        };
62        outcomes.insert(source, outcome);
63    }
64    outcomes
65}
66
67/// 按表声明的逻辑数据源分组执行 schema 同步;任一源失败立即返回错误。
68pub async fn sync_table_definitions_grouped(
69    tools: &Tools,
70    definitions: &[&TableDefinition],
71) -> Result<BTreeMap<DatasourceId, super::SchemaSyncReport>, BaseError> {
72    collect_outcomes(sync_table_definitions_grouped_outcomes(tools, definitions).await)
73}
74
75fn collect_outcomes<T>(
76    outcomes: BTreeMap<DatasourceId, Result<T, BaseError>>,
77) -> Result<BTreeMap<DatasourceId, T>, BaseError> {
78    let mut reports = BTreeMap::new();
79    for (source, outcome) in outcomes {
80        reports.insert(source, outcome?);
81    }
82    Ok(reports)
83}
84
85fn group_definitions<'a>(
86    definitions: &[&'a TableDefinition],
87) -> BTreeMap<DatasourceId, Vec<&'a TableDefinition>> {
88    let mut groups: BTreeMap<DatasourceId, Vec<&'a TableDefinition>> = BTreeMap::new();
89    for definition in definitions {
90        groups
91            .entry(definition.datasource().clone())
92            .or_default()
93            .push(*definition);
94    }
95    groups
96}
97
98/// 持有数据库连接并执行 [`crate::table::TableDefinition`] 声明的结构同步。
99pub struct DatabaseInitializer {
100    /// 显式拥有的数据库实例。
101    db: AnyDatabase,
102}
103
104impl DatabaseInitializer {
105    /// 用 MySQL 连接构造同步器(保持既有调用方式)。
106    ///
107    /// 逻辑源固定为 `default`;具名数据源必须使用
108    /// [`Self::from_any`] 并传入 `tools.database_named(id)?` 的容器。
109    #[cfg(feature = "mysql")]
110    pub fn new(db: yang_db::mysql::Database) -> Self {
111        Self::from_any(AnyDatabase::mysql(db))
112    }
113
114    /// 用 PostgreSQL 连接构造同步器。
115    ///
116    /// 逻辑源固定为 `default`;接入具名源时同样应使用 [`Self::from_any`]。
117    #[cfg(feature = "postgres")]
118    pub fn new_postgres(db: yang_db::postgres::Database) -> Self {
119        Self::from_any(AnyDatabase::postgres(db))
120    }
121
122    /// 用运行时数据库容器构造同步器。
123    pub fn from_any(db: AnyDatabase) -> Self {
124        Self { db }
125    }
126
127    /// 返回底层数据库容器。
128    pub(crate) fn db(&self) -> &AnyDatabase {
129        &self.db
130    }
131}