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