sqltrail-cli 0.1.0

Reusable PostgreSQL schema migration CLI and library: diff declared schema against a live database, generate versioned SQL, apply with a checksum-protected history
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! SQL 生成:把 [`MigrationPlan`] 渲染为可审查的 PostgreSQL DDL。
//!
//! 规则:
//! - 表名、字段名按 PostgreSQL 标识符规则安全引用;
//! - 危险操作前插入 `-- @danger` 标记,`apply` 缺省会拒绝执行;
//! - 需要注意的操作前插入 `-- @caution` 标记;
//! - 相同输入始终生成相同 SQL(确定性输出,方便审查 diff)。

use sqltrail_core::{ColumnModel, DangerLevel, MigrationOperation, MigrationPlan, TableModel};

/// 把整个迁移计划渲染成 SQL 文本。
pub fn render_plan(plan: &MigrationPlan) -> String {
    let mut out = String::new();
    out.push_str("-- 本文件由 sqltrail-cli 生成,请人工审核后再执行\n");
    for op in &plan.operations {
        let statements = render_op(op);
        for (i, stmt) in statements.iter().enumerate() {
            match op.danger() {
                DangerLevel::Dangerous if i == 0 => {
                    out.push_str("-- @danger 危险操作:apply 需要显式传入 --allow-destructive\n");
                }
                DangerLevel::Caution if i == 0 => {
                    out.push_str("-- @caution 需注意的操作:请确认不影响既有数据\n");
                }
                _ => {}
            }
            out.push_str(stmt);
            out.push('\n');
        }
        out.push('\n');
    }
    out
}

