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