yang-base 0.3.0

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use super::model::{DesiredIndex, ExistingForeignKey};
use crate::error::BaseError;
use crate::table::{
    CheckConfig, FieldConfig, FieldType, ForeignKeyConfig, TableConfig, TableDefinition,
    MAX_VARCHAR_LENGTH,
};
use std::collections::BTreeMap;

pub(super) fn normalize_definitions<'a>(
    definitions: &'a [&'a TableDefinition],
) -> Result<Vec<&'a TableDefinition>, BaseError> {
    let mut normalized: BTreeMap<&str, (&TableDefinition, String)> = BTreeMap::new();
    for definition in definitions {
        let table = definition.config();
        validate_table_config(table)?;
        let signature = render_create_table(table, true)?;
        if let Some((_, existing_signature)) = normalized.get(table.table_name.as_str()) {
            if existing_signature != &signature {
                return Err(BaseError::ConfigError(format!(
                    "表配置冲突: {} 在多个模块中声明不同 schema",
                    table.table_name
                )));
            }
            continue;
        }
        normalized.insert(table.table_name.as_str(), (*definition, signature));
    }
    Ok(normalized
        .into_values()
        .map(|(definition, _)| definition)
        .collect())
}

pub(super) fn validate_table_config(table: &TableConfig) -> Result<(), BaseError> {
    quote_identifier(&table.table_name)?;
    if table.fields.is_empty() {
        return Err(BaseError::ConfigError(format!(
            "表 {} 没有声明字段",
            table.table_name
        )));
    }
    let primary = table.fields.get(&table.primary_key).ok_or_else(|| {
        BaseError::ConfigError(format!(
            "表 {} 的主键字段 {} 未声明",
            table.table_name, table.primary_key
        ))
    })?;
    if !primary.required {
        return Err(BaseError::ConfigError(format!(
            "表 {} 的主键字段 {} 必须 required",
            table.table_name, table.primary_key
        )));
    }
    for field in table.fields.values() {
        quote_identifier(&field.name)?;
        if field.auto_increment
            && (field.name != table.primary_key
                || !matches!(field.field_type, FieldType::Integer | FieldType::BigInt))
        {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的 auto_increment 仅允许用于整数主键字段: {}",
                table.table_name, field.name
            )));
        }
        if field.auto_increment && field.default_value.is_some() {
            return Err(BaseError::ConfigError(format!(
                "表 {} 的自增字段不能同时声明默认值: {}",
                table.table_name, field.name
            )));
        }
        let _ = render_column(field)?;
    }
    let _ = desired_indexes(table)?;
    Ok(())
}

pub(super) fn render_create_table(
    table: &TableConfig,
    include_foreign_keys: bool,
) -> Result<String, BaseError> {
    let mut fields: Vec<&FieldConfig> = table.fields.values().collect();
    fields.sort_by(|left, right| left.name.cmp(&right.name));
    let mut definitions = fields
        .into_iter()
        .map(render_column)
        .collect::<Result<Vec<_>, _>>()?;
    definitions.push(format!(
        "PRIMARY KEY ({})",
        quote_identifier(&table.primary_key)?
    ));
    for index in desired_indexes(table)? {
        let columns = index
            .columns
            .iter()
            .map(|column| quote_identifier(column))
            .collect::<Result<Vec<_>, _>>()?
            .join(", ");
        let kind = if index.unique { "UNIQUE KEY" } else { "KEY" };
        definitions.push(format!(
            "{kind} {} ({columns})",
            quote_identifier(&index.name)?
        ));
    }
    for check in &table.checks {
        definitions.push(render_check(check)?);
    }
    if include_foreign_keys {
        for foreign_key in &table.foreign_keys {
            definitions.push(render_foreign_key(foreign_key)?);
        }
    }
    Ok(format!(
        "CREATE TABLE {} ({}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        quote_identifier(&table.table_name)?,
        definitions.join(", ")
    ))
}

pub(super) fn render_check(check: &CheckConfig) -> Result<String, BaseError> {
    Ok(format!(
        "CONSTRAINT {} CHECK ({})",
        quote_identifier(&check.name)?,
        check.expression
    ))
}

pub(super) fn render_foreign_key(foreign_key: &ForeignKeyConfig) -> Result<String, BaseError> {
    let columns = foreign_key
        .columns
        .iter()
        .map(|column| quote_identifier(column))
        .collect::<Result<Vec<_>, _>>()?
        .join(", ");
    let referenced_columns = foreign_key
        .referenced_columns
        .iter()
        .map(|column| quote_identifier(column))
        .collect::<Result<Vec<_>, _>>()?
        .join(", ");
    Ok(format!(
        "CONSTRAINT {} FOREIGN KEY ({columns}) REFERENCES {} ({referenced_columns})",
        quote_identifier(&foreign_key.name)?,
        quote_identifier(&foreign_key.referenced_table)?
    ))
}