/// 把单个操作渲染为 SQL 语句列表。
pub fn render_op(op: &MigrationOperation) -> Vec<String> {
    use MigrationOperation::*;
    match op {
        CreateSchema { name } => vec![format!(
            "CREATE SCHEMA IF NOT EXISTS {};",
            quote_ident(name)
        )],
        CreateTable { table } => vec![render_create_table(table)],
        RenameTable {
            schema,
            old_name,
            new_name,
        } => vec![format!(
            "ALTER TABLE {} RENAME TO {};",
            quote_table(schema, old_name),
            quote_ident(new_name)
        )],
        DropTable { schema, name } => vec![format!("DROP TABLE {};", quote_table(schema, name))],
        AddColumn {
            schema,
            table,
            column,
        } => vec![format!(
            "ALTER TABLE {} ADD COLUMN {};",
            quote_table(schema, table),
            render_column_def(column, false, false)
        )],
        DropColumn {
            schema,
            table,
            name,
        } => vec![format!(
            "ALTER TABLE {} DROP COLUMN {};",
            quote_table(schema, table),
            quote_ident(name)
        )],
        RenameColumn {
            schema,
            table,
            old_name,
            new_name,
        } => vec![format!(
            "ALTER TABLE {} RENAME COLUMN {} TO {};",
            quote_table(schema, table),
            quote_ident(old_name),
            quote_ident(new_name)
        )],
        AlterColumnType {
            schema,
            table,
            column,
            new_type,
            ..
        } => vec![format!(
            "ALTER TABLE {} ALTER COLUMN {} TYPE {};",
            quote_table(schema, table),
            quote_ident(column),
            new_type
        )],
        SetNotNull {
            schema,
            table,
            column,
        } => vec![format!(
            "ALTER TABLE {} ALTER COLUMN {} SET NOT NULL;",
            quote_table(schema, table),
            quote_ident(column)
        )],
        DropNotNull {
            schema,
            table,
            column,
        } => vec![format!(
            "ALTER TABLE {} ALTER COLUMN {} DROP NOT NULL;",
            quote_table(schema, table),
            quote_ident(column)
        )],
        SetDefault {
            schema,
            table,
            column,
            default_sql,
        } => vec![format!(
            "ALTER TABLE {} ALTER COLUMN {} SET DEFAULT {};",
            quote_table(schema, table),
            quote_ident(column),
            default_sql
        )],
        DropDefault {
            schema,
            table,
            column,
        } => vec![format!(
            "ALTER TABLE {} ALTER COLUMN {} DROP DEFAULT;",
            quote_table(schema, table),
            quote_ident(column)
        )],
        AddPrimaryKey {
            schema,
            table,
            columns,
        } => vec![format!(
            "ALTER TABLE {} ADD PRIMARY KEY ({});",
            quote_table(schema, table),
            quote_cols(columns)
        )],
        DropPrimaryKey {
            schema,
            table,
            name,
        } => vec![format!(
            "ALTER TABLE {} DROP CONSTRAINT {};",
            quote_table(schema, table),
            quote_ident(name)
        )],
        AddUnique {
            schema,
            table,
            name,
            columns,
        } => {
            let cols = quote_cols(columns);
            match name {
                Some(n) => vec![format!(
                    "ALTER TABLE {} ADD CONSTRAINT {} UNIQUE ({});",
                    quote_table(schema, table),
                    quote_ident(n),
                    cols
                )],
                None => vec![format!(
                    "ALTER TABLE {} ADD UNIQUE ({});",
                    quote_table(schema, table),
                    cols
                )],
            }
        }
        DropUnique {
            schema,
            table,
            name,
        } => {
            // name 缺失时按 PostgreSQL 自动命名规则猜测(表名_字段_key)
            let constraint = name.clone().unwrap_or_else(|| format!("{table}_key"));
            vec![format!(
                "ALTER TABLE {} DROP CONSTRAINT {};",
                quote_table(schema, table),
                quote_ident(&constraint)
            )]
        }
        AddForeignKey { schema, table, fk } => vec![format!(
            "ALTER TABLE {} ADD FOREIGN KEY ({}) REFERENCES {}({}){};",
            quote_table(schema, table),
            quote_cols(&fk.columns),
            quote_ref_table(&fk.ref_table),
            quote_cols(&fk.ref_columns),
            render_fk_rules(fk.on_delete.as_deref(), fk.on_update.as_deref()),
        )],
        DropForeignKey {
            schema,
            table,
            name,
        } => {
            // name 缺失时按 PostgreSQL 自动命名规则猜测(表名_字段_fkey)
            let constraint = name.clone().unwrap_or_else(|| format!("{table}_fkey"));
            vec![format!(
                "ALTER TABLE {} DROP CONSTRAINT {};",
                quote_table(schema, table),
                quote_ident(&constraint)
            )]
        }
        AddIndex {
            schema,
            table,
            index,
        } => {
            let unique = if index.unique { "UNIQUE " } else { "" };
            // 谓词可能已带 WHERE(如 "WHERE deleted_at IS NOT NULL"),去掉前缀避免重复
            let predicate = match &index.predicate {
                Some(p) => format!(" WHERE {}", strip_where(p)),
                None => String::new(),
            };
            let generated_name;
            let name = match index.name.as_deref() {
                Some(name) => name,
                None => {
                    generated_name = format!("{table}_{}_idx", index.columns.join("_"));
                    &generated_name
                }
            };
            vec![format!(
                "CREATE {unique}INDEX {} ON {} ({}){predicate};",
                quote_ident(name),
                quote_table(schema, table),
                quote_cols(&index.columns),
            )]
        }
        DropIndex {
            schema,
            table: _table,
            name,
        } => vec![format!(
            "DROP INDEX IF EXISTS {}.{};",
            quote_ident(schema),
            quote_ident(name)
        )],
        SetTableComment {
            schema,
            table,
            comment,
        } => vec![format!(
            "COMMENT ON TABLE {} IS {};",
            quote_table(schema, table),
            render_comment(comment.as_deref())
        )],
        SetColumnComment {
            schema,
            table,
            column,
            comment,
        } => vec![format!(
            "COMMENT ON COLUMN {}.{} IS {};",
            quote_table(schema, table),
            quote_ident(column),
            render_comment(comment.as_deref())
        )],
        CreateFunction { function } | ReplaceFunction { function } => {
            vec![ensure_statement(&function.definition_sql)]
        }
        DropFunction { function } => vec![format!(
            "DROP FUNCTION {}({});",
            quote_table(&function.schema, &function.name),
            function.identity_arguments.trim()
        )],
        SetFunctionComment {
            schema,
            name,
            identity_arguments,
            comment,
        } => vec![format!(
            "COMMENT ON FUNCTION {}({}) IS {};",
            quote_table(schema, name),
            identity_arguments.trim(),
            render_comment(comment.as_deref())
        )],
    }
}

