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