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