pub(super) fn normalize_check_expression(expression: &str) -> String {
    // MySQL 读回 CHECK 表达式时会对字符串字面量叠加多层转义(层数随版本与
    // 元数据路径不同,如 information_schema 中 `\.` 可读回为 `\\\\.`),
    // 循环解码反斜杠转义直到收敛,保证同一约束的声明侧与读回侧归一。
    let mut decoded = expression.to_string();
    loop {
        let next = decoded.replace("\\\\", "\\").replace("\\'", "'");
        if next == decoded {
            break;
        }
        decoded = next;
    }

    // 再逐字符归一化并跟踪引号态:字符串字面量内容必须原样保留,
    // 否则 'x y' 与 'xy' 会被错误归一为同一约束,导致 plan 静默跳过变更。
    let mut normalized = String::with_capacity(decoded.len());
    let mut characters = decoded.char_indices().peekable();
    while let Some((index, character)) = characters.next() {
        if character == '\'' {
            normalized.push(character);
            let mut escaped = false;
            while let Some((_, literal)) = characters.next() {
                normalized.push(literal);
                if escaped {
                    escaped = false;
                    continue;
                }
                match literal {
                    '\\' => escaped = true,
                    '\'' => {
                        // '' 是字面量内的转义引号,仍属字面量内容。
                        if matches!(characters.peek(), Some((_, '\''))) {
                            continue;
                        }
                        break;
                    }
                    _ => {}
                }
            }
            continue;
        }
        if character == '`' || character.is_ascii_whitespace() {
            continue;
        }
        if character == '_' {
            // 读回侧会在字面量前加 charset introducer(如 _utf8mb4'x'),
            // 只在紧邻引号时剔除,避免误伤以 _utf8 开头的标识符。
            let rest = &decoded[index..];
            if let Some(introducer) = ["_utf8mb4", "_utf8"].into_iter().find(|candidate| {
                rest.get(..candidate.len())
                    .is_some_and(|prefix| prefix.eq_ignore_ascii_case(candidate))
                    && rest
                        .get(candidate.len()..)
                        .is_some_and(|tail| tail.starts_with('\''))
            }) {
                for _ in 1..introducer.chars().count() {
                    characters.next();
                }
                continue;
            }
        }
        normalized.extend(character.to_lowercase());
    }

    while has_redundant_outer_parentheses(&normalized) {
        normalized = normalized[1..normalized.len() - 1].to_string();
    }
    normalized
}

fn has_redundant_outer_parentheses(expression: &str) -> bool {
    if !expression.starts_with('(') || !expression.ends_with(')') {
        return false;
    }
    let mut depth = 0_i32;
    let mut quoted = false;
    let mut previous_quote = false;
    for (index, character) in expression.char_indices() {
        if character == '\'' {
            if quoted && previous_quote {
                previous_quote = false;
                continue;
            }
            previous_quote = quoted;
            quoted = !quoted;
            continue;
        }
        previous_quote = false;
        if quoted {
            continue;
        }
        match character {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 && index + character.len_utf8() != expression.len() {
                    return false;
                }
            }
            _ => {}
        }
        if depth < 0 {
            return false;
        }
    }
    depth == 0 && !quoted
}

pub(super) fn foreign_key_matches(
    existing: &ExistingForeignKey,
    desired: &ForeignKeyConfig,
    renamed_columns: &BTreeMap<String, String>,
) -> bool {
    let columns = existing
        .columns
        .iter()
        .map(|column| {
            renamed_columns
                .get(column)
                .cloned()
                .unwrap_or_else(|| column.clone())
        })
        .collect::<Vec<_>>();
    columns == desired.columns
        && existing.referenced_table == desired.referenced_table
        && existing.referenced_columns == desired.referenced_columns
        && matches!(existing.update_rule.as_str(), "RESTRICT" | "NO ACTION")
        && matches!(existing.delete_rule.as_str(), "RESTRICT" | "NO ACTION")
}

pub(super) fn existing_column_name(
    column: &str,
    renamed_columns: &BTreeMap<String, String>,
) -> String {
    renamed_columns
        .iter()
        .find_map(|(legacy, current)| (current == column).then(|| legacy.clone()))
        .unwrap_or_else(|| column.to_string())
}

pub(super) fn expression_for_existing_schema(
    expression: &str,
    renamed_columns: &BTreeMap<String, String>,
) -> String {
    renamed_columns
        .iter()
        .fold(expression.to_string(), |expression, (legacy, current)| {
            expression.replace(&format!("`{current}`"), &format!("`{legacy}`"))
        })
}

