@guren/orm 2.13.1 → 2.15.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,1229 @@
1
+ import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ //#region src/migration-guard.ts
4
+ const ALLOW_DESTRUCTIVE_MARKER = "guren:allow-destructive";
5
+ /** One-run override of `destructiveMigrations: 'refuse'`, which `guren db:migrate --allow-destructive` sets. */
6
+ const ALLOW_DESTRUCTIVE_ENV = "GUREN_ALLOW_DESTRUCTIVE_MIGRATIONS";
7
+ const POSTGRES = {
8
+ backslashEscapes: false,
9
+ escapeStrings: true,
10
+ mysqlComments: false,
11
+ dollarQuotes: true,
12
+ nestedComments: true
13
+ };
14
+ const MYSQL = {
15
+ backslashEscapes: true,
16
+ escapeStrings: false,
17
+ mysqlComments: true,
18
+ dollarQuotes: false,
19
+ nestedComments: false
20
+ };
21
+ /**
22
+ * Each way a dialect's server may read the SQL, all of which count: MySQL under
23
+ * `NO_BACKSLASH_ESCAPES`, and PostgreSQL with `standard_conforming_strings` off,
24
+ * close a string where the default does not.
25
+ */
26
+ const LEX_READINGS = {
27
+ postgres: [POSTGRES, {
28
+ ...POSTGRES,
29
+ backslashEscapes: true
30
+ }],
31
+ mysql: [MYSQL, {
32
+ ...MYSQL,
33
+ backslashEscapes: false
34
+ }],
35
+ sqlite: [{
36
+ backslashEscapes: false,
37
+ escapeStrings: false,
38
+ mysqlComments: false,
39
+ dollarQuotes: false,
40
+ nestedComments: false
41
+ }]
42
+ };
43
+ function lex(sql, rules, firstLine = 1) {
44
+ const tokens = [];
45
+ const comments = [];
46
+ const executable = [];
47
+ let line = firstLine;
48
+ let i = 0;
49
+ const advanceTo = (end) => {
50
+ const text = sql.slice(i, end);
51
+ for (const char of text) if (char === "\n") line += 1;
52
+ i = end;
53
+ return text;
54
+ };
55
+ /** The index of the quote closing the one at `open`, or -1. A doubled quote is an escaped one in every dialect. */
56
+ const closingQuote = (open, quote, backslash) => {
57
+ if (!backslash) {
58
+ for (let end = sql.indexOf(quote, open + 1); end !== -1; end = sql.indexOf(quote, end + 2)) if (sql[end + 1] !== quote) return end;
59
+ return -1;
60
+ }
61
+ for (let end = open + 1; end < sql.length; end += 1) {
62
+ if (backslash && sql[end] === "\\") {
63
+ end += 1;
64
+ continue;
65
+ }
66
+ if (sql[end] !== quote) continue;
67
+ if (sql[end + 1] === quote) {
68
+ end += 1;
69
+ continue;
70
+ }
71
+ return end;
72
+ }
73
+ return -1;
74
+ };
75
+ /** The index of the close of the block comment opened at `open`, or -1. */
76
+ const closingComment = (open) => {
77
+ if (!rules.nestedComments) return sql.indexOf("*/", open + 2);
78
+ let depth = 0;
79
+ for (let at = open; at < sql.length - 1; at += 1) if (sql[at] === "/" && sql[at + 1] === "*") {
80
+ depth += 1;
81
+ at += 1;
82
+ } else if (sql[at] === "*" && sql[at + 1] === "/") {
83
+ depth -= 1;
84
+ if (depth === 0) return at;
85
+ at += 1;
86
+ }
87
+ return -1;
88
+ };
89
+ while (i < sql.length) {
90
+ const char = sql[i];
91
+ const startLine = line;
92
+ if (char === "\n" || char === " " || char === " " || char === "\r") {
93
+ advanceTo(i + 1);
94
+ continue;
95
+ }
96
+ if (char === "-" && sql[i + 1] === "-" || char === "#" && rules.mysqlComments) {
97
+ const end = sql.indexOf("\n", i);
98
+ const body = advanceTo(end === -1 ? sql.length : end).slice(char === "#" ? 1 : 2);
99
+ comments.push({
100
+ text: body,
101
+ line: startLine
102
+ });
103
+ if (rules.mysqlComments && char === "-" && body !== "" && !/^\s/.test(body)) executable.push({
104
+ text: body,
105
+ line: startLine
106
+ });
107
+ continue;
108
+ }
109
+ if (char === "/" && sql[i + 1] === "*") {
110
+ const end = closingComment(i);
111
+ if (end === -1) return {
112
+ tokens,
113
+ comments,
114
+ executable,
115
+ unterminatedAt: startLine
116
+ };
117
+ const inner = advanceTo(end + 2).slice(2, -2);
118
+ comments.push({
119
+ text: inner,
120
+ line: startLine
121
+ });
122
+ const versioned = rules.mysqlComments ? /^M?!\d*/.exec(inner)?.[0] : void 0;
123
+ if (versioned) executable.push({
124
+ text: inner.slice(versioned.length),
125
+ line: startLine
126
+ });
127
+ continue;
128
+ }
129
+ const escapeString = rules.escapeStrings && (char === "E" || char === "e") && sql[i + 1] === "'";
130
+ if (char === "'" || char === "\"" || char === "`" || escapeString) {
131
+ const open = escapeString ? i + 1 : i;
132
+ const quote = sql[open];
133
+ const end = closingQuote(open, quote, escapeString || rules.backslashEscapes && (quote === "'" || quote === "\"" && rules.mysqlComments));
134
+ if (end === -1) return {
135
+ tokens,
136
+ comments,
137
+ executable,
138
+ unterminatedAt: startLine
139
+ };
140
+ const inner = sql.slice(open + 1, end).replaceAll(quote + quote, quote);
141
+ advanceTo(end + 1);
142
+ tokens.push({
143
+ kind: quote === "'" ? "string" : "ident",
144
+ value: inner,
145
+ line: startLine
146
+ });
147
+ continue;
148
+ }
149
+ if (char === "[") {
150
+ const end = sql.indexOf("]", i + 1);
151
+ if (end === -1) return {
152
+ tokens,
153
+ comments,
154
+ executable,
155
+ unterminatedAt: startLine
156
+ };
157
+ const text = advanceTo(end + 1);
158
+ tokens.push({
159
+ kind: "ident",
160
+ value: text.slice(1, -1),
161
+ line: startLine
162
+ });
163
+ continue;
164
+ }
165
+ if (char === "$" && rules.dollarQuotes) {
166
+ const tag = /^\$[A-Za-z_]*\$/.exec(sql.slice(i))?.[0];
167
+ if (tag) {
168
+ const end = sql.indexOf(tag, i + tag.length);
169
+ if (end === -1) return {
170
+ tokens,
171
+ comments,
172
+ executable,
173
+ unterminatedAt: startLine
174
+ };
175
+ const inner = sql.slice(i + tag.length, end);
176
+ advanceTo(end + tag.length);
177
+ tokens.push({
178
+ kind: "body",
179
+ value: inner,
180
+ line: startLine
181
+ });
182
+ continue;
183
+ }
184
+ }
185
+ const word = /^[A-Za-z_][A-Za-z0-9_$]*/.exec(sql.slice(i))?.[0];
186
+ if (word) {
187
+ advanceTo(i + word.length);
188
+ tokens.push({
189
+ kind: "word",
190
+ value: word.toUpperCase(),
191
+ line: startLine
192
+ });
193
+ continue;
194
+ }
195
+ advanceTo(i + 1);
196
+ tokens.push({
197
+ kind: "punct",
198
+ value: char,
199
+ line: startLine
200
+ });
201
+ }
202
+ return {
203
+ tokens,
204
+ comments,
205
+ executable
206
+ };
207
+ }
208
+ function splitStatements(tokens) {
209
+ const statements = [];
210
+ let current = [];
211
+ for (const token of tokens) if (token.kind === "punct" && token.value === ";") {
212
+ if (current.length > 0) statements.push(current);
213
+ current = [];
214
+ } else current.push(token);
215
+ if (current.length > 0) statements.push(current);
216
+ return statements;
217
+ }
218
+ /** Splits at top-level commas, the separator between `ALTER TABLE` actions. */
219
+ function splitTopLevel(tokens) {
220
+ const parts = [];
221
+ let depth = 0;
222
+ let current = [];
223
+ for (const token of tokens) {
224
+ if (token.kind === "punct" && token.value === "(") depth += 1;
225
+ if (token.kind === "punct" && token.value === ")") depth -= 1;
226
+ if (depth === 0 && token.kind === "punct" && token.value === ",") {
227
+ parts.push(current);
228
+ current = [];
229
+ continue;
230
+ }
231
+ current.push(token);
232
+ }
233
+ parts.push(current);
234
+ return parts;
235
+ }
236
+ const isWord = (token, ...values) => token?.kind === "word" && values.includes(token.value);
237
+ function nameValue(token) {
238
+ return token.kind === "word" ? token.value.toLowerCase() : token.value;
239
+ }
240
+ /** Reads `name` or `schema.name` at `start`; undefined when no name is there. */
241
+ function readName(tokens, start) {
242
+ const first = tokens[start];
243
+ if (!first || first.kind === "punct" || first.kind === "body") return void 0;
244
+ let name = nameValue(first);
245
+ let next = start + 1;
246
+ while (tokens[next]?.kind === "punct" && tokens[next].value === "." && tokens[next + 1]) {
247
+ const part = tokens[next + 1];
248
+ if (part.kind === "punct" || part.kind === "body") break;
249
+ name = `${name}.${nameValue(part)}`;
250
+ next += 2;
251
+ }
252
+ return {
253
+ name,
254
+ next
255
+ };
256
+ }
257
+ function skipWords(tokens, start, ...words) {
258
+ let index = start;
259
+ while (isWord(tokens[index], ...words)) index += 1;
260
+ return index;
261
+ }
262
+ const NON_COLUMN_DROPS = [
263
+ "CONSTRAINT",
264
+ "INDEX",
265
+ "KEY",
266
+ "PRIMARY",
267
+ "FOREIGN",
268
+ "CHECK",
269
+ "DEFAULT"
270
+ ];
271
+ /** A type as the SQL spells it: words spaced, punctuation and digits joined, so `varchar ( 50 )` reads `varchar(50)`. */
272
+ function spellType(tokens) {
273
+ let text = "";
274
+ let previousWord = false;
275
+ for (const token of tokens) {
276
+ const word = token.kind === "word" || token.kind === "ident";
277
+ if (word && previousWord) text += " ";
278
+ text += token.kind === "word" ? token.value.toLowerCase() : token.value;
279
+ previousWord = word;
280
+ }
281
+ return text;
282
+ }
283
+ const MODIFY_TYPE_END = [
284
+ "NOT",
285
+ "NULL",
286
+ "DEFAULT",
287
+ "COMMENT",
288
+ "AFTER",
289
+ "FIRST",
290
+ "COLLATE",
291
+ "CHARACTER",
292
+ "CHARSET",
293
+ "AUTO_INCREMENT",
294
+ "ON",
295
+ "PRIMARY",
296
+ "UNIQUE",
297
+ "KEY",
298
+ "REFERENCES",
299
+ "CHECK",
300
+ "GENERATED",
301
+ "AS",
302
+ "VISIBLE",
303
+ "INVISIBLE",
304
+ "SRID",
305
+ "CONSTRAINT"
306
+ ];
307
+ /**
308
+ * The target type of a MySQL `MODIFY`/`CHANGE` definition, or undefined when it
309
+ * also changes a character set or collation, which can lose characters whatever the type.
310
+ */
311
+ function mysqlTargetType(definition) {
312
+ if (definition.some((token) => isWord(token, "CHARACTER", "CHARSET", "COLLATE"))) return void 0;
313
+ const end = definition.findIndex((token) => isWord(token, ...MODIFY_TYPE_END));
314
+ const type = spellType(end === -1 ? definition : definition.slice(0, end));
315
+ return type === "" ? void 0 : type;
316
+ }
317
+ /**
318
+ * The target type of a PostgreSQL `[SET DATA] TYPE t [USING …]`, kept only when
319
+ * the `USING` is absent or the plain cast drizzle-kit writes (`"col"::t`): any
320
+ * other expression rewrites values, which no snapshot can vouch for.
321
+ */
322
+ function postgresTargetType(afterType, column) {
323
+ const usingAt = afterType.findIndex((token) => isWord(token, "USING"));
324
+ if (afterType.some((token) => isWord(token, "COLLATE"))) return void 0;
325
+ const type = spellType(usingAt === -1 ? afterType : afterType.slice(0, usingAt));
326
+ if (type === "") return void 0;
327
+ if (usingAt === -1) return type;
328
+ const using = afterType.slice(usingAt + 1);
329
+ const cast = readName(using, 0);
330
+ if (!cast || cast.name !== column || using[cast.next]?.value !== ":" || using[cast.next + 1]?.value !== ":") return void 0;
331
+ return spellType(using.slice(cast.next + 2)) === type ? type : void 0;
332
+ }
333
+ function scanAlterTable(statement, line) {
334
+ const table = readName(statement, skipWords(statement, 2, "IF", "EXISTS", "ONLY"));
335
+ if (!table) return [{
336
+ kind: "unreadable",
337
+ line,
338
+ message: "alters a table whose name cannot be read, so what it does to it cannot be judged"
339
+ }];
340
+ const findings = [];
341
+ const actions = statement.slice(table.next);
342
+ if (isWord(actions[0], "DROP", "TRUNCATE") && isWord(actions[1], "PARTITION")) {
343
+ const partitions = splitTopLevel(actions.slice(2)).map((part) => readName(part, 0)?.name ?? "?").join(", ");
344
+ return [isWord(actions[0], "DROP") ? {
345
+ kind: "drop-partition",
346
+ line,
347
+ table: table.name,
348
+ message: `drops partition ${partitions} of ${table.name} with its rows`
349
+ } : {
350
+ kind: "truncate",
351
+ line,
352
+ table: table.name,
353
+ message: `empties partition ${partitions} of ${table.name}`
354
+ }];
355
+ }
356
+ for (const action of splitTopLevel(actions)) {
357
+ const [head] = action;
358
+ if (!head) continue;
359
+ if (isWord(head, "DROP") && !isWord(action[1], ...NON_COLUMN_DROPS)) {
360
+ const column = readName(action, skipWords(action, 1, "COLUMN", "IF", "EXISTS"))?.name;
361
+ findings.push({
362
+ kind: "drop-column",
363
+ line,
364
+ table: table.name,
365
+ column,
366
+ message: `drops column ${table.name}.${column ?? "?"}`
367
+ });
368
+ continue;
369
+ }
370
+ if (isWord(head, "ALTER")) {
371
+ const column = readName(action, skipWords(action, 1, "COLUMN"));
372
+ if (!column) continue;
373
+ const rest = action.slice(column.next);
374
+ const typeAt = rest.findIndex((token) => isWord(token, "TYPE"));
375
+ if (typeAt !== -1 && (typeAt === 0 || isWord(rest[typeAt - 1], "DATA"))) {
376
+ const targetType = postgresTargetType(rest.slice(typeAt + 1), column.name);
377
+ findings.push({
378
+ kind: "alter-column-type",
379
+ line,
380
+ table: table.name,
381
+ column: column.name,
382
+ message: `changes the type of ${table.name}.${column.name}`,
383
+ ...targetType ? { targetType } : {}
384
+ });
385
+ }
386
+ continue;
387
+ }
388
+ if (isWord(head, "MODIFY")) {
389
+ const column = readName(action, skipWords(action, 1, "COLUMN"));
390
+ const targetType = column && mysqlTargetType(action.slice(column.next));
391
+ findings.push({
392
+ kind: "alter-column-type",
393
+ line,
394
+ table: table.name,
395
+ column: column?.name,
396
+ message: `changes the type of ${table.name}.${column?.name ?? "?"}`,
397
+ ...targetType ? { targetType } : {}
398
+ });
399
+ continue;
400
+ }
401
+ if (isWord(head, "CHANGE")) {
402
+ const from = readName(action, skipWords(action, 1, "COLUMN"));
403
+ const to = from && readName(action, from.next);
404
+ if (!from || !to || from.name !== to.name) findings.push({
405
+ kind: "rename",
406
+ line,
407
+ table: table.name,
408
+ column: from?.name,
409
+ message: `renames column ${table.name}.${from?.name ?? "?"} to ${to?.name ?? "?"}`
410
+ });
411
+ const targetType = to && mysqlTargetType(action.slice(to.next));
412
+ findings.push({
413
+ kind: "alter-column-type",
414
+ line,
415
+ table: table.name,
416
+ column: to?.name ?? from?.name,
417
+ message: `changes the type of ${table.name}.${from?.name ?? "?"}`,
418
+ ...targetType ? { targetType } : {}
419
+ });
420
+ continue;
421
+ }
422
+ if (isWord(head, "RENAME")) {
423
+ if (isWord(action[1], "INDEX", "KEY", "CONSTRAINT")) continue;
424
+ if (isWord(action[1], "TO", "AS")) {
425
+ const to = readName(action, 2)?.name;
426
+ findings.push({
427
+ kind: "rename",
428
+ line,
429
+ table: table.name,
430
+ message: `renames table ${table.name} to ${to ?? "?"}`,
431
+ renameFrom: table.name,
432
+ renameTo: to
433
+ });
434
+ continue;
435
+ }
436
+ const from = readName(action, skipWords(action, 1, "COLUMN"));
437
+ const to = from && isWord(action[from.next], "TO") ? readName(action, from.next + 1)?.name : void 0;
438
+ findings.push({
439
+ kind: "rename",
440
+ line,
441
+ table: table.name,
442
+ column: from?.name,
443
+ message: `renames column ${table.name}.${from?.name ?? "?"} to ${to ?? "?"}`
444
+ });
445
+ }
446
+ }
447
+ return findings;
448
+ }
449
+ /** Paren depth of each token, `(` and `)` counted at the depth outside them. */
450
+ function depths(tokens) {
451
+ let depth = 0;
452
+ return tokens.map((token) => {
453
+ if (token.kind === "punct" && token.value === ")") depth -= 1;
454
+ const at = depth;
455
+ if (token.kind === "punct" && token.value === "(") depth += 1;
456
+ return at;
457
+ });
458
+ }
459
+ /**
460
+ * Every `DELETE … FROM` in a statement, a CTE's included, judged on the `WHERE`
461
+ * at its own depth, so a subquery's filter is not its filter. A `DELETE` not
462
+ * followed by `FROM` (directly, after MySQL's modifiers, or after MySQL's
463
+ * multi-table target list) is a trigger event or a privilege, not a delete.
464
+ */
465
+ function scanDeletes(tokens) {
466
+ const depth = depths(tokens);
467
+ const findings = [];
468
+ tokens.forEach((token, at) => {
469
+ if (!isWord(token, "DELETE")) return;
470
+ let index = skipWords(tokens, at + 1, "LOW_PRIORITY", "QUICK", "IGNORE");
471
+ let table;
472
+ if (isWord(tokens[index], "FROM")) table = readName(tokens, skipWords(tokens, index + 1, "ONLY"))?.name;
473
+ else {
474
+ const targets = [];
475
+ for (;;) {
476
+ const name = readName(tokens, index);
477
+ if (!name) return;
478
+ targets.push(name.name);
479
+ index = name.next;
480
+ if (tokens[index]?.value === ",") index += 1;
481
+ else break;
482
+ }
483
+ if (!isWord(tokens[index], "FROM")) return;
484
+ table = targets[0];
485
+ }
486
+ for (let next = at + 1; next < tokens.length && depth[next] >= depth[at]; next += 1) if (depth[next] === depth[at] && isWord(tokens[next], "WHERE")) return;
487
+ findings.push({
488
+ kind: "delete-all",
489
+ line: token.line,
490
+ table,
491
+ message: `deletes every row of ${table ?? "?"}`
492
+ });
493
+ });
494
+ return findings;
495
+ }
496
+ const STATEMENT_KEYWORDS = [
497
+ "DROP",
498
+ "ALTER",
499
+ "RENAME",
500
+ "TRUNCATE",
501
+ "CREATE"
502
+ ];
503
+ /** What `DROP` names before the object, for the message; `DROP TABLE`/`SCHEMA`/`DATABASE` are read apart. */
504
+ const DROPPED_OBJECT_WORDS = [
505
+ "MATERIALIZED",
506
+ "FOREIGN",
507
+ "TABLE",
508
+ "VIEW",
509
+ "TYPE",
510
+ "DOMAIN",
511
+ "EXTENSION",
512
+ "SEQUENCE",
513
+ "FUNCTION",
514
+ "PROCEDURE",
515
+ "COLUMN"
516
+ ];
517
+ /** A column's type in `CREATE TABLE x (…)` as the SQL spells it, for each column it can read. */
518
+ function readColumnTypes(statement, open) {
519
+ if (statement[open]?.value !== "(") return void 0;
520
+ const depth = depths(statement);
521
+ const close = statement.findIndex((token, at) => at > open && token.value === ")" && depth[at] === depth[open]);
522
+ if (close === -1) return void 0;
523
+ const types = {};
524
+ for (const part of splitTopLevel(statement.slice(open + 1, close))) {
525
+ if (part.length === 0 || isWord(part[0], "CONSTRAINT", "PRIMARY", "FOREIGN", "UNIQUE", "CHECK")) continue;
526
+ const column = readName(part, 0);
527
+ if (!column) continue;
528
+ const rest = part.slice(column.next);
529
+ const end = rest.findIndex((token) => isWord(token, ...MODIFY_TYPE_END));
530
+ types[column.name] = spellType(end === -1 ? rest : rest.slice(0, end));
531
+ }
532
+ return types;
533
+ }
534
+ /** The statement read from its first DDL keyword, so a `BEGIN` or `IF … THEN` in front hides nothing. */
535
+ function scanDdl(tokens) {
536
+ const start = tokens.findIndex((token, at) => isWord(token, ...STATEMENT_KEYWORDS) && !(isWord(token, "TRUNCATE") && isWord(tokens[at + 1], "ON", "OR")));
537
+ if (start === -1) return { findings: [] };
538
+ const statement = tokens.slice(start);
539
+ const [first, second] = statement;
540
+ const line = first.line;
541
+ if (isWord(first, "DROP") && isWord(second, "TABLE")) return { findings: splitTopLevel(statement.slice(skipWords(statement, 2, "IF", "EXISTS"))).map((part) => {
542
+ const table = readName(part, 0)?.name;
543
+ return {
544
+ kind: "drop-table",
545
+ line,
546
+ table,
547
+ message: `drops table ${table ?? "?"}`
548
+ };
549
+ }) };
550
+ if (isWord(first, "DROP") && isWord(second, "SCHEMA", "DATABASE")) {
551
+ const name = readName(statement, skipWords(statement, 2, "IF", "EXISTS"))?.name;
552
+ return { findings: [{
553
+ kind: "drop-schema",
554
+ line,
555
+ message: `drops ${second.value.toLowerCase()} ${name ?? "?"}`
556
+ }] };
557
+ }
558
+ if (isWord(first, "DROP") && isWord(second, "OWNED")) return { findings: [{
559
+ kind: "drop-cascade",
560
+ line,
561
+ message: "drops every object a role owns (DROP OWNED), tables included"
562
+ }] };
563
+ if (isWord(first, "DROP") && statement.some((token) => isWord(token, "CASCADE"))) {
564
+ const nameAt = skipWords(statement, 1, ...DROPPED_OBJECT_WORDS);
565
+ const what = spellType(statement.slice(1, nameAt));
566
+ const name = readName(statement, skipWords(statement, nameAt, "IF", "EXISTS"))?.name;
567
+ return { findings: [{
568
+ kind: "drop-cascade",
569
+ line,
570
+ message: `drops ${what || "an object"} ${name ?? "?"} with CASCADE, which also drops every column and object depending on it`
571
+ }] };
572
+ }
573
+ if (isWord(first, "ALTER") && isWord(second, "TABLE")) return { findings: scanAlterTable(statement, line) };
574
+ if (isWord(first, "RENAME") && isWord(second, "TABLE")) return { findings: splitTopLevel(statement.slice(2)).map((part) => {
575
+ const from = readName(part, 0);
576
+ const to = from && isWord(part[from.next], "TO") ? readName(part, from.next + 1)?.name : void 0;
577
+ return {
578
+ kind: "rename",
579
+ line,
580
+ table: from?.name,
581
+ message: `renames table ${from?.name ?? "?"} to ${to ?? "?"}`,
582
+ renameFrom: from?.name,
583
+ renameTo: to
584
+ };
585
+ }) };
586
+ if (isWord(first, "TRUNCATE")) return { findings: splitTopLevel(statement.slice(skipWords(statement, 1, "TABLE"))).map((part) => {
587
+ const table = readName(part, skipWords(part, 0, "ONLY"))?.name;
588
+ return {
589
+ kind: "truncate",
590
+ line,
591
+ table,
592
+ message: `empties table ${table ?? "?"}`
593
+ };
594
+ }) };
595
+ if (isWord(first, "CREATE")) {
596
+ const tableAt = skipWords(statement, 1, "TEMP", "TEMPORARY", "UNLOGGED", "VIRTUAL");
597
+ if (isWord(statement[tableAt], "TABLE")) {
598
+ const table = readName(statement, skipWords(statement, tableAt + 1, "IF", "NOT", "EXISTS"));
599
+ return {
600
+ findings: [],
601
+ creates: table?.name,
602
+ columnTypes: table && readColumnTypes(statement, table.next)
603
+ };
604
+ }
605
+ return { findings: scanDdl(statement.slice(1)).findings };
606
+ }
607
+ return { findings: [] };
608
+ }
609
+ function scanStatement(tokens) {
610
+ const ddl = scanDdl(tokens);
611
+ return {
612
+ ...ddl,
613
+ findings: [...ddl.findings, ...scanDeletes(tokens)]
614
+ };
615
+ }
616
+ /** The string literals that are SQL the statement runs: a PostgreSQL function's `AS '…'` or a `DO '…'` body, not a default or a comment. */
617
+ function stringBodies(tokens) {
618
+ const isFunction = isWord(tokens[0], "CREATE") && isWord(tokens[skipWords(tokens, 1, "OR", "REPLACE")], "FUNCTION", "PROCEDURE");
619
+ if (!isFunction && !isWord(tokens[0], "DO")) return [];
620
+ return tokens.filter((token, at) => token.kind === "string" && isWord(tokens[at - 1], isFunction ? "AS" : "DO"));
621
+ }
622
+ /**
623
+ * SQL a statement builds or runs from a value: `EXECUTE 'literal'` and
624
+ * `PREPARE s FROM 'literal'` are read as SQL, anything else (a concatenation,
625
+ * `format()`, a variable) cannot be, and is a finding.
626
+ */
627
+ const BLOCK_STARTS = [
628
+ "BEGIN",
629
+ "THEN",
630
+ "ELSE",
631
+ "LOOP",
632
+ "DO",
633
+ "DECLARE"
634
+ ];
635
+ function scanDynamicSql(tokens, prepared) {
636
+ const findings = [];
637
+ const sql = [];
638
+ const ends = (token) => token === void 0 || token.value === ";" || isWord(token, "USING", "INTO");
639
+ tokens.forEach((token, at) => {
640
+ let source;
641
+ if (!(at === 0 || isWord(tokens[at - 1], ...BLOCK_STARTS))) return;
642
+ if (isWord(token, "EXECUTE") && !isWord(tokens[at + 1], "FUNCTION", "PROCEDURE")) {
643
+ const name = readName(tokens, at + 1);
644
+ if (name && tokens[at + 1]?.kind !== "string" && prepared.has(name.name)) return;
645
+ source = at + 1;
646
+ } else if (isWord(token, "PREPARE")) {
647
+ const name = readName(tokens, at + 1);
648
+ const typesEnd = name && tokens[name.next]?.value === "(" ? tokens.findIndex((each, index) => index > name.next && each.value === ")") : -1;
649
+ if (name && isWord(tokens[typesEnd === -1 ? name.next : typesEnd + 1], "AS")) prepared.add(name.name);
650
+ if (name && isWord(tokens[name.next], "FROM")) {
651
+ source = name.next + 1;
652
+ if (tokens[source]?.kind === "string" && ends(tokens[source + 1])) prepared.add(name.name);
653
+ }
654
+ }
655
+ if (source === void 0) return;
656
+ const literal = tokens[source];
657
+ if (literal?.kind === "string" && ends(tokens[source + 1])) {
658
+ sql.push(literal);
659
+ return;
660
+ }
661
+ findings.push({
662
+ kind: "unreadable",
663
+ line: token.line,
664
+ message: "runs SQL built at run time, which cannot be read before it runs"
665
+ });
666
+ });
667
+ return {
668
+ findings,
669
+ sql
670
+ };
671
+ }
672
+ /** Tables a `REFERENCES` names with an `ON DELETE` that deletes or rewrites the referencing rows. */
673
+ function cascadeTargets(tokens) {
674
+ const targets = [];
675
+ tokens.forEach((token, at) => {
676
+ if (!isWord(token, "REFERENCES")) return;
677
+ const target = readName(tokens, at + 1);
678
+ if (!target) return;
679
+ for (let next = target.next; next < tokens.length && !isWord(tokens[next], "REFERENCES"); next += 1) if (isWord(tokens[next], "ON") && isWord(tokens[next + 1], "DELETE") && isWord(tokens[next + 2], "CASCADE", "SET")) {
680
+ targets.push(target.name);
681
+ return;
682
+ }
683
+ });
684
+ return targets;
685
+ }
686
+ const REBUILD_PREFIX = "__new_";
687
+ function unqualified(name) {
688
+ return name.slice(name.lastIndexOf(".") + 1);
689
+ }
690
+ /** `INSERT INTO a(c1, c2) SELECT c1, c2 FROM b` and nothing else, column for column; undefined otherwise. */
691
+ function readCopy(statement) {
692
+ if (!isWord(statement[0], "INSERT") || !isWord(statement[1], "INTO")) return void 0;
693
+ const into = readName(statement, 2);
694
+ if (!into || statement[into.next]?.value !== "(") return void 0;
695
+ const names = (start, end) => {
696
+ const columns = [];
697
+ let index = start;
698
+ for (;;) {
699
+ const name = readName(statement, index);
700
+ if (!name || name.name.includes(".")) return void 0;
701
+ columns.push(name.name);
702
+ index = name.next;
703
+ if (statement[index]?.value === ",") {
704
+ index += 1;
705
+ continue;
706
+ }
707
+ return end(statement[index]) ? {
708
+ columns,
709
+ next: index + 1
710
+ } : void 0;
711
+ }
712
+ };
713
+ const inserted = names(into.next + 1, (token) => token?.value === ")");
714
+ if (!inserted || !isWord(statement[inserted.next], "SELECT")) return void 0;
715
+ const selected = names(inserted.next + 1, (token) => isWord(token, "FROM"));
716
+ if (!selected) return void 0;
717
+ const from = readName(statement, selected.next);
718
+ if (!from || from.next !== statement.length) return void 0;
719
+ if (inserted.columns.join() !== selected.columns.join()) return void 0;
720
+ return {
721
+ into: into.name,
722
+ from: from.name,
723
+ columns: inserted.columns
724
+ };
725
+ }
726
+ function mentions(statement, table) {
727
+ const name = unqualified(table);
728
+ return statement.some((token) => (token.kind === "word" || token.kind === "ident" || token.kind === "string") && nameValue(token) === name);
729
+ }
730
+ function scanTokens(lexed, rules) {
731
+ const raw = [];
732
+ const creates = [];
733
+ const cascades = [];
734
+ const copies = [];
735
+ const copyTypes = /* @__PURE__ */ new Map();
736
+ const statements = splitStatements(lexed.tokens);
737
+ const prepared = /* @__PURE__ */ new Set();
738
+ const scanNested = (text, line) => {
739
+ const nested = scanTokens(lex(text, rules, line), rules);
740
+ raw.push(...nested.statements);
741
+ cascades.push(...nested.cascadeTargets);
742
+ };
743
+ statements.forEach((statement, index) => {
744
+ const result = scanStatement(statement);
745
+ raw.push(...result.findings.map((finding) => ({
746
+ ...finding,
747
+ statement: index
748
+ })));
749
+ const copy = readCopy(statement);
750
+ if (copy) copies.push({
751
+ ...copy,
752
+ statement: index
753
+ });
754
+ if (result.creates) {
755
+ creates.push({
756
+ table: result.creates,
757
+ line: statement[0].line
758
+ });
759
+ if (result.columnTypes && unqualified(result.creates).startsWith(REBUILD_PREFIX)) copyTypes.set(result.creates, result.columnTypes);
760
+ }
761
+ cascades.push(...cascadeTargets(statement));
762
+ const dynamic = scanDynamicSql(statement, prepared);
763
+ raw.push(...dynamic.findings);
764
+ const bodies = stringBodies(statement);
765
+ for (const token of statement) if (token.kind === "body" || bodies.includes(token) || dynamic.sql.includes(token)) scanNested(token.value, token.line);
766
+ });
767
+ for (const { text, line } of lexed.executable) scanNested(text, line);
768
+ if (lexed.unterminatedAt !== void 0) raw.push({
769
+ kind: "unreadable",
770
+ line: lexed.unterminatedAt,
771
+ message: "opens a string, identifier, comment or $$ body that never closes, so nothing after it can be read"
772
+ });
773
+ const renames = raw.filter((finding) => finding.kind === "rename" && finding.renameFrom && finding.renameTo && unqualified(finding.renameFrom) === `${REBUILD_PREFIX}${unqualified(finding.renameTo)}`);
774
+ const rebuilt = new Set(renames.map((finding) => finding.renameTo));
775
+ /**
776
+ * The copy counts only while nothing but the rebuild's own statements touches
777
+ * the copy, and nothing touches the original between the copy and the drop:
778
+ * a `DELETE FROM __new_x` in between would empty the table that survives.
779
+ */
780
+ const intactCopy = (drop) => {
781
+ const table = drop.table;
782
+ const copyName = `${REBUILD_PREFIX}${unqualified(table)}`;
783
+ const copy = copies.find((entry) => entry.from === table && unqualified(entry.into) === copyName);
784
+ const rename = renames.find((finding) => finding.renameTo === table);
785
+ if (!copy || drop.statement === void 0 || rename?.statement === void 0) return void 0;
786
+ const own = /* @__PURE__ */ new Set([
787
+ copy.statement,
788
+ drop.statement,
789
+ rename.statement
790
+ ]);
791
+ return statements.some((statement, index) => {
792
+ if (own.has(index)) return false;
793
+ if (isWord(statement[0], "CREATE") && creates.some((entry) => entry.line === statement[0].line && unqualified(entry.table) === copyName) && index < copy.statement) return false;
794
+ if (mentions(statement, copyName)) return true;
795
+ return index > copy.statement && index < drop.statement && mentions(statement, table);
796
+ }) ? void 0 : copy;
797
+ };
798
+ const out = [];
799
+ for (const { renameFrom, renameTo, statement: at, ...finding } of raw) {
800
+ if (renameTo && rebuilt.has(renameTo) && renameFrom && unqualified(renameFrom).startsWith(REBUILD_PREFIX)) continue;
801
+ if (finding.kind === "drop-table" && finding.table && rebuilt.has(finding.table)) {
802
+ const copy = intactCopy({
803
+ ...finding,
804
+ statement: at
805
+ });
806
+ const types = copy && copyTypes.get(copy.into);
807
+ out.push({
808
+ ...finding,
809
+ ...copy ? { copiedColumns: copy.columns } : {},
810
+ ...types ? { copiedColumnTypes: types } : {},
811
+ kind: "table-rebuild",
812
+ message: `rebuilds table ${finding.table} (copies rows into ${REBUILD_PREFIX}${unqualified(finding.table)}, drops ${finding.table}, renames the copy)`
813
+ });
814
+ continue;
815
+ }
816
+ out.push(finding);
817
+ }
818
+ return {
819
+ statements: out.sort((a, b) => a.line - b.line),
820
+ creates,
821
+ cascadeTargets: [...new Set(cascades)]
822
+ };
823
+ }
824
+ function readAcknowledgement(comments) {
825
+ for (const comment of comments) {
826
+ const text = comment.text.trim();
827
+ if (!text.startsWith("guren:allow-destructive")) continue;
828
+ const rest = text.slice(23);
829
+ if (rest !== "" && !/^[\s:]/.test(rest)) continue;
830
+ const reason = rest.replace(/^\s*:?\s*/, "").trim();
831
+ return {
832
+ line: comment.line,
833
+ reason: reason === "" ? void 0 : reason
834
+ };
835
+ }
836
+ return null;
837
+ }
838
+ function scanWith(sql, rules) {
839
+ const lexed = lex(sql, rules);
840
+ return {
841
+ ...scanTokens(lexed, rules),
842
+ acknowledged: readAcknowledgement(lexed.comments)
843
+ };
844
+ }
845
+ const findingKey = (statement) => [
846
+ statement.kind,
847
+ statement.line,
848
+ statement.table,
849
+ statement.column
850
+ ].join("\0");
851
+ const evidence = (statement) => JSON.stringify([
852
+ statement.copiedColumns,
853
+ statement.copiedColumnTypes,
854
+ statement.targetType
855
+ ]);
856
+ /**
857
+ * Every destructive statement in one migration file, and its acknowledgement.
858
+ * Every way the dialect's server may read the SQL (each dialect's, when none is
859
+ * named) is taken and merged so that none can hide a statement: every finding
860
+ * counts, while exemption evidence, a create and the marker count only when
861
+ * every reading has them.
862
+ */
863
+ function scanMigrationSql(sql, { dialect } = {}) {
864
+ const candidates = dialect ? LEX_READINGS[dialect] : Object.values(LEX_READINGS).flat();
865
+ const sameRules = (a, b) => JSON.stringify({
866
+ ...a,
867
+ backslashEscapes: false
868
+ }) === JSON.stringify({
869
+ ...b,
870
+ backslashEscapes: false
871
+ });
872
+ const readings = (sql.includes("\\") ? candidates : candidates.filter((rules, at) => candidates.findIndex((other) => sameRules(other, rules)) === at)).map((rules) => scanWith(sql, rules));
873
+ if (readings.length === 1) return readings[0];
874
+ const merged = /* @__PURE__ */ new Map();
875
+ for (const reading of readings) {
876
+ const byKey = /* @__PURE__ */ new Map();
877
+ for (const statement of reading.statements) {
878
+ const key = findingKey(statement);
879
+ const group = byKey.get(key);
880
+ if (group) group.push(statement);
881
+ else byKey.set(key, [statement]);
882
+ }
883
+ for (const [key, found] of byKey) {
884
+ const kept = merged.get(key);
885
+ if (!kept) {
886
+ merged.set(key, found);
887
+ continue;
888
+ }
889
+ const longer = found.length > kept.length ? found : kept;
890
+ const agree = kept.length === found.length && kept.every((statement, at) => evidence(statement) === evidence(found[at]));
891
+ merged.set(key, agree ? kept : longer.map(({ copiedColumns, copiedColumnTypes, targetType, ...rest }) => rest));
892
+ }
893
+ }
894
+ const statements = [...merged.values()].flat();
895
+ const createKey = (entry) => `${entry.table}\u0000${entry.line}`;
896
+ const [first, ...rest] = readings;
897
+ return {
898
+ statements: statements.sort((a, b) => a.line - b.line),
899
+ creates: first.creates.filter((entry) => rest.every((reading) => reading.creates.some((other) => createKey(other) === createKey(entry)))),
900
+ cascadeTargets: [...new Set(readings.flatMap((reading) => reading.cascadeTargets))],
901
+ acknowledged: readings.every((reading) => reading.acknowledged) ? first.acknowledged : null
902
+ };
903
+ }
904
+ const KEY_SEPARATOR = "\0";
905
+ function readSnapshotColumnTypes(snapshot) {
906
+ const ddl = snapshot?.ddl;
907
+ if (!Array.isArray(ddl)) return void 0;
908
+ const types = /* @__PURE__ */ new Map();
909
+ for (const entry of ddl) {
910
+ if (entry?.entityType !== "columns") continue;
911
+ const { schema, table, name, type } = entry;
912
+ if (typeof table !== "string" || typeof name !== "string" || typeof type !== "string") continue;
913
+ types.set([
914
+ typeof schema === "string" ? schema : "",
915
+ table,
916
+ name
917
+ ].join(KEY_SEPARATOR), type);
918
+ }
919
+ return types;
920
+ }
921
+ function readSnapshotForeignKeys(snapshot) {
922
+ const ddl = snapshot?.ddl;
923
+ if (!Array.isArray(ddl)) return void 0;
924
+ return ddl.flatMap((entry) => {
925
+ const { tableTo, onDelete } = entry ?? {};
926
+ if (entry?.entityType !== "fks" || typeof tableTo !== "string") return [];
927
+ return [{
928
+ tableTo,
929
+ onDelete: typeof onDelete === "string" ? onDelete : "CASCADE"
930
+ }];
931
+ });
932
+ }
933
+ /** drizzle-kit's `dialect`, folded onto how the SQL is lexed; undefined for one it does not name. */
934
+ function readSnapshotDialect(snapshot) {
935
+ const dialect = snapshot?.dialect;
936
+ if (dialect === "postgres" || dialect === "postgresql" || dialect === "gel") return "postgres";
937
+ if (dialect === "mysql" || dialect === "singlestore") return "mysql";
938
+ if (dialect === "sqlite" || dialect === "turso") return "sqlite";
939
+ }
940
+ /** The table's key prefixes to try: its own schema when the SQL qualifies it, else PostgreSQL's `public` or no schema. */
941
+ function tablePrefixes(table) {
942
+ const dot = table.lastIndexOf(".");
943
+ if (dot !== -1) return [[
944
+ table.slice(0, dot),
945
+ table.slice(dot + 1),
946
+ ""
947
+ ].join(KEY_SEPARATOR)];
948
+ return [[
949
+ "public",
950
+ table,
951
+ ""
952
+ ].join(KEY_SEPARATOR), [
953
+ "",
954
+ table,
955
+ ""
956
+ ].join(KEY_SEPARATOR)];
957
+ }
958
+ function columnType(types, table, column) {
959
+ for (const prefix of tablePrefixes(table)) {
960
+ const type = types?.get(prefix + column);
961
+ if (type !== void 0) return type;
962
+ }
963
+ }
964
+ function tableColumns(types, table) {
965
+ for (const prefix of tablePrefixes(table)) {
966
+ const columns = [...types].filter(([key]) => key.startsWith(prefix)).map(([key, type]) => [key.slice(prefix.length), type]);
967
+ if (columns.length > 0) return columns;
968
+ }
969
+ return [];
970
+ }
971
+ function parseType(type) {
972
+ let rest = type.trim().toLowerCase().replace(/\s+/g, " ");
973
+ const unsigned = rest.endsWith(" unsigned");
974
+ if (unsigned) rest = rest.slice(0, -9);
975
+ let args = [];
976
+ const open = rest.indexOf("(");
977
+ if (open !== -1) {
978
+ if (!rest.endsWith(")")) return void 0;
979
+ const inner = rest.slice(open + 1, -1);
980
+ if (!/^[\d ,]*$/.test(inner)) return void 0;
981
+ args = inner === "" ? [] : inner.split(",").map((arg) => Number(arg.trim()));
982
+ rest = rest.slice(0, open);
983
+ }
984
+ const base = rest.trim();
985
+ if (!/^[a-z][a-z0-9 ]*$/.test(base) || args.some((arg) => !Number.isInteger(arg))) return void 0;
986
+ return {
987
+ base,
988
+ args,
989
+ unsigned
990
+ };
991
+ }
992
+ const INTEGER_RANK = {
993
+ tinyint: 0,
994
+ smallint: 1,
995
+ int2: 1,
996
+ mediumint: 2,
997
+ integer: 3,
998
+ int: 3,
999
+ int4: 3,
1000
+ bigint: 4,
1001
+ int8: 4
1002
+ };
1003
+ const VARYING = /* @__PURE__ */ new Set(["varchar", "character varying"]);
1004
+ const FIXED = /* @__PURE__ */ new Set(["char", "character"]);
1005
+ const TEXT_RANK = {
1006
+ tinytext: 0,
1007
+ text: 1,
1008
+ mediumtext: 2,
1009
+ longtext: 3
1010
+ };
1011
+ /** Holds any varchar: MySQL caps a varchar at 65,535 bytes, which `text` holds; `tinytext` holds 255. */
1012
+ const HOLDS_ANY_VARCHAR = /* @__PURE__ */ new Set([
1013
+ "text",
1014
+ "mediumtext",
1015
+ "longtext"
1016
+ ]);
1017
+ const NUMERIC = /* @__PURE__ */ new Set(["numeric", "decimal"]);
1018
+ /**
1019
+ * Whether `after` holds every value `before` holds: a closed list, so a pair
1020
+ * it does not name is not widening. Equal types (a MySQL `MODIFY` that only
1021
+ * changes nullability) count, since no value changes.
1022
+ */
1023
+ function isWideningTypeChange(before, after, dialect) {
1024
+ const from = parseType(before);
1025
+ const to = parseType(after);
1026
+ if (!from || !to) return false;
1027
+ if (from.base === to.base && from.unsigned === to.unsigned && from.args.join() === to.args.join()) return true;
1028
+ if (from.unsigned !== to.unsigned) return false;
1029
+ if (from.base in INTEGER_RANK && to.base in INTEGER_RANK && from.args.length === 0) return INTEGER_RANK[to.base] >= INTEGER_RANK[from.base];
1030
+ const fromText = VARYING.has(from.base) || FIXED.has(from.base);
1031
+ if (fromText && HOLDS_ANY_VARCHAR.has(to.base)) return true;
1032
+ if (fromText && VARYING.has(to.base)) {
1033
+ if (to.args.length === 0) return true;
1034
+ return from.args.length === 1 && to.args[0] >= from.args[0];
1035
+ }
1036
+ if (from.base in TEXT_RANK && to.base in TEXT_RANK) return TEXT_RANK[to.base] >= TEXT_RANK[from.base];
1037
+ if (NUMERIC.has(from.base) && NUMERIC.has(to.base)) {
1038
+ const unbounded = dialect === "postgres";
1039
+ if (to.args.length === 0 && unbounded) return true;
1040
+ if (from.args.length === 0 && unbounded) return false;
1041
+ const [fromPrecision, fromScale = 0] = from.args.length === 0 ? [10] : from.args;
1042
+ const [toPrecision, toScale = 0] = to.args.length === 0 ? [10] : to.args;
1043
+ return toScale >= fromScale && toPrecision - toScale >= fromPrecision - fromScale;
1044
+ }
1045
+ if ((from.base === "real" || from.base === "float4") && (to.base === "double precision" || to.base === "float8")) return true;
1046
+ return false;
1047
+ }
1048
+ const DELETING_ACTIONS = /* @__PURE__ */ new Set([
1049
+ "CASCADE",
1050
+ "SET NULL",
1051
+ "SET DEFAULT"
1052
+ ]);
1053
+ /**
1054
+ * Lossless: every column the previous snapshot names is copied to itself, keeping or widening its type in
1055
+ * the copy's own `CREATE TABLE` (a `--custom` migration repeats its predecessor's snapshot, which vouches for nothing),
1056
+ * and, where foreign keys stay on (D1 ignores `PRAGMA foreign_keys=OFF`), no `ON DELETE` fires on the `DROP TABLE`.
1057
+ * drizzle-kit rebuilds a SQLite table for an added default or foreign key, so without this each such edit needs sign-off.
1058
+ */
1059
+ function isLosslessRebuild(statement, source, foreignKeysEnforced) {
1060
+ const before = source.columnTypes?.before;
1061
+ const { table, copiedColumns, copiedColumnTypes } = statement;
1062
+ if (!table || !copiedColumns || !copiedColumnTypes || !before) return false;
1063
+ const previous = tableColumns(before, table);
1064
+ if (previous.length === 0) return false;
1065
+ const copied = new Set(copiedColumns);
1066
+ const kept = previous.every(([column, type]) => {
1067
+ const next = copiedColumnTypes[column];
1068
+ return copied.has(column) && next !== void 0 && isWideningTypeChange(type, next, source.dialect);
1069
+ });
1070
+ if (!kept || !foreignKeysEnforced) return kept;
1071
+ const name = unqualified(table);
1072
+ if (source.scan.cascadeTargets.some((target) => unqualified(target) === name)) return false;
1073
+ return ![...source.foreignKeys?.before ?? [], ...source.foreignKeys?.after ?? []].some((reference) => reference.tableTo === name && DELETING_ACTIONS.has(reference.onDelete.toUpperCase()));
1074
+ }
1075
+ /** Two spellings of one type, compared after `parseType()` normalizes case, spacing and arguments. */
1076
+ function sameType(a, b) {
1077
+ const left = parseType(a);
1078
+ const right = parseType(b);
1079
+ return left !== void 0 && right !== void 0 && left.base === right.base && left.unsigned === right.unsigned && left.args.join() === right.args.join();
1080
+ }
1081
+ /**
1082
+ * A type change is exempt only when the SQL itself converts to the type this
1083
+ * migration's snapshot records, by a plain cast, and the snapshots show that
1084
+ * type holding every value of the previous one. A custom migration repeats its
1085
+ * predecessor's snapshot, so its SQL target never matches a changed type.
1086
+ */
1087
+ function isWideningChange(statement, { columnTypes, dialect }) {
1088
+ if (!statement.table || !statement.column || !statement.targetType) return false;
1089
+ const before = columnType(columnTypes?.before, statement.table, statement.column);
1090
+ const after = columnType(columnTypes?.after, statement.table, statement.column);
1091
+ return before !== void 0 && after !== void 0 && sameType(statement.targetType, after) && isWideningTypeChange(before, after, dialect);
1092
+ }
1093
+ /**
1094
+ * Judges migrations in the order they would be applied. A finding against a
1095
+ * table an earlier statement of the run creates is dropped (a fresh database
1096
+ * loses nothing), and so is a type change the snapshots show widening.
1097
+ */
1098
+ function judgeMigrations(sources, { exemptCreatedInRun = true, foreignKeysEnforced = true } = {}) {
1099
+ const created = /* @__PURE__ */ new Map();
1100
+ const report = {
1101
+ unacknowledged: [],
1102
+ acknowledged: []
1103
+ };
1104
+ sources.forEach((source, index) => {
1105
+ const createdEarlier = (table, line) => {
1106
+ if (!exemptCreatedInRun) return false;
1107
+ const at = table === void 0 ? void 0 : created.get(table);
1108
+ return at !== void 0 && (at.migration < index || at.line < line);
1109
+ };
1110
+ for (const { table, line } of source.scan.creates) if (!created.has(table)) created.set(table, {
1111
+ migration: index,
1112
+ line
1113
+ });
1114
+ const findings = source.scan.statements.filter((statement) => statement.kind === "unreadable" || statement.kind === "drop-schema" || statement.kind === "drop-cascade" || !createdEarlier(statement.table, statement.line)).filter((statement) => statement.kind !== "table-rebuild" || !isLosslessRebuild(statement, source, foreignKeysEnforced)).filter((statement) => statement.kind !== "alter-column-type" || !isWideningChange(statement, source)).map((statement) => ({
1115
+ ...statement,
1116
+ migration: source.name,
1117
+ file: source.file
1118
+ }));
1119
+ if (findings.length === 0) return;
1120
+ if (source.scan.acknowledged) report.acknowledged.push({
1121
+ migration: source.name,
1122
+ file: source.file,
1123
+ reason: source.scan.acknowledged.reason,
1124
+ findings
1125
+ });
1126
+ else report.unacknowledged.push(...findings);
1127
+ });
1128
+ return report;
1129
+ }
1130
+ function readSnapshot(path) {
1131
+ try {
1132
+ return JSON.parse(readFileSync(path, "utf8"));
1133
+ } catch {
1134
+ return;
1135
+ }
1136
+ }
1137
+ /**
1138
+ * Reads `<folder>/<name>/migration.sql` for each name, plus the snapshots a
1139
+ * type change needs. Throws when a migration file cannot be read: a guard that
1140
+ * skipped it would pass exactly the file it could not judge.
1141
+ */
1142
+ function readMigrationSources(migrationsFolder, names, displayFolder = migrationsFolder, { dialect } = {}) {
1143
+ let snapshotsById;
1144
+ const snapshotById = (id) => {
1145
+ if (typeof id !== "string") return void 0;
1146
+ if (!snapshotsById) {
1147
+ snapshotsById = /* @__PURE__ */ new Map();
1148
+ for (const entry of existsSync(migrationsFolder) ? readdirSync(migrationsFolder, { withFileTypes: true }) : []) {
1149
+ if (!entry.isDirectory()) continue;
1150
+ const snapshot = readSnapshot(resolve(migrationsFolder, entry.name, "snapshot.json"));
1151
+ const snapshotId = snapshot?.id;
1152
+ if (typeof snapshotId === "string") snapshotsById.set(snapshotId, snapshot);
1153
+ }
1154
+ }
1155
+ return snapshotsById.get(id);
1156
+ };
1157
+ return names.map((name) => {
1158
+ const path = resolve(migrationsFolder, name, "migration.sql");
1159
+ let sql;
1160
+ try {
1161
+ sql = readFileSync(path, "utf8");
1162
+ } catch (error) {
1163
+ throw new Error(`Cannot read ${path} to check it for destructive statements: ${error.message}`);
1164
+ }
1165
+ let snapshot;
1166
+ const readOwnSnapshot = () => (snapshot ??= { value: readSnapshot(resolve(migrationsFolder, name, "snapshot.json")) }).value;
1167
+ const sourceDialect = dialect ?? readSnapshotDialect(readOwnSnapshot());
1168
+ const scan = scanMigrationSql(sql, { dialect: sourceDialect });
1169
+ const source = {
1170
+ name,
1171
+ file: `${displayFolder.replace(/\/$/, "")}/${name}/migration.sql`,
1172
+ scan,
1173
+ ...sourceDialect ? { dialect: sourceDialect } : {}
1174
+ };
1175
+ if (scan.statements.some((statement) => statement.kind === "alter-column-type" || statement.kind === "table-rebuild")) {
1176
+ const snapshot = readOwnSnapshot();
1177
+ const previousIds = snapshot?.prevIds;
1178
+ const previous = Array.isArray(previousIds) && previousIds.length === 1 ? snapshotById(previousIds[0]) : void 0;
1179
+ source.columnTypes = {
1180
+ after: readSnapshotColumnTypes(snapshot),
1181
+ before: readSnapshotColumnTypes(previous)
1182
+ };
1183
+ source.foreignKeys = {
1184
+ after: readSnapshotForeignKeys(snapshot),
1185
+ before: readSnapshotForeignKeys(previous)
1186
+ };
1187
+ }
1188
+ return source;
1189
+ });
1190
+ }
1191
+ /** One finding as `file:line: message`, the form every guard prints. */
1192
+ function formatDestructiveFinding(finding) {
1193
+ return `${finding.file}:${finding.line}: ${finding.message} (${finding.kind})`;
1194
+ }
1195
+ var DestructiveMigrationError = class extends Error {
1196
+ findings;
1197
+ /** `trackerError`: why the tracker could not be read, kept as the `cause` so a connection failure is not hidden behind the findings. */
1198
+ constructor(findings, pendingKnown = true, trackerError) {
1199
+ super(`Refusing to apply ${findings.length} destructive statement(s) that no migration acknowledges:\n` + (pendingKnown ? "" : ` (${describeTrackerError(trackerError)}, so every local migration was judged, applied ones included)\n`) + findings.map((finding) => ` ${formatDestructiveFinding(finding)}`).join("\n") + `\nReview each one. To apply it, put \`-- ${ALLOW_DESTRUCTIVE_MARKER}: <reason>\` on the first line of its migration.sql, or set ${ALLOW_DESTRUCTIVE_ENV}=1 for one run.`, trackerError === void 0 ? void 0 : { cause: trackerError });
1200
+ this.findings = findings;
1201
+ this.name = "DestructiveMigrationError";
1202
+ }
1203
+ };
1204
+ function describeTrackerError(error) {
1205
+ return `the migration tracker could not be read${error === void 0 ? "" : `: ${error instanceof Error ? error.message : String(error)}`}`;
1206
+ }
1207
+ function displayFolder(folder) {
1208
+ const relativePath = relative(process.cwd(), folder);
1209
+ return relativePath === "" || relativePath.startsWith("..") || isAbsolute(relativePath) ? folder : relativePath.split(sep).join("/");
1210
+ }
1211
+ /**
1212
+ * The boot-path guard: judges the pending migrations before the migrator runs.
1213
+ * `refuse` throws unless `GUREN_ALLOW_DESTRUCTIVE_MIGRATIONS=1`; `warn`, and an
1214
+ * allowed `refuse`, print the findings and return.
1215
+ */
1216
+ function guardPendingMigrations(migrationsFolder, pending, mode, { pendingKnown = true, trackerError, dialect, foreignKeysEnforced } = {}) {
1217
+ if (pending.length === 0) return;
1218
+ const { unacknowledged } = judgeMigrations(readMigrationSources(migrationsFolder, pending, displayFolder(migrationsFolder), { dialect }), {
1219
+ exemptCreatedInRun: pendingKnown,
1220
+ foreignKeysEnforced
1221
+ });
1222
+ if (unacknowledged.length === 0) return;
1223
+ const allowed = process.env[ALLOW_DESTRUCTIVE_ENV] === "1";
1224
+ if (mode === "refuse" && !allowed) throw new DestructiveMigrationError(unacknowledged, pendingKnown, trackerError);
1225
+ const why = allowed ? `${ALLOW_DESTRUCTIVE_ENV}=1 is set` : "pass `destructiveMigrations: 'refuse'` to the database factory to stop at these instead";
1226
+ console.warn(`[guren/orm] Applying ${unacknowledged.length} destructive statement(s) that no migration acknowledges (${why}):\n` + (pendingKnown ? "" : `[guren/orm] (${describeTrackerError(trackerError)}, so every local migration was judged)\n`) + unacknowledged.map((finding) => `[guren/orm] ${formatDestructiveFinding(finding)}`).join("\n"));
1227
+ }
1228
+ //#endregion
1229
+ export { ALLOW_DESTRUCTIVE_ENV, ALLOW_DESTRUCTIVE_MARKER, DestructiveMigrationError, formatDestructiveFinding, guardPendingMigrations, isWideningTypeChange, judgeMigrations, readMigrationSources, readSnapshotColumnTypes, scanMigrationSql };