ts-grm-migrate 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3573 @@
1
+ import { createHash } from "node:crypto";
2
+ import { access, mkdir, open, readFile, readdir, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { MySqlDriver, OracleDriver, OraclePool, PostgresDriver, SqlServerDriver, SqlServerPool, SqliteDriver, newSqlClient } from "@ts-grm/sql";
6
+ import { EntityManager } from "@ts-grm/core";
7
+ import { createInterface } from "node:readline/promises";
8
+ //#region src/server/sql.ts
9
+ /** Names and namespaces are shared by introspection, history and DDL rendering. */
10
+ var ServerSql = class {
11
+ dialect;
12
+ schema;
13
+ constructor(dialect, schema) {
14
+ this.dialect = dialect;
15
+ this.schema = schema;
16
+ }
17
+ identifier(name) {
18
+ return this.dialect === "mssql" ? `[${name.replaceAll("]", "]]")}]` : `"${name.replaceAll("\"", "\"\"")}"`;
19
+ }
20
+ table(name) {
21
+ return `${this.identifier(this.schema)}.${this.identifier(name)}`;
22
+ }
23
+ param(index) {
24
+ return this.dialect === "mssql" ? `@p${index}` : `:${index}`;
25
+ }
26
+ literal(value) {
27
+ return `${this.dialect === "mssql" ? "N" : ""}'${value.replaceAll("'", "''")}'`;
28
+ }
29
+ name(value) {
30
+ if (Buffer.byteLength(value) <= 128) return value;
31
+ let prefix = value;
32
+ while (Buffer.byteLength(prefix) > 100) prefix = prefix.slice(0, -1);
33
+ return `${prefix}_${createHash("sha256").update(value).digest("hex").slice(0, 16)}`;
34
+ }
35
+ };
36
+ function normalizeServerType(type, dialect) {
37
+ let result = type.toLowerCase().replace(/\s*,\s*/g, ",").replace(/\s+/g, " ");
38
+ if (dialect === "mssql") result = result.replace(/^numeric\(/, "decimal(").replace(/^float\(53\)$/, "float").replace(/^datetime2\(7\)$/, "datetime2");
39
+ else result = result.replace(/^timestamp\(6\)$/, "timestamp").replace(/^(number\(\d+),0\)$/, "$1)");
40
+ return result;
41
+ }
42
+ //#endregion
43
+ //#region src/server/catalog.ts
44
+ const stringValue = (value) => String(value ?? "");
45
+ function groupRows(rows, key) {
46
+ const groups = /* @__PURE__ */ new Map();
47
+ for (const row of rows) {
48
+ const name = stringValue(row[key]);
49
+ const group = groups.get(name) ?? [];
50
+ group.push(row);
51
+ groups.set(name, group);
52
+ }
53
+ return groups;
54
+ }
55
+ /** Conservative formatting normalization; never rewrite the content of string literals. */
56
+ function normalizeServerExpression(expression) {
57
+ const normalized = (expression.match(/N?'(?:''|[^'])*'|"(?:""|[^"])*"|\[(?:\]\]|[^\]])*\]|[A-Za-z_$][\w$#]*|\d+(?:\.\d+)?|<>|!=|<=|>=|[^\s]/g) ?? []).map((token) => token.startsWith("'") || token.startsWith("N'") ? token.replace(/^N'/, "'") : token.startsWith("\"") ? token.slice(1, -1).replaceAll("\"\"", "\"") : token.startsWith("[") ? token.slice(1, -1).replaceAll("]]", "]").toUpperCase() : token.toUpperCase());
58
+ let changed = true;
59
+ while (changed) {
60
+ changed = false;
61
+ for (let i = 0; i < normalized.length - 2; i++) if (normalized[i] === "(" && normalized[i + 2] === ")" && normalized[i + 1] !== "(" && normalized[i + 1] !== ")" && normalized[i - 1] !== "IN") {
62
+ normalized.splice(i, 3, normalized[i + 1]);
63
+ changed = true;
64
+ }
65
+ if (normalized[0] === "(" && normalized.at(-1) === ")") {
66
+ let depth = 0;
67
+ if (normalized.every((t, i) => {
68
+ if (t === "(") depth++;
69
+ if (t === ")") depth--;
70
+ return depth > 0 || i === normalized.length - 1;
71
+ })) {
72
+ normalized.shift();
73
+ normalized.pop();
74
+ changed = true;
75
+ }
76
+ }
77
+ }
78
+ return normalized.join(" ");
79
+ }
80
+ //#endregion
81
+ //#region src/mysql/sql.ts
82
+ /** MySQL SQL primitives shared by schema adaptation, introspection and rendering. */
83
+ function quoteMysqlIdentifier(name) {
84
+ return `\`${name.replaceAll("`", "``")}\``;
85
+ }
86
+ /** Runtime uses NO_BACKSLASH_ESCAPES so literals have one unambiguous encoding. */
87
+ function quoteMysqlLiteral(value) {
88
+ return `'${value.replaceAll("'", "''")}'`;
89
+ }
90
+ /** Integer display widths are not storage types; preserve unsigned / zerofill. */
91
+ function normalizeMysqlType(type) {
92
+ if (/^(enum|set)\(/i.test(type)) return type;
93
+ return type.toLowerCase().replace(/\s*,\s*/g, ",").replace(/\b(tinyint|smallint|mediumint|int|bigint)\(\d+\)/g, "$1").replace(/^integer\b/, "int").replace(/\s+/g, " ").trim();
94
+ }
95
+ /** MySQL identifiers are limited to 64 characters; suffix keeps long names distinct. */
96
+ function mysqlName(name) {
97
+ return name.length <= 64 ? name : `${name.slice(0, 47)}_${createHash("sha256").update(name).digest("hex").slice(0, 16)}`;
98
+ }
99
+ /** Tokenize expressions without rewriting quoted data or identifier contents. */
100
+ function normalizeMysqlCheck(expression) {
101
+ const tokens = expression.match(/'(?:''|[^'])*'|`(?:``|[^`])*`|[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|<>|!=|<=|>=|[^\s]/g) ?? [];
102
+ while (tokens[0] === "(" && tokens.at(-1) === ")") {
103
+ let depth = 0;
104
+ if (!tokens.every((t, i) => {
105
+ if (t === "(") depth++;
106
+ if (t === ")") depth--;
107
+ return depth > 0 || i === tokens.length - 1;
108
+ })) break;
109
+ tokens.shift();
110
+ tokens.pop();
111
+ }
112
+ return tokens.filter((t, i) => !/^_(utf8mb4|utf8mb3|utf8|latin1|ascii|binary)$/i.test(t) || !tokens[i + 1]?.startsWith("'")).map((t) => t.startsWith("'") ? t : t.startsWith("`") ? t.slice(1, -1).replaceAll("``", "`").toLowerCase() : t.toLowerCase()).join(" ");
113
+ }
114
+ //#endregion
115
+ //#region src/schema/adapter.ts
116
+ /** 表名去引号(ts-grm 对保留字表名会带引号,如 "\"ORDER\"";数据库实际名字不带) */
117
+ /**
118
+ * 上游标识符 → 数据库里的**物理名**。
119
+ *
120
+ * ts-grm 的 `toTableName()` 是 `quoteIdentifier(toSnakeCase(...))`(`core/src/impl/entity.ts:206`),
121
+ * 而它的 `quoteIdentifier` **只对 SQL 关键字加引号**,其余原样返回
122
+ * (`sql/src/driver/abstract_drivier.ts:60`)。于是:
123
+ *
124
+ * - 带引号(如 `"ORDER"`):按字面解析,物理名就是引号里的内容
125
+ * - **不带引号(如 `AUTHOR`):PG 会把未加引号的标识符折叠为小写,物理名是 `author`**
126
+ *
127
+ * 必须复刻这条折叠规则:否则模型侧会拿 `AUTHOR` 与 introspect 读到的 `author` 比较,
128
+ * diff 永远不相等;更严重的是 DDL 再加引号就会真的建出大写表,
129
+ * 而 ts-grm 运行时用无引号查询(折叠为小写)根本找不到它。
130
+ *
131
+ * 折叠规则属于方言知识(PG 折叠小写;MySQL/SQLite 不折叠),
132
+ * 将来支持多方言时应下移到方言层。
133
+ */
134
+ function toPhysicalName(value, dialect) {
135
+ if (value.startsWith("\"") && value.endsWith("\"")) return value.slice(1, -1).replaceAll(value[0] === "[" ? "]]" : value[0].repeat(2), value[0] === "[" ? "]" : value[0]);
136
+ if (value.startsWith("`") && value.endsWith("`")) return value.slice(1, -1).replaceAll(value[0] === "[" ? "]]" : value[0].repeat(2), value[0] === "[" ? "]" : value[0]);
137
+ if (value.startsWith("[") && value.endsWith("]")) return value.slice(1, -1).replaceAll(value[0] === "[" ? "]]" : value[0].repeat(2), value[0] === "[" ? "]" : value[0]);
138
+ return dialect === "postgres" ? value.toLowerCase() : dialect === "oracle" ? value.toUpperCase() : value;
139
+ }
140
+ /** ts-grm 的 CascadeType(ORM 语义)→ 数据库 ON DELETE 动作 */
141
+ function toOnDelete$2(cascade) {
142
+ switch (cascade) {
143
+ case "DELETE": return "CASCADE";
144
+ case "SET_NULL": return "SET_NULL";
145
+ default: return "NO_ACTION";
146
+ }
147
+ }
148
+ /** 原生 CHECK(column + values)→ 表达式原文(与 ts-grm constraintCreationSql 同构) */
149
+ function checkExpression$1(constraint) {
150
+ const values = constraint.values.map((v) => typeof v === "number" ? v.toString() : `'${v.replaceAll("'", "''")}'`).join(", ");
151
+ return `${constraint.column.name} in (${values})`;
152
+ }
153
+ function toColumn$1(columnDef, ordinal, driver, dialect) {
154
+ return {
155
+ name: toPhysicalName(columnDef.name, dialect),
156
+ type: dialect === "mysql" ? normalizeMysqlType(driver.typeName(columnDef)) : dialect === "mssql" || dialect === "oracle" ? normalizeServerType(driver.typeName(columnDef), dialect) : driver.typeName(columnDef),
157
+ nullable: columnDef.nullable,
158
+ length: columnDef.length,
159
+ default: void 0,
160
+ autoIncrement: false,
161
+ ordinal,
162
+ comment: void 0
163
+ };
164
+ }
165
+ function toConstraint$1(constraint, driver, dialect) {
166
+ const name = void 0;
167
+ switch (constraint.kind) {
168
+ case "PRIMARY_KEY": return {
169
+ kind: "PRIMARY_KEY",
170
+ name,
171
+ columns: constraint.columns.map((c) => toPhysicalName(c.name, dialect)),
172
+ implicit: constraint.implicit
173
+ };
174
+ case "UNIQUE": return {
175
+ kind: "UNIQUE",
176
+ name,
177
+ columns: constraint.columns.map((c) => toPhysicalName(c.name, dialect)),
178
+ implicit: constraint.implicit
179
+ };
180
+ case "FOREIGN_KEY": return {
181
+ kind: "FOREIGN_KEY",
182
+ name,
183
+ columns: constraint.columns.map((c) => toPhysicalName(c.name, dialect)),
184
+ referencedTable: toPhysicalName(constraint.referencedColumns[0].declaringTable.name, dialect),
185
+ referencedColumns: constraint.referencedColumns.map((c) => toPhysicalName(c.name, dialect)),
186
+ onDelete: toOnDelete$2(constraint.cascade),
187
+ deferrable: false,
188
+ cascade: constraint.cascade,
189
+ implicit: constraint.implicit
190
+ };
191
+ case "CHECK": return {
192
+ kind: "CHECK",
193
+ name,
194
+ values: constraint.values,
195
+ expression: checkExpression$1(constraint),
196
+ ...dialect === "mysql" ? { comparisonExpression: normalizeMysqlCheck(checkExpression$1(constraint)) } : dialect === "mssql" || dialect === "oracle" ? { comparisonExpression: normalizeServerExpression(checkExpression$1(constraint)) } : {},
197
+ implicit: constraint.implicit
198
+ };
199
+ default: throw new Error(`不支持的约束类型: ${String(constraint.kind)}`);
200
+ }
201
+ }
202
+ function toTable(tableDef, driver, dialect) {
203
+ return {
204
+ name: toPhysicalName(tableDef.name, dialect),
205
+ columns: tableDef.columns.map((c, i) => toColumn$1(c, i + 1, driver, dialect)),
206
+ constraints: tableDef.constraints.map((c) => toConstraint$1(c, driver, dialect)),
207
+ indexes: []
208
+ };
209
+ }
210
+ /**
211
+ * TableDef[] → Schema。
212
+ *
213
+ * @param tableDefs createSchema() 的产物
214
+ * @param driver createSchema 所用 sqlClient 的 driver(提供方言类型映射)
215
+ */
216
+ function tableDefsToSchema(tableDefs, driver, options = {}) {
217
+ const dialect = options.dialect ?? "postgres";
218
+ return { tables: tableDefs.map((td) => toTable(td, driver, dialect)) };
219
+ }
220
+ //#endregion
221
+ //#region src/differ.ts
222
+ var SchemaDiffer = class {
223
+ diff(from, to) {
224
+ const fromMap = new Map(from.tables.map((t) => [t.name, t]));
225
+ const toMap = new Map(to.tables.map((t) => [t.name, t]));
226
+ const changes = [];
227
+ const destructive = [];
228
+ for (const toTable of to.tables) {
229
+ const fromTable = fromMap.get(toTable.name);
230
+ if (fromTable == null) {
231
+ changes.push({
232
+ kind: "CREATE_TABLE",
233
+ table: toTable
234
+ });
235
+ continue;
236
+ }
237
+ const alter = this._alterTable(fromTable, toTable);
238
+ if (alter != null) {
239
+ changes.push(alter);
240
+ destructive.push(...this._destructiveOf(alter));
241
+ }
242
+ }
243
+ for (const fromTable of from.tables) if (!toMap.has(fromTable.name)) {
244
+ const foreignKeyNames = fromTable.constraints.filter((c) => c.kind === "FOREIGN_KEY").map((c) => c.name).filter((name) => name != null);
245
+ changes.push({
246
+ kind: "DROP_TABLE",
247
+ table: fromTable.name,
248
+ foreignKeyNames
249
+ });
250
+ destructive.push({
251
+ kind: "DROP_TABLE",
252
+ table: fromTable.name,
253
+ foreignKeyNames
254
+ });
255
+ }
256
+ return {
257
+ changes,
258
+ destructive
259
+ };
260
+ }
261
+ /** 单表变更;无任何变化返回 null */
262
+ _alterTable(from, to) {
263
+ const columns = this._columnChanges(from, to);
264
+ const constraints = this._constraintChanges(from, to);
265
+ const indexes = this._indexChanges(from, to);
266
+ if (columns.length === 0 && constraints.length === 0 && indexes.length === 0) return null;
267
+ return {
268
+ kind: "ALTER_TABLE",
269
+ table: to.name,
270
+ columns,
271
+ constraints,
272
+ indexes
273
+ };
274
+ }
275
+ _columnChanges(from, to) {
276
+ const changes = [];
277
+ const fromCols = new Map(from.columns.map((c) => [c.name, c]));
278
+ const toCols = new Map(to.columns.map((c) => [c.name, c]));
279
+ for (const toCol of to.columns) {
280
+ const fromCol = fromCols.get(toCol.name);
281
+ if (fromCol == null) {
282
+ changes.push({
283
+ kind: "ADD_COLUMN",
284
+ column: toCol
285
+ });
286
+ continue;
287
+ }
288
+ const alter = this._alterColumn(fromCol, toCol);
289
+ if (alter != null) changes.push(alter);
290
+ }
291
+ for (const fromCol of from.columns) if (!toCols.has(fromCol.name)) changes.push({
292
+ kind: "DROP_COLUMN",
293
+ column: fromCol.name
294
+ });
295
+ return changes;
296
+ }
297
+ /** 列变更;无变化返回 null */
298
+ _alterColumn(from, to) {
299
+ const change = {
300
+ kind: "ALTER_COLUMN",
301
+ column: to.name,
302
+ type: from.type !== to.type ? to.type : void 0,
303
+ nullable: from.nullable !== to.nullable ? to.nullable : void 0,
304
+ default: to.default !== void 0 && (to.default === "" ? from.default !== void 0 : !sameDefault(to.default, from.default)) ? to.default : void 0,
305
+ autoIncrement: void 0
306
+ };
307
+ return change.type != null || change.nullable != null || change.default != null ? change : null;
308
+ }
309
+ /** 约束:内容匹配(kind + 列集合 [+ 引用/表达式]),名字不算内容;DROP 先于 ADD 执行 */
310
+ _constraintChanges(from, to) {
311
+ const changes = [];
312
+ const fromKeys = new Set(from.constraints.map(constraintKey));
313
+ const toKeys = new Set(to.constraints.map(constraintKey));
314
+ for (const constraint of from.constraints) if (!toKeys.has(constraintKey(constraint))) changes.push({
315
+ kind: "DROP_CONSTRAINT",
316
+ constraint
317
+ });
318
+ for (const constraint of to.constraints) if (!fromKeys.has(constraintKey(constraint))) changes.push({
319
+ kind: "ADD_CONSTRAINT",
320
+ constraint
321
+ });
322
+ return changes;
323
+ }
324
+ /** 索引:内容匹配(唯一性 + 列集合 + 谓词),名字不算内容;DROP 先于 ADD 执行 */
325
+ _indexChanges(from, to) {
326
+ const changes = [];
327
+ const managedFrom = from.indexes.filter((index) => !index.implicit);
328
+ const fromKeys = new Set(from.indexes.map(indexKey));
329
+ const toKeys = new Set(to.indexes.map(indexKey));
330
+ for (const index of managedFrom) if (!toKeys.has(indexKey(index))) changes.push({
331
+ kind: "DROP_INDEX",
332
+ index
333
+ });
334
+ for (const index of to.indexes) if (!fromKeys.has(indexKey(index))) changes.push({
335
+ kind: "ADD_INDEX",
336
+ index
337
+ });
338
+ return changes;
339
+ }
340
+ /** ALTER_TABLE 中的破坏性子集 */
341
+ _destructiveOf(alter) {
342
+ const destructive = [];
343
+ for (const col of alter.columns) switch (col.kind) {
344
+ case "DROP_COLUMN":
345
+ destructive.push({
346
+ kind: "DROP_COLUMN",
347
+ table: alter.table,
348
+ column: col.column
349
+ });
350
+ break;
351
+ case "ALTER_COLUMN": if (col.type != null) destructive.push({
352
+ kind: "ALTER_COLUMN",
353
+ table: alter.table,
354
+ column: col.column,
355
+ type: col.type
356
+ });
357
+ }
358
+ return destructive;
359
+ }
360
+ };
361
+ /** 约束的内容签名(匹配依据) */
362
+ function constraintKey(constraint) {
363
+ switch (constraint.kind) {
364
+ case "PRIMARY_KEY": return `pk:${constraint.columns.join(",")}`;
365
+ case "UNIQUE": return `uq:${constraint.columns.join(",")}`;
366
+ case "FOREIGN_KEY": return `fk:${constraint.columns.join(",")}->${constraint.referencedTable}(${constraint.referencedColumns.join(",")})@${constraint.onDelete}`;
367
+ case "CHECK": return `ck:${constraint.comparisonExpression ?? constraint.expression}`;
368
+ }
369
+ }
370
+ /** 索引的内容签名(匹配依据) */
371
+ function indexKey(index) {
372
+ return `${index.unique ? "uniq" : "idx"}:${index.columns.join(",")}${index.predicate != null ? `:${index.predicate}` : ""}`;
373
+ }
374
+ /** Catalogs often wrap DEFAULT expressions in parentheses. Preserve quoted data verbatim. */
375
+ function sameDefault(left, right) {
376
+ const canonical = (value) => {
377
+ const tokens = value.match(/'(?:''|[^'])*'|"(?:""|[^"])*"|[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s]/g) ?? [];
378
+ while (tokens[0] === "(" && tokens.at(-1) === ")") {
379
+ let depth = 0;
380
+ if (!tokens.every((t, i) => {
381
+ if (t === "(") depth++;
382
+ if (t === ")") depth--;
383
+ return depth > 0 || i === tokens.length - 1;
384
+ })) break;
385
+ tokens.shift();
386
+ tokens.pop();
387
+ }
388
+ return tokens.join(" ");
389
+ };
390
+ return right !== void 0 && canonical(left) === canonical(right);
391
+ }
392
+ //#endregion
393
+ //#region src/executor/postgres.ts
394
+ var PostgresSqlExecutor = class {
395
+ _pool;
396
+ constructor(_pool) {
397
+ this._pool = _pool;
398
+ }
399
+ async query(sql, params) {
400
+ return await this._pool.query(sql, params);
401
+ }
402
+ async executeStatements(statements, complete) {
403
+ const client = await this._pool.connect();
404
+ try {
405
+ await client.query("begin");
406
+ for (const sql of statements) await client.query(sql);
407
+ await complete?.(client);
408
+ await client.query("commit");
409
+ } catch (e) {
410
+ await client.query("rollback").catch(() => void 0);
411
+ throw new Error(`语句执行失败(已回滚):${e.message}`);
412
+ } finally {
413
+ client.release();
414
+ }
415
+ }
416
+ async acquireMigrationLock(key) {
417
+ const client = await this._pool.connect();
418
+ try {
419
+ await client.query("set lock_timeout = '10s'");
420
+ await client.query("select pg_advisory_lock(hashtext(current_database()), hashtext(current_schema() || ':' || $1))", [key]);
421
+ } catch (e) {
422
+ await client.query("reset lock_timeout").catch(() => void 0);
423
+ client.release();
424
+ throw new Error(`获取迁移锁失败(等待超过 10s):${e.message}`);
425
+ }
426
+ let released = false;
427
+ return async () => {
428
+ if (released) return;
429
+ released = true;
430
+ try {
431
+ await client.query("select pg_advisory_unlock(hashtext(current_database()), hashtext(current_schema() || ':' || $1))", [key]);
432
+ } catch {} finally {
433
+ await client.query("reset lock_timeout").catch(() => void 0);
434
+ client.release();
435
+ }
436
+ };
437
+ }
438
+ };
439
+ //#endregion
440
+ //#region src/lock.ts
441
+ /**
442
+ * 进程锁文件 —— 防止同一项目上并发运行多个 migrate 实例。
443
+ *
444
+ * 定位(见 docs/design.md 设计决策):migrate 是开发期独立进程工具,每次运行都是全新进程
445
+ * (`ALL_MODEL_MAP` 天然干净)。锁文件用**文件系统**做进程间互斥,在连数据库之前
446
+ * 就能拒绝并发,避免两条迁移/DDL 交叉。
447
+ *
448
+ * 设计要点:
449
+ * - 锁文件内容为 `{ pid, acquiredAt }`,不只看文件是否存在 —— 进程崩溃(如 Ctrl-C)
450
+ * 会留下 stale 锁,只看存在性会让项目永久卡住、必须手工删文件。
451
+ * - 获取时检测持有者进程是否还活着(`process.kill(pid, 0)`):活着则拒绝,死了则抢占。
452
+ * - 释放时只删**自己的**锁,避免误删别人抢到的锁。
453
+ * - 锁文件损坏(非法 JSON / 空文件)视为 stale:无从判断持有者,只能抢占。
454
+ */
455
+ /** 抢占 stale 锁时的最大重试次数(避免两个进程互相抢占导致无限循环) */
456
+ const MAX_ATTEMPTS = 3;
457
+ /**
458
+ * 获取进程锁;已有活着的持有者时抛出可读错误。
459
+ *
460
+ * @param lockPath 锁文件路径(通常在项目根)
461
+ */
462
+ async function acquireProcessLock(lockPath) {
463
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
464
+ if (await tryCreate(lockPath)) return makeLock(lockPath);
465
+ const holder = await readLockInfo(lockPath);
466
+ if (holder != null && isProcessAlive(holder.pid)) throw new Error(`另一个 migrate 进程正在操作本项目:锁文件 ${lockPath} 由 pid ${holder.pid} 持有(获取于 ${holder.acquiredAt})。若确认该进程已不存在,请删除该文件后重试。`);
467
+ await unlink(lockPath).catch(() => void 0);
468
+ }
469
+ throw new Error(`无法获取迁移锁 ${lockPath}:${MAX_ATTEMPTS} 次抢占均失败,可能有多个进程在竞争`);
470
+ }
471
+ /** 独占创建锁文件并写入持有者信息;已被占用返回 false */
472
+ async function tryCreate(lockPath) {
473
+ let handle;
474
+ try {
475
+ handle = await open(lockPath, "wx");
476
+ } catch (e) {
477
+ if (e.code === "EEXIST") return false;
478
+ throw e;
479
+ }
480
+ try {
481
+ const info = {
482
+ pid: process.pid,
483
+ acquiredAt: (/* @__PURE__ */ new Date()).toISOString()
484
+ };
485
+ await handle.writeFile(JSON.stringify(info));
486
+ return true;
487
+ } finally {
488
+ await handle.close();
489
+ }
490
+ }
491
+ function makeLock(lockPath) {
492
+ return {
493
+ path: lockPath,
494
+ async release() {
495
+ const info = await readLockInfo(lockPath);
496
+ if (info == null || info.pid === process.pid) await unlink(lockPath).catch(() => void 0);
497
+ }
498
+ };
499
+ }
500
+ /** 读取锁文件;不存在或损坏返回 null(损坏按 stale 处理) */
501
+ async function readLockInfo(lockPath) {
502
+ let raw;
503
+ try {
504
+ raw = await readFile(lockPath, "utf8");
505
+ } catch {
506
+ return null;
507
+ }
508
+ try {
509
+ const parsed = JSON.parse(raw);
510
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.pid === "number") {
511
+ const info = parsed;
512
+ return {
513
+ pid: info.pid,
514
+ acquiredAt: typeof info.acquiredAt === "string" ? info.acquiredAt : "(未知)"
515
+ };
516
+ }
517
+ } catch {}
518
+ return null;
519
+ }
520
+ /**
521
+ * 进程是否还活着。`kill(pid, 0)` 不发信号,只做存在性与权限检查:
522
+ * - 正常返回 → 存在;
523
+ * - `EPERM` → 存在但无权限发信号(仍算活着);
524
+ * - `ESRCH` → 不存在。
525
+ */
526
+ function isProcessAlive(pid) {
527
+ try {
528
+ process.kill(pid, 0);
529
+ return true;
530
+ } catch (e) {
531
+ return e.code === "EPERM";
532
+ }
533
+ }
534
+ //#endregion
535
+ //#region src/dialect.ts
536
+ const DIALECTS = [
537
+ {
538
+ name: "postgres",
539
+ tsGrmDrivers: ["PostgresDriver"],
540
+ implemented: true
541
+ },
542
+ {
543
+ name: "mysql",
544
+ tsGrmDrivers: ["MySqlDriver"],
545
+ implemented: true
546
+ },
547
+ {
548
+ name: "sqlite",
549
+ tsGrmDrivers: ["SqliteDriver"],
550
+ implemented: true
551
+ },
552
+ {
553
+ name: "mssql",
554
+ tsGrmDrivers: ["SqlServerDriver", "SqlServer2012Driver"],
555
+ implemented: true
556
+ },
557
+ {
558
+ name: "oracle",
559
+ tsGrmDrivers: ["OracleDriver", "Oracle12Drivier"],
560
+ implemented: true
561
+ }
562
+ ];
563
+ /** 全部方言名(供配置校验与错误提示) */
564
+ const DIALECT_NAMES = DIALECTS.map((d) => d.name);
565
+ /** 已端到端可用的方言名 */
566
+ const IMPLEMENTED_DIALECT_NAMES = DIALECTS.filter((d) => d.implemented).map((d) => d.name);
567
+ /**
568
+ * 取某个方言的支持信息。
569
+ * 类型上入参已受限,但配置文件可能是无类型的 JS,所以这里仍做运行时兜底。
570
+ */
571
+ function dialectInfo(name) {
572
+ const found = DIALECTS.find((d) => d.name === name);
573
+ if (found == null) throw new Error(`未知方言 "${name}"。支持的方言:${DIALECT_NAMES.join(" / ")}(当前已实现:${IMPLEMENTED_DIALECT_NAMES.join(" / ")})。`);
574
+ return found;
575
+ }
576
+ //#endregion
577
+ //#region src/introspector/postgres.ts
578
+ var PostgresIntrospector = class {
579
+ _options;
580
+ dialect = "postgres";
581
+ constructor(_options) {
582
+ this._options = _options;
583
+ }
584
+ async introspect() {
585
+ const schemaName = this._options.schema ?? "public";
586
+ const { query } = this._options;
587
+ try {
588
+ const tables = await query.query(TABLES_SQL$1, [schemaName]);
589
+ const columns = await query.query(COLUMNS_SQL, [schemaName]);
590
+ const constraints = await query.query(CONSTRAINTS_SQL, [schemaName]);
591
+ const indexes = await query.query(INDEXES_SQL, [schemaName]);
592
+ return assemble(tables.rows, columns.rows, constraints.rows, indexes.rows);
593
+ } catch (e) {
594
+ throw new Error(`Postgres 结构读取失败(schema "${schemaName}"):${e.message}`);
595
+ }
596
+ }
597
+ };
598
+ /** 普通表(relkind = 'r');分区表 'p' 与视图暂不纳入 */
599
+ const TABLES_SQL$1 = `
600
+ select c.relname as name
601
+ from pg_class c
602
+ join pg_namespace n on n.oid = c.relnamespace
603
+ where n.nspname = $1
604
+ and c.relkind = 'r'
605
+ order by c.relname
606
+ `;
607
+ const COLUMNS_SQL = `
608
+ select
609
+ c.relname as table_name,
610
+ a.attname as name,
611
+ format_type(a.atttypid, a.atttypmod) as type,
612
+ not a.attnotnull as nullable,
613
+ a.attnum as ordinal,
614
+ pg_get_expr(d.adbin, d.adrelid) as default_expr,
615
+ a.attidentity as identity,
616
+ col_description(c.oid, a.attnum) as comment
617
+ from pg_attribute a
618
+ join pg_class c on c.oid = a.attrelid
619
+ join pg_namespace n on n.oid = c.relnamespace
620
+ left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
621
+ where n.nspname = $1
622
+ and c.relkind = 'r'
623
+ and a.attnum > 0
624
+ and not a.attisdropped
625
+ order by c.relname, a.attnum
626
+ `;
627
+ /**
628
+ * contype: p=主键 u=唯一 f=外键 c=CHECK(x=排他,暂不纳入)
629
+ * confdeltype: a=no action r=restrict c=cascade n=set null d=set default
630
+ */
631
+ const CONSTRAINTS_SQL = `
632
+ select
633
+ c.relname as table_name,
634
+ con.conname as name,
635
+ con.contype as kind,
636
+ con.condeferrable as deferrable,
637
+ con.confdeltype as delete_action,
638
+ pg_get_constraintdef(con.oid) as definition,
639
+ (
640
+ select array_agg(a.attname::text order by k.ord)
641
+ from unnest(con.conkey) with ordinality as k(attnum, ord)
642
+ join pg_attribute a on a.attrelid = con.conrelid and a.attnum = k.attnum
643
+ ) as columns,
644
+ fc.relname as referenced_table,
645
+ (
646
+ select array_agg(a.attname::text order by k.ord)
647
+ from unnest(con.confkey) with ordinality as k(attnum, ord)
648
+ join pg_attribute a on a.attrelid = con.confrelid and a.attnum = k.attnum
649
+ ) as referenced_columns
650
+ from pg_constraint con
651
+ join pg_class c on c.oid = con.conrelid
652
+ join pg_namespace n on n.oid = c.relnamespace
653
+ left join pg_class fc on fc.oid = con.confrelid
654
+ where n.nspname = $1
655
+ and con.contype in ('p', 'u', 'f', 'c')
656
+ order by c.relname, con.conname
657
+ `;
658
+ /** 独立索引:排除主键索引与约束背后的索引(那些由约束表达) */
659
+ const INDEXES_SQL = `
660
+ select
661
+ c.relname as table_name,
662
+ i.relname as name,
663
+ ix.indisunique as is_unique,
664
+ pg_get_expr(ix.indpred, ix.indrelid) as predicate,
665
+ (
666
+ select array_agg(a.attname::text order by k.ord)
667
+ from unnest(ix.indkey) with ordinality as k(attnum, ord)
668
+ join pg_attribute a on a.attrelid = ix.indrelid and a.attnum = k.attnum
669
+ ) as columns
670
+ from pg_index ix
671
+ join pg_class i on i.oid = ix.indexrelid
672
+ join pg_class c on c.oid = ix.indrelid
673
+ join pg_namespace n on n.oid = c.relnamespace
674
+ where n.nspname = $1
675
+ and c.relkind = 'r'
676
+ and not ix.indisprimary
677
+ and not exists (
678
+ select 1 from pg_constraint con where con.conindid = ix.indexrelid
679
+ )
680
+ order by c.relname, i.relname
681
+ `;
682
+ function assemble(tableRows, columnRows, constraintRows, indexRows) {
683
+ const columnsByTable = /* @__PURE__ */ new Map();
684
+ for (const row of columnRows) {
685
+ const table = asString$2(row["table_name"]);
686
+ const list = columnsByTable.get(table) ?? [];
687
+ list.push(toColumn(row));
688
+ columnsByTable.set(table, list);
689
+ }
690
+ const constraintsByTable = /* @__PURE__ */ new Map();
691
+ for (const row of constraintRows) {
692
+ const constraint = toConstraint(row);
693
+ if (constraint == null) continue;
694
+ const table = asString$2(row["table_name"]);
695
+ const list = constraintsByTable.get(table) ?? [];
696
+ list.push(constraint);
697
+ constraintsByTable.set(table, list);
698
+ }
699
+ const indexesByTable = /* @__PURE__ */ new Map();
700
+ for (const row of indexRows) {
701
+ const table = asString$2(row["table_name"]);
702
+ const list = indexesByTable.get(table) ?? [];
703
+ list.push(toIndex(row));
704
+ indexesByTable.set(table, list);
705
+ }
706
+ return { tables: tableRows.map((row) => {
707
+ const name = asString$2(row["name"]);
708
+ return {
709
+ name,
710
+ columns: columnsByTable.get(name) ?? [],
711
+ constraints: constraintsByTable.get(name) ?? [],
712
+ indexes: indexesByTable.get(name) ?? []
713
+ };
714
+ }) };
715
+ }
716
+ function toColumn(row) {
717
+ const defaultExpr = row["default_expr"] == null ? void 0 : asString$2(row["default_expr"]);
718
+ const identity = asString$2(row["identity"]);
719
+ return {
720
+ name: asString$2(row["name"]),
721
+ type: normalizeType(asString$2(row["type"])),
722
+ nullable: row["nullable"] === true,
723
+ length: void 0,
724
+ default: defaultExpr,
725
+ autoIncrement: identity === "a" || identity === "d" || (defaultExpr?.startsWith("nextval(") ?? false),
726
+ ordinal: Number(row["ordinal"]),
727
+ comment: row["comment"] == null ? void 0 : asString$2(row["comment"])
728
+ };
729
+ }
730
+ function toConstraint(row) {
731
+ const name = asString$2(row["name"]);
732
+ const columns = asStringArray(row["columns"]);
733
+ switch (asString$2(row["kind"])) {
734
+ case "p": return {
735
+ kind: "PRIMARY_KEY",
736
+ name,
737
+ columns,
738
+ implicit: void 0
739
+ };
740
+ case "u": return {
741
+ kind: "UNIQUE",
742
+ name,
743
+ columns,
744
+ implicit: void 0
745
+ };
746
+ case "f": {
747
+ const onDelete = toOnDelete$1(asString$2(row["delete_action"]));
748
+ return {
749
+ kind: "FOREIGN_KEY",
750
+ name,
751
+ columns,
752
+ referencedTable: asString$2(row["referenced_table"]),
753
+ referencedColumns: asStringArray(row["referenced_columns"]),
754
+ onDelete,
755
+ deferrable: row["deferrable"] === true,
756
+ cascade: toCascade$1(onDelete),
757
+ implicit: void 0
758
+ };
759
+ }
760
+ case "c": return {
761
+ kind: "CHECK",
762
+ name,
763
+ values: [],
764
+ expression: checkExpression(asString$2(row["definition"])),
765
+ implicit: void 0
766
+ };
767
+ default: return null;
768
+ }
769
+ }
770
+ function toIndex(row) {
771
+ return {
772
+ name: asString$2(row["name"]),
773
+ columns: asStringArray(row["columns"]),
774
+ unique: row["is_unique"] === true,
775
+ predicate: row["predicate"] == null ? void 0 : asString$2(row["predicate"])
776
+ };
777
+ }
778
+ /**
779
+ * 把 `format_type()` 的输出规范成与 ts-grm `PostgresDriver.typeName()` 一致的写法。
780
+ * 只做「等价写法」归一化,不改变语义 —— 见文件头注释第 1 点。
781
+ */
782
+ function normalizeType(raw) {
783
+ if (raw === "timestamp with time zone") return "timestamptz";
784
+ const numeric = /^numeric\((\d+),(\d+)\)$/.exec(raw);
785
+ if (numeric != null) return `numeric(${numeric[1]}, ${numeric[2]})`;
786
+ return raw;
787
+ }
788
+ /** `${'CHECK ((expr))'}` → `expr`(剥掉前缀与最外层括号) */
789
+ function checkExpression(definition) {
790
+ if (!definition.startsWith("CHECK ")) return definition;
791
+ const body = definition.slice(6).trim();
792
+ if (body.startsWith("(") && body.endsWith(")")) return body.slice(1, -1);
793
+ return body;
794
+ }
795
+ /** pg 的 confdeltype → migrate 的 OnDelete */
796
+ function toOnDelete$1(code) {
797
+ switch (code) {
798
+ case "c": return "CASCADE";
799
+ case "n": return "SET_NULL";
800
+ case "d": return "SET_DEFAULT";
801
+ case "r": return "RESTRICT";
802
+ default: return "NO_ACTION";
803
+ }
804
+ }
805
+ /** migrate 的 OnDelete → ts-grm 的 ORM 级联语义(introspection 只能反推) */
806
+ function toCascade$1(onDelete) {
807
+ switch (onDelete) {
808
+ case "CASCADE": return "DELETE";
809
+ case "SET_NULL": return "SET_NULL";
810
+ default: return "NONE";
811
+ }
812
+ }
813
+ function asString$2(value) {
814
+ return typeof value === "string" ? value : String(value ?? "");
815
+ }
816
+ function asStringArray(value) {
817
+ if (Array.isArray(value)) return value.map((v) => asString$2(v));
818
+ if (typeof value === "string") return parsePgArrayLiteral(value);
819
+ return [];
820
+ }
821
+ /** 解析 PG 数组字面量(`{a,b}` / `{"a b",c}`);空数组 `{}` → [] */
822
+ function parsePgArrayLiteral(raw) {
823
+ const trimmed = raw.trim();
824
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return [];
825
+ const body = trimmed.slice(1, -1);
826
+ if (body === "") return [];
827
+ return body.split(",").map((item) => {
828
+ const s = item.trim();
829
+ return s.startsWith("\"") && s.endsWith("\"") ? s.slice(1, -1).replaceAll("\"\"", "\"") : s;
830
+ });
831
+ }
832
+ //#endregion
833
+ //#region src/ddl.ts
834
+ /** 标识符加引号(方言无关的通用形式;表名/列名来自数据库实际名字,加引号防保留字/大小写折叠) */
835
+ function quoteIdentifier(name) {
836
+ return `"${name.replaceAll("\"", "\"\"")}"`;
837
+ }
838
+ /** 列定义片段:`"NAME" type [null|not null]` */
839
+ function columnSql$1(column) {
840
+ return `${quoteIdentifier(column.name)} ${column.type}${column.nullable ? " null" : " not null"}`;
841
+ }
842
+ /** ON DELETE 动作 → SQL 子句(空串 = 省略,方言默认行为) */
843
+ function onDeleteSql(onDelete) {
844
+ switch (onDelete) {
845
+ case "CASCADE": return " on delete cascade";
846
+ case "SET_NULL": return " on delete set null";
847
+ case "SET_DEFAULT": return " on delete set default";
848
+ case "RESTRICT": return " on delete restrict";
849
+ case "NO_ACTION": return "";
850
+ }
851
+ }
852
+ /** 约束名:显式名字优先,否则按表/种类确定性生成(diff 内容匹配,名字只用于 DDL) */
853
+ function constraintName(table, constraint, seq) {
854
+ if (constraint.name != null) return constraint.name;
855
+ switch (constraint.kind) {
856
+ case "PRIMARY_KEY": return `${table}_pk`;
857
+ case "UNIQUE": return `${table}_uq_${constraint.columns.join("_")}`;
858
+ case "FOREIGN_KEY": return `${table}_fk_${constraint.columns.join("_")}`;
859
+ case "CHECK": return `${table}_ck_${seq}`;
860
+ }
861
+ }
862
+ /**
863
+ * 从零生成建表 SQL(自建兜底;提供 TableDef 映射时由方言实现改走 ts-grm 原生)。
864
+ * 约束全部 inline(PG / SQLite 都支持表级约束),语义与 ts-grm toCreationStatements 等价。
865
+ */
866
+ function createTableSql(table) {
867
+ const parts = [];
868
+ for (const column of table.columns) parts.push(` ${columnSql$1(column)}`);
869
+ let seq = 0;
870
+ for (const constraint of table.constraints) parts.push(` ${constraintSql$1(constraint, constraintName(table.name, constraint, ++seq))}`);
871
+ for (const index of table.indexes) parts.push(` ${indexSql$1(table.name, index)}`);
872
+ return `create table ${quoteIdentifier(table.name)} (\n${parts.join(",\n")}\n)`;
873
+ }
874
+ /** 表级约束片段(inline 形态) */
875
+ function constraintSql$1(constraint, name) {
876
+ switch (constraint.kind) {
877
+ case "PRIMARY_KEY": return `constraint ${quoteIdentifier(name)} primary key (${constraint.columns.map(quoteIdentifier).join(", ")})`;
878
+ case "UNIQUE": return `constraint ${quoteIdentifier(name)} unique (${constraint.columns.map(quoteIdentifier).join(", ")})`;
879
+ case "FOREIGN_KEY": return `constraint ${quoteIdentifier(name)} foreign key (${constraint.columns.map(quoteIdentifier).join(", ")}) references ${quoteIdentifier(constraint.referencedTable)} (${constraint.referencedColumns.map(quoteIdentifier).join(", ")})` + onDeleteSql(constraint.onDelete);
880
+ case "CHECK": return `constraint ${quoteIdentifier(name)} check (${constraint.expression})`;
881
+ }
882
+ }
883
+ /** 索引片段(inline 形态,createTableSql 内使用) */
884
+ function indexSql$1(table, index) {
885
+ return `constraint ${quoteIdentifier(index.name)} ${index.unique ? "unique " : ""}index (${index.columns.map(quoteIdentifier).join(", ")})`;
886
+ }
887
+ //#endregion
888
+ //#region src/ddl/postgres.ts
889
+ const q$1 = quoteIdentifier;
890
+ var PostgresDdlGenerator = class {
891
+ dialect = "postgres";
892
+ statements(diff) {
893
+ const sql = [];
894
+ const drops = [];
895
+ for (const change of diff.changes) switch (change.kind) {
896
+ case "CREATE_TABLE":
897
+ sql.push(createTableSql(change.table));
898
+ break;
899
+ case "DROP_TABLE":
900
+ drops.push(change);
901
+ break;
902
+ case "ALTER_TABLE": sql.push(...this._alterTable(change));
903
+ }
904
+ for (const drop of drops) for (const name of drop.foreignKeyNames) sql.push(`alter table ${q$1(drop.table)} drop constraint ${q$1(name)}`);
905
+ for (const drop of drops) sql.push(`drop table ${q$1(drop.table)}`);
906
+ return sql;
907
+ }
908
+ createStatements(schema) {
909
+ return schema.tables.map(createTableSql);
910
+ }
911
+ _alterTable(change) {
912
+ const sql = [];
913
+ const table = q$1(change.table);
914
+ let seq = 0;
915
+ for (const col of change.columns) sql.push(...this._columnChange(table, col));
916
+ for (const con of change.constraints) sql.push(...this._constraintChange(table, change.table, con, ++seq));
917
+ for (const idx of change.indexes) sql.push(...this._indexChange(table, idx));
918
+ return sql;
919
+ }
920
+ _columnChange(table, col) {
921
+ switch (col.kind) {
922
+ case "ADD_COLUMN": return [`alter table ${table} add column ${columnSql$1(col.column)}`];
923
+ case "DROP_COLUMN": return [`alter table ${table} drop column ${q$1(col.column)}`];
924
+ case "ALTER_COLUMN": {
925
+ const sql = [];
926
+ const column = q$1(col.column);
927
+ if (col.type != null) sql.push(`alter table ${table} alter column ${column} type ${col.type}`);
928
+ if (col.nullable != null) sql.push(`alter table ${table} alter column ${column} ${col.nullable ? "drop not null" : "set not null"}`);
929
+ if (col.default !== void 0) sql.push(col.default === "" ? `alter table ${table} alter column ${column} drop default` : `alter table ${table} alter column ${column} set default ${col.default}`);
930
+ return sql;
931
+ }
932
+ }
933
+ }
934
+ _constraintChange(table, tableName, con, seq) {
935
+ switch (con.kind) {
936
+ case "ADD_CONSTRAINT": {
937
+ const name = constraintName(tableName, con.constraint, seq);
938
+ return [`alter table ${table} add ${constraintSql$1(con.constraint, name)}`];
939
+ }
940
+ case "DROP_CONSTRAINT": {
941
+ const name = con.constraint.name ?? constraintName(tableName, con.constraint, seq);
942
+ const sql = `alter table ${table} drop constraint ${q$1(name)}`;
943
+ return con.constraint.name == null ? [`-- WARN: 约束名缺失,按生成规则推断,请核对\n${sql}`] : [sql];
944
+ }
945
+ }
946
+ }
947
+ _indexChange(table, idx) {
948
+ switch (idx.kind) {
949
+ case "ADD_INDEX": return [`create ${idx.index.unique ? "unique " : ""}index ${q$1(idx.index.name)} on ${table} (${idx.index.columns.map(q$1).join(", ")})`];
950
+ case "DROP_INDEX": return [`drop index ${q$1(idx.index.name)}`];
951
+ }
952
+ }
953
+ };
954
+ //#endregion
955
+ //#region src/ddl/sqlite.ts
956
+ const q = quoteIdentifier;
957
+ var SqliteDdlGenerator = class {
958
+ _options;
959
+ dialect = "sqlite";
960
+ constructor(_options = {}) {
961
+ this._options = _options;
962
+ }
963
+ statements(diff) {
964
+ const sql = [];
965
+ for (const change of diff.changes) switch (change.kind) {
966
+ case "CREATE_TABLE":
967
+ sql.push(...this._createTable(change.table));
968
+ break;
969
+ case "DROP_TABLE":
970
+ sql.push(`drop table ${q(change.table)}`);
971
+ break;
972
+ case "ALTER_TABLE": sql.push(...this._alterTable(change));
973
+ }
974
+ return sql;
975
+ }
976
+ createStatements(schema) {
977
+ const sql = [];
978
+ for (const table of schema.tables) sql.push(...this._createTable(table));
979
+ return sql;
980
+ }
981
+ _createTable(table) {
982
+ const tableDef = this._options.tableDefs?.get(table.name);
983
+ if (tableDef != null) {
984
+ if (this._options.driver == null) throw new Error(`生成 ${table.name} 建表 SQL 需要方言 driver(原生 toCreationStatements),请传入 DdlGeneratorOptions.driver`);
985
+ return tableDef.toCreationStatements(this._options.driver);
986
+ }
987
+ return [createTableSql(table)];
988
+ }
989
+ _alterTable(change) {
990
+ const sql = [...this._indexChanges(q(change.table), change.indexes)];
991
+ if (change.columns.some((c) => c.kind !== "ADD_COLUMN") || change.constraints.length > 0) sql.push(...this._rebuildTable(change.table));
992
+ else for (const col of change.columns) if (col.kind === "ADD_COLUMN") sql.push(...this._addColumn(q(change.table), col));
993
+ return sql;
994
+ }
995
+ /** 纯 ADD_COLUMN 原地执行(SQLite 对 not null / unique 有额外限制,注释提示) */
996
+ _addColumn(table, col) {
997
+ const column = col.column;
998
+ const sql = `alter table ${table} add column ${columnSql$1(column)}`;
999
+ return column.nullable ? [sql] : [sql, "-- 提示: SQLite 的 add column 不能是 not null(除非带默认值),如执行失败请改走重建表"];
1000
+ }
1001
+ /**
1002
+ * 重建表路径:SQLite 无法原地 drop column / 改类型 / 改约束,官方做法是
1003
+ * 「建新表 → 搬数据 → 换名」。但正确的重建还要同时处理三件目前无法安全完成的事:
1004
+ *
1005
+ * 1. **外部外键要重定向**。引用该表的其他表,会因 `alter table rename` 被 SQLite
1006
+ * 一并改成指向临时表,换名后需要逐个改回;
1007
+ * 2. **索引与触发器会随旧表消失**,需按目标态重建 —— 而索引在模型侧无来源;
1008
+ * 3. **可搬迁的列是目标与现状的交集**,需要现状信息,而 DDL 生成器只有目标态。
1009
+ *
1010
+ * 在这三件事设计清楚之前,这里**显式报错**,而不是生成会丢数据的语句 ——
1011
+ * 后者只会在真实库里安静地把表清空。这是刻意的取舍,不是遗漏。
1012
+ */
1013
+ _rebuildTable(tableName) {
1014
+ throw new Error(`SQLite 无法原地修改列或约束,表 "${tableName}" 需要重建,但重建路径尚未实现(涉及外部外键重定向、索引重建与数据搬迁,贸然执行会丢数据)。可行的替代:手工完成重建后,用 tgm resolve --applied <id> 把对应迁移标记为已应用。`);
1015
+ }
1016
+ _indexChanges(table, indexes) {
1017
+ const sql = [];
1018
+ for (const idx of indexes) switch (idx.kind) {
1019
+ case "ADD_INDEX":
1020
+ sql.push(`create ${idx.index.unique ? "unique " : ""}index ${q(idx.index.name)} on ${table} (${idx.index.columns.map(q).join(", ")})`);
1021
+ break;
1022
+ case "DROP_INDEX": sql.push(`drop index ${q(idx.index.name)}`);
1023
+ }
1024
+ return sql;
1025
+ }
1026
+ };
1027
+ //#endregion
1028
+ //#region src/server/history.ts
1029
+ /** Named columns are deliberately quoted consistently on Oracle (case-sensitive catalog names). */
1030
+ var ServerMigrationHistoryStore = class {
1031
+ executor;
1032
+ sql;
1033
+ tableName;
1034
+ constructor(executor, sql, tableName = "_migrations") {
1035
+ this.executor = executor;
1036
+ this.sql = sql;
1037
+ this.tableName = tableName;
1038
+ }
1039
+ get table() {
1040
+ return this.sql.table(this.tableName);
1041
+ }
1042
+ get now() {
1043
+ return this.sql.dialect === "mssql" ? "sysutcdatetime()" : "sys_extract_utc(systimestamp)";
1044
+ }
1045
+ column(name) {
1046
+ return this.sql.identifier(name);
1047
+ }
1048
+ async ensureTable() {
1049
+ if ((this.sql.dialect === "mssql" ? await this.executor.query("select 1 as found from sys.tables t join sys.schemas s on s.schema_id=t.schema_id where s.name=@p1 and t.name=@p2", [this.sql.schema, this.tableName]) : await this.executor.query("select 1 as \"found\" from all_tables where owner=:1 and table_name=:2", [this.sql.schema, this.tableName])).rows.length) return;
1050
+ const text = this.sql.dialect === "mssql" ? "nvarchar(max)" : "clob";
1051
+ const timestamp = this.sql.dialect === "mssql" ? "datetime2" : "timestamp";
1052
+ const id = this.sql.dialect === "mssql" ? "nvarchar(255) collate Latin1_General_100_BIN2" : "varchar2(255 char)";
1053
+ const columns = [
1054
+ `${this.column("id")} ${id} primary key`,
1055
+ `${this.column("checksum")} varchar(64) not null`,
1056
+ `${this.column("applied_at")} ${timestamp} default ${this.now} not null`,
1057
+ `${this.column("rolled_back_at")} ${timestamp}`,
1058
+ `${this.column("failed")} ${this.sql.dialect === "mssql" ? "bit" : "number(1)"} default 0 not null`,
1059
+ `${this.column("error")} ${text}`,
1060
+ `${this.column("logs")} ${text}`
1061
+ ];
1062
+ await this.executor.executeStatements([`create table ${this.table} (${columns.join(", ")})`]);
1063
+ }
1064
+ async listApplied() {
1065
+ const columns = [
1066
+ "id",
1067
+ "checksum",
1068
+ "applied_at",
1069
+ "rolled_back_at",
1070
+ "failed",
1071
+ "error",
1072
+ "logs"
1073
+ ];
1074
+ let rows;
1075
+ try {
1076
+ ({rows} = await this.executor.query(`select ${columns.map((c) => this.column(c)).join(", ")} from ${this.table} order by ${this.column("applied_at")}, ${this.column("id")}`));
1077
+ } catch (error) {
1078
+ const e = error;
1079
+ if (this.sql.dialect === "mssql" && e.number === 208) return [];
1080
+ if (this.sql.dialect === "oracle" && e.errorNum === 942) {
1081
+ const { rows: owner } = await this.executor.query(`select sys_context('USERENV', 'SESSION_USER') as "owner" from dual`);
1082
+ if (owner[0]?.owner === this.sql.schema) {
1083
+ const { rows: tables } = await this.executor.query("select table_name from user_tables where table_name=:1", [this.tableName]);
1084
+ if (!tables.length) return [];
1085
+ }
1086
+ }
1087
+ throw error;
1088
+ }
1089
+ return rows.map((r) => ({
1090
+ id: String(r.id),
1091
+ checksum: String(r.checksum),
1092
+ appliedAt: date(r.applied_at),
1093
+ rolledBackAt: r.rolled_back_at == null ? void 0 : date(r.rolled_back_at),
1094
+ failed: Number(r.failed) === 1 || r.failed === true,
1095
+ error: r.error == null ? void 0 : String(r.error),
1096
+ logs: r.logs == null ? void 0 : String(r.logs)
1097
+ }));
1098
+ }
1099
+ async recordApplied(file, connection = this.executor) {
1100
+ await this.write(file.id, file.checksum, false, null, null, connection);
1101
+ }
1102
+ async markFailed(id, error, logs) {
1103
+ await this.write(id, "", true, error, logs ?? null);
1104
+ }
1105
+ async write(id, checksum, failed, error, logs, connection = this.executor) {
1106
+ const p = (i) => this.sql.param(i);
1107
+ const c = (name) => this.column(name);
1108
+ const exists = await connection.query(`select ${c("id")} from ${this.table} where ${c("id")}=${p(1)}`, [id]);
1109
+ const params = [
1110
+ id,
1111
+ checksum || "0",
1112
+ failed ? 1 : 0,
1113
+ error,
1114
+ logs
1115
+ ];
1116
+ if (exists.rows.length) await connection.query(`update ${this.table} set ${c("checksum")}=${p(2)}, ${c("failed")}=${p(3)}, ${c("error")}=${p(4)}, ${c("logs")}=${p(5)}, ${c("applied_at")}=${this.now}, ${c("rolled_back_at")}=null where ${c("id")}=${p(1)}`, params);
1117
+ else {
1118
+ const columns = [
1119
+ "id",
1120
+ "checksum",
1121
+ "failed",
1122
+ "error",
1123
+ "logs"
1124
+ ];
1125
+ await connection.query(`insert into ${this.table} (${columns.map(c).join(", ")}) values (${columns.map((_, i) => p(i + 1)).join(", ")})`, params);
1126
+ }
1127
+ }
1128
+ async markRolledBack(id) {
1129
+ const c = (name) => this.column(name);
1130
+ const where = `where ${c("id")}=${this.sql.param(1)}`;
1131
+ const { rows } = await this.executor.query(`select ${c("id")} from ${this.table} ${where}`, [id]);
1132
+ if (!rows.length) return false;
1133
+ await this.executor.query(`update ${this.table} set ${c("rolled_back_at")}=${this.now}, ${c("failed")}=0 ${where}`, [id]);
1134
+ return true;
1135
+ }
1136
+ };
1137
+ function date(value) {
1138
+ return value instanceof Date ? value : new Date(String(value));
1139
+ }
1140
+ //#endregion
1141
+ //#region src/store.ts
1142
+ /**
1143
+ * 迁移存储 —— 磁盘上的迁移文件 + 数据库中的应用历史。
1144
+ *
1145
+ * 对应 prisma-engines 的 `sql_migration.rs`(迁移文件)与
1146
+ * `sql_migration_persistence.rs`(数据库里的 `_prisma_migrations` 表)。
1147
+ *
1148
+ * 两个关注点分开表达(不同介质、不同故障模式):
1149
+ * - `MigrationFileStore`:磁盘,`.sql` 文件即迁移;可读、可手工编辑
1150
+ * - `MigrationHistoryStore`:数据库 `_migrations` 表,记录已应用与失败
1151
+ *
1152
+ * 校验和(checksum)对**迁移 SQL 全文**计算,用于漂移检测:已应用的迁移若被事后
1153
+ * 修改,`deploy` 会拒绝继续(见 `src/migrator.ts`)。
1154
+ */
1155
+ /** 对迁移 SQL 全文计算校验和 */
1156
+ function checksumOf(sql) {
1157
+ return createHash("sha256").update(sql, "utf8").digest("hex");
1158
+ }
1159
+ /**
1160
+ * 基于目录的迁移文件存储。
1161
+ *
1162
+ * 格式:`<id>.sql`,文件全文交给执行器。PG / MySQL / SQL Server 执行批次,
1163
+ * Oracle 执行器负责识别 SQL 语句边界。文件不要自行写 begin / commit:事务由执行器管理。
1164
+ */
1165
+ var FileMigrationStore = class {
1166
+ _dir;
1167
+ constructor(_dir) {
1168
+ this._dir = _dir;
1169
+ }
1170
+ async listFiles() {
1171
+ let entries;
1172
+ try {
1173
+ entries = await readdir(this._dir);
1174
+ } catch (e) {
1175
+ if (e.code === "ENOENT") return [];
1176
+ throw new Error(`读取迁移目录失败 "${this._dir}":${e.message}`);
1177
+ }
1178
+ const files = [];
1179
+ for (const name of entries) {
1180
+ if (!name.endsWith(".sql")) continue;
1181
+ const sql = await readFile(path.join(this._dir, name), "utf8");
1182
+ const id = name.slice(0, -4);
1183
+ files.push({
1184
+ id,
1185
+ sql,
1186
+ checksum: checksumOf(sql),
1187
+ sortKey: id
1188
+ });
1189
+ }
1190
+ return files.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
1191
+ }
1192
+ async write(file) {
1193
+ await mkdir(this._dir, { recursive: true });
1194
+ await writeFile(path.join(this._dir, `${file.id}.sql`), file.sql, {
1195
+ encoding: "utf8",
1196
+ flag: "wx"
1197
+ });
1198
+ }
1199
+ };
1200
+ /** 默认历史表名(对应 prisma 的 `_prisma_migrations`) */
1201
+ const DEFAULT_HISTORY_TABLE = "_migrations";
1202
+ /**
1203
+ * 基于数据库的迁移历史存储。
1204
+ *
1205
+ * 语句是标准 SQL,方言差异集中在三处:时间类型(PG `timestamptz` / SQLite `text`)、
1206
+ * 当前时间表达式(`now()` / `current_timestamp`)、以及参数占位符(`$n` / `?`)。
1207
+ * 另有 SQLite 不支持 `alter table ... add column if not exists`,改查 catalog 实现幂等。
1208
+ */
1209
+ var DatabaseMigrationHistoryStore = class {
1210
+ _options;
1211
+ tableName;
1212
+ _table;
1213
+ _dialect;
1214
+ _server;
1215
+ constructor(_options) {
1216
+ this._options = _options;
1217
+ this.tableName = _options.table ?? "_migrations";
1218
+ this._dialect = _options.dialect ?? "postgres";
1219
+ if (this._dialect === "mssql" || this._dialect === "oracle") {
1220
+ if (this._dialect === "oracle" && !_options.schema) throw new Error("Oracle 历史表需要 schema");
1221
+ this._server = new ServerMigrationHistoryStore(_options.executor, new ServerSql(this._dialect, _options.schema ?? "dbo"), this.tableName);
1222
+ }
1223
+ this._table = this._dialect === "mysql" ? quoteMysqlIdentifier(this.tableName) : quoteIdentifier(this.tableName);
1224
+ }
1225
+ /** 当前时间表达式:PG 用 now(),SQLite 用 current_timestamp */
1226
+ get _now() {
1227
+ return this._dialect === "postgres" ? "now()" : this._dialect === "mysql" ? "current_timestamp(3)" : "current_timestamp";
1228
+ }
1229
+ /** 参数占位符:PG 是 $n,SQLite 是 ?(位置绑定,顺序一致) */
1230
+ _ph(index) {
1231
+ return this._dialect === "postgres" ? `$${index}` : "?";
1232
+ }
1233
+ async ensureTable() {
1234
+ if (this._server) return this._server.ensureTable();
1235
+ const ts = this._dialect === "postgres" ? "timestamptz" : this._dialect === "mysql" ? "datetime(3)" : "text";
1236
+ await this._options.executor.executeStatements([`create table if not exists ${this._table} (
1237
+ id ${this._dialect === "mysql" ? "varchar(255) collate utf8mb4_bin" : "text"} primary key,
1238
+ checksum text not null,
1239
+ applied_at ${ts} not null default ${this._now},
1240
+ rolled_back_at ${ts},
1241
+ failed boolean not null default false,
1242
+ error text,
1243
+ logs text
1244
+ )`]);
1245
+ await this._addColumnIfMissing("logs", "text");
1246
+ }
1247
+ /**
1248
+ * 幂等补列。
1249
+ * PG 9.6+ 有 `add column if not exists`;SQLite 没有该语法,改查 catalog
1250
+ * (`pragma_table_info` 表值函数,SQLite 3.16+)。
1251
+ */
1252
+ async _addColumnIfMissing(column, definition) {
1253
+ if (this._dialect === "postgres") {
1254
+ await this._options.executor.executeStatements([`alter table ${this._table} add column if not exists ${column} ${definition}`]);
1255
+ return;
1256
+ }
1257
+ const { rows } = this._dialect === "mysql" ? await this._options.executor.query("select COLUMN_NAME as name from information_schema.COLUMNS where TABLE_SCHEMA = database() and TABLE_NAME = ?", [this.tableName]) : await this._options.executor.query(`select name from pragma_table_info(${quoteLiteral(this.tableName)})`);
1258
+ if (rows.some((r) => asString$1(r["name"]) === column)) return;
1259
+ await this._options.executor.executeStatements([`alter table ${this._table} add column ${column} ${definition}`]);
1260
+ }
1261
+ async listApplied() {
1262
+ if (this._server) return this._server.listApplied();
1263
+ let rows;
1264
+ try {
1265
+ ({rows} = await this._options.executor.query(`select id, checksum, applied_at, rolled_back_at, failed, error, logs
1266
+ from ${this._table} order by applied_at, id`));
1267
+ } catch (error) {
1268
+ const e = error;
1269
+ if (this._dialect === "postgres" && e.code === "42P01" || this._dialect === "mysql" && e.code === "ER_NO_SUCH_TABLE" || this._dialect === "sqlite" && e.code === "SQLITE_ERROR" && e.message === `no such table: ${this.tableName}`) return [];
1270
+ throw error;
1271
+ }
1272
+ return rows.map(toAppliedMigration);
1273
+ }
1274
+ async recordApplied(migration, connection = this._options.executor) {
1275
+ if (this._server) return this._server.recordApplied(migration, connection);
1276
+ await connection.query(`insert into ${this._table} (id, checksum, applied_at, rolled_back_at, failed, error, logs)
1277
+ values (${this._ph(1)}, ${this._ph(2)}, ${this._now}, null, false, null, null)
1278
+ ${this._dialect === "mysql" ? "on duplicate key update checksum = values(checksum)," : "on conflict (id) do update set checksum = excluded.checksum,"}
1279
+ applied_at = ${this._now},
1280
+ rolled_back_at = null,
1281
+ failed = false,
1282
+ error = null,
1283
+ logs = null`, [migration.id, migration.checksum]);
1284
+ }
1285
+ async markFailed(id, error, logs) {
1286
+ if (this._server) return this._server.markFailed(id, error, logs);
1287
+ await this._options.executor.query(`insert into ${this._table} (id, checksum, applied_at, failed, error, logs)
1288
+ values (${this._ph(1)}, '', ${this._now}, true, ${this._ph(2)}, ${this._ph(3)})
1289
+ ${this._dialect === "mysql" ? "on duplicate key update failed = true, rolled_back_at = null, error = values(error), logs = values(logs)" : "on conflict (id) do update set failed = true, rolled_back_at = null, error = excluded.error, logs = excluded.logs"}`, [
1290
+ id,
1291
+ error,
1292
+ logs ?? null
1293
+ ]);
1294
+ }
1295
+ async markRolledBack(id) {
1296
+ if (this._server) return this._server.markRolledBack(id);
1297
+ if (this._dialect === "mysql") {
1298
+ const { rows } = await this._options.executor.query(`select id from ${this._table} where id = ?`, [id]);
1299
+ if (rows.length === 0) return false;
1300
+ await this._options.executor.query(`update ${this._table} set rolled_back_at = ${this._now}, failed = false where id = ?`, [id]);
1301
+ return true;
1302
+ }
1303
+ const { rows } = await this._options.executor.query(`update ${this._table}
1304
+ set rolled_back_at = ${this._now},
1305
+ failed = false
1306
+ where id = ${this._ph(1)}
1307
+ returning id`, [id]);
1308
+ return rows.length > 0;
1309
+ }
1310
+ };
1311
+ function toAppliedMigration(row) {
1312
+ return {
1313
+ id: asString$1(row["id"]),
1314
+ checksum: asString$1(row["checksum"]),
1315
+ appliedAt: toDate(row["applied_at"]),
1316
+ rolledBackAt: row["rolled_back_at"] == null ? void 0 : toDate(row["rolled_back_at"]),
1317
+ failed: row["failed"] === true || Number(row["failed"]) === 1,
1318
+ error: row["error"] == null ? void 0 : asString$1(row["error"]),
1319
+ logs: row["logs"] == null ? void 0 : asString$1(row["logs"])
1320
+ };
1321
+ }
1322
+ /** SQL 字符串字面量(用于 pragma 之类不能参数化的位置) */
1323
+ function quoteLiteral(value) {
1324
+ return `'${value.replaceAll("'", "''")}'`;
1325
+ }
1326
+ function asString$1(value) {
1327
+ return typeof value === "string" ? value : String(value ?? "");
1328
+ }
1329
+ function toDate(value) {
1330
+ return value instanceof Date ? value : new Date(String(value));
1331
+ }
1332
+ //#endregion
1333
+ //#region src/drift.ts
1334
+ /** 把一次 diff 渲染成对账报告(空数组 = 数据库与模型一致) */
1335
+ function describeDiff(diff) {
1336
+ const drift = [];
1337
+ for (const change of diff.changes) switch (change.kind) {
1338
+ case "CREATE_TABLE":
1339
+ drift.push({
1340
+ table: change.table.name,
1341
+ summary: "数据库中不存在这张表",
1342
+ known: false
1343
+ });
1344
+ break;
1345
+ case "DROP_TABLE":
1346
+ drift.push({
1347
+ table: change.table,
1348
+ summary: "数据库中多出这张表(模型里已不存在)",
1349
+ known: false
1350
+ });
1351
+ break;
1352
+ case "ALTER_TABLE": drift.push(...describeAlter(change));
1353
+ }
1354
+ return drift;
1355
+ }
1356
+ function describeAlter(alter) {
1357
+ const drift = [];
1358
+ const { table } = alter;
1359
+ for (const column of alter.columns) switch (column.kind) {
1360
+ case "ADD_COLUMN":
1361
+ drift.push({
1362
+ table,
1363
+ summary: `缺少列 ${column.column.name}`,
1364
+ known: false
1365
+ });
1366
+ break;
1367
+ case "DROP_COLUMN":
1368
+ drift.push({
1369
+ table,
1370
+ summary: `多出列 ${column.column}`,
1371
+ known: false
1372
+ });
1373
+ break;
1374
+ case "ALTER_COLUMN": {
1375
+ const parts = [];
1376
+ if (column.type != null) parts.push(`类型应为 ${column.type}`);
1377
+ if (column.nullable != null) parts.push(column.nullable ? "应为可空" : "应为非空");
1378
+ if (column.default !== void 0) parts.push(column.default === "" ? "应无默认值" : `默认值应为 ${column.default}`);
1379
+ drift.push({
1380
+ table,
1381
+ summary: `列 ${column.column}:${parts.join(",")}`,
1382
+ known: false
1383
+ });
1384
+ break;
1385
+ }
1386
+ }
1387
+ for (const change of alter.constraints) {
1388
+ const label = describeConstraint(change.constraint);
1389
+ drift.push({
1390
+ table,
1391
+ summary: change.kind === "ADD_CONSTRAINT" ? `缺少约束 ${label}` : `多出约束 ${label}`,
1392
+ known: change.constraint.kind === "CHECK"
1393
+ });
1394
+ }
1395
+ for (const change of alter.indexes) drift.push({
1396
+ table,
1397
+ summary: change.kind === "ADD_INDEX" ? `缺少索引 ${change.index.name} (${change.index.columns.join(", ")})` : `多出索引 ${change.index.name} (${change.index.columns.join(", ")})`,
1398
+ known: false
1399
+ });
1400
+ return drift;
1401
+ }
1402
+ function describeConstraint(constraint) {
1403
+ switch (constraint.kind) {
1404
+ case "PRIMARY_KEY": return `primary key (${constraint.columns.join(", ")})`;
1405
+ case "UNIQUE": return `unique (${constraint.columns.join(", ")})`;
1406
+ case "FOREIGN_KEY": return `foreign key (${constraint.columns.join(", ")}) → ${constraint.referencedTable}`;
1407
+ case "CHECK": return `check (${truncate(constraint.expression, 60)})`;
1408
+ }
1409
+ }
1410
+ function truncate(value, max) {
1411
+ return value.length <= max ? value : `${value.slice(0, max)}…`;
1412
+ }
1413
+ /** 过滤出真正的异常(排除已知限制造成的噪声) */
1414
+ function abnormalDrift(drift) {
1415
+ return drift.filter((d) => !d.known);
1416
+ }
1417
+ //#endregion
1418
+ //#region src/migrator.ts
1419
+ /**
1420
+ * Migrator —— 迁移应用器:文件扫描 → 与历史比对 → 按序执行 → 记录。
1421
+ *
1422
+ * 对应 prisma-engines 的 `apply_migration.rs` 与命令层 `apply_migrations.rs`。
1423
+ *
1424
+ * 三条路径:
1425
+ * - `deploy()`:应用所有未应用的迁移(无交互,部署/CI 用)
1426
+ * - `dev()`:introspect → diff → 生成迁移文件 → 应用(开发用)
1427
+ * - `push()`:diff 后直接应用,不写迁移文件、不记历史(快速同步)
1428
+ *
1429
+ * 可靠性(两层锁 + 漂移检测):
1430
+ * - **进程锁文件**(`src/lock.ts`):同一项目上不允许并发运行多个实例
1431
+ * - **数据库 advisory lock**:同一数据库上不允许多机并发迁移(进程锁管不到别的机器)
1432
+ * - **checksum 漂移检测**:已应用的迁移文件不得再被修改;历史里有、磁盘上没有的
1433
+ * 迁移也拒绝继续(两者都会导致结构不可复现)
1434
+ * - **按方言执行迁移**:PG / SQLite 使用事务;MySQL DDL 可能部分生效,失败记入历史
1435
+ *
1436
+ * 交互层(破坏性操作确认)不在这里 —— `Diff.destructive` 由 CLI 层使用。
1437
+ */
1438
+ /** 使用者在确认破坏性变更时选择中止 */
1439
+ var MigrationAbortedError = class extends Error {
1440
+ constructor() {
1441
+ super("已中止:检测到破坏性变更");
1442
+ this.name = "MigrationAbortedError";
1443
+ }
1444
+ };
1445
+ var Migrator = class {
1446
+ _options;
1447
+ _differ = new SchemaDiffer();
1448
+ constructor(_options) {
1449
+ this._options = _options;
1450
+ }
1451
+ /** 应用所有未应用的迁移(deploy 路径,无交互) */
1452
+ async deploy() {
1453
+ return await this._withLocks(true, async () => {
1454
+ const files = await this._options.files.listFiles();
1455
+ const applied = await this._effectiveApplied();
1456
+ this._assertNoFailed(applied);
1457
+ const appliedById = new Map(applied.map((a) => [a.id, a]));
1458
+ for (const file of files) {
1459
+ const record = appliedById.get(file.id);
1460
+ if (record != null && record.checksum !== file.checksum) throw new Error(`迁移 "${file.id}" 已应用,但文件内容已被修改(checksum 不一致):历史 ${short(record.checksum)} / 磁盘 ${short(file.checksum)}。已应用的迁移不能改,请新建一个迁移来修正。`);
1461
+ }
1462
+ const fileIds = new Set(files.map((f) => f.id));
1463
+ const missing = applied.filter((a) => !fileIds.has(a.id));
1464
+ if (missing.length > 0) throw new Error(`历史中存在但磁盘缺失的迁移:${missing.map((m) => m.id).join(", ")}。删除迁移文件会使结构不可复现,请恢复它们(或手工修正历史表)。`);
1465
+ const pending = files.filter((f) => !appliedById.has(f.id));
1466
+ const appliedNow = [];
1467
+ for (const file of pending) {
1468
+ await this._applyOne(file);
1469
+ appliedNow.push(file.id);
1470
+ }
1471
+ return {
1472
+ applied: appliedNow,
1473
+ skipped: files.length - pending.length,
1474
+ drift: await this._describeDrift()
1475
+ };
1476
+ });
1477
+ }
1478
+ /**
1479
+ * 生成并应用新迁移(dev 路径)。
1480
+ * 与数据库无差异时不产生文件;破坏性变更的确认交给 CLI 层(`Diff.destructive`)。
1481
+ * `name` 可省略,省略时迁移只用时间戳命名。
1482
+ */
1483
+ async dev(options) {
1484
+ return await this._withLocks(true, async () => {
1485
+ this._assertNoFailed(await this._effectiveApplied());
1486
+ const { diff, from, to } = await this._diffAgainstDatabase();
1487
+ if (diff.changes.length === 0) return {
1488
+ diff,
1489
+ migrationId: void 0,
1490
+ applied: false,
1491
+ drift: []
1492
+ };
1493
+ await this._confirmIfNeeded(diff);
1494
+ const sql = toSqlFile(this._options.ddl.statements(diff, {
1495
+ from,
1496
+ to
1497
+ }));
1498
+ const existing = await this._options.files.listFiles();
1499
+ let time = Date.now();
1500
+ for (const file of existing) {
1501
+ const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{3})?(?:_|$)/.exec(file.id);
1502
+ if (match) {
1503
+ const previous = Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6], +(match[7] ?? 0));
1504
+ time = Math.max(time, previous + (match[7] ? 1 : 1e3));
1505
+ }
1506
+ }
1507
+ const id = generateMigrationId(new Date(time), options.name ?? "");
1508
+ const file = {
1509
+ id,
1510
+ sql,
1511
+ checksum: checksumOf(sql),
1512
+ sortKey: id
1513
+ };
1514
+ await this._options.files.write(file);
1515
+ await this._applyOne(file);
1516
+ return {
1517
+ diff,
1518
+ migrationId: id,
1519
+ applied: true,
1520
+ drift: await this._describeDrift()
1521
+ };
1522
+ });
1523
+ }
1524
+ /** 无历史快速同步:diff 后直接应用,不写文件、不记历史(push 路径) */
1525
+ async push() {
1526
+ return await this._withLocks(false, async () => {
1527
+ const { diff, from, to } = await this._diffAgainstDatabase();
1528
+ await this._confirmIfNeeded(diff);
1529
+ const statements = this._options.ddl.statements(diff, {
1530
+ from,
1531
+ to
1532
+ });
1533
+ if (statements.length > 0) await this._options.executor.executeStatements(statements);
1534
+ return {
1535
+ diff,
1536
+ statements,
1537
+ drift: await this._describeDrift()
1538
+ };
1539
+ });
1540
+ }
1541
+ /** 迁移状态(只读,不加锁,不改库) */
1542
+ async status() {
1543
+ const files = await this._options.files.listFiles();
1544
+ const applied = await this._effectiveApplied();
1545
+ const appliedIds = new Set(applied.map((a) => a.id));
1546
+ return {
1547
+ applied: applied.map((a) => ({
1548
+ id: a.id,
1549
+ appliedAt: a.appliedAt,
1550
+ failed: a.failed
1551
+ })),
1552
+ pending: files.filter((f) => !appliedIds.has(f.id)).map((f) => f.id)
1553
+ };
1554
+ }
1555
+ /**
1556
+ * 手工修正迁移状态 —— 失败后的恢复途径。
1557
+ *
1558
+ * - `applied`:记为已应用(适用于「这条 SQL 我已经手工执行过了」)
1559
+ * - `rolled-back`:清除历史记录,让它重新变成待应用(适用于「影响已回退」)
1560
+ *
1561
+ * 没有这一步,一次失败的迁移会把 deploy / dev 永久卡住 —— `_assertNoFailed`
1562
+ * 会一直拒绝,而使用者只能去手工改数据库表。
1563
+ */
1564
+ async resolve(options) {
1565
+ return await this._withLocks(true, async () => {
1566
+ const file = (await this._options.files.listFiles()).find((f) => f.id === options.migration);
1567
+ if (file == null) throw new Error(`迁移 "${options.migration}" 不在磁盘上(${this._options.migrationsDir}),无法修正状态。`);
1568
+ if (options.action === "applied") {
1569
+ await this._options.history.recordApplied(file);
1570
+ return;
1571
+ }
1572
+ if (!await this._options.history.markRolledBack(options.migration)) throw new Error(`迁移 "${options.migration}" 没有历史记录,无法标记回滚(它可能从未被应用过)。`);
1573
+ });
1574
+ }
1575
+ /**
1576
+ * 对账:不应用任何东西,只报告当前数据库与模型的差异。
1577
+ * 迁移之后调它,可确认数据库真的变成了模型的样子。
1578
+ */
1579
+ async checkDrift() {
1580
+ return await this._describeDrift();
1581
+ }
1582
+ /** 再 introspect 一次并与模型对比(空 = 一致) */
1583
+ async _describeDrift() {
1584
+ return describeDiff((await this._diffAgainstDatabase()).diff);
1585
+ }
1586
+ /**
1587
+ * 上次失败的迁移必须先处理:它意味着数据库可能处于半应用状态,
1588
+ * 而且失败记录的 checksum 是空的(不能被当成正常应用的迁移做漂移比较)。
1589
+ */
1590
+ _assertNoFailed(applied) {
1591
+ const failed = applied.filter((a) => a.failed);
1592
+ if (failed.length === 0) return;
1593
+ throw new Error(`以下迁移上次执行失败,需要先处理:${failed.map((f) => f.id).join(", ")}。数据库可能处于半应用状态;检查并手工修正数据库后,使用 resolve --applied 或 resolve --rolled-back 修正状态。`);
1594
+ }
1595
+ /** 有破坏性变更时询问;使用者拒绝则中止 */
1596
+ async _confirmIfNeeded(diff) {
1597
+ const { confirm } = this._options;
1598
+ if (confirm == null || diff.destructive.length === 0) return;
1599
+ if (!await confirm(diff)) throw new MigrationAbortedError();
1600
+ }
1601
+ /** 包一层进程锁 + 数据库锁 */
1602
+ async _withLocks(ensureHistory, fn) {
1603
+ const lock = await acquireProcessLock(this._options.lockPath);
1604
+ let releaseDbLock;
1605
+ try {
1606
+ releaseDbLock = await this._options.executor.acquireMigrationLock(this._options.lockKey ?? "ts-grm-migrate");
1607
+ if (ensureHistory) await this._options.history.ensureTable();
1608
+ return await fn();
1609
+ } finally {
1610
+ if (releaseDbLock != null) await releaseDbLock().catch(() => void 0);
1611
+ await lock.release();
1612
+ }
1613
+ }
1614
+ async _applyOne(file) {
1615
+ await this._options.history.markFailed(file.id, "迁移已开始但尚未确认完成;请检查数据库后使用 resolve 修正状态。", file.sql);
1616
+ try {
1617
+ let completed = false;
1618
+ await this._options.executor.executeStatements([file.sql], async (connection) => {
1619
+ await this._options.history.recordApplied(file, connection);
1620
+ completed = true;
1621
+ });
1622
+ if (!completed) throw new Error("SQL 执行器未调用迁移完成回调,无法确认成功状态");
1623
+ } catch (e) {
1624
+ const message = e.message;
1625
+ try {
1626
+ await this._options.history.markFailed(file.id, message, failureLogs(file, message));
1627
+ } catch (historyError) {
1628
+ throw new AggregateError([e, historyError], `迁移 "${file.id}" 执行失败:${message};更新失败历史也失败,保留未完成状态。`);
1629
+ }
1630
+ throw new Error(`迁移 "${file.id}" 执行失败:${message}`);
1631
+ }
1632
+ }
1633
+ /**
1634
+ * 当前「已生效」的迁移记录:**排除被标记回滚的**。
1635
+ * 被回滚的迁移重新算待应用(`resolve --rolled-back` 的语义),
1636
+ * 但它那条记录会保留下来,作为「什么时候回滚过」的审计痕迹。
1637
+ */
1638
+ async _effectiveApplied() {
1639
+ return (await this._options.history.listApplied()).filter((a) => a.rolledBackAt == null);
1640
+ }
1641
+ async _diffAgainstDatabase() {
1642
+ const actual = await this._options.introspector.introspect();
1643
+ const target = await this._options.targetSchema();
1644
+ const historyTable = this._options.history.tableName;
1645
+ const business = actual.tables.some((t) => t.name === historyTable) ? { tables: actual.tables.filter((t) => t.name !== historyTable) } : actual;
1646
+ return {
1647
+ diff: this._differ.diff(business, target),
1648
+ from: business,
1649
+ to: target
1650
+ };
1651
+ }
1652
+ };
1653
+ /**
1654
+ * 迁移 id:UTC 毫秒时间戳 + 名字 slug(`20260911120000000_init`)。
1655
+ * 时间戳前缀保证**字典序即时间序**,`sortKey` 直接复用它。
1656
+ */
1657
+ function generateMigrationId(now, name) {
1658
+ const pad = (n) => n.toString().padStart(2, "0");
1659
+ const stamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}${now.getUTCMilliseconds().toString().padStart(3, "0")}`;
1660
+ const slug = name.trim().toLowerCase().replaceAll(/[^a-z0-9]+/g, "_").replaceAll(/^_+|_+$/g, "");
1661
+ return slug === "" ? stamp : `${stamp}_${slug}`;
1662
+ }
1663
+ /** 语句数组 → 迁移文件内容(语句间空行分隔,统一以分号结尾) */
1664
+ function toSqlFile(statements) {
1665
+ return `${statements.map((s) => {
1666
+ const trimmed = s.trimEnd();
1667
+ return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
1668
+ }).join("\n\n")}\n`;
1669
+ }
1670
+ function short(checksum) {
1671
+ return checksum.slice(0, 12);
1672
+ }
1673
+ /** 失败时写进历史的可读日志(`error` 是摘要,`logs` 是详情) */
1674
+ function failureLogs(file, message) {
1675
+ return [
1676
+ `迁移 ${file.id} 执行失败`,
1677
+ `时间:${(/* @__PURE__ */ new Date()).toISOString()}`,
1678
+ `错误:${message}`,
1679
+ message.includes("已回滚") ? "执行器报告事务已回滚。" : "非事务 DDL 可能已部分生效;请检查数据库后修正迁移状态。"
1680
+ ].join("\n");
1681
+ }
1682
+ //#endregion
1683
+ //#region src/config.ts
1684
+ /**
1685
+ * CLI 配置 —— 在项目根放一个 `ts-grm-migrate.config.ts`(或 `.mts` / `.mjs` / `.js`)。
1686
+ *
1687
+ * ```ts
1688
+ * import { defineConfig } from "ts-grm-migrate";
1689
+ *
1690
+ * export default defineConfig({
1691
+ * database: { host: "localhost", database: "app", user: "postgres" },
1692
+ * models: ["./src/models"], // 相对项目根,交给 EntityManager.of 加载
1693
+ * });
1694
+ * ```
1695
+ *
1696
+ * 模型文件可以是 `.ts`(Node 22.18+ / 23.6+ 原生类型剥离)或编译后的 `.js`。
1697
+ */
1698
+ /** 配置辅助函数:仅用于类型提示与自动补全 */
1699
+ function defineConfig(config) {
1700
+ return config;
1701
+ }
1702
+ /** 配置文件名候选(按顺序尝试) */
1703
+ const CONFIG_FILENAMES = [
1704
+ "ts-grm-migrate.config.ts",
1705
+ "ts-grm-migrate.config.mts",
1706
+ "ts-grm-migrate.config.mjs",
1707
+ "ts-grm-migrate.config.js"
1708
+ ];
1709
+ /** 加载配置:显式路径优先,否则在 `cwd` 下按候选名查找 */
1710
+ async function loadConfig(cwd, explicitPath) {
1711
+ const file = explicitPath != null ? path.resolve(cwd, explicitPath) : await findConfig(cwd);
1712
+ if (file == null) throw new Error(`未找到配置文件。请在项目根创建下列之一:\n ${CONFIG_FILENAMES.join("\n ")}`);
1713
+ return {
1714
+ config: validateConfig(await importConfigModule(file), file),
1715
+ path: file
1716
+ };
1717
+ }
1718
+ async function findConfig(cwd) {
1719
+ for (const name of CONFIG_FILENAMES) {
1720
+ const file = path.join(cwd, name);
1721
+ try {
1722
+ await access(file);
1723
+ return file;
1724
+ } catch {}
1725
+ }
1726
+ return null;
1727
+ }
1728
+ async function importConfigModule(file) {
1729
+ let mod;
1730
+ try {
1731
+ mod = await import(pathToFileURL(file).href);
1732
+ } catch (e) {
1733
+ throw new Error(`加载配置文件失败 "${file}":${e.message}${configLoadHint(file, e)}`);
1734
+ }
1735
+ return mod.default;
1736
+ }
1737
+ /** 针对常见失败给出可操作的提示,而不是把 Node 的原始报错直接丢给使用者 */
1738
+ function configLoadHint(file, error) {
1739
+ const message = error.message ?? "";
1740
+ if (message.includes("outside a module")) return "\n提示:`.ts` 配置文件的模块类型由最近的 package.json 决定。若你的项目是 CommonJS,请把配置改名为 `.mts`(强制 ESM),或给 package.json 加上 \"type\": \"module\"。";
1741
+ if (message.includes("Cannot find module")) return `\n提示:配置文件里 import 的包在该项目下解析不到(请确认已安装,路径:${file})。`;
1742
+ return "";
1743
+ }
1744
+ function validateConfig(value, file) {
1745
+ if (typeof value !== "object" || value === null) throw new Error(`配置文件 "${file}" 必须默认导出一个配置对象(建议用 defineConfig(...) 包裹)。`);
1746
+ const config = value;
1747
+ if (typeof config.database !== "object" || config.database === null) throw new Error(`配置文件 "${file}" 缺少 database(数据库连接信息)。`);
1748
+ if (!Array.isArray(config.models) || config.models.length === 0) throw new Error(`配置文件 "${file}" 缺少 models(模型文件或目录,至少一项)。`);
1749
+ if (config.dialect != null) dialectInfo(config.dialect);
1750
+ return config;
1751
+ }
1752
+ //#endregion
1753
+ //#region src/ddl/mysql.ts
1754
+ /**
1755
+ * Phase ordering: drop dependent FKs/indexes/constraints, alter columns, add keys, add FKs.
1756
+ * CREATE foreign keys are deferred so table order and cyclic references are harmless.
1757
+ * @see https://github.com/prisma/prisma-engines/blob/main/schema-engine/connectors/sql-schema-connector/src/flavour/mysql/renderer.rs
1758
+ */
1759
+ var MysqlDdlGenerator = class {
1760
+ dialect = "mysql";
1761
+ statements(diff, context) {
1762
+ const detach = [], dropKeys = [], body = [], addKeys = [], attach = [];
1763
+ const droppedForeignKeys = /* @__PURE__ */ new Set();
1764
+ const addedForeignKeys = /* @__PURE__ */ new Set();
1765
+ const dropFk = (table, fk) => {
1766
+ if (!fk.name) throw new Error(`删除外键 ${table} 时缺少实际约束名`);
1767
+ const key = `${table}\0${fk.name}`;
1768
+ if (droppedForeignKeys.has(key)) return;
1769
+ droppedForeignKeys.add(key);
1770
+ detach.push(`alter table ${quoteMysqlIdentifier(table)} drop foreign key ${quoteMysqlIdentifier(fk.name)}`);
1771
+ };
1772
+ const addFk = (table, fk, seq) => {
1773
+ const key = `${table}\0${fk.columns.join("\0")}`;
1774
+ if (addedForeignKeys.has(key)) return;
1775
+ addedForeignKeys.add(key);
1776
+ attach.push(`alter table ${quoteMysqlIdentifier(table)} add ${constraintSql(table, fk, seq)}`);
1777
+ };
1778
+ const needsDetach = (table, columns) => diff.changes.some((change) => change.kind === "ALTER_TABLE" && change.table === table && (change.columns.some((c) => c.kind !== "ADD_COLUMN" && columns.includes(c.column) && (c.kind === "DROP_COLUMN" || c.type !== void 0 || c.nullable !== void 0)) || change.constraints.some((c) => c.kind === "DROP_CONSTRAINT" && (c.constraint.kind === "PRIMARY_KEY" || c.constraint.kind === "UNIQUE")) || change.indexes.some((i) => i.kind === "DROP_INDEX")));
1779
+ if (context) for (const table of context.from.tables) for (const fk of table.constraints) {
1780
+ if (fk.kind !== "FOREIGN_KEY") continue;
1781
+ if (!needsDetach(table.name, fk.columns) && !needsDetach(fk.referencedTable, fk.referencedColumns)) continue;
1782
+ dropFk(table.name, fk);
1783
+ const target = context.to.tables.find((t) => t.name === table.name);
1784
+ const next = target?.constraints.find((c) => c.kind === "FOREIGN_KEY" && c.columns.join("\0") === fk.columns.join("\0") && c.referencedTable === fk.referencedTable);
1785
+ if (next) addFk(table.name, next, target.constraints.indexOf(next) + 1);
1786
+ }
1787
+ for (const change of diff.changes) {
1788
+ if (change.kind === "CREATE_TABLE") {
1789
+ body.push(createTable(change.table));
1790
+ change.table.constraints.forEach((c, i) => {
1791
+ if (c.kind === "FOREIGN_KEY") addFk(change.table.name, c, i + 1);
1792
+ });
1793
+ continue;
1794
+ }
1795
+ if (change.kind === "DROP_TABLE") {
1796
+ for (const name of change.foreignKeyNames) {
1797
+ const key = `${change.table}\0${name}`;
1798
+ if (!droppedForeignKeys.has(key)) {
1799
+ droppedForeignKeys.add(key);
1800
+ detach.push(`alter table ${quoteMysqlIdentifier(change.table)} drop foreign key ${quoteMysqlIdentifier(name)}`);
1801
+ }
1802
+ }
1803
+ body.push(`drop table ${quoteMysqlIdentifier(change.table)}`);
1804
+ continue;
1805
+ }
1806
+ const table = quoteMysqlIdentifier(change.table);
1807
+ const before = context?.from.tables.find((t) => t.name === change.table);
1808
+ for (const con of change.constraints) if (con.kind === "DROP_CONSTRAINT") {
1809
+ const c = con.constraint;
1810
+ if (c.kind === "FOREIGN_KEY") {
1811
+ dropFk(change.table, c);
1812
+ continue;
1813
+ }
1814
+ if (c.kind !== "PRIMARY_KEY" && !c.name) throw new Error(`删除约束 ${change.table} 时缺少实际约束名`);
1815
+ dropKeys.push(`alter table ${table} drop ${c.kind === "PRIMARY_KEY" ? "primary key" : c.kind === "UNIQUE" ? `index ${quoteMysqlIdentifier(c.name)}` : `check ${quoteMysqlIdentifier(c.name)}`}`);
1816
+ } else {
1817
+ const seq = context?.to.tables.find((t) => t.name === change.table)?.constraints.indexOf(con.constraint) ?? change.constraints.indexOf(con);
1818
+ if (con.constraint.kind === "FOREIGN_KEY") addFk(change.table, con.constraint, seq + 1);
1819
+ else addKeys.push(`alter table ${table} add ${constraintSql(change.table, con.constraint, seq + 1)}`);
1820
+ }
1821
+ for (const idx of change.indexes) if (idx.kind === "DROP_INDEX") dropKeys.push(`drop index ${quoteMysqlIdentifier(idx.index.name)} on ${table}`);
1822
+ else addKeys.push(`create ${indexSql(idx.index)} on ${table} (${idx.index.columns.map(quoteMysqlIdentifier).join(", ")})`);
1823
+ for (const col of change.columns) if (col.kind === "ADD_COLUMN") body.push(`alter table ${table} add column ${columnSql(col.column)}`);
1824
+ else if (col.kind === "DROP_COLUMN") body.push(`alter table ${table} drop column ${quoteMysqlIdentifier(col.column)}`);
1825
+ else {
1826
+ const previous = before?.columns.find((c) => c.name === col.column);
1827
+ if (!previous) throw new Error(`MySQL 修改 ${change.table}.${col.column} 需要 DdlContext 中的原始列定义`);
1828
+ const next = {
1829
+ ...previous,
1830
+ type: col.type ?? previous.type,
1831
+ nullable: col.nullable ?? previous.nullable,
1832
+ default: col.default === void 0 ? previous.default : col.default === "" ? void 0 : col.default,
1833
+ autoIncrement: col.autoIncrement ?? previous.autoIncrement
1834
+ };
1835
+ body.push(`alter table ${table} modify column ${columnSql(next)}`);
1836
+ }
1837
+ }
1838
+ return [
1839
+ ...detach,
1840
+ ...dropKeys,
1841
+ ...body,
1842
+ ...addKeys,
1843
+ ...attach
1844
+ ];
1845
+ }
1846
+ createStatements(schema) {
1847
+ return this.statements({
1848
+ changes: schema.tables.map((table) => ({
1849
+ kind: "CREATE_TABLE",
1850
+ table
1851
+ })),
1852
+ destructive: []
1853
+ });
1854
+ }
1855
+ };
1856
+ function columnSql(column) {
1857
+ let sql = `${quoteMysqlIdentifier(column.name)} ${column.type}`;
1858
+ const characterType = /^(?:char|varchar|tinytext|text|mediumtext|longtext|enum|set)\b/i.test(column.type);
1859
+ if (characterType && column.mysql?.charset) sql += ` character set ${quoteMysqlIdentifier(column.mysql.charset)}`;
1860
+ if (characterType && column.mysql?.collation) sql += ` collate ${quoteMysqlIdentifier(column.mysql.collation)}`;
1861
+ sql += column.nullable ? " null" : " not null";
1862
+ if (column.default !== void 0 && column.default !== "") sql += ` default ${column.default}`;
1863
+ if (column.mysql?.onUpdate) sql += ` on update ${column.mysql.onUpdate}`;
1864
+ if (column.autoIncrement) sql += " auto_increment";
1865
+ if (column.comment !== void 0) sql += ` comment ${quoteMysqlLiteral(column.comment)}`;
1866
+ return sql;
1867
+ }
1868
+ function constraintSql(table, constraint, seq) {
1869
+ const prefix = `constraint ${quoteMysqlIdentifier(mysqlName(constraintName(table, constraint, seq)))}`;
1870
+ switch (constraint.kind) {
1871
+ case "PRIMARY_KEY": return `primary key (${constraint.columns.map(quoteMysqlIdentifier).join(", ")})`;
1872
+ case "UNIQUE": return `${prefix} unique (${constraint.columns.map(quoteMysqlIdentifier).join(", ")})`;
1873
+ case "CHECK": return `${prefix} check (${constraint.expression})`;
1874
+ case "FOREIGN_KEY": {
1875
+ if (constraint.deferrable || constraint.onDelete === "SET_DEFAULT") throw new Error("MySQL 不支持 DEFERRABLE 或 ON DELETE SET DEFAULT");
1876
+ const action = constraint.onDelete.replaceAll("_", " ");
1877
+ return `${prefix} foreign key (${constraint.columns.map(quoteMysqlIdentifier).join(", ")}) references ${quoteMysqlIdentifier(constraint.referencedTable)} (${constraint.referencedColumns.map(quoteMysqlIdentifier).join(", ")}) on delete ${action}`;
1878
+ }
1879
+ }
1880
+ }
1881
+ function indexSql(index) {
1882
+ if (index.predicate != null) throw new Error(`MySQL 不支持部分索引 ${index.name}`);
1883
+ return `${index.unique ? "unique " : ""}index ${quoteMysqlIdentifier(index.name)}`;
1884
+ }
1885
+ function createTable(table) {
1886
+ const parts = table.columns.map(columnSql);
1887
+ table.constraints.forEach((c, i) => {
1888
+ if (c.kind !== "FOREIGN_KEY") parts.push(constraintSql(table.name, c, i + 1));
1889
+ });
1890
+ for (const index of table.indexes) parts.push(`${indexSql(index)} (${index.columns.map(quoteMysqlIdentifier).join(", ")})`);
1891
+ return `create table ${quoteMysqlIdentifier(table.name)} (\n ${parts.join(",\n ")}\n) engine=InnoDB`;
1892
+ }
1893
+ //#endregion
1894
+ //#region src/executor/mysql.ts
1895
+ /**
1896
+ * DDL implicitly commits in MySQL. Never report that a failed migration was rolled back.
1897
+ * Keep the advisory lock and all migration work on the same session: loss of the session
1898
+ * must abort the migration instead of continuing on another pooled connection.
1899
+ * @see https://dev.mysql.com/doc/refman/8.4/en/implicit-commit.html
1900
+ * @see https://dev.mysql.com/doc/refman/8.4/en/locking-functions.html
1901
+ */
1902
+ var MysqlSqlExecutor = class {
1903
+ _pool;
1904
+ _lockTimeout;
1905
+ _locked;
1906
+ constructor(_pool, _lockTimeout = 10) {
1907
+ this._pool = _pool;
1908
+ this._lockTimeout = _lockTimeout;
1909
+ }
1910
+ async _prepare(connection) {
1911
+ await connection.query("set session sql_mode = concat_ws(',', nullif(@@sql_mode, ''), 'NO_BACKSLASH_ESCAPES')");
1912
+ }
1913
+ async _withConnection(fn) {
1914
+ if (this._locked) return await fn(this._locked);
1915
+ const connection = await this._pool.getConnection();
1916
+ try {
1917
+ await this._prepare(connection);
1918
+ return await fn(connection);
1919
+ } finally {
1920
+ connection.release();
1921
+ }
1922
+ }
1923
+ async query(sql, params) {
1924
+ return await this._withConnection(async (connection) => {
1925
+ const [result] = params?.length ? await connection.execute(sql, params) : await connection.query(sql);
1926
+ return { rows: Array.isArray(result) ? result : [] };
1927
+ });
1928
+ }
1929
+ async executeStatements(statements, complete) {
1930
+ await this._withConnection(async (connection) => {
1931
+ try {
1932
+ for (const sql of statements) await connection.query(sql);
1933
+ await complete?.({ query: async (sql, params) => {
1934
+ const [result] = params?.length ? await connection.execute(sql, params) : await connection.query(sql);
1935
+ return { rows: Array.isArray(result) ? result : [] };
1936
+ } });
1937
+ } catch (e) {
1938
+ throw new Error(`MySQL 语句执行失败:${e.message}。DDL 会隐式提交,之前成功的语句可能已生效;请检查数据库后使用 resolve 修正状态。`);
1939
+ }
1940
+ });
1941
+ }
1942
+ async acquireMigrationLock(_key) {
1943
+ if (this._locked) throw new Error("当前 MySQL 执行器已持有迁移锁");
1944
+ const connection = await this._pool.getConnection();
1945
+ let name;
1946
+ try {
1947
+ await this._prepare(connection);
1948
+ const [result] = await connection.query("select database() as db");
1949
+ const db = result[0]?.db;
1950
+ if (!db) throw new Error("MySQL 连接必须指定 database");
1951
+ name = `tgm:${createHash("sha256").update(db).digest("hex").slice(0, 60)}`;
1952
+ const [rows] = await connection.query(`select get_lock('${name}', ${this._lockTimeout}) as acquired`);
1953
+ if (Number(rows[0]?.acquired) !== 1) throw new Error(`获取 MySQL 迁移锁失败(等待 ${this._lockTimeout}s)`);
1954
+ this._locked = connection;
1955
+ } catch (e) {
1956
+ connection.destroy();
1957
+ throw e;
1958
+ }
1959
+ let released = false;
1960
+ return async () => {
1961
+ if (released) return;
1962
+ released = true;
1963
+ this._locked = void 0;
1964
+ try {
1965
+ await connection.query(`select release_lock('${name}')`);
1966
+ connection.release();
1967
+ } catch {
1968
+ connection.destroy();
1969
+ }
1970
+ };
1971
+ }
1972
+ };
1973
+ //#endregion
1974
+ //#region src/server/ddl.ts
1975
+ /** Dependency ordering shared by SQL Server and Oracle; syntax stays dialect-specific. */
1976
+ var ServerDdlGenerator = class {
1977
+ dialect;
1978
+ sql;
1979
+ constructor(dialect, schema) {
1980
+ this.dialect = dialect;
1981
+ this.sql = new ServerSql(dialect, schema);
1982
+ }
1983
+ statements(diff, context) {
1984
+ const dropFk = /* @__PURE__ */ new Map(), dropKeys = /* @__PURE__ */ new Map();
1985
+ const body = [], addKeys = /* @__PURE__ */ new Map(), addFk = /* @__PURE__ */ new Map();
1986
+ const q = (name) => this.sql.identifier(name);
1987
+ const table = (name) => this.sql.table(name);
1988
+ const dropping = new Set(diff.changes.filter((c) => c.kind === "DROP_TABLE").map((c) => c.table));
1989
+ const altered = new Map(diff.changes.filter((c) => c.kind === "ALTER_TABLE").map((c) => [c.table, c]));
1990
+ const columnChanged = (name) => altered.get(name)?.columns.some((c) => c.kind !== "ADD_COLUMN") ?? false;
1991
+ const keyChanged = (name) => altered.get(name)?.constraints.some((c) => c.kind === "DROP_CONSTRAINT") ?? false;
1992
+ const removeConstraint = (name, c) => {
1993
+ if (!c.name) throw new Error(`删除 ${name} 的约束需要实际约束名`);
1994
+ (c.kind === "FOREIGN_KEY" ? dropFk : dropKeys).set(`${name}\0${c.name}`, `alter table ${table(name)} drop constraint ${q(c.name)}`);
1995
+ };
1996
+ const addConstraint = (name, c, i) => {
1997
+ const constraint = this.constraint(name, c, i);
1998
+ (c.kind === "FOREIGN_KEY" ? addFk : addKeys).set(`${name}\0${constraint}`, `alter table ${table(name)} add ${constraint}`);
1999
+ };
2000
+ const removeIndex = (name, index) => {
2001
+ dropKeys.set(`${name}\0index:${index.name}`, this.dialect === "mssql" ? `drop index ${q(index.name)} on ${table(name)}` : `drop index ${table(index.name)}`);
2002
+ };
2003
+ const addIndex = (name, index) => {
2004
+ addKeys.set(`${name}\0index:${index.name}`, this.index(name, index));
2005
+ };
2006
+ if (context) for (const before of context.from.tables) {
2007
+ const after = context.to.tables.find((t) => t.name === before.name);
2008
+ for (const c of before.constraints) {
2009
+ if (!(c.kind === "FOREIGN_KEY" ? dropping.has(before.name) || columnChanged(before.name) || columnChanged(c.referencedTable) || keyChanged(c.referencedTable) : columnChanged(before.name)) || dropping.has(before.name) && c.kind !== "FOREIGN_KEY") continue;
2010
+ removeConstraint(before.name, c);
2011
+ if (after) after.constraints.forEach((next, i) => {
2012
+ if (next.kind === c.kind && (next.kind !== "FOREIGN_KEY" || c.kind === "FOREIGN_KEY" && next.columns.join("\0") === c.columns.join("\0"))) addConstraint(before.name, next, i + 1);
2013
+ });
2014
+ }
2015
+ if (columnChanged(before.name)) {
2016
+ for (const index of before.indexes) removeIndex(before.name, index);
2017
+ for (const index of after?.indexes ?? []) addIndex(before.name, index);
2018
+ }
2019
+ }
2020
+ for (const change of diff.changes) {
2021
+ if (change.kind === "CREATE_TABLE") {
2022
+ body.push(this.createTable(change.table));
2023
+ change.table.constraints.forEach((c, i) => {
2024
+ if (c.kind === "FOREIGN_KEY") addConstraint(change.table.name, c, i + 1);
2025
+ });
2026
+ for (const index of change.table.indexes) addIndex(change.table.name, index);
2027
+ continue;
2028
+ }
2029
+ if (change.kind === "DROP_TABLE") {
2030
+ for (const name of change.foreignKeyNames) dropFk.set(`${change.table}\0${name}`, `alter table ${table(change.table)} drop constraint ${q(name)}`);
2031
+ body.push(`drop table ${table(change.table)}`);
2032
+ continue;
2033
+ }
2034
+ const before = context?.from.tables.find((t) => t.name === change.table);
2035
+ const after = context?.to.tables.find((t) => t.name === change.table);
2036
+ for (const c of change.constraints) if (c.kind === "DROP_CONSTRAINT") removeConstraint(change.table, c.constraint);
2037
+ else addConstraint(change.table, c.constraint, (after?.constraints.indexOf(c.constraint) ?? change.constraints.indexOf(c)) + 1);
2038
+ for (const idx of change.indexes) if (idx.kind === "DROP_INDEX") removeIndex(change.table, idx.index);
2039
+ else addIndex(change.table, idx.index);
2040
+ for (const col of change.columns) {
2041
+ const target = table(change.table);
2042
+ if (col.kind === "ADD_COLUMN") {
2043
+ body.push(`alter table ${target} add ${this.dialect === "oracle" ? `(${this.column(col.column)})` : this.column(col.column)}`);
2044
+ continue;
2045
+ }
2046
+ const old = before?.columns.find((c) => c.name === col.column);
2047
+ if (!old) throw new Error(`${this.dialect} 修改 ${change.table}.${col.column} 需要 DdlContext 中的原始列定义`);
2048
+ if (this.dialect === "mssql" && old.defaultConstraint && (col.kind === "DROP_COLUMN" || col.default !== void 0 || col.type !== void 0)) dropKeys.set(`${change.table}\0default:${old.name}`, `alter table ${target} drop constraint ${q(old.defaultConstraint)}`);
2049
+ if (col.kind === "DROP_COLUMN") {
2050
+ body.push(`alter table ${target} drop column ${q(col.column)}`);
2051
+ continue;
2052
+ }
2053
+ if (col.autoIncrement !== void 0 && col.autoIncrement !== old.autoIncrement) throw new Error("修改 identity 策略需要手工迁移");
2054
+ if (this.dialect === "mssql") {
2055
+ if (col.type !== void 0 || col.nullable !== void 0) body.push(`alter table ${target} alter column ${q(col.column)} ${col.type ?? old.type}${/^(n?varchar|n?char|n?text)\b/i.test(col.type ?? old.type) && old.collation ? ` collate ${collationName(old.collation)}` : ""} ${col.nullable ?? old.nullable ? "null" : "not null"}`);
2056
+ const defaultValue = col.default === void 0 ? old.default : col.default || void 0;
2057
+ if (defaultValue !== void 0 && (col.default !== void 0 || col.type !== void 0)) body.push(`alter table ${target} add default ${defaultValue} for ${q(col.column)}`);
2058
+ } else {
2059
+ const parts = [q(col.column)];
2060
+ if (col.type !== void 0) parts.push(col.type);
2061
+ if (col.default !== void 0) parts.push(`default ${col.default || "null"}`);
2062
+ if (col.nullable !== void 0) parts.push(col.nullable ? "null" : "not null");
2063
+ if (parts.length > 1) body.push(`alter table ${target} modify (${parts.join(" ")})`);
2064
+ }
2065
+ }
2066
+ }
2067
+ return [
2068
+ ...dropFk.values(),
2069
+ ...dropKeys.values(),
2070
+ ...body,
2071
+ ...addKeys.values(),
2072
+ ...addFk.values()
2073
+ ];
2074
+ }
2075
+ createStatements(schema) {
2076
+ return this.statements({
2077
+ changes: schema.tables.map((table) => ({
2078
+ kind: "CREATE_TABLE",
2079
+ table
2080
+ })),
2081
+ destructive: []
2082
+ });
2083
+ }
2084
+ column(c) {
2085
+ const identity = c.autoIncrement ? this.dialect === "mssql" ? " identity(1,1)" : " generated by default as identity" : "";
2086
+ return `${this.sql.identifier(c.name)} ${c.type}${identity}${c.default !== void 0 && c.default !== "" ? ` default ${c.default}` : ""}${c.nullable ? " null" : " not null"}`;
2087
+ }
2088
+ createTable(table) {
2089
+ const parts = table.columns.map((c) => this.column(c));
2090
+ table.constraints.forEach((c, i) => {
2091
+ if (c.kind !== "FOREIGN_KEY") parts.push(this.constraint(table.name, c, i + 1));
2092
+ });
2093
+ return `create table ${this.sql.table(table.name)} (\n ${parts.join(",\n ")}\n)`;
2094
+ }
2095
+ constraint(table, c, sequence) {
2096
+ const q = (v) => this.sql.identifier(v);
2097
+ const prefix = `constraint ${q(c.name ?? this.sql.name(constraintName(table, c, sequence)))}`;
2098
+ switch (c.kind) {
2099
+ case "PRIMARY_KEY": return `${prefix} primary key (${c.columns.map(q).join(", ")})`;
2100
+ case "UNIQUE": return `${prefix} unique (${c.columns.map(q).join(", ")})`;
2101
+ case "CHECK": return `${prefix} check (${c.expression})`;
2102
+ case "FOREIGN_KEY": {
2103
+ if (c.deferrable) throw new Error("当前迁移尚不支持延迟外键约束");
2104
+ if (this.dialect === "oracle" && c.onDelete === "SET_DEFAULT") throw new Error("Oracle 不支持 ON DELETE SET DEFAULT");
2105
+ const action = ["NO_ACTION", "RESTRICT"].includes(c.onDelete) ? "" : ` on delete ${c.onDelete.replaceAll("_", " ")}`;
2106
+ return `${prefix} foreign key (${c.columns.map(q).join(", ")}) references ${this.sql.table(c.referencedTable)} (${c.referencedColumns.map(q).join(", ")})${action}`;
2107
+ }
2108
+ }
2109
+ }
2110
+ index(table, idx) {
2111
+ if (idx.predicate && this.dialect === "oracle") throw new Error("Oracle 不支持部分索引");
2112
+ return `create ${idx.unique ? "unique " : ""}index ${this.dialect === "mssql" ? this.sql.identifier(idx.name) : this.sql.table(idx.name)} on ${this.sql.table(table)} (${idx.columns.map((c) => this.sql.identifier(c)).join(", ")})${idx.predicate ? ` where ${idx.predicate}` : ""}`;
2113
+ }
2114
+ };
2115
+ function collationName(value) {
2116
+ if (!/^[A-Za-z0-9_]+$/.test(value)) throw new Error("不支持的 SQL Server collation 名称");
2117
+ return value;
2118
+ }
2119
+ //#endregion
2120
+ //#region src/ddl/sqlserver.ts
2121
+ var SqlServerDdlGenerator = class extends ServerDdlGenerator {
2122
+ constructor(schema = "dbo") {
2123
+ super("mssql", schema);
2124
+ }
2125
+ };
2126
+ //#endregion
2127
+ //#region src/executor/sqlserver.ts
2128
+ /**
2129
+ * Transactional DDL and session-owned application locks use the same pinned connection.
2130
+ * @see https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql
2131
+ */
2132
+ var SqlServerSqlExecutor = class {
2133
+ _session;
2134
+ _schema;
2135
+ _lockTimeoutMs;
2136
+ _lockHeld = false;
2137
+ constructor(_session, _schema = "dbo", _lockTimeoutMs = 1e4) {
2138
+ this._session = _session;
2139
+ this._schema = _schema;
2140
+ this._lockTimeoutMs = _lockTimeoutMs;
2141
+ }
2142
+ async query(sql, params = []) {
2143
+ const request = this._session.request();
2144
+ params.forEach((value, index) => request.input(`p${index + 1}`, value));
2145
+ return { rows: (await request.query(sql)).recordset ?? [] };
2146
+ }
2147
+ async executeStatements(statements, complete) {
2148
+ await this._session.request().batch("begin transaction");
2149
+ try {
2150
+ for (const sql of statements) await this._session.request().batch(sql);
2151
+ await complete?.(this);
2152
+ await this._session.request().batch("commit transaction");
2153
+ } catch (e) {
2154
+ try {
2155
+ await this._session.request().batch("if @@trancount > 0 rollback transaction");
2156
+ } catch {
2157
+ throw new Error(`SQL Server 执行失败且无法确认回滚:${e.message}`);
2158
+ }
2159
+ throw new Error(`SQL Server 语句执行失败(事务已回滚):${e.message}`);
2160
+ }
2161
+ }
2162
+ async acquireMigrationLock(_key) {
2163
+ if (this._lockHeld) throw new Error("当前 SQL Server 执行器已持有迁移锁");
2164
+ const name = `ts-grm:${createHash("sha256").update(this._schema).digest("hex")}`;
2165
+ const { rows } = await this.query(`declare @r int;
2166
+ exec @r = sys.sp_getapplock @Resource=@p1, @LockMode='Exclusive', @LockOwner='Session', @LockTimeout=@p2;
2167
+ select @r as result`, [name, this._lockTimeoutMs]);
2168
+ if (rows[0]?.result == null || Number(rows[0].result) < 0) throw new Error("获取 SQL Server 迁移锁失败");
2169
+ this._lockHeld = true;
2170
+ return async () => {
2171
+ if (!this._lockHeld) return;
2172
+ await this.query("exec sys.sp_releaseapplock @Resource=@p1, @LockOwner='Session'", [name]);
2173
+ this._lockHeld = false;
2174
+ };
2175
+ }
2176
+ };
2177
+ //#endregion
2178
+ //#region src/executor/oracle.ts
2179
+ /** @see https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/DBMS_LOCK.html */
2180
+ var OracleSqlExecutor = class {
2181
+ session;
2182
+ schema;
2183
+ lockTimeout;
2184
+ locked = false;
2185
+ constructor(session, schema, lockTimeout = 10) {
2186
+ this.session = session;
2187
+ this.schema = schema;
2188
+ this.lockTimeout = lockTimeout;
2189
+ }
2190
+ async query(sql, params = []) {
2191
+ return { rows: (await this.session.execute(sql, Object.fromEntries(params.map((value, index) => [String(index + 1), value])), {
2192
+ autoCommit: true,
2193
+ outFormat: 4002
2194
+ })).rows ?? [] };
2195
+ }
2196
+ async executeStatements(statements, complete) {
2197
+ const parsed = statements.flatMap(splitOracleSql);
2198
+ try {
2199
+ for (const sql of parsed) await this.query(sql);
2200
+ await complete?.(this);
2201
+ } catch (e) {
2202
+ throw new Error(`Oracle 语句执行失败:${e.message}。DDL 隐式提交,之前的语句可能已生效;请检查数据库后使用 resolve 修正状态。`);
2203
+ }
2204
+ }
2205
+ async acquireMigrationLock(_key) {
2206
+ if (this.locked) throw new Error("当前 Oracle 执行器已持有迁移锁");
2207
+ const id = createHash("sha256").update(`ts-grm:${this.schema}`).digest().readUInt32BE(0) % 1073741824;
2208
+ await this.query(`declare result integer; begin result := dbms_lock.request(${id}, 6, ${this.lockTimeout}, false);
2209
+ if result <> 0 then raise_application_error(-20001, 'Migration lock failed: ' || result); end if; end;`);
2210
+ this.locked = true;
2211
+ return async () => {
2212
+ if (!this.locked) return;
2213
+ await this.query(`declare result integer; begin result := dbms_lock.release(${id});
2214
+ if result <> 0 then raise_application_error(-20002, 'Migration unlock failed: ' || result); end if; end;`);
2215
+ this.locked = false;
2216
+ };
2217
+ }
2218
+ };
2219
+ /**
2220
+ * SQL-only migration files: semicolons in strings, quoted identifiers and comments are data.
2221
+ * PL/SQL and SQL*Plus commands are explicitly rejected before execution; no naive split(';').
2222
+ * @see https://node-oracledb.readthedocs.io/en/latest/user_guide/sql_execution.html
2223
+ */
2224
+ function splitOracleSql(source) {
2225
+ const statements = [];
2226
+ let current = "", quote = "", comment = "", alternativeEnd = "";
2227
+ const finish = () => {
2228
+ const sql = current.trim();
2229
+ current = "";
2230
+ if (!sql) return;
2231
+ if (/^(begin|declare|create\s+(or\s+replace\s+)?(procedure|function|package|trigger|type)|\/|set\s+|prompt\s+|exec(?:ute)?\s+)/i.test(sql)) throw new Error("Oracle 迁移文件当前只支持 SQL,不支持 PL/SQL 或 SQL*Plus 命令");
2232
+ statements.push(sql);
2233
+ };
2234
+ for (let i = 0; i < source.length; i++) {
2235
+ const c = source[i], next = source[i + 1];
2236
+ if (comment === "line") {
2237
+ if (c === "\n") {
2238
+ comment = "";
2239
+ current += "\n";
2240
+ }
2241
+ continue;
2242
+ }
2243
+ if (comment === "block") {
2244
+ if (c === "*" && next === "/") {
2245
+ comment = "";
2246
+ i++;
2247
+ current += " ";
2248
+ }
2249
+ continue;
2250
+ }
2251
+ if (alternativeEnd) {
2252
+ current += c;
2253
+ if (c === alternativeEnd && next === "'") {
2254
+ current += "'";
2255
+ i++;
2256
+ alternativeEnd = "";
2257
+ }
2258
+ continue;
2259
+ }
2260
+ if (quote) {
2261
+ current += c;
2262
+ if (c === quote) {
2263
+ if (next === quote) {
2264
+ current += next;
2265
+ i++;
2266
+ } else quote = "";
2267
+ }
2268
+ continue;
2269
+ }
2270
+ if ((c === "q" || c === "Q") && next === "'" && source[i + 2]) {
2271
+ const delimiter = source[i + 2];
2272
+ alternativeEnd = {
2273
+ "[": "]",
2274
+ "{": "}",
2275
+ "(": ")",
2276
+ "<": ">"
2277
+ }[delimiter] ?? delimiter;
2278
+ current += source.slice(i, i + 3);
2279
+ i += 2;
2280
+ continue;
2281
+ }
2282
+ if (c === "-" && next === "-") {
2283
+ comment = "line";
2284
+ i++;
2285
+ continue;
2286
+ }
2287
+ if (c === "/" && next === "*") {
2288
+ comment = "block";
2289
+ i++;
2290
+ continue;
2291
+ }
2292
+ if (c === "'" || c === "\"") {
2293
+ quote = c;
2294
+ current += c;
2295
+ continue;
2296
+ }
2297
+ if (c === ";") finish();
2298
+ else current += c;
2299
+ }
2300
+ if (quote || alternativeEnd || comment === "block") throw new Error("Oracle SQL 文件含未结束的字符串或注释");
2301
+ finish();
2302
+ return statements;
2303
+ }
2304
+ //#endregion
2305
+ //#region src/server/connections.ts
2306
+ /**
2307
+ * mssql exposes acquire/release for pinning connections. Keep this boundary in one place.
2308
+ * A Request's parent delegates acquisition to the reserved physical session, never the pool.
2309
+ * @see https://github.com/tediousjs/node-mssql/blob/master/lib/base/connection-pool.js
2310
+ * @see https://github.com/tediousjs/node-mssql/blob/master/lib/base/transaction.js
2311
+ */
2312
+ async function openSqlServer(database, schema) {
2313
+ let runtime;
2314
+ try {
2315
+ runtime = await import("mssql");
2316
+ } catch {
2317
+ throw new Error("mssql 方言需要 mssql 依赖,请安装:yarn add mssql");
2318
+ }
2319
+ const pool = new runtime.ConnectionPool(database.connectionString ?? {
2320
+ server: database.host ?? "localhost",
2321
+ port: database.port ?? 1433,
2322
+ user: database.user,
2323
+ password: database.password,
2324
+ database: database.database,
2325
+ options: {
2326
+ encrypt: database.encrypt ?? true,
2327
+ trustServerCertificate: database.trustServerCertificate ?? false
2328
+ },
2329
+ connectionTimeout: 15e3,
2330
+ requestTimeout: 3e4
2331
+ });
2332
+ pool.on("error", () => {});
2333
+ const pinnedPool = pool;
2334
+ await pool.connect();
2335
+ let connection;
2336
+ try {
2337
+ connection = await pinnedPool.acquire(pool);
2338
+ } catch (e) {
2339
+ await pool.close();
2340
+ throw e;
2341
+ }
2342
+ const parent = {
2343
+ config: pinnedPool.config,
2344
+ connected: true,
2345
+ acquire(_request, callback) {
2346
+ callback(null, connection, pinnedPool.config);
2347
+ },
2348
+ release() {}
2349
+ };
2350
+ const session = { request: () => new runtime.Request(parent) };
2351
+ const executor = new SqlServerSqlExecutor(session, schema);
2352
+ const close = async () => {
2353
+ pinnedPool.release(connection);
2354
+ await pool.close();
2355
+ };
2356
+ try {
2357
+ const version = await executor.query("select cast(serverproperty('ProductMajorVersion') as int) as version");
2358
+ if (Number(version.rows[0]?.version) < 13) throw new Error("mssql 方言需要 SQL Server 2016+");
2359
+ const { rows } = await executor.query("select schema_id(@p1) as id", [schema]);
2360
+ if (rows[0]?.id == null) {
2361
+ const sql = new ServerSql("mssql", schema);
2362
+ await executor.query(`exec(${sql.literal(`create schema ${sql.identifier(schema)}`)})`);
2363
+ }
2364
+ const canonical = await executor.query("select name from sys.schemas where schema_id=schema_id(@p1)", [schema]);
2365
+ const canonicalSchema = String(canonical.rows[0]?.name ?? schema);
2366
+ return {
2367
+ executor: new SqlServerSqlExecutor(session, canonicalSchema),
2368
+ schema: canonicalSchema,
2369
+ close
2370
+ };
2371
+ } catch (e) {
2372
+ await close();
2373
+ throw e;
2374
+ }
2375
+ }
2376
+ async function openOracle(database, requestedSchema) {
2377
+ let runtime;
2378
+ try {
2379
+ runtime = (await import("oracledb")).default;
2380
+ } catch {
2381
+ throw new Error("oracle 方言需要 oracledb 依赖,请安装:yarn add oracledb");
2382
+ }
2383
+ const connectString = database.connectionString ?? `${database.host ?? "localhost"}:${database.port ?? 1521}/${database.database ?? "FREEPDB1"}`;
2384
+ const connection = await runtime.getConnection({
2385
+ user: database.user,
2386
+ password: database.password,
2387
+ connectString
2388
+ });
2389
+ connection.callTimeout = 3e4;
2390
+ const close = async () => {
2391
+ await connection.close();
2392
+ };
2393
+ try {
2394
+ if (Number(connection.oracleServerVersionString.split(".")[0]) < 19) throw new Error("oracle 方言需要 Oracle 19c+");
2395
+ const who = await connection.execute("select sys_context('USERENV', 'CURRENT_SCHEMA') as name from dual", [], { outFormat: runtime.OUT_FORMAT_OBJECT });
2396
+ const schema = requestedSchema ?? who.rows?.[0]?.NAME;
2397
+ if (!schema) throw new Error("无法确定 Oracle schema");
2398
+ const sql = new ServerSql("oracle", schema);
2399
+ await connection.execute(`alter session set current_schema=${sql.identifier(schema)}`);
2400
+ await connection.execute("alter session set nls_length_semantics=BYTE");
2401
+ return {
2402
+ executor: new OracleSqlExecutor({ execute: async (statement, binds, options) => {
2403
+ return await connection.execute(statement, binds, {
2404
+ ...options,
2405
+ fetchInfo: {
2406
+ error: { type: runtime.STRING },
2407
+ logs: { type: runtime.STRING }
2408
+ }
2409
+ });
2410
+ } }, schema),
2411
+ schema,
2412
+ close
2413
+ };
2414
+ } catch (e) {
2415
+ await close();
2416
+ throw e;
2417
+ }
2418
+ }
2419
+ //#endregion
2420
+ //#region src/ddl/oracle.ts
2421
+ var OracleDdlGenerator = class extends ServerDdlGenerator {
2422
+ constructor(schema) {
2423
+ super("oracle", schema);
2424
+ }
2425
+ };
2426
+ //#endregion
2427
+ //#region src/introspector/oracle.ts
2428
+ /** @see https://docs.oracle.com/en/database/oracle/oracle-database/23/refrn/ALL_TAB_COLUMNS.html */
2429
+ var OracleIntrospector = class {
2430
+ options;
2431
+ dialect = "oracle";
2432
+ constructor(options) {
2433
+ this.options = options;
2434
+ }
2435
+ async introspect() {
2436
+ const query = async (sql) => (await this.options.query.query(sql, [this.options.schema])).rows;
2437
+ try {
2438
+ const tables = await query("select table_name, temporary, nested, secondary, iot_type from all_tables where owner=:1 and table_name not like 'BIN$%' order by table_name");
2439
+ const columns = await query("select table_name,column_name,data_type,data_length,data_precision,data_scale,char_length,char_used,nullable,data_default,identity_column,virtual_column,hidden_column,column_id from all_tab_cols where owner=:1 and table_name not like 'BIN$%' order by table_name,column_id");
2440
+ const constraints = await query(`select c.table_name,c.constraint_name,c.constraint_type,c.search_condition_vc,c.status,c.validated,c.deferrable,c.delete_rule,c.generated,c.index_name,
2441
+ cc.column_name,cc.position,rc.owner as ref_owner,rc.table_name as ref_table,rcc.column_name as ref_column
2442
+ from all_constraints c left join all_cons_columns cc on cc.owner=c.owner and cc.constraint_name=c.constraint_name
2443
+ left join all_constraints rc on rc.owner=c.r_owner and rc.constraint_name=c.r_constraint_name
2444
+ left join all_cons_columns rcc on rcc.owner=rc.owner and rcc.constraint_name=rc.constraint_name and rcc.position=cc.position
2445
+ where c.owner=:1 order by c.table_name,c.constraint_name,cc.position`);
2446
+ const indexes = await query(`select i.table_name,i.index_name,i.uniqueness,i.index_type,i.status,c.column_name,c.column_position,c.descend
2447
+ from all_indexes i join all_ind_columns c on c.index_owner=i.owner and c.index_name=i.index_name
2448
+ where i.table_owner=:1 order by i.table_name,i.index_name,c.column_position`);
2449
+ return { tables: tables.map((table) => {
2450
+ const name = stringValue(table.TABLE_NAME);
2451
+ if (table.TEMPORARY !== "N" || table.NESTED !== "NO" || table.SECONDARY !== "N" || table.IOT_TYPE != null) throw new Error(`Oracle 表 ${name} 使用临时、嵌套或组织索引结构,尚不支持`);
2452
+ const forTable = (rows) => rows.filter((r) => r.TABLE_NAME === name);
2453
+ const tableColumns = forTable(columns).map(column$1);
2454
+ const tableConstraints = [];
2455
+ const constraintIndexes = /* @__PURE__ */ new Set();
2456
+ for (const [constraintName, rows] of groupRows(forTable(constraints), "CONSTRAINT_NAME")) {
2457
+ const c = rows[0];
2458
+ if (c.STATUS !== "ENABLED" || c.VALIDATED !== "VALIDATED" || c.DEFERRABLE !== "NOT DEFERRABLE") throw new Error(`约束 ${constraintName} 未验证/启用或使用延迟检查,尚不支持`);
2459
+ const names = rows.map((r) => stringValue(r.COLUMN_NAME));
2460
+ switch (c.CONSTRAINT_TYPE) {
2461
+ case "P":
2462
+ case "U":
2463
+ constraintIndexes.add(stringValue(c.INDEX_NAME));
2464
+ tableConstraints.push({
2465
+ kind: c.CONSTRAINT_TYPE === "P" ? "PRIMARY_KEY" : "UNIQUE",
2466
+ name: constraintName,
2467
+ columns: names,
2468
+ implicit: void 0
2469
+ });
2470
+ break;
2471
+ case "R": {
2472
+ if (c.REF_OWNER !== this.options.schema) throw new Error(`外键 ${constraintName} 跨 schema,尚不支持`);
2473
+ const onDelete = c.DELETE_RULE === "CASCADE" ? "CASCADE" : c.DELETE_RULE === "SET NULL" ? "SET_NULL" : "NO_ACTION";
2474
+ tableConstraints.push({
2475
+ kind: "FOREIGN_KEY",
2476
+ name: constraintName,
2477
+ columns: names,
2478
+ referencedTable: stringValue(c.REF_TABLE),
2479
+ referencedColumns: rows.map((r) => stringValue(r.REF_COLUMN)),
2480
+ onDelete,
2481
+ cascade: onDelete === "CASCADE" ? "DELETE" : onDelete === "SET_NULL" ? "SET_NULL" : "NONE",
2482
+ deferrable: false,
2483
+ implicit: void 0
2484
+ });
2485
+ break;
2486
+ }
2487
+ case "C": {
2488
+ const expression = stringValue(c.SEARCH_CONDITION_VC);
2489
+ if (/^"(?:""|[^"])+" IS NOT NULL$/i.test(expression.trim()) && names.length === 1 && tableColumns.some((col) => col.name === names[0] && !col.nullable)) break;
2490
+ if (expression.length >= 4e3) throw new Error(`CHECK ${constraintName} 超出 catalog 表达式长度,不能安全读取`);
2491
+ tableConstraints.push({
2492
+ kind: "CHECK",
2493
+ name: constraintName,
2494
+ expression,
2495
+ comparisonExpression: normalizeServerExpression(expression),
2496
+ values: [],
2497
+ implicit: void 0
2498
+ });
2499
+ break;
2500
+ }
2501
+ default: throw new Error(`不支持的 Oracle 约束类型 ${stringValue(c.CONSTRAINT_TYPE)}`);
2502
+ }
2503
+ }
2504
+ const tableIndexes = [];
2505
+ for (const [indexName, rows] of groupRows(forTable(indexes), "INDEX_NAME")) {
2506
+ if (constraintIndexes.has(indexName)) continue;
2507
+ if (rows[0].INDEX_TYPE === "LOB") continue;
2508
+ if (rows.some((r) => r.INDEX_TYPE !== "NORMAL" || r.DESCEND !== "ASC" || r.STATUS !== "VALID")) throw new Error(`索引 ${indexName} 使用表达式、降序或特殊结构,尚不支持`);
2509
+ tableIndexes.push({
2510
+ name: indexName,
2511
+ columns: rows.map((r) => stringValue(r.COLUMN_NAME)),
2512
+ unique: rows[0].UNIQUENESS === "UNIQUE",
2513
+ predicate: void 0
2514
+ });
2515
+ }
2516
+ return {
2517
+ name,
2518
+ columns: tableColumns,
2519
+ constraints: tableConstraints,
2520
+ indexes: tableIndexes
2521
+ };
2522
+ }) };
2523
+ } catch (e) {
2524
+ throw new Error(`读取 Oracle 结构失败:${e.message}`);
2525
+ }
2526
+ }
2527
+ };
2528
+ function column$1(row) {
2529
+ if (row.VIRTUAL_COLUMN === "YES" || row.HIDDEN_COLUMN === "YES") throw new Error(`列 ${stringValue(row.COLUMN_NAME)} 为虚拟/隐藏列,尚不支持`);
2530
+ let type = stringValue(row.DATA_TYPE).toLowerCase();
2531
+ if (["varchar2", "char"].includes(type)) type += row.CHAR_USED === "C" ? `(${stringValue(row.CHAR_LENGTH)} char)` : `(${stringValue(row.DATA_LENGTH)})`;
2532
+ else if (["nvarchar2", "nchar"].includes(type)) type += `(${stringValue(row.CHAR_LENGTH)})`;
2533
+ else if (type === "raw") type += `(${stringValue(row.DATA_LENGTH)})`;
2534
+ else if (type === "number" && row.DATA_PRECISION != null) type += `(${stringValue(row.DATA_PRECISION)},${stringValue(row.DATA_SCALE ?? 0)})`;
2535
+ else if (type === "float" && row.DATA_PRECISION != null) type += `(${stringValue(row.DATA_PRECISION)})`;
2536
+ const identity = row.IDENTITY_COLUMN === "YES";
2537
+ const defaultValue = row.DATA_DEFAULT == null ? void 0 : stringValue(row.DATA_DEFAULT).trim();
2538
+ return {
2539
+ name: stringValue(row.COLUMN_NAME),
2540
+ type: normalizeServerType(type, "oracle"),
2541
+ nullable: row.NULLABLE === "Y",
2542
+ length: void 0,
2543
+ default: identity || defaultValue?.toLowerCase() === "null" ? void 0 : defaultValue,
2544
+ autoIncrement: identity,
2545
+ ordinal: Number(row.COLUMN_ID),
2546
+ comment: void 0
2547
+ };
2548
+ }
2549
+ //#endregion
2550
+ //#region src/introspector/sqlserver.ts
2551
+ /** @see https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/catalog-views-transact-sql */
2552
+ var SqlServerIntrospector = class {
2553
+ _options;
2554
+ dialect = "mssql";
2555
+ constructor(_options) {
2556
+ this._options = _options;
2557
+ }
2558
+ async introspect() {
2559
+ const schema = this._options.schema ?? "dbo";
2560
+ const query = async (sql) => (await this._options.query.query(sql, [schema])).rows;
2561
+ try {
2562
+ const tables = await query(`select t.name, t.temporal_type, t.is_memory_optimized from sys.tables t
2563
+ join sys.schemas s on s.schema_id=t.schema_id where s.name=@p1 and t.is_ms_shipped=0 order by t.name`);
2564
+ const columns = await query(`select t.name as table_name, c.name, ty.name as type_name, c.max_length, c.precision, c.scale,
2565
+ c.is_nullable, c.is_identity, c.is_computed, c.is_sparse, c.generated_always_type, c.is_hidden,
2566
+ c.column_id, c.collation_name, dc.name as default_name, dc.definition as default_value, ty.is_user_defined
2567
+ from sys.tables t join sys.schemas s on s.schema_id=t.schema_id
2568
+ join sys.columns c on c.object_id=t.object_id join sys.types ty on c.user_type_id=ty.user_type_id
2569
+ left join sys.default_constraints dc on c.default_object_id=dc.object_id
2570
+ where s.name=@p1 order by t.name,c.column_id`);
2571
+ const keys = await query(`select t.name as table_name,k.name,k.type,i.type as index_type,c.name as column_name,ic.key_ordinal
2572
+ from sys.key_constraints k join sys.tables t on t.object_id=k.parent_object_id join sys.schemas s on s.schema_id=t.schema_id
2573
+ join sys.indexes i on i.object_id=t.object_id and i.index_id=k.unique_index_id
2574
+ join sys.index_columns ic on ic.object_id=t.object_id and ic.index_id=k.unique_index_id
2575
+ join sys.columns c on c.object_id=t.object_id and c.column_id=ic.column_id
2576
+ where s.name=@p1 order by t.name,k.name,ic.key_ordinal`);
2577
+ const fks = await query(`select t.name as table_name,fk.name,c.name as column_name,rt.name as ref_table,
2578
+ rs.name as ref_schema,rc.name as ref_column,fk.delete_referential_action_desc as delete_rule,
2579
+ fk.update_referential_action_desc as update_rule,fk.is_disabled,fk.is_not_trusted
2580
+ from sys.foreign_keys fk join sys.tables t on t.object_id=fk.parent_object_id join sys.schemas s on s.schema_id=t.schema_id
2581
+ join sys.foreign_key_columns fc on fc.constraint_object_id=fk.object_id
2582
+ join sys.columns c on c.object_id=t.object_id and c.column_id=fc.parent_column_id
2583
+ join sys.tables rt on rt.object_id=fk.referenced_object_id join sys.schemas rs on rs.schema_id=rt.schema_id
2584
+ join sys.columns rc on rc.object_id=rt.object_id and rc.column_id=fc.referenced_column_id
2585
+ where s.name=@p1 order by t.name,fk.name,fc.constraint_column_id`);
2586
+ const checks = await query(`select t.name as table_name,c.name,c.definition,c.is_disabled,c.is_not_trusted
2587
+ from sys.check_constraints c join sys.tables t on t.object_id=c.parent_object_id
2588
+ join sys.schemas s on s.schema_id=t.schema_id where s.name=@p1`);
2589
+ const indexes = await query(`select t.name as table_name,i.name,i.type,i.is_unique,i.is_disabled,i.filter_definition,
2590
+ ic.is_descending_key,ic.is_included_column,ic.key_ordinal,c.name as column_name
2591
+ from sys.indexes i join sys.tables t on t.object_id=i.object_id join sys.schemas s on s.schema_id=t.schema_id
2592
+ join sys.index_columns ic on ic.object_id=t.object_id and ic.index_id=i.index_id
2593
+ join sys.columns c on c.object_id=t.object_id and c.column_id=ic.column_id
2594
+ where s.name=@p1 and i.is_primary_key=0 and i.is_unique_constraint=0 and i.is_hypothetical=0
2595
+ order by t.name,i.name,ic.key_ordinal`);
2596
+ return { tables: tables.map((t) => {
2597
+ const name = stringValue(t.name);
2598
+ if (Number(t.temporal_type) !== 0 || t.is_memory_optimized) throw new Error(`表 ${name} 为 temporal 或 memory-optimized,尚不支持`);
2599
+ const forTable = (rows) => rows.filter((r) => r.table_name === name);
2600
+ const constraints = [];
2601
+ for (const [name, rows] of groupRows(forTable(keys), "name")) {
2602
+ const primary = rows[0].type === "PK";
2603
+ if (Number(rows[0].index_type) !== (primary ? 1 : 2)) throw new Error(`约束 ${name} 使用自定义聚集布局,尚不支持`);
2604
+ constraints.push({
2605
+ kind: primary ? "PRIMARY_KEY" : "UNIQUE",
2606
+ name,
2607
+ columns: rows.map((r) => stringValue(r.column_name)),
2608
+ implicit: void 0
2609
+ });
2610
+ }
2611
+ for (const [name, rows] of groupRows(forTable(fks), "name")) {
2612
+ const first = rows[0];
2613
+ if (first.ref_schema !== schema || first.update_rule !== "NO_ACTION" || first.is_disabled || first.is_not_trusted) throw new Error(`外键 ${name} 跨 schema、含 ON UPDATE 动作或未启用/验证,尚不支持`);
2614
+ const onDelete = stringValue(first.delete_rule);
2615
+ constraints.push({
2616
+ kind: "FOREIGN_KEY",
2617
+ name,
2618
+ columns: rows.map((r) => stringValue(r.column_name)),
2619
+ referencedTable: stringValue(first.ref_table),
2620
+ referencedColumns: rows.map((r) => stringValue(r.ref_column)),
2621
+ onDelete,
2622
+ cascade: onDelete === "CASCADE" ? "DELETE" : onDelete === "SET_NULL" ? "SET_NULL" : "NONE",
2623
+ deferrable: false,
2624
+ implicit: void 0
2625
+ });
2626
+ }
2627
+ for (const c of forTable(checks)) {
2628
+ if (c.is_disabled || c.is_not_trusted) throw new Error(`CHECK ${stringValue(c.name)} 未启用或未验证`);
2629
+ constraints.push({
2630
+ kind: "CHECK",
2631
+ name: stringValue(c.name),
2632
+ expression: stringValue(c.definition),
2633
+ comparisonExpression: normalizeServerExpression(stringValue(c.definition)),
2634
+ values: [],
2635
+ implicit: void 0
2636
+ });
2637
+ }
2638
+ const tableIndexes = [];
2639
+ for (const [indexName, rows] of groupRows(forTable(indexes), "name")) {
2640
+ if (rows.some((r) => Number(r.type) !== 2 || r.is_disabled || r.is_descending_key || r.is_included_column)) throw new Error(`索引 ${indexName} 使用不支持的聚集、降序、INCLUDE 或禁用属性`);
2641
+ tableIndexes.push({
2642
+ name: indexName,
2643
+ columns: rows.map((r) => stringValue(r.column_name)),
2644
+ unique: Boolean(rows[0].is_unique),
2645
+ predicate: rows[0].filter_definition == null ? void 0 : stringValue(rows[0].filter_definition)
2646
+ });
2647
+ }
2648
+ return {
2649
+ name,
2650
+ columns: forTable(columns).map(column),
2651
+ constraints,
2652
+ indexes: tableIndexes
2653
+ };
2654
+ }) };
2655
+ } catch (e) {
2656
+ throw new Error(`读取 SQL Server 结构失败:${e.message}`);
2657
+ }
2658
+ }
2659
+ };
2660
+ function column(row) {
2661
+ if (row.is_computed || row.is_sparse || row.is_hidden || Number(row.generated_always_type) !== 0 || row.is_user_defined) throw new Error(`列 ${stringValue(row.name)} 使用不支持的生成列、稀疏列、隐藏列或用户类型`);
2662
+ let type = stringValue(row.type_name);
2663
+ if ([
2664
+ "nvarchar",
2665
+ "varchar",
2666
+ "varbinary",
2667
+ "char",
2668
+ "nchar",
2669
+ "binary"
2670
+ ].includes(type)) {
2671
+ const length = Number(row.max_length);
2672
+ type += `(${length === -1 ? "max" : type.startsWith("n") ? length / 2 : length})`;
2673
+ } else if (["decimal", "numeric"].includes(type)) type += `(${stringValue(row.precision)},${stringValue(row.scale)})`;
2674
+ else if ([
2675
+ "datetime2",
2676
+ "datetimeoffset",
2677
+ "time"
2678
+ ].includes(type)) type += `(${stringValue(row.scale)})`;
2679
+ if (["timestamp", "rowversion"].includes(type)) throw new Error(`列 ${stringValue(row.name)} 为 rowversion,尚不支持`);
2680
+ return {
2681
+ name: stringValue(row.name),
2682
+ type: normalizeServerType(type, "mssql"),
2683
+ nullable: Boolean(row.is_nullable),
2684
+ length: void 0,
2685
+ default: row.default_value == null ? void 0 : stringValue(row.default_value),
2686
+ defaultConstraint: row.default_name == null ? void 0 : stringValue(row.default_name),
2687
+ collation: row.collation_name == null ? void 0 : stringValue(row.collation_name),
2688
+ autoIncrement: Boolean(row.is_identity),
2689
+ ordinal: Number(row.column_id),
2690
+ comment: void 0
2691
+ };
2692
+ }
2693
+ //#endregion
2694
+ //#region src/introspector/mysql.ts
2695
+ const str = (value) => String(value ?? "");
2696
+ /**
2697
+ * MySQL 8.0.16+ / InnoDB catalog reader. Catalog names are bound, never interpolated.
2698
+ * @see https://dev.mysql.com/doc/refman/8.4/en/information-schema.html
2699
+ */
2700
+ var MysqlIntrospector = class {
2701
+ _options;
2702
+ dialect = "mysql";
2703
+ constructor(_options) {
2704
+ this._options = _options;
2705
+ }
2706
+ async introspect() {
2707
+ const query = async (sql) => (await this._options.query.query(sql)).rows;
2708
+ try {
2709
+ const tables = await query("select TABLE_NAME as name, ENGINE as engine from information_schema.TABLES where TABLE_SCHEMA = database() and TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME");
2710
+ const columns = await query("select * from information_schema.COLUMNS where TABLE_SCHEMA = database() order by TABLE_NAME, ORDINAL_POSITION");
2711
+ const keys = await query(`select tc.TABLE_NAME, tc.CONSTRAINT_NAME, tc.CONSTRAINT_TYPE, k.COLUMN_NAME,
2712
+ k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME, k.REFERENCED_TABLE_SCHEMA,
2713
+ rc.DELETE_RULE, rc.UPDATE_RULE, cc.CHECK_CLAUSE, tc.ENFORCED
2714
+ from information_schema.TABLE_CONSTRAINTS tc
2715
+ left join information_schema.KEY_COLUMN_USAGE k on k.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
2716
+ and k.TABLE_NAME = tc.TABLE_NAME and k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
2717
+ left join information_schema.REFERENTIAL_CONSTRAINTS rc on rc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
2718
+ and rc.TABLE_NAME = tc.TABLE_NAME and rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
2719
+ left join information_schema.CHECK_CONSTRAINTS cc on cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
2720
+ and cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
2721
+ where tc.CONSTRAINT_SCHEMA = database() order by tc.TABLE_NAME, tc.CONSTRAINT_NAME, k.ORDINAL_POSITION`);
2722
+ const indexes = await query("select * from information_schema.STATISTICS where TABLE_SCHEMA = database() order by TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX");
2723
+ const db = str((await query("select database() as name"))[0]?.name);
2724
+ return { tables: tables.map((table) => {
2725
+ const name = str(table.name);
2726
+ if (table.engine !== "InnoDB") throw new Error(`表 ${name} 的引擎 ${str(table.engine)} 尚不支持,仅支持 InnoDB`);
2727
+ const constraints = this._constraints(keys.filter((r) => r.TABLE_NAME === name), db);
2728
+ return {
2729
+ name,
2730
+ columns: columns.filter((r) => r.TABLE_NAME === name).map((r) => this._column(r)),
2731
+ constraints,
2732
+ indexes: this._indexes(indexes.filter((r) => r.TABLE_NAME === name), constraints)
2733
+ };
2734
+ }) };
2735
+ } catch (e) {
2736
+ throw new Error(`读取 MySQL 结构失败:${e.message}`);
2737
+ }
2738
+ }
2739
+ _column(row) {
2740
+ const extra = str(row.EXTRA);
2741
+ if (str(row.GENERATION_EXPRESSION) || /invisible/i.test(extra)) throw new Error(`列 ${str(row.TABLE_NAME)}.${str(row.COLUMN_NAME)} 为生成列或隐藏列,尚不支持迁移`);
2742
+ const rawDefault = row.COLUMN_DEFAULT;
2743
+ let defaultValue;
2744
+ if (rawDefault != null) {
2745
+ if (/DEFAULT_GENERATED/i.test(extra)) {
2746
+ const expression = str(rawDefault);
2747
+ defaultValue = /^current_timestamp(?:\(\d*\))?$/i.test(expression) ? expression : `(${expression})`;
2748
+ } else defaultValue = quoteMysqlLiteral(str(rawDefault));
2749
+ }
2750
+ return {
2751
+ name: str(row.COLUMN_NAME),
2752
+ type: normalizeMysqlType(str(row.COLUMN_TYPE)),
2753
+ nullable: row.IS_NULLABLE === "YES",
2754
+ length: void 0,
2755
+ default: defaultValue,
2756
+ autoIncrement: /auto_increment/i.test(extra),
2757
+ ordinal: Number(row.ORDINAL_POSITION),
2758
+ comment: str(row.COLUMN_COMMENT) || void 0,
2759
+ mysql: {
2760
+ charset: row.CHARACTER_SET_NAME == null ? void 0 : str(row.CHARACTER_SET_NAME),
2761
+ collation: row.COLLATION_NAME == null ? void 0 : str(row.COLLATION_NAME),
2762
+ onUpdate: extra.match(/on update (current_timestamp(?:\(\d*\))?)/i)?.[1]
2763
+ }
2764
+ };
2765
+ }
2766
+ _constraints(rows, database) {
2767
+ return [...group(rows, "CONSTRAINT_NAME").entries()].map(([name, entries]) => {
2768
+ const row = entries[0];
2769
+ const columns = entries.map((r) => str(r.COLUMN_NAME));
2770
+ switch (row.CONSTRAINT_TYPE) {
2771
+ case "PRIMARY KEY": return {
2772
+ kind: "PRIMARY_KEY",
2773
+ name,
2774
+ columns,
2775
+ implicit: void 0
2776
+ };
2777
+ case "UNIQUE": return {
2778
+ kind: "UNIQUE",
2779
+ name,
2780
+ columns,
2781
+ implicit: void 0
2782
+ };
2783
+ case "CHECK":
2784
+ if (row.ENFORCED === "NO") throw new Error(`CHECK ${name} 未启用,尚不支持迁移`);
2785
+ return {
2786
+ kind: "CHECK",
2787
+ name,
2788
+ expression: str(row.CHECK_CLAUSE),
2789
+ comparisonExpression: normalizeMysqlCheck(str(row.CHECK_CLAUSE)),
2790
+ values: [],
2791
+ implicit: void 0
2792
+ };
2793
+ case "FOREIGN KEY": {
2794
+ if (row.REFERENCED_TABLE_SCHEMA !== database) throw new Error(`外键 ${name} 跨数据库引用,尚不支持迁移`);
2795
+ if (!["NO ACTION", "RESTRICT"].includes(str(row.UPDATE_RULE))) throw new Error(`外键 ${name} 的 ON UPDATE ${str(row.UPDATE_RULE)} 尚不支持迁移`);
2796
+ const onDelete = deleteAction(str(row.DELETE_RULE));
2797
+ return {
2798
+ kind: "FOREIGN_KEY",
2799
+ name,
2800
+ columns,
2801
+ referencedTable: str(row.REFERENCED_TABLE_NAME),
2802
+ referencedColumns: entries.map((r) => str(r.REFERENCED_COLUMN_NAME)),
2803
+ onDelete,
2804
+ cascade: onDelete === "CASCADE" ? "DELETE" : onDelete === "SET_NULL" ? "SET_NULL" : "NONE",
2805
+ deferrable: false,
2806
+ implicit: void 0
2807
+ };
2808
+ }
2809
+ default: throw new Error(`不支持的 MySQL 约束 ${str(row.CONSTRAINT_TYPE)}`);
2810
+ }
2811
+ });
2812
+ }
2813
+ _indexes(rows, constraints) {
2814
+ const foreignKeys = constraints.filter((c) => c.kind === "FOREIGN_KEY");
2815
+ const result = [];
2816
+ for (const [name, entries] of group(rows, "INDEX_NAME")) {
2817
+ if (entries.some((r) => r.SUB_PART != null || r.EXPRESSION != null || r.COLLATION === "D" || r.INDEX_TYPE !== "BTREE" || r.IS_VISIBLE === "NO")) throw new Error(`索引 ${name} 使用前缀、表达式、降序、隐藏或非 BTREE 定义,尚不支持迁移`);
2818
+ if (name === "PRIMARY" || Number(entries[0].NON_UNIQUE) === 0) continue;
2819
+ const columns = entries.map((r) => str(r.COLUMN_NAME));
2820
+ result.push({
2821
+ name,
2822
+ columns,
2823
+ unique: false,
2824
+ predicate: void 0,
2825
+ implicit: foreignKeys.some((fk) => fk.columns.every((c, i) => columns[i] === c))
2826
+ });
2827
+ }
2828
+ return result;
2829
+ }
2830
+ };
2831
+ function group(rows, key) {
2832
+ const groups = /* @__PURE__ */ new Map();
2833
+ for (const row of rows) {
2834
+ const name = str(row[key]);
2835
+ const entries = groups.get(name) ?? [];
2836
+ entries.push(row);
2837
+ groups.set(name, entries);
2838
+ }
2839
+ return groups;
2840
+ }
2841
+ function deleteAction(value) {
2842
+ switch (value) {
2843
+ case "CASCADE": return "CASCADE";
2844
+ case "SET NULL": return "SET_NULL";
2845
+ case "RESTRICT":
2846
+ case "NO ACTION": return "NO_ACTION";
2847
+ default: throw new Error(`不支持的 ON DELETE ${value}`);
2848
+ }
2849
+ }
2850
+ //#endregion
2851
+ //#region src/vendor/ts-grm.ts
2852
+ /**
2853
+ * ts-grm 依赖的唯一入口(适配层)。
2854
+ * TableDef、ColumnDef 与约束类型声明改写自 ts-grm 的 schema_def.ts:
2855
+ * 仅保留迁移器所需字段,调整类型名称和引用,并添加本项目的适配接口及实现。
2856
+ * 原作者 陈涛 (Chen Tao);改写部分保留 Apache-2.0 许可与署名。
2857
+ * @see ../../THIRD_PARTY_NOTICES.md
2858
+ * @see https://github.com/babyfish-ct/ts-grm/blob/fe78eb6c323bf335ff23650a414856eb36bfbce7/packages/sql/src/impl/schema_def.ts
2859
+ *
2860
+ * 约定:migrate 源码中所有对 `@ts-grm/*` 的 import 必须经过本文件,
2861
+ * 禁止在业务代码里直接 `import ... from "@ts-grm/sql"` 等。
2862
+ *
2863
+ * 依赖形态(2026-09-11 起):`@ts-grm/core` / `@ts-grm/sql` 是**运行时依赖**
2864
+ * (npm `^0.0.13`),不再是 yarn workspace 跨目录挂载 —— migrate 是 ts-grm 的
2865
+ * 插件,宿主由 npm 提供。上游换代时本文件是唯一修改点。
2866
+ *
2867
+ * 上游 API 现状(0.0.13 实测)与适配点:
2868
+ * - 公开导出里**没有** `createSchema` / `TableDef` / `ColumnDef` / `ConstraintDef`
2869
+ * / `SqlClientImplementor` —— 上游把 schema 定义收回了内部模块。
2870
+ * - 结构化表定义唯一的公开入口是 `sqlClient.createSchema()`,但它的**公开类型**
2871
+ * (`@ts-grm/core` 的 `Schema`)只暴露 creationSqlArray / deletionSqlArray /
2872
+ * execute / toString,即只有 SQL 字符串,没有结构;diff 引擎需要结构。
2873
+ * - 该调用的运行时返回值是上游内部的 SchemaImpl,其上有 `tableDefs: TableDef[]`。
2874
+ * **本文件的 `createSchema()` 是全仓库唯一读取该内部字段的地方**;
2875
+ * 上游一旦公开结构化 API,只改这一个函数即可。
2876
+ * - `TableDef` / `ColumnDef` / `ConstraintDef` 上游未导出,此处按 dist 类型声明
2877
+ * 镜像(结构等价;子类型一律引用 core 的公开类型,不引入 any)。
2878
+ */
2879
+ /**
2880
+ * 从 ts-grm 模型推导目标态表定义(`createSchema()` 的适配封装)。
2881
+ *
2882
+ * 上游只公开 SQL 字符串(`Schema.creationSqlArray`),而 diff 需要结构化定义,
2883
+ * 因此这里读取运行时实例上的 `tableDefs`。**这是全仓库唯一的内部字段依赖点**,
2884
+ * 上游若公开结构化 API,替换本函数实现即可。
2885
+ *
2886
+ * 读不到时抛可读错误(外部输入路径不 fail-fast 的原则,见 schema/model.ts)。
2887
+ */
2888
+ async function createSchema(client) {
2889
+ const tableDefs = (await client.createSchema()).tableDefs;
2890
+ if (tableDefs == null) throw new Error("ts-grm 的 createSchema() 未返回结构化表定义(内部字段 tableDefs 缺失)。上游可能变更了 schema 定义实现,请检查 src/vendor/ts-grm.ts 的适配点。");
2891
+ return tableDefs;
2892
+ }
2893
+ /** Upstream 0.0.13 spells FLOAT as flat. Keep the correction at the upstream boundary.
2894
+ * @see https://github.com/babyfish-ct/ts-grm/blob/main/packages/sql/src/driver/mysql_driver.ts
2895
+ */
2896
+ var MySqlDriver$1 = class extends MySqlDriver {
2897
+ typeName(column) {
2898
+ return column.type.kind === "F32" ? "float" : super.typeName(column);
2899
+ }
2900
+ };
2901
+ //#endregion
2902
+ //#region src/executor/sqlite.ts
2903
+ var SqliteSqlExecutor = class {
2904
+ _database;
2905
+ constructor(_database) {
2906
+ this._database = _database;
2907
+ }
2908
+ async query(sql, params) {
2909
+ const statement = this._database.prepare(sql);
2910
+ if (!statement.reader) {
2911
+ statement.run(...params ?? []);
2912
+ return { rows: [] };
2913
+ }
2914
+ return { rows: statement.all(...params ?? []) };
2915
+ }
2916
+ async executeStatements(statements, complete) {
2917
+ this._database.exec("begin");
2918
+ try {
2919
+ for (const sql of statements) this._database.exec(sql);
2920
+ await complete?.(this);
2921
+ this._database.exec("commit");
2922
+ } catch (e) {
2923
+ try {
2924
+ this._database.exec("rollback");
2925
+ } catch {}
2926
+ throw new Error(`语句执行失败(已回滚):${e.message}`);
2927
+ }
2928
+ }
2929
+ async acquireMigrationLock(_key) {
2930
+ return async () => {};
2931
+ }
2932
+ };
2933
+ //#endregion
2934
+ //#region src/introspector/sqlite.ts
2935
+ /** 表清单(排除 SQLite 内部表) */
2936
+ const TABLES_SQL = `
2937
+ select name
2938
+ from sqlite_master
2939
+ where type = 'table' and name not like 'sqlite_%'
2940
+ order by name
2941
+ `;
2942
+ var SqliteIntrospector = class {
2943
+ _options;
2944
+ dialect = "sqlite";
2945
+ constructor(_options) {
2946
+ this._options = _options;
2947
+ }
2948
+ async introspect() {
2949
+ const { query } = this._options;
2950
+ try {
2951
+ const tableRows = await query.query(TABLES_SQL);
2952
+ const tables = [];
2953
+ for (const row of tableRows.rows) {
2954
+ const name = asString(row["name"]);
2955
+ const { columns, primaryKey } = await this._columns(name);
2956
+ const foreignKeys = await this._foreignKeys(name);
2957
+ const { uniques, indexes } = await this._indexes(name);
2958
+ tables.push({
2959
+ name,
2960
+ columns,
2961
+ constraints: [
2962
+ ...primaryKey,
2963
+ ...uniques,
2964
+ ...foreignKeys
2965
+ ],
2966
+ indexes
2967
+ });
2968
+ }
2969
+ return { tables };
2970
+ } catch (e) {
2971
+ throw new Error(`读取 SQLite 结构失败:${e.message}`);
2972
+ }
2973
+ }
2974
+ /**
2975
+ * 列与主键。
2976
+ * `table_info` 的 `pk` 列给出该列在复合主键中的位置(0 = 非主键),
2977
+ * 据此还原主键并保持列序。
2978
+ */
2979
+ async _columns(table) {
2980
+ const { rows } = await this._options.query.query(`pragma table_info(${quoteForPragma(table)})`);
2981
+ const pkColumns = [];
2982
+ const columns = rows.map((row) => {
2983
+ const name = asString(row["name"]);
2984
+ const pkPosition = Number(row["pk"]);
2985
+ if (pkPosition > 0) pkColumns.push({
2986
+ name,
2987
+ position: pkPosition
2988
+ });
2989
+ return {
2990
+ name,
2991
+ type: normalizeSqliteType(asString(row["type"])),
2992
+ nullable: Number(row["notnull"]) === 0,
2993
+ length: void 0,
2994
+ default: row["dflt_value"] == null ? void 0 : asString(row["dflt_value"]),
2995
+ autoIncrement: false,
2996
+ ordinal: Number(row["cid"]) + 1,
2997
+ comment: void 0
2998
+ };
2999
+ });
3000
+ pkColumns.sort((a, b) => a.position - b.position);
3001
+ return {
3002
+ columns,
3003
+ primaryKey: pkColumns.length === 0 ? [] : [{
3004
+ kind: "PRIMARY_KEY",
3005
+ name: void 0,
3006
+ columns: pkColumns.map((c) => c.name),
3007
+ implicit: void 0
3008
+ }]
3009
+ };
3010
+ }
3011
+ /** 外键:复合键在 pragma 里是同一 id 的多行,按 id 归组、按 seq 排序 */
3012
+ async _foreignKeys(table) {
3013
+ const { rows } = await this._options.query.query(`pragma foreign_key_list(${quoteForPragma(table)})`);
3014
+ const byId = /* @__PURE__ */ new Map();
3015
+ for (const row of rows) {
3016
+ const id = Number(row["id"]);
3017
+ const group = byId.get(id);
3018
+ if (group == null) byId.set(id, [row]);
3019
+ else group.push(row);
3020
+ }
3021
+ const result = [];
3022
+ for (const group of byId.values()) {
3023
+ const ordered = [...group].sort((a, b) => Number(a["seq"]) - Number(b["seq"]));
3024
+ const onDelete = toOnDelete(asString(ordered[0]["on_delete"]));
3025
+ result.push({
3026
+ kind: "FOREIGN_KEY",
3027
+ name: void 0,
3028
+ columns: ordered.map((r) => asString(r["from"])),
3029
+ referencedTable: asString(ordered[0]["table"]),
3030
+ referencedColumns: ordered.map((r) => asString(r["to"])),
3031
+ onDelete,
3032
+ deferrable: false,
3033
+ cascade: toCascade(onDelete),
3034
+ implicit: void 0
3035
+ });
3036
+ }
3037
+ return result;
3038
+ }
3039
+ /**
3040
+ * 索引与唯一约束。
3041
+ *
3042
+ * `pragma index_list` 的 origin 区分来源:
3043
+ * - `c` = create index(我们意义上的索引)
3044
+ * - `u` = unique 约束(表级 UNIQUE)
3045
+ * - `pk` = 主键,跳过(主键从 table_info 取,避免重复表示)
3046
+ */
3047
+ async _indexes(table) {
3048
+ const { rows } = await this._options.query.query(`pragma index_list(${quoteForPragma(table)})`);
3049
+ const uniques = [];
3050
+ const indexes = [];
3051
+ for (const row of rows) {
3052
+ const name = asString(row["name"]);
3053
+ const origin = asString(row["origin"]);
3054
+ if (origin === "pk") continue;
3055
+ const columns = await this._indexColumns(name);
3056
+ if (origin === "u") uniques.push({
3057
+ kind: "UNIQUE",
3058
+ name: void 0,
3059
+ columns,
3060
+ implicit: void 0
3061
+ });
3062
+ else indexes.push({
3063
+ name,
3064
+ columns,
3065
+ unique: Number(row["unique"]) === 1,
3066
+ predicate: void 0
3067
+ });
3068
+ }
3069
+ return {
3070
+ uniques,
3071
+ indexes
3072
+ };
3073
+ }
3074
+ async _indexColumns(index) {
3075
+ const { rows } = await this._options.query.query(`pragma index_info(${quoteForPragma(index)})`);
3076
+ return [...rows].sort((a, b) => Number(a["seqno"]) - Number(b["seqno"])).map((r) => asString(r["name"]));
3077
+ }
3078
+ };
3079
+ /** pragma 不支持参数绑定,标识符只能拼接 —— 双引号包裹并把内部双引号翻倍 */
3080
+ function quoteForPragma(name) {
3081
+ return `"${name.replaceAll("\"", "\"\"")}"`;
3082
+ }
3083
+ /**
3084
+ * SQLite 的声明类型 → ts-grm `SqliteDriver.typeName()` 的输出。
3085
+ *
3086
+ * SQLite 的类型系统是「亲和性」而非强类型(列上可以写任意类型名),而 ts-grm
3087
+ * 只会产出四种(见 `sqlite_driver.ts` 的 typeName)。归一化保证
3088
+ * 「模型建的表 == introspection 读到的」自洽,否则差分会永远不相等。
3089
+ */
3090
+ function normalizeSqliteType(raw) {
3091
+ const t = raw.trim().toLowerCase();
3092
+ if (t === "") return "blob";
3093
+ if (t.includes("int")) return "integer";
3094
+ if (t.includes("char") || t.includes("clob") || t.includes("text")) return "text";
3095
+ if (t.includes("blob")) return "blob";
3096
+ if (t.includes("real") || t.includes("floa") || t.includes("doub")) return "real";
3097
+ return "real";
3098
+ }
3099
+ /** SQLite 的 on_delete 文本 → migrate 的 OnDelete */
3100
+ function toOnDelete(raw) {
3101
+ switch (raw.toUpperCase()) {
3102
+ case "CASCADE": return "CASCADE";
3103
+ case "SET NULL": return "SET_NULL";
3104
+ case "SET DEFAULT": return "SET_DEFAULT";
3105
+ case "RESTRICT": return "RESTRICT";
3106
+ default: return "NO_ACTION";
3107
+ }
3108
+ }
3109
+ /** migrate 的 OnDelete → ts-grm 的 ORM 级联语义(introspection 只能反推,与 PG 版同口径) */
3110
+ function toCascade(onDelete) {
3111
+ switch (onDelete) {
3112
+ case "CASCADE": return "DELETE";
3113
+ case "SET_NULL": return "SET_NULL";
3114
+ default: return "NONE";
3115
+ }
3116
+ }
3117
+ function asString(value) {
3118
+ return value == null ? "" : String(value);
3119
+ }
3120
+ //#endregion
3121
+ //#region src/runtime.ts
3122
+ /**
3123
+ * 运行时组装 —— 从 `MigrateConfig` 造出一个可用的 `Migrator`。
3124
+ *
3125
+ * CLI 与程序化调用共用这一层,这样「命令行能用」和「脚本里能用」走的是同一条路径。
3126
+ *
3127
+ * 组装链(正是 docs/design.md 里写的那条):
3128
+ * EntityManager.of(cwd, ...models) ← 触发模型注册,取回全部 entity
3129
+ * newSqlClient(<方言>Driver(conn), { entityManager })
3130
+ * createSchema(sqlClient) ← 上游 API,结构在 tableDefs 上(见 vendor 层)
3131
+ * tableDefsToSchema(..., { dialect }) ← 目标态 Schema
3132
+ *
3133
+ * 方言差异集中在 `createConnection` 与 `assembleRuntime` 的两处分支里;
3134
+ * 哪些方言可用由 `src/dialect.ts` 的注册表决定(未实现在装配前就拒掉)。
3135
+ */
3136
+ /** 默认迁移目录 / 锁文件(相对项目根) */
3137
+ const DEFAULT_MIGRATIONS_DIR = "./src/ts-grm";
3138
+ const DEFAULT_LOCK_PATH = "./.ts-grm-migrate.lock";
3139
+ /**
3140
+ * 从配置组装运行时。
3141
+ *
3142
+ * `cwd` 是项目根:模型路径、迁移目录、锁文件都相对它解析。
3143
+ */
3144
+ async function createRuntime(config, cwd, options = {}) {
3145
+ const dialect = config.dialect ?? "postgres";
3146
+ const dialectSupport = dialectInfo(dialect);
3147
+ if (!dialectSupport.implemented) throw new Error(`方言 "${dialect}" 尚未实现(ts-grm 侧由 ${dialectSupport.tsGrmDrivers.join(" / ")} 提供)。目前端到端可用的方言:${IMPLEMENTED_DIALECT_NAMES.join(" / ")}。`);
3148
+ const connection = await createConnection(dialect, config, cwd);
3149
+ try {
3150
+ return await assembleRuntime(config, cwd, options, dialect, connection);
3151
+ } catch (e) {
3152
+ await connection.close().catch(() => void 0);
3153
+ throw e;
3154
+ }
3155
+ }
3156
+ async function createConnection(dialect, config, cwd) {
3157
+ if (dialect === "sqlite") {
3158
+ const database = await openSqlite(config, cwd);
3159
+ const executor = new SqliteSqlExecutor(database);
3160
+ return {
3161
+ executor,
3162
+ introspector: new SqliteIntrospector({ query: executor }),
3163
+ driver: new SqliteDriver(database),
3164
+ close: async () => {
3165
+ database.close();
3166
+ }
3167
+ };
3168
+ }
3169
+ if (dialect === "mysql") {
3170
+ if (config.schema != null) throw new Error("mysql 请使用 database.database 选择数据库,不支持 schema 配置");
3171
+ let mysql;
3172
+ try {
3173
+ mysql = await import("mysql2/promise");
3174
+ } catch {
3175
+ throw new Error("mysql 方言需要 mysql2 依赖,请先安装:yarn add mysql2");
3176
+ }
3177
+ const { connectionString, file: _file, ...settings } = config.database;
3178
+ const pool = mysql.createPool(connectionString ? {
3179
+ uri: connectionString,
3180
+ multipleStatements: true,
3181
+ timezone: "Z",
3182
+ supportBigNumbers: true,
3183
+ bigNumberStrings: true,
3184
+ connectTimeout: DEFAULT_CONNECTION_TIMEOUT_MS
3185
+ } : {
3186
+ ...settings,
3187
+ multipleStatements: true,
3188
+ timezone: "Z",
3189
+ supportBigNumbers: true,
3190
+ bigNumberStrings: true,
3191
+ connectTimeout: DEFAULT_CONNECTION_TIMEOUT_MS
3192
+ });
3193
+ const executor = new MysqlSqlExecutor(pool);
3194
+ try {
3195
+ const { rows } = await executor.query("select version() as version, database() as db, @@lower_case_table_names as folding");
3196
+ const version = String(rows[0]?.version ?? "");
3197
+ const [major = 0, minor = 0, patch = 0] = version.split(".").map(Number);
3198
+ if (/mariadb/i.test(version) || major < 8 || major === 8 && minor === 0 && patch < 16) throw new Error(`mysql 需要 MySQL 8.0.16+(当前 ${version});MariaDB 尚未验证`);
3199
+ if (!rows[0]?.db) throw new Error("mysql 连接必须指定 database.database 或 connectionString 中的数据库");
3200
+ if (Number(rows[0]?.folding) !== 0) throw new Error("mysql 当前仅支持 lower_case_table_names=0,以保证模型和物理表名一致");
3201
+ return {
3202
+ executor,
3203
+ introspector: new MysqlIntrospector({ query: executor }),
3204
+ driver: new MySqlDriver$1(pool),
3205
+ close: () => pool.end()
3206
+ };
3207
+ } catch (error) {
3208
+ await pool.end();
3209
+ throw error;
3210
+ }
3211
+ }
3212
+ if (dialect === "mssql") {
3213
+ const schema = config.schema ?? "dbo";
3214
+ const connection = await openSqlServer(config.database, schema);
3215
+ return {
3216
+ ...connection,
3217
+ introspector: new SqlServerIntrospector({
3218
+ query: connection.executor,
3219
+ schema: connection.schema
3220
+ }),
3221
+ driver: new SqlServerDriver(new SqlServerPool({ server: config.database.host ?? "localhost" }))
3222
+ };
3223
+ }
3224
+ if (dialect === "oracle") {
3225
+ const connection = await openOracle(config.database, config.schema);
3226
+ return {
3227
+ ...connection,
3228
+ introspector: new OracleIntrospector({
3229
+ query: connection.executor,
3230
+ schema: connection.schema
3231
+ }),
3232
+ driver: new OracleDriver(new OraclePool({ user: config.database.user }))
3233
+ };
3234
+ }
3235
+ if (dialect !== "postgres") throw new Error(`方言 ${dialect} 尚未实现`);
3236
+ const pool = await createPool(config);
3237
+ const executor = new PostgresSqlExecutor(pool);
3238
+ return {
3239
+ executor,
3240
+ introspector: new PostgresIntrospector({
3241
+ query: executor,
3242
+ schema: config.schema ?? "public"
3243
+ }),
3244
+ driver: new PostgresDriver(pool),
3245
+ close: async () => {
3246
+ await pool.end();
3247
+ }
3248
+ };
3249
+ }
3250
+ /** 与方言无关的接线:迁移文件、历史表、模型加载、DDL 生成器 */
3251
+ async function assembleRuntime(config, cwd, options, dialect, connection) {
3252
+ const { executor, introspector, driver } = connection;
3253
+ const migrationsDir = path.resolve(cwd, config.migrationsDir ?? "./src/ts-grm");
3254
+ const lockPath = path.resolve(cwd, config.lockPath ?? "./.ts-grm-migrate.lock");
3255
+ const schema = connection.schema ?? config.schema ?? "public";
3256
+ if (dialect === "postgres") {
3257
+ if (schema !== "public") await executor.executeStatements([`create schema if not exists ${quoteIdentifier(schema)}`]);
3258
+ } else if (dialect !== "mssql" && dialect !== "oracle" && schema !== "public") throw new Error(`方言 "${dialect}" 不支持 schema(配置里给的是 "${schema}")。请去掉 schema 配置。`);
3259
+ const entityManager = EntityManager.of(cwd, ...config.models);
3260
+ const sqlClient = newSqlClient(driver, { entityManager });
3261
+ const ddlOptions = {};
3262
+ const ddl = dialect === "sqlite" ? new SqliteDdlGenerator(ddlOptions) : dialect === "mysql" ? new MysqlDdlGenerator() : dialect === "mssql" ? new SqlServerDdlGenerator(schema) : dialect === "oracle" ? new OracleDdlGenerator(schema) : new PostgresDdlGenerator();
3263
+ return {
3264
+ migrator: new Migrator({
3265
+ files: new FileMigrationStore(migrationsDir),
3266
+ history: new DatabaseMigrationHistoryStore({
3267
+ executor,
3268
+ dialect,
3269
+ schema
3270
+ }),
3271
+ executor,
3272
+ introspector,
3273
+ ddl,
3274
+ targetSchema: async () => {
3275
+ let tableDefs;
3276
+ try {
3277
+ tableDefs = await createSchema(sqlClient);
3278
+ } catch (e) {
3279
+ throw new Error(`加载模型失败:${e.message}\n提示:migrate 用 Node 原生 import 直接加载你的模型文件,所以它们必须是 ESM —— 给项目加上 "type": "module",或把 models 指向编译后的 ESM 产物(.js)。`);
3280
+ }
3281
+ ddlOptions.tableDefs = new Map(tableDefs.map((t) => [t.name, t]));
3282
+ ddlOptions.driver = sqlClient.driver;
3283
+ return tableDefsToSchema(tableDefs, sqlClient.driver, { dialect });
3284
+ },
3285
+ migrationsDir,
3286
+ lockPath,
3287
+ ...options.confirm != null ? { confirm: options.confirm } : {}
3288
+ }),
3289
+ close: () => connection.close()
3290
+ };
3291
+ }
3292
+ /**
3293
+ * 建连接池。pg 是**可选** peer 依赖:只有 postgres 方言才需要它,
3294
+ * 因此放在这里动态 import,缺失时给可操作的提示而不是模块解析崩溃。
3295
+ */
3296
+ /**
3297
+ * 连接建立(含主机名解析)的默认上限。
3298
+ * 主机名解析偶发卡住时,pg 会无限等待;有上限才能报错而非挂死。
3299
+ */
3300
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 15e3;
3301
+ async function createPool(config) {
3302
+ let Pool;
3303
+ try {
3304
+ Pool = (await import("pg")).Pool;
3305
+ } catch {
3306
+ throw new Error("postgres 方言需要 pg 依赖,请先安装:yarn add pg(或 npm install pg)");
3307
+ }
3308
+ const poolConfig = {
3309
+ connectionTimeoutMillis: DEFAULT_CONNECTION_TIMEOUT_MS,
3310
+ ...config.database
3311
+ };
3312
+ const schema = config.schema;
3313
+ if (schema != null && schema !== "public") poolConfig["options"] = `${typeof poolConfig["options"] === "string" ? `${poolConfig["options"]} ` : ""}-c search_path=${schema}`;
3314
+ return new Pool(poolConfig);
3315
+ }
3316
+ /**
3317
+ * 打开 SQLite 库文件。better-sqlite3 是**可选** peer 依赖(同 pg 的处理方式):
3318
+ * 只有 sqlite 方言才需要它,因此动态 import 并给可操作的提示。
3319
+ */
3320
+ async function openSqlite(config, cwd) {
3321
+ let Database;
3322
+ try {
3323
+ Database = (await import("better-sqlite3")).default;
3324
+ } catch {
3325
+ throw new Error("sqlite 方言需要 better-sqlite3 依赖,请先安装:yarn add better-sqlite3");
3326
+ }
3327
+ const file = config.database.file ?? ":memory:";
3328
+ return new Database(file === ":memory:" ? file : path.resolve(cwd, file));
3329
+ }
3330
+ //#endregion
3331
+ //#region src/cli.ts
3332
+ /**
3333
+ * CLI 入口 —— 装好依赖后,在项目根敲命令即可。
3334
+ *
3335
+ * ts-grm-migrate dev --name init 对比模型与数据库,生成并应用一个迁移
3336
+ * ts-grm-migrate deploy 应用所有未应用的迁移(部署 / CI)
3337
+ * ts-grm-migrate push [--force] 直接同步成模型的样子(不记历史)
3338
+ * ts-grm-migrate status 查看迁移状态
3339
+ *
3340
+ * 配置文件在项目根自动查找(见 `src/config.ts` 的候选名)。
3341
+ */
3342
+ const USAGE = `ts-grm-migrate —— ts-grm 的 schema 迁移工具
3343
+
3344
+ 用法:
3345
+ ts-grm-migrate <命令> [选项]
3346
+
3347
+ 命令:
3348
+ dev [--name <名字>] 对比模型与数据库,生成并应用一个迁移(开发用)
3349
+ 不给名字时用纯时间戳命名
3350
+ deploy 应用所有未应用的迁移(部署 / CI 用)
3351
+ push 直接把数据库同步成模型的样子(不写迁移文件、不记历史)
3352
+ status 查看已应用 / 待应用的迁移
3353
+ resolve --applied <id> 把迁移标记为已应用(SQL 已手工执行过)
3354
+ resolve --rolled-back <id> 标记迁移已回滚,它将重新待应用
3355
+
3356
+ 选项:
3357
+ -n, --name <名字> 迁移名(dev 命令用;可省略,省略时只用时间戳)
3358
+ --config <path> 指定配置文件(默认在项目根自动查找)
3359
+ --force 破坏性变更不询问,直接执行(非交互环境下必需)
3360
+ -h, --help 显示本帮助
3361
+
3362
+ 配置文件(项目根,任选其一):
3363
+ ${CONFIG_FILENAMES.join("\n ")}
3364
+ `;
3365
+ /** 解析 argv:`--k v` / `--k=v` / `-h` / 位置参数(第一个位置参数是命令) */
3366
+ /**
3367
+ * 短选项 → 长选项别名。
3368
+ * 只有登记过的短选项才会吃掉下一个参数,其余一律按布尔开关处理
3369
+ * (否则 `-h dev` 会把命令名当成 help 的值)。
3370
+ */
3371
+ const SHORT_FLAG_ALIASES = { n: "name" };
3372
+ function parseArgs(argv) {
3373
+ const flags = /* @__PURE__ */ new Map();
3374
+ let command;
3375
+ for (let i = 0; i < argv.length; i++) {
3376
+ const arg = argv[i];
3377
+ if (arg.startsWith("--")) {
3378
+ const eq = arg.indexOf("=");
3379
+ if (eq >= 0) {
3380
+ flags.set(arg.slice(2, eq), arg.slice(eq + 1));
3381
+ continue;
3382
+ }
3383
+ const name = arg.slice(2);
3384
+ const next = argv[i + 1];
3385
+ if (next != null && !next.startsWith("-")) {
3386
+ flags.set(name, next);
3387
+ i++;
3388
+ } else flags.set(name, true);
3389
+ } else if (arg.startsWith("-") && arg.length > 1) {
3390
+ const short = arg.slice(1);
3391
+ const eq = short.indexOf("=");
3392
+ if (eq >= 0) {
3393
+ const key = short.slice(0, eq);
3394
+ flags.set(SHORT_FLAG_ALIASES[key] ?? key, short.slice(eq + 1));
3395
+ continue;
3396
+ }
3397
+ const canonical = SHORT_FLAG_ALIASES[short];
3398
+ const next = argv[i + 1];
3399
+ if (canonical != null && next != null && !next.startsWith("-")) {
3400
+ flags.set(canonical, next);
3401
+ i++;
3402
+ } else flags.set(canonical ?? short, true);
3403
+ } else if (command == null) command = arg;
3404
+ }
3405
+ return {
3406
+ command,
3407
+ flags
3408
+ };
3409
+ }
3410
+ /**
3411
+ * 执行一条命令,返回退出码。
3412
+ *
3413
+ * 不调用 `process.exit`,也不直接写 console(可注入),便于测试。
3414
+ */
3415
+ async function run(argv, cwd, options = {}) {
3416
+ const log = options.log ?? ((message) => console.log(message));
3417
+ const errorLog = options.errorLog ?? ((message) => console.error(message));
3418
+ const { command, flags } = parseArgs(argv);
3419
+ if (command == null || command === "help" || flags.has("help") || flags.has("h")) {
3420
+ log(USAGE);
3421
+ return 0;
3422
+ }
3423
+ const configFlag = flags.get("config");
3424
+ const { config, path: configFile } = await loadConfig(cwd, typeof configFlag === "string" ? configFlag : void 0);
3425
+ const runtime = await createRuntime(config, cwd, { confirm: options.confirm ?? makeConfirm(flags.has("force"), errorLog) });
3426
+ const dbLabel = describeDatabase(config);
3427
+ try {
3428
+ log(`配置:${configFile}`);
3429
+ switch (command) {
3430
+ case "dev": return await runDev(runtime, flags.get("name"), dbLabel, log, errorLog);
3431
+ case "deploy": return await runDeploy(runtime, dbLabel, log, errorLog);
3432
+ case "push": return await runPush(runtime, dbLabel, log, errorLog);
3433
+ case "status": return await runStatus(runtime, log);
3434
+ case "resolve": return await runResolve(runtime, flags, log, errorLog);
3435
+ default:
3436
+ errorLog(`未知命令 "${command}"。`);
3437
+ log(USAGE);
3438
+ return 1;
3439
+ }
3440
+ } catch (e) {
3441
+ if (e instanceof MigrationAbortedError) {
3442
+ log("已取消。");
3443
+ return 0;
3444
+ }
3445
+ throw e;
3446
+ } finally {
3447
+ await runtime.close();
3448
+ }
3449
+ }
3450
+ async function runDev(runtime, name, dbLabel, log, errorLog) {
3451
+ const migrationName = typeof name === "string" ? name.trim() : "";
3452
+ const result = await runtime.migrator.dev({ name: migrationName });
3453
+ if (!result.applied) {
3454
+ log("模型与数据库结构一致,无需迁移。");
3455
+ return 0;
3456
+ }
3457
+ log(`已生成并应用迁移:${result.migrationId}`);
3458
+ reportDrift(result.drift, dbLabel, log, errorLog);
3459
+ return 0;
3460
+ }
3461
+ async function runDeploy(runtime, dbLabel, log, errorLog) {
3462
+ const result = await runtime.migrator.deploy();
3463
+ if (result.applied.length === 0) log(`没有待应用的迁移(已应用 ${result.skipped} 个)。`);
3464
+ else for (const id of result.applied) log(`已应用 ${id}`);
3465
+ reportDrift(result.drift, dbLabel, log, errorLog);
3466
+ return 0;
3467
+ }
3468
+ async function runPush(runtime, dbLabel, log, errorLog) {
3469
+ const result = await runtime.migrator.push();
3470
+ if (result.statements.length === 0) log("模型与数据库结构一致,无需同步。");
3471
+ else log(`已同步:应用了 ${result.statements.length} 条语句。`);
3472
+ reportDrift(result.drift, dbLabel, log, errorLog);
3473
+ return 0;
3474
+ }
3475
+ /** 数据库的可读标识(用于对账消息里指认「哪个库」) */
3476
+ function describeDatabase(config) {
3477
+ const schema = config.schema ?? "public";
3478
+ const database = config.database.database;
3479
+ return database != null && database !== "" ? `库 ${database},schema ${schema}` : `schema ${schema}`;
3480
+ }
3481
+ /**
3482
+ * 输出对账结果。已知限制(如 CHECK 表达式)降级为一行提示,不当作异常。
3483
+ */
3484
+ function reportDrift(drift, dbLabel, log, errorLog) {
3485
+ const abnormal = abnormalDrift(drift);
3486
+ const knownCount = drift.length - abnormal.length;
3487
+ if (abnormal.length > 0) {
3488
+ errorLog(`\n⚠ 对账发现数据库与模型不一致(${dbLabel}):`);
3489
+ for (const item of abnormal) errorLog(` - 表 ${item.table}:${item.summary}`);
3490
+ errorLog("这通常意味着迁移未完整生效,或数据库被手工改动过。");
3491
+ }
3492
+ if (knownCount > 0) log(`(另有 ${knownCount} 处因已知限制无法比对(如 CHECK 约束表达式),已忽略)`);
3493
+ }
3494
+ async function runStatus(runtime, log) {
3495
+ const status = await runtime.migrator.status();
3496
+ if (status.applied.length === 0 && status.pending.length === 0) {
3497
+ log("没有任何迁移。");
3498
+ return 0;
3499
+ }
3500
+ if (status.applied.length > 0) {
3501
+ log("已应用:");
3502
+ for (const applied of status.applied) log(` ${applied.id} ${applied.appliedAt.toISOString()}${applied.failed ? " [失败]" : ""}`);
3503
+ }
3504
+ if (status.pending.length > 0) {
3505
+ log("待应用:");
3506
+ for (const id of status.pending) log(` ${id}`);
3507
+ } else log("没有待应用的迁移。");
3508
+ return 0;
3509
+ }
3510
+ /** 手工修正迁移状态(失败后的恢复途径) */
3511
+ async function runResolve(runtime, flags, log, errorLog) {
3512
+ const applied = flags.get("applied");
3513
+ const rolledBack = flags.get("rolled-back");
3514
+ if (typeof applied === "string" && typeof rolledBack === "string") {
3515
+ errorLog("--applied 与 --rolled-back 只能选一个。");
3516
+ return 1;
3517
+ }
3518
+ if (typeof applied === "string") {
3519
+ await runtime.migrator.resolve({
3520
+ migration: applied,
3521
+ action: "applied"
3522
+ });
3523
+ log(`已标记为已应用:${applied}`);
3524
+ return 0;
3525
+ }
3526
+ if (typeof rolledBack === "string") {
3527
+ await runtime.migrator.resolve({
3528
+ migration: rolledBack,
3529
+ action: "rolled-back"
3530
+ });
3531
+ log(`已标记回滚(将重新待应用):${rolledBack}`);
3532
+ return 0;
3533
+ }
3534
+ errorLog("resolve 需要 --applied <迁移 id> 或 --rolled-back <迁移 id>。");
3535
+ return 1;
3536
+ }
3537
+ /** 破坏性变更的交互确认;`--force` 或非 TTY 下直接放行/拒绝 */
3538
+ function makeConfirm(force, errorLog) {
3539
+ return async (diff) => {
3540
+ if (force) return true;
3541
+ printDestructive(diff.destructive, errorLog);
3542
+ if (!process.stdin.isTTY) {
3543
+ errorLog("当前不是交互环境,无法确认;确认后请加 --force 重试。");
3544
+ return false;
3545
+ }
3546
+ const rl = createInterface({
3547
+ input: process.stdin,
3548
+ output: process.stdout
3549
+ });
3550
+ try {
3551
+ const answer = (await rl.question("是否继续?(y/N) ")).trim().toLowerCase();
3552
+ return answer === "y" || answer === "yes";
3553
+ } finally {
3554
+ rl.close();
3555
+ }
3556
+ };
3557
+ }
3558
+ function printDestructive(changes, errorLog) {
3559
+ errorLog("检测到破坏性变更(可能丢失数据):");
3560
+ for (const change of changes) switch (change.kind) {
3561
+ case "DROP_TABLE":
3562
+ errorLog(` - 删除表 ${change.table}`);
3563
+ break;
3564
+ case "DROP_COLUMN":
3565
+ errorLog(` - 删除列 ${change.table}.${change.column}`);
3566
+ break;
3567
+ case "ALTER_COLUMN": errorLog(` - 修改列类型 ${change.table}.${change.column} → ${change.type}`);
3568
+ }
3569
+ }
3570
+ //#endregion
3571
+ export { PostgresDdlGenerator as A, ServerSql as B, describeDiff as C, checksumOf as D, FileMigrationStore as E, dialectInfo as F, acquireProcessLock as I, PostgresSqlExecutor as L, DIALECTS as M, DIALECT_NAMES as N, ServerMigrationHistoryStore as O, IMPLEMENTED_DIALECT_NAMES as P, SchemaDiffer as R, abnormalDrift as S, DatabaseMigrationHistoryStore as T, loadConfig as _, createRuntime as a, generateMigrationId as b, OracleIntrospector as c, SqlServerSqlExecutor as d, SqlServerDdlGenerator as f, defineConfig as g, CONFIG_FILENAMES as h, DEFAULT_MIGRATIONS_DIR as i, PostgresIntrospector as j, SqliteDdlGenerator as k, OracleDdlGenerator as l, MysqlDdlGenerator as m, run as n, MysqlIntrospector as o, MysqlSqlExecutor as p, DEFAULT_LOCK_PATH as r, SqlServerIntrospector as s, parseArgs as t, OracleSqlExecutor as u, MigrationAbortedError as v, DEFAULT_HISTORY_TABLE as w, toSqlFile as x, Migrator as y, tableDefsToSchema as z };
3572
+
3573
+ //# sourceMappingURL=cli-C-KYDbI_.mjs.map