pub(super) fn render_column(field: &FieldConfig) -> Result<String, BaseError> {
    let sql_type = match &field.field_type {
        // 防御性断言:构建期 validate_field_shape 已强制同一上界,
        // 此处不应再可达;保留 Err 以免绕过构建期的配置静默渲染出非法 DDL。
        FieldType::String { max_length } if (1..=MAX_VARCHAR_LENGTH).contains(max_length) => {
            format!("VARCHAR({max_length})")
        }
        FieldType::String { max_length } => {
            return Err(BaseError::ConfigError(format!(
                "字段 {} 的 VARCHAR 长度必须在 1..={MAX_VARCHAR_LENGTH}: {}",
                field.name, max_length
            )))
        }
        FieldType::Integer => "INT".to_string(),
        FieldType::BigInt => "BIGINT".to_string(),
        FieldType::Float => "FLOAT".to_string(),
        FieldType::Double => "DOUBLE".to_string(),
        FieldType::Decimal { precision, scale } => format!("DECIMAL({precision},{scale})"),
        FieldType::Boolean => "TINYINT(1)".to_string(),
        FieldType::Date => "DATE".to_string(),
        FieldType::DateTime => "DATETIME".to_string(),
        FieldType::Timestamp => "BIGINT".to_string(),
        FieldType::Json => "JSON".to_string(),
        FieldType::Text => "TEXT".to_string(),
        FieldType::Enum { values } => {
            if values.is_empty() || values.iter().any(|value| value.is_empty()) {
                return Err(BaseError::ConfigError(format!(
                    "枚举字段 {} 必须声明非空值",
                    field.name
                )));
            }
            let mut sorted = values.clone();
            sorted.sort();
            if sorted.windows(2).any(|pair| pair[0] == pair[1]) {
                return Err(BaseError::ConfigError(format!(
                    "枚举字段 {} 包含重复值",
                    field.name
                )));
            }
            format!(
                "ENUM({})",
                values
                    .iter()
                    .map(|value| quote_string(value))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    };

    let mut definition = format!(
        "{} {sql_type} {}",
        quote_identifier(&field.name)?,
        if field.required { "NOT NULL" } else { "NULL" }
    );
    if field.auto_increment {
        definition.push_str(" AUTO_INCREMENT");
    }
    if let Some(default) = &field.default_value {
        if default.is_null() && field.required {
            return Err(BaseError::ConfigError(format!(
                "必填字段 {} 不能声明 NULL 默认值",
                field.name
            )));
        }
        if matches!(field.field_type, FieldType::Text | FieldType::Json) {
            return Err(BaseError::ConfigError(format!(
                "TEXT/JSON 字段 {} 不自动生成数据库默认值",
                field.name
            )));
        }
        if !default.is_null() {
            field.field_type.validate(&field.name, default)?;
        }
        definition.push_str(" DEFAULT ");
        definition.push_str(&render_default(default)?);
    }
    Ok(definition)
}

fn render_default(value: &serde_json::Value) -> Result<String, BaseError> {
    match value {
        serde_json::Value::Null => Ok("NULL".to_string()),
        serde_json::Value::Bool(value) => Ok(if *value { "1" } else { "0" }.to_string()),
        serde_json::Value::Number(value) => Ok(value.to_string()),
        serde_json::Value::String(value) => Ok(quote_string(value)),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Err(BaseError::ConfigError(
            "数据库字段默认值只支持 null/bool/number/string".to_string(),
        )),
    }
}

pub(super) fn desired_indexes(table: &TableConfig) -> Result<Vec<DesiredIndex>, BaseError> {
    let mut desired = Vec::new();
    for (unique, indexes) in [
        (true, table.unique_indexes.as_slice()),
        (false, table.indexes.as_slice()),
    ] {
        for index in indexes {
            if index.fields.is_empty() {
                return Err(BaseError::ConfigError(format!(
                    "表 {} 包含空索引",
                    table.table_name
                )));
            }
            for field in &index.fields {
                if !table.fields.contains_key(field) {
                    return Err(BaseError::ConfigError(format!(
                        "表 {} 的索引引用未声明字段: {}",
                        table.table_name, field
                    )));
                }
            }
            let prefix = if unique { "uk" } else { "idx" };
            let name = index.name.clone().unwrap_or_else(|| {
                format!("{prefix}_{}_{}", table.table_name, index.fields.join("_"))
            });
            if name.len() > 64 {
                return Err(BaseError::ConfigError(format!(
                    "索引名超过 MySQL 64 字符限制,请显式命名: {name}"
                )));
            }
            quote_identifier(&name)?;
            desired.push(DesiredIndex {
                name,
                unique,
                columns: index.fields.clone(),
            });
        }
    }
    Ok(desired)
}

pub(super) fn quote_identifier(identifier: &str) -> Result<String, BaseError> {
    yang_db::mysql::quote_identifier(identifier).map_err(|error| {
        BaseError::ConfigError(format!("非法数据库标识符 {identifier:?}: {error}"))
    })
}

pub(super) fn quote_string(value: &str) -> String {
    format!("'{}'", value.replace('\\', "\\\\").replace('\'', "''"))
}

pub(super) fn schema_lock_name(database_name: &str) -> String {
    let mut hash: u64 = 0xcbf29ce484222325;
    for byte in database_name.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("yang_base_schema_{hash:016x}")
}