跳转到内容

Schema 差异检测

diffSchemas 对比当前数据库 Schema 与目标 Schema,检测表和列的增删改差异。generateMigrationSQL 根据差异生成 up / down 双向迁移 SQL。

import { diffSchemas, generateMigrationSQL } from "@ventostack/database";
const current = [
{
name: "users",
columns: [
{ name: "id", type: "bigint", primaryKey: true },
{ name: "name", type: "varchar", nullable: false },
],
},
];
const target = [
{
name: "users",
columns: [
{ name: "id", type: "bigint", primaryKey: true },
{ name: "name", type: "varchar", nullable: false },
{ name: "email", type: "varchar", nullable: true },
],
},
{
name: "posts",
columns: [
{ name: "id", type: "bigint", primaryKey: true },
{ name: "title", type: "varchar" },
],
},
];
const diff = diffSchemas(current, target);
// diff.addedTables → ["posts"]
// diff.modifiedTables → [{ table: "users", addedColumns: [...], ... }]
const { up, down } = generateMigrationSQL(diff);
// up: 正向迁移 SQL
// down: 回滚 SQL
字段类型说明
addedTablesstring[]新增表名列表
removedTablesstring[]移除表名列表
modifiedTablesTableDiff[]发生变更的表差异列表
字段类型说明
tablestring表名
addedColumnsColumnSchema[]新增列
removedColumnsstring[]移除的列名
modifiedColumnsColumnDiff[]变更的列差异
字段类型说明
columnstring列名
changesstring[]变更项(typenullabledefault
from / toPartial<ColumnSchema>变更前后的值
函数说明
diffSchemas(current, target)对比两个 Schema,返回 SchemaDiff
generateMigrationSQL(diff)生成 { up, down } 迁移 SQL 数组