@voltro/database 0.6.0 → 0.8.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/index.js CHANGED
@@ -1,14 +1,15 @@
1
- import { $ as e, A as t, At as n, B as r, C as i, Ct as a, D as o, Dt as s, E as c, Et as l, F as u, G as d, H as f, I as p, J as m, K as h, L as g, M as ee, N as te, O as _, Ot as v, P as y, Q as b, R as ne, S as x, St as S, T as re, Tt as ie, U as ae, V as C, W as oe, X as se, Y as ce, Z as le, _ as ue, _t as de, a as fe, at as pe, b as me, bt as w, c as he, ct as ge, d as _e, dt as ve, et as ye, f as be, ft as xe, g as Se, gt as Ce, h as we, ht as Te, i as T, it as Ee, j as De, k as Oe, kt as E, l as ke, lt as Ae, m as je, mt as Me, n as Ne, nt as Pe, o as Fe, ot as Ie, p as Le, pt as Re, q as ze, r as Be, rt as Ve, s as He, st as Ue, t as We, tt as Ge, u as Ke, ut as qe, v as Je, vt as Ye, w as Xe, wt as Ze, x as Qe, xt as $e, y as et, yt as D, z as tt } from "./fileBased-Cc-F1oFv.js";
2
- import { Chunk as nt, Data as rt, Effect as it, Option as O, Schema as k, Stream as at } from "effect";
3
- import { ansi as A } from "@voltro/logger";
1
+ import { $ as e, A as t, At as n, B as r, C as i, Ct as a, D as o, Dt as s, E as c, Et as l, F as u, G as d, H as f, I as p, J as m, K as h, L as g, M as ee, N as _, O as v, Ot as y, P as b, Q as x, R as te, S, St as C, T as ne, Tt as re, U as ie, V as w, W as ae, X as oe, Y as se, Z as ce, _ as le, _t as ue, a as de, at as fe, b as pe, bt as T, c as me, ct as he, d as ge, dt as _e, et as ve, f as ye, ft as be, g as xe, gt as Se, h as Ce, ht as we, i as E, it as Te, j as Ee, k as De, kt as D, l as Oe, lt as ke, m as Ae, mt as je, n as Me, nt as Ne, o as Pe, ot as Fe, p as Ie, pt as Le, q as Re, r as ze, rt as Be, s as Ve, st as He, t as Ue, tt as We, u as Ge, ut as Ke, v as qe, vt as Je, w as Ye, wt as Xe, x as Ze, xt as Qe, y as $e, yt as O, z as et } from "./fileBased-Cc-F1oFv.js";
2
+ import { timestampMs as tt, timestampMsOrNull as nt } from "./wire.js";
3
+ import { Chunk as rt, Data as it, Effect as at, Option as k, Schema as A, Stream as ot } from "effect";
4
+ import { ansi as j } from "@voltro/logger";
4
5
  //#region src/arrayCodec.ts
5
- var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", st = (e) => {
6
+ var st = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", ct = (e) => {
6
7
  let t = [];
7
8
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
8
9
  return t;
9
- }, ct = (e, t, n) => {
10
- if (!ot(n) || !t) return e;
11
- let r = st(t);
10
+ }, lt = (e, t, n) => {
11
+ if (!st(n) || !t) return e;
12
+ let r = ct(t);
12
13
  if (r.length === 0) return e;
13
14
  let i = { ...e };
14
15
  for (let e of r) {
@@ -16,9 +17,9 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
16
17
  Array.isArray(t) && (i[e] = JSON.stringify(t));
17
18
  }
18
19
  return i;
19
- }, lt = (e, t, n) => {
20
- if (!ot(n) || !t) return e;
21
- let r = st(t);
20
+ }, ut = (e, t, n) => {
21
+ if (!st(n) || !t) return e;
22
+ let r = ct(t);
22
23
  return r.length === 0 ? e : e.map((e) => {
23
24
  let t;
24
25
  for (let n of r) {
@@ -30,86 +31,86 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
30
31
  }
31
32
  return t ?? e;
32
33
  });
33
- }, ut = "enc:v1:", dt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), ft = (e) => {
34
+ }, dt = "enc:v1:", ft = (e) => typeof e == "string" && e.startsWith("enc:v1:"), pt = (e) => {
34
35
  let t = [];
35
36
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
36
37
  return t;
37
- }, pt = (e, t, n) => {
38
+ }, mt = (e, t, n) => {
38
39
  if (!t) return e;
39
- let r = ft(t);
40
+ let r = pt(t);
40
41
  if (r.length === 0) return e;
41
42
  let i = { ...e };
42
43
  for (let e of r) {
43
44
  let r = i[e];
44
- if (!(r == null || dt(r))) {
45
+ if (!(r == null || ft(r))) {
45
46
  if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
46
47
  i[e] = n.encrypt(JSON.stringify(r));
47
48
  }
48
49
  }
49
50
  return i;
50
- }, mt = (e, t, n) => {
51
+ }, ht = (e, t, n) => {
51
52
  if (!t) return e;
52
- let r = ft(t);
53
+ let r = pt(t);
53
54
  return r.length === 0 || !n ? e : e.map((e) => {
54
55
  let t;
55
56
  for (let i of r) {
56
57
  let r = e[i];
57
- dt(r) && (t ??= { ...e }, t[i] = JSON.parse(n.decrypt(r)));
58
+ ft(r) && (t ??= { ...e }, t[i] = JSON.parse(n.decrypt(r)));
58
59
  }
59
60
  return t ?? e;
60
61
  });
61
- }, ht = (e) => {
62
+ }, gt = (e) => {
62
63
  let t = (() => {
63
64
  switch (e.type) {
64
65
  case "id":
65
66
  case "reference":
66
67
  case "text":
67
- case "enum": return k.String;
68
+ case "enum": return A.String;
68
69
  case "integer":
69
70
  case "real":
70
- case "decimal": return k.Number;
71
- case "boolean": return k.Boolean;
71
+ case "decimal": return A.Number;
72
+ case "boolean": return A.Boolean;
72
73
  case "timestamp":
73
- case "date": return k.DateFromNumber;
74
- case "bigint": return k.BigInt;
75
- case "bytes": return k.Uint8ArrayFromSelf;
76
- case "array": return k.Array(k.Unknown);
77
- case "interval": return k.String;
78
- default: return k.Unknown;
74
+ case "date": return tt;
75
+ case "bigint": return A.BigInt;
76
+ case "bytes": return A.Uint8ArrayFromSelf;
77
+ case "array": return A.Array(A.Unknown);
78
+ case "interval": return A.String;
79
+ default: return A.Unknown;
79
80
  }
80
81
  })();
81
- return e.nullable === !0 ? k.NullOr(t) : t;
82
- }, gt = (e, t) => {
82
+ return e.nullable === !0 ? A.NullOr(t) : t;
83
+ }, _t = (e, t) => {
83
84
  let n = new Set(t?.omit ?? []), r = {};
84
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = ht(i));
85
- return k.Struct(r);
86
- }, _t = (e) => typeof e == "function" ? e : () => e, vt = (e, t) => ({
85
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = gt(i));
86
+ return A.Struct(r);
87
+ }, vt = (e) => typeof e == "function" ? e : () => e, yt = (e, t) => ({
87
88
  kind: "one",
88
- target: _t(e),
89
+ target: vt(e),
89
90
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
90
91
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
91
- }), yt = (e, t) => ({
92
+ }), bt = (e, t) => ({
92
93
  kind: "many",
93
- target: _t(e),
94
+ target: vt(e),
94
95
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
95
96
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
96
- }), bt = (e, t) => ({
97
+ }), xt = (e, t) => ({
97
98
  kind: "manyToMany",
98
- target: _t(e),
99
- through: _t(t.through),
99
+ target: vt(e),
100
+ through: vt(t.through),
100
101
  sourceKey: t.sourceKey,
101
102
  targetKey: t.targetKey
102
- }), xt = {
103
- one: vt,
104
- many: yt,
105
- manyToMany: bt
106
- }, St = (e, t) => {
103
+ }), St = {
104
+ one: yt,
105
+ many: bt,
106
+ manyToMany: xt
107
+ }, Ct = (e, t) => {
107
108
  let n = typeof e == "function" ? e : () => e;
108
109
  return {
109
110
  source: n,
110
- relations: t(xt, n())
111
+ relations: t(St, n())
111
112
  };
112
- }, Ct = (e) => {
113
+ }, wt = (e) => {
113
114
  if (typeof e != "object" || !e) return !1;
114
115
  let t = e;
115
116
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -118,63 +119,63 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
118
119
  let t = e?.kind;
119
120
  return t === "one" || t === "many" || t === "manyToMany";
120
121
  });
121
- }, wt = vt, Tt = yt, Et = bt, j = (e, t, n) => {
122
+ }, Tt = yt, Et = bt, Dt = xt, M = (e, t, n) => {
122
123
  let r = [];
123
124
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
124
125
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
125
126
  if (r.length > 1) throw Error(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
126
127
  return r[0];
127
- }, Dt = (e) => Object.keys(e.fields), M = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Ot = (e) => {
128
- let t = Dt(e);
128
+ }, Ot = (e) => Object.keys(e.fields), N = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), kt = (e) => {
129
+ let t = Ot(e);
129
130
  return t.length === 0 ? "<none>" : t.join(", ");
130
- }, kt = (e, t, n) => {
131
+ }, At = (e, t, n) => {
131
132
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
132
133
  if (n.kind === "manyToMany") {
133
134
  let t = n.through();
134
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!M(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${Ot(t)}.`);
135
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!N(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${kt(t)}.`);
135
136
  return;
136
137
  }
137
138
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw Error(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
138
- if (n.sourceKey !== void 0 && !M(e, n.sourceKey)) {
139
- let t = M(i, n.sourceKey);
140
- throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${Ot(e)}.`));
139
+ if (n.sourceKey !== void 0 && !N(e, n.sourceKey)) {
140
+ let t = N(i, n.sourceKey);
141
+ throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${kt(e)}.`));
141
142
  }
142
- if (n.foreignKey !== void 0 && !M(i, n.foreignKey)) {
143
- let t = M(e, n.foreignKey);
144
- throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${Ot(i)}.`));
143
+ if (n.foreignKey !== void 0 && !N(i, n.foreignKey)) {
144
+ let t = N(e, n.foreignKey);
145
+ throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${kt(i)}.`));
145
146
  }
