@voltro/database 0.10.0 → 0.11.1

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