/// 渲染 CREATE TABLE(含内联主键/唯一约束/外键)。
pub fn render_create_table(table: &TableModel) -> String {
    let mut body: Vec<String> = Vec::new();

    // 单列主键内联到字段定义;联合主键走表级 PRIMARY KEY
    let single_pk: Option<&str> = table
        .primary_key
        .as_ref()
        .filter(|p| p.columns.len() == 1)
        .map(|p| p.columns[0].as_str());

    // 单列唯一约束(未命名)内联到字段定义
    let inline_unique = |col: &str| {
        table
            .unique_constraints
            .iter()
            .any(|u| u.name.is_none() && u.columns.len() == 1 && u.columns[0] == col)
    };

    for col in &table.columns {
        body.push(render_column_def(
            col,
            single_pk == Some(col.name.as_str()),
            inline_unique(&col.name),
        ));
    }

    // 联合主键
    if let Some(pk) = &table.primary_key {
        if pk.columns.len() > 1 {
            body.push(format!("PRIMARY KEY ({})", quote_cols(&pk.columns)));
        }
    }
    // 表级唯一约束(命名或多列)
    for u in &table.unique_constraints {
        if u.name.is_none() && u.columns.len() == 1 {
            continue; // 已在字段定义中内联
        }
        let cols = quote_cols(&u.columns);
        match &u.name {
            Some(n) => body.push(format!("CONSTRAINT {} UNIQUE ({cols})", quote_ident(n))),
            None => body.push(format!("UNIQUE ({cols})")),
        }
    }
    // 外键(内联 REFERENCES)
    for fk in &table.foreign_keys {
        body.push(format!(
            "FOREIGN KEY ({}) REFERENCES {}({}){}",
            quote_cols(&fk.columns),
            quote_ref_table(&fk.ref_table),
            quote_cols(&fk.ref_columns),
            render_fk_rules(fk.on_delete.as_deref(), fk.on_update.as_deref()),
        ));
    }

    format!(
        "CREATE TABLE {} (\n    {}\n);",
        quote_table(&table.schema, &table.name),
        body.join(",\n    ")
    )
}

/// 渲染单字段定义。
pub fn render_column_def(col: &ColumnModel, inline_pk: bool, inline_unique: bool) -> String {
    let mut s = format!("{} {}", quote_ident(&col.name), col.sql_type);
    // serial 系列本身隐含 NOT NULL,无需重复声明
    if !is_serial(&col.sql_type) && !col.nullable {
        s.push_str(" NOT NULL");
    }
    if let Some(d) = &col.default_sql {
        s.push_str(&format!(" DEFAULT {d}"));
    }
    if inline_unique {
        s.push_str(" UNIQUE");
    }
    if inline_pk {
        s.push_str(" PRIMARY KEY");
    }
    s
}

/// 渲染外键的 ON DELETE / ON UPDATE 子句。
fn render_fk_rules(on_delete: Option<&str>, on_update: Option<&str>) -> String {
    let mut s = String::new();
    if let Some(d) = on_delete {
        s.push_str(&format!(" ON DELETE {}", d.to_uppercase()));
    }
    if let Some(u) = on_update {
        s.push_str(&format!(" ON UPDATE {}", u.to_uppercase()));
    }
    s
}

/// 去掉谓词开头的 `WHERE `(大小写不敏感)。
fn strip_where(p: &str) -> String {
    let trimmed = p.trim();
    // `where ` 为 6 个字符,小写化不影响字节长度
    if trimmed.to_lowercase().starts_with("where ") {
        trimmed[6..].trim().to_string()
    } else {
        trimmed.to_string()
    }
}

