@voltro/database 0.22.1 → 0.23.0

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