@voltro/database 0.54.0 → 0.56.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.
package/dist/sql.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, Bt as t, Q as n, Qt as r, St as i, Vt as a, Z as o, Zt as s, _ as c, a as l, c as u, gt as d, i as f, l as p, m, n as h, nt as g, o as _, p as v, r as y, rt as b } from "./frameworkLiveTables-ChVR-C5F.js";
2
- import { Effect as x, Schedule as S } from "effect";
3
- import { createHash as ee } from "node:crypto";
4
- import { createLogger as te } from "@voltro/logger";
5
- import { SqlClient as C } from "@effect/sql";
6
- import { promises as ne } from "node:fs";
7
- import { join as re } from "node:path";
8
- import { pathToFileURL as ie } from "node:url";
1
+ import { $ as e, $t as t, Ht as n, Ut as r, a as i, at as a, c as o, d as s, en as c, et as l, g as u, h as d, i as f, it as p, o as m, r as h, s as g, tt as _, u as v, vt as y, wt as b, y as x } from "./frameworkLiveTables-CwDemhjW.js";
2
+ import { Effect as S, Schedule as C } from "effect";
3
+ import { createHash as w } from "node:crypto";
4
+ import { createLogger as T } from "@voltro/logger";
5
+ import { SqlClient as E } from "@effect/sql";
6
+ import { promises as ee } from "node:fs";
7
+ import { join as te } from "node:path";
8
+ import { pathToFileURL as ne } from "node:url";
9
9
  //#region src/migrations/ddlError.ts