/// 是否 serial 系列类型(隐含 NOT NULL)。
fn is_serial(t: &str) -> bool {
    matches!(t.trim(), "serial" | "bigserial" | "smallserial")
}

/// 始终引用标识符,避免合法名称与 PostgreSQL 关键字冲突。
fn quote_ident(name: &str) -> String {
    format!("\"{}\"", name.replace('"', "\"\""))
}

/// 引用 schema.table。
fn quote_table(schema: &str, table: &str) -> String {
    format!("{}.{}", quote_ident(schema), quote_ident(table))
}

/// 引用 "schema.table" 或 "table" 形式的引用表。
fn quote_ref_table(reference: &str) -> String {
    match reference.rsplit_once('.') {
        Some((schema, table)) => format!("{}.{}", quote_ident(schema), quote_ident(table)),
        None => quote_ident(reference),
    }
}

/// 引用字段列表。
fn quote_cols(cols: &[String]) -> String {
    cols.iter()
        .map(|c| quote_ident(c))
        .collect::<Vec<_>>()
        .join(", ")
}

/// PostgreSQL 注释字面量;None 使用 `IS NULL` 删除注释。
fn render_comment(comment: Option<&str>) -> String {
    match comment {
        Some(comment) => format!("'{}'", comment.replace('\'', "''")),
        None => "NULL".to_string(),
    }
}

