yang-base 0.6.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use super::super::schema_sync::{
    plan_table_sync, ExistingIndex, ExistingTableSchema, SchemaPreflightCheck,
};
use super::super::{DatabaseInitializer, SchemaSyncChangeKind, SchemaSyncReport};
use crate::definition::{
    AddonName, AddonSpec, AppBuilder, FieldKind, FieldName, FieldSpec, ModuleName, ModuleSpec,
    TableName, TableSpec,
};
use crate::error::BaseError;
use crate::table::{Field, RelationType, SchemaColumn, Table, TableDefinition};
use crate::tools::ToolsBuilder;

fn account_table() -> TableDefinition {
    Table::new("accounts")
        .fields([
            Field::id("id"),
            Field::string("username", 32).required().unique(),
        ])
        .build()
        .expect("accounts 表定义应有效")
}

#[allow(dead_code)]
async fn public_schema_sync_api_typechecks(
    initializer: &DatabaseInitializer,
    definitions: &[&TableDefinition],
) -> Result<SchemaSyncReport, BaseError> {
    initializer.sync_table_definitions(definitions).await
}

#[allow(dead_code)]
async fn public_schema_plan_api_typechecks(
    initializer: &DatabaseInitializer,
    definitions: &[&TableDefinition],
) -> Result<SchemaSyncReport, BaseError> {
    initializer.plan_table_definitions(definitions).await
}

#[allow(dead_code)]
async fn public_schema_preflight_api_typechecks(
    initializer: &DatabaseInitializer,
    definitions: &[&TableDefinition],
) -> Result<super::super::SchemaPreflightReport, BaseError> {
    initializer.preflight_table_definitions(definitions).await
}

#[test]
fn built_app_exposes_compiled_table_definitions_in_module_order() {
    let table_spec = |name: &str| {
        TableSpec::new(TableName::new(name).expect("测试表名应有效")).field(FieldSpec::new(
            FieldName::new("id").expect("测试字段名应有效"),
            FieldKind::Key,
        ))
    };
    let app = AppBuilder::new()
        .addon(
            AddonSpec::new(AddonName::new("account").expect("测试 Addon 名称应有效"))
                .module(
                    ModuleSpec::new(
                        ModuleName::new("account.z_account").expect("测试 Module 名称应有效"),
                    )
                    .table(table_spec("accounts")),
                )
                .module(
                    ModuleSpec::new(
                        ModuleName::new("account.a_audit").expect("测试 Module 名称应有效"),
                    )
                    .table(table_spec("audit_logs")),
                ),
        )
        .build(ToolsBuilder::new().build().expect("测试 Tools 应有效"))
        .expect("应用定义应构建成功");

    let names: Vec<&str> = app
        .table_definitions()
        .iter()
        .map(TableDefinition::name)
        .collect();

    assert_eq!(names, vec!["audit_logs", "accounts"]);
}

#[test]
fn additive_plan_creates_missing_table_from_definition() {
    let table = account_table();
    let plan = plan_table_sync(&table, &ExistingTableSchema::missing())
        .expect("合法 TableDefinition 应生成建表计划");

    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::CreatedTable);
    assert!(plan.statements[0].contains("CREATE TABLE `accounts`"));
    assert!(plan.statements[0].contains("`id` BIGINT NOT NULL AUTO_INCREMENT"));
    assert!(plan.statements[0].contains("PRIMARY KEY (`id`)"));
    assert!(plan.statements[0].contains("UNIQUE KEY"));
}

#[test]
fn relation_field_uses_its_concrete_type_for_local_column_ddl() {
    let table = Table::new("orders")
        .fields([
            Field::id("id"),
            Field::bigint("account_id").required().relation(
                "accounts",
                "id",
                RelationType::ManyToOne,
            ),
        ])
        .build()
        .expect("关联字段定义应有效");

    let plan = plan_table_sync(&table, &ExistingTableSchema::missing())
        .expect("具体存储类型必须能生成本地列 DDL");

    assert!(plan.statements[0].contains("`account_id` BIGINT NOT NULL"));
}

#[test]
fn additive_plan_only_adds_missing_columns_and_indexes() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
        ],
        vec!["id".to_string()],
        Vec::new(),
    );

    let table = account_table();
    let plan = plan_table_sync(&table, &existing).expect("兼容旧表应生成增量计划");

    assert_eq!(plan.changes.len(), 2);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::AddedColumn);
    assert_eq!(plan.changes[0].object, "username");
    assert_eq!(plan.changes[1].kind, SchemaSyncChangeKind::AddedIndex);
    assert!(plan
        .statements
        .iter()
        .all(|statement| !statement.contains("DROP")));
}