10
- var ae = (e, t, n, r = 400) => {
10
+ var re = (e, t, n, r = 400) => {
11
11
  let i = n, a = i.cause ?? {}, o = (e) => {
12
12
  let t = a[e];
13
13
  return t == null || t === "" ? void 0 : String(t);
@@ -38,21 +38,21 @@ var ae = (e, t, n, r = 400) => {
38
38
  let t = o(e);
39
39
  t !== void 0 && s.push(`db.${e}: ${t}`);
40
40
  }
41
- let c = oe(o("code"));
41
+ let c = ie(o("code"));
42
42
  return c !== void 0 && s.push("", c), s.push(""), s.join("\n");
43
- }, oe = (e) => e === "3F000" ? "remedy: the connection's search_path names a schema that does not exist. Voltro sets it from DB_SCHEMA — create the schema (`CREATE SCHEMA \"<name>\"`) or unset DB_SCHEMA to use the connection default. Voltro creates TABLES, never the schema itself: that is a namespace decision, and inventing one from a typo is how a migration lands somewhere nobody is looking." : void 0, se = (e) => e.unique === !0 && typeof e.where == "string" && e.where.length > 0, ce = (e) => e.replace(/"/g, "`"), le = (e) => typeof e == "string" ? e : e.name ?? String(e), ue = (e, t) => `_ua_${t}_${e}`.slice(0, 64), de = (e, t) => {
44
- if (t !== "mysql" && t !== "mariadb" || !e.appliedIndexes.some(se)) return e;
43
+ }, ie = (e) => e === "3F000" ? "remedy: the connection's search_path names a schema that does not exist. Voltro sets it from DB_SCHEMA — create the schema (`CREATE SCHEMA \"<name>\"`) or unset DB_SCHEMA to use the connection default. Voltro creates TABLES, never the schema itself: that is a namespace decision, and inventing one from a typo is how a migration lands somewhere nobody is looking." : void 0, ae = (e) => e.unique === !0 && typeof e.where == "string" && e.where.length > 0, oe = (e) => e.replace(/"/g, "`"), se = (e) => typeof e == "string" ? e : e.name ?? String(e), ce = (e, t) => `_ua_${t}_${e}`.slice(0, 64), le = (e, t) => {
44
+ if (t !== "mysql" && t !== "mariadb" || !e.appliedIndexes.some(ae)) return e;
45
45
  let n = { ...e.fields }, r = [], i = [];
46
46
  for (let t of e.appliedIndexes) {
47
- if (!se(t)) {
47
+ if (!ae(t)) {
48
48
  r.push(t);
49
49
  continue;
50
50
  }
51
- let a = ce(t.where), o = [];
51
+ let a = oe(t.where), o = [];
52
52
  for (let r of t.fields) {
53
- let i = le(r);
53
+ let i = se(r);
54
54
  if (!(i in e.fields)) throw Error(`@voltro/migrate: uniqueActive '${t.name}' on '${e.tableName}' references unknown column '${i}'.`);
55
- let s = ue(t.name, i);
55
+ let s = ce(t.name, i);
56
56
  o.push(s), n[s] = {
57
57
  type: "text",
58
58
  nullable: !0,
@@ -75,99 +75,99 @@ var ae = (e, t, n, r = 400) => {
75
75
  appliedIndexes: r,
76
76
  appliedUniques: [...e.appliedUniques ?? [], ...i]
77
77
  };
78
- }, w = (e, t) => `${e}::${t}`, fe = (e, t) => {
78
+ }, D = (e, t) => `${e}::${t}`, ue = (e, t) => {
79
79
  let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set(), a = (e) => {
80
80
  n.add(e);
81
81
  let o = [...t(e)].filter((t) => t.target !== e).sort((e, t) => e.column.localeCompare(t.column));
82
- for (let t of o) n.has(t.target) ? i.add(w(e, t.column)) : r.has(t.target) || a(t.target);
82
+ for (let t of o) n.has(t.target) ? i.add(D(e, t.column)) : r.has(t.target) || a(t.target);
83
83
  n.delete(e), r.add(e);
84
84
  };
85
85
  for (let t of [...e].sort()) r.has(t) || a(t);
86
86
  return i;
87
- }, pe = 6322741009312437n, me = (e) => {
87
+ }, de = 6322741009312437n, fe = (e) => {
88
88
  let t = e?.trim();
89
89
  return t === void 0 || t === "" || t === "public" ? void 0 : t;
90
- }, he = (e) => e?.schema === void 0 ? me(process.env.DB_SCHEMA) : me(e.schema), ge = 14695981039346656037n, _e = 1099511628211n, ve = 18446744073709551615n, ye = (e) => {
91
- let t = ge;
92
- for (let n of new TextEncoder().encode(e)) t ^= BigInt(n), t = t * _e & ve;
90
+ }, pe = (e) => e?.schema === void 0 ? fe(process.env.DB_SCHEMA) : fe(e.schema), me = 14695981039346656037n, he = 1099511628211n, ge = 18446744073709551615n, _e = (e) => {
91
+ let t = me;
92
+ for (let n of new TextEncoder().encode(e)) t ^= BigInt(n), t = t * he & ge;
93
93
  return t;
94
- }, be = (e) => {
95
- let t = me(e);
96
- return t === void 0 ? pe : ye(`voltro_migration_lock:${t}`) & 9223372036854775807n;
97
- }, xe = (e) => {
98
- let t = `voltro_migration_${pe.toString(36)}`, n = me(e);
94
+ }, ve = (e) => {
95
+ let t = fe(e);
96
+ return t === void 0 ? de : _e(`voltro_migration_lock:${t}`) & 9223372036854775807n;
97
+ }, ye = (e) => {
98
+ let t = `voltro_migration_${de.toString(36)}`, n = fe(e);
99
99
  if (n === void 0) return t;
100
100
  let r = `${t}_${n}`;
101
- return /^[A-Za-z0-9_]+$/.test(n) && r.length <= 64 ? r : `${t}_h${(ye(`voltro_migration_lock:${n}`) & ve).toString(16)}`;
102
- }, Se = 250, Ce = () => {
101
+ return /^[A-Za-z0-9_]+$/.test(n) && r.length <= 64 ? r : `${t}_h${(_e(`voltro_migration_lock:${n}`) & ge).toString(16)}`;
102
+ }, be = 250, xe = () => {
103
103
  let e = Number(process.env.VOLTRO_MIGRATION_LOCK_TIMEOUT_MS);
104
104
  return Number.isFinite(e) && e > 0 ? e : 3e4;
105
- }, we = (e, t) => x.gen(function* () {
106
- let n = Ce(), r = Date.now();
105
+ }, Se = (e, t) => S.gen(function* () {
106
+ let n = xe(), r = Date.now();
107
107
  for (;;) {
108
108
  if ((yield* e`
109
109
  SELECT pg_try_advisory_lock(${t.toString()}::bigint) AS got`)[0]?.got) return;
110
- Date.now() - r >= n && (yield* x.die(/* @__PURE__ */ Error(`could not acquire the postgres migration advisory lock within ${Math.round(n / 1e3)}s. Another migration is in progress, or a prior boot crashed while holding it. (A crashed process's session-level advisory lock is released once its DB connection closes; if this persists, find + terminate the holder via pg_stat_activity, or raise VOLTRO_MIGRATION_LOCK_TIMEOUT_MS.)`))), yield* x.sleep(`${Se} millis`);
110
+ Date.now() - r >= n && (yield* S.die(/* @__PURE__ */ Error(`could not acquire the postgres migration advisory lock within ${Math.round(n / 1e3)}s. Another migration is in progress, or a prior boot crashed while holding it. (A crashed process's session-level advisory lock is released once its DB connection closes; if this persists, find + terminate the holder via pg_stat_activity, or raise VOLTRO_MIGRATION_LOCK_TIMEOUT_MS.)`))), yield* S.sleep(`${be} millis`);
111
111
  }
112
- }), Te = (e, t) => x.gen(function* () {
112
+ }), Ce = (e, t) => S.gen(function* () {
113
113
  yield* e`SELECT pg_advisory_unlock(${t.toString()}::bigint)`;
114
- }), Ee = 30, De = (e, t) => x.gen(function* () {
114
+ }), we = 30, Te = (e, t) => S.gen(function* () {
115
115
  (yield* e`
116
- SELECT GET_LOCK(${t}, ${Ee}) AS got`)[0]?.got !== 1 && (yield* x.die(/* @__PURE__ */ Error(`could not acquire the migration lock '${t}' within ${Ee}s (another migration is in progress, or a prior one left it held).`)));
117
- }), Oe = (e, t) => x.gen(function* () {
116
+ SELECT GET_LOCK(${t}, ${we}) AS got`)[0]?.got !== 1 && (yield* S.die(/* @__PURE__ */ Error(`could not acquire the migration lock '${t}' within ${we}s (another migration is in progress, or a prior one left it held).`)));
117
+ }), Ee = (e, t) => S.gen(function* () {
118
118
  yield* e`SELECT RELEASE_LOCK(${t})`;
119
- }), ke = 3e4, Ae = (e, t) => x.gen(function* () {
119
+ }), De = 3e4, Oe = (e, t) => S.gen(function* () {
120
120
  let n = yield* e`
121
121
  DECLARE @res int;
122
122
  EXEC @res = sp_getapplock @Resource = ${t}, @LockMode = 'Exclusive',
123
- @LockOwner = 'Session', @LockTimeout = ${ke};
123
+ @LockOwner = 'Session', @LockTimeout = ${De};
124
124
  SELECT @res AS res`;
125
- (n[0]?.res ?? -999) < 0 && (yield* x.die(/* @__PURE__ */ Error(`could not acquire the migration lock '${t}' (sp_getapplock returned ${n[0]?.res ?? "no row"}; another migration is in progress).`)));
126
- }), je = (e, t) => x.gen(function* () {
125
+ (n[0]?.res ?? -999) < 0 && (yield* S.die(/* @__PURE__ */ Error(`could not acquire the migration lock '${t}' (sp_getapplock returned ${n[0]?.res ?? "no row"}; another migration is in progress).`)));
126
+ }), ke = (e, t) => S.gen(function* () {
127
127
  yield* e`EXEC sp_releaseapplock @Resource = ${t}, @LockOwner = 'Session'`;
128
- }), Me = x.void, T = (e, t) => {
129
- let n = he(t);
128
+ }), Ae = S.void, je = (e, t) => {
129
+ let n = pe(t);
130
130
  return e.onDialectOrElse({
131
- mysql: () => De(e, xe(n)),
132
- mssql: () => Ae(e, xe(n)),
133
- sqlite: () => Me,
134
- orElse: () => we(e, be(n))
131
+ mysql: () => Te(e, ye(n)),
132
+ mssql: () => Oe(e, ye(n)),
133
+ sqlite: () => Ae,
134
+ orElse: () => Se(e, ve(n))
135
135
  });
136
- }, E = (e, t) => {
137
- let n = he(t);
136
+ }, O = (e, t) => {
137
+ let n = pe(t);
138
138
  return e.onDialectOrElse({
139
- mysql: () => Oe(e, xe(n)),
140
- mssql: () => je(e, xe(n)),
141
- sqlite: () => Me,
142
- orElse: () => Te(e, be(n))
139
+ mysql: () => Ee(e, ye(n)),
140
+ mssql: () => ke(e, ye(n)),
141
+ sqlite: () => Ae,
142
+ orElse: () => Ce(e, ve(n))
143
143
  });
144
- }, Ne = (e, t, n) => x.acquireUseRelease(T(e, n), () => t, () => E(e, n).pipe(x.orDie)), Pe = (e) => e.onDialectOrElse({
144
+ }, Me = (e, t, n) => S.acquireUseRelease(je(e, n), () => t, () => O(e, n).pipe(S.orDie)), Ne = (e) => e.onDialectOrElse({
145
145
  pg: () => "postgres",
146
146
  mysql: () => "mysql",
147
147
  mssql: () => "mssql",
148
148
  sqlite: () => "sqlite",
149
149
  orElse: () => "sqlite"
150
- }), Fe = {
150
+ }), Pe = {
151
151
  postgres: "plan-transactional",
152
152
  mssql: "plan-transactional",
153
153
  mysql: "per-operation",
154
154
  mariadb: "per-operation",
155
155
  sqlite: "per-operation",
156
156
  turso: "per-operation"
157
- }, Ie = (e) => Fe[e], D = "_voltro_migration_ops", Le = g(D, {
158
- id: t({ prefix: "mop" }),
159
- runId: s(),
160
- planFingerprint: s(),
161
- opIndex: a(),
162
- opKind: s(),
163
- opTarget: s(),
164
- status: s(),
165
- payload: s(),
166
- startedAt: r().nullable(),
167
- appliedAt: r().nullable(),
168
- durationMs: a().nullable(),
169
- createdAt: r().default("now")
170
- }), Re = (e) => {
157
+ }, Fe = (e) => Pe[e], k = "_voltro_migration_ops", Ie = p(k, {
158
+ id: n({ prefix: "mop" }),
159
+ runId: t(),
160
+ planFingerprint: t(),
161
+ opIndex: r(),
162
+ opKind: t(),
163
+ opTarget: t(),
164
+ status: t(),
165
+ payload: t(),
166
+ startedAt: c().nullable(),
167
+ appliedAt: c().nullable(),
168
+ durationMs: r().nullable(),
169
+ createdAt: c().default("now")
170
+ }), Le = (e) => {
171
171
  switch (e.kind) {
172
172
  case "create-table": return /* @__PURE__ */ new Set([
173
173
  `table:${e.table}`,
@@ -194,11 +194,11 @@ var ae = (e, t, n, r = 400) => {
194
194
  case "add-unique-composite":
195
195
  case "drop-unique-composite": return /* @__PURE__ */ new Set([`unique:${e.table}.${e.name}`]);
196
196
  }
197
- }, ze = (e) => [...Re(e)].join(" "), Be = (e, t) => {
198
- let n = Re(t);
199
- for (let t of Re(e)) if (n.has(t)) return !0;
197
+ }, Re = (e) => [...Le(e)].join(" "), ze = (e, t) => {
198
+ let n = Le(t);
199
+ for (let t of Le(e)) if (n.has(t)) return !0;
200
200
  return !1;
201
- }, Ve = (e, t) => e.operations.some((e) => Be(e.op, t)), He = "__voltro_rebuild", Ue = "__shadow", We = "__old", Ge = /* @__PURE__ */ new Set([
201
+ }, Be = (e, t) => e.operations.some((e) => ze(e.op, t)), Ve = "__voltro_rebuild", He = "__shadow", Ue = "__old", We = /* @__PURE__ */ new Set([
202
202
  "add-unique",
203
203
  "drop-unique",
204
204
  "add-unique-composite",
@@ -210,63 +210,63 @@ var ae = (e, t, n, r = 400) => {
210
210
  "alter-column-nullability",
211
211
  "alter-column-type",
212
212
  "alter-column-default"
213
- ]), Ke = /* @__PURE__ */ new Set(["alter-column-default", "alter-column-nullability"]), qe = (e, t, n) => {
213
+ ]), Ge = /* @__PURE__ */ new Set(["alter-column-default", "alter-column-nullability"]), Ke = (e, t, n) => {
214
214
  let r = n === "sqlite" || n === "turso";
215
- return e.kind === "alter-column-type" && t === "online-required" || r && Ge.has(e.kind) ? "artefact-repair" : Ke.has(e.kind) ? "idempotent" : "probe-then-replay";
215
+ return e.kind === "alter-column-type" && t === "online-required" || r && We.has(e.kind) ? "artefact-repair" : Ge.has(e.kind) ? "idempotent" : "probe-then-replay";
216
216
  };
217
- Object.keys(Fe);
217
+ Object.keys(Pe);
218
218
  //#endregion
219
219
  //#region src/migrations/reactiveTriggerName.ts
220
- var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "framework_changes" ? `${Je}${e}` : `${Je}${t}_${e}`, Xe = (e) => e === "framework_changes" ? "framework_notify_change" : `framework_notify_change_${e}`, Ze = "voltro:notify:v2", Qe = te({ scope: "voltro:migrate" }), k = (e) => {
221
- Qe.warn(e.replace(/^\[voltro:migrate\]\s*/, ""));
222
- }, A = (e, t) => {
223
- let r = e.type;
220
+ var A = "framework_changes", qe = "framework_changes_", Je = (e, t) => t === "framework_changes" ? `${qe}${e}` : `${qe}${t}_${e}`, Ye = (e) => e === "framework_changes" ? "framework_notify_change" : `framework_notify_change_${e}`, Xe = "voltro:notify:v2", Ze = T({ scope: "voltro:migrate" }), j = (e) => {
221
+ Ze.warn(e.replace(/^\[voltro:migrate\]\s*/, ""));
222
+ }, M = (e, t) => {
223
+ let n = e.type;
224
224
  if (e.spatial) {
225
225
  if (t === "postgres") return `${e.spatial.kind}(${e.spatial.geomKind},${e.spatial.srid})`;
226
226
  throw Error(`@voltro/plugin-postgis: ${e.spatial.kind}('${e.spatial.geomKind}', ${e.spatial.srid}) is postgres-only — the active dialect is '${t}'. PostGIS has no portable equivalent; use store: 'postgres' (or DB_DIALECT=postgres) for spatial columns, or model the value as plain text/json.`);
227
227
  }
228
- if (r === "raw") {
228
+ if (n === "raw") {
229
229
  if (e.rawDdl === void 0) throw Error("raw() column is missing its DDL fragment — this is a framework bug.");
230
230
  return e.rawDdl;
231
231
  }
232
- if (r === "array" && e.arrayElement) {
233
- if (t === "postgres") return `${A({
232
+ if (n === "array" && e.arrayElement) {
233
+ if (t === "postgres") return `${M({
234
234
  ...e,
235
235
  type: e.arrayElement,
236
236
  arrayElement: void 0
237
237
  }, t)}[]`;
238
238
  if (t === "mysql" || t === "mariadb") return "JSON";
239
239
  if (t === "mssql") return "NVARCHAR(MAX)";
240
- if (n(t)) return "TEXT";
241
- }
242
- if (r === "vector") {
243
- let r = e.vectorDim;
244
- if (r === void 0) throw Error("vector column is missing its dimension — this is a framework bug.");
245
- let i = e.vectorPrecision === "half";
246
- if (t === "postgres") return i ? `HALFVEC(${r})` : `VECTOR(${r})`;
247
- if (t === "mysql" || t === "mariadb") return `VECTOR(${r})`;
240
+ if (l(t)) return "TEXT";
241
+ }
242
+ if (n === "vector") {
243
+ let n = e.vectorDim;
244
+ if (n === void 0) throw Error("vector column is missing its dimension — this is a framework bug.");
245
+ let r = e.vectorPrecision === "half";
246
+ if (t === "postgres") return r ? `HALFVEC(${n})` : `VECTOR(${n})`;
247
+ if (t === "mysql" || t === "mariadb") return `VECTOR(${n})`;
248
248
  if (t === "mssql") return "VARBINARY(MAX)";
249
- if (n(t)) return "BLOB";
249
+ if (l(t)) return "BLOB";
250
250
  }
251
- if (r === "interval") {
251
+ if (n === "interval") {
252
252
  if (t === "postgres") return "INTERVAL";
253
253
  if (t === "mysql" || t === "mariadb" || t === "mssql") return "BIGINT";
254
- if (n(t)) return "INTEGER";
254
+ if (l(t)) return "INTEGER";
255
255
  }
256
- if (r === "decimal") {
257
- let r = e.precision, i = e.scale ?? 0;
258
- if (r === void 0) throw Error("decimal column is missing its precision — this is a framework bug.");
259
- return n(t) ? "NUMERIC" : t === "postgres" ? `NUMERIC(${r}, ${i})` : `DECIMAL(${r}, ${i})`;
256
+ if (n === "decimal") {
257
+ let n = e.precision, r = e.scale ?? 0;
258
+ if (n === void 0) throw Error("decimal column is missing its precision — this is a framework bug.");
259
+ return l(t) ? "NUMERIC" : t === "postgres" ? `NUMERIC(${n}, ${r})` : `DECIMAL(${n}, ${r})`;
260
260
  }
261
- if (r === "bigint") return n(t) ? "INTEGER" : "BIGINT";
262
- if (r === "enum") {
261
+ if (n === "bigint") return l(t) ? "INTEGER" : "BIGINT";
262
+ if (n === "enum") {
263
263
  if (t === "postgres") return e.enumName ?? "TEXT";
264
264
  if (t === "mysql" || t === "mariadb") return `ENUM(${(e.enumValues ?? []).map((e) => `'${e.replace(/'/g, "''")}'`).join(", ")})`;
265
265
  if (t === "mssql") return "NVARCHAR(255)";
266
- if (n(t)) return "TEXT";
266
+ if (l(t)) return "TEXT";
267
267
  }
268
- if (r === "text" && e.maxLength !== void 0 && e.generatedAs === void 0) return t === "mssql" ? `NVARCHAR(${e.maxLength})` : n(t) ? "TEXT" : `VARCHAR(${e.maxLength})`;
269
- if (n(t)) switch (r) {
268
+ if (n === "text" && e.maxLength !== void 0 && e.generatedAs === void 0) return t === "mssql" ? `NVARCHAR(${e.maxLength})` : l(t) ? "TEXT" : `VARCHAR(${e.maxLength})`;
269
+ if (l(t)) switch (n) {
270
270
  case "id": return "TEXT";
271
271
  case "text": return "TEXT";
272
272
  case "integer": return "INTEGER";
@@ -282,7 +282,7 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
282
282
  case "array": return "TEXT";
283
283
  case "interval": return "INTEGER";
284
284
  }
285
- if (t === "mysql" || t === "mariadb") switch (r) {
285
+ if (t === "mysql" || t === "mariadb") switch (n) {
286
286
  case "id": return "VARCHAR(64)";
287
287
  case "text": return e.hasDefault && e.defaultFactory === void 0 || e.oneOf && e.oneOf.length > 0 ? "VARCHAR(255)" : e.generatedAs ? "TEXT" : "LONGTEXT";
288
288
  case "integer": return "INT";
@@ -298,7 +298,7 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
298
298
  case "array": return "JSON";
299
299
  case "interval": return "BIGINT";
300
300
  }
301
- if (t === "mssql") switch (r) {
301
+ if (t === "mssql") switch (n) {
302
302
  case "id": return "NVARCHAR(64)";
303
303
  case "text": return e.hasDefault && e.defaultFactory === void 0 || e.oneOf && e.oneOf.length > 0 ? "NVARCHAR(450)" : "NVARCHAR(MAX)";
304
304
  case "integer": return "INT";
@@ -314,7 +314,7 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
314
314
  case "array": return "NVARCHAR(MAX)";
315
315
  case "interval": return "BIGINT";
316
316
  }
317
- switch (r) {
317
+ switch (n) {
318
318
  case "id": return "TEXT";
319
319
  case "text": return "TEXT";
320
320
  case "integer": return "INTEGER";
@@ -330,22 +330,22 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
330
330
  case "array": return "TEXT[]";
331
331
  case "interval": return "INTERVAL";
332
332
  }
333
- }, $e = (e, t) => {
333
+ }, Qe = (e, t) => {
334
334
  if (!e.hasDefault || e.defaultFactory !== void 0) return null;
335
- let r = e.defaultValue;
336
- return r === "now" ? n(t) ? "DEFAULT CURRENT_TIMESTAMP" : t === "mssql" ? "DEFAULT SYSUTCDATETIME()" : t === "mysql" || t === "mariadb" ? "DEFAULT CURRENT_TIMESTAMP(6)" : "DEFAULT now()" : typeof r == "boolean" ? t === "postgres" ? `DEFAULT ${r}` : `DEFAULT ${+!!r}` : typeof r == "number" ? `DEFAULT ${r}` : typeof r == "string" ? `DEFAULT '${r.replace(/'/g, "''")}'` : Array.isArray(r) ? et(r, e, t) : typeof r == "object" && r ? j(r, t) : null;
337
- }, et = (e, t, n) => {
338
- if (n !== "postgres" || t.type !== "array" || t.arrayElement === void 0) return j(e, n);
339
- let r = A({
335
+ let n = e.defaultValue;
336
+ return n === "now" ? l(t) ? "DEFAULT CURRENT_TIMESTAMP" : t === "mssql" ? "DEFAULT SYSUTCDATETIME()" : t === "mysql" || t === "mariadb" ? "DEFAULT CURRENT_TIMESTAMP(6)" : "DEFAULT now()" : typeof n == "boolean" ? t === "postgres" ? `DEFAULT ${n}` : `DEFAULT ${+!!n}` : typeof n == "number" ? `DEFAULT ${n}` : typeof n == "string" ? `DEFAULT '${n.replace(/'/g, "''")}'` : Array.isArray(n) ? $e(n, e, t) : typeof n == "object" && n ? N(n, t) : null;
337
+ }, $e = (e, t, n) => {
338
+ if (n !== "postgres" || t.type !== "array" || t.arrayElement === void 0) return N(e, n);
339
+ let r = M({
340
340
  ...t,
341
341
  type: t.arrayElement,
342
342
  arrayElement: void 0
343
343
  }, n);
344
344
  return `DEFAULT '{${e.map((e) => typeof e == "number" || typeof e == "boolean" ? String(e) : `"${String(e).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join(",").replace(/'/g, "''")}}'::${r}[]`;
345
- }, j = (e, t) => {
345
+ }, N = (e, t) => {
346
346
  let n = JSON.stringify(e).replace(/'/g, "''");
347
347
  return t === "postgres" ? `DEFAULT '${n}'::jsonb` : t === "mysql" || t === "mariadb" ? `DEFAULT (CONVERT('${n}' USING utf8mb4))` : `DEFAULT '${n}'`;
348
- }, M = (e, t) => {
348
+ }, P = (e, t) => {
349
349
  switch (t) {
350
350
  case "postgres": return `"${e}" BIGSERIAL PRIMARY KEY`;
351
351
  case "mysql":
@@ -354,7 +354,7 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
354
354
  case "sqlite": return `"${e}" INTEGER PRIMARY KEY AUTOINCREMENT`;
355
355
  case "turso": return `"${e}" INTEGER PRIMARY KEY`;
356
356
  }
357
- }, N = (e, t) => {
357
+ }, F = (e, t) => {
358
358
  if (e === "restrict" && t === "mssql") return "NO ACTION";
359
359
  switch (e) {
360
360
  case "cascade": return "CASCADE";
@@ -362,117 +362,117 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
362
362
  case "setNull": return "SET NULL";
363
363
  case "noAction": return "NO ACTION";
364
364
  }
365
- }, tt = (t, n, r) => r === null ? e(t, n) : `${e(r, n)}.${e(t, n)}`, nt = 191, rt = (e, t) => {
365
+ }, et = (e, t, n) => n === null ? _(e, t) : `${_(n, t)}.${_(e, t)}`, tt = 191, nt = (e, t) => {
366
366
  if (!e || t !== "mysql" && t !== "mariadb") return !1;
367
- let n = A(e, t).toUpperCase();
367
+ let n = M(e, t).toUpperCase();
368
368
  return n.endsWith("TEXT") || n.endsWith("BLOB");
369
- }, it = (t, n, r) => {
370
- let i = e(t, r);
371
- if (r !== "mysql" && r !== "mariadb") return i;
372
- let a = n[t];
373
- if (!a) return i;
374
- let o = A(a, r).toUpperCase();
375
- return o.endsWith("TEXT") || o.endsWith("BLOB") ? `${i}(${nt})` : i;
376
- }, at = (e, t) => {
369
+ }, rt = (e, t, n) => {
370
+ let r = _(e, n);
371
+ if (n !== "mysql" && n !== "mariadb") return r;
372
+ let i = t[e];
373
+ if (!i) return r;
374
+ let a = M(i, n).toUpperCase();
375
+ return a.endsWith("TEXT") || a.endsWith("BLOB") ? `${r}(${tt})` : r;
376
+ }, it = (e, t) => {
377
377
  if (!e.generatedAs) return null;
378
378
  let { expr: n, stored: r } = e.generatedAs;
379
- if (t === "postgres") return r || k("[voltro:migrate] generated column requested as VIRTUAL but postgres only supports STORED — promoting"), `GENERATED ALWAYS AS (${n}) STORED`;
379
+ if (t === "postgres") return r || j("[voltro:migrate] generated column requested as VIRTUAL but postgres only supports STORED — promoting"), `GENERATED ALWAYS AS (${n}) STORED`;
380
380
  if (t === "mysql" || t === "mariadb") return `GENERATED ALWAYS AS (${n}) ${r ? "STORED" : "VIRTUAL"}`;
381
381
  if (t === "mssql") return `AS (${n})${r ? " PERSISTED" : ""}`;
382
382
  if (t === "turso") throw Error("@voltro/sql-turso: generated columns (.generatedAs(...)) are not supported — Turso's MVCC mode (journal_mode=experimental_mvcc) rejects them. Drop the generated column, or use the 'sqlite' / 'postgres' dialect for this table.");
383
383
  return `GENERATED ALWAYS AS (${n}) ${r ? "STORED" : "VIRTUAL"}`;
384
- }, ot = (t, r, i, a, s = !1, c = !1) => {
385
- if (r.type === "id" && r.idScheme?.kind === "numeric") return M(t, i);
386
- let l = i === "mssql" && r.type === "text" && !r.generatedAs && r.maxLength === void 0 && a?.has(t) ? "NVARCHAR(450)" : A(r, i), u = [e(t, i), l];
387
- r.type === "id" && !c && u.push("PRIMARY KEY");
388
- let d = at(r, i);
389
- if (d) u.push(d);
384
+ }, at = (t, n, r, i, a = !1, o = !1) => {
385
+ if (n.type === "id" && n.idScheme?.kind === "numeric") return P(t, r);
386
+ let s = r === "mssql" && n.type === "text" && !n.generatedAs && n.maxLength === void 0 && i?.has(t) ? "NVARCHAR(450)" : M(n, r), c = [_(t, r), s];
387
+ n.type === "id" && !o && c.push("PRIMARY KEY");
388
+ let u = it(n, r);
389
+ if (u) c.push(u);
390
390
  else {
391
- r.nullable || u.push("NOT NULL"), r.unique && r.type !== "id" && !rt(r, i) && u.push("UNIQUE");
392
- let e = $e(r, i);
393
- e && u.push(e);
394
- }
395
- if (r.type === "reference" && r.references && !s && !o(i)) {
396
- let t = r.references();
397
- u.push(`REFERENCES ${e(t.tableName, i)} (${e("id", i)})`);
398
- let n = N(r.onDelete ?? "restrict", i);
399
- u.push(`ON DELETE ${n}`);
400
- let a = N(r.refOnUpdate ?? "noAction", i);
401
- a !== "NO ACTION" && u.push(`ON UPDATE ${a}`);
402
- }
403
- if (r.oneOf && r.oneOf.length > 0) {
404
- let n = r.oneOf.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
405
- u.push(`CHECK (${e(t, i)} IN (${n}))`);
406
- }
407
- if (r.checks && r.checks.length > 0) for (let e of r.checks) u.push(`CHECK (${e})`);
408
- if (r.type === "enum" && r.enumValues && r.enumValues.length > 0 && (i === "mssql" || n(i))) {
409
- let n = r.enumValues.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
410
- u.push(`CHECK (${e(t, i)} IN (${n}))`);
411
- }
412
- if (r.type === "json" || r.type === "array") {
413
- let r = e(t, i);
414
- n(i) ? u.push(`CHECK (${r} IS NULL OR json_valid(${r}))`) : i === "mssql" && u.push(`CHECK (${r} IS NULL OR ISJSON(${r}) = 1)`);
415
- }
416
- return u.join(" ");
417
- }, st = (t, n, r = null, i) => {
391
+ n.nullable || c.push("NOT NULL"), n.unique && n.type !== "id" && !nt(n, r) && c.push("UNIQUE");
392
+ let e = Qe(n, r);
393
+ e && c.push(e);
394
+ }
395
+ if (n.type === "reference" && n.references && !a && !e(r)) {
396
+ let e = n.references();
397
+ c.push(`REFERENCES ${_(e.tableName, r)} (${_("id", r)})`);
398
+ let t = F(n.onDelete ?? "restrict", r);
399
+ c.push(`ON DELETE ${t}`);
400
+ let i = F(n.refOnUpdate ?? "noAction", r);
401
+ i !== "NO ACTION" && c.push(`ON UPDATE ${i}`);
402
+ }
403
+ if (n.oneOf && n.oneOf.length > 0) {
404
+ let e = n.oneOf.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
405
+ c.push(`CHECK (${_(t, r)} IN (${e}))`);
406
+ }
407
+ if (n.checks && n.checks.length > 0) for (let e of n.checks) c.push(`CHECK (${e})`);
408
+ if (n.type === "enum" && n.enumValues && n.enumValues.length > 0 && (r === "mssql" || l(r))) {
409
+ let e = n.enumValues.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
410
+ c.push(`CHECK (${_(t, r)} IN (${e}))`);
411
+ }
412
+ if (n.type === "json" || n.type === "array") {
413
+ let e = _(t, r);
414
+ l(r) ? c.push(`CHECK (${e} IS NULL OR json_valid(${e}))`) : r === "mssql" && c.push(`CHECK (${e} IS NULL OR ISJSON(${e}) = 1)`);
415
+ }
416
+ return c.join(" ");
417
+ }, ot = (t, n, r = null, i) => {
418
418
  let a = /* @__PURE__ */ new Set();
419
419
  for (let e of t.appliedIndexes ?? []) for (let t of e.fields) typeof t == "string" && a.add(t);
420
420
  for (let e of t.appliedUniques ?? []) for (let t of e.fields) typeof t == "string" && a.add(t);
421
- let s = t.appliedPrimaryKey ?? [], c = s.length > 0, l = Object.entries(t.fields).map(([e, t]) => ` ${ot(e, t, n, a, i?.has(e) ?? !1, c)}`).join(",\n"), u = (t.appliedUniques ?? []).map((r) => {
422
- let i = r.fields.map((e) => it(e, t.fields, n)).join(", ");
423
- return ` CONSTRAINT ${e(r.name, n)} UNIQUE (${i})`;
424
- }), d = (t.appliedChecks ?? []).map((t) => ` CONSTRAINT ${e(t.name, n)} CHECK (${t.expr})`), f = c ? [` PRIMARY KEY (${s.map((e) => it(e, t.fields, n)).join(", ")})`] : [], p = o(n) ? Object.entries(t.fields).flatMap(([a, o]) => {
425
- if (o.type !== "reference" || !o.references || (i?.has(a) ?? !1)) return [];
426
- let s = o.references(), c = N(o.onDelete ?? "restrict", n), l = N(o.refOnUpdate ?? "noAction", n);
427
- return [` CONSTRAINT ${e(`${t.tableName}_${a}_fkey`, n)} FOREIGN KEY (${e(a, n)}) REFERENCES ${tt(s.tableName, n, r)} (${e("id", n)}) ON DELETE ${c}${l === "NO ACTION" ? "" : ` ON UPDATE ${l}`}`];
428
- }) : [], m = [
429
- ...f,
430
- ...u,
421
+ let o = t.appliedPrimaryKey ?? [], s = o.length > 0, c = Object.entries(t.fields).map(([e, t]) => ` ${at(e, t, n, a, i?.has(e) ?? !1, s)}`).join(",\n"), l = (t.appliedUniques ?? []).map((e) => {
422
+ let r = e.fields.map((e) => rt(e, t.fields, n)).join(", ");
423
+ return ` CONSTRAINT ${_(e.name, n)} UNIQUE (${r})`;
424
+ }), u = (t.appliedChecks ?? []).map((e) => ` CONSTRAINT ${_(e.name, n)} CHECK (${e.expr})`), d = s ? [` PRIMARY KEY (${o.map((e) => rt(e, t.fields, n)).join(", ")})`] : [], f = e(n) ? Object.entries(t.fields).flatMap(([e, a]) => {
425
+ if (a.type !== "reference" || !a.references || (i?.has(e) ?? !1)) return [];
426
+ let o = a.references(), s = F(a.onDelete ?? "restrict", n), c = F(a.refOnUpdate ?? "noAction", n);
427
+ return [` CONSTRAINT ${_(`${t.tableName}_${e}_fkey`, n)} FOREIGN KEY (${_(e, n)}) REFERENCES ${et(o.tableName, n, r)} (${_("id", n)}) ON DELETE ${s}${c === "NO ACTION" ? "" : ` ON UPDATE ${c}`}`];
428
+ }) : [], p = [
431
429
  ...d,
432
- ...p
433
- ], h = m.length > 0 ? `${l},\n${m.join(",\n")}` : l, g = tt(t.tableName, n, r);
430
+ ...l,
431
+ ...u,
432
+ ...f
433
+ ], m = p.length > 0 ? `${c},\n${p.join(",\n")}` : c, h = et(t.tableName, n, r);
434
434
  if (n === "mssql") {
435
- let e = r === null ? t.tableName : `${r}.${t.tableName}`, n = `CREATE TABLE ${g} (\n${h}\n)`;
435
+ let e = r === null ? t.tableName : `${r}.${t.tableName}`, n = `CREATE TABLE ${h} (\n${m}\n)`;
436
436
  return `IF OBJECT_ID('${e.replace(/'/g, "''")}', 'U') IS NULL EXEC(N'${n.replace(/'/g, "''")}');`;
437
437
  }
438
438
  return [
439
- `CREATE TABLE IF NOT EXISTS ${g} (`,
440
- h,
439
+ `CREATE TABLE IF NOT EXISTS ${h} (`,
440
+ m,
441
441
  ");"
442
442
  ].join("\n");
443
- }, ct = (t, n, r) => {
444
- let i = `${t}_${n.name}_fts`, a = (t) => e(t, r), o = n.columns.map(a).join(", "), s = n.columns.map((e) => `new.${a(e)}`).join(", "), c = [];
445
- return c.push(`CREATE VIRTUAL TABLE IF NOT EXISTS ${a(i)} USING fts5(${o}, row_id UNINDEXED, tokenize='porter');`), c.push(`CREATE TRIGGER IF NOT EXISTS ${a(`${i}_ai`)} AFTER INSERT ON ${a(t)} BEGIN\n INSERT INTO ${a(i)} (${o}, row_id) VALUES (${s}, new.${a("id")});\nEND;`), c.push(`CREATE TRIGGER IF NOT EXISTS ${a(`${i}_ad`)} AFTER DELETE ON ${a(t)} BEGIN\n DELETE FROM ${a(i)} WHERE row_id = old.${a("id")};\nEND;`), c.push(`CREATE TRIGGER IF NOT EXISTS ${a(`${i}_au`)} AFTER UPDATE ON ${a(t)} BEGIN\n DELETE FROM ${a(i)} WHERE row_id = old.${a("id")};\n INSERT INTO ${a(i)} (${o}, row_id) VALUES (${s}, new.${a("id")});\nEND;`), c;
446
- }, lt = (t, n, r = null) => {
447
- let i = [], a = /* @__PURE__ */ new Set(), o = (e) => e.join("\0"), s = (e, t, r, i) => {
448
- let a = {
443
+ }, st = (e, t, n) => {
444
+ let r = `${e}_${t.name}_fts`, i = (e) => _(e, n), a = t.columns.map(i).join(", "), o = t.columns.map((e) => `new.${i(e)}`).join(", "), s = [];
445
+ return s.push(`CREATE VIRTUAL TABLE IF NOT EXISTS ${i(r)} USING fts5(${a}, row_id UNINDEXED, tokenize='porter');`), s.push(`CREATE TRIGGER IF NOT EXISTS ${i(`${r}_ai`)} AFTER INSERT ON ${i(e)} BEGIN\n INSERT INTO ${i(r)} (${a}, row_id) VALUES (${o}, new.${i("id")});\nEND;`), s.push(`CREATE TRIGGER IF NOT EXISTS ${i(`${r}_ad`)} AFTER DELETE ON ${i(e)} BEGIN\n DELETE FROM ${i(r)} WHERE row_id = old.${i("id")};\nEND;`), s.push(`CREATE TRIGGER IF NOT EXISTS ${i(`${r}_au`)} AFTER UPDATE ON ${i(e)} BEGIN\n DELETE FROM ${i(r)} WHERE row_id = old.${i("id")};\n INSERT INTO ${i(r)} (${a}, row_id) VALUES (${o}, new.${i("id")});\nEND;`), s;
446
+ }, ct = (e, t, n = null) => {
447
+ let r = [], i = /* @__PURE__ */ new Set(), o = (e) => e.join("\0"), s = (e, n, r, i) => {
448
+ let o = {
449
449
  using: "",
450
450
  withSuffix: "",
451
451
  skip: !1
452
452
  };
453
- if (r === void 0 || r === "btree") return a;
454
- if (r === "gist") return n === "postgres" ? {
453
+ if (r === void 0 || r === "btree") return o;
454
+ if (r === "gist") return t === "postgres" ? {
455
455
  using: " USING GIST",
456
456
  withSuffix: "",
457
457
  skip: !1
458
- } : (k(`[voltro:migrate] index '${e}' on '${t}': ${n} doesn't support GiST — falling back to btree. Spatial queries on this column will fall back to sequential scan.`), a);
459
- if (r === "gin") return n === "postgres" ? {
458
+ } : (j(`[voltro:migrate] index '${e}' on '${n}': ${t} doesn't support GiST — falling back to btree. Spatial queries on this column will fall back to sequential scan.`), o);
459
+ if (r === "gin") return t === "postgres" ? {
460
460
  using: " USING GIN",
461
461
  withSuffix: "",
462
462
  skip: !1
463
- } : n === "mysql" || n === "mariadb" ? (k(`[voltro:migrate] gin index '${e}' on '${t}': ${n} has no GIN access method — skipping (a btree on a JSON/array column can't serve containment/membership queries). Add a generated column for the specific path you query, then index that with .expressionIndex(...).`), {
463
+ } : t === "mysql" || t === "mariadb" ? (j(`[voltro:migrate] gin index '${e}' on '${n}': ${t} has no GIN access method — skipping (a btree on a JSON/array column can't serve containment/membership queries). Add a generated column for the specific path you query, then index that with .expressionIndex(...).`), {
464
464
  using: "",
465
465
  withSuffix: "",
466
466
  skip: !0
467
- }) : (k(`[voltro:migrate] gin index '${e}' on '${t}': ${n} has no GIN access method — falling back to btree. Containment/membership queries won't use this index efficiently.`), a);
468
- if (r === "brin") return n === "postgres" ? {
467
+ }) : (j(`[voltro:migrate] gin index '${e}' on '${n}': ${t} has no GIN access method — falling back to btree. Containment/membership queries won't use this index efficiently.`), o);
468
+ if (r === "brin") return t === "postgres" ? {
469
469
  using: " USING BRIN",
470
470
  withSuffix: "",
471
471
  skip: !1
472
- } : (k(`[voltro:migrate] brin index '${e}' on '${t}': ${n} has no BRIN access method — falling back to btree (larger on disk, but the range scan still works).`), a);
472
+ } : (j(`[voltro:migrate] brin index '${e}' on '${n}': ${t} has no BRIN access method — falling back to btree (larger on disk, but the range scan still works).`), o);
473
473
  if (r === "hnsw") {
474
- if (n === "postgres") {
475
- let e = i?.hnsw?.m ?? 16, t = i?.hnsw?.efConstruction ?? 64, n = i?.hnsw?.opclass ?? b(i?.hnsw?.distance);
474
+ if (t === "postgres") {
475
+ let e = i?.hnsw?.m ?? 16, t = i?.hnsw?.efConstruction ?? 64, n = i?.hnsw?.opclass ?? a(i?.hnsw?.distance);
476
476
  return {
477
477
  using: " USING hnsw",
478
478
  withSuffix: ` WITH (m = ${e}, ef_construction = ${t})`,
@@ -480,73 +480,73 @@ var O = "framework_changes", Je = "framework_changes_", Ye = (e, t) => t === "fr
480
480
  skip: !1
481
481
  };
482
482
  }
483
- return k(`[voltro:migrate] hnsw index '${e}' on '${t}': ${n} has no pgvector / HNSW access method — skipping. Nearest-neighbour queries on this column fall back to a sequential scan.`), {
483
+ return j(`[voltro:migrate] hnsw index '${e}' on '${n}': ${t} has no pgvector / HNSW access method — skipping. Nearest-neighbour queries on this column fall back to a sequential scan.`), {
484
484
  using: "",
485
485
  withSuffix: "",
486
486
  skip: !0
487
487
  };
488
488
  }
489
- return a;
490
- }, c = (e, r) => {
491
- let i = e.map((e) => {
492
- if (typeof e == "string") return it(e, t.fields, n);
493
- if ("jsonPath" in e) {
494
- let { column: t, path: r, numeric: i } = e.jsonPath;
495
- return `(${v(t, r, n, { numeric: i })})`;
489
+ return o;
490
+ }, c = (n, r) => {
491
+ let i = n.map((n) => {
492
+ if (typeof n == "string") return rt(n, e.fields, t);
493
+ if ("jsonPath" in n) {
494
+ let { column: e, path: r, numeric: i } = n.jsonPath;
495
+ return `(${d(e, r, t, { numeric: i })})`;
496
496
  }
497
- return `(${e.expr})`;
497
+ return `(${n.expr})`;
498
498
  });
499
499
  return r !== void 0 && i.length === 1 ? `${i[0]} ${r}` : i.join(", ");
500
- }, l = (t, i, a, o, l, u = "", d = !1) => {
501
- let f = s(t, i, o, l);
502
- if (f.skip) return "";
503
- let p = c(a, f.opclass), m = `${f.withSuffix}${u}`, h = tt(i, n, r), g = d ? "UNIQUE " : "";
504
- return n === "mssql" ? `IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = '${t}') CREATE ${g}INDEX ${e(t, n)} ON ${h}${f.using} (${p})${m};` : n === "mysql" ? `CREATE ${g}INDEX ${e(t, n)} ON ${h}${f.using} (${p})${m};` : `CREATE ${g}INDEX IF NOT EXISTS ${e(t, n)} ON ${h}${f.using} (${p})${m};`;
500
+ }, l = (e, r, i, a, o, l = "", u = !1) => {
501
+ let d = s(e, r, a, o);
502
+ if (d.skip) return "";
503
+ let f = c(i, d.opclass), p = `${d.withSuffix}${l}`, m = et(r, t, n), h = u ? "UNIQUE " : "";
504
+ return t === "mssql" ? `IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = '${e}') CREATE ${h}INDEX ${_(e, t)} ON ${m}${d.using} (${f})${p};` : t === "mysql" ? `CREATE ${h}INDEX ${_(e, t)} ON ${m}${d.using} (${f})${p};` : `CREATE ${h}INDEX IF NOT EXISTS ${_(e, t)} ON ${m}${d.using} (${f})${p};`;
505
505
  };
506
- if (n === "mysql" || n === "mariadb") for (let [e, r] of Object.entries(t.fields)) {
507
- if (!r.unique || r.type === "id" || !rt(r, n)) continue;
508
- let a = l(`${t.tableName}_${e}_key`, t.tableName, [e], void 0, void 0, "", !0);
509
- a && i.push(a);
510
- }
511
- for (let r of t.appliedFullText ?? []) if (n === "postgres") {
512
- let a = r.config ?? "english", o = `${r.name}_tsv`, s = r.columns.map((t) => {
513
- let i = r.weights?.[t] ?? "A";
514
- return `setweight(to_tsvector('${a}', coalesce(${e(t, n)}, '')), '${i}')`;
506
+ if (t === "mysql" || t === "mariadb") for (let [n, i] of Object.entries(e.fields)) {
507
+ if (!i.unique || i.type === "id" || !nt(i, t)) continue;
508
+ let a = l(`${e.tableName}_${n}_key`, e.tableName, [n], void 0, void 0, "", !0);
509
+ a && r.push(a);
510
+ }
511
+ for (let n of e.appliedFullText ?? []) if (t === "postgres") {
512
+ let i = n.config ?? "english", a = `${n.name}_tsv`, o = n.columns.map((e) => {
513
+ let r = n.weights?.[e] ?? "A";
514
+ return `setweight(to_tsvector('${i}', coalesce(${_(e, t)}, '')), '${r}')`;
515
515
  }).join(" || ");
516
- i.push(`ALTER TABLE ${e(t.tableName, n)} ADD COLUMN IF NOT EXISTS ${e(o, n)} tsvector GENERATED ALWAYS AS (${s}) STORED;`), i.push(`CREATE INDEX IF NOT EXISTS ${e(r.name, n)} ON ${e(t.tableName, n)} USING GIN (${e(o, n)});`);
517
- } else if (n === "mysql" || n === "mariadb") {
518
- let a = r.columns.map((t) => e(t, n)).join(", ");
519
- i.push(`CREATE FULLTEXT INDEX ${e(r.name, n)} ON ${e(t.tableName, n)} (${a});`);
520
- } else if (n === "turso") throw Error(`@voltro/sql-turso: full-text index '${r.name}' on '${t.tableName}' is not supported — Turso's MVCC mode has no FTS5 virtual tables. Drop .fullTextIndex(), or use the 'sqlite' / 'postgres' dialect for this table.`);
521
- else n === "sqlite" ? i.push(...ct(t.tableName, r, n)) : k(`[voltro:migrate] full-text index '${r.name}' on '${t.tableName}': ${n} uses a ranked LIKE search at query time (no native FTS catalog required).`);
522
- for (let e of t.appliedIndexes) {
523
- if ((n === "mariadb" || n === "mssql") && e.fields.some((e) => typeof e != "string" && "jsonPath" in e)) {
524
- k(`[voltro:migrate] json-path index '${e.name}' on '${t.tableName}': ${n} cannot index a JSON expression directly — skipping. For an indexed JSON path on ${n}, add a generated column for the path (text().generatedAs(...) / .stored()) and .index([...]) it, then filter on that column instead of jsonField(...).`);
516
+ r.push(`ALTER TABLE ${_(e.tableName, t)} ADD COLUMN IF NOT EXISTS ${_(a, t)} tsvector GENERATED ALWAYS AS (${o}) STORED;`), r.push(`CREATE INDEX IF NOT EXISTS ${_(n.name, t)} ON ${_(e.tableName, t)} USING GIN (${_(a, t)});`);
517
+ } else if (t === "mysql" || t === "mariadb") {
518
+ let i = n.columns.map((e) => _(e, t)).join(", ");
519
+ r.push(`CREATE FULLTEXT INDEX ${_(n.name, t)} ON ${_(e.tableName, t)} (${i});`);
520
+ } else if (t === "turso") throw Error(`@voltro/sql-turso: full-text index '${n.name}' on '${e.tableName}' is not supported — Turso's MVCC mode has no FTS5 virtual tables. Drop .fullTextIndex(), or use the 'sqlite' / 'postgres' dialect for this table.`);
521
+ else t === "sqlite" ? r.push(...st(e.tableName, n, t)) : j(`[voltro:migrate] full-text index '${n.name}' on '${e.tableName}': ${t} uses a ranked LIKE search at query time (no native FTS catalog required).`);
522
+ for (let n of e.appliedIndexes) {
523
+ if ((t === "mariadb" || t === "mssql") && n.fields.some((e) => typeof e != "string" && "jsonPath" in e)) {
524
+ j(`[voltro:migrate] json-path index '${n.name}' on '${e.tableName}': ${t} cannot index a JSON expression directly — skipping. For an indexed JSON path on ${t}, add a generated column for the path (text().generatedAs(...) / .stored()) and .index([...]) it, then filter on that column instead of jsonField(...).`);
525
525
  continue;
526
526
  }
527
- if (e.unique && e.where !== void 0 && e.where.length > 0 && (n === "mysql" || n === "mariadb")) throw Error(`@voltro/migrate: uniqueActive index '${e.name}' on '${t.tableName}' cannot be expressed on ${n} — it has no partial (WHERE) index support, and a full UNIQUE index would forbid re-creating a soft-deleted row. Use a generated STORED column (text().generatedAs("CASE WHEN \`deletedAt\` IS NULL THEN <key> ELSE NULL END", { stored: true })) + .unique([...]) on ${n}, or move this table to postgres/sqlite/mssql.`);
528
- let r = "";
529
- e.where !== void 0 && e.where.length > 0 && (n === "mysql" || n === "mariadb" ? k(`[voltro:migrate] partial index '${e.name}' on '${t.tableName}': ${n} does not support WHERE clauses on indexes — emitting a full index`) : r = ` WHERE ${e.where}`);
530
- let s = l(e.name, t.tableName, e.fields, e.kind, e.kindOptions, r, e.unique === !0);
531
- s !== "" && i.push(s), e.fields.every((e) => typeof e == "string") && a.add(o(e.fields));
532
- }
533
- for (let [e, n] of Object.entries(t.fields)) {
534
- if (n.type !== "reference" || n.fkAutoIndex === !1 || a.has(o([e]))) continue;
535
- let r = `${t.tableName}_${e}_idx`;
536
- i.push(l(r, t.tableName, [e])), a.add(o([e]));
537
- }
538
- return i.join("\n");
539
- }, ut = (e, t, n = O) => {
527
+ if (n.unique && n.where !== void 0 && n.where.length > 0 && (t === "mysql" || t === "mariadb")) throw Error(`@voltro/migrate: uniqueActive index '${n.name}' on '${e.tableName}' cannot be expressed on ${t} — it has no partial (WHERE) index support, and a full UNIQUE index would forbid re-creating a soft-deleted row. Use a generated STORED column (text().generatedAs("CASE WHEN \`deletedAt\` IS NULL THEN <key> ELSE NULL END", { stored: true })) + .unique([...]) on ${t}, or move this table to postgres/sqlite/mssql.`);
528
+ let a = "";
529
+ n.where !== void 0 && n.where.length > 0 && (t === "mysql" || t === "mariadb" ? j(`[voltro:migrate] partial index '${n.name}' on '${e.tableName}': ${t} does not support WHERE clauses on indexes — emitting a full index`) : a = ` WHERE ${n.where}`);
530
+ let s = l(n.name, e.tableName, n.fields, n.kind, n.kindOptions, a, n.unique === !0);
531
+ s !== "" && r.push(s), n.fields.every((e) => typeof e == "string") && i.add(o(n.fields));
532
+ }
533
+ for (let [t, n] of Object.entries(e.fields)) {
534
+ if (n.type !== "reference" || n.fkAutoIndex === !1 || i.has(o([t]))) continue;
535
+ let a = `${e.tableName}_${t}_idx`;
536
+ r.push(l(a, e.tableName, [t])), i.add(o([t]));
537
+ }
538
+ return r.join("\n");
539
+ }, lt = (e, t, n = A) => {
540
540
  if (t !== "postgres") return [];
541
541
  let r = e.filter((e) => e.isReactive !== !1);
542
- return r.length === 0 ? [] : [dt(n), ...r.map((e) => pt(e, n))];
543
- }, dt = (e) => `
544
- CREATE OR REPLACE FUNCTION ${Xe(e)}() RETURNS trigger AS $$
542
+ return r.length === 0 ? [] : [ut(n), ...r.map((e) => ft(e, n))];
543
+ }, ut = (e) => `
544
+ CREATE OR REPLACE FUNCTION ${Ye(e)}() RETURNS trigger AS $$
545
545
  DECLARE
546
546
  payload TEXT;
547
547
  pk JSONB;
548
548
  BEGIN
549
- -- ${Ze}
549
+ -- ${Xe}
550
550
  payload := json_build_object(
551
551
  'table', TG_TABLE_NAME,
552
552
  -- The schema the write landed in. Under namespace isolation this is
@@ -600,22 +600,22 @@ BEGIN
600
600
  RETURN COALESCE(NEW, OLD);
601
601
  END;
602
602
  $$ LANGUAGE plpgsql;
603
- `.trim(), ft = (e, t) => {
604
- let n = Ye(e.tableName, t);
603
+ `.trim(), dt = (e, t) => {
604
+ let n = Je(e.tableName, t);
605
605
  return [
606
606
  `ALTER TABLE "${e.tableName}" REPLICA IDENTITY FULL`,
607
607
  `DROP TRIGGER IF EXISTS ${n} ON "${e.tableName}"`,
608
- `CREATE TRIGGER ${n}\nAFTER INSERT OR UPDATE OR DELETE ON "${e.tableName}"\nFOR EACH ROW EXECUTE FUNCTION ${Xe(t)}()`
608
+ `CREATE TRIGGER ${n}\nAFTER INSERT OR UPDATE OR DELETE ON "${e.tableName}"\nFOR EACH ROW EXECUTE FUNCTION ${Ye(t)}()`
609
609
  ];
610
- }, pt = (e, t) => ft(e, t).map((e) => `${e};`).join("\n"), mt = (e) => {
610
+ }, ft = (e, t) => dt(e, t).map((e) => `${e};`).join("\n"), pt = (e) => {
611
611
  if (e.dialect !== "postgres") return [];
612
612
  let t = e.channel ?? "framework_changes", n = new Map(e.tables.map((e) => [e.tableName, e])), r = [], i = e.missing.filter((e) => n.has(e));
613
- (i.length > 0 || e.functionOutdated === !0) && r.push(dt(t));
614
- for (let e of i) r.push(...ft(n.get(e), t));
615
- for (let n of e.stale) r.push(`DROP TRIGGER IF EXISTS ${Ye(n, t)} ON "${n}"`), r.push(`ALTER TABLE "${n}" REPLICA IDENTITY DEFAULT`);
613
+ (i.length > 0 || e.functionOutdated === !0) && r.push(ut(t));
614
+ for (let e of i) r.push(...dt(n.get(e), t));
615
+ for (let n of e.stale) r.push(`DROP TRIGGER IF EXISTS ${Je(n, t)} ON "${n}"`), r.push(`ALTER TABLE "${n}" REPLICA IDENTITY DEFAULT`);
616
616
  return r;
617
- }, ht = (e) => e.some((e) => Object.values(e.fields).some((e) => e.type === "vector")), gt = (e) => e.some((e) => Object.values(e.fields).some((e) => e.spatial !== void 0)), _t = (e) => {
618
- let t = new Map(e.map((e) => [e.tableName, e])), n = fe(e.map((e) => e.tableName), (e) => {
617
+ }, mt = (e) => e.some((e) => Object.values(e.fields).some((e) => e.type === "vector")), ht = (e) => e.some((e) => Object.values(e.fields).some((e) => e.spatial !== void 0)), gt = (e) => {
618
+ let t = new Map(e.map((e) => [e.tableName, e])), n = ue(e.map((e) => e.tableName), (e) => {
619
619
  let n = t.get(e);
620
620
  return n ? Object.entries(n.fields).flatMap(([e, n]) => {
621
621
  if (n.type !== "reference" || !n.references) return [];
@@ -626,7 +626,7 @@ $$ LANGUAGE plpgsql;
626
626
  }] : [];
627
627
  }) : [];
628
628
  }), r = [];
629
- for (let t of e) for (let [e, i] of Object.entries(t.fields)) i.type !== "reference" || !i.references || n.has(w(t.tableName, e)) && r.push({
629
+ for (let t of e) for (let [e, i] of Object.entries(t.fields)) i.type !== "reference" || !i.references || n.has(D(t.tableName, e)) && r.push({
630
630
  table: t.tableName,
631
631
  column: e,
632
632
  targetTable: i.references().tableName,
@@ -637,7 +637,7 @@ $$ LANGUAGE plpgsql;
637
637
  if (!(i.has(e.tableName) || a.has(e.tableName))) {
638
638
  a.add(e.tableName);
639
639
  for (let [r, i] of Object.entries(e.fields)) {
640
- if (i.type !== "reference" || !i.references || n.has(w(e.tableName, r))) continue;
640
+ if (i.type !== "reference" || !i.references || n.has(D(e.tableName, r))) continue;
641
641
  let a = i.references();
642
642
  if (a.tableName === e.tableName) continue;
643
643
  let o = t.get(a.tableName);
@@ -651,30 +651,30 @@ $$ LANGUAGE plpgsql;
651
651
  sorted: o,
652
652
  cyclic: r
653
653
  };
654
- }, vt = (t, n, r = null) => {
655
- let i = (t) => r ? `${e(r, n)}.${e(t, n)}` : e(t, n), a = `${t.table}_${t.column}_fkey`, o = N(t.onDelete, n), s = N(t.onUpdate, n), c = ` ON DELETE ${o}${s === "NO ACTION" ? "" : ` ON UPDATE ${s}`}`, l = (r) => `ADD CONSTRAINT ${e(a, n)} FOREIGN KEY ${r ? "IF NOT EXISTS " : ""}(${e(t.column, n)}) REFERENCES ${i(t.targetTable)} (${e("id", n)})${c}`;
656
- switch (n) {
654
+ }, _t = (e, t, n = null) => {
655
+ let r = (e) => n ? `${_(n, t)}.${_(e, t)}` : _(e, t), i = `${e.table}_${e.column}_fkey`, a = F(e.onDelete, t), o = F(e.onUpdate, t), s = ` ON DELETE ${a}${o === "NO ACTION" ? "" : ` ON UPDATE ${o}`}`, c = (n) => `ADD CONSTRAINT ${_(i, t)} FOREIGN KEY ${n ? "IF NOT EXISTS " : ""}(${_(e.column, t)}) REFERENCES ${r(e.targetTable)} (${_("id", t)})${s}`;
656
+ switch (t) {
657
657
  case "postgres": return [
658
658
  "DO $$ BEGIN",
659
659
  " IF NOT EXISTS (SELECT 1 FROM pg_constraint",
660
- ` WHERE conname = '${a}' AND conrelid = '${r ? `${r}.` : ""}${t.table}'::regclass) THEN`,
661
- ` ALTER TABLE ${i(t.table)} ${l(!1)};`,
660
+ ` WHERE conname = '${i}' AND conrelid = '${n ? `${n}.` : ""}${e.table}'::regclass) THEN`,
661
+ ` ALTER TABLE ${r(e.table)} ${c(!1)};`,
662
662
  " END IF;",
663
663
  "END $$;"
664
664
  ].join("\n");
665
- case "mssql": return `IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = '${a}') ALTER TABLE ${i(t.table)} ${l(!1)};`;
666
- case "mariadb": return `ALTER TABLE ${i(t.table)} ${l(!0)};`;
667
- default: return `ALTER TABLE ${i(t.table)} ${l(!1)};`;
665
+ case "mssql": return `IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = '${i}') ALTER TABLE ${r(e.table)} ${c(!1)};`;
666
+ case "mariadb": return `ALTER TABLE ${r(e.table)} ${c(!0)};`;
667
+ default: return `ALTER TABLE ${r(e.table)} ${c(!1)};`;
668
668
  }
669
- }, yt = (e, t) => {
670
- let r = /* @__PURE__ */ new Map();
671
- if (n(t)) return r;
669
+ }, vt = (e, t) => {
670
+ let n = /* @__PURE__ */ new Map();
671
+ if (l(t)) return n;
672
672
  for (let t of e) {
673
- let e = r.get(t.table) ?? /* @__PURE__ */ new Set();
674
- e.add(t.column), r.set(t.table, e);
673
+ let e = n.get(t.table) ?? /* @__PURE__ */ new Set();
674
+ e.add(t.column), n.set(t.table, e);
675
675
  }
676
- return r;
677
- }, bt = (e, t) => {
676
+ return n;
677
+ }, yt = (e, t) => {
678
678
  if (t !== "postgres") return "";
679
679
  let n = /* @__PURE__ */ new Map();
680
680
  for (let t of e) for (let e of Object.values(t.fields)) {
@@ -690,12 +690,12 @@ $$ LANGUAGE plpgsql;
690
690
  r.push(`DO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = '${e.replace(/'/g, "''")}') THEN\n CREATE TYPE "${e}" AS ENUM (${n});\n END IF;\nEND $$;`);
691
691
  }
692
692
  return r.join("\n\n");
693
- }, xt = (e, t) => {
693
+ }, bt = (e, t) => {
694
694
  if (t !== "postgres") return "";
695
695
  let n = /* @__PURE__ */ new Set();
696
696
  for (let t of e) for (let e of Object.values(t.fields)) e.type === "enum" && e.enumName && n.add(e.enumName);
697
697
  let r = [];
698
- for (let e of n) for (let { from: t, to: n } of i(e)) {
698
+ for (let e of n) for (let { from: t, to: n } of b(e)) {
699
699
  let i = e.replace(/'/g, "''"), a = t.replace(/'/g, "''"), o = n.replace(/'/g, "''");
700
700
  r.push(`DO \$\$
701
701
  DECLARE
@@ -704,95 +704,95 @@ BEGIN
704
704
  SELECT oid INTO type_oid FROM pg_type WHERE typname = '${i}';\n IF type_oid IS NOT NULL\n AND EXISTS (SELECT 1 FROM pg_enum WHERE enumtypid = type_oid AND enumlabel = '${a}')\n AND NOT EXISTS (SELECT 1 FROM pg_enum WHERE enumtypid = type_oid AND enumlabel = '${o}') THEN\n IF current_setting('server_version_num')::int >= 140000 THEN\n EXECUTE format('ALTER TYPE %I RENAME VALUE %L TO %L', '${i}', '${a}', '${o}');\n ELSE\n UPDATE pg_enum SET enumlabel = '${o}' WHERE enumtypid = type_oid AND enumlabel = '${a}';\n END IF;\n END IF;\nEND $$;`);
705
705
  }
706
706
  return r.join("\n\n");
707
- }, St = (e) => {
707
+ }, xt = (e) => {
708
708
  let t = [], n = [];
709
- for (let r of e) m(r) ? n.push(r) : t.push(r);
709
+ for (let r of e) u(r) ? n.push(r) : t.push(r);
710
710
  return {
711
711
  tables: t,
712
712
  views: n
713
713
  };
714
- }, Ct = (e, t, r = O) => {
715
- let { tables: i, views: a } = St(e), { sorted: o, cyclic: s } = _t(i.map((e) => de(e, t))), l = yt(s, t), u = [];
716
- t === "postgres" && ht(o) && u.push("CREATE EXTENSION IF NOT EXISTS vector;"), t === "postgres" && gt(o) && u.push("CREATE EXTENSION IF NOT EXISTS postgis;");
717
- let d = xt(o, t);
718
- d && u.push(d);
719
- let f = bt(o, t);
720
- f && u.push(f);
721
- for (let e of o) u.push(st(e, t, null, l.get(e.tableName)));
722
- if (!n(t)) for (let e of s) u.push(vt(e, t));
714
+ }, St = (e, t, n = A) => {
715
+ let { tables: r, views: i } = xt(e), { sorted: a, cyclic: o } = gt(r.map((e) => le(e, t))), s = vt(o, t), c = [];
716
+ t === "postgres" && mt(a) && c.push("CREATE EXTENSION IF NOT EXISTS vector;"), t === "postgres" && ht(a) && c.push("CREATE EXTENSION IF NOT EXISTS postgis;");
717
+ let u = bt(a, t);
718
+ u && c.push(u);
719
+ let d = yt(a, t);
720
+ d && c.push(d);
721
+ for (let e of a) c.push(ot(e, t, null, s.get(e.tableName)));
722
+ if (!l(t)) for (let e of o) c.push(_t(e, t));
723
+ for (let e of a) {
724
+ let n = ct(e, t);
725
+ n && c.push(n);
726
+ }
727
+ c.push(...lt(a, t, n));
728
+ for (let e of i) c.push(x(e, t));
729
+ return c.join("\n\n") + "\n";
730
+ }, Ct = (e, t, n) => {
731
+ let r = _(e, t);
732
+ switch (t) {
733
+ case "postgres": return `CREATE SCHEMA IF NOT EXISTS ${r};`;
734
+ case "mysql":
735
+ case "mariadb": return `CREATE DATABASE IF NOT EXISTS ${r};`;
736
+ case "mssql": return `IF SCHEMA_ID('${e.replace(/'/g, "''")}') IS NULL EXEC(N'CREATE SCHEMA ${r.replace(/'/g, "''")}');`;
737
+ case "turso":
738
+ case "sqlite": return `ATTACH DATABASE '${(n ?? `${e}.db`).replace(/'/g, "''")}' AS ${r};`;
739
+ }
740
+ }, wt = (e, t, n, r) => {
741
+ let i = Ct(n, t, r), a = _(n, t);
742
+ if (t === "postgres") return `${i}\n\nSET search_path TO ${a};\n\n${St(e, t)}`;
743
+ if (t === "mysql" || t === "mariadb") return `${i}\n\nUSE ${a};\n\n${St(e, t)}`;
744
+ let { sorted: o, cyclic: s } = gt(e), c = vt(s, t), u = [i];
745
+ for (let e of o) u.push(ot(e, t, n, c.get(e.tableName)));
746
+ if (!l(t)) for (let e of s) u.push(_t(e, t, n));
723
747
  for (let e of o) {
724
- let n = lt(e, t);
725
- n && u.push(n);
748
+ let r = ct(e, t, n);
749
+ r && u.push(r);
726
750
  }
727
- u.push(...ut(o, t, r));
728
- for (let e of a) u.push(c(e, t));
729
751
  return u.join("\n\n") + "\n";
730
- }, wt = (t, n, r) => {
731
- let i = e(t, n);
732
- switch (n) {
733
- case "postgres": return `CREATE SCHEMA IF NOT EXISTS ${i};`;
734
- case "mysql":
735
- case "mariadb": return `CREATE DATABASE IF NOT EXISTS ${i};`;
736
- case "mssql": return `IF SCHEMA_ID('${t.replace(/'/g, "''")}') IS NULL EXEC(N'CREATE SCHEMA ${i.replace(/'/g, "''")}');`;
737
- case "turso":
738
- case "sqlite": return `ATTACH DATABASE '${(r ?? `${t}.db`).replace(/'/g, "''")}' AS ${i};`;
739
- }
740
- }, Tt = (t, r, i, a) => {
741
- let o = wt(i, r, a), s = e(i, r);
742
- if (r === "postgres") return `${o}\n\nSET search_path TO ${s};\n\n${Ct(t, r)}`;
743
- if (r === "mysql" || r === "mariadb") return `${o}\n\nUSE ${s};\n\n${Ct(t, r)}`;
744
- let { sorted: c, cyclic: l } = _t(t), u = yt(l, r), d = [o];
745
- for (let e of c) d.push(st(e, r, i, u.get(e.tableName)));
746
- if (!n(r)) for (let e of l) d.push(vt(e, r, i));
747
- for (let e of c) {
748
- let t = lt(e, r, i);
749
- t && d.push(t);
750
- }
751
- return d.join("\n\n") + "\n";
752
- }, Et = (e, t, n = O) => {
753
- let { sorted: r, cyclic: i } = _t(e), a = yt(i, t), o = [], s = xt(r, t);
752
+ }, Tt = (e, t, n = A) => {
753
+ let { sorted: r, cyclic: i } = gt(e), a = vt(i, t), o = [], s = bt(r, t);
754
754
  s && o.push(s);
755
- let c = bt(r, t);
755
+ let c = yt(r, t);
756
756
  c && o.push(c);
757
- for (let e of r) o.push(st(e, t, null, a.get(e.tableName)));
758
- for (let e of i) o.push(vt(e, t));
759
- return o.push(...ut(r, t, n)), o.join("\n\n") + "\n";
760
- }, Dt = (e, t = "postgres", n = O, r = {}) => x.gen(function* () {
761
- let i = yield* C.SqlClient;
762
- yield* Ne(i, Pt(i, Ct(e, t, n), t, r.retryFilter), { schema: r.lockSchema }).pipe(x.orDie);
763
- }), Ot = (e, t) => {
757
+ for (let e of r) o.push(ot(e, t, null, a.get(e.tableName)));
758
+ for (let e of i) o.push(_t(e, t));
759
+ return o.push(...lt(r, t, n)), o.join("\n\n") + "\n";
760
+ }, Et = (e, t = "postgres", n = A, r = {}) => S.gen(function* () {
761
+ let i = yield* E.SqlClient;
762
+ yield* Me(i, Nt(i, St(e, t, n), t, r.retryFilter), { schema: r.lockSchema }).pipe(S.orDie);
763
+ }), Dt = (e, t) => {
764
764
  let n = t.cause ?? {};
765
765
  return (n.errno === 1061 || n.code === "ER_DUP_KEYNAME") && /^\s*CREATE\s+(UNIQUE\s+|FULLTEXT\s+)?INDEX\b/i.test(e);
766
- }, kt = (e, t) => {
766
+ }, Ot = (e, t) => {
767
767
  let n = e.trimStart();
768
768
  return !!(/\bIF NOT EXISTS\b/i.test(n) || /^CREATE OR REPLACE\b/i.test(n) || /^DROP\s[\s\S]*?\bIF EXISTS\b/i.test(n) || /^SET search_path\b/i.test(n) || /^USE[\s`"[]/i.test(n) || /^IF\s/i.test(n) || (t === "mysql" || t === "mariadb") && /^CREATE\s+(UNIQUE\s+|FULLTEXT\s+)?INDEX\b/i.test(n));
769
- }, At = () => {
769
+ }, kt = () => {
770
770
  let e = Number(process.env.VOLTRO_MIGRATION_DDL_RETRIES);
771
771
  return Number.isInteger(e) && e >= 0 ? e : 4;
772
- }, jt = (e) => ({
772
+ }, At = (e) => ({
773
773
  while: e,
774
- times: At(),
775
- schedule: S.jittered(S.exponential("50 millis"))
776
- }), Mt = class {
774
+ times: kt(),
775
+ schedule: C.jittered(C.exponential("50 millis"))
776
+ }), jt = class {
777
777
  statement;
778
778
  error;
779
779
  _tag = "DdlStatementFailed";
780
780
  constructor(e, t) {
781
781
  this.statement = e, this.error = t;
782
782
  }
783
- }, Nt = (e, t, n) => x.gen(function* () {
784
- let r = yield* C.SqlClient, i = n !== void 0 && Ie(t) === "per-operation";
785
- for (let a of Ft(e)) {
786
- process.env.VOLTRO_MIGRATE_DEBUG === "1" && Qe.debug(`EXEC: ${a.replace(/\s+/g, " ").slice(0, 180)}`);
787
- let e = r.unsafe(a).pipe(x.catchIf((e) => Ot(a, e), () => x.succeed([])), x.tapError((e) => x.sync(() => {
788
- Qe.error(ae("migrate: statement failed", a, e, 200));
783
+ }, Mt = (e, t, n) => S.gen(function* () {
784
+ let r = yield* E.SqlClient, i = n !== void 0 && Fe(t) === "per-operation";
785
+ for (let a of Pt(e)) {
786
+ process.env.VOLTRO_MIGRATE_DEBUG === "1" && Ze.debug(`EXEC: ${a.replace(/\s+/g, " ").slice(0, 180)}`);
787
+ let e = r.unsafe(a).pipe(S.catchIf((e) => Dt(a, e), () => S.succeed([])), S.tapError((e) => S.sync(() => {
788
+ Ze.error(re("migrate: statement failed", a, e, 200));
789
789
  })));
790
- yield* (i && n !== void 0 && kt(a, t) ? e.pipe(x.retry(jt((e) => n(e) === "retry"))) : e).pipe(x.mapError((e) => new Mt(a, e)));
790
+ yield* (i && n !== void 0 && Ot(a, t) ? e.pipe(S.retry(At((e) => n(e) === "retry"))) : e).pipe(S.mapError((e) => new jt(a, e)));
791
791
  }
792
- }), Pt = (e, t, n, r) => {
793
- let i = n === "turso" ? Nt(t, n, r) : e.withTransaction(Nt(t, n, r)), a = (e) => e instanceof Mt ? e.error : e;
794
- return (r !== void 0 && Ie(n) === "plan-transactional" ? i.pipe(x.retry(jt((e) => r(a(e)) === "retry"))) : i).pipe(x.orDieWith((e) => e instanceof Mt ? Error(ae("migrate: statement failed", e.statement, e.error, 400).trim()) : e));
795
- }, Ft = (e) => {
792
+ }), Nt = (e, t, n, r) => {
793
+ let i = n === "turso" ? Mt(t, n, r) : e.withTransaction(Mt(t, n, r)), a = (e) => e instanceof jt ? e.error : e;
794
+ return (r !== void 0 && Fe(n) === "plan-transactional" ? i.pipe(S.retry(At((e) => r(a(e)) === "retry"))) : i).pipe(S.orDieWith((e) => e instanceof jt ? Error(re("migrate: statement failed", e.statement, e.error, 400).trim()) : e));
795
+ }, Pt = (e) => {
796
796
  let t = [], n = "", r = !1;
797
797
  for (let i = 0; i < e.length; i++) {
798
798
  if (e.slice(i, i + 2) === "$$") {
@@ -807,42 +807,42 @@ BEGIN
807
807
  }
808
808
  let i = n.trim();
809
809
  return i.length > 0 && t.push(i), t;
810
- }, It = async (e, t, n = "postgres", r = {}) => {
811
- await x.runPromise(Dt(e, n, void 0, r).pipe(x.provide(t)));
812
- }, Lt = (e, t, n = "postgres", r = {}) => x.gen(function* () {
813
- let i = Tt(e, n, t), a = yield* C.SqlClient;
814
- yield* Ne(a, Pt(a, i, n, r.retryFilter), { schema: r.lockSchema }).pipe(x.orDie);
815
- }), Rt = async (e, t, n, r = "postgres", i = {}) => {
816
- await x.runPromise(Lt(e, t, r, i).pipe(x.provide(n))), await p({
810
+ }, Ft = async (e, t, n = "postgres", r = {}) => {
811
+ await S.runPromise(Et(e, n, void 0, r).pipe(S.provide(t)));
812
+ }, It = (e, t, n = "postgres", r = {}) => S.gen(function* () {
813
+ let i = wt(e, n, t), a = yield* E.SqlClient;
814
+ yield* Me(a, Nt(a, i, n, r.retryFilter), { schema: r.lockSchema }).pipe(S.orDie);
815
+ }), Lt = async (e, t, n, r = "postgres", i = {}) => {
816
+ await S.runPromise(It(e, t, r, i).pipe(S.provide(n))), await s({
817
817
  namespace: t,
818
818
  dialect: r
819
819
  });
820
- }, zt = async (e, t, n = "postgres", r = {}) => {
821
- await x.runPromise(x.gen(function* () {
822
- let t = Et(e, n), i = yield* C.SqlClient;
823
- yield* Ne(i, Pt(i, t, n, r.retryFilter), { schema: r.lockSchema }).pipe(x.orDie);
824
- }).pipe(x.provide(t)));
825
- }, Bt = (e) => {
820
+ }, Rt = async (e, t, n = "postgres", r = {}) => {
821
+ await S.runPromise(S.gen(function* () {
822
+ let t = Tt(e, n), i = yield* E.SqlClient;
823
+ yield* Me(i, Nt(i, t, n, r.retryFilter), { schema: r.lockSchema }).pipe(S.orDie);
824
+ }).pipe(S.provide(t)));
825
+ }, zt = (e) => {
826
826
  if (e == null) return e;
827
- if (Array.isArray(e)) return e.map(Bt);
827
+ if (Array.isArray(e)) return e.map(zt);
828
828
  if (typeof e != "object") return e;
829
829
  let t = {};
830
830
  for (let n of Object.keys(e).sort()) {
831
831
  let r = e[n];
832
- r !== void 0 && (t[n] = Bt(r));
832
+ r !== void 0 && (t[n] = zt(r));
833
833
  }
834
834
  return t;
835
- }, Vt = (e) => {
835
+ }, Bt = (e) => {
836
836
  if (!e.idScheme && !e.sensitive && !e.safe && !e.generatedAs) return e;
837
837
  let { idScheme: t, sensitive: n, safe: r, generatedAs: i, ...a } = e;
838
838
  return a;
839
- }, Ht = (e) => [...e].map(Vt).sort((e, t) => e.name.localeCompare(t.name)), Ut = (e) => [...e].sort((e, t) => e.name.localeCompare(t.name)), Wt = (e) => [...e].map((e) => ({
839
+ }, Vt = (e) => [...e].map(Bt).sort((e, t) => e.name.localeCompare(t.name)), Ht = (e) => [...e].sort((e, t) => e.name.localeCompare(t.name)), Ut = (e) => [...e].map((e) => ({
840
840
  name: e.name,
841
- columns: Ht(e.columns),
842
- indexes: Ut(e.indexes)
843
- })).sort((e, t) => e.name.localeCompare(t.name)), P = (e) => {
844
- let t = { tables: Wt(e.tables) }, n = JSON.stringify(Bt(t));
845
- return ee("sha256").update(n).digest("hex");
841
+ columns: Vt(e.columns),
842
+ indexes: Ht(e.indexes)
843
+ })).sort((e, t) => e.name.localeCompare(t.name)), Wt = (e) => {
844
+ let t = { tables: Ut(e.tables) }, n = JSON.stringify(zt(t));
845
+ return w("sha256").update(n).digest("hex");
846
846
  }, Gt = (e) => e.slice(0, 16), Kt = (e, t) => {
847
847
  let n = t.references ? {
848
848
  table: t.references().tableName,
@@ -922,7 +922,7 @@ BEGIN
922
922
  let i = n;
923
923
  if (i.dropped || !i.references || i.fkAutoIndex === !1 || s.has(t)) continue;
924
924
  let a = `${e.tableName}_${t}_idx`;
925
- d(e.tableName, a, !0, [t]), r({
925
+ y(e.tableName, a, !0, [t]), r({
926
926
  name: a,
927
927
  table: e.tableName,
928
928
  columns: [t],
@@ -955,16 +955,16 @@ BEGIN
955
955
  if (r !== void 0 && r !== n.name) throw Error(`duplicate index name '${e.name}' across tables '${r}' and '${n.name}'. Index names must be unique per SCHEMA, not just per table — the DB creates only one, so the other never applies and 'db plan' re-emits it forever. Give each an explicit, table-prefixed name (e.g. '${n.name}_${e.name}').`);
956
956
  t.set(e.name, n.name);
957
957
  }
958
- }, F = (e, t) => {
959
- let n = e.map((e) => Jt(de(e, t)));
958
+ }, I = (e, t) => {
959
+ let n = e.filter((e) => !i(e.tableName)).map((e) => Jt(le(e, t)));
960
960
  return Yt(n), { tables: n };
961
- }, Xt = (e, t, n = O) => x.gen(function* () {
961
+ }, Xt = (e, t, n = A) => S.gen(function* () {
962
962
  let r = (yield* e`
963
963
  SELECT p.prosrc
964
964
  FROM pg_proc p
965
965
  JOIN pg_namespace n ON n.oid = p.pronamespace
966
966
  WHERE n.nspname = current_schema()
967
- AND p.proname = ${Xe(n)}
967
+ AND p.proname = ${Ye(n)}
968
968
  `)[0]?.prosrc, i = r !== void 0 && !r.includes("voltro:notify:v2"), a = t.filter((e) => !e.tableName.startsWith("_voltro_"));
969
969
  if (a.length === 0) return {
970
970
  missing: [],
@@ -978,10 +978,10 @@ BEGIN
978
978
  JOIN pg_namespace n ON n.oid = c.relnamespace
979
979
  WHERE NOT t.tgisinternal
980
980
  AND n.nspname = current_schema()
981
- AND t.tgname LIKE ${`${Je}%`}
981
+ AND t.tgname LIKE ${`${qe}%`}
982
982
  `, s = new Set(o.map((e) => e.tgname)), c = [], l = [];
983
983
  for (let e of a) {
984
- let t = s.has(Ye(e.tableName, n)), r = e.isReactive !== !1;
984
+ let t = s.has(Je(e.tableName, n)), r = e.isReactive !== !1;
985
985
  r && !t && c.push(e.tableName), !r && t && l.push(e.tableName);
986
986
  }
987
987
  return {
@@ -1032,29 +1032,29 @@ BEGIN
1032
1032
  snapshot: n.get(e.tableName),
1033
1033
  columnDefs: e.fields
1034
1034
  }]));
1035
- }, I = (e) => {
1035
+ }, L = (e) => {
1036
1036
  if (typeof e != "object" || !e) return JSON.stringify(e);
1037
- if (Array.isArray(e)) return `[${e.map(I).join(",")}]`;
1037
+ if (Array.isArray(e)) return `[${e.map(L).join(",")}]`;
1038
1038
  let t = e;
1039
- return `{${Object.keys(t).sort().map((e) => `${JSON.stringify(e)}:${I(t[e])}`).join(",")}}`;
1039
+ return `{${Object.keys(t).sort().map((e) => `${JSON.stringify(e)}:${L(t[e])}`).join(",")}}`;
1040
1040
  }, nn = (e) => {
1041
1041
  if (!e.hasDefault || e.defaultValue === void 0 || e.defaultValue === null) return null;
1042
1042
  let t = e.defaultValue;
1043
1043
  if (typeof t == "boolean") return t ? "__BOOL_TRUE__" : "__BOOL_FALSE__";
1044
1044
  if (typeof t == "number") return String(t);
1045
- if (typeof t != "string") return I(t);
1045
+ if (typeof t != "string") return L(t);
1046
1046
  let n = t.trim(), r = n.toLowerCase().replace(/\s+/g, "");
1047
1047
  if (r === "now" || r === "now()" || /^current_timestamp(\(\d*\))?$/.test(r) || r === "sysutcdatetime()" || r === "sysdatetime()" || r === "getutcdate()" || r === "getdate()") return "__NOW__";
1048
1048
  let i = n.replace(/::[a-zA-Z0-9_ "]+$/, "").trim(), a = /^'(.*)'$/.test(i) ? i.slice(1, -1).replace(/''/g, "'") : i, o = /^cast\(\s*(?:_\w+\s*)?\\?'(.*?)\\?'\s+as\s+json\s*\)$/i.exec(a);
1049
1049
  if (o) try {
1050
- return I(JSON.parse(o[1]));
1050
+ return L(JSON.parse(o[1]));
1051
1051
  } catch {}
1052
1052
  let s = /^convert\(\s*(?:_\w+\s*)?\\?'(.*?)\\?'\s+using\s+[\w]+\s*\)$/i.exec(a);
1053
1053
  if (s) try {
1054
- return I(JSON.parse(s[1]));
1054
+ return L(JSON.parse(s[1]));
1055
1055
  } catch {}
1056
1056
  if (a.startsWith("{") || a.startsWith("[")) try {
1057
- return I(JSON.parse(a));
1057
+ return L(JSON.parse(a));
1058
1058
  } catch {}
1059
1059
  return /^-?\d+(\.\d+)?$/.test(a) ? String(Number(a)) : a;
1060
1060
  }, rn = (e, t) => {
@@ -1079,12 +1079,12 @@ BEGIN
1079
1079
  return i.every((e, t) => e === a[t]);
1080
1080
  }, sn = (e, t) => {
1081
1081
  try {
1082
- let n = /\((\d+)\)/.exec(A(e, t));
1082
+ let n = /\((\d+)\)/.exec(M(e, t));
1083
1083
  return n ? Number(n[1]) : void 0;
1084
1084
  } catch {
1085
1085
  return;
1086
1086
  }
1087
- }, cn = (e, t, r) => r === void 0 || n(r) ? !0 : e.type !== "text" || t.type !== "text" || sn(e, r) === t.maxLength, ln = (e, t, n) => e.type === t.type && e.nullable === t.nullable && e.unique === t.unique && rn(e, t) && cn(e, t, n) && JSON.stringify(an(e.references)) === JSON.stringify(an(t.references)) && on(e.oneOf, t.oneOf), un = (e, t) => t.oneOf && t.oneOf.length > 0 ? L({
1087
+ }, cn = (e, t, n) => n === void 0 || l(n) ? !0 : e.type !== "text" || t.type !== "text" || sn(e, n) === t.maxLength, ln = (e, t, n) => e.type === t.type && e.nullable === t.nullable && e.unique === t.unique && rn(e, t) && cn(e, t, n) && JSON.stringify(an(e.references)) === JSON.stringify(an(t.references)) && on(e.oneOf, t.oneOf), un = (e, t) => t.oneOf && t.oneOf.length > 0 ? R({
1088
1088
  kind: "add-check",
1089
1089
  table: e,
1090
1090
  column: t.name,
@@ -1119,7 +1119,7 @@ BEGIN
1119
1119
  added: i,
1120
1120
  removed: a
1121
1121
  };
1122
- }, L = (e, t, n, r) => ({
1122
+ }, R = (e, t, n, r) => ({
1123
1123
  op: e,
1124
1124
  classification: t,
1125
1125
  atomicByDialect: en(e.kind),
@@ -1131,21 +1131,21 @@ BEGIN
1131
1131
  table: e,
1132
1132
  column: t
1133
1133
  };
1134
- return t.nullable ? L(r, "safe", "nullable column add — no backfill needed") : t.hasDefault && t.defaultValue !== void 0 ? L(r, "needs-default", "NOT NULL with literal default — DDL DEFAULT will populate existing rows") : n?.backfill ? L(r, "needs-backfill", `backfill declared (kind=${n.backfill.kind}) — applier will run 3-step add/update/set-not-null`) : L(r, "needs-backfill", "NOT NULL column on a table whose row count is unknown", { fix: `declare \`${t.name}: <type>().backfill(sql\`...\`)\` OR \`.default(value)\` so existing rows survive the migration` });
1134
+ return t.nullable ? R(r, "safe", "nullable column add — no backfill needed") : t.hasDefault && t.defaultValue !== void 0 ? R(r, "needs-default", "NOT NULL with literal default — DDL DEFAULT will populate existing rows") : n?.backfill ? R(r, "needs-backfill", `backfill declared (kind=${n.backfill.kind}) — applier will run 3-step add/update/set-not-null`) : R(r, "needs-backfill", "NOT NULL column on a table whose row count is unknown", { fix: `declare \`${t.name}: <type>().backfill(sql\`...\`)\` OR \`.default(value)\` so existing rows survive the migration` });
1135
1135
  }, hn = (e, t, n) => {
1136
1136
  let r = {
1137
1137
  kind: "drop-column",
1138
1138
  table: e,
1139
1139
  column: t.name
1140
1140
  };
1141
- return n?.dropped ? L(r, "lossy", `column dropped via \`${t.name}: dropped()\` marker — intentional`) : L(r, "lossy", "column missing from declared schema", { fix: `if intentional, add \`${t.name}: dropped()\` to the schema. If a typo, restore the field` });
1142
- }, gn = (e, t, n, r, i) => L({
1141
+ return n?.dropped ? R(r, "lossy", `column dropped via \`${t.name}: dropped()\` marker — intentional`) : R(r, "lossy", "column missing from declared schema", { fix: `if intentional, add \`${t.name}: dropped()\` to the schema. If a typo, restore the field` });
1142
+ }, gn = (e, t, n, r, i) => R({
1143
1143
  kind: "create-table",
1144
1144
  table: e,
1145
1145
  columns: t,
1146
1146
  indexes: n,
1147
1147
  ...r && r.length > 0 ? { primaryKey: r } : {}
1148
- }, "safe", i ?? "new table — no data to preserve"), _n = (e) => L({
1148
+ }, "safe", i ?? "new table — no data to preserve"), _n = (e) => R({
1149
1149
  kind: "drop-table",
1150
1150
  table: e
1151
1151
  }, "lossy", "table missing from declared schema", { fix: "if intentional, set VOLTRO_DESTRUCTIVE_OK=1 OR add a file-based migration. If a typo, restore the table declaration" }), vn = 5e4, yn = (e, t, n, r) => {
@@ -1163,12 +1163,12 @@ BEGIN
1163
1163
  kind: "add-index",
1164
1164
  table: e,
1165
1165
  index: t
1166
- }, i ? L(a, "online-required", `online build on ${n} rows — CONCURRENTLY / INPLACE / WITH(ONLINE=ON) depending on dialect`) : L(a, "safe", t.unique ? t.columns.length === 1 ? "add unique constraint" : "add composite UNIQUE constraint" : "add B-tree index");
1167
- }, bn = (e, t) => t.unique && t.columns.length > 1 ? L({
1166
+ }, i ? R(a, "online-required", `online build on ${n} rows — CONCURRENTLY / INPLACE / WITH(ONLINE=ON) depending on dialect`) : R(a, "safe", t.unique ? t.columns.length === 1 ? "add unique constraint" : "add composite UNIQUE constraint" : "add B-tree index");
1167
+ }, bn = (e, t) => t.unique && t.columns.length > 1 ? R({
1168
1168
  kind: "drop-unique-composite",
1169
1169
  table: e,
1170
1170
  name: t.name
1171
- }, "safe", "drop composite UNIQUE constraint (no data loss — constraint is derived metadata)") : L({
1171
+ }, "safe", "drop composite UNIQUE constraint (no data loss — constraint is derived metadata)") : R({
1172
1172
  kind: "drop-index",
1173
1173
  table: e,
1174
1174
  index: t.name
@@ -1183,65 +1183,65 @@ BEGIN
1183
1183
  }, Sn = (e, t, n) => {
1184
1184
  let r = `acknowledge it on the column: \`.narrowedFrom('${e}')\``;
1185
1185
  return n === "postgres" ? `${r} — add \`{ using: '${t.name}::${t.type}' }\` when the cast is not implicit, or use a file-based migration` : `${r} — ${n === void 0 ? "this dialect" : n} converts in place (\`using\` is postgres-only and is ignored here), so verify the conversion is value-preserving for your data, or use a file-based migration`;
1186
- }, Cn = (e, t, r, i, a, o) => {
1187
- let s = [];
1188
- if (t.nullable !== r.nullable) {
1186
+ }, Cn = (e, t, n, r, i, a) => {
1187
+ let o = [];
1188
+ if (t.nullable !== n.nullable) {
1189
1189
  let n = {
1190
1190
  kind: "alter-column-nullability",
1191
1191
  table: e,
1192
1192
  column: t.name,
1193
1193
  toNullable: t.nullable
1194
1194
  };
1195
- s.push(t.nullable ? L(n, "safe", `loosen ${e}.${t.name} to nullable`) : L(n, "needs-backfill", `tighten ${e}.${t.name} to NOT NULL — existing rows must already be non-null`));
1195
+ o.push(t.nullable ? R(n, "safe", `loosen ${e}.${t.name} to nullable`) : R(n, "needs-backfill", `tighten ${e}.${t.name} to NOT NULL — existing rows must already be non-null`));
1196
1196
  }
1197
- if (t.unique !== r.unique) {
1197
+ if (t.unique !== n.unique) {
1198
1198
  if (t.unique) {
1199
1199
  let n = {
1200
1200
  kind: "add-unique",
1201
1201
  table: e,
1202
1202
  column: t.name
1203
- }, r = (a ?? 0) >= o;
1204
- s.push(r ? L(n, "online-required", `online unique build on ${a} rows — CONCURRENTLY / INPLACE / WITH(ONLINE=ON) depending on dialect`) : L(n, "safe", `add unique constraint on ${e}.${t.name} — existing rows must already be distinct (else the DB rejects at migrate)`));
1205
- } else s.push(L({
1203
+ }, r = (i ?? 0) >= a;
1204
+ o.push(r ? R(n, "online-required", `online unique build on ${i} rows — CONCURRENTLY / INPLACE / WITH(ONLINE=ON) depending on dialect`) : R(n, "safe", `add unique constraint on ${e}.${t.name} — existing rows must already be distinct (else the DB rejects at migrate)`));
1205
+ } else o.push(R({
1206
1206
  kind: "drop-unique",
1207
1207
  table: e,
1208
1208
  column: t.name
1209
1209
  }, "safe", `drop unique constraint on ${e}.${t.name} — constraint is derived metadata, no data loss`));
1210
1210
  }
1211
- if (xn(t.type, i) !== xn(r.type, i)) {
1212
- let n = t.narrowedFrom;
1213
- if (n && n.from === r.type) {
1214
- let i = {
1211
+ if (xn(t.type, r) !== xn(n.type, r)) {
1212
+ let i = t.narrowedFrom;
1213
+ if (i && i.from === n.type) {
1214
+ let r = {
1215
1215
  kind: "alter-column-type",
1216
1216
  table: e,
1217
1217
  column: t.name,
1218
- from: r.type,
1218
+ from: n.type,
1219
1219
  to: t.type,
1220
- ...n.using === void 0 ? {} : { using: n.using }
1220
+ ...i.using === void 0 ? {} : { using: i.using }
1221
1221
  };
1222
- s.push(L(i, "needs-backfill", `type change ${r.type} → ${t.type} on ${e}.${t.name} — narrowedFrom('${n.from}') declared` + (n.using ? ` with USING ${n.using}` : " (implicit cast)")));
1222
+ o.push(R(r, "needs-backfill", `type change ${n.type} → ${t.type} on ${e}.${t.name} — narrowedFrom('${i.from}') declared` + (i.using ? ` with USING ${i.using}` : " (implicit cast)")));
1223
1223
  } else {
1224
- let n = {
1224
+ let i = {
1225
1225
  kind: "alter-column-type",
1226
1226
  table: e,
1227
1227
  column: t.name,
1228
- from: r.type,
1228
+ from: n.type,
1229
1229
  to: t.type
1230
1230
  };
1231
- s.push(L(n, "lossy", `type change ${r.type} → ${t.type} on ${e}.${t.name} may not be value-preserving`, { fix: Sn(r.type, t, i) }));
1231
+ o.push(R(i, "lossy", `type change ${n.type} → ${t.type} on ${e}.${t.name} may not be value-preserving`, { fix: Sn(n.type, t, r) }));
1232
1232
  }
1233
1233
  }
1234
- if (t.type === "text" && r.type === "text" && !n(i ?? "postgres") && t.maxLength !== r.maxLength) {
1235
- let n = t.maxLength === void 0 || r.maxLength !== void 0 && t.maxLength > r.maxLength, i = r.maxLength === void 0 ? "unbounded" : `varchar(${r.maxLength})`, a = t.maxLength === void 0 ? "unbounded" : `varchar(${t.maxLength})`;
1236
- s.push(L({
1234
+ if (t.type === "text" && n.type === "text" && !l(r ?? "postgres") && t.maxLength !== n.maxLength) {
1235
+ let r = t.maxLength === void 0 || n.maxLength !== void 0 && t.maxLength > n.maxLength, i = n.maxLength === void 0 ? "unbounded" : `varchar(${n.maxLength})`, a = t.maxLength === void 0 ? "unbounded" : `varchar(${t.maxLength})`;
1236
+ o.push(R({
1237
1237
  kind: "alter-column-type",
1238
1238
  table: e,
1239
1239
  column: t.name,
1240
1240
  from: "text",
1241
1241
  to: "text"
1242
- }, n ? "safe" : "needs-backfill", n ? `text length ${i} → ${a} on ${e}.${t.name} — widening, no data can be lost` : `text length ${i} → ${a} on ${e}.${t.name} — NARROWING; the ALTER fails if any existing value is longer than ${String(t.maxLength)}. Check first: SELECT COUNT(*) FROM ${e} WHERE LENGTH(${t.name}) > ${String(t.maxLength)}`));
1242
+ }, r ? "safe" : "needs-backfill", r ? `text length ${i} → ${a} on ${e}.${t.name} — widening, no data can be lost` : `text length ${i} → ${a} on ${e}.${t.name} — NARROWING; the ALTER fails if any existing value is longer than ${String(t.maxLength)}. Check first: SELECT COUNT(*) FROM ${e} WHERE LENGTH(${t.name}) > ${String(t.maxLength)}`));
1243
1243
  }
1244
- if (!rn(t, r)) {
1244
+ if (!rn(t, n)) {
1245
1245
  let n = {
1246
1246
  kind: "alter-column-default",
1247
1247
  table: e,
@@ -1249,22 +1249,22 @@ BEGIN
1249
1249
  hasDefault: t.hasDefault,
1250
1250
  ...t.defaultValue === void 0 ? {} : { defaultValue: t.defaultValue }
1251
1251
  };
1252
- s.push(L(n, "safe", `default change on ${e}.${t.name} affects only future inserts`));
1252
+ o.push(R(n, "safe", `default change on ${e}.${t.name} affects only future inserts`));
1253
1253
  }
1254
- if (!on(t.oneOf, r.oneOf)) {
1255
- r.oneOf && r.oneOf.length > 0 && s.push(L({
1254
+ if (!on(t.oneOf, n.oneOf)) {
1255
+ n.oneOf && n.oneOf.length > 0 && o.push(R({
1256
1256
  kind: "drop-check",
1257
1257
  table: e,
1258
1258
  column: t.name
1259
1259
  }, "safe", `drop stale enum CHECK on ${e}.${t.name}`));
1260
- let n = un(e, t);
1261
- n && s.push(n);
1260
+ let r = un(e, t);
1261
+ r && o.push(r);
1262
1262
  }
1263
- return JSON.stringify(an(t.references)) !== JSON.stringify(an(r.references)) && (r.references && s.push(L({
1263
+ return JSON.stringify(an(t.references)) !== JSON.stringify(an(n.references)) && (n.references && o.push(R({
1264
1264
  kind: "drop-foreign-key",
1265
1265
  table: e,
1266
1266
  column: t.name
1267
- }, "safe", `drop FK on ${e}.${t.name} (→ ${r.references.table})`)), s.push(...wn(e, t))), s;
1267
+ }, "safe", `drop FK on ${e}.${t.name} (→ ${n.references.table})`)), o.push(...wn(e, t))), o;
1268
1268
  }, wn = (e, t) => {
1269
1269
  let n = [];
1270
1270
  if (!t.references) return n;
@@ -1277,15 +1277,15 @@ BEGIN
1277
1277
  ...t.references.onDelete ? { onDelete: t.references.onDelete } : {},
1278
1278
  ...t.references.onUpdate ? { onUpdate: t.references.onUpdate } : {}
1279
1279
  };
1280
- return i === "null" && !t.nullable ? n.push(L(a, "lossy", `add FK ${e}.${t.name} → ${r}: orphanPolicy 'null' needs a nullable column (the NULL-out would violate NOT NULL)`, { fix: `make ${t.name} \`.nullable()\`, OR use \`orphanPolicy: 'delete'\`, OR clean the orphans and drop the policy` })) : i === "null" || i === "delete" ? n.push(L({
1280
+ return i === "null" && !t.nullable ? n.push(R(a, "lossy", `add FK ${e}.${t.name} → ${r}: orphanPolicy 'null' needs a nullable column (the NULL-out would violate NOT NULL)`, { fix: `make ${t.name} \`.nullable()\`, OR use \`orphanPolicy: 'delete'\`, OR clean the orphans and drop the policy` })) : i === "null" || i === "delete" ? n.push(R({
1281
1281
  ...a,
1282
1282
  orphanPolicy: i
1283
- }, "lossy", i === "delete" ? `add FK ${e}.${t.name} → ${r}: orphanPolicy 'delete' first DELETES rows whose ${t.name} points at a missing ${r}` : `add FK ${e}.${t.name} → ${r}: orphanPolicy 'null' first NULLs ${t.name} where it points at a missing ${r}`)) : n.push(L(a, "needs-backfill", `add FK ${e}.${t.name} → ${r} — existing rows must already reference a valid ${r} (else set orphanPolicy:'null'/'delete')`)), n;
1283
+ }, "lossy", i === "delete" ? `add FK ${e}.${t.name} → ${r}: orphanPolicy 'delete' first DELETES rows whose ${t.name} points at a missing ${r}` : `add FK ${e}.${t.name} → ${r}: orphanPolicy 'null' first NULLs ${t.name} where it points at a missing ${r}`)) : n.push(R(a, "needs-backfill", `add FK ${e}.${t.name} → ${r} — existing rows must already reference a valid ${r} (else set orphanPolicy:'null'/'delete')`)), n;
1284
1284
  }, Tn = (e, t, n) => {
1285
1285
  let r = [], i = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set(), o = new Set(n.removed.map((e) => e.name)), s = new Set(n.added.map((e) => e.name));
1286
1286
  for (let [n, c] of Object.entries(t)) {
1287
1287
  let t = c.renamedFrom;
1288
- t && o.has(t) && s.has(n) && (i.add(n), a.add(t), r.push(L({
1288
+ t && o.has(t) && s.has(n) && (i.add(n), a.add(t), r.push(R({
1289
1289
  kind: "rename-column",
1290
1290
  table: e.tableName,
1291
1291
  from: t,
@@ -1316,7 +1316,7 @@ BEGIN
1316
1316
  let t = o(n), r = a.filter((e) => !l.has(e.name) && s(e) === t);
1317
1317
  if (r.length !== 1) continue;
1318
1318
  let i = r[0];
1319
- i.name !== n.name && (l.add(i.name), u.add(n.name), c.push(L({
1319
+ i.name !== n.name && (l.add(i.name), u.add(n.name), c.push(R({
1320
1320
  kind: "rename-index",
1321
1321
  table: e,
1322
1322
  from: n.name,
@@ -1339,7 +1339,7 @@ BEGIN
1339
1339
  continue;
1340
1340
  }
1341
1341
  if (t.has(c.name)) {
1342
- r.push(L({
1342
+ r.push(R({
1343
1343
  kind: "rename-table",
1344
1344
  from: e,
1345
1345
  to: c.name
@@ -1347,14 +1347,14 @@ BEGIN
1347
1347
  continue;
1348
1348
  }
1349
1349
  if ((s.get(e) ?? 0) !== 1) {
1350
- r.push(L({
1350
+ r.push(R({
1351
1351
  kind: "rename-table",
1352
1352
  from: e,
1353
1353
  to: c.name
1354
1354
  }, "needs-rename-annotation", `.renamedFrom('${e}') is claimed by ${s.get(e)} tables — nothing says which receives its rows`, { fix: `remove the \`.renamedFrom('${e}')\` marker from all but one of them.` }));
1355
1355
  continue;
1356
1356
  }
1357
- i.set(c.name, e), a.add(e), r.push(L({
1357
+ i.set(c.name, e), a.add(e), r.push(R({
1358
1358
  kind: "rename-table",
1359
1359
  from: e,
1360
1360
  to: c.name
@@ -1380,7 +1380,7 @@ BEGIN
1380
1380
  ...e,
1381
1381
  name: r,
1382
1382
  table: n
1383
- } : i ? (a.push(L({
1383
+ } : i ? (a.push(R({
1384
1384
  kind: "rename-index",
1385
1385
  table: n,
1386
1386
  from: e.name,
@@ -1433,7 +1433,7 @@ BEGIN
1433
1433
  }
1434
1434
  return t;
1435
1435
  }, Nn = (e) => {
1436
- let t = F(e.declared, e.dialect), n = tn(e.declared, t), r = new Map(e.live.tables.map((e) => [e.name, e])), i = e.onlineAfter ?? vn, a = [], o = An(t, r, n);
1436
+ let t = I(e.declared, e.dialect), n = tn(e.declared, t), r = new Map(e.live.tables.map((e) => [e.name, e])), i = e.onlineAfter ?? vn, a = [], o = An(t, r, n);
1437
1437
  a.push(...o.ops);
1438
1438
  for (let e of t.tables) if (!o.renamedInto.has(e.name) && !r.has(e.name)) {
1439
1439
  a.push(gn(e.name, e.columns, e.indexes, e.primaryKey, o.refusals.get(e.name)));
@@ -1443,31 +1443,31 @@ BEGIN
1443
1443
  }
1444
1444
  }
1445
1445
  let s = new Set(e.ignoreTables ?? []);
1446
- for (let t of e.live.tables) n.has(t.name) || o.claimedOldNames.has(t.name) || h(t.name) || y(t.name) || s.has(t.name) || a.push(_n(t.name));
1446
+ for (let t of e.live.tables) n.has(t.name) || o.claimedOldNames.has(t.name) || h(t.name) || f(t.name) || s.has(t.name) || a.push(_n(t.name));
1447
1447
  for (let s of t.tables) {
1448
1448
  let t = o.renamedInto.get(s.name), c = r.get(s.name) ?? (t === void 0 ? void 0 : r.get(t));
1449
1449
  if (!c) continue;
1450
1450
  let l = jn(c, t, s.name, e.dialect);
1451
1451
  a.push(...l.ops);
1452
- let u = l.live, d = n.get(s.name), f = fn(s, u, e.dialect), p = pn(s, u), m = Tn(d.table, d.columnDefs, f);
1453
- a.push(...m.ops);
1454
- for (let e of f.removed) {
1455
- if (m.consumedRemovedNames.has(e.name) || y(e.name)) continue;
1452
+ let u = l.live, d = n.get(s.name), p = fn(s, u, e.dialect), m = pn(s, u), h = Tn(d.table, d.columnDefs, p);
1453
+ a.push(...h.ops);
1454
+ for (let e of p.removed) {
1455
+ if (h.consumedRemovedNames.has(e.name) || f(e.name)) continue;
1456
1456
  let t = d.columnDefs[e.name];
1457
1457
  a.push(hn(s.name, e, t));
1458
1458
  }
1459
- for (let e of f.added) {
1460
- if (m.consumedAddedNames.has(e.name)) continue;
1459
+ for (let e of p.added) {
1460
+ if (h.consumedAddedNames.has(e.name)) continue;
1461
1461
  let t = d.columnDefs[e.name];
1462
1462
  a.push(mn(s.name, e, t));
1463
1463
  let n = un(s.name, e);
1464
1464
  n && a.push(n), a.push(...wn(s.name, e));
1465
1465
  }
1466
- let h = new Map(m.ops.flatMap((e) => e.op.kind === "rename-column" ? [[e.op.from, e.op.to]] : [])), g = kn(s.name, p, h, new Set(u.indexes.map((e) => e.name)), e.dialect);
1467
- a.push(...g.ops);
1468
- for (let e of p.added) g.consumedAddedNames.has(e.name) || a.push(yn(s.name, e, u.rowCount, i));
1469
- for (let e of p.removed) g.consumedRemovedNames.has(e.name) || a.push(bn(s.name, e));
1470
- for (let { declared: t, live: n } of f.changed) a.push(...Cn(s.name, t, n, e.dialect, u.rowCount, i));
1466
+ let g = new Map(h.ops.flatMap((e) => e.op.kind === "rename-column" ? [[e.op.from, e.op.to]] : [])), _ = kn(s.name, m, g, new Set(u.indexes.map((e) => e.name)), e.dialect);
1467
+ a.push(..._.ops);
1468
+ for (let e of m.added) _.consumedAddedNames.has(e.name) || a.push(yn(s.name, e, u.rowCount, i));
1469
+ for (let e of m.removed) _.consumedRemovedNames.has(e.name) || a.push(bn(s.name, e));
1470
+ for (let { declared: t, live: n } of p.changed) a.push(...Cn(s.name, t, n, e.dialect, u.rowCount, i));
1471
1471
  }
1472
1472
  let c = new Set(a.flatMap((e) => e.op.kind === "create-table" ? [e.op.table] : [])), l = new Map(t.tables.map((e) => [e.name, e])), u = (e) => {
1473
1473
  let t = l.get(e);
@@ -1475,8 +1475,8 @@ BEGIN
1475
1475
  column: e.name,
1476
1476
  target: e.references.table
1477
1477
  }] : []) : [];
1478
- }, d = fe([...c], u), f = [];
1479
- for (let e of t.tables) if (c.has(e.name)) for (let t of e.columns) !t.references || !d.has(w(e.name, t.name)) || f.push(L({
1478
+ }, d = ue([...c], u), p = [];
1479
+ for (let e of t.tables) if (c.has(e.name)) for (let t of e.columns) !t.references || !d.has(D(e.name, t.name)) || p.push(R({
1480
1480
  kind: "add-foreign-key",
1481
1481
  table: e.name,
1482
1482
  column: t.name,
@@ -1491,8 +1491,8 @@ BEGIN
1491
1491
  let n = a[t];
1492
1492
  if (n.op.kind !== "create-table") continue;
1493
1493
  let r = n.op;
1494
- if (!r.columns.some((e) => d.has(w(r.table, e.name)))) continue;
1495
- let i = r.columns.map((t) => d.has(w(r.table, t.name)) ? e(t) : t);
1494
+ if (!r.columns.some((e) => d.has(D(r.table, e.name)))) continue;
1495
+ let i = r.columns.map((t) => d.has(D(r.table, t.name)) ? e(t) : t);
1496
1496
  a[t] = {
1497
1497
  ...n,
1498
1498
  op: {
@@ -1501,23 +1501,23 @@ BEGIN
1501
1501
  }
1502
1502
  };
1503
1503
  }
1504
- a.push(...f);
1504
+ a.push(...p);
1505
1505
  }
1506
- let p = new Map(t.tables.map((e) => [e.name, e])), m = /* @__PURE__ */ new Map(), g = (e, t = /* @__PURE__ */ new Set()) => {
1507
- let n = m.get(e);
1506
+ let m = new Map(t.tables.map((e) => [e.name, e])), g = /* @__PURE__ */ new Map(), _ = (e, t = /* @__PURE__ */ new Set()) => {
1507
+ let n = g.get(e);
1508
1508
  if (n !== void 0) return n;
1509
1509
  if (t.has(e)) return 0;
1510
- let r = p.get(e);
1510
+ let r = m.get(e);
1511
1511
  if (!r) return 0;
1512
1512
  let i = new Set(t).add(e), a = 0;
1513
1513
  for (let t of r.columns) {
1514
1514
  let n = t.references?.table;
1515
- n && n !== e && !d.has(w(e, t.name)) && (a = Math.max(a, g(n, i) + 1));
1515
+ n && n !== e && !d.has(D(e, t.name)) && (a = Math.max(a, _(n, i) + 1));
1516
1516
  }
1517
- return m.set(e, a), a;
1518
- }, _ = (e) => e === "rename-table" ? -1 : e === "create-table" ? 0 : e === "drop-table" ? 2 : 1, v = (e) => {
1517
+ return g.set(e, a), a;
1518
+ }, v = (e) => e === "rename-table" ? -1 : e === "create-table" ? 0 : e === "drop-table" ? 2 : 1, y = (e) => {
1519
1519
  let t = "table" in e ? e.table : "";
1520
- return e.kind === "create-table" ? g(t) : e.kind === "drop-table" ? -g(t) : 0;
1520
+ return e.kind === "create-table" ? _(t) : e.kind === "drop-table" ? -_(t) : 0;
1521
1521
  }, b = {
1522
1522
  "add-column": 0,
1523
1523
  "rename-column": 1,
@@ -1537,9 +1537,9 @@ BEGIN
1537
1537
  "add-foreign-key": 5,
1538
1538
  "add-check": 5
1539
1539
  }, x = (e) => b[e] ?? 9, S = [...a].sort((e, t) => {
1540
- let n = _(e.op.kind), r = _(t.op.kind);
1540
+ let n = v(e.op.kind), r = v(t.op.kind);
1541
1541
  if (n !== r) return n - r;
1542
- let i = v(e.op), a = v(t.op);
1542
+ let i = y(e.op), a = y(t.op);
1543
1543
  if (i !== a) return i - a;
1544
1544
  let o = "table" in e.op ? e.op.table : "", s = "table" in t.op ? t.op.table : "";
1545
1545
  if (o !== s) return o.localeCompare(s);
@@ -1548,8 +1548,8 @@ BEGIN
1548
1548
  });
1549
1549
  return {
1550
1550
  operations: S,
1551
- fromFingerprint: P(e.live),
1552
- toFingerprint: P(t),
1551
+ fromFingerprint: Wt(e.live),
1552
+ toFingerprint: Wt(t),
1553
1553
  summary: Mn(S)
1554
1554
  };
1555
1555
  }, Pn = (e) => {
@@ -1590,7 +1590,7 @@ BEGIN
1590
1590
  }, In = (e, t) => e == null || e === "" ? void 0 : { generatedAs: {
1591
1591
  expr: e,
1592
1592
  stored: t
1593
- } }, R = (e) => {
1593
+ } }, z = (e) => {
1594
1594
  switch (e.toUpperCase()) {
1595
1595
  case "CASCADE": return "cascade";
1596
1596
  case "RESTRICT": return "restrict";
@@ -1609,9 +1609,9 @@ BEGIN
1609
1609
  for (let t = 0; t < e.length; t += n) r.push(e.slice(t, t + n));
1610
1610
  return r;
1611
1611
  }, Hn = (e) => {
1612
- let t = Bn(), n = x.gen(function* () {
1612
+ let t = Bn(), n = S.gen(function* () {
1613
1613
  t > 0 && (yield* e.unsafe(`SET LOCAL statement_timeout = ${t}`));
1614
- let n = (t) => e.unsafe("(" + t.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ") + ")"), r = (t) => e.unsafe(String(Math.max(0, Math.trunc(t)))), i = Rn(), a = (e, t) => x.gen(function* () {
1614
+ let n = (t) => e.unsafe("(" + t.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ") + ")"), r = (t) => e.unsafe(String(Math.max(0, Math.trunc(t)))), i = Rn(), a = (e, t) => S.gen(function* () {
1615
1615
  let r = [];
1616
1616
  for (let a of Vn(e, i)) a.length !== 0 && r.push(...yield* t(n(a)));
1617
1617
  return r;
@@ -1712,7 +1712,7 @@ BEGIN
1712
1712
  AND c.relname IN ${t}
1713
1713
  )
1714
1714
  SELECT * FROM ix ORDER BY table_name, index_name, position
1715
- `), _ = /* @__PURE__ */ new Map(), v = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map(), S = /* @__PURE__ */ new Map(), ee = /* @__PURE__ */ new Map();
1715
+ `), _ = /* @__PURE__ */ new Map(), v = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map(), x = /* @__PURE__ */ new Map(), C = /* @__PURE__ */ new Map();
1716
1716
  for (let e of u) {
1717
1717
  let t = _.get(e.table_name);
1718
1718
  t || (t = [], _.set(e.table_name, t)), t.push(e);
@@ -1721,18 +1721,18 @@ BEGIN
1721
1721
  let t = v.get(e.table_name);
1722
1722
  t || (t = /* @__PURE__ */ new Set(), v.set(e.table_name, t)), t.add(e.column_name);
1723
1723
  }
1724
- let te = /* @__PURE__ */ new Map();
1724
+ let w = /* @__PURE__ */ new Map();
1725
1725
  for (let e of f) {
1726
- let t = `${e.table_name}\u0000${e.constraint_name}`, n = te.get(t);
1726
+ let t = `${e.table_name}\u0000${e.constraint_name}`, n = w.get(t);
1727
1727
  n || (n = {
1728
1728
  table: e.table_name,
1729
1729
  columns: []
1730
- }, te.set(t, n)), n.columns.push({
1730
+ }, w.set(t, n)), n.columns.push({
1731
1731
  name: e.column_name,
1732
1732
  position: e.position
1733
1733
  });
1734
1734
  }
1735
- for (let [e, t] of te) {
1735
+ for (let [e, t] of w) {
1736
1736
  let n = [...t.columns].sort((e, t) => e.position - t.position).map((e) => e.name);
1737
1737
  if (n.length === 1) {
1738
1738
  let e = y.get(t.table);
@@ -1748,28 +1748,28 @@ BEGIN
1748
1748
  }
1749
1749
  }
1750
1750
  for (let e of h) {
1751
- let t = S.get(e.source_table);
1752
- t || (t = [], S.set(e.source_table, t)), t.push(e);
1751
+ let t = x.get(e.source_table);
1752
+ t || (t = [], x.set(e.source_table, t)), t.push(e);
1753
1753
  }
1754
1754
  for (let e of g) {
1755
- let t = ee.get(e.table_name);
1756
- t || (t = /* @__PURE__ */ new Map(), ee.set(e.table_name, t));
1755
+ let t = C.get(e.table_name);
1756
+ t || (t = /* @__PURE__ */ new Map(), C.set(e.table_name, t));
1757
1757
  let n = t.get(e.index_name);
1758
1758
  n || (n = [], t.set(e.index_name, n)), n.push(e);
1759
1759
  }
1760
- let C = [];
1760
+ let T = [];
1761
1761
  for (let e of c) {
1762
- let t = /* @__PURE__ */ new Set(), n = (_.get(e.table_name) ?? []).filter((e) => !t.has(e.column_name) && (t.add(e.column_name), !0)), r = v.get(e.table_name) ?? /* @__PURE__ */ new Set(), i = y.get(e.table_name) ?? /* @__PURE__ */ new Set(), a = S.get(e.table_name) ?? [], o = new Map(a.map((e) => [e.source_column, e])), s = new Set(n.filter((e) => e.udt_name === "tsvector").map((e) => e.column_name)), c = n.filter((e) => !s.has(e.column_name)).map((t) => {
1762
+ let t = /* @__PURE__ */ new Set(), n = (_.get(e.table_name) ?? []).filter((e) => !t.has(e.column_name) && (t.add(e.column_name), !0)), r = v.get(e.table_name) ?? /* @__PURE__ */ new Set(), i = y.get(e.table_name) ?? /* @__PURE__ */ new Set(), a = x.get(e.table_name) ?? [], o = new Map(a.map((e) => [e.source_column, e])), s = new Set(n.filter((e) => e.udt_name === "tsvector").map((e) => e.column_name)), c = n.filter((e) => !s.has(e.column_name)).map((t) => {
1763
1763
  let n = r.has(t.column_name) && r.size === 1, a = o.get(t.column_name), s = a ? "reference" : n && t.column_name === "id" ? "id" : Fn(t.data_type, t.udt_name), c = a ? {
1764
1764
  table: a.target_table,
1765
1765
  column: a.target_column,
1766
- onDelete: R(a.delete_rule),
1767
- onUpdate: R(a.update_rule)
1766
+ onDelete: z(a.delete_rule),
1767
+ onUpdate: z(a.update_rule)
1768
1768
  } : void 0, l = m.get(`${e.table_name}.${t.column_name}`);
1769
1769
  return {
1770
1770
  name: t.column_name,
1771
1771
  type: s,
1772
- ...V(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: V(t.data_type, t.character_maximum_length) },
1772
+ ...H(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: H(t.data_type, t.character_maximum_length) },
1773
1773
  nullable: t.is_nullable === "YES",
1774
1774
  unique: i.has(t.column_name) || n && t.column_name === "id",
1775
1775
  hasDefault: t.column_default !== null,
@@ -1778,7 +1778,7 @@ BEGIN
1778
1778
  ...l ? { oneOf: l } : {},
1779
1779
  ...In(t.is_generated === "ALWAYS" ? t.generation_expression ?? "generated" : null, !0) ?? {}
1780
1780
  };
1781
- }), l = [], u = ee.get(e.table_name);
1781
+ }), l = [], u = C.get(e.table_name);
1782
1782
  if (u) for (let [t, n] of u) {
1783
1783
  let r = /* @__PURE__ */ new Set(), i = [...n].filter((e) => e.column_name !== null && e.position !== null).sort((e, t) => (e.position ?? 0) - (t.position ?? 0)).filter((e) => {
1784
1784
  let t = e.position;
@@ -1802,18 +1802,18 @@ BEGIN
1802
1802
  unique: !0
1803
1803
  });
1804
1804
  let d = Number(e.row_count ?? 0);
1805
- C.push({
1805
+ T.push({
1806
1806
  name: e.table_name,
1807
1807
  columns: c,
1808
1808
  indexes: l,
1809
1809
  ...d > 0 ? { rowCount: d } : {}
1810
1810
  });
1811
1811
  }
1812
- return { tables: C };
1812
+ return { tables: T };
1813
1813
  });
1814
- return (t > 0 ? e.withTransaction(n) : n).pipe(x.catchAll((e) => {
1814
+ return (t > 0 ? e.withTransaction(n) : n).pipe(S.catchAll((e) => {
1815
1815
  let n = `${String(e)} ${String(e.cause ?? "")}`.toLowerCase();
1816
- return n.includes("statement timeout") || n.includes("57014") ? x.die(/* @__PURE__ */ Error(`schema introspection exceeded VOLTRO_INTROSPECT_TIMEOUT_MS (${t}ms) — the schema is very large / FK-dense or the database is slow. Raise VOLTRO_INTROSPECT_TIMEOUT_MS, set it to 0 to disable the ceiling, or use DB_DIRECT_URL for a non-pooler connection.`)) : x.fail(e);
1816
+ return n.includes("statement timeout") || n.includes("57014") ? S.die(/* @__PURE__ */ Error(`schema introspection exceeded VOLTRO_INTROSPECT_TIMEOUT_MS (${t}ms) — the schema is very large / FK-dense or the database is slow. Raise VOLTRO_INTROSPECT_TIMEOUT_MS, set it to 0 to disable the ceiling, or use DB_DIRECT_URL for a non-pooler connection.`)) : S.fail(e);
1817
1817
  }));
1818
1818
  }, Un = (e, t) => {
1819
1819
  switch (e.toLowerCase()) {
@@ -1847,21 +1847,21 @@ BEGIN
1847
1847
  case "json": return "json";
1848
1848
  default: return "text";
1849
1849
  }
1850
- }, z = (e) => e.map((e) => {
1850
+ }, B = (e) => e.map((e) => {
1851
1851
  let t = e, n = {};
1852
1852
  for (let e of Object.keys(t)) n[e.toLowerCase()] = t[e];
1853
1853
  return n;
1854
- }), Wn = (e) => x.gen(function* () {
1855
- let t = z(yield* e`
1854
+ }), Wn = (e) => S.gen(function* () {
1855
+ let t = B(yield* e`
1856
1856
  SELECT table_name, COALESCE(table_rows, 0) AS table_rows
1857
1857
  FROM information_schema.tables
1858
1858
  WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
1859
- ORDER BY table_name`), n = z(yield* e`
1859
+ ORDER BY table_name`), n = B(yield* e`
1860
1860
  SELECT table_name, column_name, data_type, column_type, is_nullable, column_default, column_key,
1861
1861
  character_maximum_length, generation_expression, extra
1862
1862
  FROM information_schema.columns
1863
1863
  WHERE table_schema = DATABASE()
1864
- ORDER BY table_name, ordinal_position`), r = z(yield* e`
1864
+ ORDER BY table_name, ordinal_position`), r = B(yield* e`
1865
1865
  SELECT k.table_name AS source_table,
1866
1866
  k.column_name AS source_column,
1867
1867
  k.referenced_table_name AS target_table,
@@ -1871,7 +1871,7 @@ BEGIN
1871
1871
  JOIN information_schema.referential_constraints r
1872
1872
  ON k.constraint_name = r.constraint_name
1873
1873
  AND k.table_schema = r.constraint_schema
1874
- WHERE k.table_schema = DATABASE() AND k.referenced_table_name IS NOT NULL`), i = z(yield* e`
1874
+ WHERE k.table_schema = DATABASE() AND k.referenced_table_name IS NOT NULL`), i = B(yield* e`
1875
1875
  SELECT table_name, index_name, non_unique, column_name, seq_in_index
1876
1876
  FROM information_schema.statistics
1877
1877
  WHERE table_schema = DATABASE() AND index_name <> 'PRIMARY'
@@ -1884,7 +1884,7 @@ BEGIN
1884
1884
  JOIN information_schema.table_constraints tc
1885
1885
  ON tc.constraint_schema = cc.constraint_schema
1886
1886
  AND tc.constraint_name = cc.constraint_name
1887
- WHERE cc.constraint_schema = DATABASE()`.unprepared, s = z(yield* a.pipe(x.orElse(() => o), x.orElseSucceed(() => []))), c = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Map();
1887
+ WHERE cc.constraint_schema = DATABASE()`.unprepared, s = B(yield* a.pipe(S.orElse(() => o), S.orElseSucceed(() => []))), c = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Map();
1888
1888
  for (let e of s) {
1889
1889
  let t = /json_valid\(`?([^`)]+)`?\)/i.exec(e.check_clause);
1890
1890
  if (t) {
@@ -1917,14 +1917,14 @@ BEGIN
1917
1917
  let n = i.includes(t.column_name) && i.length === 1, o = r.get(t.column_name), s = o ? "reference" : n && t.column_name === "id" ? "id" : c.has(`${e.table_name}.${t.column_name}`) ? "json" : Un(t.data_type, t.column_type), u = o ? {
1918
1918
  table: o.target_table,
1919
1919
  column: o.target_column,
1920
- onDelete: R(o.delete_rule),
1921
- onUpdate: R(o.update_rule)
1920
+ onDelete: z(o.delete_rule),
1921
+ onUpdate: z(o.update_rule)
1922
1922
  } : void 0, d = a.has(t.column_name) || n && t.column_name === "id", f = t.column_default === "NULL" ? null : t.column_default, p = l.get(`${e.table_name}.${t.column_name}`);
1923
1923
  return {
1924
1924
  name: t.column_name,
1925
1925
  type: s,
1926
1926
  nullable: t.is_nullable === "YES",
1927
- ...V(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: V(t.data_type, t.character_maximum_length) },
1927
+ ...H(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: H(t.data_type, t.character_maximum_length) },
1928
1928
  unique: d,
1929
1929
  hasDefault: f !== null,
1930
1930
  ...f === null ? {} : { defaultValue: f },
@@ -1960,7 +1960,7 @@ BEGIN
1960
1960
  }), Gn = (e) => {
1961
1961
  let t = e.toUpperCase();
1962
1962
  return t.includes("INT") ? "integer" : t.includes("REAL") || t.includes("FLOA") || t.includes("DOUB") ? "real" : t.includes("BLOB") ? "bytes" : "text";
1963
- }, Kn = (e) => x.gen(function* () {
1963
+ }, Kn = (e) => S.gen(function* () {
1964
1964
  let t = yield* e`
1965
1965
  SELECT name, sql FROM sqlite_master
1966
1966
  WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
@@ -1980,8 +1980,8 @@ BEGIN
1980
1980
  let n = u.length === 1 && u[0] === e.name, r = l.get(e.name), i = r ? "reference" : n && e.name === "id" ? "id" : Gn(e.type), a = r ? {
1981
1981
  table: r.table,
1982
1982
  column: r.to,
1983
- onDelete: R(r.on_delete),
1984
- onUpdate: R(r.on_update)
1983
+ onDelete: z(r.on_delete),
1984
+ onUpdate: z(r.on_update)
1985
1985
  } : void 0, o = t.get(e.name);
1986
1986
  return {
1987
1987
  name: e.name,
@@ -2039,14 +2039,14 @@ BEGIN
2039
2039
  case "image": return "bytes";
2040
2040
  default: return "text";
2041
2041
  }
2042
- }, B = (e) => e === !0 || e === 1, Jn = (e) => x.gen(function* () {
2042
+ }, V = (e) => e === !0 || e === 1, Jn = (e) => S.gen(function* () {
2043
2043
  let t = yield* e`
2044
2044
  SELECT TABLE_NAME AS table_name FROM INFORMATION_SCHEMA.TABLES
2045
2045
  WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`, n = yield* e`
2046
2046
  SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name, DATA_TYPE AS data_type,
2047
2047
  IS_NULLABLE AS is_nullable, COLUMN_DEFAULT AS column_default,
2048
2048
  CHARACTER_MAXIMUM_LENGTH AS character_maximum_length
2049
- FROM INFORMATION_SCHEMA.COLUMNS ORDER BY TABLE_NAME, ORDINAL_POSITION`, r = yield* x.orElseSucceed(e`
2049
+ FROM INFORMATION_SCHEMA.COLUMNS ORDER BY TABLE_NAME, ORDINAL_POSITION`, r = yield* S.orElseSucceed(e`
2050
2050
  SELECT t.name AS table_name, c.name AS column_name, cc.definition AS definition,
2051
2051
  cc.is_persisted AS is_persisted
2052
2052
  FROM sys.computed_columns cc
@@ -2101,8 +2101,8 @@ BEGIN
2101
2101
  let t = l.get(e) ?? [], n = u.get(e) ?? [], r = new Map(n.map((e) => [e.source_column, e])), a = new Set(n.map((e) => e.source_column)), o = d.get(e), s = [], p = /* @__PURE__ */ new Set();
2102
2102
  if (o) for (let [, e] of o) {
2103
2103
  let t = [...e].sort((e, t) => e.key_ordinal - t.key_ordinal);
2104
- if (B(t[0].is_primary)) for (let e of t) s.push(e.column_name);
2105
- else B(t[0].is_unique) && t.length === 1 && p.add(t[0].column_name);
2104
+ if (V(t[0].is_primary)) for (let e of t) s.push(e.column_name);
2105
+ else V(t[0].is_unique) && t.length === 1 && p.add(t[0].column_name);
2106
2106
  }
2107
2107
  let m = t.map((t) => {
2108
2108
  let n = s.length === 1 && s[0] === t.column_name, a = r.get(t.column_name), o = a ? "reference" : n && t.column_name === "id" ? "id" : qn(t.data_type), l = a ? {
@@ -2115,22 +2115,22 @@ BEGIN
2115
2115
  name: t.column_name,
2116
2116
  type: o,
2117
2117
  nullable: t.is_nullable === "YES",
2118
- ...V(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: V(t.data_type, t.character_maximum_length) },
2118
+ ...H(t.data_type, t.character_maximum_length) === void 0 ? {} : { maxLength: H(t.data_type, t.character_maximum_length) },
2119
2119
  unique: p.has(t.column_name) || n && t.column_name === "id",
2120
2120
  hasDefault: u !== null,
2121
2121
  ...u === null ? {} : { defaultValue: u },
2122
2122
  ...l ? { references: l } : {},
2123
2123
  ...d ? { oneOf: d } : {},
2124
- ...In(i.get(`${e}.${t.column_name}`)?.definition ?? null, B(i.get(`${e}.${t.column_name}`)?.is_persisted ?? !1)) ?? {}
2124
+ ...In(i.get(`${e}.${t.column_name}`)?.definition ?? null, V(i.get(`${e}.${t.column_name}`)?.is_persisted ?? !1)) ?? {}
2125
2125
  };
2126
2126
  }), h = [];
2127
2127
  if (o) for (let [t, n] of o) {
2128
2128
  let r = [...n].sort((e, t) => e.key_ordinal - t.key_ordinal);
2129
- B(r[0].is_primary) || r.length === 1 && B(r[0].is_unique) || r.length === 1 && !B(r[0].is_unique) && a.has(r[0].column_name) && t !== `${e}_${r[0].column_name}_idx` || h.push({
2129
+ V(r[0].is_primary) || r.length === 1 && V(r[0].is_unique) || r.length === 1 && !V(r[0].is_unique) && a.has(r[0].column_name) && t !== `${e}_${r[0].column_name}_idx` || h.push({
2130
2130
  name: t,
2131
2131
  table: e,
2132
2132
  columns: r.map((e) => e.column_name),
2133
- unique: B(r[0].is_unique)
2133
+ unique: V(r[0].is_unique)
2134
2134
  });
2135
2135
  }
2136
2136
  s.length > 0 && h.push({
@@ -2163,25 +2163,25 @@ BEGIN
2163
2163
  "char",
2164
2164
  "character",
2165
2165
  "nchar"
2166
- ]), V = (e, t) => {
2166
+ ]), H = (e, t) => {
2167
2167
  if (!Zn.has(e.toLowerCase())) return;
2168
2168
  let n = Number(t);
2169
2169
  if (!(!Number.isFinite(n) || n <= 0)) return n;
2170
- }, Qn = /* @__PURE__ */ new Set([D]), $n = (e) => e.onDialectOrElse({
2170
+ }, Qn = /* @__PURE__ */ new Set([k]), $n = (e) => e.onDialectOrElse({
2171
2171
  mysql: () => Wn(e),
2172
2172
  mssql: () => Jn(e),
2173
2173
  sqlite: () => Kn(e),
2174
2174
  orElse: () => Hn(e)
2175
- }).pipe(x.map((e) => ({
2175
+ }).pipe(S.map((e) => ({
2176
2176
  ...e,
2177
2177
  tables: e.tables.filter((e) => !Qn.has(e.name))
2178
- }))), er = (e) => /mariadb/i.test(e) ? "mariadb" : "mysql", tr = /* @__PURE__ */ new WeakMap(), H = (e) => x.suspend(() => {
2178
+ }))), er = (e) => /mariadb/i.test(e) ? "mariadb" : "mysql", tr = /* @__PURE__ */ new WeakMap(), U = (e) => S.suspend(() => {
2179
2179
  let t = tr.get(e);
2180
- return t === void 0 ? nr(e).pipe(x.tap((t) => x.sync(() => tr.set(e, t)))) : x.succeed(t);
2181
- }), nr = (e) => e.unsafe("SELECT VERSION() AS v").pipe(x.map((e) => {
2180
+ return t === void 0 ? nr(e).pipe(S.tap((t) => S.sync(() => tr.set(e, t)))) : S.succeed(t);
2181
+ }), nr = (e) => e.unsafe("SELECT VERSION() AS v").pipe(S.map((e) => {
2182
2182
  let t = e[0]?.v;
2183
2183
  return typeof t == "string" ? er(t) : "mysql";
2184
- }), x.catchAll(() => x.succeed("mysql"))), rr = (e) => {
2184
+ }), S.catchAll(() => S.succeed("mysql"))), rr = (e) => {
2185
2185
  let t = e;
2186
2186
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
2187
2187
  let e = t;
@@ -2211,14 +2211,14 @@ BEGIN
2211
2211
  }, lr = {
2212
2212
  why: "mysql/mariadb DROP CONSTRAINT has no portable IF EXISTS; 1091 / 3940 are exactly \"already gone\"",
2213
2213
  errno: [1091, 3940]
2214
- }, U = (e, t) => e.onDialectOrElse({
2215
- mysql: () => x.succeed(t.replace("T", " ").replace("Z", "")),
2216
- orElse: () => x.succeed(t)
2214
+ }, W = (e, t) => e.onDialectOrElse({
2215
+ mysql: () => S.succeed(t.replace("T", " ").replace("Z", "")),
2216
+ orElse: () => S.succeed(t)
2217
2217
  }), ur = (e, t) => `${t}(${e.precision ?? 38}, ${e.scale ?? 0})`, dr = (e) => e.type === "text" && (e.hasDefault && e.defaultValue !== void 0 || e.oneOf !== void 0 && e.oneOf.length > 0), fr = (e, t) => {
2218
2218
  if ((e.type !== "text" || e.maxLength === void 0) && !dr(e) && !e.spatial && e.type !== "vector" && e.type !== "array" && e.type !== "enum") return;
2219
2219
  let n = e.type === "vector" && e.vectorDim === void 0 ? "vector dimension" : e.type === "array" && e.arrayElement === void 0 ? "array element type" : e.type === "enum" && e.enumName === void 0 && e.enumValues === void 0 ? "enum name/values" : void 0;
2220
2220
  if (n !== void 0) throw Error(`migration applier: cannot render '${e.name}' (${e.type}) — the schema snapshot carries no ${n}. Rendering it as 'text' would emit DDL that applies successfully and changes nothing, so this fails instead. This is a framework bug: declaredSchema.ts must carry the parameter into the ColumnSnapshot.`);
2221
- return A(e, t);
2221
+ return M(e, t);
2222
2222
  }, pr = (e) => {
2223
2223
  let t = fr(e, "postgres");
2224
2224
  return t === void 0 ? mr(e) : t;
@@ -2264,9 +2264,9 @@ BEGIN
2264
2264
  case "interval": return "BIGINT";
2265
2265
  case "raw": return e.rawDdl ?? "LONGTEXT";
2266
2266
  }
2267
- }, W = (e) => `"${e}"`, G = (e) => `\`${e.replace(/`/g, "``")}\``, gr = (e) => e === "mariadb" ? "IF NOT EXISTS " : "", _r = (e, t, n = !0) => `ALTER TABLE ${t(e.table)} DROP COLUMN ${n ? "IF EXISTS " : ""}${t(e.column)};`, vr = (e, t = "mariadb") => `ALTER TABLE ${G(e.table)} DROP COLUMN ${t === "mariadb" ? "IF EXISTS " : ""}${G(e.column)}, ALGORITHM=COPY;`, yr = (e, t) => `ALTER TABLE ${t(e.table)} RENAME COLUMN ${t(e.from)} TO ${t(e.to)};`, br = (e, t, n) => `ALTER TABLE ${n(e.table)} RENAME COLUMN ${n(e.column)} TO ${n(`${e.column}${Jr(t)}`)};`, xr = (e, t, n) => e.hasDefault && e.defaultValue !== void 0 ? `ALTER TABLE ${t(e.table)} ALTER COLUMN ${t(e.column)} SET ${Cr(e, n)};` : `ALTER TABLE ${t(e.table)} ALTER COLUMN ${t(e.column)} DROP DEFAULT;`, Sr = (e, t) => {
2267
+ }, G = (e) => `"${e}"`, K = (e) => `\`${e.replace(/`/g, "``")}\``, gr = (e) => e === "mariadb" ? "IF NOT EXISTS " : "", _r = (e, t, n = !0) => `ALTER TABLE ${t(e.table)} DROP COLUMN ${n ? "IF EXISTS " : ""}${t(e.column)};`, vr = (e, t = "mariadb") => `ALTER TABLE ${K(e.table)} DROP COLUMN ${t === "mariadb" ? "IF EXISTS " : ""}${K(e.column)}, ALGORITHM=COPY;`, yr = (e, t) => `ALTER TABLE ${t(e.table)} RENAME COLUMN ${t(e.from)} TO ${t(e.to)};`, br = (e, t, n) => `ALTER TABLE ${n(e.table)} RENAME COLUMN ${n(e.column)} TO ${n(`${e.column}${Yr(t)}`)};`, xr = (e, t, n) => e.hasDefault && e.defaultValue !== void 0 ? `ALTER TABLE ${t(e.table)} ALTER COLUMN ${t(e.column)} SET ${Cr(e, n)};` : `ALTER TABLE ${t(e.table)} ALTER COLUMN ${t(e.column)} DROP DEFAULT;`, Sr = (e, t) => {
2268
2268
  let { defaultFactory: n, ...r } = e;
2269
- return A(e, t) !== A({
2269
+ return M(e, t) !== M({
2270
2270
  ...r,
2271
2271
  hasDefault: !1
2272
2272
  }, t);
@@ -2274,54 +2274,54 @@ BEGIN
2274
2274
  let n = t(e.defaultValue);
2275
2275
  if (n === null) throw Error(`migration applier: cannot render the declared default for '${e.table}.${e.column}' (${JSON.stringify(e.defaultValue)}). Emitting 'DEFAULT NULL' would apply cleanly and drop the default silently, so this fails instead. This is a framework bug — report the column type + default.`);
2276
2276
  return n;
2277
- }, K = (e, t, n) => e.find((e) => e.tableName === t)?.fields[n], wr = (e, t, n) => {
2278
- let r = K(e, t, n);
2277
+ }, q = (e, t, n) => e.find((e) => e.tableName === t)?.fields[n], wr = (e, t, n) => {
2278
+ let r = q(e, t, n);
2279
2279
  return r ? Kt(n, r) : void 0;
2280
2280
  }, Tr = (e, t, n) => {
2281
- let r = n ?? e.nullable, i = $e(e, "mariadb");
2281
+ let r = n ?? e.nullable, i = Qe(e, "mariadb");
2282
2282
  return [
2283
- G(t),
2284
- A(e, "mariadb"),
2283
+ K(t),
2284
+ M(e, "mariadb"),
2285
2285
  r ? null : "NOT NULL",
2286
2286
  i
2287
2287
  ].filter(Boolean).join(" ");
2288
- }, Er = (e, t) => e == null ? null : Array.isArray(e) ? Dr(e, t, "mariadb") : e === "now" ? "DEFAULT CURRENT_TIMESTAMP(6)" : typeof e == "boolean" ? `DEFAULT ${+!!e}` : typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? j(e, "mariadb") : null, Dr = (e, t, n) => et(e, t ?? { type: "json" }, n), Or = (e, t) => e == null ? null : Array.isArray(e) ? Dr(e, t, "postgres") : e === "now" ? "DEFAULT now()" : typeof e == "boolean" || typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|::|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? j(e, "postgres") : null, q = (e, t) => {
2288
+ }, Er = (e, t) => e == null ? null : Array.isArray(e) ? Dr(e, t, "mariadb") : e === "now" ? "DEFAULT CURRENT_TIMESTAMP(6)" : typeof e == "boolean" ? `DEFAULT ${+!!e}` : typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? N(e, "mariadb") : null, Dr = (e, t, n) => $e(e, t ?? { type: "json" }, n), Or = (e, t) => e == null ? null : Array.isArray(e) ? Dr(e, t, "postgres") : e === "now" ? "DEFAULT now()" : typeof e == "boolean" || typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|::|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? N(e, "postgres") : null, kr = (e, t) => {
2289
2289
  if (!e.generatedAs) return null;
2290
2290
  let { expr: n, stored: r } = e.generatedAs;
2291
2291
  return t === "postgres" ? `GENERATED ALWAYS AS (${n}) STORED` : t === "mssql" ? `AS (${n})${r ? " PERSISTED" : ""}` : `GENERATED ALWAYS AS (${n}) ${r ? "STORED" : "VIRTUAL"}`;
2292
- }, kr = (e) => {
2293
- if (e.type === "id" && e.idScheme?.kind === "numeric") return M(e.name, "postgres");
2294
- let t = q(e, "postgres");
2295
- if (t) return `${W(e.name)} ${pr(e)} ${t}`;
2296
- let n = [W(e.name), pr(e)];
2292
+ }, Ar = (e) => {
2293
+ if (e.type === "id" && e.idScheme?.kind === "numeric") return P(e.name, "postgres");
2294
+ let t = kr(e, "postgres");
2295
+ if (t) return `${G(e.name)} ${pr(e)} ${t}`;
2296
+ let n = [G(e.name), pr(e)];
2297
2297
  if (e.type === "id" && n.push("PRIMARY KEY"), e.nullable || n.push("NOT NULL"), e.unique && e.type !== "id" && n.push("UNIQUE"), e.hasDefault) {
2298
2298
  let t = Or(e.defaultValue, e);
2299
2299
  t && n.push(t);
2300
2300
  }
2301
- return e.references && (n.push(`REFERENCES ${W(e.references.table)} (${W(e.references.column)})`), e.references.onDelete && n.push(`ON DELETE ${{
2301
+ return e.references && (n.push(`REFERENCES ${G(e.references.table)} (${G(e.references.column)})`), e.references.onDelete && n.push(`ON DELETE ${{
2302
2302
  cascade: "CASCADE",
2303
2303
  restrict: "RESTRICT",
2304
2304
  setNull: "SET NULL",
2305
2305
  noAction: "NO ACTION"
2306
2306
  }[e.references.onDelete]}`)), n.join(" ");
2307
- }, Ar = (e, t) => e.primaryKey && e.primaryKey.length > 0 ? `,\n PRIMARY KEY (${e.primaryKey.map(t).join(", ")})` : "", jr = (e) => {
2308
- let t = e.columns.map((e) => ` ${kr(e)}`).join(",\n"), n = [`CREATE TABLE IF NOT EXISTS ${W(e.table)} (\n${t}${Ar(e, W)}\n)`];
2309
- for (let t of e.indexes) t.name !== `${e.table}_pkey` && n.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${W(t.name)} ON ${W(e.table)} (${t.columns.map($r).join(", ")})`);
2307
+ }, jr = (e, t) => e.primaryKey && e.primaryKey.length > 0 ? `,\n PRIMARY KEY (${e.primaryKey.map(t).join(", ")})` : "", Mr = (e) => {
2308
+ let t = e.columns.map((e) => ` ${Ar(e)}`).join(",\n"), n = [`CREATE TABLE IF NOT EXISTS ${G(e.table)} (\n${t}${jr(e, G)}\n)`];
2309
+ for (let t of e.indexes) t.name !== `${e.table}_pkey` && n.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${G(t.name)} ON ${G(e.table)} (${t.columns.map(ei).join(", ")})`);
2310
2310
  return n;
2311
- }, Mr = 191, Nr = (e) => {
2311
+ }, Nr = 191, Pr = (e) => {
2312
2312
  let t = hr(e).toUpperCase();
2313
2313
  return t.endsWith("TEXT") || t.endsWith("BLOB");
2314
- }, Pr = (e) => {
2315
- if (e.type === "id" && e.idScheme?.kind === "numeric") return M(e.name, "mariadb");
2316
- let t = q(e, "mariadb");
2317
- if (t) return `${G(e.name)} ${hr(e)} ${t}`;
2318
- let n = [G(e.name), hr(e)];
2319
- if (e.type === "id" && n.push("PRIMARY KEY"), e.nullable || n.push("NOT NULL"), e.unique && e.type !== "id" && !Nr(e) && n.push("UNIQUE"), e.hasDefault) {
2314
+ }, Fr = (e) => {
2315
+ if (e.type === "id" && e.idScheme?.kind === "numeric") return P(e.name, "mariadb");
2316
+ let t = kr(e, "mariadb");
2317
+ if (t) return `${K(e.name)} ${hr(e)} ${t}`;
2318
+ let n = [K(e.name), hr(e)];
2319
+ if (e.type === "id" && n.push("PRIMARY KEY"), e.nullable || n.push("NOT NULL"), e.unique && e.type !== "id" && !Pr(e) && n.push("UNIQUE"), e.hasDefault) {
2320
2320
  let t = Er(e.defaultValue, e);
2321
2321
  t && n.push(t);
2322
2322
  }
2323
2323
  return n.join(" ");
2324
- }, Fr = (e) => e.columns.flatMap((t) => {
2324
+ }, Ir = (e) => e.columns.flatMap((t) => {
2325
2325
  if (!t.references) return [];
2326
2326
  let n = t.references.onDelete ? ` ON DELETE ${{
2327
2327
  cascade: "CASCADE",
@@ -2329,26 +2329,26 @@ BEGIN
2329
2329
  setNull: "SET NULL",
2330
2330
  noAction: "NO ACTION"
2331
2331
  }[t.references.onDelete]}` : "";
2332
- return [` CONSTRAINT ${G(`${e.table}_${t.name}_fkey`)} FOREIGN KEY (${G(t.name)}) REFERENCES ${G(t.references.table)} (${G(t.references.column)})${n}`];
2333
- }), Ir = (e, t = "mariadb") => {
2332
+ return [` CONSTRAINT ${K(`${e.table}_${t.name}_fkey`)} FOREIGN KEY (${K(t.name)}) REFERENCES ${K(t.references.table)} (${K(t.references.column)})${n}`];
2333
+ }), Lr = (e, t = "mariadb") => {
2334
2334
  let n = new Map(e.columns.map((e) => [e.name, e])), r = (e) => {
2335
- let t = Zr(n.get(e));
2336
- return t === void 0 ? G(e) : `${G(e)}(${t})`;
2337
- }, i = e.columns.map((e) => ` ${Pr(e)}`).join(",\n"), a = Fr(e), o = a.length > 0 ? `${i},\n${a.join(",\n")}` : i, s = [`CREATE TABLE IF NOT EXISTS ${G(e.table)} (\n${o}${Ar(e, r)}\n)`];
2338
- for (let n of e.columns) n.unique && n.type !== "id" && Nr(n) && s.push(`CREATE UNIQUE INDEX ${gr(t)}${G(`${e.table}_${n.name}_key`)} ON ${G(e.table)} (${r(n.name)})`);
2339
- for (let n of e.indexes) n.name !== `${e.table}_pkey` && s.push(`CREATE ${n.unique ? "UNIQUE " : ""}INDEX ${gr(t)}${G(n.name)} ON ${G(e.table)} (${n.columns.map(r).join(", ")})`);
2335
+ let t = Qr(n.get(e));
2336
+ return t === void 0 ? K(e) : `${K(e)}(${t})`;
2337
+ }, i = e.columns.map((e) => ` ${Fr(e)}`).join(",\n"), a = Ir(e), o = a.length > 0 ? `${i},\n${a.join(",\n")}` : i, s = [`CREATE TABLE IF NOT EXISTS ${K(e.table)} (\n${o}${jr(e, r)}\n)`];
2338
+ for (let n of e.columns) n.unique && n.type !== "id" && Pr(n) && s.push(`CREATE UNIQUE INDEX ${gr(t)}${K(`${e.table}_${n.name}_key`)} ON ${K(e.table)} (${r(n.name)})`);
2339
+ for (let n of e.indexes) n.name !== `${e.table}_pkey` && s.push(`CREATE ${n.unique ? "UNIQUE " : ""}INDEX ${gr(t)}${K(n.name)} ON ${K(e.table)} (${n.columns.map(r).join(", ")})`);
2340
2340
  return s;
2341
- }, Lr = {
2341
+ }, Rr = {
2342
2342
  cascade: "CASCADE",
2343
2343
  restrict: "RESTRICT",
2344
2344
  setNull: "SET NULL",
2345
2345
  noAction: "NO ACTION"
2346
- }, Rr = {
2346
+ }, zr = {
2347
2347
  cascade: "CASCADE",
2348
2348
  restrict: "NO ACTION",
2349
2349
  setNull: "SET NULL",
2350
2350
  noAction: "NO ACTION"
2351
- }, zr = (e) => {
2351
+ }, Br = (e) => {
2352
2352
  let t = fr(e, "sqlite");
2353
2353
  if (t !== void 0) return t;
2354
2354
  switch (e.type) {
@@ -2360,52 +2360,52 @@ BEGIN
2360
2360
  case "bytes": return "BLOB";
2361
2361
  default: return "TEXT";
2362
2362
  }
2363
- }, Br = (e, t) => e == null ? null : e === "now" ? `DEFAULT ${t}` : typeof e == "boolean" ? `DEFAULT ${+!!e}` : typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? j(e, "sqlite") : null, Vr = (e) => {
2364
- if (e.type === "id" && e.idScheme?.kind === "numeric") return M(e.name, "sqlite");
2365
- let t = q(e, "sqlite");
2366
- if (t) return `${W(e.name)} ${zr(e)} ${t}`;
2367
- let n = [W(e.name), zr(e)];
2363
+ }, Vr = (e, t) => e == null ? null : e === "now" ? `DEFAULT ${t}` : typeof e == "boolean" ? `DEFAULT ${+!!e}` : typeof e == "number" ? `DEFAULT ${e}` : typeof e == "string" ? /[()]|^'/.test(e) ? `DEFAULT ${e}` : `DEFAULT '${e.replace(/'/g, "''")}'` : typeof e == "object" ? N(e, "sqlite") : null, Hr = (e) => {
2364
+ if (e.type === "id" && e.idScheme?.kind === "numeric") return P(e.name, "sqlite");
2365
+ let t = kr(e, "sqlite");
2366
+ if (t) return `${G(e.name)} ${Br(e)} ${t}`;
2367
+ let n = [G(e.name), Br(e)];
2368
2368
  if (e.type === "id" && n.push("PRIMARY KEY"), e.nullable || n.push("NOT NULL"), e.unique && e.type !== "id" && n.push("UNIQUE"), e.hasDefault) {
2369
- let t = Br(e.defaultValue, "CURRENT_TIMESTAMP");
2369
+ let t = Vr(e.defaultValue, "CURRENT_TIMESTAMP");
2370
2370
  t && n.push(t);
2371
2371
  }
2372
- if (e.references && (n.push(`REFERENCES ${W(e.references.table)} (${W(e.references.column)})`), e.references.onDelete && n.push(`ON DELETE ${Lr[e.references.onDelete]}`)), e.oneOf && e.oneOf.length > 0) {
2372
+ if (e.references && (n.push(`REFERENCES ${G(e.references.table)} (${G(e.references.column)})`), e.references.onDelete && n.push(`ON DELETE ${Rr[e.references.onDelete]}`)), e.oneOf && e.oneOf.length > 0) {
2373
2373
  let t = e.oneOf.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
2374
- n.push(`CHECK (${W(e.name)} IN (${t}))`);
2374
+ n.push(`CHECK (${G(e.name)} IN (${t}))`);
2375
2375
  }
2376
2376
  return n.join(" ");
2377
- }, Hr = (e) => {
2378
- let t = e.columns.map((e) => ` ${Vr(e)}`).join(",\n"), n = [`CREATE TABLE IF NOT EXISTS ${W(e.table)} (\n${t}${Ar(e, W)}\n)`];
2379
- for (let t of e.indexes) t.name !== `${e.table}_pkey` && n.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${W(t.name)} ON ${W(e.table)} (${t.columns.map(W).join(", ")})`);
2377
+ }, Ur = (e) => {
2378
+ let t = e.columns.map((e) => ` ${Hr(e)}`).join(",\n"), n = [`CREATE TABLE IF NOT EXISTS ${G(e.table)} (\n${t}${jr(e, G)}\n)`];
2379
+ for (let t of e.indexes) t.name !== `${e.table}_pkey` && n.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${G(t.name)} ON ${G(e.table)} (${t.columns.map(G).join(", ")})`);
2380
2380
  return n;
2381
2381
  }, J = (e, t) => {
2382
2382
  let n = t.find((t) => t.tableName === e);
2383
2383
  if (!n) return [];
2384
- let r = F([n]).tables[0], i = `${e}__voltro_rebuild`, a = r.columns.map((e) => W(e.name)).join(", "), o = [
2385
- ...Hr({
2384
+ let r = I([n]).tables[0], i = `${e}__voltro_rebuild`, a = r.columns.map((e) => G(e.name)).join(", "), o = [
2385
+ ...Ur({
2386
2386
  kind: "create-table",
2387
2387
  table: i,
2388
2388
  columns: r.columns,
2389
2389
  indexes: [],
2390
2390
  ...r.primaryKey ? { primaryKey: r.primaryKey } : {}
2391
2391
  }),
2392
- `INSERT INTO ${W(i)} (${a}) SELECT ${a} FROM ${W(e)}`,
2393
- `DROP TABLE ${W(e)}`,
2394
- `ALTER TABLE ${W(i)} RENAME TO ${W(e)}`
2392
+ `INSERT INTO ${G(i)} (${a}) SELECT ${a} FROM ${G(e)}`,
2393
+ `DROP TABLE ${G(e)}`,
2394
+ `ALTER TABLE ${G(i)} RENAME TO ${G(e)}`
2395
2395
  ];
2396
- for (let t of r.indexes) t.name !== `${e}_pkey` && o.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${W(t.name)} ON ${W(e)} (${t.columns.map(W).join(", ")})`);
2396
+ for (let t of r.indexes) t.name !== `${e}_pkey` && o.push(`CREATE ${t.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${G(t.name)} ON ${G(e)} (${t.columns.map(G).join(", ")})`);
2397
2397
  return o;
2398
- }, Ur = (e, t, n, r) => {
2398
+ }, Wr = (e, t, n, r) => {
2399
2399
  let i = r ?? e.nullable;
2400
- return `ALTER TABLE ${Y(n)} ALTER COLUMN ${Y(t)} ${A(e, "mssql")} ${i ? "NULL" : "NOT NULL"};`;
2401
- }, Wr = (e, t) => {
2400
+ return `ALTER TABLE ${Y(n)} ALTER COLUMN ${Y(t)} ${M(e, "mssql")} ${i ? "NULL" : "NOT NULL"};`;
2401
+ }, Gr = (e, t) => {
2402
2402
  let n = `DECLARE @dc sysname; SELECT @dc = dc.name FROM sys.default_constraints dc JOIN sys.columns col ON col.object_id = dc.parent_object_id AND col.column_id = dc.parent_column_id WHERE dc.parent_object_id = OBJECT_ID(N'${e.table.replace(/'/g, "''")}') AND col.name = N'${e.column.replace(/'/g, "''")}'; IF @dc IS NOT NULL EXEC(N'ALTER TABLE ${Y(e.table)} DROP CONSTRAINT [' + @dc + ']');` + (t ? ` ${t}` : "");
2403
2403
  if (!e.hasDefault) return n;
2404
- let r = Br(e.defaultValue, "SYSUTCDATETIME()");
2404
+ let r = Vr(e.defaultValue, "SYSUTCDATETIME()");
2405
2405
  if (!r) return n;
2406
2406
  let i = r.replace(/^DEFAULT\s+/i, "");
2407
2407
  return `${n} ALTER TABLE ${Y(e.table)} ADD DEFAULT ${i} FOR ${Y(e.column)};`;
2408
- }, Y = (e) => `[${e.replace(/]/g, "]]")}]`, Gr = (e) => {
2408
+ }, Y = (e) => `[${e.replace(/]/g, "]]")}]`, Kr = (e) => {
2409
2409
  let t = fr(e, "mssql");
2410
2410
  if (t !== void 0) return t;
2411
2411
  switch (e.type) {
@@ -2421,44 +2421,44 @@ BEGIN
2421
2421
  case "bytes": return "VARBINARY(MAX)";
2422
2422
  default: return "NVARCHAR(MAX)";
2423
2423
  }
2424
- }, Kr = (e, t) => {
2425
- if (e.type === "id" && e.idScheme?.kind === "numeric") return M(e.name, "mssql");
2426
- let n = e.type === "text" && t?.has(e.name) ? "NVARCHAR(450)" : Gr(e), r = q(e, "mssql");
2424
+ }, qr = (e, t) => {
2425
+ if (e.type === "id" && e.idScheme?.kind === "numeric") return P(e.name, "mssql");
2426
+ let n = e.type === "text" && t?.has(e.name) ? "NVARCHAR(450)" : Kr(e), r = kr(e, "mssql");
2427
2427
  if (r) return `${Y(e.name)} ${r}`;
2428
2428
  let i = [Y(e.name), n];
2429
2429
  if (e.type === "id" && i.push("PRIMARY KEY"), e.nullable || i.push("NOT NULL"), e.unique && e.type !== "id" && i.push("UNIQUE"), e.hasDefault) {
2430
- let t = Br(e.defaultValue, "SYSUTCDATETIME()");
2430
+ let t = Vr(e.defaultValue, "SYSUTCDATETIME()");
2431
2431
  t && i.push(t);
2432
2432
  }
2433
- return e.references && (i.push(`REFERENCES ${Y(e.references.table)} (${Y(e.references.column)})`), e.references.onDelete && i.push(`ON DELETE ${Rr[e.references.onDelete]}`)), i.join(" ");
2434
- }, qr = (e) => {
2435
- let t = (e) => e.replace(/'/g, "''"), n = new Set(e.indexes.flatMap((e) => e.columns)), r = e.columns.map((e) => ` ${Kr(e, n)}`).join(",\n"), i = `CREATE TABLE ${Y(e.table)} (\n${r}${Ar(e, Y)}\n)`, a = [`IF OBJECT_ID(N'${t(e.table)}', N'U') IS NULL EXEC(N'${t(i)}')`];
2433
+ return e.references && (i.push(`REFERENCES ${Y(e.references.table)} (${Y(e.references.column)})`), e.references.onDelete && i.push(`ON DELETE ${zr[e.references.onDelete]}`)), i.join(" ");
2434
+ }, Jr = (e) => {
2435
+ let t = (e) => e.replace(/'/g, "''"), n = new Set(e.indexes.flatMap((e) => e.columns)), r = e.columns.map((e) => ` ${qr(e, n)}`).join(",\n"), i = `CREATE TABLE ${Y(e.table)} (\n${r}${jr(e, Y)}\n)`, a = [`IF OBJECT_ID(N'${t(e.table)}', N'U') IS NULL EXEC(N'${t(i)}')`];
2436
2436
  for (let n of e.indexes) {
2437
2437
  if (n.name === `${e.table}_pkey`) continue;
2438
2438
  let r = `CREATE ${n.unique ? "UNIQUE " : ""}INDEX ${Y(n.name)} ON ${Y(e.table)} (${n.columns.map(Y).join(", ")})`;
2439
2439
  a.push(`IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'${t(n.name)}' AND object_id = OBJECT_ID(N'${t(e.table)}')) EXEC(N'${t(r)}')`);
2440
2440
  }
2441
2441
  return a;
2442
- }, Jr = (e) => `__dropped_${e.replace(/[-:T.Z]/g, "").slice(0, 14)}`, Yr = (e, t) => `DROP TABLE IF EXISTS ${t(e.table)};`, Xr = (e, t, n) => {
2443
- let r = `${e.table}${Jr(t)}`;
2442
+ }, Yr = (e) => `__dropped_${e.replace(/[-:T.Z]/g, "").slice(0, 14)}`, Xr = (e, t) => `DROP TABLE IF EXISTS ${t(e.table)};`, Zr = (e, t, n) => {
2443
+ let r = `${e.table}${Yr(t)}`;
2444
2444
  return `ALTER TABLE ${n(e.table)} RENAME TO ${n(r)};`;
2445
- }, Zr = (e) => {
2446
- if (e === void 0 || !Nr(e)) return;
2445
+ }, Qr = (e) => {
2446
+ if (e === void 0 || !Pr(e)) return;
2447
2447
  let t = typeof e.maxLength == "number" && e.maxLength > 0 ? e.maxLength : void 0;
2448
- return t === void 0 ? Mr : Math.min(Mr, t);
2449
- }, Qr = (e, t, n) => {
2450
- let r = Zr(wr(e, t, n));
2451
- return r === void 0 ? G(n) : `${G(n)}(${r})`;
2452
- }, $r = (e) => e.startsWith("(") ? e : W(e), ei = (e, t) => `CREATE ${e.index.unique ? "UNIQUE " : ""}INDEX ${t ? "CONCURRENTLY " : ""}IF NOT EXISTS ${W(e.index.name)} ON ${W(e.table)} (${e.index.columns.map($r).join(", ")});`, ti = (e, t, n = "mariadb") => `CREATE ${e.index.unique ? "UNIQUE " : ""}INDEX ${gr(n)}${G(e.index.name)} ON ${G(e.table)} (${e.index.columns.map((n) => Qr(t, e.table, n)).join(", ")});`, ni = (e) => `DROP INDEX IF EXISTS ${W(e.index)};`, ri = (e) => `DROP INDEX ${G(e.index)} ON ${G(e.table)};`, ii = (e) => `DROP INDEX IF EXISTS ${Y(e.index)} ON ${Y(e.table)};`, ai = (e, t) => `ALTER TABLE ${t(e.from)} RENAME TO ${t(e.to)};`, oi = (e) => {
2448
+ return t === void 0 ? Nr : Math.min(Nr, t);
2449
+ }, $r = (e, t, n) => {
2450
+ let r = Qr(wr(e, t, n));
2451
+ return r === void 0 ? K(n) : `${K(n)}(${r})`;
2452
+ }, ei = (e) => e.startsWith("(") ? e : G(e), ti = (e, t) => `CREATE ${e.index.unique ? "UNIQUE " : ""}INDEX ${t ? "CONCURRENTLY " : ""}IF NOT EXISTS ${G(e.index.name)} ON ${G(e.table)} (${e.index.columns.map(ei).join(", ")});`, ni = (e, t, n = "mariadb") => `CREATE ${e.index.unique ? "UNIQUE " : ""}INDEX ${gr(n)}${K(e.index.name)} ON ${K(e.table)} (${e.index.columns.map((n) => $r(t, e.table, n)).join(", ")});`, ri = (e) => `DROP INDEX IF EXISTS ${G(e.index)};`, ii = (e) => `DROP INDEX ${K(e.index)} ON ${K(e.table)};`, ai = (e) => `DROP INDEX IF EXISTS ${Y(e.index)} ON ${Y(e.table)};`, oi = (e, t) => `ALTER TABLE ${t(e.from)} RENAME TO ${t(e.to)};`, si = (e) => {
2453
2453
  let t = (e) => e.replace(/'/g, "''");
2454
2454
  return `EXEC sp_rename N'${t(e.from)}', N'${t(e.to)}';`;
2455
- }, si = (e) => `ALTER INDEX ${W(e.from)} RENAME TO ${W(e.to)};`, ci = (e) => `ALTER TABLE ${G(e.table)} RENAME INDEX ${G(e.from)} TO ${G(e.to)};`, li = (e) => {
2455
+ }, ci = (e) => `ALTER INDEX ${G(e.from)} RENAME TO ${G(e.to)};`, li = (e) => `ALTER TABLE ${K(e.table)} RENAME INDEX ${K(e.from)} TO ${K(e.to)};`, ui = (e) => {
2456
2456
  let t = (e) => e.replace(/'/g, "''");
2457
2457
  return `EXEC sp_rename N'${t(e.table)}.${t(e.from)}', N'${t(e.to)}', N'INDEX';`;
2458
- }, ui = (e) => {
2458
+ }, di = (e) => {
2459
2459
  let t = (e) => e.replace(/'/g, "''"), n = `CREATE ${e.index.unique ? "UNIQUE " : ""}INDEX ${Y(e.index.name)} ON ${Y(e.table)} (${e.index.columns.map(Y).join(", ")})`;
2460
2460
  return `IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'${t(e.index.name)}' AND object_id = OBJECT_ID(N'${t(e.table)}')) EXEC(N'${t(n)}');`;
2461
- }, di = (e, t, n) => {
2461
+ }, fi = (e, t, n) => {
2462
2462
  let r = n.find((t) => t.tableName === e);
2463
2463
  if (!r) return [];
2464
2464
  let i = [];
@@ -2467,13 +2467,13 @@ BEGIN
2467
2467
  t && t.type === "text" && !t.generatedAs && i.push(`ALTER TABLE ${Y(e)} ALTER COLUMN ${Y(n)} NVARCHAR(450) ${t.nullable ? "NULL" : "NOT NULL"};`);
2468
2468
  }
2469
2469
  return i;
2470
- }, fi = (e) => `ALTER TABLE ${W(e.table)} ADD CONSTRAINT ${W(`${e.table}_${e.column}_key`)} UNIQUE (${W(e.column)});`, pi = (e, t) => `ALTER TABLE ${G(e.table)} ADD CONSTRAINT ${G(`${e.table}_${e.column}_key`)} UNIQUE (${Qr(t, e.table, e.column)});`, mi = (e) => {
2471
- let t = e.fields.map((e) => W(e)).join(", ");
2472
- return `ALTER TABLE ${W(e.table)} ADD CONSTRAINT ${W(e.name)} UNIQUE (${t});`;
2473
- }, hi = (e, t) => {
2474
- let n = e.fields.map((n) => Qr(t, e.table, n)).join(", ");
2475
- return `ALTER TABLE ${G(e.table)} ADD CONSTRAINT ${G(e.name)} UNIQUE (${n});`;
2476
- }, gi = (e) => `ALTER TABLE ${W(e.table)} DROP CONSTRAINT IF EXISTS ${W(e.name)};`, _i = (e) => `ALTER TABLE ${G(e.table)} DROP INDEX ${G(e.name)};`, vi = (e) => `ALTER TABLE ${W(e.table)} DROP CONSTRAINT IF EXISTS ${W(`${e.table}_${e.column}_key`)};`, yi = (e) => `ALTER TABLE ${G(e.table)} DROP INDEX ${G(`${e.table}_${e.column}_key`)};`, bi = (e, t) => {
2470
+ }, pi = (e) => `ALTER TABLE ${G(e.table)} ADD CONSTRAINT ${G(`${e.table}_${e.column}_key`)} UNIQUE (${G(e.column)});`, mi = (e, t) => `ALTER TABLE ${K(e.table)} ADD CONSTRAINT ${K(`${e.table}_${e.column}_key`)} UNIQUE (${$r(t, e.table, e.column)});`, hi = (e) => {
2471
+ let t = e.fields.map((e) => G(e)).join(", ");
2472
+ return `ALTER TABLE ${G(e.table)} ADD CONSTRAINT ${G(e.name)} UNIQUE (${t});`;
2473
+ }, gi = (e, t) => {
2474
+ let n = e.fields.map((n) => $r(t, e.table, n)).join(", ");
2475
+ return `ALTER TABLE ${K(e.table)} ADD CONSTRAINT ${K(e.name)} UNIQUE (${n});`;
2476
+ }, _i = (e) => `ALTER TABLE ${G(e.table)} DROP CONSTRAINT IF EXISTS ${G(e.name)};`, vi = (e) => `ALTER TABLE ${K(e.table)} DROP INDEX ${K(e.name)};`, yi = (e) => `ALTER TABLE ${G(e.table)} DROP CONSTRAINT IF EXISTS ${G(`${e.table}_${e.column}_key`)};`, bi = (e) => `ALTER TABLE ${K(e.table)} DROP INDEX ${K(`${e.table}_${e.column}_key`)};`, xi = (e, t) => {
2477
2477
  let n = [], r = t(e.table), i = t(e.column), a = t(e.targetTable), o = t(e.targetColumn);
2478
2478
  if (e.orphanPolicy) {
2479
2479
  let t = `${i} IS NOT NULL AND ${i} NOT IN (SELECT ${o} FROM ${a})`;
@@ -2491,34 +2491,34 @@ BEGIN
2491
2491
  setNull: "SET NULL",
2492
2492
  noAction: "NO ACTION"
2493
2493
  }[e.onDelete]}`), n.push(s.join(" ") + ";"), n;
2494
- }, xi = (e) => `ALTER TABLE ${W(e.table)} DROP CONSTRAINT IF EXISTS ${W(`${e.table}_${e.column}_fkey`)};`, Si = (e) => `ALTER TABLE ${G(e.table)} DROP FOREIGN KEY ${G(`${e.table}_${e.column}_fkey`)};`, Ci = (e, t) => {
2494
+ }, Si = (e) => `ALTER TABLE ${G(e.table)} DROP CONSTRAINT IF EXISTS ${G(`${e.table}_${e.column}_fkey`)};`, Ci = (e) => `ALTER TABLE ${K(e.table)} DROP FOREIGN KEY ${K(`${e.table}_${e.column}_fkey`)};`, wi = (e, t) => {
2495
2495
  let n = e.values.map((e) => `'${e.replace(/'/g, "''")}'`).join(", ");
2496
2496
  return `ALTER TABLE ${t(e.table)} ADD CONSTRAINT ${t(`${e.table}_${e.column}_check`)} CHECK (${t(e.column)} IN (${n}));`;
2497
- }, wi = (e) => `ALTER TABLE ${W(e.table)} DROP CONSTRAINT IF EXISTS ${W(`${e.table}_${e.column}_check`)};`, Ti = (e, t) => x.gen(function* () {
2497
+ }, Ti = (e) => `ALTER TABLE ${G(e.table)} DROP CONSTRAINT IF EXISTS ${G(`${e.table}_${e.column}_check`)};`, Ei = (e, t) => S.gen(function* () {
2498
2498
  let n = yield* e`
2499
2499
  SELECT cc.constraint_name AS n, cc.check_clause AS c
2500
2500
  FROM information_schema.check_constraints cc
2501
- WHERE cc.constraint_schema = DATABASE() AND cc.table_name = ${t.table}`.pipe(x.orElse(() => e`
2501
+ WHERE cc.constraint_schema = DATABASE() AND cc.table_name = ${t.table}`.pipe(S.orElse(() => e`
2502
2502
  SELECT cc.constraint_name AS n, cc.check_clause AS c
2503
2503
  FROM information_schema.check_constraints cc
2504
2504
  JOIN information_schema.table_constraints tc
2505
2505
  ON tc.constraint_schema = cc.constraint_schema
2506
2506
  AND tc.constraint_name = cc.constraint_name
2507
- WHERE tc.table_schema = DATABASE() AND tc.table_name = ${t.table}`), x.orElseSucceed(() => []));
2507
+ WHERE tc.table_schema = DATABASE() AND tc.table_name = ${t.table}`), S.orElseSucceed(() => []));
2508
2508
  for (let e of n) {
2509
2509
  let n = String(e.n ?? "");
2510
2510
  if (n !== "" && Pn(String(e.c ?? ""))?.column === t.column) return n;
2511
2511
  }
2512
- }), Ei = (e, t, n) => x.gen(function* () {
2513
- let r = yield* Ti(e, t);
2514
- r !== void 0 && (yield* X(e, `ALTER TABLE ${G(t.table)} DROP CONSTRAINT ${G(r)};`, t.kind, [lr]));
2515
- let i = yield* Ti(e, t);
2512
+ }), Di = (e, t, n) => S.gen(function* () {
2513
+ let r = yield* Ei(e, t);
2514
+ r !== void 0 && (yield* X(e, `ALTER TABLE ${K(t.table)} DROP CONSTRAINT ${K(r)};`, t.kind, [lr]));
2515
+ let i = yield* Ei(e, t);
2516
2516
  if (i === void 0) return;
2517
- let a = K(n, t.table, t.column);
2518
- if (!a) return yield* x.die(/* @__PURE__ */ Error(`applier: cannot drop the CHECK on '${t.table}.${t.column}' — it is column-level (catalog name '${i}'), which this family removes only by redefining the column, and the declared column is not available to redefine it from.`));
2519
- yield* X(e, `ALTER TABLE ${G(t.table)} MODIFY COLUMN ${Tr(a, t.column)};`, t.kind);
2520
- }), Di = (e, t, n, r) => {
2521
- let i = e.column, a = r === "mariadb", o = a ? G : r === "mssql" ? Y : W, s = a ? hr(i) : r === "mssql" ? Gr(i) : r === "sqlite" ? zr(i) : pr(i), c = r === "mssql" ? "ADD" : "ADD COLUMN", l = (e) => a ? Er(e, i) : r === "mssql" ? Br(e, "SYSUTCDATETIME()") : r === "sqlite" ? Br(e, "CURRENT_TIMESTAMP") : Or(e, i), u = q(i, r);
2517
+ let a = q(n, t.table, t.column);
2518
+ if (!a) return yield* S.die(/* @__PURE__ */ Error(`applier: cannot drop the CHECK on '${t.table}.${t.column}' — it is column-level (catalog name '${i}'), which this family removes only by redefining the column, and the declared column is not available to redefine it from.`));
2519
+ yield* X(e, `ALTER TABLE ${K(t.table)} MODIFY COLUMN ${Tr(a, t.column)};`, t.kind);
2520
+ }), Oi = (e, t, n, r) => {
2521
+ let i = e.column, a = r === "mariadb", o = a ? K : r === "mssql" ? Y : G, s = a ? hr(i) : r === "mssql" ? Kr(i) : r === "sqlite" ? Br(i) : pr(i), c = r === "mssql" ? "ADD" : "ADD COLUMN", l = (e) => a ? Er(e, i) : r === "mssql" ? Vr(e, "SYSUTCDATETIME()") : r === "sqlite" ? Vr(e, "CURRENT_TIMESTAMP") : Or(e, i), u = kr(i, r);
2522
2522
  if (u) {
2523
2523
  let t = r === "mssql" ? `${o(i.name)} ${u}` : `${o(i.name)} ${s} ${u}`;
2524
2524
  return {
@@ -2546,7 +2546,7 @@ BEGIN
2546
2546
  post: f ? [f] : []
2547
2547
  };
2548
2548
  return d?.sql && (p.backfillKind = "sql", p.backfillSql = d.sql), d?.js && (p.backfillKind = "js", p.backfillJs = d.js), d?.batchSize !== void 0 && (p.batchSize = d.batchSize), d?.sleepMs !== void 0 && (p.sleepMs = d.sleepMs), p;
2549
- }, Oi = (e) => {
2549
+ }, ki = (e) => {
2550
2550
  let t = new Map(e.map((e) => [e.tableName, e]));
2551
2551
  return (e, n) => {
2552
2552
  let r = t.get(e);
@@ -2566,47 +2566,47 @@ BEGIN
2566
2566
  ...o
2567
2567
  };
2568
2568
  };
2569
- }, X = (e, t, n, r = []) => e.unsafe(t).pipe(x.catchIf((e) => ar(e, r), () => x.void), x.tapError((e) => x.sync(() => {
2570
- process.stderr.write(ae(`applier: statement failed (op=${n})`, t, e, 400));
2571
- })), x.mapError((e) => {
2572
- let r = ae(`applier: statement failed (op=${n})`, t, e, 400).trim();
2569
+ }, X = (e, t, n, r = []) => e.unsafe(t).pipe(S.catchIf((e) => ar(e, r), () => S.void), S.tapError((e) => S.sync(() => {
2570
+ process.stderr.write(re(`applier: statement failed (op=${n})`, t, e, 400));
2571
+ })), S.mapError((e) => {
2572
+ let r = re(`applier: statement failed (op=${n})`, t, e, 400).trim();
2573
2573
  return Object.assign(e, { message: r });
2574
- }), x.map(() => void 0)), Z = (e, t, n) => x.forEach(t, (t) => X(e, t, n), { discard: !0 }), Q = (e, t) => e.literal(`LIMIT ${Math.max(1, Math.floor(Number.isFinite(t) ? t : 1))}`), $ = (t, n, r, i) => t.unsafe(`SELECT ${i === void 0 ? "*" : e(i, n)} FROM ${e(r, n)} WHERE 1=0`).pipe(x.as(!0), x.catchAll(() => x.succeed(!1))), ki = (e, t) => x.gen(function* () {
2575
- let n = F([Le], t).tables[0];
2576
- if (!n) return yield* x.die(/* @__PURE__ */ Error("migration applier: the resume-ledger table descriptor produced no snapshot. This is a framework bug."));
2574
+ }), S.map(() => void 0)), Z = (e, t, n) => S.forEach(t, (t) => X(e, t, n), { discard: !0 }), Q = (e, t) => e.literal(`LIMIT ${Math.max(1, Math.floor(Number.isFinite(t) ? t : 1))}`), $ = (e, t, n, r) => e.unsafe(`SELECT ${r === void 0 ? "*" : _(r, t)} FROM ${_(n, t)} WHERE 1=0`).pipe(S.as(!0), S.catchAll(() => S.succeed(!1))), Ai = (e, t) => S.gen(function* () {
2575
+ let n = I([Ie], t).tables[0];
2576
+ if (!n) return yield* S.die(/* @__PURE__ */ Error("migration applier: the resume-ledger table descriptor produced no snapshot. This is a framework bug."));
2577
2577
  let r = {
2578
2578
  kind: "create-table",
2579
- table: D,
2579
+ table: k,
2580
2580
  columns: n.columns,
2581
2581
  indexes: []
2582
2582
  }, i = yield* e.onDialectOrElse({
2583
- mysql: () => H(e).pipe(x.map((e) => Ir(r, e))),
2584
- mssql: () => x.succeed(qr(r)),
2585
- sqlite: () => x.succeed(Hr(r)),
2586
- orElse: () => x.succeed(jr(r))
2583
+ mysql: () => U(e).pipe(S.map((e) => Lr(r, e))),
2584
+ mssql: () => S.succeed(Jr(r)),
2585
+ sqlite: () => S.succeed(Ur(r)),
2586
+ orElse: () => S.succeed(Mr(r))
2587
2587
  });
2588
- yield* x.forEach(i, (t) => X(e, t, "resume-ledger-bootstrap"), { discard: !0 });
2589
- }), Ai = (e) => e`
2588
+ yield* S.forEach(i, (t) => X(e, t, "resume-ledger-bootstrap"), { discard: !0 });
2589
+ }), ji = (e) => e`
2590
2590
  SELECT ${e("runId")}, ${e("planFingerprint")}, ${e("opIndex")},
2591
2591
  ${e("status")}, ${e("payload")}
2592
- FROM ${e(D)}
2593
- `, ji = (e, t, n, r) => x.gen(function* () {
2594
- let i = yield* U(e, (/* @__PURE__ */ new Date()).toISOString());
2595
- yield* x.forEach(r, ({ index: r, planned: a }) => e`
2596
- INSERT INTO ${e(D)}
2592
+ FROM ${e(k)}
2593
+ `, Mi = (e, t, n, r) => S.gen(function* () {
2594
+ let i = yield* W(e, (/* @__PURE__ */ new Date()).toISOString());
2595
+ yield* S.forEach(r, ({ index: r, planned: a }) => e`
2596
+ INSERT INTO ${e(k)}
2597
2597
  (${e("id")}, ${e("runId")}, ${e("planFingerprint")}, ${e("opIndex")},
2598
2598
  ${e("opKind")}, ${e("opTarget")}, ${e("status")}, ${e("payload")},
2599
2599
  ${e("createdAt")})
2600
2600
  VALUES
2601
2601
  (${`mop_${t}_${r}`}, ${t}, ${n}, ${r},
2602
- ${a.op.kind}, ${ze(a.op)}, ${"pending"},
2602
+ ${a.op.kind}, ${Re(a.op)}, ${"pending"},
2603
2603
  ${JSON.stringify(a)}, ${i})
2604
2604
  `, { discard: !0 });
2605
- }), Mi = (e, t, n, r, i) => x.gen(function* () {
2606
- let a = yield* U(e, (/* @__PURE__ */ new Date()).toISOString());
2605
+ }), Ni = (e, t, n, r, i) => S.gen(function* () {
2606
+ let a = yield* W(e, (/* @__PURE__ */ new Date()).toISOString());
2607
2607
  if (r === "applied") {
2608
2608
  yield* e`
2609
- UPDATE ${e(D)}
2609
+ UPDATE ${e(k)}
2610
2610
  SET ${e("status")} = ${r}, ${e("appliedAt")} = ${a},
2611
2611
  ${e("durationMs")} = ${i ?? null}
2612
2612
  WHERE ${e("runId")} = ${t} AND ${e("opIndex")} = ${n}
@@ -2614,145 +2614,145 @@ BEGIN
2614
2614
  return;
2615
2615
  }
2616
2616
  yield* e`
2617
- UPDATE ${e(D)}
2617
+ UPDATE ${e(k)}
2618
2618
  SET ${e("status")} = ${r}, ${e("startedAt")} = ${a}
2619
2619
  WHERE ${e("runId")} = ${t} AND ${e("opIndex")} = ${n}
2620
2620
  `;
2621
- }), Ni = (e, t, n, r) => x.gen(function* () {
2622
- let i = yield* U(e, (/* @__PURE__ */ new Date()).toISOString());
2621
+ }), Pi = (e, t, n, r) => S.gen(function* () {
2622
+ let i = yield* W(e, (/* @__PURE__ */ new Date()).toISOString());
2623
2623
  r.length > 0 && (yield* e`
2624
- UPDATE ${e(D)}
2624
+ UPDATE ${e(k)}
2625
2625
  SET ${e("status")} = ${"applied"}, ${e("appliedAt")} = ${i}
2626
2626
  WHERE ${e("runId")} = ${t} AND ${e("opIndex")} IN ${e.in(r)}
2627
2627
  `), n.length > 0 && (yield* e`
2628
- UPDATE ${e(D)}
2628
+ UPDATE ${e(k)}
2629
2629
  SET ${e("status")} = ${"pending"}
2630
2630
  WHERE ${e("runId")} = ${t} AND ${e("opIndex")} IN ${e.in(n)}
2631
2631
  `);
2632
- }), Pi = (e, t) => t === void 0 ? e`DELETE FROM ${e(D)}`.pipe(x.asVoid) : e`DELETE FROM ${e(D)} WHERE ${e("runId")} = ${t}`.pipe(x.asVoid), Fi = (t, n, r) => x.gen(function* () {
2633
- if (qe(r.op, r.classification, n) !== "artefact-repair") return "clean";
2634
- let i = r.op, a = (t) => e(t, n);
2635
- if (n === "sqlite" || n === "turso") {
2636
- if (!("table" in i)) return "clean";
2637
- let e = `${i.table}${He}`;
2638
- return (yield* $(t, n, e)) ? ((yield* $(t, n, i.table)) ? yield* X(t, `DROP TABLE ${a(e)}`, "resume-repair") : yield* X(t, `ALTER TABLE ${a(e)} RENAME TO ${a(i.table)}`, "resume-repair"), yield* x.logWarning(`migration resume: reconciled an interrupted sqlite table rebuild on '${i.table}' — replaying the operation`).pipe(x.annotateLogs({ scope: "voltro:migrate" })), "outstanding") : "clean";
2639
- }
2640
- if (i.kind !== "alter-column-type") return "clean";
2641
- let o = `${i.column}${Ue}`, s = `${i.column}${We}`, c = yield* $(t, n, i.table, i.column), l = yield* $(t, n, i.table, o), u = yield* $(t, n, i.table, s), d = (e) => x.logWarning(`migration resume: ${e}`).pipe(x.annotateLogs({ scope: "voltro:migrate" }));
2642
- return !l && !u ? "clean" : c && l && !u ? (yield* X(t, `ALTER TABLE ${a(i.table)} DROP COLUMN ${a(o)}`, "resume-repair"), yield* d(`dropped a half-populated shadow column '${i.table}.${o}' — replaying the type change`), "outstanding") : !c && l && u ? (yield* X(t, `ALTER TABLE ${a(i.table)} RENAME COLUMN ${a(o)} TO ${a(i.column)}`, "resume-repair"), yield* X(t, `ALTER TABLE ${a(i.table)} DROP COLUMN ${a(s)}`, "resume-repair"), yield* d(`completed an interrupted shadow swap on '${i.table}.${i.column}'`), "applied") : c && !l && u ? (yield* X(t, `ALTER TABLE ${a(i.table)} DROP COLUMN ${a(s)}`, "resume-repair"), yield* d(`dropped the leftover pre-swap column '${i.table}.${s}'`), "applied") : yield* x.die(/* @__PURE__ */ Error(`applyPlan: an interrupted online type change on '${i.table}.${i.column}' left a shadow-swap state this resume cannot classify (column=${c}, ${o}=${l}, ${s}=${u}).\nNothing was changed. Inspect those three columns and reconcile them by hand — the data is in whichever of them is populated — then re-run the migration.`));
2643
- }), Ii = (e, t, n, r = "fresh") => x.gen(function* () {
2644
- let i = process.hrtime.bigint(), a = Oi(n.declared), o = t.op;
2632
+ }), Fi = (e, t) => t === void 0 ? e`DELETE FROM ${e(k)}`.pipe(S.asVoid) : e`DELETE FROM ${e(k)} WHERE ${e("runId")} = ${t}`.pipe(S.asVoid), Ii = (e, t, n) => S.gen(function* () {
2633
+ if (Ke(n.op, n.classification, t) !== "artefact-repair") return "clean";
2634
+ let r = n.op, i = (e) => _(e, t);
2635
+ if (t === "sqlite" || t === "turso") {
2636
+ if (!("table" in r)) return "clean";
2637
+ let n = `${r.table}${Ve}`;
2638
+ return (yield* $(e, t, n)) ? ((yield* $(e, t, r.table)) ? yield* X(e, `DROP TABLE ${i(n)}`, "resume-repair") : yield* X(e, `ALTER TABLE ${i(n)} RENAME TO ${i(r.table)}`, "resume-repair"), yield* S.logWarning(`migration resume: reconciled an interrupted sqlite table rebuild on '${r.table}' — replaying the operation`).pipe(S.annotateLogs({ scope: "voltro:migrate" })), "outstanding") : "clean";
2639
+ }
2640
+ if (r.kind !== "alter-column-type") return "clean";
2641
+ let a = `${r.column}${He}`, o = `${r.column}${Ue}`, s = yield* $(e, t, r.table, r.column), c = yield* $(e, t, r.table, a), l = yield* $(e, t, r.table, o), u = (e) => S.logWarning(`migration resume: ${e}`).pipe(S.annotateLogs({ scope: "voltro:migrate" }));
2642
+ return !c && !l ? "clean" : s && c && !l ? (yield* X(e, `ALTER TABLE ${i(r.table)} DROP COLUMN ${i(a)}`, "resume-repair"), yield* u(`dropped a half-populated shadow column '${r.table}.${a}' — replaying the type change`), "outstanding") : !s && c && l ? (yield* X(e, `ALTER TABLE ${i(r.table)} RENAME COLUMN ${i(a)} TO ${i(r.column)}`, "resume-repair"), yield* X(e, `ALTER TABLE ${i(r.table)} DROP COLUMN ${i(o)}`, "resume-repair"), yield* u(`completed an interrupted shadow swap on '${r.table}.${r.column}'`), "applied") : s && !c && l ? (yield* X(e, `ALTER TABLE ${i(r.table)} DROP COLUMN ${i(o)}`, "resume-repair"), yield* u(`dropped the leftover pre-swap column '${r.table}.${o}'`), "applied") : yield* S.die(/* @__PURE__ */ Error(`applyPlan: an interrupted online type change on '${r.table}.${r.column}' left a shadow-swap state this resume cannot classify (column=${s}, ${a}=${c}, ${o}=${l}).\nNothing was changed. Inspect those three columns and reconcile them by hand — the data is in whichever of them is populated — then re-run the migration.`));
2643
+ }), Li = (e, t, n, r = "fresh") => S.gen(function* () {
2644
+ let i = process.hrtime.bigint(), a = ki(n.declared), o = t.op;
2645
2645
  switch (o.kind) {
2646
2646
  case "create-table": {
2647
2647
  let t = yield* e.onDialectOrElse({
2648
- mysql: () => H(e).pipe(x.map((e) => Ir(o, e))),
2649
- mssql: () => x.succeed(qr(o)),
2650
- sqlite: () => x.succeed(Hr(o)),
2651
- orElse: () => x.succeed(jr(o))
2648
+ mysql: () => U(e).pipe(S.map((e) => Lr(o, e))),
2649
+ mssql: () => S.succeed(Jr(o)),
2650
+ sqlite: () => S.succeed(Ur(o)),
2651
+ orElse: () => S.succeed(Mr(o))
2652
2652
  }), n = yield* e.onDialectOrElse({
2653
- mysql: () => x.succeed([or]),
2654
- orElse: () => x.succeed([])
2653
+ mysql: () => S.succeed([or]),
2654
+ orElse: () => S.succeed([])
2655
2655
  });
2656
2656
  for (let r of t) yield* X(e, r, o.kind, n);
2657
2657
  break;
2658
2658
  }
2659
2659
  case "drop-table": {
2660
- let t = process.env.VOLTRO_SOFT_DROP === "1", n = (/* @__PURE__ */ new Date()).toISOString(), r = (e) => t ? Xr(o, n, e) : Yr(o, e);
2660
+ let t = process.env.VOLTRO_SOFT_DROP === "1", n = (/* @__PURE__ */ new Date()).toISOString(), r = (e) => t ? Zr(o, n, e) : Xr(o, e);
2661
2661
  yield* e.onDialectOrElse({
2662
- mysql: () => X(e, r(G), o.kind),
2663
- orElse: () => X(e, r(W), o.kind)
2662
+ mysql: () => X(e, r(K), o.kind),
2663
+ orElse: () => X(e, r(G), o.kind)
2664
2664
  });
2665
2665
  break;
2666
2666
  }
2667
2667
  case "drop-column": {
2668
2668
  let t = process.env.VOLTRO_SOFT_DROP === "1", n = (/* @__PURE__ */ new Date()).toISOString();
2669
2669
  yield* e.onDialectOrElse({
2670
- mysql: () => H(e).pipe(x.flatMap((r) => X(e, t ? br(o, n, G) : vr(o, r), o.kind, t ? [] : [sr]))),
2671
- sqlite: () => X(e, t ? br(o, n, W) : _r(o, W, !1), o.kind, t ? [] : [cr]),
2672
- orElse: () => X(e, t ? br(o, n, W) : _r(o, W), o.kind)
2670
+ mysql: () => U(e).pipe(S.flatMap((r) => X(e, t ? br(o, n, K) : vr(o, r), o.kind, t ? [] : [sr]))),
2671
+ sqlite: () => X(e, t ? br(o, n, G) : _r(o, G, !1), o.kind, t ? [] : [cr]),
2672
+ orElse: () => X(e, t ? br(o, n, G) : _r(o, G), o.kind)
2673
2673
  });
2674
2674
  break;
2675
2675
  }
2676
2676
  case "rename-column":
2677
2677
  yield* e.onDialectOrElse({
2678
- mysql: () => X(e, yr(o, G), o.kind),
2678
+ mysql: () => X(e, yr(o, K), o.kind),
2679
2679
  mssql: () => X(e, `EXEC sp_rename N'${o.table.replace(/'/g, "''")}.${o.from.replace(/'/g, "''")}', N'${o.to.replace(/'/g, "''")}', 'COLUMN';`, o.kind),
2680
- orElse: () => X(e, yr(o, W), o.kind)
2680
+ orElse: () => X(e, yr(o, G), o.kind)
2681
2681
  });
2682
2682
  break;
2683
2683
  case "add-index":
2684
2684
  yield* e.onDialectOrElse({
2685
- mysql: () => H(e).pipe(x.flatMap((t) => X(e, ti(o, n.declared, t), o.kind, [or]))),
2686
- mssql: () => Z(e, [...di(o.table, o.index.columns, n.declared), ui(o)], o.kind),
2687
- orElse: () => X(e, ei(o, t.classification === "online-required"), o.kind)
2685
+ mysql: () => U(e).pipe(S.flatMap((t) => X(e, ni(o, n.declared, t), o.kind, [or]))),
2686
+ mssql: () => Z(e, [...fi(o.table, o.index.columns, n.declared), di(o)], o.kind),
2687
+ orElse: () => X(e, ti(o, t.classification === "online-required"), o.kind)
2688
2688
  });
2689
2689
  break;
2690
2690
  case "drop-index":
2691
2691
  yield* e.onDialectOrElse({
2692
- mysql: () => X(e, ri(o), o.kind),
2693
- mssql: () => X(e, ii(o), o.kind),
2694
- orElse: () => X(e, ni(o), o.kind)
2692
+ mysql: () => X(e, ii(o), o.kind),
2693
+ mssql: () => X(e, ai(o), o.kind),
2694
+ orElse: () => X(e, ri(o), o.kind)
2695
2695
  });
2696
2696
  break;
2697
2697
  case "rename-table":
2698
2698
  yield* e.onDialectOrElse({
2699
- mysql: () => X(e, ai(o, G), o.kind),
2700
- mssql: () => X(e, oi(o), o.kind),
2701
- orElse: () => X(e, ai(o, W), o.kind)
2699
+ mysql: () => X(e, oi(o, K), o.kind),
2700
+ mssql: () => X(e, si(o), o.kind),
2701
+ orElse: () => X(e, oi(o, G), o.kind)
2702
2702
  });
2703
2703
  break;
2704
2704
  case "rename-index":
2705
2705
  yield* e.onDialectOrElse({
2706
- mysql: () => X(e, ci(o), o.kind),
2707
- mssql: () => X(e, li(o), o.kind),
2708
- orElse: () => X(e, si(o), o.kind)
2706
+ mysql: () => X(e, li(o), o.kind),
2707
+ mssql: () => X(e, ui(o), o.kind),
2708
+ orElse: () => X(e, ci(o), o.kind)
2709
2709
  });
2710
2710
  break;
2711
2711
  case "add-unique":
2712
2712
  yield* e.onDialectOrElse({
2713
- mysql: () => X(e, pi(o, n.declared), o.kind),
2713
+ mysql: () => X(e, mi(o, n.declared), o.kind),
2714
2714
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2715
- mssql: () => Z(e, [...di(o.table, [o.column], n.declared), fi(o)], o.kind),
2716
- orElse: () => X(e, fi(o), o.kind)
2715
+ mssql: () => Z(e, [...fi(o.table, [o.column], n.declared), pi(o)], o.kind),
2716
+ orElse: () => X(e, pi(o), o.kind)
2717
2717
  });
2718
2718
  break;
2719
2719
  case "drop-unique":
2720
2720
  yield* e.onDialectOrElse({
2721
- mysql: () => X(e, yi(o), o.kind),
2721
+ mysql: () => X(e, bi(o), o.kind),
2722
2722
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2723
- orElse: () => X(e, vi(o), o.kind)
2723
+ orElse: () => X(e, yi(o), o.kind)
2724
2724
  });
2725
2725
  break;
2726
2726
  case "add-unique-composite":
2727
2727
  yield* e.onDialectOrElse({
2728
- mysql: () => X(e, hi(o, n.declared), o.kind),
2728
+ mysql: () => X(e, gi(o, n.declared), o.kind),
2729
2729
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2730
- mssql: () => Z(e, [...di(o.table, o.fields, n.declared), mi(o)], o.kind),
2731
- orElse: () => X(e, mi(o), o.kind)
2730
+ mssql: () => Z(e, [...fi(o.table, o.fields, n.declared), hi(o)], o.kind),
2731
+ orElse: () => X(e, hi(o), o.kind)
2732
2732
  });
2733
2733
  break;
2734
2734
  case "drop-unique-composite":
2735
2735
  yield* e.onDialectOrElse({
2736
- mysql: () => X(e, _i(o), o.kind),
2736
+ mysql: () => X(e, vi(o), o.kind),
2737
2737
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2738
- orElse: () => X(e, gi(o), o.kind)
2738
+ orElse: () => X(e, _i(o), o.kind)
2739
2739
  });
2740
2740
  break;
2741
2741
  case "add-foreign-key":
2742
2742
  yield* e.onDialectOrElse({
2743
- mysql: () => Z(e, bi(o, G), o.kind),
2743
+ mysql: () => Z(e, xi(o, K), o.kind),
2744
2744
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2745
- orElse: () => Z(e, bi(o, W), o.kind)
2745
+ orElse: () => Z(e, xi(o, G), o.kind)
2746
2746
  });
2747
2747
  break;
2748
2748
  case "add-column": {
2749
- let n = Di(o, t, a, yield* e.onDialectOrElse({
2750
- mysql: () => x.succeed("mariadb"),
2751
- mssql: () => x.succeed("mssql"),
2752
- sqlite: () => x.succeed("sqlite"),
2753
- orElse: () => x.succeed("postgres")
2749
+ let n = Oi(o, t, a, yield* e.onDialectOrElse({
2750
+ mysql: () => S.succeed("mariadb"),
2751
+ mssql: () => S.succeed("mssql"),
2752
+ sqlite: () => S.succeed("sqlite"),
2753
+ orElse: () => S.succeed("postgres")
2754
2754
  }));
2755
- if (!(r === "resume" && (yield* $(e, Pe(e), o.table, o.column.name)))) for (let t of n.pre) yield* X(e, t, o.kind);
2755
+ if (!(r === "resume" && (yield* $(e, Ne(e), o.table, o.column.name)))) for (let t of n.pre) yield* X(e, t, o.kind);
2756
2756
  if (n.backfillKind === "sql" && n.backfillSql) {
2757
2757
  if (t.classification !== "online-required" && n.batchSize === void 0) yield* e`UPDATE ${e(o.table)} SET ${e(o.column.name)} = ${n.backfillSql}`;
2758
2758
  else {
@@ -2761,10 +2761,10 @@ BEGIN
2761
2761
  let s = i === void 0 ? yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(o.column.name)} IS NULL ORDER BY ${e("id")} ${Q(e, t)}` : yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(o.column.name)} IS NULL AND ${e("id")} > ${i} ORDER BY ${e("id")} ${Q(e, t)}`;
2762
2762
  if (s.length === 0) break;
2763
2763
  let c = s.map((e) => e.id);
2764
- yield* e`UPDATE ${e(o.table)} SET ${e(o.column.name)} = ${n.backfillSql} WHERE ${e("id")} IN ${e.in(c)}`, a += s.length, yield* x.logInfo(`backfill ${o.table}.${o.column.name}: ${a} rows`).pipe(x.annotateLogs({
2764
+ yield* e`UPDATE ${e(o.table)} SET ${e(o.column.name)} = ${n.backfillSql} WHERE ${e("id")} IN ${e.in(c)}`, a += s.length, yield* S.logInfo(`backfill ${o.table}.${o.column.name}: ${a} rows`).pipe(S.annotateLogs({
2765
2765
  scope: "voltro:migrate",
2766
2766
  mode: "sql-batched"
2767
- })), i = s[s.length - 1].id, r > 0 && (yield* x.sleep(`${r} millis`));
2767
+ })), i = s[s.length - 1].id, r > 0 && (yield* S.sleep(`${r} millis`));
2768
2768
  }
2769
2769
  }
2770
2770
  } else if (n.backfillKind === "js" && n.backfillJs) {
@@ -2773,17 +2773,17 @@ BEGIN
2773
2773
  let s = i === void 0 ? yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(o.column.name)} IS NULL ORDER BY ${e("id")} ${Q(e, t)}` : yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(o.column.name)} IS NULL AND ${e("id")} > ${i} ORDER BY ${e("id")} ${Q(e, t)}`;
2774
2774
  if (s.length === 0) break;
2775
2775
  for (let t of s) {
2776
- let r = yield* x.tryPromise({
2776
+ let r = yield* S.tryPromise({
2777
2777
  try: () => Promise.resolve(n.backfillJs({ id: t.id })),
2778
2778
  catch: (e) => e
2779
- }).pipe(x.orDie);
2779
+ }).pipe(S.orDie);
2780
2780
  yield* e`UPDATE ${e(o.table)} SET ${e(o.column.name)} = ${r} WHERE ${e("id")} = ${t.id}`;
2781
2781
  }
2782
- a += s.length, yield* x.logInfo(`backfill ${o.table}.${o.column.name}: ${a} rows processed`).pipe(x.annotateLogs({
2782
+ a += s.length, yield* S.logInfo(`backfill ${o.table}.${o.column.name}: ${a} rows processed`).pipe(S.annotateLogs({
2783
2783
  scope: "voltro:migrate",
2784
2784
  table: o.table,
2785
2785
  column: o.column.name
2786
- })), i = s[s.length - 1].id, r > 0 && (yield* x.sleep(`${r} millis`));
2786
+ })), i = s[s.length - 1].id, r > 0 && (yield* S.sleep(`${r} millis`));
2787
2787
  }
2788
2788
  }
2789
2789
  for (let t of n.post) yield* X(e, t, o.kind);
@@ -2792,30 +2792,30 @@ BEGIN
2792
2792
  case "alter-column-nullability":
2793
2793
  yield* e.onDialectOrElse({
2794
2794
  mysql: () => {
2795
- let t = K(n.declared, o.table, o.column);
2796
- return t ? X(e, `ALTER TABLE ${G(o.table)} MODIFY COLUMN ${Tr(t, o.column, o.toNullable)};`, o.kind) : x.die(/* @__PURE__ */ Error(`alter-column-nullability on mariadb needs the declared column '${o.table}.${o.column}' (to render MODIFY COLUMN); it was not in ctx.declared.`));
2795
+ let t = q(n.declared, o.table, o.column);
2796
+ return t ? X(e, `ALTER TABLE ${K(o.table)} MODIFY COLUMN ${Tr(t, o.column, o.toNullable)};`, o.kind) : S.die(/* @__PURE__ */ Error(`alter-column-nullability on mariadb needs the declared column '${o.table}.${o.column}' (to render MODIFY COLUMN); it was not in ctx.declared.`));
2797
2797
  },
2798
2798
  mssql: () => {
2799
- let t = K(n.declared, o.table, o.column);
2800
- return t ? X(e, Ur(t, o.column, o.table, o.toNullable), o.kind) : x.die(/* @__PURE__ */ Error(`alter-column-nullability on mssql needs the declared column '${o.table}.${o.column}'.`));
2799
+ let t = q(n.declared, o.table, o.column);
2800
+ return t ? X(e, Wr(t, o.column, o.table, o.toNullable), o.kind) : S.die(/* @__PURE__ */ Error(`alter-column-nullability on mssql needs the declared column '${o.table}.${o.column}'.`));
2801
2801
  },
2802
2802
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2803
- orElse: () => X(e, `ALTER TABLE ${W(o.table)} ALTER COLUMN ${W(o.column)} ${o.toNullable ? "DROP NOT NULL" : "SET NOT NULL"};`, o.kind)
2803
+ orElse: () => X(e, `ALTER TABLE ${G(o.table)} ALTER COLUMN ${G(o.column)} ${o.toNullable ? "DROP NOT NULL" : "SET NOT NULL"};`, o.kind)
2804
2804
  });
2805
2805
  break;
2806
2806
  case "alter-column-default": {
2807
- let t = wr(n.declared, o.table, o.column), r = K(n.declared, o.table, o.column), i = (e) => o.hasDefault && r !== void 0 && Sr(r, e) ? r : void 0;
2807
+ let t = wr(n.declared, o.table, o.column), r = q(n.declared, o.table, o.column), i = (e) => o.hasDefault && r !== void 0 && Sr(r, e) ? r : void 0;
2808
2808
  yield* e.onDialectOrElse({
2809
2809
  mysql: () => {
2810
2810
  let n = i("mariadb");
2811
- return X(e, n ? `ALTER TABLE ${G(o.table)} MODIFY COLUMN ${Tr(n, o.column)};` : xr(o, G, (e) => Er(e, t)), o.kind);
2811
+ return X(e, n ? `ALTER TABLE ${K(o.table)} MODIFY COLUMN ${Tr(n, o.column)};` : xr(o, K, (e) => Er(e, t)), o.kind);
2812
2812
  },
2813
2813
  mssql: () => {
2814
2814
  let t = i("mssql");
2815
- return X(e, Wr(o, t ? Ur(t, o.column, o.table) : void 0), o.kind);
2815
+ return X(e, Gr(o, t ? Wr(t, o.column, o.table) : void 0), o.kind);
2816
2816
  },
2817
2817
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2818
- orElse: () => X(e, xr(o, W, (e) => Or(e, t)), o.kind)
2818
+ orElse: () => X(e, xr(o, G, (e) => Or(e, t)), o.kind)
2819
2819
  });
2820
2820
  break;
2821
2821
  }
@@ -2824,51 +2824,51 @@ BEGIN
2824
2824
  if (t.classification !== "online-required") {
2825
2825
  yield* e.onDialectOrElse({
2826
2826
  mysql: () => {
2827
- let t = K(n.declared, o.table, o.column);
2828
- return t ? X(e, `ALTER TABLE ${G(o.table)} MODIFY COLUMN ${Tr(t, o.column)};`, o.kind) : x.die(/* @__PURE__ */ Error(`alter-column-type on mariadb needs the declared column '${o.table}.${o.column}' (to render MODIFY COLUMN); it was not in ctx.declared.`));
2827
+ let t = q(n.declared, o.table, o.column);
2828
+ return t ? X(e, `ALTER TABLE ${K(o.table)} MODIFY COLUMN ${Tr(t, o.column)};`, o.kind) : S.die(/* @__PURE__ */ Error(`alter-column-type on mariadb needs the declared column '${o.table}.${o.column}' (to render MODIFY COLUMN); it was not in ctx.declared.`));
2829
2829
  },
2830
2830
  mssql: () => {
2831
- let t = K(n.declared, o.table, o.column);
2832
- return t ? X(e, Ur(t, o.column, o.table), o.kind) : x.die(/* @__PURE__ */ Error(`alter-column-type on mssql needs the declared column '${o.table}.${o.column}'.`));
2831
+ let t = q(n.declared, o.table, o.column);
2832
+ return t ? X(e, Wr(t, o.column, o.table), o.kind) : S.die(/* @__PURE__ */ Error(`alter-column-type on mssql needs the declared column '${o.table}.${o.column}'.`));
2833
2833
  },
2834
2834
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2835
- orElse: () => X(e, `ALTER TABLE ${W(o.table)} ALTER COLUMN ${W(o.column)} TYPE ${r}${i};`, o.kind)
2835
+ orElse: () => X(e, `ALTER TABLE ${G(o.table)} ALTER COLUMN ${G(o.column)} TYPE ${r}${i};`, o.kind)
2836
2836
  });
2837
2837
  break;
2838
2838
  }
2839
2839
  yield* e.onDialectOrElse({
2840
- mysql: () => x.die(/* @__PURE__ */ Error(`online-required alter-column-type on ${o.table}.${o.column} is not supported on mariadb (the shadow-swap path is postgres-only). Use a smaller-table window or an external online-DDL tool.`)),
2841
- orElse: () => x.void
2840
+ mysql: () => S.die(/* @__PURE__ */ Error(`online-required alter-column-type on ${o.table}.${o.column} is not supported on mariadb (the shadow-swap path is postgres-only). Use a smaller-table window or an external online-DDL tool.`)),
2841
+ orElse: () => S.void
2842
2842
  });
2843
2843
  let a = `${o.column}__shadow`, s = `${o.column}__old`;
2844
- yield* e.unsafe(`ALTER TABLE ${W(o.table)} ADD COLUMN ${W(a)} ${r}`);
2845
- let c = o.using ?? W(o.column), l;
2844
+ yield* e.unsafe(`ALTER TABLE ${G(o.table)} ADD COLUMN ${G(a)} ${r}`);
2845
+ let c = o.using ?? G(o.column), l;
2846
2846
  for (;;) {
2847
2847
  let t = l === void 0 ? yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(a)} IS NULL ORDER BY ${e("id")} ${Q(e, 5e3)}` : yield* e`SELECT ${e("id")} FROM ${e(o.table)} WHERE ${e(a)} IS NULL AND ${e("id")} > ${l} ORDER BY ${e("id")} ${Q(e, 5e3)}`;
2848
2848
  if (t.length === 0) break;
2849
- yield* e.unsafe(`UPDATE ${W(o.table)} SET ${W(a)} = ${c} WHERE ${W(o.column)} IS NOT NULL AND ${W(a)} IS NULL AND ${W("id")} IN (${t.map((e) => `'${e.id.replace(/'/g, "''")}'`).join(",")})`), l = t[t.length - 1].id;
2849
+ yield* e.unsafe(`UPDATE ${G(o.table)} SET ${G(a)} = ${c} WHERE ${G(o.column)} IS NOT NULL AND ${G(a)} IS NULL AND ${G("id")} IN (${t.map((e) => `'${e.id.replace(/'/g, "''")}'`).join(",")})`), l = t[t.length - 1].id;
2850
2850
  }
2851
- yield* x.logInfo(`alter-column-type shadow ${o.table}.${o.column}: shadow populated`).pipe(x.annotateLogs({ scope: "voltro:migrate" })), yield* e.unsafe(`ALTER TABLE ${W(o.table)} RENAME COLUMN ${W(o.column)} TO ${W(s)}`), yield* e.unsafe(`ALTER TABLE ${W(o.table)} RENAME COLUMN ${W(a)} TO ${W(o.column)}`), yield* e.unsafe(`ALTER TABLE ${W(o.table)} DROP COLUMN ${W(s)}`);
2851
+ yield* S.logInfo(`alter-column-type shadow ${o.table}.${o.column}: shadow populated`).pipe(S.annotateLogs({ scope: "voltro:migrate" })), yield* e.unsafe(`ALTER TABLE ${G(o.table)} RENAME COLUMN ${G(o.column)} TO ${G(s)}`), yield* e.unsafe(`ALTER TABLE ${G(o.table)} RENAME COLUMN ${G(a)} TO ${G(o.column)}`), yield* e.unsafe(`ALTER TABLE ${G(o.table)} DROP COLUMN ${G(s)}`);
2852
2852
  break;
2853
2853
  }
2854
2854
  case "drop-foreign-key":
2855
2855
  yield* e.onDialectOrElse({
2856
- mysql: () => X(e, Si(o), o.kind),
2856
+ mysql: () => X(e, Ci(o), o.kind),
2857
2857
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2858
- orElse: () => X(e, xi(o), o.kind)
2858
+ orElse: () => X(e, Si(o), o.kind)
2859
2859
  });
2860
2860
  break;
2861
2861
  case "add-check":
2862
2862
  yield* e.onDialectOrElse({
2863
- mysql: () => X(e, Ci(o, G), o.kind),
2863
+ mysql: () => X(e, wi(o, K), o.kind),
2864
2864
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2865
- orElse: () => X(e, Ci(o, W), o.kind)
2865
+ orElse: () => X(e, wi(o, G), o.kind)
2866
2866
  });
2867
2867
  break;
2868
2868
  case "drop-check": yield* e.onDialectOrElse({
2869
- mysql: () => Ei(e, o, n.declared),
2869
+ mysql: () => Di(e, o, n.declared),
2870
2870
  sqlite: () => Z(e, J(o.table, n.declared), o.kind),
2871
- orElse: () => X(e, wi(o), o.kind)
2871
+ orElse: () => X(e, Ti(o), o.kind)
2872
2872
  });
2873
2873
  }
2874
2874
  return {
@@ -2876,32 +2876,32 @@ BEGIN
2876
2876
  status: "applied",
2877
2877
  durationMs: Number((process.hrtime.bigint() - i) / 1000000n)
2878
2878
  };
2879
- }), Li = (e, t, n, r) => x.gen(function* () {
2879
+ }), Ri = (e, t, n, r) => S.gen(function* () {
2880
2880
  let i = [...new Set(r.map((e) => e.runId))];
2881
- if (i.length > 1) return yield* x.die(/* @__PURE__ */ Error(`applyPlan: the resume ledger holds ${i.length} unfinished runs (${i.join(", ")}). Only one migration may be in flight at a time — the advisory lock enforces it — so this means a run was interrupted and a LATER one wrote over it without clearing.\nNothing was changed. Inspect \`${D}\`, reconcile the schema by hand, and delete the rows of the run you have finished.`));
2881
+ if (i.length > 1) return yield* S.die(/* @__PURE__ */ Error(`applyPlan: the resume ledger holds ${i.length} unfinished runs (${i.join(", ")}). Only one migration may be in flight at a time — the advisory lock enforces it — so this means a run was interrupted and a LATER one wrote over it without clearing.\nNothing was changed. Inspect \`${k}\`, reconcile the schema by hand, and delete the rows of the run you have finished.`));
2882
2882
  let a = i[0], o = [...r].map((e) => ({
2883
2883
  index: Number(e.opIndex),
2884
2884
  status: e.status,
2885
2885
  planned: JSON.parse(e.payload)
2886
2886
  })).sort((e, t) => e.index - t.index), s = o.find((e) => e.status === "started"), c = o.filter((e) => e.status === "started").length;
2887
- if (c > 1) return yield* x.die(/* @__PURE__ */ Error(`applyPlan: the resume ledger records ${c} operations as in-flight for run ${a}. It is written strictly sequentially, so at most one can be — this ledger is corrupt and the schema state it describes cannot be trusted.\nNothing was changed. Reconcile \`${D}\` by hand before re-running.`));
2888
- if (yield* x.logWarning(`migration resume: found an interrupted run (${a}) — ${o.filter((e) => e.status === "applied").length} of ${o.length} operation(s) completed${s ? `, in flight: ${s.planned.op.kind} ${ze(s.planned.op)}` : ""}`).pipe(x.annotateLogs({ scope: "voltro:migrate" })), o.every((e) => e.status === "pending")) return {
2887
+ if (c > 1) return yield* S.die(/* @__PURE__ */ Error(`applyPlan: the resume ledger records ${c} operations as in-flight for run ${a}. It is written strictly sequentially, so at most one can be — this ledger is corrupt and the schema state it describes cannot be trusted.\nNothing was changed. Reconcile \`${k}\` by hand before re-running.`));
2888
+ if (yield* S.logWarning(`migration resume: found an interrupted run (${a}) — ${o.filter((e) => e.status === "applied").length} of ${o.length} operation(s) completed${s ? `, in flight: ${s.planned.op.kind} ${Re(s.planned.op)}` : ""}`).pipe(S.annotateLogs({ scope: "voltro:migrate" })), o.every((e) => e.status === "pending")) return {
2889
2889
  kind: "discard",
2890
2890
  runId: a,
2891
2891
  why: "no operation had started — no DDL ran"
2892
2892
  };
2893
- let l = s ? yield* Fi(e, t, s.planned) : "clean", u = r[0].planFingerprint;
2893
+ let l = s ? yield* Ii(e, t, s.planned) : "clean", u = r[0].planFingerprint;
2894
2894
  if (u !== n.toFingerprint) return {
2895
2895
  kind: "discard",
2896
2896
  runId: a,
2897
2897
  why: `the declared schema changed since the interruption (recorded target ${u.slice(0, 12)}…, current ${n.toFingerprint.slice(0, 12)}…) — applying the freshly-diffed plan instead`
2898
2898
  };
2899
- let d = (e) => e.status === "applied" ? !1 : s && e.index === s.index && l !== "clean" ? l === "outstanding" : Ve(n, e.planned.op), f = o.filter(d), p = o.filter((e) => e.status !== "applied" && !d(e));
2899
+ let d = (e) => e.status === "applied" ? !1 : s && e.index === s.index && l !== "clean" ? l === "outstanding" : Be(n, e.planned.op), f = o.filter(d), p = o.filter((e) => e.status !== "applied" && !d(e));
2900
2900
  return f.length === 0 ? {
2901
2901
  kind: "discard",
2902
2902
  runId: a,
2903
2903
  why: "every recorded operation had already taken effect"
2904
- } : (yield* Ni(e, a, f.map((e) => e.index), p.map((e) => e.index)), yield* x.logWarning(`migration resume: continuing run ${a} — replaying ${f.length} operation(s), ${o.length - f.length} already applied`).pipe(x.annotateLogs({ scope: "voltro:migrate" })), {
2904
+ } : (yield* Pi(e, a, f.map((e) => e.index), p.map((e) => e.index)), yield* S.logWarning(`migration resume: continuing run ${a} — replaying ${f.length} operation(s), ${o.length - f.length} already applied`).pipe(S.annotateLogs({ scope: "voltro:migrate" })), {
2905
2905
  kind: "resume",
2906
2906
  runId: a,
2907
2907
  ops: f.map((e) => ({
@@ -2909,70 +2909,90 @@ BEGIN
2909
2909
  planned: e.planned
2910
2910
  }))
2911
2911
  });
2912
- }), Ri = (e, t, n) => x.gen(function* () {
2912
+ }), zi = (e) => {
2913
+ let t = e.op, n = (e) => typeof t[e] == "string" ? t[e] : "";
2914
+ return [
2915
+ t.kind,
2916
+ n("table"),
2917
+ n("column"),
2918
+ n("name"),
2919
+ n("to")
2920
+ ].join("\0");
2921
+ }, Bi = (e, t, n) => S.gen(function* () {
2913
2922
  let r = t.operations.filter((e) => e.blocked);
2914
- if (r.length > 0) return yield* x.die(/* @__PURE__ */ Error(`applyPlan: refusing to execute — ${r.length} blocked operations. Run \`voltro db plan\` to see the fixes.`));
2915
- yield* T(e, { schema: n.lockSchema });
2916
- let i = Date.now(), a = [], o = Pe(e), s = Ie(o) === "plan-transactional", c = s ? t.operations.filter((e) => e.classification !== "online-required") : [], l = s ? t.operations.filter((e) => e.classification === "online-required") : t.operations, d = `plan_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`, f = l.map((e, t) => ({
2923
+ if (r.length > 0) return yield* S.die(/* @__PURE__ */ Error(`applyPlan: refusing to execute — ${r.length} blocked operations. Run \`voltro db plan\` to see the fixes.`));
2924
+ yield* je(e, { schema: n.lockSchema });
2925
+ let i = Date.now(), a = [], o = Ne(e), s = yield* n.replan(e), c = new Set(t.operations.filter((e) => !e.blocked).map((e) => zi(e))), l = {
2926
+ ...s,
2927
+ operations: s.operations.map((e) => {
2928
+ if (!e.blocked || !c.has(zi(e))) return e;
2929
+ let { blocked: t, ...n } = e;
2930
+ return n;
2931
+ })
2932
+ };
2933
+ (l.operations.length !== t.operations.length || l.toFingerprint !== t.toFingerprint) && (yield* S.logInfo(`migration: re-planned under the lock — ${t.operations.length} operation(s) became ${l.operations.length}. Another writer changed the schema while this plan waited.`).pipe(S.annotateLogs({ scope: "voltro:migrate" })));
2934
+ let u = l.operations.filter((e) => e.blocked);
2935
+ if (u.length > 0) return yield* O(e, { schema: n.lockSchema }).pipe(S.orDie), yield* S.die(/* @__PURE__ */ Error(`applyPlan: refusing to execute — re-planning under the migration lock found ${u.length} blocked operation(s). Run \`voltro db plan\` to see the fixes.`));
2936
+ let d = Fe(o) === "plan-transactional", f = d ? l.operations.filter((e) => e.classification !== "online-required") : [], p = d ? l.operations.filter((e) => e.classification === "online-required") : l.operations, m = `plan_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`, h = p.map((e, t) => ({
2917
2937
  index: t,
2918
2938
  planned: e
2919
- })), p = "fresh";
2939
+ })), g = "fresh";
2920
2940
  try {
2921
- yield* ki(e, o);
2922
- let r = yield* Ai(e);
2923
- if (r.length > 0) {
2924
- let n = yield* Li(e, o, t, r);
2925
- n.kind === "resume" ? (d = n.runId, f = n.ops, p = "resume") : (yield* x.logWarning(`migration resume: discarding the ledger of run ${n.runId} — ${n.why}`).pipe(x.annotateLogs({ scope: "voltro:migrate" })), yield* Pi(e, n.runId));
2941
+ yield* Ai(e, o);
2942
+ let t = yield* ji(e);
2943
+ if (t.length > 0) {
2944
+ let n = yield* Ri(e, o, l, t);
2945
+ n.kind === "resume" ? (m = n.runId, h = n.ops, g = "resume") : (yield* S.logWarning(`migration resume: discarding the ledger of run ${n.runId} — ${n.why}`).pipe(S.annotateLogs({ scope: "voltro:migrate" })), yield* Fi(e, n.runId));
2926
2946
  }
2927
- p === "fresh" && f.length > 0 && (yield* ji(e, d, t.toFingerprint, f)), c.length > 0 && (yield* e.withTransaction(x.gen(function* () {
2928
- let e = yield* C.SqlClient;
2929
- for (let t of c) a.push(yield* Ii(e, t, n));
2947
+ g === "fresh" && h.length > 0 && (yield* Mi(e, m, l.toFingerprint, h)), f.length > 0 && (yield* e.withTransaction(S.gen(function* () {
2948
+ let e = yield* E.SqlClient;
2949
+ for (let t of f) a.push(yield* Li(e, t, n));
2930
2950
  })));
2931
- for (let { index: t, planned: r } of f) {
2932
- yield* Mi(e, d, t, "started");
2933
- let i = a.length, o = yield* Ii(e, r, n, p).pipe(x.mapError((e) => Object.assign(e, { message: `${String(e?.message ?? e)}\n\n progress: ${i} of ${f.length + c.length} operation(s) applied before this one${c.length > 0 ? ` (${c.length} of them in a transaction)` : ""}.\n` + (s ? " This dialect applies a plan atomically, so the run is rolled back.\n" : ` This dialect does NOT apply a plan atomically: those ${i} are COMMITTED and there is no rollback.\n The next \`voltro db apply\` resumes from operation ${t} — the ledger records the sequence.\n`) })));
2934
- a.push(o), yield* Mi(e, d, t, "applied", o.durationMs);
2951
+ for (let { index: t, planned: r } of h) {
2952
+ yield* Ni(e, m, t, "started");
2953
+ let i = a.length, o = yield* Li(e, r, n, g).pipe(S.mapError((e) => Object.assign(e, { message: `${String(e?.message ?? e)}\n\n progress: ${i} of ${h.length + f.length} operation(s) applied before this one${f.length > 0 ? ` (${f.length} of them in a transaction)` : ""}.\n` + (d ? " This dialect applies a plan atomically, so the run is rolled back.\n" : ` This dialect does NOT apply a plan atomically: those ${i} are COMMITTED and there is no rollback.\n The next \`voltro db apply\` resumes from operation ${t} — the ledger records the sequence.\n`) })));
2954
+ a.push(o), yield* Ni(e, m, t, "applied", o.durationMs);
2935
2955
  }
2936
2956
  } finally {
2937
- yield* E(e, { schema: n.lockSchema }).pipe(x.orDie);
2957
+ yield* O(e, { schema: n.lockSchema }).pipe(S.orDie);
2938
2958
  }
2939
- let m = yield* n.replan(e);
2940
- if (m.operations.length > 0) {
2941
- let e = m.operations.slice(0, 10).map((e) => ` - ${e.op.kind} ${"table" in e.op ? e.op.table : ""}${"column" in e.op ? `.${String(e.op.column)}` : ""}`).join("\n");
2942
- return yield* x.die(/* @__PURE__ */ Error(`applyPlan: the migration did not converge. ${t.operations.length} operation(s) were executed without error, but re-planning against the live schema still finds ${m.operations.length}:\n${e}${m.operations.length > 10 ? `\n … and ${m.operations.length - 10} more` : ""}\nNo fingerprint was recorded — recording one would make the next boot report "schema up to date" for a schema that was never applied. This is a framework bug; the schema is unchanged and safe.\nTwo causes look identical from here, so read the list before assuming either:\n - the DDL for those operations is a no-op (it succeeded and changed nothing), or\n - the planner cannot see what the DDL did, so it proposes the same work again — which is what an\n operation naming an object a PREVIOUS operation created or renamed usually means.\nReport the operation kinds above with the column types involved.`));
2959
+ let _ = yield* n.replan(e);
2960
+ if (_.operations.length > 0) {
2961
+ let e = _.operations.slice(0, 10).map((e) => ` - ${e.op.kind} ${"table" in e.op ? e.op.table : ""}${"column" in e.op ? `.${String(e.op.column)}` : ""}`).join("\n");
2962
+ return yield* S.die(/* @__PURE__ */ Error(`applyPlan: the migration did not converge. ${l.operations.length} operation(s) were executed without error, but re-planning against the live schema still finds ${_.operations.length}:\n${e}${_.operations.length > 10 ? `\n … and ${_.operations.length - 10} more` : ""}\nNo fingerprint was recorded — recording one would make the next boot report "schema up to date" for a schema that was never applied. This is a framework bug; the schema is unchanged and safe.\nTwo causes look identical from here, so read the list before assuming either:\n - the DDL for those operations is a no-op (it succeeded and changed nothing), or\n - the planner cannot see what the DDL did, so it proposes the same work again — which is what an\n operation naming an object a PREVIOUS operation created or renamed usually means.\nReport the operation kinds above with the column types involved.`));
2943
2963
  }
2944
- let h = a.filter((e) => e.status === "applied").length, g = Date.now() - i, _ = d, v = (/* @__PURE__ */ new Date()).toISOString(), y = yield* U(e, v), b = [...c, ...f.map((e) => e.planned)];
2964
+ let y = a.filter((e) => e.status === "applied").length, b = Date.now() - i, x = m, C = (/* @__PURE__ */ new Date()).toISOString(), w = yield* W(e, C), T = [...f, ...h.map((e) => e.planned)];
2945
2965
  yield* e`
2946
2966
  INSERT INTO ${e("_voltro_migration_plans")}
2947
2967
  (${e("id")}, ${e("fingerprint")}, ${e("liveFingerprint")}, ${e("operations")},
2948
2968
  ${e("appliedBy")}, ${e("environment")}, ${e("source")},
2949
2969
  ${e("durationMs")}, ${e("appliedAt")}, ${e("notes")})
2950
2970
  VALUES
2951
- (${_}, ${t.toFingerprint}, ${m.fromFingerprint}, ${JSON.stringify(b)},
2971
+ (${x}, ${l.toFingerprint}, ${_.fromFingerprint}, ${JSON.stringify(T)},
2952
2972
  ${n.appliedBy}, ${n.environment}, ${n.source},
2953
- ${g}, ${y}, ${n.notes ?? null})
2954
- `, yield* Pi(e, d);
2955
- let S = [...new Set(b.flatMap((e) => e.op.kind === "rename-table" ? [e.op.to] : [e.op.table]))];
2956
- return yield* x.promise(() => u({ changedTables: S }).catch(() => {})), {
2957
- id: _,
2958
- appliedAt: v,
2959
- fingerprint: t.toFingerprint,
2960
- operations: b,
2973
+ ${b}, ${w}, ${n.notes ?? null})
2974
+ `, yield* Fi(e, m);
2975
+ let ee = [...new Set(T.flatMap((e) => e.op.kind === "rename-table" ? [e.op.to] : [e.op.table]))];
2976
+ return yield* S.promise(() => v({ changedTables: ee }).catch(() => {})), {
2977
+ id: x,
2978
+ appliedAt: C,
2979
+ fingerprint: l.toFingerprint,
2980
+ operations: T,
2961
2981
  appliedBy: n.appliedBy,
2962
2982
  environment: n.environment,
2963
- durationMs: g,
2964
- appliedOps: h,
2983
+ durationMs: b,
2984
+ appliedOps: y,
2965
2985
  source: n.source,
2966
2986
  ...n.notes ? { notes: n.notes } : {}
2967
2987
  };
2968
- }), zi = (e) => e.operations.filter((e) => e.blocked).map((e) => ` - ${e.op.kind} ${"table" in e.op ? `[${e.op.table}]` : ""}: ${e.reason ?? "<no reason>"}\n fix: ${e.blocked?.fix ?? "<no fix>"}`).join("\n"), Bi = (e) => e`
2988
+ }), Vi = (e) => e.operations.filter((e) => e.blocked).map((e) => ` - ${e.op.kind} ${"table" in e.op ? `[${e.op.table}]` : ""}: ${e.reason ?? "<no reason>"}\n fix: ${e.blocked?.fix ?? "<no fix>"}`).join("\n"), Hi = (e) => e`
2969
2989
  SELECT fingerprint
2970
2990
  FROM _voltro_migration_plans
2971
2991
  ORDER BY ${e("appliedAt")} DESC
2972
2992
  LIMIT 1
2973
- `.pipe(x.map((e) => e.length > 0 ? e[0].fingerprint : void 0), x.catchAll(() => x.succeed(void 0))), Vi = (e, t, n) => x.gen(function* () {
2974
- if ((yield* Bi(e)) === t.toFingerprint) return "already-current";
2975
- let r = `plan_${Date.now().toString(36)}`, i = yield* U(e, (/* @__PURE__ */ new Date()).toISOString());
2993
+ `.pipe(S.map((e) => e.length > 0 ? e[0].fingerprint : void 0), S.catchAll(() => S.succeed(void 0))), Ui = (e, t, n) => S.gen(function* () {
2994
+ if ((yield* Hi(e)) === t.toFingerprint) return "already-current";
2995
+ let r = `plan_${Date.now().toString(36)}`, i = yield* W(e, (/* @__PURE__ */ new Date()).toISOString());
2976
2996
  return yield* e`
2977
2997
  INSERT INTO ${e("_voltro_migration_plans")}
2978
2998
  (${e("id")}, ${e("fingerprint")}, ${e("liveFingerprint")}, ${e("operations")},
@@ -2983,8 +3003,8 @@ BEGIN
2983
3003
  ${n.appliedBy}, ${n.environment}, ${n.source},
2984
3004
  ${0}, ${i}, ${"no DDL — the declared schema already matched the database"})
2985
3005
  `, "recorded";
2986
- }).pipe(x.catchAll(() => x.succeed("already-current"))), Hi = (e, t) => x.gen(function* () {
2987
- let n = P(F(t, Pe(e))), r = yield* Bi(e);
3006
+ }).pipe(S.catchAll(() => S.succeed("already-current"))), Wi = (e, t) => S.gen(function* () {
3007
+ let n = Wt(I(t, Ne(e))), r = yield* Hi(e);
2988
3008
  return r === n ? {
2989
3009
  kind: "up-to-date",
2990
3010
  fingerprint: n
@@ -2993,23 +3013,23 @@ BEGIN
2993
3013
  expected: n,
2994
3014
  ...r === void 0 ? {} : { actual: r }
2995
3015
  };
2996
- }), Ui = [
3016
+ }), Gi = [
2997
3017
  "pgeagertest_",
2998
3018
  "mig_e2e_",
2999
3019
  "mig_test_",
3000
3020
  "mysqleagertest_",
3001
3021
  "mssqleagertest_",
3002
3022
  "sqliteeagertest_"
3003
- ], Wi = (e) => Ui.some((t) => e.startsWith(t)), Gi = (e, t) => x.gen(function* () {
3023
+ ], Ki = (e) => Gi.some((t) => e.startsWith(t)), qi = (e, t) => S.gen(function* () {
3004
3024
  if (process.env.VOLTRO_TEST_FIXTURE_GC === "off") return [];
3005
- let n = t.filter((e) => Wi(e.name)).map((e) => e.name);
3025
+ let n = t.filter((e) => Ki(e.name)).map((e) => e.name);
3006
3026
  if (n.length === 0) return [];
3007
- for (let t of n) yield* e.unsafe(`DROP TABLE IF EXISTS "${t}" CASCADE`).pipe(x.catchAll(() => x.void));
3027
+ for (let t of n) yield* e.unsafe(`DROP TABLE IF EXISTS "${t}" CASCADE`).pipe(S.catchAll(() => S.void));
3008
3028
  return n;
3009
- }), Ki = () => {
3029
+ }), Ji = () => {
3010
3030
  let e = (process.env.VOLTRO_DB_IGNORE_TABLES ?? "").split(",").map((e) => e.trim()).filter((e) => e.length > 0);
3011
3031
  return e.length > 0 ? { ignoreTables: e } : {};
3012
- }, qi = (e) => {
3032
+ }, Yi = (e) => {
3013
3033
  if (e === void 0) return;
3014
3034
  let t = e.trim();
3015
3035
  if (t === "") return;
@@ -3019,31 +3039,31 @@ BEGIN
3019
3039
  kind: "tables",
3020
3040
  tables: new Set(n)
3021
3041
  } : void 0;
3022
- }, Ji = (e) => typeof e.table == "string" ? e.table : void 0, Yi = (e, t = { kind: "all" }) => ({
3042
+ }, Xi = (e) => typeof e.table == "string" ? e.table : void 0, Zi = (e, t = { kind: "all" }) => ({
3023
3043
  ...e,
3024
3044
  operations: e.operations.map((e) => {
3025
3045
  if (!e.blocked || e.classification !== "lossy") return e;
3026
3046
  if (t?.kind === "tables") {
3027
- let n = Ji(e.op);
3047
+ let n = Xi(e.op);
3028
3048
  if (n === void 0 || !t.tables.has(n)) return e;
3029
3049
  }
3030
3050
  let { blocked: n, ...r } = e;
3031
3051
  return r;
3032
3052
  })
3033
- }), Xi = (e, t, n) => t === "postgres" ? Xt(e, n).pipe(x.flatMap((e) => {
3053
+ }), Qi = (e, t, n) => t === "postgres" ? Xt(e, n).pipe(S.flatMap((e) => {
3034
3054
  let t = Zt(e);
3035
- return t === void 0 ? x.void : x.logWarning(`auto-migrate: ${t}`).pipe(x.annotateLogs({ scope: "voltro:migrate" }));
3036
- }), x.catchAll(() => x.void)) : x.void, Zi = (e, t, n) => x.gen(function* () {
3037
- let r = Pe(e), i = t;
3055
+ return t === void 0 ? S.void : S.logWarning(`auto-migrate: ${t}`).pipe(S.annotateLogs({ scope: "voltro:migrate" }));
3056
+ }), S.catchAll(() => S.void)) : S.void, $i = (e, t, n) => S.gen(function* () {
3057
+ let r = Ne(e), i = t;
3038
3058
  if (process.env.VOLTRO_MIGRATE_FORCE !== "1") {
3039
- let t = P(F(i, r));
3040
- if ((yield* Bi(e)) === t) return yield* Xi(e, r, i), {
3059
+ let t = Wt(I(i, r));
3060
+ if ((yield* Hi(e)) === t) return yield* Qi(e, r, i), {
3041
3061
  kind: "up-to-date",
3042
3062
  fingerprint: t
3043
3063
  };
3044
3064
  }
3045
- let a = yield* $n(e), o = yield* Gi(e, a.tables);
3046
- o.length > 0 && (yield* x.logInfo(`auto-migrate: reaped ${o.length} test-fixture leftover(s)`).pipe(x.annotateLogs({
3065
+ let a = yield* $n(e), o = yield* qi(e, a.tables);
3066
+ o.length > 0 && (yield* S.logInfo(`auto-migrate: reaped ${o.length} test-fixture leftover(s)`).pipe(S.annotateLogs({
3047
3067
  scope: "voltro:migrate",
3048
3068
  count: o.length
3049
3069
  })), a = yield* $n(e));
@@ -3051,16 +3071,16 @@ BEGIN
3051
3071
  declared: i,
3052
3072
  live: { tables: c(a.tables) },
3053
3073
  dialect: r,
3054
- ...Ki()
3074
+ ...Ji()
3055
3075
  });
3056
3076
  if (l.summary.blocked > 0) {
3057
- let e = l.operations.filter((e) => e.blocked).every((e) => e.classification === "lossy"), t = qi(process.env.VOLTRO_DESTRUCTIVE_OK);
3058
- if (t === void 0 || !e || (l = Yi(l, t), l.operations.some((e) => e.blocked))) return {
3077
+ let e = l.operations.filter((e) => e.blocked).every((e) => e.classification === "lossy"), t = Yi(process.env.VOLTRO_DESTRUCTIVE_OK);
3078
+ if (t === void 0 || !e || (l = Zi(l, t), l.operations.some((e) => e.blocked))) return {
3059
3079
  kind: "refused-blocked",
3060
3080
  plan: l
3061
3081
  };
3062
3082
  }
3063
- return l.operations.length === 0 ? (yield* Vi(e, l, {
3083
+ return l.operations.length === 0 ? (yield* Ui(e, l, {
3064
3084
  appliedBy: n.appliedBy,
3065
3085
  environment: n.environment === "prod" ? "dev" : n.environment,
3066
3086
  source: "auto-diff"
@@ -3069,27 +3089,27 @@ BEGIN
3069
3089
  fingerprint: l.toFingerprint
3070
3090
  }) : {
3071
3091
  kind: "applied",
3072
- applied: yield* Ri(e, l, {
3092
+ applied: yield* Bi(e, l, {
3073
3093
  declared: t,
3074
3094
  appliedBy: n.appliedBy,
3075
3095
  environment: n.environment === "prod" ? "dev" : n.environment,
3076
3096
  source: "auto-diff",
3077
- replan: (e) => x.gen(function* () {
3097
+ replan: (e) => S.gen(function* () {
3078
3098
  let t = yield* $n(e);
3079
3099
  return Nn({
3080
3100
  declared: i,
3081
3101
  live: { tables: c(t.tables) },
3082
3102
  dialect: r,
3083
- ...Ki()
3103
+ ...Ji()
3084
3104
  });
3085
3105
  })
3086
3106
  }),
3087
3107
  plan: l
3088
3108
  };
3089
- }), Qi = (e, t, n) => process.env.VOLTRO_AUTO_MIGRATE === "0" ? x.succeed({
3109
+ }), ea = (e, t, n) => process.env.VOLTRO_AUTO_MIGRATE === "0" ? S.succeed({
3090
3110
  kind: "skipped",
3091
3111
  reason: "VOLTRO_AUTO_MIGRATE=0"
3092
- }) : n.environment === "prod" ? Hi(e, t) : Zi(e, t, n), $i = (e, t) => {
3112
+ }) : n.environment === "prod" ? Wi(e, t) : $i(e, t, n), ta = (e, t) => {
3093
3113
  switch (e.kind) {
3094
3114
  case "skipped": return `auto-migrate: skipped (${e.reason})`;
3095
3115
  case "up-to-date": return `auto-migrate: schema up to date (${t}, fingerprint=${Gt(e.fingerprint)})`;
@@ -3099,7 +3119,7 @@ BEGIN
3099
3119
  }
3100
3120
  case "prod-mismatch": return `auto-migrate: SCHEMA FINGERPRINT MISMATCH — declared=${Gt(e.expected)}` + (e.actual ? ` live=${Gt(e.actual)}` : " live=<no _voltro_migration_plans row>") + ". Run `voltro db apply --plan plan.json` from the deploy pipeline before serving.";
3101
3121
  case "refused-blocked": {
3102
- let t = e.plan.operations.filter((e) => e.blocked), n = t.filter((e) => e.op.kind === "drop-table").length, r = t.filter((e) => e.op.kind === "drop-table").map((e) => "table" in e.op ? e.op.table : "").filter(Boolean), i = t.filter((e) => e.op.kind === "add-column").length, a = t.filter((e) => e.op.kind === "drop-column").length, o = t.filter((e) => e.classification === "needs-rename-annotation").length, s = `auto-migrate: REFUSED — ${e.plan.summary.blocked} blocked operation(s):\n` + zi(e.plan), c = [""];
3122
+ let t = e.plan.operations.filter((e) => e.blocked), n = t.filter((e) => e.op.kind === "drop-table").length, r = t.filter((e) => e.op.kind === "drop-table").map((e) => "table" in e.op ? e.op.table : "").filter(Boolean), i = t.filter((e) => e.op.kind === "add-column").length, a = t.filter((e) => e.op.kind === "drop-column").length, o = t.filter((e) => e.classification === "needs-rename-annotation").length, s = `auto-migrate: REFUSED — ${e.plan.summary.blocked} blocked operation(s):\n` + Vi(e.plan), c = [""];
3103
3123
  if (n > 0 && c.push(`${n} table(s) exist in the live DB but aren't in your declared schema.`, "This is usually one of three things:", " (a) You're iterating on the schema — the table file got renamed, moved, or temporarily commented out.", " → Restore the declaration. Your data stays intact.", " (b) You want to KEEP the table but NOT manage it with Voltro (a leftover from another tool —", " a Strapi/Rails/legacy migration artifact, or an externally-owned table).", ` → Set \`VOLTRO_DB_IGNORE_TABLES=${r.join(",")}\` (comma-separated).`, " The planner excludes those tables from the diff entirely — it never drops them, and they", " stop blocking your OTHER (additive) changes. This is the fix when a leftover freezes your schema.", " (c) You actually want to drop the table.", ` → Set \`VOLTRO_DESTRUCTIVE_OK=${r.join(",")}\` for ONE run — it acknowledges`, " the data loss for THOSE tables only; every other lossy op in this plan stays blocked.", " (`VOLTRO_DESTRUCTIVE_OK=1` acknowledges all of them, which is rarely what you mean.)", " There is deliberately no `dropped()` marker for a TABLE, unlike for a column: a", " dropped column leaves a slot worth documenting in the declaration, a dropped table", " leaves nothing — the marker would be a dead entry you must remember to delete.", " Soft-drop: set `VOLTRO_SOFT_DROP=1` alongside DESTRUCTIVE_OK to RENAME instead of DROP", " (data survives as `<name>__dropped_<ts>` for ~7d; restorable via `voltro db restore-snapshot`)."), i > 0 && c.push(`${i} required column(s) need a backfill strategy before adding to a populated table.`, " → Annotate the column: `.backfill(sql`<expr>`)` or `.backfill(row => <fn>)` or `.default(<value>)`.", " Existing rows get the backfill value; the column then lands as NOT NULL."), a > 0) {
3104
3124
  let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
3105
3125
  for (let r of e.plan.operations) {
@@ -3116,7 +3136,7 @@ BEGIN
3116
3136
  return o > 0 && c.push(`${o} column(s) look like renames (one column gone + a new one of same shape appeared).`, " → On the NEW column add `.renamedFrom('<oldName>')` so the planner emits RENAME instead of DROP+ADD."), c.push("", "See `voltro db plan` for the full machine-readable diff."), s + "\n" + c.join("\n");
3117
3137
  }
3118
3138
  }
3119
- }, ea = /* @__PURE__ */ new Set([
3139
+ }, na = /* @__PURE__ */ new Set([
3120
3140
  "node_modules",
3121
3141
  "dist",
3122
3142
  "build",
@@ -3125,24 +3145,24 @@ BEGIN
3125
3145
  ".next",
3126
3146
  ".git",
3127
3147
  ".framework"
3128
- ]), ta = async (e) => {
3148
+ ]), ra = async (e) => {
3129
3149
  let t = [], n = async (e) => {
3130
- let r = await ne.readdir(e, { withFileTypes: !0 }).catch(() => []);
3150
+ let r = await ee.readdir(e, { withFileTypes: !0 }).catch(() => []);
3131
3151
  for (let i of r) {
3132
- if (ea.has(i.name)) continue;
3133
- let r = re(e, i.name);
3134
- i.isDirectory() ? await n(r) : i.isFile() && f.test(i.name) && t.push(r);
3152
+ if (na.has(i.name)) continue;
3153
+ let r = te(e, i.name);
3154
+ i.isDirectory() ? await n(r) : i.isFile() && m.test(i.name) && t.push(r);
3135
3155
  }
3136
3156
  };
3137
3157
  return await n(e), t.sort((e, t) => {
3138
3158
  let n = e.split("/").pop() ?? e, r = t.split("/").pop() ?? t;
3139
3159
  return n.localeCompare(r);
3140
3160
  });
3141
- }, na = async (e) => {
3161
+ }, ia = async (e) => {
3142
3162
  let t = [];
3143
3163
  for (let n of e) {
3144
- let e = (await import(ie(n).href)).default;
3145
- if (!l(e)) {
3164
+ let e = (await import(ne(n).href)).default;
3165
+ if (!g(e)) {
3146
3166
  process.stderr.write(`[voltro:migrate] ${n} has no default-exported \`migration(...)\` — skipped\n`);
3147
3167
  continue;
3148
3168
  }
@@ -3152,11 +3172,11 @@ BEGIN
3152
3172
  });
3153
3173
  }
3154
3174
  return t;
3155
- }, ra = (e) => e`
3175
+ }, aa = (e) => e`
3156
3176
  SELECT ${e("id")}
3157
3177
  FROM ${e("_voltro_migration_plans")}
3158
3178
  WHERE ${e("source")} = 'file'
3159
- `.pipe(x.map((e) => e.map((e) => e.id)), x.catchAll(() => x.succeed([]))), ia = class extends Error {
3179
+ `.pipe(S.map((e) => e.map((e) => e.id)), S.catchAll(() => S.succeed([]))), oa = class extends Error {
3160
3180
  migrationId;
3161
3181
  file;
3162
3182
  cause;
@@ -3164,28 +3184,28 @@ BEGIN
3164
3184
  constructor(e, t, n) {
3165
3185
  super(`migration ${e}: up() SUCCEEDED but the ledger row could not be written.\n The change IS in the database. It is NOT recorded, so the next run would apply it AGAIN.\n Do not re-run ${t} until this is resolved.\n Cause: ${n instanceof Error ? n.message : String(n)}`), this.migrationId = e, this.file = t, this.cause = n, this.name = "FileMigrationLedgerError";
3166
3186
  }
3167
- }, aa = (e, t, n, r) => x.gen(function* () {
3187
+ }, sa = (e, t, n, r) => S.gen(function* () {
3168
3188
  let i = Date.now(), a = (/* @__PURE__ */ new Date()).toISOString(), o = {
3169
3189
  sql: e,
3170
3190
  log: {
3171
- info: (e, n) => x.logInfo(e).pipe(x.annotateLogs({
3191
+ info: (e, n) => S.logInfo(e).pipe(S.annotateLogs({
3172
3192
  scope: `migrations:file:${t.migration.id}`,
3173
3193
  ...n ?? {}
3174
3194
  })),
3175
- warn: (e, n) => x.logWarning(e).pipe(x.annotateLogs({
3195
+ warn: (e, n) => S.logWarning(e).pipe(S.annotateLogs({
3176
3196
  scope: `migrations:file:${t.migration.id}`,
3177
3197
  ...n ?? {}
3178
3198
  }))
3179
3199
  },
3180
3200
  appliedAt: a
3181
3201
  }, s = t.migration.up(o);
3182
- x.isEffect(s) ? yield* s : yield* x.tryPromise({
3202
+ S.isEffect(s) ? yield* s : yield* S.tryPromise({
3183
3203
  try: () => s,
3184
3204
  catch: (e) => e
3185
3205
  });
3186
3206
  let c = Date.now() - i;
3187
- !x.isEffect(s) && c < 2 && (yield* x.logWarning(`migration ${t.migration.id}: up() resolved in ${c}ms — did the body \`await\` an \`@effect/sql\` Effect by accident? \`sql.unsafe(...)\` returns an Effect, not a Promise; \`await\` on it is a silent no-op. Switch the body to \`Effect.gen(function* () { yield* sql.unsafe(...) })\` form.`).pipe(x.annotateLogs({ scope: `migrations:file:${t.migration.id}` })));
3188
- let l = yield* U(e, a);
3207
+ !S.isEffect(s) && c < 2 && (yield* S.logWarning(`migration ${t.migration.id}: up() resolved in ${c}ms — did the body \`await\` an \`@effect/sql\` Effect by accident? \`sql.unsafe(...)\` returns an Effect, not a Promise; \`await\` on it is a silent no-op. Switch the body to \`Effect.gen(function* () { yield* sql.unsafe(...) })\` form.`).pipe(S.annotateLogs({ scope: `migrations:file:${t.migration.id}` })));
3208
+ let l = yield* W(e, a);
3189
3209
  return yield* e`
3190
3210
  INSERT INTO ${e("_voltro_migration_plans")}
3191
3211
  (${e("id")}, ${e("fingerprint")}, ${e("operations")},
@@ -3198,94 +3218,94 @@ BEGIN
3198
3218
  }])},
3199
3219
  ${r}, ${n}, ${"file"},
3200
3220
  ${c}, ${l}, ${t.migration.description})
3201
- `.pipe(x.mapError((e) => new ia(t.migration.id, t.file, e))), { durationMs: c };
3202
- }), oa = (e, t) => x.gen(function* () {
3203
- let n = yield* x.tryPromise({
3204
- try: () => ta(re(t, "migrations")),
3221
+ `.pipe(S.mapError((e) => new oa(t.migration.id, t.file, e))), { durationMs: c };
3222
+ }), ca = (e, t) => S.gen(function* () {
3223
+ let n = yield* S.tryPromise({
3224
+ try: () => ra(te(t, "migrations")),
3205
3225
  catch: (e) => e
3206
3226
  });
3207
3227
  if (n.length === 0) return {
3208
3228
  pending: [],
3209
3229
  skipped: []
3210
3230
  };
3211
- let r = yield* x.tryPromise({
3212
- try: () => na(n),
3231
+ let r = yield* S.tryPromise({
3232
+ try: () => ia(n),
3213
3233
  catch: (e) => e
3214
3234
  });
3215
3235
  if (r.length === 0) return {
3216
3236
  pending: [],
3217
3237
  skipped: []
3218
3238
  };
3219
- let i = new Set(yield* ra(e));
3239
+ let i = new Set(yield* aa(e));
3220
3240
  return {
3221
3241
  pending: r.filter((e) => !i.has(e.migration.id)),
3222
3242
  skipped: r.filter((e) => i.has(e.migration.id)).map((e) => e.migration.id)
3223
3243
  };
3224
- }), sa = (e, t) => oa(e, t).pipe(x.map((e) => e.pending.map((e) => e.migration.id))), ca = (e, t) => x.gen(function* () {
3225
- let { pending: n, skipped: r } = yield* oa(e, t.projectRoot);
3244
+ }), la = (e, t) => ca(e, t).pipe(S.map((e) => e.pending.map((e) => e.migration.id))), ua = (e, t) => S.gen(function* () {
3245
+ let { pending: n, skipped: r } = yield* ca(e, t.projectRoot);
3226
3246
  if (n.length === 0) return {
3227
3247
  applied: [],
3228
3248
  skipped: r
3229
3249
  };
3230
- yield* T(e, { schema: t.lockSchema });
3250
+ yield* je(e, { schema: t.lockSchema });
3231
3251
  let i = [];
3232
3252
  try {
3233
3253
  for (let r of n) {
3234
- yield* x.logInfo("file-based migration applying").pipe(x.annotateLogs({
3254
+ yield* S.logInfo("file-based migration applying").pipe(S.annotateLogs({
3235
3255
  scope: "voltro:migrate",
3236
3256
  id: r.migration.id,
3237
3257
  file: r.file
3238
3258
  }));
3239
- let { durationMs: n } = yield* aa(e, r, t.env, t.appliedBy);
3259
+ let { durationMs: n } = yield* sa(e, r, t.env, t.appliedBy);
3240
3260
  i.push({
3241
3261
  id: r.migration.id,
3242
3262
  durationMs: n
3243
- }), yield* x.logInfo("file-based migration applied").pipe(x.annotateLogs({
3263
+ }), yield* S.logInfo("file-based migration applied").pipe(S.annotateLogs({
3244
3264
  scope: "voltro:migrate",
3245
3265
  id: r.migration.id,
3246
3266
  durationMs: n
3247
3267
  }));
3248
3268
  }
3249
3269
  } finally {
3250
- yield* E(e, { schema: t.lockSchema }).pipe(x.orDie);
3270
+ yield* O(e, { schema: t.lockSchema }).pipe(S.orDie);
3251
3271
  }
3252
3272
  return {
3253
3273
  applied: i,
3254
3274
  skipped: r
3255
3275
  };
3256
- }), la = (e, t) => e`
3276
+ }), da = (e, t) => e`
3257
3277
  SELECT ${e("id")}
3258
3278
  FROM ${e("_voltro_migration_plans")}
3259
3279
  WHERE ${e("id")} = ${t} AND ${e("source")} = 'file'
3260
3280
  LIMIT 1
3261
- `, ua = (e, t) => x.gen(function* () {
3262
- if (!(yield* la(e, t.id))[0]) return yield* x.fail(/* @__PURE__ */ Error(`rollback: ${t.id} not found in _voltro_migration_plans (file source)`));
3263
- let n = yield* x.tryPromise({
3264
- try: () => ta(re(t.projectRoot, "migrations")),
3281
+ `, fa = (e, t) => S.gen(function* () {
3282
+ if (!(yield* da(e, t.id))[0]) return yield* S.fail(/* @__PURE__ */ Error(`rollback: ${t.id} not found in _voltro_migration_plans (file source)`));
3283
+ let n = yield* S.tryPromise({
3284
+ try: () => ra(te(t.projectRoot, "migrations")),
3265
3285
  catch: (e) => e
3266
- }), r = (yield* x.tryPromise({
3267
- try: () => na(n),
3286
+ }), r = (yield* S.tryPromise({
3287
+ try: () => ia(n),
3268
3288
  catch: (e) => e
3269
3289
  })).find((e) => e.migration.id === t.id);
3270
- if (!r) return yield* x.fail(/* @__PURE__ */ Error(`rollback: file for migration ${t.id} not found on disk under ${t.projectRoot}/migrations/`));
3271
- yield* T(e, { schema: t.lockSchema });
3290
+ if (!r) return yield* S.fail(/* @__PURE__ */ Error(`rollback: file for migration ${t.id} not found on disk under ${t.projectRoot}/migrations/`));
3291
+ yield* je(e, { schema: t.lockSchema });
3272
3292
  let i = Date.now();
3273
3293
  try {
3274
3294
  let n = {
3275
3295
  sql: e,
3276
3296
  log: {
3277
- info: (e, n) => x.logInfo(e).pipe(x.annotateLogs({
3297
+ info: (e, n) => S.logInfo(e).pipe(S.annotateLogs({
3278
3298
  scope: `migrations:file:${t.id}`,
3279
3299
  ...n ?? {}
3280
3300
  })),
3281
- warn: (e, n) => x.logWarning(e).pipe(x.annotateLogs({
3301
+ warn: (e, n) => S.logWarning(e).pipe(S.annotateLogs({
3282
3302
  scope: `migrations:file:${t.id}`,
3283
3303
  ...n ?? {}
3284
3304
  }))
3285
3305
  },
3286
3306
  appliedAt: (/* @__PURE__ */ new Date()).toISOString()
3287
3307
  }, a = r.migration.down(n);
3288
- x.isEffect(a) ? yield* a : yield* x.tryPromise({
3308
+ S.isEffect(a) ? yield* a : yield* S.tryPromise({
3289
3309
  try: () => a,
3290
3310
  catch: (e) => e
3291
3311
  });
@@ -3295,19 +3315,19 @@ BEGIN
3295
3315
  durationMs: o
3296
3316
  };
3297
3317
  } finally {
3298
- yield* E(e, { schema: t.lockSchema }).pipe(x.orDie);
3318
+ yield* O(e, { schema: t.lockSchema }).pipe(S.orDie);
3299
3319
  }
3300
- }), da = (e) => x.gen(function* () {
3301
- let t = yield* C.SqlClient, n = yield* t`
3320
+ }), pa = (e) => S.gen(function* () {
3321
+ let t = yield* E.SqlClient, n = yield* t`
3302
3322
  SELECT id, fingerprint, appliedAt FROM _voltro_migration_plans
3303
3323
  WHERE source = 'auto-diff'
3304
3324
  AND squashedAt IS NULL
3305
3325
  AND appliedAt < ${e.before}
3306
3326
  ORDER BY appliedAt DESC
3307
3327
  `;
3308
- if (n.length === 0) return yield* x.fail(/* @__PURE__ */ Error(`squash: no rows applied before ${e.before}`));
3328
+ if (n.length === 0) return yield* S.fail(/* @__PURE__ */ Error(`squash: no rows applied before ${e.before}`));
3309
3329
  let r = n[0];
3310
- if (r.fingerprint !== e.fingerprint) return yield* x.fail(/* @__PURE__ */ Error(`squash: latest pre-squash fingerprint (${r.fingerprint.slice(0, 12)}…) differs from current declared-schema fingerprint (${e.fingerprint.slice(0, 12)}…). This means the working tree carries un-applied changes — squashing now would lock the drift in.\n\nFix: run \`voltro db apply\` first to align the live schema with the working tree, then re-squash.`));
3330
+ if (r.fingerprint !== e.fingerprint) return yield* S.fail(/* @__PURE__ */ Error(`squash: latest pre-squash fingerprint (${r.fingerprint.slice(0, 12)}…) differs from current declared-schema fingerprint (${e.fingerprint.slice(0, 12)}…). This means the working tree carries un-applied changes — squashing now would lock the drift in.\n\nFix: run \`voltro db apply\` first to align the live schema with the working tree, then re-squash.`));
3311
3331
  yield* t`
3312
3332
  UPDATE _voltro_migration_plans
3313
3333
  SET squashedAt = CURRENT_TIMESTAMP
@@ -3342,7 +3362,7 @@ BEGIN
3342
3362
  snapshotFingerprint: e.fingerprint,
3343
3363
  snapshotId: i
3344
3364
  };
3345
- }), fa = { safe: !0 }, pa = (e) => {
3365
+ }), ma = { safe: !0 }, ha = (e) => {
3346
3366
  switch (e.kind) {
3347
3367
  case "drop-column": return {
3348
3368
  safe: !1,
@@ -3369,7 +3389,7 @@ BEGIN
3369
3389
  reason: `old instances read/write "${e.table}"."${e.column}" as ${e.from}; the new ${e.to} type can reject their writes or fail to decode their reads`,
3370
3390
  remedy: "add a new column of the target type + backfill + dual-write, cut code over, then drop the old column in a LATER deploy"
3371
3391
  };
3372
- case "alter-column-nullability": return e.toNullable ? fa : {
3392
+ case "alter-column-nullability": return e.toNullable ? ma : {
3373
3393
  safe: !1,
3374
3394
  reason: `old instances may INSERT "${e.table}" without (or with NULL in) "${e.column}", which the new NOT NULL rejects`,
3375
3395
  remedy: `make code always write "${e.column}" and deploy that first; add NOT NULL in a LATER deploy (with a default to cover the gap)`
@@ -3399,12 +3419,12 @@ BEGIN
3399
3419
  case "drop-unique":
3400
3420
  case "drop-unique-composite":
3401
3421
  case "drop-foreign-key":
3402
- case "drop-check": return fa;
3422
+ case "drop-check": return ma;
3403
3423
  }
3404
- }, ma = (e) => {
3424
+ }, ga = (e) => {
3405
3425
  let t = [];
3406
3426
  for (let n of e) {
3407
- let e = pa(n.op);
3427
+ let e = ha(n.op);
3408
3428
  e.safe || t.push({
3409
3429
  op: n,
3410
3430
  reason: e.reason,
@@ -3412,7 +3432,7 @@ BEGIN
3412
3432
  });
3413
3433
  }
3414
3434
  return t;
3415
- }, ha = (e) => {
3435
+ }, _a = (e) => {
3416
3436
  if (!e.enabled || e.unsafeCount === 0) return {
3417
3437
  refuse: !1,
3418
3438
  warnForced: !1,
@@ -3428,18 +3448,18 @@ BEGIN
3428
3448
  warnForced: !1,
3429
3449
  message: `${t}. Old instances would break against the new schema mid-rollout. Split into expand → deploy → contract (see the ⚠ list above), deploy with no overlap (maintenance window / scale-to-zero), or pass --force to override.`
3430
3450
  };
3431
- }, ga = (e) => {
3451
+ }, va = (e) => {
3432
3452
  let t = e.table;
3433
3453
  if (typeof t == "string") return t;
3434
3454
  let n = e.from;
3435
3455
  return typeof n == "string" ? n : void 0;
3436
- }, _a = (e) => ({
3456
+ }, ya = (e) => ({
3437
3457
  kind: e.op.kind,
3438
- table: ga(e.op),
3458
+ table: va(e.op),
3439
3459
  classification: e.classification,
3440
3460
  reason: e.reason,
3441
3461
  blockedFix: e.blocked?.fix
3442
- }), va = (e) => e.operations.map(_a), ya = async (e) => {
3462
+ }), ba = (e) => e.operations.map(ya), xa = async (e) => {
3443
3463
  let t = e.log ?? (() => {}), n = {
3444
3464
  branchId: e.branchId,
3445
3465
  mechanism: e.mechanism,
@@ -3458,10 +3478,10 @@ BEGIN
3458
3478
  applied: !1,
3459
3479
  converged: !1,
3460
3480
  residual: r,
3461
- infidelity: va(o)
3481
+ infidelity: ba(o)
3462
3482
  };
3463
3483
  else {
3464
- let i = await e.plan(), o = va(i), s = o.filter((e) => e.classification === "lossy"), c = Yi(i), l = c.operations.filter((e) => e.blocked !== void 0).map(_a);
3484
+ let i = await e.plan(), o = ba(i), s = o.filter((e) => e.classification === "lossy"), c = Zi(i), l = c.operations.filter((e) => e.blocked !== void 0).map(ya);
3465
3485
  if (l.length > 0) a = {
3466
3486
  ...n,
3467
3487
  outcome: "blocked",
@@ -3486,7 +3506,7 @@ BEGIN
3486
3506
  };
3487
3507
  else {
3488
3508
  await e.apply(c), t(`branch ${e.branchId}: applied ${o.length} operation(s)`);
3489
- let i = va(await e.replan());
3509
+ let i = ba(await e.replan());
3490
3510
  a = {
3491
3511
  ...n,
3492
3512
  outcome: i.length > 0 ? "diverged" : s.length > 0 ? "lossy" : "clean",
@@ -3524,7 +3544,7 @@ BEGIN
3524
3544
  ...a,
3525
3545
  tornDown: o
3526
3546
  };
3527
- }, ba = (e) => {
3547
+ }, Sa = (e) => {
3528
3548
  switch (e.outcome) {
3529
3549
  case "clean": return 0;
3530
3550
  case "lossy": return 2;
@@ -3533,22 +3553,22 @@ BEGIN
3533
3553
  case "infidelity": return 1;
3534
3554
  case "failed": return 1;
3535
3555
  }
3536
- }, xa = (e) => ` ${e.classification === "lossy" ? "✗" : "•"} ${e.kind}${e.table ? ` ${e.table}` : ""} [${e.classification}]${e.reason ? ` — ${e.reason}` : ""}${e.blockedFix ? `\n ! ${e.blockedFix}` : ""}`, Sa = (e) => {
3556
+ }, Ca = (e) => ` ${e.classification === "lossy" ? "✗" : "•"} ${e.kind}${e.table ? ` ${e.table}` : ""} [${e.classification}]${e.reason ? ` — ${e.reason}` : ""}${e.blockedFix ? `\n ! ${e.blockedFix}` : ""}`, wa = (e) => {
3537
3557
  let t = [];
3538
3558
  if (t.push(`branch rehearsal · ${e.branchId} · mechanism ${e.mechanism}`), t.push(` branched ${e.branchedTables} table(s), replayed ${e.replayedForeignKeys} foreign key(s)`), e.outcome === "failed") t.push(` FAILED: ${e.error ?? "unknown error"}`);
3539
3559
  else if (e.outcome === "infidelity") {
3540
3560
  t.push(" BRANCH IS NOT A FAITHFUL COPY of the parent — the rehearsal proves nothing about your migration."), t.push(" The parent's own schema still differs from the branch by:");
3541
- for (let n of e.infidelity) t.push(xa(n));
3561
+ for (let n of e.infidelity) t.push(Ca(n));
3542
3562
  } else {
3543
3563
  t.push(` plan: ${e.operations.length} operation(s), ${e.lossy.length} lossy, ${e.blocked.length} refused`);
3544
- for (let n of e.operations) t.push(xa(n));
3545
- if (e.lossy.length > 0 && (t.push(""), t.push(` ⚠ ${e.lossy.length} operation(s) DESTROY DATA. They were executed on the branch (it is`), t.push(" disposable) so they are rehearsed, but production refuses them until you set"), t.push(" VOLTRO_DESTRUCTIVE_OK — naming the tables, not `1`.")), e.blocked.length > 0 && (t.push(""), t.push(` ${e.blocked.length} operation(s) the planner will not auto-apply anywhere — the plan was NOT executed.`)), e.applied && (t.push(""), t.push(e.converged ? " ✓ applied on the branch, and the re-plan is EMPTY (the migration converges)." : ` ✗ applied, but the re-plan STILL proposes ${e.residual.length} operation(s) — this migration does not converge:`), !e.converged)) for (let n of e.residual) t.push(xa(n));
3564
+ for (let n of e.operations) t.push(Ca(n));
3565
+ if (e.lossy.length > 0 && (t.push(""), t.push(` ⚠ ${e.lossy.length} operation(s) DESTROY DATA. They were executed on the branch (it is`), t.push(" disposable) so they are rehearsed, but production refuses them until you set"), t.push(" VOLTRO_DESTRUCTIVE_OK — naming the tables, not `1`.")), e.blocked.length > 0 && (t.push(""), t.push(` ${e.blocked.length} operation(s) the planner will not auto-apply anywhere — the plan was NOT executed.`)), e.applied && (t.push(""), t.push(e.converged ? " ✓ applied on the branch, and the re-plan is EMPTY (the migration converges)." : ` ✗ applied, but the re-plan STILL proposes ${e.residual.length} operation(s) — this migration does not converge:`), !e.converged)) for (let n of e.residual) t.push(Ca(n));
3546
3566
  }
3547
3567
  return t.push(e.tornDown ? ` branch ${e.branchId} torn down.` : ` branch ${e.branchId} KEPT — drop it when you are done.`), t.join("\n");
3548
- }, Ca = (e, ...t) => ({
3568
+ }, Ta = (e, ...t) => ({
3549
3569
  _tag: "RawSqlFragment",
3550
3570
  strings: [...e],
3551
3571
  values: [...t]
3552
- }), wa = (e) => typeof e == "object" && !!e && e._tag === "RawSqlFragment";
3572
+ }), Ea = (e) => typeof e == "object" && !!e && e._tag === "RawSqlFragment";
3553
3573
  //#endregion
3554
- export { O as DEFAULT_CDC_CHANNEL, f as FILE_MIGRATION_PATTERN, ia as FileMigrationLedgerError, Je as REACTIVE_TRIGGER_PREFIX, pe as VOLTRO_MIGRATION_LOCK_KEY, T as acquireMigrationLock, U as appliedAtValue, Lt as applyNamespacedSchema, Ri as applyPlan, Dt as applySchema, ha as assessRollingDeployGate, ba as branchRehearsalExitCode, Vn as chunkTables, pa as classifyRollingDeploySafety, F as declaredSnapshot, et as defaultArrayClause, $e as defaultClause, j as defaultJsonClause, $i as describeOutcome, qi as destructiveScope, Xt as detectReactiveTriggerDrift, ti as emitAddIndexMysql, Ir as emitCreateTableMysql, _r as emitDropColumnDdl, vr as emitDropColumnDdlMysql, Et as emitFrameworkBootstrapSql, wt as emitNamespaceProvisionDdl, Tt as emitNamespacedSchemaSql, Ct as emitSchemaSql, er as engineFromVersion, P as fingerprintSchema, ye as fnv1a64, Sa as formatBranchRehearsal, Zt as formatReactiveTriggerDrift, Ki as ignoreTablesFromEnv, $n as introspectSchema, ar as isAlreadySatisfied, l as isFileMigration, wa as isRawSqlFragment, kt as isReRunSafeDdl, Fn as mapPgType, _ as migration, be as migrationLockKeyForSchema, xe as migrationLockNameForSchema, Zr as mysqlIndexPrefixFor, Xe as notifyFunctionName, M as numericIdSql, Pn as parseEnumCheck, sa as pendingFileMigrationIds, Nn as planMigrations, Rt as provisionTenantNamespace, Ye as reactiveTriggerName, mt as reactiveTriggerRepairSql, Vi as recordUpToDate, ya as rehearseMigrationOnBranch, _a as rehearsedOperation, E as releaseMigrationLock, Pr as renderColumnMysql, kr as renderColumnPg, he as resolveMigrationLockSchema, H as resolveMysqlEngine, ua as rollbackFileBasedMigration, ma as rollingDeployUnsafeOps, ca as runFileBasedMigrations, zt as runFrameworkBootstrap, It as runMigrate, Qi as runPlannedMigrations, Gt as shortFingerprint, Kt as snapshotColumn, Ca as sql, A as sqlType, da as squashMigrationPlans, Yi as unblockLossy, Ne as withMigrationLock };
3574
+ export { A as DEFAULT_CDC_CHANNEL, m as FILE_MIGRATION_PATTERN, oa as FileMigrationLedgerError, qe as REACTIVE_TRIGGER_PREFIX, de as VOLTRO_MIGRATION_LOCK_KEY, je as acquireMigrationLock, W as appliedAtValue, It as applyNamespacedSchema, Bi as applyPlan, Et as applySchema, _a as assessRollingDeployGate, Sa as branchRehearsalExitCode, Vn as chunkTables, ha as classifyRollingDeploySafety, I as declaredSnapshot, $e as defaultArrayClause, Qe as defaultClause, N as defaultJsonClause, ta as describeOutcome, Yi as destructiveScope, Xt as detectReactiveTriggerDrift, ni as emitAddIndexMysql, Lr as emitCreateTableMysql, _r as emitDropColumnDdl, vr as emitDropColumnDdlMysql, Tt as emitFrameworkBootstrapSql, Ct as emitNamespaceProvisionDdl, wt as emitNamespacedSchemaSql, St as emitSchemaSql, er as engineFromVersion, Wt as fingerprintSchema, _e as fnv1a64, wa as formatBranchRehearsal, Zt as formatReactiveTriggerDrift, Ji as ignoreTablesFromEnv, $n as introspectSchema, ar as isAlreadySatisfied, g as isFileMigration, Ea as isRawSqlFragment, Ot as isReRunSafeDdl, Fn as mapPgType, o as migration, ve as migrationLockKeyForSchema, ye as migrationLockNameForSchema, Qr as mysqlIndexPrefixFor, Ye as notifyFunctionName, P as numericIdSql, Pn as parseEnumCheck, la as pendingFileMigrationIds, Nn as planMigrations, Lt as provisionTenantNamespace, Je as reactiveTriggerName, pt as reactiveTriggerRepairSql, Ui as recordUpToDate, xa as rehearseMigrationOnBranch, ya as rehearsedOperation, O as releaseMigrationLock, Fr as renderColumnMysql, Ar as renderColumnPg, pe as resolveMigrationLockSchema, U as resolveMysqlEngine, fa as rollbackFileBasedMigration, ga as rollingDeployUnsafeOps, ua as runFileBasedMigrations, Rt as runFrameworkBootstrap, Ft as runMigrate, ea as runPlannedMigrations, Gt as shortFingerprint, Kt as snapshotColumn, Ta as sql, M as sqlType, pa as squashMigrationPlans, Zi as unblockLossy, Me as withMigrationLock };