/// 确保完整函数定义以分号结束。
fn ensure_statement(sql: &str) -> String {
    let sql = sql.trim();
    if sql.ends_with(';') {
        sql.to_string()
    } else {
        format!("{sql};")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sqltrail_core::{
        ColumnModel, ForeignKeyModel, FunctionModel, IndexModel, PrimaryKeyModel,
        UniqueConstraintModel,
    };

    fn employee_table() -> TableModel {
        TableModel {
            schema: "auth".into(),
            name: "employees".into(),
            rename_from: None,
            comment: None,
            columns: vec![
                ColumnModel {
                    name: "id".into(),
                    sql_type: "bigserial".into(),
                    nullable: false,
                    primary_key: true,
                    rename_from: None,
                    default_sql: None,
                    comment: None,
                },
                ColumnModel {
                    name: "employee_no".into(),
                    sql_type: "varchar(64)".into(),
                    nullable: false,
                    primary_key: false,
                    rename_from: None,
                    default_sql: None,
                    comment: None,
                },
                ColumnModel {
                    name: "avatar".into(),
                    sql_type: "text".into(),
                    nullable: true,
                    primary_key: false,
                    rename_from: None,
                    default_sql: None,
                    comment: None,
                },
            ],
            primary_key: Some(PrimaryKeyModel {
                name: None,
                columns: vec!["id".into()],
            }),
            unique_constraints: vec![UniqueConstraintModel {
                name: None,
                columns: vec!["employee_no".into()],
            }],
            foreign_keys: vec![],
            indexes: vec![],
        }
    }

    #[test]
    fn 渲染建表语句() {
        let sql = render_create_table(&employee_table());
        assert!(sql.starts_with("CREATE TABLE \"auth\".\"employees\" ("));
        assert!(sql.contains("\"id\" bigserial PRIMARY KEY"));
        assert!(sql.contains("\"employee_no\" varchar(64) NOT NULL UNIQUE"));
        assert!(sql.contains("\"avatar\" text"));
        assert!(sql.ends_with(");"));
    }

    #[test]
    fn 渲染联合主键与外键() {
        let t = TableModel {
            schema: "auth".into(),
            name: "employee_departments".into(),
            rename_from: None,
            comment: None,
            columns: vec![
                ColumnModel {
                    name: "employee_id".into(),
                    sql_type: "bigint".into(),
                    nullable: false,
                    primary_key: true,
                    rename_from: None,
                    default_sql: None,
                    comment: None,
                },
                ColumnModel {
                    name: "department_id".into(),
                    sql_type: "bigint".into(),
                    nullable: false,
                    primary_key: true,
                    rename_from: None,
                    default_sql: None,
                    comment: None,
                },
            ],
            primary_key: Some(PrimaryKeyModel {
                name: None,
                columns: vec!["employee_id".into(), "department_id".into()],
            }),
            unique_constraints: vec![],
            foreign_keys: vec![ForeignKeyModel {
                name: None,
                columns: vec!["employee_id".into()],
                ref_table: "auth.employees".into(),
                ref_columns: vec!["id".into()],
                on_delete: Some("CASCADE".into()),
                on_update: None,
            }],
            indexes: vec![],
        };
        let sql = render_create_table(&t);
        assert!(sql.contains("PRIMARY KEY (\"employee_id\", \"department_id\")"));
        assert!(
            sql.contains(
                "FOREIGN KEY (\"employee_id\") REFERENCES \"auth\".\"employees\"(\"id\") ON DELETE CASCADE"
            )
        );
    }

    #[test]
    fn 渲染部分索引() {
        let t = TableModel {
            schema: "auth".into(),
            name: "employees".into(),
            rename_from: None,
            comment: None,
            columns: vec![ColumnModel {
                name: "deleted_at".into(),
                sql_type: "timestamptz".into(),
                nullable: true,
                primary_key: false,
                rename_from: None,
                default_sql: None,
                comment: None,
            }],
            primary_key: None,
            unique_constraints: vec![],
            foreign_keys: vec![],
            indexes: vec![IndexModel {
                name: Some("idx_employees_deleted".into()),
                columns: vec!["deleted_at".into()],
                unique: false,
                predicate: Some("deleted_at IS NOT NULL".into()),
            }],
        };
        let sql = render_op(&MigrationOperation::AddIndex {
            schema: "auth".into(),
            table: "employees".into(),
            index: t.indexes[0].clone(),
        });
        assert_eq!(
            sql[0],
            "CREATE INDEX \"idx_employees_deleted\" ON \"auth\".\"employees\" (\"deleted_at\") WHERE deleted_at IS NOT NULL;"
        );
    }

    #[test]
    fn 危险操作带标记() {
        let plan = MigrationPlan {
            operations: vec![MigrationOperation::DropTable {
                schema: "public".into(),
                name: "legacy".into(),
            }],
        };
        let sql = render_plan(&plan);
        assert!(sql.contains("-- @danger"));
        assert!(sql.contains("DROP TABLE \"public\".\"legacy\";"));
    }

    #[test]
    fn 渲染注释会转义单引号() {
        let sql = render_op(&MigrationOperation::SetColumnComment {
            schema: "public".into(),
            table: "users".into(),
            column: "name".into(),
            comment: Some("用户的显示名".into()),
        });
        assert_eq!(
            sql[0],
            "COMMENT ON COLUMN \"public\".\"users\".\"name\" IS '用户的显示名';"
        );

        let escaped = render_op(&MigrationOperation::SetTableComment {
            schema: "public".into(),
            table: "users".into(),
            comment: Some("owner's table".into()),
        });
        assert!(escaped[0].contains("'owner''s table'"));
    }

    #[test]
    fn 渲染函数与稳定索引名() {
        let function = FunctionModel {
            schema: "public".into(),
            name: "answer".into(),
            identity_arguments: String::new(),
            definition_sql: "CREATE OR REPLACE FUNCTION public.answer() RETURNS integer LANGUAGE sql AS $$ SELECT 42 $$".into(),
            comment: Some("答案".into()),
        };
        let sql = render_op(&MigrationOperation::CreateFunction { function });
        assert!(sql[0].ends_with(';'));

        let index = render_op(&MigrationOperation::AddIndex {
            schema: "public".into(),
            table: "users".into(),
            index: IndexModel {
                name: None,
                columns: vec!["email".into()],
                unique: false,
                predicate: None,
            },
        });
        assert!(index[0].contains("\"users_email_idx\""));
    }
}