#[test]
fn evolution_plan_modifies_supported_string_and_nullability_drift_after_preflight() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("username", "varchar", "varchar(8)", true, Some(8), None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    );

    let table = account_table();
    let plan = plan_table_sync(&table, &existing).expect("受支持的字段变化应进入预检计划");

    assert!(plan.changes.iter().any(|change| {
        change.kind == SchemaSyncChangeKind::ModifiedColumn && change.object == "username"
    }));
    assert!(plan
        .statements
        .iter()
        .any(|statement| statement.contains("MODIFY COLUMN `username` VARCHAR(32) NOT NULL")));
}

#[test]
fn additive_plan_rejects_conflicting_named_index() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_accounts_username",
            false,
            vec!["username".to_string()],
        )],
    );

    let table = account_table();
    let error = plan_table_sync(&table, &existing).expect_err("同名索引定义冲突时不能自动覆盖");

    assert!(matches!(error, BaseError::DatabaseInitFailed(message)
        if message.contains("uk_accounts_username") && message.contains("定义不同")));
}

#[test]
fn additive_plan_rejects_missing_auto_increment_column_on_existing_table() {
    let existing = ExistingTableSchema::existing(Vec::new(), Vec::new(), Vec::new());

    let table = account_table();
    let error = plan_table_sync(&table, &existing).expect_err("已有表不能分步增加自增主键列");

    assert!(matches!(error, BaseError::DatabaseInitFailed(message)
        if message.contains("自增主键字段") && message.contains("人工处理")));
}

#[test]
fn evolution_plan_updates_existing_database_default_drift() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new(
                "username",
                "varchar",
                "varchar(32)",
                false,
                Some(32),
                Some("guest".to_string()),
            ),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    );

    let table = account_table();
    let plan = plan_table_sync(&table, &existing).expect("默认值漂移应生成字段修改计划");

    assert!(plan.changes.iter().any(|change| {
        change.kind == SchemaSyncChangeKind::ModifiedColumn && change.object == "username"
    }));
}

#[test]
fn evolution_plan_rejects_unsupported_numeric_type_conversion() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("score", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    );
    let table = Table::new("scores")
        .fields([Field::id("id"), Field::bigint("score").required()])
        .build()
        .expect("测试表定义应有效");

    let error = plan_table_sync(&table, &existing).expect_err("文本转数值不能自动猜测语义");

    assert!(matches!(error, BaseError::DatabaseInitFailed(message)
        if message.contains("scores") && message.contains("score")));
}

#[test]
fn compatible_smallint_storage_does_not_require_integer_rewrite() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new(
                "schema_version",
                "smallint",
                "smallint unsigned",
                false,
                None,
                Some("1".to_string()),
            ),
        ],
        vec!["id".to_string()],
        Vec::new(),
    );
    let table = Table::new("audit_event")
        .fields([
            Field::id("id"),
            Field::integer("schema_version").required().default(1),
        ])
        .build()
        .expect("测试表定义应有效");

    let plan = plan_table_sync(&table, &existing).expect("smallint 应满足整数语义");

    assert!(
        plan.changes.is_empty(),
        "兼容的旧数值存储不应为统一外观重写整列"
    );
}

#[test]
fn evolution_plan_renames_one_declared_legacy_column_without_drop() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    );
    let table = Table::new("accounts")
        .fields([
            Field::id("id"),
            Field::string("handle", 32)
                .required()
                .renamed_from("username"),
        ])
        .build()
        .expect("改名声明应构建成功");

    let plan = plan_table_sync(&table, &existing).expect("单列显式改名应生成保数据计划");

    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::RenamedColumn);
    assert_eq!(plan.changes[0].object, "username->handle");
    assert_eq!(
        plan.statements,
        ["ALTER TABLE `accounts` RENAME COLUMN `username` TO `handle`"]
    );
    assert!(plan
        .statements
        .iter()
        .all(|statement| !statement.contains("DROP")));
}

#[test]
fn create_plan_renders_declared_check_and_foreign_key_constraints() {
    let table = Table::new("children")
        .fields([Field::id("id"), Field::bigint("parent_id").required()])
        .check_named("chk_children_parent_positive", "`parent_id` > 0")
        .foreign_key_named("fk_children_parent", ["parent_id"], "parents", ["id"])
        .build()
        .expect("约束声明应构建成功");

    let plan = plan_table_sync(&table, &ExistingTableSchema::missing())
        .expect("新表应直接渲染全部声明约束");
    let ddl = plan.statements.join("; ");

    assert!(ddl.contains("CONSTRAINT `chk_children_parent_positive` CHECK (`parent_id` > 0)"));
    assert!(ddl.contains(
        "CONSTRAINT `fk_children_parent` FOREIGN KEY (`parent_id`) REFERENCES `parents` (`id`)"
    ));
}