146
- }, At = Symbol.for("@voltro/database/relationsRegistry"), jt = globalThis, N = jt[At] ?? (jt[At] = /* @__PURE__ */ new Map()), Mt = (e) => {
147
- let t = e.source(), n = N.get(t.tableName);
147
+ }, jt = Symbol.for("@voltro/database/relationsRegistry"), Mt = globalThis, P = Mt[jt] ?? (Mt[jt] = /* @__PURE__ */ new Map()), Nt = (e) => {
148
+ let t = e.source(), n = P.get(t.tableName);
148
149
  if (n === void 0) {
149
- N.set(t.tableName, new Map(Object.entries(e.relations)));
150
+ P.set(t.tableName, new Map(Object.entries(e.relations)));
150
151
  return;
151
152
  }
152
153
  for (let [r, i] of Object.entries(e.relations)) {
153
154
  if (n.has(r)) throw Error(`duplicate relation '${r}' on '${t.tableName}': two relations() blocks both declare it. Pick distinct names or merge them into one block.`);
154
155
  n.set(r, i);
155
156
  }
156
- }, Nt = (e) => {
157
+ }, Pt = (e) => {
157
158
  let t = 0;
158
- for (let n of Object.values(e)) Ct(n) && (Mt(n), t += 1);
159
+ for (let n of Object.values(e)) wt(n) && (Nt(n), t += 1);
159
160
  return t;
160
- }, Pt = (e) => {
161
- let t = N.get(e);
161
+ }, F = (e) => {
162
+ let t = P.get(e);
162
163
  if (t !== void 0) return Object.fromEntries(t);
163
- }, Ft = (e, t) => N.get(e)?.get(t), It = () => {
164
+ }, Ft = (e, t) => P.get(e)?.get(t), It = () => {
164
165
  let e = [];
165
- for (let [t, n] of N) for (let [r, i] of n) e.push({
166
+ for (let [t, n] of P) for (let [r, i] of n) e.push({
166
167
  source: t,
167
168
  name: r,
168
169
  relation: i
169
170
  });
170
171
  return e;
171
172
  }, Lt = () => {
172
- for (let [e, t] of N) {
173
+ for (let [e, t] of P) {
173
174
  let n = u(e);
174
- if (n !== void 0) for (let [e, r] of t) kt(n, e, r);
175
+ if (n !== void 0) for (let [e, r] of t) At(n, e, r);
175
176
  }
176
177
  }, Rt = () => {
177
- N.clear();
178
+ P.clear();
178
179
  }, zt = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, Bt = (e) => {
179
180
  if (e == null || typeof e != "string") return e;
180
181
  let t = e.trim();
@@ -249,7 +250,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
249
250
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
250
251
  }, Yt = async (e, t, n, r) => {
251
252
  if (e.length === 0) return e;
252
- let i = Pt(n.tableName);
253
+ let i = F(n.tableName);
253
254
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
254
255
  let a = e.map((e) => ({ ...e }));
255
256
  for (let [e, o] of Object.entries(t)) {
@@ -258,7 +259,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
258
259
  let t = Object.keys(i).join(", ") || "<none>";
259
260
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
260
261
  }
261
- kt(n, e, t), await Xt(a, e, t, o === !0 ? {} : o, n, r);
262
+ At(n, e, t), await Xt(a, e, t, o === !0 ? {} : o, n, r);
262
263
  }
263
264
  return a;
264
265
  }, Xt = async (e, t, n, r, i, a) => {
@@ -276,7 +277,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
276
277
  }, Zt = async (e, t, n, r, i, a) => {
277
278
  let o = n.target(), s = n.sourceKey ?? tn(i, o.tableName);
278
279
  if (s !== void 0) {
279
- let n = P(e, s), i = n.length === 0 ? [] : await nn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
280
+ let n = I(e, s), i = n.length === 0 ? [] : await nn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
280
281
  for (let n of e) {
281
282
  let e = n[s];
282
283
  n[t] = e == null ? null : c.get(e) ?? null;
@@ -284,7 +285,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
284
285
  await rn(i, r.with, o, a);
285
286
  return;
286
287
  }
287
- let c = n.foreignKey ?? j(o, i.tableName, t), l = n.sourceKey ?? "id", u = P(e, l), d = u.length === 0 ? [] : await nn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
288
+ let c = n.foreignKey ?? M(o, i.tableName, t), l = n.sourceKey ?? "id", u = I(e, l), d = u.length === 0 ? [] : await nn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
288
289
  for (let e of d) {
289
290
  let n = e[c];
290
291
  if (f.has(n)) throw new qt(Jt({
@@ -302,7 +303,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
302
303
  }
303
304
  await rn(d, r.with, o, a);
304
305
  }, Qt = async (e, t, n, r, i, a) => {
305
- let o = n.target(), s = n.foreignKey ?? j(o, i.tableName, t), c = n.sourceKey ?? "id", l = P(e, c), u = $t(r), d = l.length === 0 ? [] : await nn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
306
+ let o = n.target(), s = n.foreignKey ?? M(o, i.tableName, t), c = n.sourceKey ?? "id", l = I(e, c), u = $t(r), d = l.length === 0 ? [] : await nn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
306
307
  for (let e of d) {
307
308
  let t = e[s], n = f.get(t);
308
309
  n ? n.push(e) : f.set(t, [e]);
@@ -323,7 +324,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
323
324
  let { limit: t, offset: n, ...r } = e;
324
325
  return r;
325
326
  }, en = async (e, t, n, r, i, a) => {
326
- let o = n.target(), s = n.through(), c = P(e, "id");
327
+ let o = n.target(), s = n.through(), c = I(e, "id");
327
328
  if (c.length === 0) {
328
329
  for (let n of e) n[t] = [];
329
330
  return;
@@ -344,7 +345,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
344
345
  for (let n of e) n[t] = [];
345
346
  return;
346
347
  }
347
- let f = await nn(o, "id", P(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
348
+ let f = await nn(o, "id", I(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
348
349
  await rn(f, r.with, o, a);
349
350
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
350
351
  for (let e of d) {
@@ -359,7 +360,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
359
360
  for (let n of e) n[t] = h.get(n.id) ?? [];
360
361
  }, tn = (e, t) => {
361
362
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
362
- }, P = (e, t) => {
363
+ }, I = (e, t) => {
363
364
  let n = /* @__PURE__ */ new Set();
364
365
  for (let r of e) {
365
366
  let e = r[t];
@@ -402,11 +403,11 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
402
403
  let n = `${ln}${t}`;
403
404
  if (n.length > cn) throw new sn(`namespace '${n}' for tenant '${e}' exceeds the ${cn}-byte identifier limit. Use a shorter tenant id.`);
404
405
  return n;
405
- }, F = (e, t) => e === null ? t : `${e}.${t}`, fn = (e, t) => {
406
+ }, fn = (e, t) => e === null ? t : `${e}.${t}`, pn = (e, t) => {
406
407
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
407
408
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
408
409
  return t`${i}`;
409
- }, I = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null) => {
410
+ }, mn = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null) => {
410
411
  if ("not" in e) return t`NOT (${L(e.not, t, n)})`;
411
412
  if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n)));
412
413
  if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n)));
@@ -419,15 +420,15 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
419
420
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
420
421
  }
421
422
  let r = e, i = t(r.column), a = r.path, o = a !== void 0 && a.length > 0, s = () => t.onDialectOrElse({
422
- mysql: () => t.unsafe(T(r.column, a, "mysql")),
423
- mssql: () => t.unsafe(T(r.column, a, "mssql")),
424
- sqlite: () => t.unsafe(T(r.column, a, "sqlite")),
425
- orElse: () => t.unsafe(T(r.column, a, "postgres"))
423
+ mysql: () => t.unsafe(E(r.column, a, "mysql")),
424
+ mssql: () => t.unsafe(E(r.column, a, "mssql")),
425
+ sqlite: () => t.unsafe(E(r.column, a, "sqlite")),
426
+ orElse: () => t.unsafe(E(r.column, a, "postgres"))
426
427
  }), c = () => t.onDialectOrElse({
427
- mysql: () => t.unsafe(T(r.column, a, "mysql", { numeric: !0 })),
428
- mssql: () => t.unsafe(T(r.column, a, "mssql", { numeric: !0 })),
429
- sqlite: () => t.unsafe(T(r.column, a, "sqlite", { numeric: !0 })),
430
- orElse: () => t.unsafe(T(r.column, a, "postgres", { numeric: !0 }))
428
+ mysql: () => t.unsafe(E(r.column, a, "mysql", { numeric: !0 })),
429
+ mssql: () => t.unsafe(E(r.column, a, "mssql", { numeric: !0 })),
430
+ sqlite: () => t.unsafe(E(r.column, a, "sqlite", { numeric: !0 })),
431
+ orElse: () => t.unsafe(E(r.column, a, "postgres", { numeric: !0 }))
431
432
  }), l = o ? s() : i, u = o ? c() : i, d = (e) => o && e != null ? String(e) : e, f = (e) => o ? Number(e) : e;
432
433
  switch (r.op) {
433
434
  case "eq": return t`${l} = ${d(r.value)}`;
@@ -445,7 +446,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
445
446
  return e.length === 0 ? t`TRUE` : t`${l} NOT IN ${t.in(o ? e.map((e) => d(e)) : e)}`;
446
447
  }
447
448
  case "contains": {
448
- let e = `%${I(typeof r.value == "string" ? r.value : String(r.value ?? ""))}%`;
449
+ let e = `%${mn(typeof r.value == "string" ? r.value : String(r.value ?? ""))}%`;
449
450
  return t.onDialectOrElse({
450
451
  mysql: () => t`LOWER(${l}) LIKE LOWER(${e})`,
451
452
  mssql: () => t`LOWER(${l}) LIKE LOWER(${e})`,
@@ -495,13 +496,13 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
495
496
  });
496
497
  }
497
498
  }
498
- }, pn = (e, t) => {
499
+ }, hn = (e, t) => {
499
500
  let n = [];
500
501
  return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.csv(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.csv(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
501
- }, mn = (e, t) => t.csv(e.map((e) => {
502
+ }, gn = (e, t) => t.csv(e.map((e) => {
502
503
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
503
504
  if (e.op.startsWith("window-")) {
504
- let r = pn(e.window ?? {}, t);
505
+ let r = hn(e.window ?? {}, t);
505
506
  switch (e.op) {
506
507
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
507
508
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -525,39 +526,39 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
525
526
  return t`${t(e.column)} AS ${t(e.alias)}`;
526
527
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
527
528
  }
528
- })), hn = (e) => `[${e.join(",")}]`, gn = (e, t) => {
529
+ })), _n = (e) => `[${e.join(",")}]`, vn = (e, t) => {
529
530
  if (e.queryVector === void 0) return null;
530
- let n = t(e.column), r = hn(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
531
+ let n = t(e.column), r = _n(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
531
532
  return t.onDialectOrElse({
532
533
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
533
534
  mssql: () => t`NULL`,
534
535
  sqlite: () => t`NULL`,
535
536
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
536
537
  });
537
- }, _n = (e, t) => {
538
+ }, yn = (e, t) => {
538
539
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
539
540
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
540
- }, vn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, yn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, bn = (e, t) => `${t}_${e.indexName}_fts`, xn = (e, t, n) => {
541
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${I(e.query)}%`;
541
+ }, bn = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, xn = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Sn = (e, t) => `${t}_${e.indexName}_fts`, Cn = (e, t, n) => {
542
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${mn(e.query)}%`;
542
543
  return n.onDialectOrElse({
543
544
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
544
545
  sqlite: () => {
545
- let r = n(bn(e, t));
546
+ let r = n(Sn(e, t));
546
547
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
547
548
  },
548
549
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
549
- orElse: () => n`${yn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
550
+ orElse: () => n`${xn(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
550
551
  });
551
- }, Sn = (e, t, n) => {
552
- let r = `%${I(e.query)}%`;
552
+ }, wn = (e, t, n) => {
553
+ let r = `%${mn(e.query)}%`;
553
554
  return n.onDialectOrElse({
554
555
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
555
556
  sqlite: () => {
556
- let r = n(bn(e, t));
557
+ let r = n(Sn(e, t));
557
558
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
558
559
  },
559
560
  mssql: () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`),
560
- orElse: () => n`ts_rank(${yn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
561
+ orElse: () => n`ts_rank(${xn(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
561
562
  });
562
563
  }, R = (e, t, n = null) => {
563
564
  if (e.setOp && e.setOp.queries.length >= 2) {
@@ -572,7 +573,7 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
572
573
  }
573
574
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
574
575
  }
575
- let r = e.annClause === void 0 ? null : gn(e.annClause, t);
576
+ let r = e.annClause === void 0 ? null : vn(e.annClause, t);
576
577
  e.spatialClause !== void 0 && t.onDialectOrElse({
577
578
  mysql: () => {
578
579
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -585,57 +586,57 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
585
586
  },
586
587
  orElse: () => t``
587
588
  });
588
- let i = e.spatialClause?.projectAs === void 0 ? null : _n(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? mn(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? Sn(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
589
+ let i = e.spatialClause?.projectAs === void 0 ? null : yn(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? gn(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? wn(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
589
590
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
590
591
  mysql: () => t`DISTINCT `,
591
592
  mssql: () => t`DISTINCT `,
592
593
  sqlite: () => t`DISTINCT `
593
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(F(n, e.table))}` : t`${t(F(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
594
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(fn(n, e.table))}` : t`${t(fn(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
594
595
  let r = e.kind === "inner" ? "INNER" : "LEFT";
595
- return t` ${t.unsafe(r)} JOIN ${t(F(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
596
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : xn(c, e.table, t), ee = [e.predicate ? L(e.predicate, t, n) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, v = e.having ? t` HAVING ${L(e.having, t, n)}` : t``, y = e.skip !== void 0, b = [];
597
- r !== null && b.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && b.push(e.spatialClause.order === "desc" ? t`${vn(e.spatialClause, t)} DESC` : t`${vn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && b.push(t`${l} DESC`);
598
- for (let n of e.order) b.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
599
- let ne = b.length > 0 ? t` ORDER BY ${t.csv(b)}` : y ? t.onDialectOrElse({
596
+ return t` ${t.unsafe(r)} JOIN ${t(fn(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
597
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Cn(c, e.table, t), ee = [e.predicate ? L(e.predicate, t, n) : null, g].filter((e) => e !== null), _ = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, v = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, y = e.having ? t` HAVING ${L(e.having, t, n)}` : t``, b = e.skip !== void 0, x = [];
598
+ r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${bn(e.spatialClause, t)} DESC` : t`${bn(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
599
+ for (let n of e.order) x.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
600
+ let te = x.length > 0 ? t` ORDER BY ${t.csv(x)}` : b ? t.onDialectOrElse({
600
601
  mssql: () => t` ORDER BY (SELECT NULL)`,
601
602
  orElse: () => t``
602
- }) : t``, x = (e) => {
603
+ }) : t``, S = (e) => {
603
604
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
604
605
  return t.unsafe(String(e));
605
- }, S = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${R(e.descriptor, t, n)})`), re = (e.ctes ?? []).some((e) => e.recursive === !0), ie = S.length > 0 ? t`WITH ${t.unsafe(re ? "RECURSIVE " : "")}${t.csv(S)} ` : t``;
606
+ }, C = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${R(e.descriptor, t, n)})`), ne = (e.ctes ?? []).some((e) => e.recursive === !0), re = C.length > 0 ? t`WITH ${t.unsafe(ne ? "RECURSIVE " : "")}${t.csv(C)} ` : t``;
606
607
  return t.onDialectOrElse({
607
608
  mssql: () => {
608
- let n = e.take !== void 0 && !y ? t`TOP ${x(e.take)} ` : t``, r = y ? t` OFFSET ${x(e.skip)} ROWS FETCH NEXT ${x(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
609
- return t`${ie}SELECT ${n}${f}${d} FROM ${h}${te}${_}${v}${ne}${r}`;
609
+ let n = e.take !== void 0 && !b ? t`TOP ${S(e.take)} ` : t``, r = b ? t` OFFSET ${S(e.skip)} ROWS FETCH NEXT ${S(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
610
+ return t`${re}SELECT ${n}${f}${d} FROM ${h}${_}${v}${y}${te}${r}`;
610
611
  },
611
612
  orElse: () => {
612
- let n = e.take === void 0 ? t`` : t` LIMIT ${x(e.take)}`, r = y ? t` OFFSET ${x(e.skip)}` : t``;
613
- return t`${ie}SELECT ${f}${d} FROM ${h}${te}${_}${v}${ne}${n}${r}`;
613
+ let n = e.take === void 0 ? t`` : t` LIMIT ${S(e.take)}`, r = b ? t` OFFSET ${S(e.skip)}` : t``;
614
+ return t`${re}SELECT ${f}${d} FROM ${h}${_}${v}${y}${te}${n}${r}`;
614
615
  }
615
616
  });
616
- }, Cn = (e, t, n) => {
617
+ }, Tn = (e, t, n) => {
617
618
  if (e.eager === void 0) return null;
618
- let r = Tn(e.table, e.eager, e.sourceTable);
619
+ let r = En(e.table, e.eager, e.sourceTable);
619
620
  if (r === null) return null;
620
- let i = Mn(n, e, r, jn(t, n));
621
+ let i = Nn(n, e, r, Mn(t, n));
621
622
  return i === null ? null : {
622
623
  fragment: i,
623
- decode: Fn(r, n)
624
+ decode: In(r, n)
624
625
  };
625
- }, z = (e) => e.relation.kind === "one" && e.fkSide === "target", wn = (e) => ({
626
+ }, z = (e) => e.relation.kind === "one" && e.fkSide === "target", B = (e) => ({
626
627
  ...e,
627
628
  branch: {
628
629
  ...e.branch,
629
630
  limit: 2
630
631
  }
631
- }), Tn = (e, t, n) => {
632
- let r = n ?? g(e), i = Pt(e);
632
+ }), En = (e, t, n) => {
633
+ let r = n ?? g(e), i = F(e);
633
634
  if (i === void 0) return null;
634
635
  let a = [];
635
636
  for (let [e, n] of Object.entries(t)) {
636
637
  let t = i[e];
637
638
  if (t === void 0) return null;
638
- let o = En(e, t, r, n === !0 ? {} : n);
639
+ let o = Dn(e, t, r, n === !0 ? {} : n);
639
640
  if (o === null) return null;
640
641
  a.push(o);
641
642
  }
@@ -643,30 +644,30 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
643
644
  table: r,
644
645
  children: a
645
646
  };
646
- }, En = (e, t, n, r) => {
647
+ }, Dn = (e, t, n, r) => {
647
648
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
648
649
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
649
650
  else if (t.kind === "one") {
650
- let r = t.sourceKey ?? An(n, i.tableName);
651
+ let r = t.sourceKey ?? jn(n, i.tableName);
651
652
  if (r !== void 0) o = r, s = "source";
652
653
  else try {
653
- o = t.foreignKey ?? j(i, n.tableName, e), s = "target";
654
+ o = t.foreignKey ?? M(i, n.tableName, e), s = "target";
654
655
  } catch {
655
656
  return null;
656
657
  }
657
658
  } else try {
658
- o = t.foreignKey ?? j(i, n.tableName, e), s = "target";
659
+ o = t.foreignKey ?? M(i, n.tableName, e), s = "target";
659
660
  } catch {
660
661
  return null;
661
662
  }
662
663
  let c = r.with === void 0 ? [] : (() => {
663
- let e = Pt(i.tableName);
664
+ let e = F(i.tableName);
664
665
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
665
666
  let t = [];
666
667
  for (let [n, a] of Object.entries(r.with)) {
667
668
  let r = e?.[n];
668
669
  if (r === void 0) return null;
669
- let o = En(n, r, i, a === !0 ? {} : a);
670
+ let o = Dn(n, r, i, a === !0 ? {} : a);
670
671
  if (o === null) return null;
671
672
  t.push(o);
672
673
  }
@@ -682,9 +683,9 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
682
683
  fkSide: s,
683
684
  branch: r,
684
685
  children: c,
685
- junction: Dn(t, r)
686
+ junction: On(t, r)
686
687
  };
687
- }, Dn = (e, t) => {
688
+ }, On = (e, t) => {
688
689
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
689
690
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
690
691
  return {
@@ -696,35 +697,35 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
696
697
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
697
698
  })
698
699
  };
699
- }, On = (e) => `__j_${e}`, kn = "__j", An = (e, t) => {
700
+ }, kn = (e) => `__j_${e}`, An = "__j", jn = (e, t) => {
700
701
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
701
- }, jn = (e, t) => {
702
+ }, Mn = (e, t) => {
702
703
  let n = 0;
703
704
  return {
704
705
  sql: e,
705
706
  dialect: t,
706
707
  nextAlias: () => `__a${n++}`
707
708
  };
708
- }, Mn = (e, t, n, r) => {
709
+ }, Nn = (e, t, n, r) => {
709
710
  switch (e) {
710
- case "postgres": return Rn(t, n, r);
711
+ case "postgres": return zn(t, n, r);
711
712
  case "sqlite":
712
- case "turso": return Kn(t, n, r);
713
+ case "turso": return qn(t, n, r);
713
714
  case "mysql":
714
- case "mariadb": return nr(t, n, r);
715
- case "mssql": return lr(t, n, r);
715
+ case "mariadb": return rr(t, n, r);
716
+ case "mssql": return ur(t, n, r);
716
717
  }
717
- }, Nn = (e, t) => t === "mssql" && !Pn.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Pn = /(?:Z|[+-]\d{2}:?\d{2})$/, Fn = (e, t) => {
718
- let n = In(e.table, e.children, t);
718
+ }, Pn = (e, t) => t === "mssql" && !Fn.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Fn = /(?:Z|[+-]\d{2}:?\d{2})$/, In = (e, t) => {
719
+ let n = Ln(e.table, e.children, t);
719
720
  return (e) => e.map((e) => {
720
721
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
721
722
  return n(r);
722
723
  });
723
- }, In = (e, t, n) => {
724
+ }, Ln = (e, t, n) => {
724
725
  let r = [];
725
726
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
726
727
  let i = t.map((e) => {
727
- let t = In(e.target, e.children, n), r = e.relation.kind === "one", i = z(e), a = i ? Jt({
728
+ let t = Ln(e.target, e.children, n), r = e.relation.kind === "one", i = z(e), a = i ? Jt({
728
729
  relationName: e.relationName,
729
730
  sourceTableName: e.source.tableName,
730
731
  targetTableName: e.target.tableName,
@@ -737,14 +738,14 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
737
738
  isSingle: r,
738
739
  fromOverFetch: i,
739
740
  cardinalityMessage: a,
740
- junction: Ln(e.junction, n)
741
+ junction: Rn(e.junction, n)
741
742
  };
742
743
  });
743
744
  return (e) => {
744
745
  let t = { ...e };
745
746
  for (let e of r) {
746
747
  let r = t[e];
747
- typeof r == "string" && (t[e] = Nn(r, n));
748
+ typeof r == "string" && (t[e] = Pn(r, n));
748
749
  }
749
750
  for (let e of i) {
750
751
  let n = t[e.name];
@@ -766,204 +767,204 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
766
767
  }
767
768
  return t;
768
769
  };
769
- }, Ln = (e, t) => {
770
+ }, Rn = (e, t) => {
770
771
  if (e === void 0) return;
771
772
  let n = new Set(e.dateColumns), r = e.requested;
772
773
  return (e) => {
773
774
  let i = e._junction ?? {}, a = {};
774
775
  for (let e of r) {
775
776
  let r = i[e];
776
- a[e] = n.has(e) && typeof r == "string" ? Nn(r, t) : r;
777
+ a[e] = n.has(e) && typeof r == "string" ? Pn(r, t) : r;
777
778
  }
778
779
  return {
779
780
  ...e,
780
781
  _junction: a
781
782
  };
782
783
  };
783
- }, Rn = (e, t, n) => {
784
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = zn(i, t.children, n);
785
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${G(e.predicate, i, r)}` : r``}${e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${H(i, e.column, r)} DESC` : r`${H(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${W(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${W(e.skip, r)}`}`;
786
- }, zn = (e, t, n, r) => {
787
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${U(kn, i)}::text)`;
784
+ }, zn = (e, t, n) => {
785
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Bn(i, t.children, n);
786
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${K(e.predicate, i, r)}` : r``}${e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${U(i, e.column, r)} DESC` : r`${U(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${G(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${G(e.skip, r)}`}`;
787
+ }, Bn = (e, t, n, r) => {
788
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${W(An, i)}::text)`;
788
789
  if (t.length === 0 && r === void 0) return a;
789
790
  let o = [];
790
- r !== void 0 && o.push(i`${U("_junction", i)}, ${H(e, kn, i)}`);
791
+ r !== void 0 && o.push(i`${W("_junction", i)}, ${U(e, An, i)}`);
791
792
  for (let r of t) {
792
- let t = Bn(r, e, n);
793
+ let t = Vn(r, e, n);
793
794
  if (t === null) return null;
794
- o.push(i`${U(r.relationName, i)}, ${t}`);
795
+ o.push(i`${W(r.relationName, i)}, ${t}`);
795
796
  }
796
797
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
797
- }, Bn = (e, t, n) => {
798
+ }, Vn = (e, t, n) => {
798
799
  switch (e.relation.kind) {
799
- case "one": return z(e) ? Hn(wn(e), t, n) : Vn(e, t, n);
800
- case "many": return Hn(e, t, n);
801
- case "manyToMany": return Un(e, t, n);
800
+ case "one": return z(e) ? Un(B(e), t, n) : Hn(e, t, n);
801
+ case "many": return Un(e, t, n);
802
+ case "manyToMany": return Wn(e, t, n);
802
803
  }
803
- }, Vn = (e, t, n) => {
804
- let r = n.sql, i = n.nextAlias(), a = zn(i, e.children, n);
804
+ }, Hn = (e, t, n) => {
805
+ let r = n.sql, i = n.nextAlias(), a = Bn(i, e.children, n);
805
806
  if (a === null) return null;
806
- let o = e.fkSide === "source" ? r`${H(i, "id", r)} = ${H(t, e.foreignKey, r)}` : r`${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${G(e.branch.where, i, r)}`, c = B(i, e.branch.orderBy, r);
807
+ let o = e.fkSide === "source" ? r`${U(i, "id", r)} = ${U(t, e.foreignKey, r)}` : r`${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${K(e.branch.where, i, r)}`, c = V(i, e.branch.orderBy, r);
807
808
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
808
- }, Hn = (e, t, n) => {
809
- let r = n.sql, i = n.nextAlias(), a = zn(i, e.children, n);
809
+ }, Un = (e, t, n) => {
810
+ let r = n.sql, i = n.nextAlias(), a = Bn(i, e.children, n);
810
811
  if (a === null) return null;
811
- let o = r`${H(void 0, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Gn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`;
812
+ let o = r`${U(void 0, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Kn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`;
812
813
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
813
- }, Un = (e, t, n) => {
814
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = zn(o, e.children, n, e.junction);
814
+ }, Wn = (e, t, n) => {
815
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Bn(o, e.children, n, e.junction);
815
816
  if (c === null) return null;
816
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = K(e, s, r), d = B(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Wn(e.junction, s, r)} AS ${r(kn)}`;
817
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${H(o, "id", r)} = ${H(s, i.targetKey, r)} WHERE ${H(s, i.sourceKey, r)} = ${H(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
818
- }, Wn = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${U(e, n)}, ${H(t, e, n)}`))})`, B = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${H(e, t.column, n)} DESC` : n`${H(e, t.column, n)} ASC`))}`, Gn = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Kn = (e, t, n) => {
819
- let r = n.sql, i = n.nextAlias(), a = qn(i, t.table, t.children, n);
817
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = q(e, s, r), d = V(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Gn(e.junction, s, r)} AS ${r(An)}`;
818
+ return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${U(o, "id", r)} = ${U(s, i.targetKey, r)} WHERE ${U(s, i.sourceKey, r)} = ${U(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
819
+ }, Gn = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${W(e, n)}, ${U(t, e, n)}`))})`, V = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${U(e, t.column, n)} DESC` : n`${U(e, t.column, n)} ASC`))}`, Kn = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, qn = (e, t, n) => {
820
+ let r = n.sql, i = n.nextAlias(), a = Jn(i, t.table, t.children, n);
820
821
  if (a === null) return null;
821
- let o = e.predicate ? r` WHERE ${G(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${H(i, e.column, r)} DESC` : r`${H(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${W(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${W(e.skip, r)}`;
822
+ let o = e.predicate ? r` WHERE ${K(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${U(i, e.column, r)} DESC` : r`${U(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${G(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${G(e.skip, r)}`;
822
823
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
823
- }, qn = (e, t, n, r, i) => {
824
+ }, Jn = (e, t, n, r, i) => {
824
825
  let a = r.sql, o = [];
825
- for (let n of Object.keys(t.fields)) o.push(a`${U(n, a)}, ${H(e, n, a)}`);
826
+ for (let n of Object.keys(t.fields)) o.push(a`${W(n, a)}, ${U(e, n, a)}`);
826
827
  if (i !== void 0) {
827
- let e = Jn(i.projection, i.source, a);
828
- o.push(a`${U("_junction", a)}, json_object(${e})`);
828
+ let e = Yn(i.projection, i.source, a);
829
+ o.push(a`${W("_junction", a)}, json_object(${e})`);
829
830
  }
830
831
  for (let t of n) {
831
- let n = Qn(t, e, r);
832
+ let n = $n(t, e, r);
832
833
  if (n === null) return null;
833
- o.push(a`${U(t.relationName, a)}, ${n}`);
834
+ o.push(a`${W(t.relationName, a)}, ${n}`);
834
835
  }
835
836
  return a`json_object(${a.csv(o)})`;
836
- }, Jn = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${U(e, n)}, ${H(t.alias, t.physical(e), n)}`)), Yn = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${H(t, e, n)} AS ${n(On(e))}`))}`, Xn = (e) => ({
837
+ }, Yn = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${W(e, n)}, ${U(t.alias, t.physical(e), n)}`)), Xn = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${U(t, e, n)} AS ${n(kn(e))}`))}`, Zn = (e) => ({
837
838
  alias: e,
838
- physical: On
839
- }), Zn = (e) => ({
839
+ physical: kn
840
+ }), Qn = (e) => ({
840
841
  alias: e,
841
842
  physical: (e) => e
842
- }), Qn = (e, t, n) => {
843
+ }), $n = (e, t, n) => {
843
844
  switch (e.relation.kind) {
844
- case "one": return z(e) ? er(wn(e), t, n) : $n(e, t, n);
845
- case "many": return er(e, t, n);
846
- case "manyToMany": return tr(e, t, n);
845
+ case "one": return z(e) ? tr(B(e), t, n) : er(e, t, n);
846
+ case "many": return tr(e, t, n);
847
+ case "manyToMany": return nr(e, t, n);
847
848
  }
848
- }, $n = (e, t, n) => {
849
- let r = n.sql, i = n.nextAlias(), a = qn(i, e.target, e.children, n);
849
+ }, er = (e, t, n) => {
850
+ let r = n.sql, i = n.nextAlias(), a = Jn(i, e.target, e.children, n);
850
851
  if (a === null) return null;
851
- let o = e.fkSide === "source" ? r`${H(i, "id", r)} = ${H(t, e.foreignKey, r)}` : r`${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`;
852
+ let o = e.fkSide === "source" ? r`${U(i, "id", r)} = ${U(t, e.foreignKey, r)}` : r`${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`;
852
853
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
853
- }, er = (e, t, n) => {
854
- let r = n.sql, i = n.nextAlias(), a = qn(i, e.target, e.children, n);
854
+ }, tr = (e, t, n) => {
855
+ let r = n.sql, i = n.nextAlias(), a = Jn(i, e.target, e.children, n);
855
856
  if (a === null) return null;
856
- let o = r`${H(void 0, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, c = Gn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`;
857
+ let o = r`${U(void 0, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, c = Kn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`;
857
858
  return r`COALESCE((SELECT json_group_array(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), json('[]'))`;
858
- }, tr = (e, t, n) => {
859
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = qn(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
859
+ }, nr = (e, t, n) => {
860
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Jn(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
860
861
  projection: e.junction,
861
- source: Xn(o)
862
+ source: Zn(o)
862
863
  });
863
864
  if (c === null) return null;
864
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, u = K(e, s, r, !0), d = B(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Yn(e.junction, s, r);
865
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${H(o, "id", r)} = ${H(s, i.targetKey, r)} WHERE ${H(s, i.sourceKey, r)} = ${H(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
866
- }, nr = (e, t, n) => {
867
- let r = n.sql, i = n.nextAlias(), a = V(i, t.table, t.children, n);
865
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, u = q(e, s, r, !0), d = V(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xn(e.junction, s, r);
866
+ return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${U(o, "id", r)} = ${U(s, i.targetKey, r)} WHERE ${U(s, i.sourceKey, r)} = ${U(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
867
+ }, rr = (e, t, n) => {
868
+ let r = n.sql, i = n.nextAlias(), a = H(i, t.table, t.children, n);
868
869
  if (a === null) return null;
869
- let o = e.predicate ? r` WHERE ${G(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${H(i, e.column, r)} DESC` : r`${H(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${W(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${W(e.skip, r)}`;
870
+ let o = e.predicate ? r` WHERE ${K(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${U(i, e.column, r)} DESC` : r`${U(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${G(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${G(e.skip, r)}`;
870
871
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
871
- }, V = (e, t, n, r, i) => {
872
+ }, H = (e, t, n, r, i) => {
872
873
  let a = r.sql, o = [];
873
- for (let n of Object.keys(t.fields)) o.push(a`${U(n, a)}, ${H(e, n, a)}`);
874
+ for (let n of Object.keys(t.fields)) o.push(a`${W(n, a)}, ${U(e, n, a)}`);
874
875
  if (i !== void 0) {
875
- let e = Jn(i.projection, i.source, a);
876
- o.push(a`${U("_junction", a)}, JSON_OBJECT(${e})`);
876
+ let e = Yn(i.projection, i.source, a);
877
+ o.push(a`${W("_junction", a)}, JSON_OBJECT(${e})`);
877
878
  }
878
879
  for (let t of n) {
879
- let n = rr(t, e, r);
880
+ let n = ir(t, e, r);
880
881
  if (n === null) return null;
881
- o.push(a`${U(t.relationName, a)}, ${n}`);
882
+ o.push(a`${W(t.relationName, a)}, ${n}`);
882
883
  }
883
884
  return a`JSON_OBJECT(${a.csv(o)})`;
884
- }, rr = (e, t, n) => {
885
+ }, ir = (e, t, n) => {
885
886
  switch (e.relation.kind) {
886
887
  case "one":
887
888
  if (z(e)) {
888
- let r = wn(e);
889
- return n.dialect === "mariadb" ? sr(r, t, n) : ar(r, t, n);
889
+ let r = B(e);
890
+ return n.dialect === "mariadb" ? cr(r, t, n) : or(r, t, n);
890
891
  }
891
- return ir(e, t, n);
892
- case "many": return n.dialect === "mariadb" ? sr(e, t, n) : ar(e, t, n);
893
- case "manyToMany": return n.dialect === "mariadb" ? cr(e, t, n) : or(e, t, n);
892
+ return ar(e, t, n);
893
+ case "many": return n.dialect === "mariadb" ? cr(e, t, n) : or(e, t, n);
894
+ case "manyToMany": return n.dialect === "mariadb" ? lr(e, t, n) : sr(e, t, n);
894
895
  }
895
- }, ir = (e, t, n) => {
896
- let r = n.sql, i = n.nextAlias(), a = V(i, e.target, e.children, n);
896
+ }, ar = (e, t, n) => {
897
+ let r = n.sql, i = n.nextAlias(), a = H(i, e.target, e.children, n);
897
898
  if (a === null) return null;
898
- let o = e.fkSide === "source" ? r`${H(i, "id", r)} = ${H(t, e.foreignKey, r)}` : r`${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`;
899
+ let o = e.fkSide === "source" ? r`${U(i, "id", r)} = ${U(t, e.foreignKey, r)}` : r`${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`;
899
900
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
900
- }, ar = (e, t, n) => {
901
- let r = n.sql, i = n.nextAlias(), a = V(i, e.target, e.children, n);
901
+ }, or = (e, t, n) => {
902
+ let r = n.sql, i = n.nextAlias(), a = H(i, e.target, e.children, n);
902
903
  if (a === null) return null;
903
- let o = r`${H(void 0, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, c = Gn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`;
904
+ let o = r`${U(void 0, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, c = Kn(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`;
904
905
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), JSON_ARRAY())`;
905
- }, or = (e, t, n) => {
906
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = V(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
906
+ }, sr = (e, t, n) => {
907
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = H(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
907
908
  projection: e.junction,
908
- source: Xn(o)
909
+ source: Zn(o)
909
910
  });
910
911
  if (c === null) return null;
911
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, u = K(e, s, r, !0), d = B(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${W(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${W(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Yn(e.junction, s, r);
912
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${H(o, "id", r)} = ${H(s, i.targetKey, r)} WHERE ${H(s, i.sourceKey, r)} = ${H(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
913
- }, sr = (e, t, n) => {
914
- let r = n.sql, i = n.nextAlias(), a = V(i, e.target, e.children, n);
915
- if (a === null) return null;
916
- let o = r`${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
917
- if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${H(i, e.column, r)} DESC` : r`${H(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
918
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${H(i, "rn", r)} > ${W(d, r)} AND ${H(i, "rn", r)} <= ${W(d + u, r)}` : u === void 0 ? r` AND ${H(i, "rn", r)} > ${W(d, r)}` : r` AND ${H(i, "rn", r)} <= ${W(u, r)}`;
919
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${H(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
912
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, u = q(e, s, r, !0), d = V(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${G(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${G(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xn(e.junction, s, r);
913
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${U(o, "id", r)} = ${U(s, i.targetKey, r)} WHERE ${U(s, i.sourceKey, r)} = ${U(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
920
914
  }, cr = (e, t, n) => {
915
+ let r = n.sql, i = n.nextAlias(), a = H(i, e.target, e.children, n);
916
+ if (a === null) return null;
917
+ let o = r`${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
918
+ if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${U(i, e.column, r)} DESC` : r`${U(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
919
+ let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${U(i, "rn", r)} > ${G(d, r)} AND ${U(i, "rn", r)} <= ${G(d + u, r)}` : u === void 0 ? r` AND ${U(i, "rn", r)} > ${G(d, r)}` : r` AND ${U(i, "rn", r)} <= ${G(u, r)}`;
920
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${U(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
921
+ }, lr = (e, t, n) => {
921
922
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
922
923
  projection: e.junction,
923
924
  source: t
924
- }, l = r`${H(s, i.sourceKey, r)} = ${H(t, "id", r)}`, u = r`${H(o, "id", r)} = ${H(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(q(e.branch.where), r)}`, f = K(e, s, r, !0), p = e.branch.orderBy ?? [];
925
+ }, l = r`${U(s, i.sourceKey, r)} = ${U(t, "id", r)}`, u = r`${U(o, "id", r)} = ${U(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(J(e.branch.where), r)}`, f = q(e, s, r, !0), p = e.branch.orderBy ?? [];
925
926
  if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) {
926
- let t = V(o, e.target, e.children, n, c(Zn(s)));
927
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${H(o, e.column, r)} DESC` : r`${H(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
928
- }
929
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${H(o, e.column, r)} DESC` : r`${H(o, e.column, r)} ASC`))}` : r` ORDER BY ${H(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${H(o, "rn", r)} > ${W(g, r)} AND ${H(o, "rn", r)} <= ${W(g + h, r)}` : h === void 0 ? r` AND ${H(o, "rn", r)} > ${W(g, r)}` : r` AND ${H(o, "rn", r)} <= ${W(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${G(q(e.branch.onJunction), s, r)}`, _ = V(o, e.target, e.children, n, c(Xn(o)));
930
- if (_ === null) return null;
931
- let v = e.junction === void 0 ? r`` : Yn(e.junction, s, r);
932
- return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${H(o, "rn", r)}) FROM (SELECT ${r(o)}.*${v}, ${H(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${H(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${H(o, `__src_${i.sourceKey}`, r)} = ${H(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
933
- }, lr = (e, t, n) => {
934
- let r = n.sql, i = n.nextAlias(), a = ur(i, t.table, t.children, n);
927
+ let t = H(o, e.target, e.children, n, c(Qn(s)));
928
+ return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${U(o, e.column, r)} DESC` : r`${U(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
929
+ }
930
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${U(o, e.column, r)} DESC` : r`${U(o, e.column, r)} ASC`))}` : r` ORDER BY ${U(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${U(o, "rn", r)} > ${G(g, r)} AND ${U(o, "rn", r)} <= ${G(g + h, r)}` : h === void 0 ? r` AND ${U(o, "rn", r)} > ${G(g, r)}` : r` AND ${U(o, "rn", r)} <= ${G(h, r)}`, _ = e.branch.onJunction === void 0 ? r`` : r` WHERE ${K(J(e.branch.onJunction), s, r)}`, v = H(o, e.target, e.children, n, c(Zn(o)));
931
+ if (v === null) return null;
932
+ let y = e.junction === void 0 ? r`` : Xn(e.junction, s, r);
933
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${v} ORDER BY ${U(o, "rn", r)}) FROM (SELECT ${r(o)}.*${y}, ${U(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${U(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${_}) AS ${r(o)} WHERE ${U(o, `__src_${i.sourceKey}`, r)} = ${U(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
934
+ }, ur = (e, t, n) => {
935
+ let r = n.sql, i = n.nextAlias(), a = dr(i, t.table, t.children, n);
935
936
  if (a === null) return null;
936
- let o = e.predicate ? r` WHERE ${G(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${H(i, e.column, r)} DESC` : r`${H(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
937
+ let o = e.predicate ? r` WHERE ${K(e.predicate, i, r)}` : r``, s = e.order.length > 0 ? r` ORDER BY ${r.csv(e.order.map((e) => e.direction === "desc" ? r`${U(i, e.column, r)} DESC` : r`${U(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
937
938
  if (e.skip !== void 0) {
938
939
  let t = e.order.length > 0 ? s : r` ORDER BY (SELECT NULL)`;
939
- l = e.take === void 0 ? r`${t} OFFSET ${W(e.skip, r)} ROWS` : r`${t} OFFSET ${W(e.skip, r)} ROWS FETCH NEXT ${W(e.take, r)} ROWS ONLY`;
940
- } else e.take !== void 0 && (c = r`TOP ${W(e.take, r)} `);
940
+ l = e.take === void 0 ? r`${t} OFFSET ${G(e.skip, r)} ROWS` : r`${t} OFFSET ${G(e.skip, r)} ROWS FETCH NEXT ${G(e.take, r)} ROWS ONLY`;
941
+ } else e.take !== void 0 && (c = r`TOP ${G(e.take, r)} `);
941
942
  let u = e.skip === void 0 ? s : r``;
942
943
  return r`SELECT ${c}(SELECT ${a} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) AS ${r("__row")} FROM ${r(t.table.tableName)} AS ${r(i)}${o}${u}${l}`;
943
- }, ur = (e, t, n, r, i) => {
944
+ }, dr = (e, t, n, r, i) => {
944
945
  let a = r.sql, o = [];
945
- for (let n of Object.keys(t.fields)) o.push(a`${H(e, n, a)} AS ${a(n)}`);
946
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${H(i.source.alias, i.source.physical(e), a)} AS ${dr(`_junction.${e}`, a)}`);
946
+ for (let n of Object.keys(t.fields)) o.push(a`${U(e, n, a)} AS ${a(n)}`);
947
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${U(i.source.alias, i.source.physical(e), a)} AS ${fr(`_junction.${e}`, a)}`);
947
948
  for (let t of n) {
948
- let n = fr(t, e, r);
949
+ let n = pr(t, e, r);
949
950
  if (n === null) return null;
950
951
  o.push(n);
951
952
  }
952
953
  return a.csv(o);
953
- }, dr = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), fr = (e, t, n) => {
954
+ }, fr = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), pr = (e, t, n) => {
954
955
  switch (e.relation.kind) {
955
- case "one": return z(e) ? hr(wn(e), t, n) : pr(e, t, n);
956
- case "many": return hr(e, t, n);
957
- case "manyToMany": return gr(e, t, n);
956
+ case "one": return z(e) ? gr(B(e), t, n) : mr(e, t, n);
957
+ case "many": return gr(e, t, n);
958
+ case "manyToMany": return _r(e, t, n);
958
959
  }
959
- }, pr = (e, t, n) => {
960
- let r = n.sql, i = n.nextAlias(), a = ur(i, e.target, e.children, n);
960
+ }, mr = (e, t, n) => {
961
+ let r = n.sql, i = n.nextAlias(), a = dr(i, e.target, e.children, n);
961
962
  if (a === null) return null;
962
- let o = e.fkSide === "source" ? r`${H(i, "id", r)} = ${H(t, e.foreignKey, r)}` : r`${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}`;
963
+ let o = e.fkSide === "source" ? r`${U(i, "id", r)} = ${U(t, e.foreignKey, r)}` : r`${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}`;
963
964
  return r`JSON_QUERY((SELECT TOP 1 ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)) AS ${r(e.relationName)}`;
964
- }, mr = (e, t, n) => {
965
+ }, hr = (e, t, n) => {
965
966
  if (e.offset !== void 0) {
966
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${W(e.offset, n)} ROWS` : n`${r} OFFSET ${W(e.offset, n)} ROWS FETCH NEXT ${W(e.limit, n)} ROWS ONLY`;
967
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${G(e.offset, n)} ROWS` : n`${r} OFFSET ${G(e.offset, n)} ROWS FETCH NEXT ${G(e.limit, n)} ROWS ONLY`;
967
968
  return {
968
969
  top: n``,
969
970
  pagination: i,
@@ -971,33 +972,33 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
971
972
  };
972
973
  }
973
974
  return {
974
- top: e.limit === void 0 ? n`` : n`TOP ${W(e.limit, n)} `,
975
+ top: e.limit === void 0 ? n`` : n`TOP ${G(e.limit, n)} `,
975
976
  pagination: n``,
976
977
  finalOrder: t
977
978
  };
978
- }, hr = (e, t, n) => {
979
- let r = n.sql, i = n.nextAlias(), a = ur(i, e.target, e.children, n);
980
- if (a === null) return null;
981
- let o = e.branch.where === void 0 ? r`` : r` AND ${G(e.branch.where, i, r)}`, s = B(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = mr(e.branch, s, r);
982
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${H(i, e.foreignKey, r)} = ${H(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
983
979
  }, gr = (e, t, n) => {
984
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ur(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
980
+ let r = n.sql, i = n.nextAlias(), a = dr(i, e.target, e.children, n);
981
+ if (a === null) return null;
982
+ let o = e.branch.where === void 0 ? r`` : r` AND ${K(e.branch.where, i, r)}`, s = V(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = hr(e.branch, s, r);
983
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${U(i, e.foreignKey, r)} = ${U(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
984
+ }, _r = (e, t, n) => {
985
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = dr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
985
986
  projection: e.junction,
986
- source: Zn(s)
987
+ source: Qn(s)
987
988
  });
988
989
  if (c === null) return null;
989
- let l = e.branch.where === void 0 ? r`` : r` AND ${G(e.branch.where, o, r)}`, u = K(e, s, r), d = B(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = mr(e.branch, d, r);
990
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${H(o, "id", r)} = ${H(s, i.targetKey, r)} WHERE ${H(s, i.sourceKey, r)} = ${H(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
991
- }, H = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, U = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), W = (e, t) => {
990
+ let l = e.branch.where === void 0 ? r`` : r` AND ${K(e.branch.where, o, r)}`, u = q(e, s, r), d = V(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = hr(e.branch, d, r);
991
+ return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${U(o, "id", r)} = ${U(s, i.targetKey, r)} WHERE ${U(s, i.sourceKey, r)} = ${U(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
992
+ }, U = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, W = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), G = (e, t) => {
992
993
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
993
994
  return t.unsafe(String(e));
994
- }, G = (e, t, n) => L(_r(e, t), n), K = (e, t, n, r = !1) => {
995
+ }, K = (e, t, n) => L(vr(e, t), n), q = (e, t, n, r = !1) => {
995
996
  let i = e.branch.onJunction;
996
- return i === void 0 ? n`` : n` AND ${G(r ? q(i) : i, t, n)}`;
997
- }, _r = (e, t) => {
998
- if ("not" in e) return { not: _r(e.not, t) };
999
- if ("and" in e) return { and: e.and.map((e) => _r(e, t)) };
1000
- if ("or" in e) return { or: e.or.map((e) => _r(e, t)) };
997
+ return i === void 0 ? n`` : n` AND ${K(r ? J(i) : i, t, n)}`;
998
+ }, vr = (e, t) => {
999
+ if ("not" in e) return { not: vr(e.not, t) };
1000
+ if ("and" in e) return { and: e.and.map((e) => vr(e, t)) };
1001
+ if ("or" in e) return { or: e.or.map((e) => vr(e, t)) };
1001
1002
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1002
1003
  let n = e;
1003
1004
  return {
@@ -1011,91 +1012,91 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1011
1012
  ...n,
1012
1013
  column: `${t}.${n.column}`
1013
1014
  };
1014
- }, q = (e) => {
1015
- if ("not" in e) return { not: q(e.not) };
1016
- if ("and" in e) return { and: e.and.map((e) => q(e)) };
1017
- if ("or" in e) return { or: e.or.map((e) => q(e)) };
1015
+ }, J = (e) => {
1016
+ if ("not" in e) return { not: J(e.not) };
1017
+ if ("and" in e) return { and: e.and.map((e) => J(e)) };
1018
+ if ("or" in e) return { or: e.or.map((e) => J(e)) };
1018
1019
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1019
1020
  let t = e;
1020
1021
  return {
1021
1022
  ...t,
1022
- value: vr(t.value)
1023
+ value: yr(t.value)
1023
1024
  };
1024
- }, vr = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => vr(e)) : e, yr = Symbol.for("@voltro/database/coreTablesRegistry"), br = globalThis, xr = br[yr] ?? (br[yr] = {}), Sr = (e) => {
1025
- e.actors !== void 0 && (xr.actors = e.actors), e.tenants !== void 0 && (xr.tenants = e.tenants);
1026
- }, Cr = (e, t) => () => {
1025
+ }, yr = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => yr(e)) : e, br = Symbol.for("@voltro/database/coreTablesRegistry"), xr = globalThis, Sr = xr[br] ?? (xr[br] = {}), Cr = (e) => {
1026
+ e.actors !== void 0 && (Sr.actors = e.actors), e.tenants !== void 0 && (Sr.tenants = e.tenants);
1027
+ }, wr = (e, t) => () => {
1027
1028
  let n = e();
1028
1029
  if (n === void 0) throw Error(`core '${t}' table not registered; expected the framework CLI or your migrate step to call registerCoreTables({ ${t}: () => ${t}Table }) before the database handle is constructed`);
1029
1030
  return n();
1030
- }, wr = () => Cr(() => xr.actors, "actors"), Tr = () => Cr(() => xr.tenants, "tenants"), Er = C("actors", {
1031
- id: D(),
1032
- kind: v().oneOf([
1031
+ }, Tr = () => wr(() => Sr.actors, "actors"), Er = () => wr(() => Sr.tenants, "tenants"), Dr = w("actors", {
1032
+ id: O(),
1033
+ kind: y().oneOf([
1033
1034
  "user",
1034
1035
  "serviceAccount",
1035
1036
  "apiKey",
1036
1037
  "system"
1037
1038
  ]),
1038
- displayName: v().nullable(),
1039
- createdAt: E().default("now")
1040
- }), Dr = (e, t) => ({
1039
+ displayName: y().nullable(),
1040
+ createdAt: D().default("now")
1041
+ }), Or = (e, t) => ({
1041
1042
  column: e,
1042
1043
  op: "eq",
1043
1044
  value: t
1044
- }), Or = (e, t) => ({
1045
+ }), kr = (e, t) => ({
1045
1046
  column: e,
1046
1047
  op: "neq",
1047
1048
  value: t
1048
- }), kr = (e, t) => ({
1049
+ }), Ar = (e, t) => ({
1049
1050
  column: e,
1050
1051
  op: "gt",
1051
1052
  value: t
1052
- }), Ar = (e, t) => ({
1053
+ }), jr = (e, t) => ({
1053
1054
  column: e,
1054
1055
  op: "gte",
1055
1056
  value: t
1056
- }), jr = (e, t) => ({
1057
+ }), Mr = (e, t) => ({
1057
1058
  column: e,
1058
1059
  op: "lt",
1059
1060
  value: t
1060
- }), Mr = (e, t) => ({
1061
+ }), Nr = (e, t) => ({
1061
1062
  column: e,
1062
1063
  op: "lte",
1063
1064
  value: t
1064
- }), Nr = (e, t) => ({
1065
+ }), Pr = (e, t) => ({
1065
1066
  column: e,
1066
1067
  op: "in",
1067
1068
  value: t
1068
- }), Pr = (e, t) => ({
1069
+ }), Fr = (e, t) => ({
1069
1070
  column: e,
1070
1071
  op: "notIn",
1071
1072
  value: t
1072
- }), Fr = (e, t) => ({
1073
+ }), Ir = (e, t) => ({
1073
1074
  column: e,
1074
1075
  op: "contains",
1075
1076
  value: t
1076
- }), Ir = (e, t) => ({
1077
+ }), Lr = (e, t) => ({
1077
1078
  column: e,
1078
1079
  op: "arrayContains",
1079
1080
  value: t
1080
- }), Lr = (e, t) => ({
1081
+ }), Rr = (e, t) => ({
1081
1082
  column: e,
1082
1083
  op: "arrayOverlaps",
1083
1084
  value: t
1084
- }), Rr = (e, t) => ({
1085
+ }), zr = (e, t) => ({
1085
1086
  column: e,
1086
1087
  op: "arrayHas",
1087
1088
  value: t
1088
- }), zr = (e) => ({
1089
+ }), Br = (e) => ({
1089
1090
  column: e,
1090
1091
  op: "isNull"
1091
- }), Br = (e) => ({
1092
+ }), Vr = (e) => ({
1092
1093
  column: e,
1093
1094
  op: "isNotNull"
1094
- }), Vr = (e, t) => ({
1095
+ }), Hr = (e, t) => ({
1095
1096
  column: e,
1096
1097
  op: "spatial",
1097
1098
  value: t
1098
- }), Hr = (...e) => ({ and: e }), Ur = (...e) => ({ or: e }), Wr = (e) => ({ not: e }), Gr = (e, ...t) => {
1099
+ }), Ur = (...e) => ({ and: e }), Wr = (...e) => ({ or: e }), Gr = (e) => ({ not: e }), Kr = (e, ...t) => {
1099
1100
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1100
1101
  let n = (n, r) => ({
1101
1102
  column: e,
@@ -1116,29 +1117,29 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1116
1117
  isNull: () => n("isNull"),
1117
1118
  isNotNull: () => n("isNotNull")
1118
1119
  };
1119
- }, Kr = (e) => "descriptor" in e ? e.descriptor : e, qr = (e, t) => ({
1120
+ }, qr = (e) => "descriptor" in e ? e.descriptor : e, Jr = (e, t) => ({
1120
1121
  column: e,
1121
1122
  op: "subquery-in",
1122
- subquery: Kr(t)
1123
- }), Jr = (e, t) => ({
1123
+ subquery: qr(t)
1124
+ }), Yr = (e, t) => ({
1124
1125
  column: e,
1125
1126
  op: "subquery-not-in",
1126
- subquery: Kr(t)
1127
- }), Yr = (e) => ({
1128
- op: "exists",
1129
- subquery: Kr(e)
1127
+ subquery: qr(t)
1130
1128
  }), Xr = (e) => ({
1129
+ op: "exists",
1130
+ subquery: qr(e)
1131
+ }), Zr = (e) => ({
1131
1132
  op: "not-exists",
1132
- subquery: Kr(e)
1133
- }), J = (e, t) => e == null || t == null ? null : typeof e == typeof t ? e === t ? 0 : e > t ? 1 : -1 : null, Zr = (e, t, n = null) => {
1133
+ subquery: qr(e)
1134
+ }), Qr = (e, t) => e == null || t == null ? null : typeof e == typeof t ? e === t ? 0 : e > t ? 1 : -1 : null, $r = (e, t, n = null) => {
1134
1135
  if (!t) return !1;
1135
- if ("not" in e) return !Zr(e.not, t, n);
1136
+ if ("not" in e) return !$r(e.not, t, n);
1136
1137
  if ("and" in e) {
1137
- for (let r of e.and) if (!Zr(r, t, n)) return !1;
1138
+ for (let r of e.and) if (!$r(r, t, n)) return !1;
1138
1139
  return !0;
1139
1140
  }
1140
1141
  if ("or" in e) {
1141
- for (let r of e.or) if (Zr(r, t, n)) return !0;
1142
+ for (let r of e.or) if ($r(r, t, n)) return !0;
1142
1143
  return !1;
1143
1144
  }
1144
1145
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1157,10 +1158,10 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1157
1158
  switch (r.op) {
1158
1159
  case "eq": return i === r.value;
1159
1160
  case "neq": return i !== r.value;
1160
- case "gt": return (J(i, r.value) ?? -1) > 0;
1161
- case "gte": return (J(i, r.value) ?? -1) >= 0;
1162
- case "lt": return (J(i, r.value) ?? 1) < 0;
1163
- case "lte": return (J(i, r.value) ?? 1) <= 0;
1161
+ case "gt": return (Qr(i, r.value) ?? -1) > 0;
1162
+ case "gte": return (Qr(i, r.value) ?? -1) >= 0;
1163
+ case "lt": return (Qr(i, r.value) ?? 1) < 0;
1164
+ case "lte": return (Qr(i, r.value) ?? 1) <= 0;
1164
1165
  case "in": return Array.isArray(r.value) && r.value.includes(i);
1165
1166
  case "notIn": return Array.isArray(r.value) && !r.value.includes(i);
1166
1167
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
@@ -1177,17 +1178,17 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1177
1178
  case "isNotNull": return i != null;
1178
1179
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1179
1180
  }
1180
- }, Qr = function* (e) {
1181
+ }, ei = function* (e) {
1181
1182
  if ("not" in e) {
1182
- yield* Qr(e.not);
1183
+ yield* ei(e.not);
1183
1184
  return;
1184
1185
  }
1185
1186
  if ("and" in e) {
1186
- for (let t of e.and) yield* Qr(t);
1187
+ for (let t of e.and) yield* ei(t);
1187
1188
  return;
1188
1189
  }
1189
1190
  if ("or" in e) {
1190
- for (let t of e.or) yield* Qr(t);
1191
+ for (let t of e.or) yield* ei(t);
1191
1192
  return;
1192
1193
  }
1193
1194
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1197,27 +1198,27 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1197
1198
  kind: "exists",
1198
1199
  descriptor: e.subquery
1199
1200
  });
1200
- }, $r = function* (e, t = !0) {
1201
+ }, ti = function* (e, t = !0) {
1201
1202
  if ("not" in e) {
1202
- yield* $r(e.not, !1);
1203
+ yield* ti(e.not, !1);
1203
1204
  return;
1204
1205
  }
1205
1206
  if ("and" in e) {
1206
- for (let n of e.and) yield* $r(n, t);
1207
+ for (let n of e.and) yield* ti(n, t);
1207
1208
  return;
1208
1209
  }
1209
1210
  if ("or" in e) {
1210
- for (let t of e.or) yield* $r(t, !1);
1211
+ for (let t of e.or) yield* ti(t, !1);
1211
1212
  return;
1212
1213
  }
1213
1214
  e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists" || (yield {
1214
1215
  ...e,
1215
1216
  conjunctive: t
1216
1217
  });
1217
- }, ei = class extends rt.TaggedError("TableStreamError") {}, ti = 1e3, ni = (e, t, n, r) => {
1218
- let i = O.match(r, {
1218
+ }, ni = class extends it.TaggedError("TableStreamError") {}, ri = 1e3, ii = (e, t, n, r) => {
1219
+ let i = k.match(r, {
1219
1220
  onNone: () => e.where,
1220
- onSome: (n) => e.where ? Hr(e.where, kr(t, n)) : kr(t, n)
1221
+ onSome: (n) => e.where ? Ur(e.where, Ar(t, n)) : Ar(t, n)
1221
1222
  });
1222
1223
  return {
1223
1224
  table: e.table,
@@ -1232,19 +1233,19 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1232
1233
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1233
1234
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1234
1235
  };
1235
- }, ri = (e, t) => {
1236
- let n = t.pk ?? "id", r = t.chunkSize ?? ti;
1237
- return at.paginateChunkEffect(O.none(), (i) => {
1238
- let a = it.tryPromise({
1239
- try: () => e.query(ni(t, n, r, i)),
1240
- catch: (e) => new ei({
1236
+ }, ai = (e, t) => {
1237
+ let n = t.pk ?? "id", r = t.chunkSize ?? ri;
1238
+ return ot.paginateChunkEffect(k.none(), (i) => {
1239
+ let a = at.tryPromise({
1240
+ try: () => e.query(ii(t, n, r, i)),
1241
+ catch: (e) => new ni({
1241
1242
  table: t.table,
1242
1243
  cause: e
1243
1244
  })
1244
1245
  });
1245
- return (t.retry ? a.pipe(it.retry(t.retry)) : a).pipe(it.map((e) => [nt.fromIterable(e), e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1246
+ return (t.retry ? a.pipe(at.retry(t.retry)) : a).pipe(at.map((e) => [rt.fromIterable(e), e.length === r && e.length > 0 ? k.some(k.some(e[e.length - 1][n])) : k.none()]));
1246
1247
  });
1247
- }, ii = (e) => {
1248
+ }, oi = (e) => {
1248
1249
  let t = e.alpha ?? .5;
1249
1250
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1250
1251
  return (n) => {
@@ -1271,15 +1272,15 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1271
1272
  }
1272
1273
  };
1273
1274
  };
1274
- }, ai = async (e, t) => {
1275
+ }, si = async (e, t) => {
1275
1276
  let n = e.as ?? "embedding", r = t.row[e.from];
1276
1277
  if (typeof r != "string" || r.length === 0) return {};
1277
1278
  let i = await t.embed(r);
1278
1279
  return { [n]: i };
1279
- }, oi = (e) => {
1280
+ }, ci = (e) => {
1280
1281
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1281
- let t = e.as ?? "embedding", r = (t) => ai(e, t);
1282
- return ae({
1282
+ let t = e.as ?? "embedding", r = (t) => si(e, t);
1283
+ return ie({
1283
1284
  id: "voltro/vectorEmbedding",
1284
1285
  fields: { [t]: n(e.dimensions) },
1285
1286
  ...e.index === !1 ? {} : { indexes: [{
@@ -1296,19 +1297,19 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1296
1297
  beforeUpdate: r
1297
1298
  }
1298
1299
  });
1299
- }, si = 63, ci = "br_pr", Y = class extends Error {
1300
+ }, li = 63, ui = "br_pr", Y = class extends Error {
1300
1301
  _tag = "BranchNameInvalid";
1301
1302
  constructor(e) {
1302
1303
  super(e), this.name = "BranchNameInvalid";
1303
1304
  }
1304
- }, li = (e, t) => {
1305
+ }, di = (e, t) => {
1305
1306
  if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1306
1307
  let n = un(e);
1307
1308
  if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1308
- let r = `${ci}${t}_${n}`;
1309
- if (r.length > si) throw new Y(`branch namespace '${r}' exceeds the ${si}-byte identifier limit — use a shorter app slug`);
1309
+ let r = `${ui}${t}_${n}`;
1310
+ if (r.length > li) throw new Y(`branch namespace '${r}' exceeds the ${li}-byte identifier limit — use a shorter app slug`);
1310
1311
  return r;
1311
- }, ui = (e) => e.startsWith(ci), di = {
1312
+ }, fi = (e) => e.startsWith(ui), pi = {
1312
1313
  requested: {
1313
1314
  provision: "provisioning",
1314
1315
  destroy: "destroying"
@@ -1327,18 +1328,18 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1327
1328
  fail: "failed"
1328
1329
  },
1329
1330
  destroyed: {}
1330
- }, fi = class extends Error {
1331
+ }, mi = class extends Error {
1331
1332
  from;
1332
1333
  event;
1333
1334
  _tag = "BranchTransitionInvalid";
1334
1335
  constructor(e, t) {
1335
1336
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1336
1337
  }
1337
- }, pi = (e, t) => {
1338
- let n = di[e][t];
1339
- if (n === void 0) throw new fi(e, t);
1338
+ }, hi = (e, t) => {
1339
+ let n = pi[e][t];
1340
+ if (n === void 0) throw new mi(e, t);
1340
1341
  return n;
1341
- }, mi = (e, t, n, r) => {
1342
+ }, gi = (e, t, n, r) => {
1342
1343
  if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
1343
1344
  let i = [{
1344
1345
  kind: "create-namespace",
@@ -1359,13 +1360,13 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1359
1360
  detail: `run boot seeds into ${e}`
1360
1361
  });
1361
1362
  return i;
1362
- }, hi = (e) => {
1363
- if (!ui(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1363
+ }, _i = (e) => {
1364
+ if (!fi(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1364
1365
  return [{
1365
1366
  kind: "drop-namespace",
1366
1367
  detail: e
1367
1368
  }];
1368
- }, gi = (e) => {
1369
+ }, vi = (e) => {
1369
1370
  if (e === void 0 || e === "") return !1;
1370
1371
  try {
1371
1372
  let t = new URL(e).hostname.toLowerCase();
@@ -1373,27 +1374,27 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1373
1374
  } catch {
1374
1375
  return /\bneon\.(tech|build)\b/i.test(e);
1375
1376
  }
1376
- }, _i = (e) => e.prefer === void 0 ? e.seed === "copy" && gi(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, vi = (e, t = {}) => [{
1377
+ }, yi = (e) => e.prefer === void 0 ? e.seed === "copy" && vi(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, bi = (e, t = {}) => [{
1377
1378
  kind: "neon-branch-create",
1378
1379
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1379
- }], yi = (e) => {
1380
- if (!ui(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1380
+ }], xi = (e) => {
1381
+ if (!fi(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1381
1382
  return [{
1382
1383
  kind: "neon-branch-delete",
1383
1384
  detail: e
1384
1385
  }];
1385
- }, bi = (e) => e.mechanism === "neon-cow" ? vi(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : mi(e.branchId, e.tableNames, e.seed, e.parentNamespace), xi = (e, t) => e === "neon-cow" ? yi(t) : hi(t), Si = (e, t, n) => {
1386
+ }, Si = (e) => e.mechanism === "neon-cow" ? bi(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : gi(e.branchId, e.tableNames, e.seed, e.parentNamespace), Ci = (e, t) => e === "neon-cow" ? xi(t) : _i(t), wi = (e, t, n) => {
1386
1387
  let r = e.filter((e) => e.state !== "destroyed" && e.state !== "destroying"), i = r.filter((e) => n - e.createdAtMs > t.ttlMs).map((e) => e.namespace), a = new Set(i);
1387
1388
  return {
1388
1389
  evict: i,
1389
1390
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1390
1391
  };
1391
- }, Ci = async (e, t) => {
1392
- let n = li(e.appSlug, e.prNumber), r = _i({
1392
+ }, Ti = async (e, t) => {
1393
+ let n = di(e.appSlug, e.prNumber), r = yi({
1393
1394
  seed: e.seed,
1394
1395
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1395
1396
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1396
- }), i = bi({
1397
+ }), i = Si({
1397
1398
  mechanism: r,
1398
1399
  branchId: n,
1399
1400
  tableNames: e.tableNames,
@@ -1418,10 +1419,10 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1418
1419
  mechanism: r,
1419
1420
  steps: i
1420
1421
  };
1421
- }, wi = async (e, t, n) => {
1422
- let r = xi(t, e);
1422
+ }, Ei = async (e, t, n) => {
1423
+ let r = Ci(t, e);
1423
1424
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1424
- }, Ti = (e, t, n) => Si(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, Ei = (e) => {
1425
+ }, Di = (e, t, n) => wi(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, Oi = (e) => {
1425
1426
  let t = () => {
1426
1427
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1427
1428
  };
@@ -1433,18 +1434,18 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1433
1434
  neonBranchCreate: t,
1434
1435
  neonBranchDelete: t
1435
1436
  };
1436
- }, Di = class extends Error {
1437
+ }, ki = class extends Error {
1437
1438
  _tag = "TenantResidencyUnresolved";
1438
1439
  constructor(e) {
1439
1440
  super(e), this.name = "TenantResidencyUnresolved";
1440
1441
  }
1441
- }, Oi = class extends Error {
1442
+ }, Ai = class extends Error {
1442
1443
  region;
1443
1444
  _tag = "TenantRegionUnavailable";
1444
1445
  constructor(e, t) {
1445
1446
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1446
1447
  }
1447
- }, ki, Ai = (e) => {
1448
+ }, ji, Mi = (e) => {
1448
1449
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1449
1450
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1450
1451
  let t = /* @__PURE__ */ new Map();
@@ -1453,32 +1454,32 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1453
1454
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1454
1455
  t.set(n.tenantId, n.region);
1455
1456
  }
1456
- return ki = e, e;
1457
- }, ji = () => ki, Mi = () => {
1458
- ki = void 0;
1459
- }, Ni = (e, t) => {
1460
- if (e == null || e === "") throw new Di("residency is on but the request has no resolvable tenant — refusing to bind a store");
1457
+ return ji = e, e;
1458
+ }, Ni = () => ji, Pi = () => {
1459
+ ji = void 0;
1460
+ }, Fi = (e, t) => {
1461
+ if (e == null || e === "") throw new ki("residency is on but the request has no resolvable tenant — refusing to bind a store");
1461
1462
  let n = t.homes.find((t) => t.tenantId === e);
1462
- if (n === void 0) throw new Di(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1463
+ if (n === void 0) throw new ki(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1463
1464
  return n;
1464
- }, Pi = (e, t) => t.servableRegions.includes(e), Fi = (e, t) => {
1465
- let n = Ni(e.tenantId, t), r = dn(n.tenantId);
1465
+ }, Ii = (e, t) => t.servableRegions.includes(e), Li = (e, t) => {
1466
+ let n = Fi(e.tenantId, t), r = dn(n.tenantId);
1466
1467
  return {
1467
1468
  region: n.region,
1468
1469
  namespace: r,
1469
1470
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1470
1471
  };
1471
- }, Ii = (e, t, n) => {
1472
- let r = Fi(e, t);
1473
- if (!Pi(r.region, t)) throw new Oi(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1472
+ }, Ri = (e, t, n) => {
1473
+ let r = Li(e, t);
1474
+ if (!Ii(r.region, t)) throw new Ai(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1474
1475
  let i = n.get(r.region);
1475
- if (i === void 0) throw new Oi(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1476
+ if (i === void 0) throw new Ai(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1476
1477
  return {
1477
1478
  store: i,
1478
1479
  placement: r
1479
1480
  };
1480
- }, Li = async (e, t, n, r) => {
1481
- let { store: i, placement: a } = Ii(e, t, n);
1481
+ }, zi = async (e, t, n, r) => {
1482
+ let { store: i, placement: a } = Ri(e, t, n);
1482
1483
  return await r(i, a), a;
1483
1484
  }, Z = (e) => {
1484
1485
  if (typeof e == "string") return e;
@@ -1487,21 +1488,21 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1487
1488
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1488
1489
  }
1489
1490
  return `(${e.expr})`;
1490
- }, Q = (e) => e.map(Z), Ri = (e, t) => {
1491
+ }, Q = (e) => e.map(Z), Bi = (e, t) => {
1491
1492
  if (e.length !== t.length) return !1;
1492
1493
  for (let n = 0; n < e.length; n++) if (Z(e[n]) !== Z(t[n])) return !1;
1493
1494
  return !0;
1494
- }, zi = (e, t) => {
1495
+ }, Vi = (e, t) => {
1495
1496
  if (e.length >= t.length) return !1;
1496
1497
  for (let n = 0; n < e.length; n++) if (Z(e[n]) !== Z(t[n])) return !1;
1497
1498
  return !0;
1498
- }, Bi = (e) => {
1499
+ }, Hi = (e) => {
1499
1500
  let t = [], n = e.appliedIndexes, r = e.tableName;
1500
1501
  for (let e = 0; e < n.length; e++) {
1501
1502
  let i = n[e];
1502
1503
  for (let a = e + 1; a < n.length; a++) {
1503
1504
  let e = n[a];
1504
- if (Ri(i.fields, e.fields)) {
1505
+ if (Bi(i.fields, e.fields)) {
1505
1506
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
1506
1507
  t.push({
1507
1508
  kind: "duplicate-fields",
@@ -1512,13 +1513,13 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1512
1513
  });
1513
1514
  continue;
1514
1515
  }
1515
- zi(i.fields, e.fields) ? t.push({
1516
+ Vi(i.fields, e.fields) ? t.push({
1516
1517
  kind: "redundant-prefix",
1517
1518
  table: r,
1518
1519
  redundant: i,
1519
1520
  coveredBy: e,
1520
1521
  message: `'${r}' index '${i.name}' on [${Q(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Q(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
1521
- }) : zi(e.fields, i.fields) && t.push({
1522
+ }) : Vi(e.fields, i.fields) && t.push({
1522
1523
  kind: "redundant-prefix",
1523
1524
  table: r,
1524
1525
  redundant: e,
@@ -1528,23 +1529,23 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1528
1529
  }
1529
1530
  }
1530
1531
  return t;
1531
- }, Vi = (e) => {
1532
+ }, Ui = (e) => {
1532
1533
  let t = [];
1533
- for (let n of e) t.push(...Bi(n));
1534
+ for (let n of e) t.push(...Hi(n));
1534
1535
  return t;
1535
- }, Hi = "\x1B[", Ui = `${Hi}38;2;245;158;11m`, Wi = `${Hi}38;2;16;185;129m`, Gi = (e, t) => `${e}${t}${A.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Gi(t, n) : n, Ki = (e, t = {}) => {
1536
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, A.dim, e.padEnd(11)), a = (e) => $(n, (e) => A.bold(A.brand(e)), e), o = (e) => $(n, A.brightRed24, e), s = (e) => $(n, Wi, e), c = (e) => $(n, Ui, e), l = (e) => $(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1536
+ }, Wi = "\x1B[", Gi = `${Wi}38;2;245;158;11m`, Ki = `${Wi}38;2;16;185;129m`, qi = (e, t) => `${e}${t}${j.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : qi(t, n) : n, Ji = (e, t = {}) => {
1537
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, j.dim, e.padEnd(11)), a = (e) => $(n, (e) => j.bold(j.brand(e)), e), o = (e) => $(n, j.brightRed24, e), s = (e) => $(n, Ki, e), c = (e) => $(n, Gi, e), l = (e) => $(n, j.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, j.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1537
1538
  let n = e.slice(0, t), r = e.slice(t), i = [];
1538
1539
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
1539
1540
  }, m = [];
1540
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, A.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
1541
- }, qi = (e, t) => ({
1541
+ return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, j.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
1542
+ }, Yi = (e, t) => ({
1542
1543
  name: e,
1543
1544
  body: t
1544
- }), Ji = (e) => {
1545
+ }), Xi = (e) => {
1545
1546
  if (e.lifecycle === "cron" && !e.cron) throw Error(`seed "${e.id}": lifecycle 'cron' requires a 'cron' field`);
1546
1547
  if (e.lifecycle === "onSchemaChange" && (!e.watchedTables || e.watchedTables.length === 0)) throw Error(`seed "${e.id}": lifecycle 'onSchemaChange' requires at least one entry in 'watchedTables'`);
1547
- let t = e.steps({ step: qi });
1548
+ let t = e.steps({ step: Yi });
1548
1549
  if (t.length === 0) throw Error(`seed "${e.id}": at least one step is required`);
1549
1550
  return {
1550
1551
  __seed: !0,
@@ -1556,13 +1557,13 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1556
1557
  ...e.fingerprint === void 0 ? {} : { fingerprint: e.fingerprint },
1557
1558
  steps: t
1558
1559
  };
1559
- }, Yi = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, Xi = (e, { apply: t, undo: n }) => ({
1560
+ }, Zi = (e) => typeof e == "object" && !!e && "__seed" in e && e.__seed === !0, Qi = (e, { apply: t, undo: n }) => ({
1560
1561
  name: e,
1561
1562
  apply: t,
1562
1563
  undo: n
1563
- }), Zi = (e) => {
1564
+ }), $i = (e) => {
1564
1565
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
1565
- let t = e.steps({ step: Xi });
1566
+ let t = e.steps({ step: Qi });
1566
1567
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
1567
1568
  return {
1568
1569
  __migration: !0,
@@ -1570,111 +1571,111 @@ var ot = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqli
1570
1571
  name: e.name,
1571
1572
  steps: t
1572
1573
  };
1573
- }, Qi = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, $i = C("_voltro_migrations", {
1574
- id: D({ prefix: "mig" }),
1575
- name: v(),
1576
- hash: v(),
1577
- status: v(),
1578
- appliedAt: E().nullable(),
1579
- durationMs: w().nullable(),
1580
- errorMessage: v().nullable(),
1581
- errorStack: v().nullable(),
1582
- workflowRunId: v().nullable(),
1583
- createdAt: E().default("now"),
1584
- updatedAt: E().default("now").onUpdate("now")
1585
- }).index(["status"]).reactive(), ea = C("_voltro_seeds", {
1586
- id: D({ prefix: "seed" }),
1587
- name: v(),
1588
- lifecycle: v(),
1589
- fingerprint: v(),
1590
- cronSchedule: v().nullable(),
1591
- watchedTables: S().nullable(),
1592
- nextRunAt: E().nullable(),
1593
- lastRunStatus: v().nullable(),
1594
- lastRunAt: E().nullable(),
1595
- lastRunDurationMs: w().nullable(),
1596
- lastRunRowsTouched: w().nullable(),
1597
- lastError: v().nullable(),
1598
- workflowRunId: v().nullable(),
1599
- createdAt: E().default("now"),
1600
- updatedAt: E().default("now").onUpdate("now")
1601
- }).index(["lifecycle"]).index(["nextRunAt"]).reactive(), ta = C("_voltro_migration_plans", {
1602
- id: D({ prefix: "plan" }),
1603
- fingerprint: v(),
1604
- operations: S(),
1605
- rollbackPlan: S().nullable(),
1606
- appliedBy: v(),
1607
- environment: v(),
1608
- source: v(),
1609
- onlineStrategy: v().nullable(),
1610
- durationMs: w(),
1611
- notes: v().nullable(),
1612
- squashedAt: E().nullable(),
1613
- appliedAt: E().default("now"),
1614
- createdAt: E().default("now"),
1615
- updatedAt: E().default("now").onUpdate("now")
1616
- }).index(["fingerprint"]).index(["environment"]).reactive(), na = C("_voltro_idempotency", {
1617
- id: D({ prefix: "idem" }),
1618
- scope: v(),
1619
- key: v(),
1620
- status: v(),
1621
- response: S().nullable(),
1622
- createdAt: E().default("now")
1623
- }).unique(["scope", "key"]).index(["createdAt"]).reactive(), ra = C("_voltro_kv", {
1624
- id: D({ prefix: "kv" }),
1625
- key: v().unique(),
1626
- value: v().nullable(),
1627
- expiresAt: E().nullable(),
1628
- createdAt: E().default("now"),
1629
- updatedAt: E().default("now").onUpdate("now")
1630
- }).index(["expiresAt"]).reactive(), ia = C("_voltro_api_keys", {
1631
- id: D({ prefix: "apikey" }),
1632
- tenantId: v().nullable(),
1633
- name: v(),
1634
- hashedKey: v().unique(),
1635
- keyPrefix: v(),
1636
- scopes: S().nullable(),
1637
- lastUsedAt: E().nullable(),
1638
- expiresAt: E().nullable(),
1639
- revokedAt: E().nullable(),
1640
- createdBy: v().nullable(),
1641
- createdAt: E().default("now")
1642
- }).index("byTenant", ["tenantId"]).reactive(), aa = [
1643
- $i,
1644
- ea,
1645
- ta
1646
- ], oa = (e, t, n) => ({
1574
+ }, ea = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, ta = w("_voltro_migrations", {
1575
+ id: O({ prefix: "mig" }),
1576
+ name: y(),
1577
+ hash: y(),
1578
+ status: y(),
1579
+ appliedAt: D().nullable(),
1580
+ durationMs: T().nullable(),
1581
+ errorMessage: y().nullable(),
1582
+ errorStack: y().nullable(),
1583
+ workflowRunId: y().nullable(),
1584
+ createdAt: D().default("now"),
1585
+ updatedAt: D().default("now").onUpdate("now")
1586
+ }).index(["status"]).reactive(), na = w("_voltro_seeds", {
1587
+ id: O({ prefix: "seed" }),
1588
+ name: y(),
1589
+ lifecycle: y(),
1590
+ fingerprint: y(),
1591
+ cronSchedule: y().nullable(),
1592
+ watchedTables: C().nullable(),
1593
+ nextRunAt: D().nullable(),
1594
+ lastRunStatus: y().nullable(),
1595
+ lastRunAt: D().nullable(),
1596
+ lastRunDurationMs: T().nullable(),
1597
+ lastRunRowsTouched: T().nullable(),
1598
+ lastError: y().nullable(),
1599
+ workflowRunId: y().nullable(),
1600
+ createdAt: D().default("now"),
1601
+ updatedAt: D().default("now").onUpdate("now")
1602
+ }).index(["lifecycle"]).index(["nextRunAt"]).reactive(), ra = w("_voltro_migration_plans", {
1603
+ id: O({ prefix: "plan" }),
1604
+ fingerprint: y(),
1605
+ operations: C(),
1606
+ rollbackPlan: C().nullable(),
1607
+ appliedBy: y(),
1608
+ environment: y(),
1609
+ source: y(),
1610
+ onlineStrategy: y().nullable(),
1611
+ durationMs: T(),
1612
+ notes: y().nullable(),
1613
+ squashedAt: D().nullable(),
1614
+ appliedAt: D().default("now"),
1615
+ createdAt: D().default("now"),
1616
+ updatedAt: D().default("now").onUpdate("now")
1617
+ }).index(["fingerprint"]).index(["environment"]).reactive(), ia = w("_voltro_idempotency", {
1618
+ id: O({ prefix: "idem" }),
1619
+ scope: y(),
1620
+ key: y(),
1621
+ status: y(),
1622
+ response: C().nullable(),
1623
+ createdAt: D().default("now")
1624
+ }).unique(["scope", "key"]).index(["createdAt"]).reactive(), aa = w("_voltro_kv", {
1625
+ id: O({ prefix: "kv" }),
1626
+ key: y().unique(),
1627
+ value: y().nullable(),
1628
+ expiresAt: D().nullable(),
1629
+ createdAt: D().default("now"),
1630
+ updatedAt: D().default("now").onUpdate("now")
1631
+ }).index(["expiresAt"]).reactive(), oa = w("_voltro_api_keys", {
1632
+ id: O({ prefix: "apikey" }),
1633
+ tenantId: y().nullable(),
1634
+ name: y(),
1635
+ hashedKey: y().unique(),
1636
+ keyPrefix: y(),
1637
+ scopes: C().nullable(),
1638
+ lastUsedAt: D().nullable(),
1639
+ expiresAt: D().nullable(),
1640
+ revokedAt: D().nullable(),
1641
+ createdBy: y().nullable(),
1642
+ createdAt: D().default("now")
1643
+ }).index("byTenant", ["tenantId"]).reactive(), sa = [
1644
+ ta,
1645
+ na,
1646
+ ra
1647
+ ], ca = (e, t, n) => ({
1647
1648
  _tag: "PrimaryKeyConflictError",
1648
1649
  table: e,
1649
1650
  key: t,
1650
1651
  cause: n
1651
- }), sa = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", ca = /* @__PURE__ */ new Map(), la = (e) => {
1652
+ }), la = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", ua = /* @__PURE__ */ new Map(), da = (e) => {
1652
1653
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
1653
1654
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
1654
- ca.set(e.table, e);
1655
- }, ua = () => [...ca.values()], da = () => ca.clear(), fa = async (e, t, n, r = 2e4) => {
1655
+ ua.set(e.table, e);
1656
+ }, fa = () => [...ua.values()], pa = () => ua.clear(), ma = async (e, t, n, r = 2e4) => {
1656
1657
  let i = new Date(t - e.ttlMs), a = 0;
1657
1658
  for (;;) {
1658
1659
  let t = await n(e.table, e.timeColumn, i, r, e.where);
1659
1660
  if (a += t, t < r) break;
1660
1661
  }
1661
1662
  return a;
1662
- }, pa = (e, t) => {
1663
+ }, ha = (e, t) => {
1663
1664
  let n = Number(e ?? String(t));
1664
1665
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
1665
- }, ma = "_voltro_cdc_offsets", ha = C(ma, {
1666
- id: D({ prefix: "cdcoff" }),
1667
- replicaId: v(),
1668
- streamName: v(),
1669
- binlogFile: v(),
1670
- binlogPosition: v(),
1671
- updatedAt: E()
1672
- }).index(["replicaId"]), ga = C(ma, {
1673
- id: D({ prefix: "cdcoff" }),
1674
- replicaId: v(),
1675
- streamName: v(),
1676
- ctVersion: v(),
1677
- updatedAt: E()
1678
- }).index(["replicaId"]), _a = "postgres";
1666
+ }, ga = "_voltro_cdc_offsets", _a = w(ga, {
1667
+ id: O({ prefix: "cdcoff" }),
1668
+ replicaId: y(),
1669
+ streamName: y(),
1670
+ binlogFile: y(),
1671
+ binlogPosition: y(),
1672
+ updatedAt: D()
1673
+ }).index(["replicaId"]), va = w(ga, {
1674
+ id: O({ prefix: "cdcoff" }),
1675
+ replicaId: y(),
1676
+ streamName: y(),
1677
+ ctVersion: y(),
1678
+ updatedAt: D()
1679
+ }).index(["replicaId"]), ya = "postgres";
1679
1680
  //#endregion
1680
- export { Y as BranchNameInvalid, fi as BranchTransitionInvalid, ma as CDC_OFFSETS_TABLE, ge as ColumnBuilder, ut as ENCRYPTED_PREFIX, _a as ENGINE, qt as EagerCardinalityError, We as FILE_MIGRATION_PATTERN, le as MAX_IDENTIFIER_LENGTH, ei as TableStreamError, sn as TenantNamespaceInvalid, on as TenantNamespaceUnresolved, Oi as TenantRegionUnavailable, Di as TenantResidencyUnresolved, b as WARN_IDENTIFIER_LENGTH, ia as _voltroApiKeysTable, ha as _voltroCdcOffsetsTable, na as _voltroIdempotencyTable, ra as _voltroKvTable, ta as _voltroMigrationPlansTable, $i as _voltroMigrationsTable, ga as _voltroMssqlCdcOffsetsTable, ea as _voltroSeedsTable, Er as actorsTable, Ti as admitBranch, Ee as allEnumRenames, It as allRegisteredRelations, ee as allRegisteredTables, Hr as and, Ae as array, Ir as arrayContains, Rr as arrayHas, Lr as arrayOverlaps, Yt as attachEagerLoads, Vi as auditAllTableIndexes, Bi as auditTableIndexes, ke as avg, Ke as avgOver, qe as bigint, Ii as bindResidentStore, ve as boolean, li as branchNamespaceName, xe as bytes, pe as clearEnumRenames, Rt as clearRelationsRegistry, Mi as clearResidencyConfig, da as clearRetentions, te as clearTableRegistry, Qr as collectSubqueries, _e as column, ht as columnSchema, Cn as compileEagerJson, L as compilePredicate, fn as compileRawFragment, R as compileSelect, ai as computeEmbedding, Fr as contains, be as count, Le as countDistinct, je as databaseHandle, Re as date, Me as dbEnum, Te as decimal, Ie as declareEnumRename, Wt as decodeRowsFromSchema, mt as decryptFieldsOnRead, Zi as defineMigration, ae as defineMixin, Ji as defineSeed, we as denseRank, h as deriveTypeIdPrefix, lt as deserializeArraysOnRead, e as drainIdentifierWarnings, Ce as dropped, Kt as encodeRowForSchema, pt as encryptFieldsForWrite, ft as encryptedColumnsOf, Si as enforceBranchLimits, y as ensureTableRegistered, Dr as eq, I as escapeLike, Zr as evaluatePredicate, Se as except, Yr as exists, Ki as formatIndexAuditIssue, aa as frameworkTables, ze as generateId, ce as generateSnowflake, de as geography, Ye as geometry, Ue as getEnumRenames, Ft as getRelation, Pt as getRelations, ji as getResidencyConfig, u as getTable, kr as gt, Ar as gte, an as hasEagerLoads, ii as hybridSearch, D as id, Nr as inSet, qr as inSubquery, j as inferForeignKey, w as integer, ue as intersect, $e as interval, ui as isBranchNamespace, dt as isEncrypted, Ne as isFileMigration, Qi as isMigrationDefinition, gi as isNeonConnection, Br as isNotNull, zr as isNull, sa as isPrimaryKeyConflictError, Pi as isRegionServable, Ct as isRelationsSpec, Yi as isSeedDefinition, ne as isSqliteFamily, fe as isView, S as json, Gr as jsonField, r as jsonIndex, Je as lag, et as lead, ua as listRetentions, jr as lt, Mr as lte, Ei as makeNamespaceBranchExecutor, Tt as many, Et as manyToMany, a as materializeFields, me as max, Be as migration, Qe as min, oe as mixin, Or as neq, pi as nextBranchState, Wr as not, Xr as notExists, Pr as notInSet, Jr as notInSubquery, Ze as numeric, wt as one, Jt as oneCardinalityMessage, Ur as or, x as paginateBy, i as paginateById, bi as planBranch, mi as planBranchProvision, hi as planBranchTeardown, xi as planBranchTeardownFor, vi as planNeonBranchProvision, yi as planNeonBranchTeardown, oa as primaryKeyConflictError, Ci as provisionBranch, Li as provisionResidentTenant, F as qualifyTable, Xe as queryFor, Fe as queryForView, tt as quoteIdent, re as rank, ie as raw, l as real, s as reference, Sr as registerCoreTables, Nt as registerDiscoveredRelations, Mt as registerRelations, la as registerRetention, p as registerTable, St as relations, wr as requireActors, g as requireTable, Tr as requireTenants, se as resetSnowflake, Fi as residentPlacement, _i as resolveBranchMechanism, c as resolveFullTextIndex, m as resolveIdScheme, d as resolveMixinGraph, Ni as resolveTenantHome, dn as resolveTenantNamespace, pa as retentionTtlMsFromEnv, o as rowNumber, gt as rowSchema, un as sanitizeIdentifierFragment, ct as serializeArraysForWrite, Ai as setResidencyConfig, Vr as spatialPredicate, ri as streamTable, _ as sum, Oe as sumOver, fa as sweepRetention, C as table, wi as teardownBranch, v as text, E as timestamp, t as union, De as unionAll, ye as validateColumnName, Ge as validateIndexName, Lt as validateRegisteredRelations, kt as validateRelationConfig, Pe as validateTableName, Ve as validateTypeIdPrefix, n as vector, f as vectorDistanceToOpclass, oi as vectorEmbedding, He as view, he as viewSql, $r as walkLeaves };
1681
+ export { Y as BranchNameInvalid, mi as BranchTransitionInvalid, ga as CDC_OFFSETS_TABLE, he as ColumnBuilder, dt as ENCRYPTED_PREFIX, ya as ENGINE, qt as EagerCardinalityError, Ue as FILE_MIGRATION_PATTERN, ce as MAX_IDENTIFIER_LENGTH, ni as TableStreamError, sn as TenantNamespaceInvalid, on as TenantNamespaceUnresolved, Ai as TenantRegionUnavailable, ki as TenantResidencyUnresolved, x as WARN_IDENTIFIER_LENGTH, oa as _voltroApiKeysTable, _a as _voltroCdcOffsetsTable, ia as _voltroIdempotencyTable, aa as _voltroKvTable, ra as _voltroMigrationPlansTable, ta as _voltroMigrationsTable, va as _voltroMssqlCdcOffsetsTable, na as _voltroSeedsTable, Dr as actorsTable, Di as admitBranch, Te as allEnumRenames, It as allRegisteredRelations, ee as allRegisteredTables, Ur as and, ke as array, Lr as arrayContains, zr as arrayHas, Rr as arrayOverlaps, Yt as attachEagerLoads, Ui as auditAllTableIndexes, Hi as auditTableIndexes, Oe as avg, Ge as avgOver, Ke as bigint, Ri as bindResidentStore, _e as boolean, di as branchNamespaceName, be as bytes, fe as clearEnumRenames, Rt as clearRelationsRegistry, Pi as clearResidencyConfig, pa as clearRetentions, _ as clearTableRegistry, ei as collectSubqueries, ge as column, gt as columnSchema, Tn as compileEagerJson, L as compilePredicate, pn as compileRawFragment, R as compileSelect, si as computeEmbedding, Ir as contains, ye as count, Ie as countDistinct, Ae as databaseHandle, Le as date, je as dbEnum, we as decimal, Fe as declareEnumRename, Wt as decodeRowsFromSchema, ht as decryptFieldsOnRead, $i as defineMigration, ie as defineMixin, Xi as defineSeed, Ce as denseRank, h as deriveTypeIdPrefix, ut as deserializeArraysOnRead, e as drainIdentifierWarnings, Se as dropped, Kt as encodeRowForSchema, mt as encryptFieldsForWrite, pt as encryptedColumnsOf, wi as enforceBranchLimits, b as ensureTableRegistered, Or as eq, mn as escapeLike, $r as evaluatePredicate, xe as except, Xr as exists, Ji as formatIndexAuditIssue, sa as frameworkTables, Re as generateId, se as generateSnowflake, ue as geography, Je as geometry, He as getEnumRenames, Ft as getRelation, F as getRelations, Ni as getResidencyConfig, u as getTable, Ar as gt, jr as gte, an as hasEagerLoads, oi as hybridSearch, O as id, Pr as inSet, Jr as inSubquery, M as inferForeignKey, T as integer, le as intersect, Qe as interval, fi as isBranchNamespace, ft as isEncrypted, Me as isFileMigration, ea as isMigrationDefinition, vi as isNeonConnection, Vr as isNotNull, Br as isNull, la as isPrimaryKeyConflictError, Ii as isRegionServable, wt as isRelationsSpec, Zi as isSeedDefinition, te as isSqliteFamily, de as isView, C as json, Kr as jsonField, r as jsonIndex, qe as lag, $e as lead, fa as listRetentions, Mr as lt, Nr as lte, Oi as makeNamespaceBranchExecutor, Et as many, Dt as manyToMany, a as materializeFields, pe as max, ze as migration, Ze as min, ae as mixin, kr as neq, hi as nextBranchState, Gr as not, Zr as notExists, Fr as notInSet, Yr as notInSubquery, Xe as numeric, Tt as one, Jt as oneCardinalityMessage, Wr as or, S as paginateBy, i as paginateById, Si as planBranch, gi as planBranchProvision, _i as planBranchTeardown, Ci as planBranchTeardownFor, bi as planNeonBranchProvision, xi as planNeonBranchTeardown, ca as primaryKeyConflictError, Ti as provisionBranch, zi as provisionResidentTenant, fn as qualifyTable, Ye as queryFor, Pe as queryForView, et as quoteIdent, ne as rank, re as raw, l as real, s as reference, Cr as registerCoreTables, Pt as registerDiscoveredRelations, Nt as registerRelations, da as registerRetention, p as registerTable, Ct as relations, Tr as requireActors, g as requireTable, Er as requireTenants, oe as resetSnowflake, Li as residentPlacement, yi as resolveBranchMechanism, c as resolveFullTextIndex, m as resolveIdScheme, d as resolveMixinGraph, Fi as resolveTenantHome, dn as resolveTenantNamespace, ha as retentionTtlMsFromEnv, o as rowNumber, _t as rowSchema, un as sanitizeIdentifierFragment, lt as serializeArraysForWrite, Mi as setResidencyConfig, Hr as spatialPredicate, ai as streamTable, v as sum, De as sumOver, ma as sweepRetention, w as table, Ei as teardownBranch, y as text, D as timestamp, tt as timestampMs, nt as timestampMsOrNull, t as union, Ee as unionAll, ve as validateColumnName, We as validateIndexName, Lt as validateRegisteredRelations, At as validateRelationConfig, Ne as validateTableName, Be as validateTypeIdPrefix, n as vector, f as vectorDistanceToOpclass, ci as vectorEmbedding, Ve as view, me as viewSql, ti as walkLeaves };