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