#[test]
fn evolution_plan_adds_missing_constraints_without_dropping_unknown_structure() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("parent_id", "bigint", "bigint", false, None, None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "legacy_extra_index",
            false,
            vec!["parent_id".to_string()],
        )],
    );
    let table = Table::new("children")
        .fields([Field::id("id"), Field::bigint("parent_id").required()])
        .check_named("chk_children_parent_positive", "`parent_id` > 0")
        .foreign_key_named("fk_children_parent", ["parent_id"], "parents", ["id"])
        .build()
        .expect("约束声明应构建成功");

    let plan = plan_table_sync(&table, &existing).expect("缺失约束应生成增量计划");

    assert_eq!(
        plan.changes
            .iter()
            .map(|change| change.kind)
            .collect::<Vec<_>>(),
        [
            SchemaSyncChangeKind::AddedCheck,
            SchemaSyncChangeKind::AddedForeignKey
        ]
    );
    assert!(plan
        .statements
        .iter()
        .all(|statement| !statement.contains("DROP")));
}

#[test]
fn evolution_declarations_reject_ambiguous_legacy_column_sources() {
    let table = Table::new("accounts")
        .fields([
            Field::id("id"),
            Field::string("handle", 32)
                .required()
                .renamed_from("username"),
            Field::string("display_name", 32)
                .required()
                .renamed_from("username"),
        ])
        .build();

    assert!(matches!(
        table,
        Err(BaseError::ConfigError(message))
            if message.contains("username") && message.contains("重复")
    ));
}

#[test]
fn new_unique_column_skips_unique_index_preflight() {
    // 回归测试:在已有数据的表上新增 unique nullable 列时,unique 索引的 preflight
    // 检查会引用尚未添加的列,导致 "Unknown column" 报错。新列没有任何数据,不可能
    // 有重复值,应跳过 preflight。
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_rows(true);

    let table = Table::new("posts")
        .fields([
            Field::id("id"),
            Field::string("slug", 64).unique(), // 新增 unique nullable 列
        ])
        .build()
        .expect("表定义应有效");

    let plan = plan_table_sync(&table, &existing).expect("增量计划应成功");

    // 计划应包含 ADD COLUMN 和 ADD UNIQUE INDEX
    assert!(
        plan.changes
            .iter()
            .any(|c| c.kind == SchemaSyncChangeKind::AddedColumn && c.object == "slug"),
        "应包含新增 slug 列"
    );
    assert!(
        plan.changes
            .iter()
            .any(|c| c.kind == SchemaSyncChangeKind::AddedIndex),
        "应包含新增唯一索引"
    );

    // 关键断言:preflight 不应包含 UniqueIndex 检查(新列无数据,无需查重)
    let has_unique_preflight = plan
        .preflight
        .iter()
        .any(|check| matches!(check, SchemaPreflightCheck::UniqueIndex { .. }));
    assert!(
        !has_unique_preflight,
        "新列的唯一索引不应生成 preflight 检查(列尚未存在,SQL 会报 Unknown column)"
    );
}

#[test]
fn existing_column_unique_index_keeps_preflight() {
    // 对照测试:在已有列上加 unique 索引时,preflight 检查必须保留(旧数据可能有重复)。
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None)
                .with_auto_increment(true),
            SchemaColumn::new("slug", "varchar", "varchar(64)", false, Some(64), None),
        ],
        vec!["id".to_string()],
        Vec::new(), // 没有索引
    )
    .with_rows(true);

    let table = Table::new("posts")
        .fields([
            Field::id("id"),
            Field::string("slug", 64).unique(), // 对已有列加 unique
        ])
        .build()
        .expect("表定义应有效");

    let plan = plan_table_sync(&table, &existing).expect("增量计划应成功");

    // 计划应包含 ADD UNIQUE INDEX(列已存在,只加索引)
    assert!(
        plan.changes
            .iter()
            .any(|c| c.kind == SchemaSyncChangeKind::AddedIndex),
        "应包含新增唯一索引"
    );
    assert!(
        !plan
            .changes
            .iter()
            .any(|c| c.kind == SchemaSyncChangeKind::AddedColumn),
        "不应新增列(slug 已存在)"
    );

    // 关键断言:preflight 应包含 UniqueIndex 检查(旧数据可能有重复)
    let has_unique_preflight = plan
        .preflight
        .iter()
        .any(|check| matches!(check, SchemaPreflightCheck::UniqueIndex { .. }));
    assert!(
        has_unique_preflight,
        "已有列的唯一索引必须保留 preflight 检查(旧数据可能有重复)"
    );
}