Skip to main content

yang_base/database/
schema_sync.rs

1//! 基于模块 [`TableDefinition`] 的 MySQL 启动期 additive schema 同步。
2//!
3//! 同步器只创建缺失表、字段、主键和索引;不会删除列/索引,也不会自动修改已有
4//! 字段类型或 NULL 约束。多实例同时启动时使用同一 MySQL 会话持有 advisory lock,
5//! DDL 中断后下一实例可按 information_schema 重新规划并幂等续作。
6
7use super::DatabaseInitializer;
8use crate::error::BaseError;
9use crate::table::{
10    FieldConfig, FieldType, SchemaColumn, SchemaIssueKind, TableConfig, TableDefinition,
11};
12use sqlx::mysql::MySqlConnection;
13use sqlx::{Executor, FromRow};
14use std::collections::BTreeMap;
15
16const SCHEMA_LOCK_TIMEOUT_SECONDS: i64 = 30;
17
18/// schema 同步变更类型。
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum SchemaSyncChangeKind {
22    /// 创建整张表。
23    CreatedTable,
24    /// 增加字段。
25    AddedColumn,
26    /// 增加主键。
27    AddedPrimaryKey,
28    /// 增加普通或唯一索引。
29    AddedIndex,
30}
31
32/// 一项实际执行的 schema 变更。
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct SchemaSyncChange {
36    /// 表名。
37    pub table: String,
38    /// 变更对象;建表时等于表名,其它变更为字段或索引名。
39    pub object: String,
40    /// 变更类型。
41    pub kind: SchemaSyncChangeKind,
42}
43
44/// 启动期 schema 同步报告。
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46#[non_exhaustive]
47pub struct SchemaSyncReport {
48    /// 已检查的表名,按名称确定性排序。
49    pub tables: Vec<String>,
50    /// 本次实际执行的 additive 变更。
51    pub changes: Vec<SchemaSyncChange>,
52}
53
54impl SchemaSyncReport {
55    /// 是否没有执行任何 DDL。
56    pub fn is_noop(&self) -> bool {
57        self.changes.is_empty()
58    }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub(super) struct ExistingIndex {
63    name: String,
64    unique: bool,
65    columns: Vec<String>,
66}
67
68impl ExistingIndex {
69    pub(super) fn new(name: impl Into<String>, unique: bool, columns: Vec<String>) -> Self {
70        Self {
71            name: name.into(),
72            unique,
73            columns,
74        }
75    }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub(super) struct ExistingTableSchema {
80    exists: bool,
81    columns: Vec<SchemaColumn>,
82    primary_key: Vec<String>,
83    indexes: Vec<ExistingIndex>,
84    has_rows: bool,
85}
86
87impl ExistingTableSchema {
88    pub(super) fn missing() -> Self {
89        Self {
90            exists: false,
91            columns: Vec::new(),
92            primary_key: Vec::new(),
93            indexes: Vec::new(),
94            has_rows: false,
95        }
96    }
97
98    pub(super) fn existing(
99        columns: Vec<SchemaColumn>,
100        primary_key: Vec<String>,
101        indexes: Vec<ExistingIndex>,
102    ) -> Self {
103        Self {
104            exists: true,
105            columns,
106            primary_key,
107            indexes,
108            has_rows: false,
109        }
110    }
111
112    fn with_rows(mut self, has_rows: bool) -> Self {
113        self.has_rows = has_rows;
114        self
115    }
116}
117
118#[derive(Debug)]
119pub(super) struct TableSyncPlan {
120    pub(super) statements: Vec<String>,
121    pub(super) changes: Vec<SchemaSyncChange>,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
125struct DesiredIndex {
126    name: String,
127    unique: bool,
128    columns: Vec<String>,
129}
130
131impl DatabaseInitializer {
132    /// 只读取当前数据库 schema 并计算待执行变更,不获取同步锁、不执行 DDL。
133    ///
134    /// 适用于生产启动门禁:返回非空 `changes` 表示数据库尚未与定义对齐;不兼容
135    /// 变更仍返回错误。调用方若要实际应用变更,应使用 [`Self::sync_table_definitions`]。
136    pub async fn plan_table_definitions(
137        &self,
138        definitions: &[&TableDefinition],
139    ) -> Result<SchemaSyncReport, BaseError> {
140        let definitions = normalize_definitions(definitions)?;
141        if definitions.is_empty() {
142            return Ok(SchemaSyncReport::default());
143        }
144        let mut connection = self
145            .db()
146            .pool()
147            .acquire()
148            .await
149            .map_err(|error| BaseError::DatabaseConnectionDbError(error.into()))?;
150        let plans = plan_locked(&mut connection, &definitions).await?;
151        Ok(SchemaSyncReport {
152            tables: report_tables(&definitions),
153            changes: plans.into_iter().flat_map(|plan| plan.changes).collect(),
154        })
155    }
156
157    /// 同步一组不可变表定义,使用单个数据库级 advisory lock 串行化多实例启动。
158    pub async fn sync_table_definitions(
159        &self,
160        definitions: &[&TableDefinition],
161    ) -> Result<SchemaSyncReport, BaseError> {
162        let definitions = normalize_definitions(definitions)?;
163        if definitions.is_empty() {
164            return Ok(SchemaSyncReport::default());
165        }
166
167        let mut connection = self
168            .db()
169            .pool()
170            .acquire()
171            .await
172            .map_err(|error| BaseError::DatabaseConnectionDbError(error.into()))?;
173        let database_name: Option<String> = sqlx::query_scalar("SELECT DATABASE()")
174            .fetch_one(&mut *connection)
175            .await
176            .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
177        let database_name = database_name.ok_or_else(|| {
178            BaseError::DatabaseInitFailed("当前 MySQL 连接没有选定数据库".to_string())
179        })?;
180        let lock_name = schema_lock_name(&database_name);
181        let acquired: Option<i64> = sqlx::query_scalar("SELECT GET_LOCK(?, ?)")
182            .bind(&lock_name)
183            .bind(SCHEMA_LOCK_TIMEOUT_SECONDS)
184            .fetch_one(&mut *connection)
185            .await
186            .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
187        if acquired != Some(1) {
188            return Err(BaseError::DatabaseInitFailed(format!(
189                "等待 schema 同步锁超时: {lock_name}"
190            )));
191        }
192
193        let result = sync_locked(&mut connection, &definitions).await;
194        let release_result: Result<Option<i64>, sqlx::Error> =
195            sqlx::query_scalar("SELECT RELEASE_LOCK(?)")
196                .bind(&lock_name)
197                .fetch_one(&mut *connection)
198                .await;
199
200        match (result, release_result) {
201            (Err(error), _) => Err(error),
202            (Ok(_), Err(error)) => Err(BaseError::DatabaseQueryFailed(error.into())),
203            (Ok(report), Ok(Some(1))) => Ok(report),
204            (Ok(_), Ok(_)) => Err(BaseError::DatabaseInitFailed(format!(
205                "schema 同步锁释放失败: {lock_name}"
206            ))),
207        }
208    }
209}
210
211async fn sync_locked(
212    connection: &mut MySqlConnection,
213    definitions: &[&TableDefinition],
214) -> Result<SchemaSyncReport, BaseError> {
215    let mut report = SchemaSyncReport {
216        tables: report_tables(definitions),
217        changes: Vec::new(),
218    };
219
220    let plans = plan_locked(connection, definitions).await?;
221    for plan in plans {
222        for (statement, change) in plan.statements.into_iter().zip(plan.changes) {
223            connection
224                .execute(sqlx::query(&statement))
225                .await
226                .map_err(|error| BaseError::DatabaseExecuteFailed(error.into()))?;
227            tracing::info!(
228                table = %change.table,
229                object = %change.object,
230                kind = ?change.kind,
231                "数据库 schema 已同步"
232            );
233            report.changes.push(change);
234        }
235    }
236
237    Ok(report)
238}
239
240async fn plan_locked(
241    connection: &mut MySqlConnection,
242    definitions: &[&TableDefinition],
243) -> Result<Vec<TableSyncPlan>, BaseError> {
244    let mut plans = Vec::with_capacity(definitions.len());
245    for definition in definitions {
246        let existing = load_existing_schema(connection, definition).await?;
247        let plan = plan_table_sync(definition, &existing)?;
248        if plan.statements.len() != plan.changes.len() {
249            return Err(BaseError::DatabaseInitFailed(format!(
250                "表 {} 的 schema 计划内部不一致",
251                definition.name()
252            )));
253        }
254        plans.push(plan);
255    }
256    Ok(plans)
257}
258
259fn report_tables(definitions: &[&TableDefinition]) -> Vec<String> {
260    definitions
261        .iter()
262        .map(|definition| definition.name().to_string())
263        .collect()
264}
265
266async fn load_existing_schema(
267    connection: &mut MySqlConnection,
268    definition: &TableDefinition,
269) -> Result<ExistingTableSchema, BaseError> {
270    let table = definition.config();
271    #[derive(FromRow)]
272    struct ColumnRow {
273        column_name: String,
274        data_type: String,
275        column_type: String,
276        is_nullable: String,
277        character_maximum_length: Option<i64>,
278        column_default: Option<String>,
279        extra: String,
280    }
281
282    #[derive(FromRow)]
283    struct IndexRow {
284        index_name: String,
285        non_unique: i64,
286        column_name: String,
287    }
288
289    let count: i64 = sqlx::query_scalar(
290        "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?",
291    )
292    .bind(&table.table_name)
293    .fetch_one(&mut *connection)
294    .await
295    .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
296    if count == 0 {
297        return Ok(ExistingTableSchema::missing());
298    }
299
300    let column_rows: Vec<ColumnRow> = sqlx::query_as(
301        "SELECT CAST(COLUMN_NAME AS CHAR) AS column_name, CAST(DATA_TYPE AS CHAR) AS data_type, CAST(COLUMN_TYPE AS CHAR) AS column_type, CAST(IS_NULLABLE AS CHAR) AS is_nullable, CAST(CHARACTER_MAXIMUM_LENGTH AS SIGNED) AS character_maximum_length, CAST(COLUMN_DEFAULT AS CHAR) AS column_default, CAST(EXTRA AS CHAR) AS extra FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? ORDER BY ORDINAL_POSITION",
302    )
303    .bind(&table.table_name)
304    .fetch_all(&mut *connection)
305    .await
306    .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
307    let columns = column_rows
308        .into_iter()
309        .map(|row| {
310            SchemaColumn::new(
311                row.column_name,
312                row.data_type,
313                row.column_type,
314                row.is_nullable.eq_ignore_ascii_case("YES"),
315                row.character_maximum_length
316                    .and_then(|length| u64::try_from(length).ok()),
317                row.column_default,
318            )
319            .with_auto_increment(
320                row.extra
321                    .split_whitespace()
322                    .any(|part| part.eq_ignore_ascii_case("auto_increment")),
323            )
324        })
325        .collect();
326
327    let primary_key: Vec<String> = sqlx::query_scalar(
328        "SELECT CAST(COLUMN_NAME AS CHAR) FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = 'PRIMARY' ORDER BY SEQ_IN_INDEX",
329    )
330    .bind(&table.table_name)
331    .fetch_all(&mut *connection)
332    .await
333    .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
334
335    let index_rows: Vec<IndexRow> = sqlx::query_as(
336        "SELECT CAST(INDEX_NAME AS CHAR) AS index_name, CAST(NON_UNIQUE AS SIGNED) AS non_unique, CAST(COLUMN_NAME AS CHAR) AS column_name FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name <> 'PRIMARY' ORDER BY INDEX_NAME, SEQ_IN_INDEX",
337    )
338    .bind(&table.table_name)
339    .fetch_all(&mut *connection)
340    .await
341    .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
342    let mut index_map: BTreeMap<String, (bool, Vec<String>)> = BTreeMap::new();
343    for row in index_rows {
344        let entry = index_map
345            .entry(row.index_name)
346            .or_insert_with(|| (row.non_unique == 0, Vec::new()));
347        entry.1.push(row.column_name);
348    }
349    let indexes = index_map
350        .into_iter()
351        .map(|(name, (unique, columns))| ExistingIndex::new(name, unique, columns))
352        .collect();
353
354    let quoted_table = quote_identifier(&table.table_name)?;
355    let has_rows: Option<i64> =
356        sqlx::query_scalar(&format!("SELECT 1 FROM {quoted_table} LIMIT 1"))
357            .fetch_optional(&mut *connection)
358            .await
359            .map_err(|error| BaseError::DatabaseQueryFailed(error.into()))?;
360
361    Ok(ExistingTableSchema::existing(columns, primary_key, indexes).with_rows(has_rows.is_some()))
362}
363
364pub(super) fn plan_table_sync(
365    definition: &TableDefinition,
366    existing: &ExistingTableSchema,
367) -> Result<TableSyncPlan, BaseError> {
368    let table = definition.config();
369    validate_table_config(table)?;
370    if !existing.exists {
371        return Ok(TableSyncPlan {
372            statements: vec![render_create_table(table)?],
373            changes: vec![SchemaSyncChange {
374                table: table.table_name.clone(),
375                object: table.table_name.clone(),
376                kind: SchemaSyncChangeKind::CreatedTable,
377            }],
378        });
379    }
380
381    let report = table.validate_schema(&existing.columns);
382    let unsafe_issues: Vec<_> = report
383        .issues
384        .iter()
385        .filter(|issue| issue.kind != SchemaIssueKind::MissingColumn)
386        .collect();
387    if !unsafe_issues.is_empty() {
388        let details = unsafe_issues
389            .iter()
390            .map(|issue| format!("{}:{:?}", issue.field, issue.kind))
391            .collect::<Vec<_>>()
392            .join(", ");
393        return Err(BaseError::DatabaseInitFailed(format!(
394            "表 {} 存在不可自动修改的 schema 差异: {details}",
395            table.table_name
396        )));
397    }
398
399    let quoted_table = quote_identifier(&table.table_name)?;
400    let mut statements = Vec::new();
401    let mut changes = Vec::new();
402    let mut fields: Vec<&FieldConfig> = table.fields.values().collect();
403    fields.sort_by(|left, right| left.name.cmp(&right.name));
404    for field in fields {
405        if existing
406            .columns
407            .iter()
408            .any(|column| column.name == field.name)
409        {
410            continue;
411        }
412        if field.auto_increment {
413            return Err(BaseError::DatabaseInitFailed(format!(
414                "表 {} 已存在,缺失的自增主键字段 {} 不能安全地分步增加;请人工处理后再启动",
415                table.table_name, field.name
416            )));
417        }
418        if existing.has_rows
419            && field.required
420            && field.default_value.is_none()
421            && !field.auto_increment
422        {
423            return Err(BaseError::DatabaseInitFailed(format!(
424                "表 {} 已有数据,不能自动增加无默认值的必填字段 {}",
425                table.table_name, field.name
426            )));
427        }
428        statements.push(format!(
429            "ALTER TABLE {quoted_table} ADD COLUMN {}",
430            render_column(field)?
431        ));
432        changes.push(SchemaSyncChange {
433            table: table.table_name.clone(),
434            object: field.name.clone(),
435            kind: SchemaSyncChangeKind::AddedColumn,
436        });
437    }
438
439    let desired_primary = vec![table.primary_key.clone()];
440    if existing.primary_key.is_empty() {
441        statements.push(format!(
442            "ALTER TABLE {quoted_table} ADD PRIMARY KEY ({})",
443            quote_identifier(&table.primary_key)?
444        ));
445        changes.push(SchemaSyncChange {
446            table: table.table_name.clone(),
447            object: table.primary_key.clone(),
448            kind: SchemaSyncChangeKind::AddedPrimaryKey,
449        });
450    } else if existing.primary_key != desired_primary {
451        return Err(BaseError::DatabaseInitFailed(format!(
452            "表 {} 的主键 {:?} 与声明 {:?} 不一致,拒绝自动修改",
453            table.table_name, existing.primary_key, desired_primary
454        )));
455    }
456
457    for desired in desired_indexes(table)? {
458        if let Some(existing_named) = existing
459            .indexes
460            .iter()
461            .find(|index| index.name == desired.name)
462        {
463            if existing_named.unique == desired.unique && existing_named.columns == desired.columns
464            {
465                continue;
466            }
467            return Err(BaseError::DatabaseInitFailed(format!(
468                "表 {} 的索引 {} 已存在但定义不同,拒绝自动修改",
469                table.table_name, desired.name
470            )));
471        }
472        let already_exists = existing.indexes.iter().any(|index| {
473            index.columns == desired.columns && (index.unique == desired.unique || index.unique)
474        });
475        if already_exists {
476            continue;
477        }
478        let columns = desired
479            .columns
480            .iter()
481            .map(|column| quote_identifier(column))
482            .collect::<Result<Vec<_>, _>>()?
483            .join(", ");
484        let kind = if desired.unique {
485            "UNIQUE INDEX"
486        } else {
487            "INDEX"
488        };
489        statements.push(format!(
490            "ALTER TABLE {quoted_table} ADD {kind} {} ({columns})",
491            quote_identifier(&desired.name)?
492        ));
493        changes.push(SchemaSyncChange {
494            table: table.table_name.clone(),
495            object: desired.name,
496            kind: SchemaSyncChangeKind::AddedIndex,
497        });
498    }
499
500    Ok(TableSyncPlan {
501        statements,
502        changes,
503    })
504}
505
506fn normalize_definitions<'a>(
507    definitions: &'a [&'a TableDefinition],
508) -> Result<Vec<&'a TableDefinition>, BaseError> {
509    let mut normalized: BTreeMap<&str, (&TableDefinition, String)> = BTreeMap::new();
510    for definition in definitions {
511        let table = definition.config();
512        validate_table_config(table)?;
513        let signature = render_create_table(table)?;
514        if let Some((_, existing_signature)) = normalized.get(table.table_name.as_str()) {
515            if existing_signature != &signature {
516                return Err(BaseError::ConfigError(format!(
517                    "表配置冲突: {} 在多个模块中声明不同 schema",
518                    table.table_name
519                )));
520            }
521            continue;
522        }
523        normalized.insert(table.table_name.as_str(), (*definition, signature));
524    }
525    Ok(normalized
526        .into_values()
527        .map(|(definition, _)| definition)
528        .collect())
529}
530
531fn validate_table_config(table: &TableConfig) -> Result<(), BaseError> {
532    quote_identifier(&table.table_name)?;
533    if table.fields.is_empty() {
534        return Err(BaseError::ConfigError(format!(
535            "表 {} 没有声明字段",
536            table.table_name
537        )));
538    }
539    let primary = table.fields.get(&table.primary_key).ok_or_else(|| {
540        BaseError::ConfigError(format!(
541            "表 {} 的主键字段 {} 未声明",
542            table.table_name, table.primary_key
543        ))
544    })?;
545    if !primary.required {
546        return Err(BaseError::ConfigError(format!(
547            "表 {} 的主键字段 {} 必须 required",
548            table.table_name, table.primary_key
549        )));
550    }
551    for field in table.fields.values() {
552        quote_identifier(&field.name)?;
553        if field.auto_increment
554            && (field.name != table.primary_key
555                || !matches!(field.field_type, FieldType::Integer | FieldType::BigInt))
556        {
557            return Err(BaseError::ConfigError(format!(
558                "表 {} 的 auto_increment 仅允许用于整数主键字段: {}",
559                table.table_name, field.name
560            )));
561        }
562        if field.auto_increment && field.default_value.is_some() {
563            return Err(BaseError::ConfigError(format!(
564                "表 {} 的自增字段不能同时声明默认值: {}",
565                table.table_name, field.name
566            )));
567        }
568        let _ = render_column(field)?;
569    }
570    let _ = desired_indexes(table)?;
571    Ok(())
572}
573
574fn render_create_table(table: &TableConfig) -> Result<String, BaseError> {
575    let mut fields: Vec<&FieldConfig> = table.fields.values().collect();
576    fields.sort_by(|left, right| left.name.cmp(&right.name));
577    let mut definitions = fields
578        .into_iter()
579        .map(render_column)
580        .collect::<Result<Vec<_>, _>>()?;
581    definitions.push(format!(
582        "PRIMARY KEY ({})",
583        quote_identifier(&table.primary_key)?
584    ));
585    for index in desired_indexes(table)? {
586        let columns = index
587            .columns
588            .iter()
589            .map(|column| quote_identifier(column))
590            .collect::<Result<Vec<_>, _>>()?
591            .join(", ");
592        let kind = if index.unique { "UNIQUE KEY" } else { "KEY" };
593        definitions.push(format!(
594            "{kind} {} ({columns})",
595            quote_identifier(&index.name)?
596        ));
597    }
598    Ok(format!(
599        "CREATE TABLE {} ({}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
600        quote_identifier(&table.table_name)?,
601        definitions.join(", ")
602    ))
603}
604
605fn render_column(field: &FieldConfig) -> Result<String, BaseError> {
606    let sql_type = match &field.field_type {
607        FieldType::String { max_length } if (1..=16_383).contains(max_length) => {
608            format!("VARCHAR({max_length})")
609        }
610        FieldType::String { max_length } => {
611            return Err(BaseError::ConfigError(format!(
612                "字段 {} 的 VARCHAR 长度必须在 1..=16383: {}",
613                field.name, max_length
614            )))
615        }
616        FieldType::Integer => "INT".to_string(),
617        FieldType::BigInt => "BIGINT".to_string(),
618        FieldType::Float => "FLOAT".to_string(),
619        FieldType::Double => "DOUBLE".to_string(),
620        FieldType::Decimal { precision, scale } => format!("DECIMAL({precision},{scale})"),
621        FieldType::Boolean => "TINYINT(1)".to_string(),
622        FieldType::Date => "DATE".to_string(),
623        FieldType::DateTime => "DATETIME".to_string(),
624        FieldType::Timestamp => "BIGINT".to_string(),
625        FieldType::Json => "JSON".to_string(),
626        FieldType::Text => "TEXT".to_string(),
627        FieldType::Enum { values } => {
628            if values.is_empty() || values.iter().any(|value| value.is_empty()) {
629                return Err(BaseError::ConfigError(format!(
630                    "枚举字段 {} 必须声明非空值",
631                    field.name
632                )));
633            }
634            let mut sorted = values.clone();
635            sorted.sort();
636            if sorted.windows(2).any(|pair| pair[0] == pair[1]) {
637                return Err(BaseError::ConfigError(format!(
638                    "枚举字段 {} 包含重复值",
639                    field.name
640                )));
641            }
642            format!(
643                "ENUM({})",
644                values
645                    .iter()
646                    .map(|value| quote_string(value))
647                    .collect::<Vec<_>>()
648                    .join(", ")
649            )
650        }
651    };
652
653    let mut definition = format!(
654        "{} {sql_type} {}",
655        quote_identifier(&field.name)?,
656        if field.required { "NOT NULL" } else { "NULL" }
657    );
658    if field.auto_increment {
659        definition.push_str(" AUTO_INCREMENT");
660    }
661    if let Some(default) = &field.default_value {
662        if default.is_null() && field.required {
663            return Err(BaseError::ConfigError(format!(
664                "必填字段 {} 不能声明 NULL 默认值",
665                field.name
666            )));
667        }
668        if matches!(field.field_type, FieldType::Text | FieldType::Json) {
669            return Err(BaseError::ConfigError(format!(
670                "TEXT/JSON 字段 {} 不自动生成数据库默认值",
671                field.name
672            )));
673        }
674        if !default.is_null() {
675            field.field_type.validate(&field.name, default)?;
676        }
677        definition.push_str(" DEFAULT ");
678        definition.push_str(&render_default(default)?);
679    }
680    Ok(definition)
681}
682
683fn render_default(value: &serde_json::Value) -> Result<String, BaseError> {
684    match value {
685        serde_json::Value::Null => Ok("NULL".to_string()),
686        serde_json::Value::Bool(value) => Ok(if *value { "1" } else { "0" }.to_string()),
687        serde_json::Value::Number(value) => Ok(value.to_string()),
688        serde_json::Value::String(value) => Ok(quote_string(value)),
689        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Err(BaseError::ConfigError(
690            "数据库字段默认值只支持 null/bool/number/string".to_string(),
691        )),
692    }
693}
694
695fn desired_indexes(table: &TableConfig) -> Result<Vec<DesiredIndex>, BaseError> {
696    let mut desired = Vec::new();
697    for (unique, indexes) in [
698        (true, table.unique_indexes.as_slice()),
699        (false, table.indexes.as_slice()),
700    ] {
701        for index in indexes {
702            if index.fields.is_empty() {
703                return Err(BaseError::ConfigError(format!(
704                    "表 {} 包含空索引",
705                    table.table_name
706                )));
707            }
708            for field in &index.fields {
709                if !table.fields.contains_key(field) {
710                    return Err(BaseError::ConfigError(format!(
711                        "表 {} 的索引引用未声明字段: {}",
712                        table.table_name, field
713                    )));
714                }
715            }
716            let prefix = if unique { "uk" } else { "idx" };
717            let name = index.name.clone().unwrap_or_else(|| {
718                format!("{prefix}_{}_{}", table.table_name, index.fields.join("_"))
719            });
720            if name.len() > 64 {
721                return Err(BaseError::ConfigError(format!(
722                    "索引名超过 MySQL 64 字符限制,请显式命名: {name}"
723                )));
724            }
725            quote_identifier(&name)?;
726            desired.push(DesiredIndex {
727                name,
728                unique,
729                columns: index.fields.clone(),
730            });
731        }
732    }
733    Ok(desired)
734}
735
736fn quote_identifier(identifier: &str) -> Result<String, BaseError> {
737    yang_db::mysql::quote_identifier(identifier).map_err(|error| {
738        BaseError::ConfigError(format!("非法数据库标识符 {identifier:?}: {error}"))
739    })
740}
741
742fn quote_string(value: &str) -> String {
743    format!("'{}'", value.replace('\\', "\\\\").replace('\'', "''"))
744}
745
746fn schema_lock_name(database_name: &str) -> String {
747    let mut hash: u64 = 0xcbf29ce484222325;
748    for byte in database_name.as_bytes() {
749        hash ^= u64::from(*byte);
750        hash = hash.wrapping_mul(0x100000001b3);
751    }
752    format!("yang_base_schema_{hash:016x}")
753}