@voltro/database 0.44.1 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as ee, It as te, J as _, Jt as v, K as ne, Kt as y, L as re, Lt as b, M as ie, Mt as ae, N as oe, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, R as pe, Rt as x, S as me, St as he, T as ge, Tt as _e, U as ve, Ut as ye, V as be, Vt as xe, W as Se, Wt as Ce, X as we, Xt as Te, Y as Ee, Yt as S, Z as De, _ as Oe, _t as ke, a as Ae, at as je, b as Me, bt as Ne, c as Pe, ct as Fe, d as Ie, dt as Le, et as Re, f as ze, ft as Be, g as Ve, gt as He, h as Ue, ht as We, i as Ge, it as Ke, j as C, jt as qe, k as Je, kt as Ye, l as Xe, lt as Ze, m as Qe, mt as $e, n as et, nt as tt, o as nt, ot as rt, p as w, pt as it, q as at, qt as ot, rt as st, s as ct, st as lt, t as ut, tt as T, u as dt, ut as ft, v as pt, vt as mt, w as ht, wt as gt, x as _t, xt as vt, y as yt, yt as bt, z as xt, zt as St } from "./frameworkLiveTables-XPFqj8n3.js";
2
- import { timestampMs as Ct, timestampMsOrNull as wt } from "./wire.js";
3
- import { Cause as Tt, Chunk as Et, Data as Dt, Effect as E, Exit as Ot, Metric as D, MetricBoundaries as kt, Option as O, Runtime as At, Schedule as jt, Schema as k, Stream as Mt } from "effect";
4
- import { AsyncLocalStorage as Nt } from "node:async_hooks";
5
- import { TransactionConnection as Pt } from "@effect/sql/SqlClient";
6
- import { ansi as A } from "@voltro/logger";
7
- import { SqlClient as Ft } from "@effect/sql";
8
- import { createHash as It } from "node:crypto";
1
+ import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as ee, It as te, J as _, Jt as ne, K as re, Kt as v, L as ie, Lt as y, M as ae, Mt as oe, N as se, Nt as ce, O as le, Ot as ue, P as de, Pt as fe, Q as pe, R as me, Rt as b, S as he, St as ge, T as _e, Tt as ve, U as ye, Ut as be, V as xe, Vt as x, W as Se, Wt as Ce, X as we, Xt as S, Y as Te, Yt as C, Z as Ee, Zt as De, _ as Oe, _t as ke, a as Ae, at as je, b as Me, bt as Ne, c as Pe, ct as Fe, d as Ie, dt as Le, et as Re, f as ze, ft as Be, g as Ve, gt as He, h as Ue, ht as We, i as Ge, it as Ke, j as w, jt as qe, k as Je, kt as Ye, l as Xe, lt as Ze, m as Qe, mt as $e, n as et, nt as T, o as tt, ot as nt, p as E, pt as rt, q as it, qt as at, rt as ot, s as st, st as ct, t as lt, tt as ut, u as dt, ut as ft, v as pt, vt as mt, w as ht, wt as gt, x as _t, xt as vt, y as yt, yt as bt, z as xt, zt as D } from "./frameworkLiveTables-DNu6F6P8.js";
2
+ import { timestampMs as St, timestampMsOrNull as Ct } from "./wire.js";
3
+ import { Cause as O, Chunk as wt, Data as Tt, Effect as k, Exit as Et, Metric as A, MetricBoundaries as Dt, Option as j, Runtime as Ot, Schedule as kt, Schema as M, Stream as At } from "effect";
4
+ import { AsyncLocalStorage as jt } from "node:async_hooks";
5
+ import { createHash as Mt } from "node:crypto";
6
+ import { TransactionConnection as Nt } from "@effect/sql/SqlClient";
7
+ import { ansi as N } from "@voltro/logger";
8
+ import { SqlClient as Pt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n) => {
10
+ var Ft = (e) => typeof e == "string" && e !== "" ? e : null, It = async (e, t, n) => {
11
11
  if (t != null && t !== "") try {
12
12
  let r = (await e.query({
13
13
  table: "actors",
@@ -23,20 +23,20 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Lt(r.kind) ?? n,
27
- displayName: Lt(r.displayName),
28
- email: Lt(r.email)
26
+ type: Ft(r.kind) ?? n,
27
+ displayName: Ft(r.displayName),
28
+ email: Ft(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, zt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Bt = (e) => {
33
+ }, Lt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Rt = (e) => {
34
34
  let t = [];
35
35
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
36
36
  return t;
37
- }, Vt = (e, t, n) => {
38
- if (!zt(n) || !t) return e;
39
- let r = Bt(t);
37
+ }, zt = (e, t, n) => {
38
+ if (!Lt(n) || !t) return e;
39
+ let r = Rt(t);
40
40
  if (r.length === 0) return e;
41
41
  let i = { ...e };
42
42
  for (let e of r) {
@@ -44,9 +44,9 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Ht = (e, t, n) => {
48
- if (!zt(n) || !t) return e;
49
- let r = Bt(t);
47
+ }, Bt = (e, t, n) => {
48
+ if (!Lt(n) || !t) return e;
49
+ let r = Rt(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,7 +58,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Ut = "enc:v1:", Wt = class extends Error {
61
+ }, Vt = "enc:v1:", Ht = class extends Error {
62
62
  _tag = "FieldDecryptionError";
63
63
  table;
64
64
  column;
@@ -66,7 +66,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
66
66
  constructor(e) {
67
67
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
68
68
  }
69
- }, Gt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Kt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), qt = (e, t) => e.encrypt(JSON.stringify(t)), Jt = /* @__PURE__ */ new Set([
69
+ }, Ut = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Wt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Gt = (e, t) => e.encrypt(JSON.stringify(t)), Kt = /* @__PURE__ */ new Set([
70
70
  "text",
71
71
  "id",
72
72
  "reference",
@@ -74,51 +74,51 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
74
74
  "uuid",
75
75
  "email",
76
76
  "url"
77
- ]), Yt = (e, t, n) => {
77
+ ]), qt = (e, t, n) => {
78
78
  let r = e.decrypt(t), i;
79
79
  try {
80
80
  i = JSON.parse(r);
81
81
  } catch {
82
82
  return r;
83
83
  }
84
- return typeof i == "string" ? i : n === void 0 || Jt.has(n) ? r : i;
85
- }, Xt = (e, t, n) => {
84
+ return typeof i == "string" ? i : n === void 0 || Kt.has(n) ? r : i;
85
+ }, Jt = (e, t, n) => {
86
86
  let r = e.decrypt(t);
87
87
  try {
88
- return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Jt.has(n) ? !0 : void 0;
88
+ return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Kt.has(n) ? !0 : void 0;
89
89
  } catch {
90
90
  return !0;
91
91
  }
92
- }, Zt = (e, t) => e.fields[t]?.type, Qt = (e) => {
92
+ }, Yt = (e, t) => e.fields[t]?.type, Xt = (e) => {
93
93
  let t = [];
94
94
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
95
95
  return t;
96
- }, $t = (e, t, n) => {
96
+ }, Zt = (e, t, n) => {
97
97
  if (!t) return e;
98
- let r = Qt(t);
98
+ let r = Xt(t);
99
99
  if (r.length === 0) return e;
100
100
  let i = { ...e };
101
101
  for (let e of r) {
102
102
  let r = i[e];
103
- if (!(r == null || Kt(r))) {
103
+ if (!(r == null || Wt(r))) {
104
104
  if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
105
- i[e] = qt(n, r);
105
+ i[e] = Gt(n, r);
106
106
  }
107
107
  }
108
108
  return i;
109
- }, en = (e, t, n, r) => {
109
+ }, Qt = (e, t, n, r) => {
110
110
  if (!t) return e;
111
- let i = Qt(t);
111
+ let i = Xt(t);
112
112
  if (i.length === 0 || !n) return e;
113
113
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
114
114
  return e.map((e) => {
115
115
  let s;
116
116
  for (let c of i) {
117
117
  let i = e[c];
118
- if (Kt(i)) {
118
+ if (Wt(i)) {
119
119
  s ??= { ...e };
120
120
  try {
121
- s[c] = Yt(n, i, Zt(t, c));
121
+ s[c] = qt(n, i, Yt(t, c));
122
122
  } catch (e) {
123
123
  let t = String(e?.message ?? e);
124
124
  if (a === "null") {
@@ -129,7 +129,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
129
129
  });
130
130
  continue;
131
131
  }
132
- throw new Wt({
132
+ throw new Ht({
133
133
  table: o,
134
134
  column: c,
135
135
  reason: t
@@ -139,125 +139,125 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
139
139
  }
140
140
  return s ?? e;
141
141
  });
142
- }, tn = (e) => {
142
+ }, $t = (e) => {
143
143
  let t = e;
144
- for (let e = 0; e < 4 && At.isFiberFailure(t); e++) t = Tt.squash(t[At.FiberFailureCauseId]);
144
+ for (let e = 0; e < 4 && Ot.isFiberFailure(t); e++) t = O.squash(t[Ot.FiberFailureCauseId]);
145
145
  return t;
146
- }, nn = (e, t = 0) => {
147
- if (t >= 4 || !At.isFiberFailure(e)) return [e];
148
- let n = e[At.FiberFailureCauseId], r = [...Tt.failures(n), ...Tt.defects(n)];
149
- if (r.length === 0) return [Tt.squash(n)];
146
+ }, en = (e, t = 0) => {
147
+ if (t >= 4 || !Ot.isFiberFailure(e)) return [e];
148
+ let n = e[Ot.FiberFailureCauseId], r = [...O.failures(n), ...O.defects(n)];
149
+ if (r.length === 0) return [O.squash(n)];
150
150
  let i = [];
151
- for (let e of r.slice(0, 8)) i.push(...nn(e, t + 1));
151
+ for (let e of r.slice(0, 8)) i.push(...en(e, t + 1));
152
152
  return i;
153
- }, rn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, an = (e) => {
154
- let t = {}, n = [], r = tn(e);
153
+ }, tn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, nn = (e) => {
154
+ let t = {}, n = [], r = $t(e);
155
155
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
156
156
  let e = r;
157
- t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
157
+ t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
158
158
  let i = e.sqlMessage ?? e.detail;
159
159
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
160
160
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
161
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = e.cause;
161
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = $t(e.cause);
162
162
  }
163
163
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
164
- }, on = (e) => {
165
- let t = nn(e).map(an);
164
+ }, rn = (e) => {
165
+ let t = en(e).map(nn);
166
166
  if (t.length <= 1) return t[0] ?? {};
167
- let n = t.find(rn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
167
+ let n = t.find(tn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
168
168
  if (r.length === 0) return n;
169
169
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
170
170
  return {
171
171
  ...n,
172
172
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
173
173
  };
174
- }, sn = /^[A-Za-z_][A-Za-z0-9_$]*$/, j = (e) => e !== void 0 && e.length <= 128 && sn.test(e) ? e : void 0, cn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, M = (e, ...t) => {
174
+ }, an = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && an.test(e) ? e : void 0, on = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
175
175
  for (let n of t) {
176
176
  let t = n.exec(e);
177
177
  if (t?.[1] !== void 0) return t[1];
178
178
  }
179
- }, ln = (e, t) => {
179
+ }, sn = (e, t) => {
180
180
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
181
181
  if (n === "23503") {
182
- let t = j(e.dbConstraint);
182
+ let t = P(e.dbConstraint);
183
183
  return {
184
184
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
185
185
  ...t === void 0 ? {} : { constraint: t }
186
186
  };
187
187
  }
188
188
  if (n === "23505") {
189
- let t = j(e.dbConstraint);
189
+ let t = P(e.dbConstraint);
190
190
  return {
191
191
  kind: "unique",
192
192
  ...t === void 0 ? {} : { constraint: t }
193
193
  };
194
194
  }
195
195
  if (n === "23502") {
196
- let t = j(e.dbColumn);
196
+ let t = P(e.dbColumn);
197
197
  return {
198
198
  kind: "notNull",
199
199
  ...t === void 0 ? {} : { column: t }
200
200
  };
201
201
  }
202
202
  if (n === "23514") {
203
- let t = j(e.dbConstraint);
203
+ let t = P(e.dbConstraint);
204
204
  return {
205
205
  kind: "check",
206
206
  ...t === void 0 ? {} : { constraint: t }
207
207
  };
208
208
  }
209
209
  if (r === 1452 || r === 1451) {
210
- let e = j(M(o, /CONSTRAINT `([^`]+)`/));
210
+ let e = P(F(o, /CONSTRAINT `([^`]+)`/));
211
211
  return {
212
212
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
213
213
  ...e === void 0 ? {} : { constraint: e }
214
214
  };
215
215
  }
216
216
  if (r === 1062) {
217
- let e = j(cn(M(o, /for key '([^']+)'/)));
217
+ let e = P(on(F(o, /for key '([^']+)'/)));
218
218
  return {
219
219
  kind: "unique",
220
220
  ...e === void 0 ? {} : { constraint: e }
221
221
  };
222
222
  }
223
223
  if (r === 1048 || r === 1364) {
224
- let e = j(M(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
224
+ let e = P(F(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
225
225
  return {
226
226
  kind: "notNull",
227
227
  ...e === void 0 ? {} : { column: e }
228
228
  };
229
229
  }
230
230
  if (r === 3819 || r === 4025) {
231
- let e = j(M(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
231
+ let e = P(F(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
232
232
  return {
233
233
  kind: "check",
234
234
  ...e === void 0 ? {} : { constraint: e }
235
235
  };
236
236
  }
237
237
  if (i === 547) {
238
- let e = M(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = M(o, /CHECK constraint "([^"]+)"/);
238
+ let e = F(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = F(o, /CHECK constraint "([^"]+)"/);
239
239
  if (t !== void 0 && e === void 0) {
240
- let e = j(t);
240
+ let e = P(t);
241
241
  return {
242
242
  kind: "check",
243
243
  ...e === void 0 ? {} : { constraint: e }
244
244
  };
245
245
  }
246
- let n = /REFERENCE constraint/.test(o), r = j(e);
246
+ let n = /REFERENCE constraint/.test(o), r = P(e);
247
247
  return {
248
248
  kind: n ? "foreignKeyInUse" : "foreignKey",
249
249
  ...r === void 0 ? {} : { constraint: r }
250
250
  };
251
251
  }
252
252
  if (i === 2627 || i === 2601) {
253
- let e = j(M(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
253
+ let e = P(F(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
254
254
  return {
255
255
  kind: "unique",
256
256
  ...e === void 0 ? {} : { constraint: e }
257
257
  };
258
258
  }
259
259
  if (i === 515) {
260
- let e = j(M(o, /Cannot insert the value NULL into column '([^']+)'/));
260
+ let e = P(F(o, /Cannot insert the value NULL into column '([^']+)'/));
261
261
  return {
262
262
  kind: "notNull",
263
263
  ...e === void 0 ? {} : { column: e }
@@ -265,66 +265,77 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
265
265
  }
266
266
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
267
267
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
268
- let e = j(cn(M(o, /UNIQUE constraint failed: ([^,\s]+)/)));
268
+ let e = P(on(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
269
269
  return {
270
270
  kind: "unique",
271
271
  ...e === void 0 ? {} : { column: e }
272
272
  };
273
273
  }
274
274
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
275
- let e = j(cn(M(o, /NOT NULL constraint failed: ([^,\s]+)/)));
275
+ let e = P(on(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
276
276
  return {
277
277
  kind: "notNull",
278
278
  ...e === void 0 ? {} : { column: e }
279
279
  };
280
280
  }
281
281
  if (n === "SQLITE_CONSTRAINT_CHECK") {
282
- let e = j(M(a, /CHECK constraint failed: (.+)$/));
282
+ let e = P(F(a, /CHECK constraint failed: (.+)$/));
283
283
  return {
284
284
  kind: "check",
285
285
  ...e === void 0 ? {} : { constraint: e }
286
286
  };
287
287
  }
288
- }, un = (e) => {
289
- let t = ln(e)?.kind;
288
+ }, cn = (e) => {
289
+ let t = sn(e)?.kind;
290
290
  return t === "foreignKey" || t === "foreignKeyInUse";
291
- }, dn = (e) => {
291
+ }, ln = (e) => {
292
292
  let t = e.dbCode, n = e.dbErrno;
293
293
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
294
- }, fn = (e) => {
295
- let t = on(e), n = [
294
+ }, un = (e) => {
295
+ let t = rn(e), n = [
296
296
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
297
297
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
298
298
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
299
299
  t.dbSqlState === void 0 ? void 0 : `sqlState=${String(t.dbSqlState)}`,
300
- t.dbConstraint === void 0 ? void 0 : `constraint=${String(t.dbConstraint)}`
301
- ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0;
302
- if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ");
300
+ t.dbConstraint === void 0 ? void 0 : `constraint=${String(t.dbConstraint)}`,
301
+ t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
302
+ ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
303
+ if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
304
+ }, dn = (e) => Object.entries(e).map(([e, t]) => `${e}:${fn(t)}`).join(" "), fn = (e) => {
305
+ if (e === null) return "null";
306
+ if (e === void 0) return "undefined";
307
+ if (typeof e == "bigint") return "bigint";
308
+ if (typeof e != "object") return typeof e;
309
+ if (e instanceof Date) return Number.isNaN(e.getTime()) ? "Date(Invalid)" : "Date";
310
+ if (Array.isArray(e)) return "Array";
311
+ if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
312
+ let t = e.constructor?.name;
313
+ return typeof t == "string" && t !== "" ? t : "Object";
303
314
  }, pn = (e) => {
304
315
  let t = (() => {
305
316
  switch (e.type) {
306
317
  case "id":
307
318
  case "reference":
308
319
  case "text":
309
- case "enum": return k.String;
320
+ case "enum": return M.String;
310
321
  case "integer":
311
322
  case "real":
312
- case "decimal": return k.Number;
313
- case "boolean": return k.Boolean;
323
+ case "decimal": return M.Number;
324
+ case "boolean": return M.Boolean;
314
325
  case "timestamp":
315
- case "date": return Ct;
316
- case "bigint": return k.BigInt;
317
- case "bytes": return k.Uint8ArrayFromBase64;
318
- case "array": return k.Array(k.Unknown);
319
- case "interval": return k.String;
320
- default: return k.Unknown;
326
+ case "date": return St;
327
+ case "bigint": return M.BigInt;
328
+ case "bytes": return M.Uint8ArrayFromBase64;
329
+ case "array": return M.Array(M.Unknown);
330
+ case "interval": return M.String;
331
+ default: return M.Unknown;
321
332
  }
322
333
  })();
323
- return e.nullable === !0 ? k.NullOr(t) : t;
334
+ return e.nullable === !0 ? M.NullOr(t) : t;
324
335
  }, mn = (e, t) => {
325
336
  let n = new Set(t?.omit ?? []), r = {};
326
337
  for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = pn(i));
327
- return k.Struct(r);
338
+ return M.Struct(r);
328
339
  }, hn = (e) => typeof e == "function" ? e : () => e, gn = (e, t) => ({
329
340
  kind: "one",
330
341
  target: hn(e),
@@ -364,35 +375,35 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
364
375
  let t = e?.kind;
365
376
  return t === "one" || t === "many" || t === "manyToMany";
366
377
  });
367
- }, Cn = gn, wn = _n, Tn = vn, N = (e, t, n) => {
378
+ }, Cn = gn, wn = _n, Tn = vn, En = (e, t, n) => {
368
379
  let r = [];
369
380
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
370
381
  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>' }.`);
371
382
  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.`);
372
383
  return r[0];
373
- }, En = (e) => Object.keys(e.fields), Dn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), On = (e) => {
374
- let t = En(e);
384
+ }, Dn = (e) => Object.keys(e.fields), On = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), kn = (e) => {
385
+ let t = Dn(e);
375
386
  return t.length === 0 ? "<none>" : t.join(", ");
376
- }, kn = (e, t, n) => {
387
+ }, An = (e, t, n) => {
377
388
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
378
389
  if (n.kind === "manyToMany") {
379
390
  let t = n.through();
380
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Dn(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}': ${On(t)}.`);
391
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!On(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}': ${kn(t)}.`);
381
392
  return;
382
393
  }
383
394
  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.`);
384
- if (n.sourceKey !== void 0 && !Dn(e, n.sourceKey)) {
385
- let t = Dn(i, n.sourceKey);
386
- 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}': ${On(e)}.`));
395
+ if (n.sourceKey !== void 0 && !On(e, n.sourceKey)) {
396
+ let t = On(i, n.sourceKey);
397
+ 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}': ${kn(e)}.`));
387
398
  }
388
- if (n.foreignKey !== void 0 && !Dn(i, n.foreignKey)) {
389
- let t = Dn(e, n.foreignKey);
390
- 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}': ${On(i)}.`));
399
+ if (n.foreignKey !== void 0 && !On(i, n.foreignKey)) {
400
+ let t = On(e, n.foreignKey);
401
+ 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}': ${kn(i)}.`));
391
402
  }
392
- }, An = Symbol.for("@voltro/database/relationsRegistry"), jn = globalThis, P = jn[An] ?? (jn[An] = /* @__PURE__ */ new Map()), Mn = (e) => {
393
- let t = e.source(), n = P.get(t.tableName);
403
+ }, jn = Symbol.for("@voltro/database/relationsRegistry"), Mn = globalThis, I = Mn[jn] ?? (Mn[jn] = /* @__PURE__ */ new Map()), Nn = (e) => {
404
+ let t = e.source(), n = I.get(t.tableName);
394
405
  if (n === void 0) {
395
- P.set(t.tableName, new Map(Object.entries(e.relations)));
406
+ I.set(t.tableName, new Map(Object.entries(e.relations)));
396
407
  return;
397
408
  }
398
409
  for (let [r, i] of Object.entries(e.relations)) {
@@ -402,33 +413,33 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
402
413
  n.set(r, i);
403
414
  }
404
415
  }
405
- }, Nn = (e) => {
416
+ }, Pn = (e) => {
406
417
  let t = 0;
407
- for (let n of Object.values(e)) Sn(n) && (Mn(n), t += 1);
418
+ for (let n of Object.values(e)) Sn(n) && (Nn(n), t += 1);
408
419
  return t;
409
- }, Pn = (e) => {
410
- let t = P.get(e);
420
+ }, Fn = (e) => {
421
+ let t = I.get(e);
411
422
  if (t !== void 0) return Object.fromEntries(t);
412
- }, Fn = (e, t) => P.get(e)?.get(t), In = () => {
423
+ }, In = (e, t) => I.get(e)?.get(t), Ln = () => {
413
424
  let e = [];
414
- for (let [t, n] of P) for (let [r, i] of n) e.push({
425
+ for (let [t, n] of I) for (let [r, i] of n) e.push({
415
426
  source: t,
416
427
  name: r,
417
428
  relation: i
418
429
  });
419
430
  return e;
420
- }, Ln = () => {
421
- for (let [e, t] of P) {
431
+ }, Rn = () => {
432
+ for (let [e, t] of I) {
422
433
  let n = p(e);
423
- if (n !== void 0) for (let [e, r] of t) kn(n, e, r);
434
+ if (n !== void 0) for (let [e, r] of t) An(n, e, r);
424
435
  }
425
- }, Rn = () => {
426
- P.clear();
427
- }, zn = 4, Bn = (e) => Object.keys(e.fields), Vn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Hn = (e, t) => {
436
+ }, zn = () => {
437
+ I.clear();
438
+ }, Bn = 4, Vn = (e) => Object.keys(e.fields), Hn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Un = (e, t) => {
428
439
  let n = [];
429
440
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
430
441
  return n;
431
- }, Un = (e, t) => {
442
+ }, Wn = (e, t) => {
432
443
  let n = [];
433
444
  for (let r of t) {
434
445
  if (r.source !== e) continue;
@@ -445,7 +456,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
445
456
  } catch {
446
457
  continue;
447
458
  }
448
- if (!Vn(e, t.sourceKey)) continue;
459
+ if (!Hn(e, t.sourceKey)) continue;
449
460
  n.push({
450
461
  table: e.tableName,
451
462
  foreignKey: t.sourceKey,
@@ -454,24 +465,24 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
454
465
  continue;
455
466
  }
456
467
  if (t.sourceKey !== void 0) continue;
457
- let a = Hn(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
458
- o === void 0 || !Vn(i, o) || n.push({
468
+ let a = Un(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
469
+ o === void 0 || !Hn(i, o) || n.push({
459
470
  table: i.tableName,
460
471
  foreignKey: o,
461
472
  parentKey: "id"
462
473
  });
463
474
  }
464
475
  return n;
465
- }, Wn = (e, t) => {
476
+ }, Gn = (e, t) => {
466
477
  let n = [];
467
- for (let r of t) if (r.tableName !== e) for (let t of Hn(r, e)) n.push({
478
+ for (let r of t) if (r.tableName !== e) for (let t of Un(r, e)) n.push({
468
479
  table: r.tableName,
469
480
  foreignKey: t,
470
481
  parentKey: "id"
471
482
  });
472
483
  return n;
473
- }, Gn = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Kn = (e) => {
474
- let t = e.tables ?? h(), n = e.relations ?? In(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
484
+ }, Kn = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, qn = (e) => {
485
+ let t = e.tables ?? h(), n = e.relations ?? Ln(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
475
486
  if (!a.has(e.subjectTable)) return {
476
487
  subjectTable: e.subjectTable,
477
488
  paths: [],
@@ -486,11 +497,11 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
486
497
  hops: [],
487
498
  depth: 0,
488
499
  via: "relation"
489
- }, c = [s], l = /* @__PURE__ */ new Set([Gn(s)]), u = /* @__PURE__ */ new Set(), d = [s];
500
+ }, c = [s], l = /* @__PURE__ */ new Set([Kn(s)]), u = /* @__PURE__ */ new Set(), d = [s];
490
501
  for (let e = 1; e <= r; e++) {
491
502
  let r = [];
492
503
  for (let a of d) {
493
- let s = Un(a.table, n), d = Wn(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
504
+ let s = Wn(a.table, n), d = Gn(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
494
505
  for (let [t, n] of f) {
495
506
  if (i.has(t.table)) {
496
507
  o.push({
@@ -508,7 +519,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
508
519
  hops: [...a.hops, t],
509
520
  depth: e,
510
521
  via: n
511
- }, f = Gn(d);
522
+ }, f = Kn(d);
512
523
  l.has(f) || (l.add(f), c.push(d), r.push(d));
513
524
  }
514
525
  }
@@ -518,7 +529,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
518
529
  }
519
530
  d = r;
520
531
  }
521
- for (let e of d) (Un(e.table, n).length > 0 || Wn(e.table, t).length > 0) && o.push({
532
+ for (let e of d) (Wn(e.table, n).length > 0 || Gn(e.table, t).length > 0) && o.push({
522
533
  kind: "depth-truncated",
523
534
  table: e.table,
524
535
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -527,14 +538,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
527
538
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
528
539
  kind: "unreachable",
529
540
  table: n.tableName,
530
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Bn(n).join(", ")}`
541
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Vn(n).join(", ")}`
531
542
  });
532
543
  return {
533
544
  subjectTable: e.subjectTable,
534
545
  paths: c,
535
546
  limitations: o
536
547
  };
537
- }, qn = (e) => {
548
+ }, Jn = (e) => {
538
549
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
539
550
  for (let n of e.paths) {
540
551
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -542,7 +553,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
542
553
  }
543
554
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
544
555
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
545
- }, Jn = (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, Yn = (e) => {
556
+ }, Yn = (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, Xn = (e) => {
546
557
  if (e == null || typeof e != "string") return e;
547
558
  let t = e.trim();
548
559
  if (t.length === 0) return e;
@@ -553,7 +564,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
553
564
  } catch {
554
565
  return e;
555
566
  }
556
- }, Xn = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, Zn = (e) => {
567
+ }, Zn = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, Qn = (e) => {
557
568
  if (e == null || e instanceof Date) return e;
558
569
  if (typeof e == "string") {
559
570
  let t = new Date(e);
@@ -564,19 +575,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
564
575
  return isNaN(t.getTime()) ? e : t;
565
576
  }
566
577
  return e;
567
- }, Qn = (e, t, n) => {
578
+ }, $n = (e, t, n) => {
568
579
  if (e == null) return e;
569
580
  switch (t) {
570
- case "boolean": return n === "postgres" ? e : Jn(e);
581
+ case "boolean": return n === "postgres" ? e : Yn(e);
571
582
  case "json":
572
- case "array": return n === "postgres" ? e : Yn(e);
583
+ case "array": return n === "postgres" ? e : Xn(e);
573
584
  case "timestamp":
574
- case "date": return n === "sqlite" || n === "turso" ? Zn(e) : e;
585
+ case "date": return n === "sqlite" || n === "turso" ? Qn(e) : e;
575
586
  case "decimal":
576
- case "bigint": return Xn(e);
587
+ case "bigint": return Zn(e);
577
588
  default: return e;
578
589
  }
579
- }, $n = (e, t, n) => {
590
+ }, er = (e, t, n) => {
580
591
  if (e.length === 0) return e;
581
592
  let r = p(t);
582
593
  if (r === void 0) return e;
@@ -587,36 +598,36 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
587
598
  });
588
599
  return e.map((e) => {
589
600
  let t = { ...e };
590
- for (let { key: e, type: r } of a) e in t && (t[e] = Qn(t[e], r, n));
601
+ for (let { key: e, type: r } of a) e in t && (t[e] = $n(t[e], r, n));
591
602
  return t;
592
603
  });
593
- }, er = (e, t) => {
604
+ }, tr = (e, t) => {
594
605
  if (e == null) return e;
595
606
  switch (t) {
596
607
  case "json":
597
608
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
598
609
  default: return e;
599
610
  }
600
- }, tr = (e, t, n = ["json", "array"]) => {
611
+ }, nr = (e, t, n = ["json", "array"]) => {
601
612
  let r = p(t);
602
613
  if (r === void 0) return e;
603
614
  let i = r.fields, a = null;
604
615
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
605
- let n = er(e[t], r.type);
616
+ let n = tr(e[t], r.type);
606
617
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
607
618
  }
608
619
  return a ?? e;
609
- }, nr = class extends Error {
620
+ }, rr = class extends Error {
610
621
  _tag = "EagerCardinalityError";
611
622
  constructor(e) {
612
623
  super(e), this.name = "EagerCardinalityError";
613
624
  }
614
- }, rr = (e) => {
625
+ }, ir = (e) => {
615
626
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
616
627
  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.");
617
- }, ir = async (e, t, n, r) => {
628
+ }, ar = async (e, t, n, r) => {
618
629
  if (e.length === 0) return e;
619
- let i = Pn(n.tableName);
630
+ let i = Fn(n.tableName);
620
631
  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?`);
621
632
  let a = e.map((e) => ({ ...e }));
622
633
  for (let [e, o] of Object.entries(t)) {
@@ -625,36 +636,36 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
625
636
  let t = Object.keys(i).join(", ") || "<none>";
626
637
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
627
638
  }
628
- kn(n, e, t), await ar(a, e, t, o === !0 ? {} : o, n, r);
639
+ An(n, e, t), await or(a, e, t, o === !0 ? {} : o, n, r);
629
640
  }
630
641
  return a;
631
- }, ar = async (e, t, n, r, i, a) => {
642
+ }, or = async (e, t, n, r, i, a) => {
632
643
  switch (n.kind) {
633
644
  case "one":
634
- await or(e, t, n, r, i, a);
645
+ await sr(e, t, n, r, i, a);
635
646
  return;
636
647
  case "many":
637
- await sr(e, t, n, r, i, a);
648
+ await cr(e, t, n, r, i, a);
638
649
  return;
639
650
  case "manyToMany":
640
- await lr(e, t, n, r, i, a);
651
+ await ur(e, t, n, r, i, a);
641
652
  return;
642
653
  }
643
- }, or = async (e, t, n, r, i, a) => {
644
- let o = n.target(), s = n.sourceKey ?? ur(i, o.tableName);
654
+ }, sr = async (e, t, n, r, i, a) => {
655
+ let o = n.target(), s = n.sourceKey ?? dr(i, o.tableName);
645
656
  if (s !== void 0) {
646
- let n = dr(e, s), i = n.length === 0 ? [] : await fr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
657
+ let n = fr(e, s), i = n.length === 0 ? [] : await pr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
647
658
  for (let n of e) {
648
659
  let e = n[s];
649
660
  n[t] = e == null ? null : c.get(e) ?? null;
650
661
  }
651
- await pr(i, r.with, o, a);
662
+ await mr(i, r.with, o, a);
652
663
  return;
653
664
  }
654
- let c = n.foreignKey ?? N(o, i.tableName, t), l = n.sourceKey ?? "id", u = dr(e, l), d = u.length === 0 ? [] : await fr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
665
+ let c = n.foreignKey ?? En(o, i.tableName, t), l = n.sourceKey ?? "id", u = fr(e, l), d = u.length === 0 ? [] : await pr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
655
666
  for (let e of d) {
656
667
  let n = e[c];
657
- if (f.has(n)) throw new nr(rr({
668
+ if (f.has(n)) throw new rr(ir({
658
669
  relationName: t,
659
670
  sourceTableName: i.tableName,
660
671
  targetTableName: o.tableName,
@@ -667,9 +678,9 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
667
678
  let e = n[l];
668
679
  n[t] = e == null ? null : f.get(e) ?? null;
669
680
  }
670
- await pr(d, r.with, o, a);
671
- }, sr = async (e, t, n, r, i, a) => {
672
- let o = n.target(), s = n.foreignKey ?? N(o, i.tableName, t), c = n.sourceKey ?? "id", l = dr(e, c), u = cr(r), d = l.length === 0 ? [] : await fr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
681
+ await mr(d, r.with, o, a);
682
+ }, cr = async (e, t, n, r, i, a) => {
683
+ let o = n.target(), s = n.foreignKey ?? En(o, i.tableName, t), c = n.sourceKey ?? "id", l = fr(e, c), u = lr(r), d = l.length === 0 ? [] : await pr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
673
684
  for (let e of d) {
674
685
  let t = e[s], n = f.get(t);
675
686
  n ? n.push(e) : f.set(t, [e]);
@@ -685,12 +696,12 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
685
696
  let e = n[c];
686
697
  n[t] = f.get(e) ?? [];
687
698
  }
688
- await pr(d, r.with, o, a);
689
- }, cr = (e) => {
699
+ await mr(d, r.with, o, a);
700
+ }, lr = (e) => {
690
701
  let { limit: t, offset: n, ...r } = e;
691
702
  return r;
692
- }, lr = async (e, t, n, r, i, a) => {
693
- let o = n.target(), s = n.through(), c = dr(e, "id");
703
+ }, ur = async (e, t, n, r, i, a) => {
704
+ let o = n.target(), s = n.through(), c = fr(e, "id");
694
705
  if (c.length === 0) {
695
706
  for (let n of e) n[t] = [];
696
707
  return;
@@ -711,8 +722,8 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
711
722
  for (let n of e) n[t] = [];
712
723
  return;
713
724
  }
714
- let f = await fr(o, "id", dr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
715
- await pr(f, r.with, o, a);
725
+ let f = await pr(o, "id", fr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
726
+ await mr(f, r.with, o, a);
716
727
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
717
728
  for (let e of d) {
718
729
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -724,16 +735,16 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
724
735
  o ? o.push(a) : h.set(t, [a]);
725
736
  }
726
737
  for (let n of e) n[t] = h.get(n.id) ?? [];
727
- }, ur = (e, t) => {
728
- for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
729
738
  }, dr = (e, t) => {
739
+ for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
740
+ }, fr = (e, t) => {
730
741
  let n = /* @__PURE__ */ new Set();
731
742
  for (let r of e) {
732
743
  let e = r[t];
733
744
  e != null && n.add(e);
734
745
  }
735
746
  return [...n];
736
- }, fr = (e, t, n, r, i) => {
747
+ }, pr = (e, t, n, r, i) => {
737
748
  let a = {
738
749
  column: t,
739
750
  op: "in",
@@ -747,63 +758,63 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
747
758
  skip: r.offset,
748
759
  projection: void 0
749
760
  });
750
- }, pr = async (e, t, n, r) => {
751
- t !== void 0 && e.length !== 0 && (await ir(e, t, n, r)).forEach((t, n) => {
761
+ }, mr = async (e, t, n, r) => {
762
+ t !== void 0 && e.length !== 0 && (await ar(e, t, n, r)).forEach((t, n) => {
752
763
  let r = e[n];
753
764
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
754
765
  });
755
- }, mr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, hr = class extends Error {
766
+ }, hr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, gr = class extends Error {
756
767
  _tag = "TenantNamespaceUnresolved";
757
768
  constructor(e) {
758
769
  super(e), this.name = "TenantNamespaceUnresolved";
759
770
  }
760
- }, gr = class extends Error {
771
+ }, _r = class extends Error {
761
772
  _tag = "TenantNamespaceInvalid";
762
773
  constructor(e) {
763
774
  super(e), this.name = "TenantNamespaceInvalid";
764
775
  }
765
- }, _r = 63, vr = "tenant_", yr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), br = (e) => {
766
- if (e == null || e === "") throw new hr("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.");
767
- let t = yr(e);
768
- if (t.replace(/_/g, "") === "") throw new gr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
769
- let n = `${vr}${t}`;
770
- if (n.length > _r) throw new gr(`namespace '${n}' for tenant '${e}' exceeds the ${_r}-byte identifier limit. Use a shorter tenant id.`);
776
+ }, vr = 63, yr = "tenant_", br = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), xr = (e) => {
777
+ if (e == null || e === "") throw new gr("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.");
778
+ let t = br(e);
779
+ if (t.replace(/_/g, "") === "") throw new _r(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
780
+ let n = `${yr}${t}`;
781
+ if (n.length > vr) throw new _r(`namespace '${n}' for tenant '${e}' exceeds the ${vr}-byte identifier limit. Use a shorter tenant id.`);
771
782
  return n;
772
- }, xr = (e, t) => e === null ? t : `${e}.${t}`, Sr = /* @__PURE__ */ new Set(["timestamp", "date"]), Cr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, wr = (e, t) => {
773
- if (e === void 0 || t == null || !Sr.has(e) || t instanceof Date) return t;
783
+ }, Sr = (e, t) => e === null ? t : `${e}.${t}`, Cr = /* @__PURE__ */ new Set(["timestamp", "date"]), wr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Tr = (e, t) => {
784
+ if (e === void 0 || t == null || !Cr.has(e) || t instanceof Date) return t;
774
785
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
775
- if (typeof t == "string" && Cr.test(t)) {
786
+ if (typeof t == "string" && wr.test(t)) {
776
787
  let e = new Date(t);
777
788
  return Number.isNaN(e.getTime()) ? t : e;
778
789
  }
779
790
  return t;
780
- }, Tr = (e, t) => e === void 0 || !Sr.has(e) ? t : t.map((t) => wr(e, t)), Er = (e, t) => {
791
+ }, Er = (e, t) => e === void 0 || !Cr.has(e) ? t : t.map((t) => Tr(e, t)), Dr = (e, t) => {
781
792
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
782
793
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
783
794
  return t`${i}`;
784
- }, Dr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), F = (e, t, n = null, r) => {
785
- if ("not" in e) return t`NOT (${F(e.not, t, n, r)})`;
786
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => F(e, t, n, r)));
787
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => F(e, t, n, r)));
795
+ }, Or = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
796
+ if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
797
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
798
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
788
799
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
789
- let r = e, i = Rr(r.subquery, t, n);
800
+ let r = e, i = zr(r.subquery, t, n);
790
801
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
791
802
  }
792
803
  if (e.op === "exists" || e.op === "not-exists") {
793
- let r = e, i = Rr(r.subquery, t, n);
804
+ let r = e, i = zr(r.subquery, t, n);
794
805
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
795
806
  }
796
807
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
797
- mysql: () => t.unsafe(w(i.column, o, "mysql")),
798
- mssql: () => t.unsafe(w(i.column, o, "mssql")),
799
- sqlite: () => t.unsafe(w(i.column, o, "sqlite")),
800
- orElse: () => t.unsafe(w(i.column, o, "postgres"))
808
+ mysql: () => t.unsafe(E(i.column, o, "mysql")),
809
+ mssql: () => t.unsafe(E(i.column, o, "mssql")),
810
+ sqlite: () => t.unsafe(E(i.column, o, "sqlite")),
811
+ orElse: () => t.unsafe(E(i.column, o, "postgres"))
801
812
  }), l = () => t.onDialectOrElse({
802
- mysql: () => t.unsafe(w(i.column, o, "mysql", { numeric: !0 })),
803
- mssql: () => t.unsafe(w(i.column, o, "mssql", { numeric: !0 })),
804
- sqlite: () => t.unsafe(w(i.column, o, "sqlite", { numeric: !0 })),
805
- orElse: () => t.unsafe(w(i.column, o, "postgres", { numeric: !0 }))
806
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => wr(h, e);
813
+ mysql: () => t.unsafe(E(i.column, o, "mysql", { numeric: !0 })),
814
+ mssql: () => t.unsafe(E(i.column, o, "mssql", { numeric: !0 })),
815
+ sqlite: () => t.unsafe(E(i.column, o, "sqlite", { numeric: !0 })),
816
+ orElse: () => t.unsafe(E(i.column, o, "postgres", { numeric: !0 }))
817
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => Tr(h, e);
807
818
  switch (i.op) {
808
819
  case "eq": return t`${u} = ${f(g(i.value))}`;
809
820
  case "neq": return t`${u} <> ${f(g(i.value))}`;
@@ -820,7 +831,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
820
831
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
821
832
  }
822
833
  case "contains": {
823
- let e = `%${Dr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
834
+ let e = `%${Or(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
824
835
  return t.onDialectOrElse({
825
836
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
826
837
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -829,7 +840,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
829
840
  });
830
841
  }
831
842
  case "startsWith": {
832
- let e = `${Dr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
843
+ let e = `${Or(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
833
844
  return t.onDialectOrElse({
834
845
  mysql: () => t`${u} LIKE ${e}`,
835
846
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -877,13 +888,13 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
877
888
  });
878
889
  }
879
890
  }
880
- }, Or = (e, t) => {
891
+ }, kr = (e, t) => {
881
892
  let n = [];
882
893
  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}`);
883
- }, kr = (e, t) => t.csv(e.map((e) => {
894
+ }, Ar = (e, t) => t.csv(e.map((e) => {
884
895
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
885
896
  if (e.op.startsWith("window-")) {
886
- let r = Or(e.window ?? {}, t);
897
+ let r = kr(e.window ?? {}, t);
887
898
  switch (e.op) {
888
899
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
889
900
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -907,44 +918,44 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
907
918
  return t`${t(e.column)} AS ${t(e.alias)}`;
908
919
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
909
920
  }
910
- })), Ar = (e) => `[${e.join(",")}]`, jr = (e, t) => {
921
+ })), jr = (e) => `[${e.join(",")}]`, Mr = (e, t) => {
911
922
  if (e.queryVector === void 0) return null;
912
- let n = t(e.column), r = Ar(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
923
+ let n = t(e.column), r = jr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
913
924
  return t.onDialectOrElse({
914
925
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
915
926
  mssql: () => t`NULL`,
916
927
  sqlite: () => t`NULL`,
917
928
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
918
929
  });
919
- }, Mr = (e, t) => {
930
+ }, Nr = (e, t) => {
920
931
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
921
932
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
922
- }, Nr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Pr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Fr = (e, t) => `${t}_${e.indexName}_fts`, Ir = (e, t, n) => {
923
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Dr(e.query)}%`;
933
+ }, Pr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Fr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Ir = (e, t) => `${t}_${e.indexName}_fts`, Lr = (e, t, n) => {
934
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Or(e.query)}%`;
924
935
  return n.onDialectOrElse({
925
936
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
926
937
  sqlite: () => {
927
- let r = n(Fr(e, t));
938
+ let r = n(Ir(e, t));
928
939
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
929
940
  },
930
941
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
931
- orElse: () => n`${Pr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
942
+ orElse: () => n`${Fr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
932
943
  });
933
- }, Lr = (e, t, n) => {
934
- let r = `%${Dr(e.query)}%`;
944
+ }, Rr = (e, t, n) => {
945
+ let r = `%${Or(e.query)}%`;
935
946
  return n.onDialectOrElse({
936
947
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
937
948
  sqlite: () => {
938
- let r = n(Fr(e, t));
949
+ let r = n(Ir(e, t));
939
950
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
940
951
  },
941
952
  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}`),
942
- orElse: () => n`ts_rank(${Pr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
953
+ orElse: () => n`ts_rank(${Fr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
943
954
  });
944
- }, Rr = (e, t, n = null) => {
955
+ }, zr = (e, t, n = null) => {
945
956
  if (e.setOp && e.setOp.queries.length >= 2) {
946
- 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`(${Rr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
947
- if (C(e).length > 0 && a.push(t` ORDER BY ${t.csv(C(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
957
+ 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`(${zr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
+ if (w(e).length > 0 && a.push(t` ORDER BY ${t.csv(w(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
948
959
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
949
960
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
950
961
  }
@@ -954,7 +965,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
954
965
  }
955
966
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
956
967
  }
957
- let r = e.annClause === void 0 ? null : jr(e.annClause, t);
968
+ let r = e.annClause === void 0 ? null : Mr(e.annClause, t);
958
969
  e.spatialClause !== void 0 && t.onDialectOrElse({
959
970
  mysql: () => {
960
971
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -967,57 +978,57 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
967
978
  },
968
979
  orElse: () => t``
969
980
  });
970
- let i = e.spatialClause?.projectAs === void 0 ? null : Mr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? kr(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 ? Lr(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({
981
+ let i = e.spatialClause?.projectAs === void 0 ? null : Nr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Ar(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 ? Rr(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({
971
982
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
972
983
  mysql: () => t`DISTINCT `,
973
984
  mssql: () => t`DISTINCT `,
974
985
  sqlite: () => t`DISTINCT `
975
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(xr(n, e.table))}` : t`${t(xr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
986
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Sr(n, e.table))}` : t`${t(Sr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
976
987
  let r = e.kind === "inner" ? "INNER" : "LEFT";
977
- return t` ${t.unsafe(r)} JOIN ${t(xr(n, e.table))} AS ${t(e.alias)} ON ${F(e.on, t, n)}`;
978
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Ir(c, e.table, t), ee = [e.predicate ? F(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, v = e.having ? t` HAVING ${F(e.having, t, n, e.table)}` : t``, ne = e.skip !== void 0, y = [];
979
- r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${Nr(e.spatialClause, t)} DESC` : t`${Nr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
980
- for (let n of C(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
981
- let re = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : ne ? t.onDialectOrElse({
988
+ return t` ${t.unsafe(r)} JOIN ${t(Sr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
989
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Lr(c, e.table, t), ee = [e.predicate ? L(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ne = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, re = e.skip !== void 0, v = [];
990
+ r !== null && v.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && v.push(e.spatialClause.order === "desc" ? t`${Pr(e.spatialClause, t)} DESC` : t`${Pr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && v.push(t`${l} DESC`);
991
+ for (let n of w(e)) v.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
+ let ie = v.length > 0 ? t` ORDER BY ${t.csv(v)}` : re ? t.onDialectOrElse({
982
993
  mssql: () => t` ORDER BY (SELECT NULL)`,
983
994
  orElse: () => t``
984
- }) : t``, b = (e) => {
995
+ }) : t``, y = (e) => {
985
996
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
986
997
  return t.unsafe(String(e));
987
- }, ie = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Rr(e.descriptor, t, n)})`), ae = (e.ctes ?? []).some((e) => e.recursive === !0), oe = ie.length > 0 ? t`WITH ${t.unsafe(ae ? "RECURSIVE " : "")}${t.csv(ie)} ` : t``;
998
+ }, ae = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${zr(e.descriptor, t, n)})`), oe = (e.ctes ?? []).some((e) => e.recursive === !0), se = ae.length > 0 ? t`WITH ${t.unsafe(oe ? "RECURSIVE " : "")}${t.csv(ae)} ` : t``;
988
999
  return t.onDialectOrElse({
989
1000
  mssql: () => {
990
- let n = e.take !== void 0 && !ne ? t`TOP ${b(e.take)} ` : t``, r = ne ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
991
- return t`${oe}SELECT ${n}${f}${d} FROM ${h}${te}${_}${v}${re}${r}`;
1001
+ let n = e.take !== void 0 && !re ? t`TOP ${y(e.take)} ` : t``, r = re ? t` OFFSET ${y(e.skip)} ROWS FETCH NEXT ${y(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1002
+ return t`${se}SELECT ${n}${f}${d} FROM ${h}${te}${_}${ne}${ie}${r}`;
992
1003
  },
993
1004
  orElse: () => {
994
- let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = ne ? t` OFFSET ${b(e.skip)}` : t``;
995
- return t`${oe}SELECT ${f}${d} FROM ${h}${te}${_}${v}${re}${n}${r}`;
1005
+ let n = e.take === void 0 ? t`` : t` LIMIT ${y(e.take)}`, r = re ? t` OFFSET ${y(e.skip)}` : t``;
1006
+ return t`${se}SELECT ${f}${d} FROM ${h}${te}${_}${ne}${ie}${n}${r}`;
996
1007
  }
997
1008
  });
998
- }, zr = (e, t, n) => {
1009
+ }, Br = (e, t, n) => {
999
1010
  if (e.eager === void 0) return null;
1000
- let r = Hr(e.table, e.eager, e.sourceTable);
1011
+ let r = Ur(e.table, e.eager, e.sourceTable);
1001
1012
  if (r === null) return null;
1002
- let i = Yr(n, e, r, Jr(t, n));
1013
+ let i = Xr(n, e, r, Yr(t, n));
1003
1014
  return i === null ? null : {
1004
1015
  fragment: i,
1005
- decode: Qr(r, n)
1016
+ decode: $r(r, n)
1006
1017
  };
1007
- }, Br = (e) => e.relation.kind === "one" && e.fkSide === "target", Vr = (e) => ({
1018
+ }, Vr = (e) => e.relation.kind === "one" && e.fkSide === "target", Hr = (e) => ({
1008
1019
  ...e,
1009
1020
  branch: {
1010
1021
  ...e.branch,
1011
1022
  limit: 2
1012
1023
  }
1013
- }), Hr = (e, t, n) => {
1014
- let r = n ?? _(e), i = Pn(e);
1024
+ }), Ur = (e, t, n) => {
1025
+ let r = n ?? _(e), i = Fn(e);
1015
1026
  if (i === void 0) return null;
1016
1027
  let a = [];
1017
1028
  for (let [e, n] of Object.entries(t)) {
1018
1029
  let t = i[e];
1019
1030
  if (t === void 0) return null;
1020
- let o = Ur(e, t, r, n === !0 ? {} : n);
1031
+ let o = Wr(e, t, r, n === !0 ? {} : n);
1021
1032
  if (o === null) return null;
1022
1033
  a.push(o);
1023
1034
  }
@@ -1025,30 +1036,30 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1025
1036
  table: r,
1026
1037
  children: a
1027
1038
  };
1028
- }, Ur = (e, t, n, r) => {
1039
+ }, Wr = (e, t, n, r) => {
1029
1040
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1030
1041
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1031
1042
  else if (t.kind === "one") {
1032
- let r = t.sourceKey ?? qr(n, i.tableName);
1043
+ let r = t.sourceKey ?? Jr(n, i.tableName);
1033
1044
  if (r !== void 0) o = r, s = "source";
1034
1045
  else try {
1035
- o = t.foreignKey ?? N(i, n.tableName, e), s = "target";
1046
+ o = t.foreignKey ?? En(i, n.tableName, e), s = "target";
1036
1047
  } catch {
1037
1048
  return null;
1038
1049
  }
1039
1050
  } else try {
1040
- o = t.foreignKey ?? N(i, n.tableName, e), s = "target";
1051
+ o = t.foreignKey ?? En(i, n.tableName, e), s = "target";
1041
1052
  } catch {
1042
1053
  return null;
1043
1054
  }
1044
1055
  let c = r.with === void 0 ? [] : (() => {
1045
- let e = Pn(i.tableName);
1056
+ let e = Fn(i.tableName);
1046
1057
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
1047
1058
  let t = [];
1048
1059
  for (let [n, a] of Object.entries(r.with)) {
1049
1060
  let r = e?.[n];
1050
1061
  if (r === void 0) return null;
1051
- let o = Ur(n, r, i, a === !0 ? {} : a);
1062
+ let o = Wr(n, r, i, a === !0 ? {} : a);
1052
1063
  if (o === null) return null;
1053
1064
  t.push(o);
1054
1065
  }
@@ -1064,9 +1075,9 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1064
1075
  fkSide: s,
1065
1076
  branch: r,
1066
1077
  children: c,
1067
- junction: Wr(t, r)
1078
+ junction: Gr(t, r)
1068
1079
  };
1069
- }, Wr = (e, t) => {
1080
+ }, Gr = (e, t) => {
1070
1081
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1071
1082
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1072
1083
  return {
@@ -1078,35 +1089,35 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1078
1089
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1079
1090
  })
1080
1091
  };
1081
- }, Gr = (e) => `__j_${e}`, Kr = "__j", qr = (e, t) => {
1092
+ }, Kr = (e) => `__j_${e}`, qr = "__j", Jr = (e, t) => {
1082
1093
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1083
- }, Jr = (e, t) => {
1094
+ }, Yr = (e, t) => {
1084
1095
  let n = 0;
1085
1096
  return {
1086
1097
  sql: e,
1087
1098
  dialect: t,
1088
1099
  nextAlias: () => `__a${n++}`
1089
1100
  };
1090
- }, Yr = (e, t, n, r) => {
1101
+ }, Xr = (e, t, n, r) => {
1091
1102
  switch (e) {
1092
- case "postgres": return ti(t, n, r);
1103
+ case "postgres": return ni(t, n, r);
1093
1104
  case "sqlite":
1094
- case "turso": return li(t, n, r);
1105
+ case "turso": return ui(t, n, r);
1095
1106
  case "mysql":
1096
- case "mariadb": return yi(t, n, r);
1097
- case "mssql": return Ei(t, n, r);
1107
+ case "mariadb": return bi(t, n, r);
1108
+ case "mssql": return Di(t, n, r);
1098
1109
  }
1099
- }, Xr = (e, t) => t === "mssql" && !Zr.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Zr = /(?:Z|[+-]\d{2}:?\d{2})$/, Qr = (e, t) => {
1100
- let n = $r(e.table, e.children, t);
1110
+ }, Zr = (e, t) => t === "mssql" && !Qr.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Qr = /(?:Z|[+-]\d{2}:?\d{2})$/, $r = (e, t) => {
1111
+ let n = ei(e.table, e.children, t);
1101
1112
  return (e) => e.map((e) => {
1102
1113
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1103
1114
  return n(r);
1104
1115
  });
1105
- }, $r = (e, t, n) => {
1116
+ }, ei = (e, t, n) => {
1106
1117
  let r = [];
1107
1118
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1108
1119
  let i = t.map((e) => {
1109
- let t = $r(e.target, e.children, n), r = e.relation.kind === "one", i = Br(e), a = i ? rr({
1120
+ let t = ei(e.target, e.children, n), r = e.relation.kind === "one", i = Vr(e), a = i ? ir({
1110
1121
  relationName: e.relationName,
1111
1122
  sourceTableName: e.source.tableName,
1112
1123
  targetTableName: e.target.tableName,
@@ -1119,14 +1130,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1119
1130
  isSingle: r,
1120
1131
  fromOverFetch: i,
1121
1132
  cardinalityMessage: a,
1122
- junction: ei(e.junction, n)
1133
+ junction: ti(e.junction, n)
1123
1134
  };
1124
1135
  });
1125
1136
  return (e) => {
1126
1137
  let t = { ...e };
1127
1138
  for (let e of r) {
1128
1139
  let r = t[e];
1129
- typeof r == "string" && (t[e] = Xr(r, n));
1140
+ typeof r == "string" && (t[e] = Zr(r, n));
1130
1141
  }
1131
1142
  for (let e of i) {
1132
1143
  let n = t[e.name];
@@ -1136,7 +1147,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1136
1147
  }
1137
1148
  if (e.fromOverFetch) {
1138
1149
  let r = n;
1139
- if (r.length > 1) throw new nr(e.cardinalityMessage);
1150
+ if (r.length > 1) throw new rr(e.cardinalityMessage);
1140
1151
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1141
1152
  continue;
1142
1153
  }
@@ -1148,204 +1159,204 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1148
1159
  }
1149
1160
  return t;
1150
1161
  };
1151
- }, ei = (e, t) => {
1162
+ }, ti = (e, t) => {
1152
1163
  if (e === void 0) return;
1153
1164
  let n = new Set(e.dateColumns), r = e.requested;
1154
1165
  return (e) => {
1155
1166
  let i = e._junction ?? {}, a = {};
1156
1167
  for (let e of r) {
1157
1168
  let r = i[e];
1158
- a[e] = n.has(e) && typeof r == "string" ? Xr(r, t) : r;
1169
+ a[e] = n.has(e) && typeof r == "string" ? Zr(r, t) : r;
1159
1170
  }
1160
1171
  return {
1161
1172
  ...e,
1162
1173
  _junction: a
1163
1174
  };
1164
1175
  };
1165
- }, ti = (e, t, n) => {
1166
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ni(i, t.children, n);
1167
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``}${C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`}`;
1168
- }, ni = (e, t, n, r) => {
1169
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${z(Kr, i)}::text)`;
1176
+ }, ni = (e, t, n) => {
1177
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ri(i, t.children, n);
1178
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1179
+ }, ri = (e, t, n, r) => {
1180
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(qr, i)}::text)`;
1170
1181
  if (t.length === 0 && r === void 0) return a;
1171
1182
  let o = [];
1172
- r !== void 0 && o.push(i`${z("_junction", i)}, ${R(e, Kr, i)}`);
1183
+ r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, qr, i)}`);
1173
1184
  for (let r of t) {
1174
- let t = ri(r, e, n);
1185
+ let t = ii(r, e, n);
1175
1186
  if (t === null) return null;
1176
- o.push(i`${z(r.relationName, i)}, ${t}`);
1187
+ o.push(i`${V(r.relationName, i)}, ${t}`);
1177
1188
  }
1178
1189
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1179
- }, ri = (e, t, n) => {
1190
+ }, ii = (e, t, n) => {
1180
1191
  switch (e.relation.kind) {
1181
- case "one": return Br(e) ? ai(Vr(e), t, n) : ii(e, t, n);
1182
- case "many": return ai(e, t, n);
1183
- case "manyToMany": return oi(e, t, n);
1192
+ case "one": return Vr(e) ? oi(Hr(e), t, n) : ai(e, t, n);
1193
+ case "many": return oi(e, t, n);
1194
+ case "manyToMany": return si(e, t, n);
1184
1195
  }
1185
- }, ii = (e, t, n) => {
1186
- let r = n.sql, i = n.nextAlias(), a = ni(i, e.children, n);
1196
+ }, ai = (e, t, n) => {
1197
+ let r = n.sql, i = n.nextAlias(), a = ri(i, e.children, n);
1187
1198
  if (a === null) return null;
1188
- let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, c = I(i, e.branch.orderBy, r);
1199
+ let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
1189
1200
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1190
- }, ai = (e, t, n) => {
1191
- let r = n.sql, i = n.nextAlias(), a = ni(i, e.children, n);
1201
+ }, oi = (e, t, n) => {
1202
+ let r = n.sql, i = n.nextAlias(), a = ri(i, e.children, n);
1192
1203
  if (a === null) return null;
1193
- let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, c = ci(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1204
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1194
1205
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1195
- }, oi = (e, t, n) => {
1196
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ni(o, e.children, n, e.junction);
1206
+ }, si = (e, t, n) => {
1207
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ri(o, e.children, n, e.junction);
1197
1208
  if (c === null) return null;
1198
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, u = Pi(e, s, r), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${si(e.junction, s, r)} AS ${r(Kr)}`;
1199
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1200
- }, si = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t, e, n)}`))})`, I = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${R(e, t.column, n)} DESC` : n`${R(e, t.column, n)} ASC`))}`, ci = (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`))}`, li = (e, t, n) => {
1201
- let r = n.sql, i = n.nextAlias(), a = ui(i, t.table, t.children, n);
1209
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = Fi(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${ci(e.junction, s, r)} AS ${r(qr)}`;
1210
+ return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1211
+ }, ci = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, li = (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`))}`, ui = (e, t, n) => {
1212
+ let r = n.sql, i = n.nextAlias(), a = di(i, t.table, t.children, n);
1202
1213
  if (a === null) return null;
1203
- let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
1214
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1204
1215
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1205
- }, ui = (e, t, n, r, i) => {
1216
+ }, di = (e, t, n, r, i) => {
1206
1217
  let a = r.sql, o = [];
1207
- for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
1218
+ for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1208
1219
  if (i !== void 0) {
1209
- let e = di(i.projection, i.source, a);
1210
- o.push(a`${z("_junction", a)}, json_object(${e})`);
1220
+ let e = fi(i.projection, i.source, a);
1221
+ o.push(a`${V("_junction", a)}, json_object(${e})`);
1211
1222
  }
1212
1223
  for (let t of n) {
1213
- let n = hi(t, e, r);
1224
+ let n = gi(t, e, r);
1214
1225
  if (n === null) return null;
1215
- o.push(a`${z(t.relationName, a)}, ${n}`);
1226
+ o.push(a`${V(t.relationName, a)}, ${n}`);
1216
1227
  }
1217
1228
  return a`json_object(${a.csv(o)})`;
1218
- }, di = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t.alias, t.physical(e), n)}`)), fi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${R(t, e, n)} AS ${n(Gr(e))}`))}`, pi = (e) => ({
1229
+ }, fi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), pi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(Kr(e))}`))}`, mi = (e) => ({
1219
1230
  alias: e,
1220
- physical: Gr
1221
- }), mi = (e) => ({
1231
+ physical: Kr
1232
+ }), hi = (e) => ({
1222
1233
  alias: e,
1223
1234
  physical: (e) => e
1224
- }), hi = (e, t, n) => {
1235
+ }), gi = (e, t, n) => {
1225
1236
  switch (e.relation.kind) {
1226
- case "one": return Br(e) ? _i(Vr(e), t, n) : gi(e, t, n);
1227
- case "many": return _i(e, t, n);
1228
- case "manyToMany": return vi(e, t, n);
1237
+ case "one": return Vr(e) ? vi(Hr(e), t, n) : _i(e, t, n);
1238
+ case "many": return vi(e, t, n);
1239
+ case "manyToMany": return yi(e, t, n);
1229
1240
  }
1230
- }, gi = (e, t, n) => {
1231
- let r = n.sql, i = n.nextAlias(), a = ui(i, e.target, e.children, n);
1241
+ }, _i = (e, t, n) => {
1242
+ let r = n.sql, i = n.nextAlias(), a = di(i, e.target, e.children, n);
1232
1243
  if (a === null) return null;
1233
- let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1244
+ let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1234
1245
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1235
- }, _i = (e, t, n) => {
1236
- let r = n.sql, i = n.nextAlias(), a = ui(i, e.target, e.children, n);
1246
+ }, vi = (e, t, n) => {
1247
+ let r = n.sql, i = n.nextAlias(), a = di(i, e.target, e.children, n);
1237
1248
  if (a === null) return null;
1238
- let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = ci(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1249
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1239
1250
  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('[]'))`;
1240
- }, vi = (e, t, n) => {
1241
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ui(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1251
+ }, yi = (e, t, n) => {
1252
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = di(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1242
1253
  projection: e.junction,
1243
- source: pi(o)
1254
+ source: mi(o)
1244
1255
  });
1245
1256
  if (c === null) return null;
1246
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, u = Pi(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : fi(e.junction, s, r);
1247
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1248
- }, yi = (e, t, n) => {
1249
- let r = n.sql, i = n.nextAlias(), a = L(i, t.table, t.children, n);
1257
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = Fi(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1258
+ return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1259
+ }, bi = (e, t, n) => {
1260
+ let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1250
1261
  if (a === null) return null;
1251
- let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
1262
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1252
1263
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1253
- }, L = (e, t, n, r, i) => {
1264
+ }, z = (e, t, n, r, i) => {
1254
1265
  let a = r.sql, o = [];
1255
- for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
1266
+ for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1256
1267
  if (i !== void 0) {
1257
- let e = di(i.projection, i.source, a);
1258
- o.push(a`${z("_junction", a)}, JSON_OBJECT(${e})`);
1268
+ let e = fi(i.projection, i.source, a);
1269
+ o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1259
1270
  }
1260
1271
  for (let t of n) {
1261
- let n = bi(t, e, r);
1272
+ let n = xi(t, e, r);
1262
1273
  if (n === null) return null;
1263
- o.push(a`${z(t.relationName, a)}, ${n}`);
1274
+ o.push(a`${V(t.relationName, a)}, ${n}`);
1264
1275
  }
1265
1276
  return a`JSON_OBJECT(${a.csv(o)})`;
1266
- }, bi = (e, t, n) => {
1277
+ }, xi = (e, t, n) => {
1267
1278
  switch (e.relation.kind) {
1268
1279
  case "one":
1269
- if (Br(e)) {
1270
- let r = Vr(e);
1271
- return n.dialect === "mariadb" ? wi(r, t, n) : Si(r, t, n);
1280
+ if (Vr(e)) {
1281
+ let r = Hr(e);
1282
+ return n.dialect === "mariadb" ? Ti(r, t, n) : Ci(r, t, n);
1272
1283
  }
1273
- return xi(e, t, n);
1274
- case "many": return n.dialect === "mariadb" ? wi(e, t, n) : Si(e, t, n);
1275
- case "manyToMany": return n.dialect === "mariadb" ? Ti(e, t, n) : Ci(e, t, n);
1284
+ return Si(e, t, n);
1285
+ case "many": return n.dialect === "mariadb" ? Ti(e, t, n) : Ci(e, t, n);
1286
+ case "manyToMany": return n.dialect === "mariadb" ? Ei(e, t, n) : wi(e, t, n);
1276
1287
  }
1277
- }, xi = (e, t, n) => {
1278
- let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1288
+ }, Si = (e, t, n) => {
1289
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1279
1290
  if (a === null) return null;
1280
- let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1291
+ let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1281
1292
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1282
- }, Si = (e, t, n) => {
1283
- let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1293
+ }, Ci = (e, t, n) => {
1294
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1284
1295
  if (a === null) return null;
1285
- let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = ci(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1296
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1286
1297
  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())`;
1287
- }, Ci = (e, t, n) => {
1288
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = L(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1298
+ }, wi = (e, t, n) => {
1299
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1289
1300
  projection: e.junction,
1290
- source: pi(o)
1301
+ source: mi(o)
1291
1302
  });
1292
1303
  if (c === null) return null;
1293
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, u = Pi(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : fi(e.junction, s, r);
1294
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1295
- }, wi = (e, t, n) => {
1296
- let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1297
- if (a === null) return null;
1298
- let o = r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1299
- if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1300
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${R(i, "rn", r)} > ${B(d, r)} AND ${R(i, "rn", r)} <= ${B(d + u, r)}` : u === void 0 ? r` AND ${R(i, "rn", r)} > ${B(d, r)}` : r` AND ${R(i, "rn", r)} <= ${B(u, r)}`;
1301
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${R(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1304
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = Fi(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1305
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1302
1306
  }, Ti = (e, t, n) => {
1307
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1308
+ if (a === null) return null;
1309
+ let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1310
+ if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1311
+ let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1312
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1313
+ }, Ei = (e, t, n) => {
1303
1314
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1304
1315
  projection: e.junction,
1305
1316
  source: t
1306
- }, l = r`${R(s, i.sourceKey, r)} = ${R(t, "id", r)}`, u = r`${R(o, "id", r)} = ${R(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, f = Pi(e, s, r, !0), p = e.branch.orderBy ?? [];
1317
+ }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = Fi(e, s, r, !0), p = e.branch.orderBy ?? [];
1307
1318
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1308
- let t = L(o, e.target, e.children, n, c(mi(s)));
1309
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1319
+ let t = z(o, e.target, e.children, n, c(hi(s)));
1320
+ return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1310
1321
  }
1311
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r` ORDER BY ${R(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)} AND ${R(o, "rn", r)} <= ${B(g + h, r)}` : h === void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)}` : r` AND ${R(o, "rn", r)} <= ${B(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${V(H(e.branch.onJunction), s, r)}`, _ = L(o, e.target, e.children, n, c(pi(o)));
1322
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, _ = z(o, e.target, e.children, n, c(mi(o)));
1312
1323
  if (_ === null) return null;
1313
- let v = e.junction === void 0 ? r`` : fi(e.junction, s, r);
1314
- return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${R(o, "rn", r)}) FROM (SELECT ${r(o)}.*${v}, ${R(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${R(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${R(o, `__src_${i.sourceKey}`, r)} = ${R(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1315
- }, Ei = (e, t, n) => {
1316
- let r = n.sql, i = n.nextAlias(), a = Di(i, t.table, t.children, n);
1324
+ let ne = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1325
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1326
+ }, Di = (e, t, n) => {
1327
+ let r = n.sql, i = n.nextAlias(), a = Oi(i, t.table, t.children, n);
1317
1328
  if (a === null) return null;
1318
- let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1329
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1319
1330
  if (e.skip !== void 0) {
1320
- let t = C(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1321
- l = e.take === void 0 ? r`${t} OFFSET ${B(e.skip, r)} ROWS` : r`${t} OFFSET ${B(e.skip, r)} ROWS FETCH NEXT ${B(e.take, r)} ROWS ONLY`;
1322
- } else e.take !== void 0 && (c = r`TOP ${B(e.take, r)} `);
1331
+ let t = w(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1332
+ l = e.take === void 0 ? r`${t} OFFSET ${H(e.skip, r)} ROWS` : r`${t} OFFSET ${H(e.skip, r)} ROWS FETCH NEXT ${H(e.take, r)} ROWS ONLY`;
1333
+ } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1323
1334
  let u = e.skip === void 0 ? s : r``;
1324
1335
  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}`;
1325
- }, Di = (e, t, n, r, i) => {
1336
+ }, Oi = (e, t, n, r, i) => {
1326
1337
  let a = r.sql, o = [];
1327
- for (let n of Object.keys(t.fields)) o.push(a`${R(e, n, a)} AS ${a(n)}`);
1328
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${R(i.source.alias, i.source.physical(e), a)} AS ${Oi(`_junction.${e}`, a)}`);
1338
+ for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1339
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${ki(`_junction.${e}`, a)}`);
1329
1340
  for (let t of n) {
1330
- let n = ki(t, e, r);
1341
+ let n = Ai(t, e, r);
1331
1342
  if (n === null) return null;
1332
1343
  o.push(n);
1333
1344
  }
1334
1345
  return a.csv(o);
1335
- }, Oi = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ki = (e, t, n) => {
1346
+ }, ki = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Ai = (e, t, n) => {
1336
1347
  switch (e.relation.kind) {
1337
- case "one": return Br(e) ? Mi(Vr(e), t, n) : Ai(e, t, n);
1338
- case "many": return Mi(e, t, n);
1339
- case "manyToMany": return Ni(e, t, n);
1348
+ case "one": return Vr(e) ? Ni(Hr(e), t, n) : ji(e, t, n);
1349
+ case "many": return Ni(e, t, n);
1350
+ case "manyToMany": return Pi(e, t, n);
1340
1351
  }
1341
- }, Ai = (e, t, n) => {
1342
- let r = n.sql, i = n.nextAlias(), a = Di(i, e.target, e.children, n);
1352
+ }, ji = (e, t, n) => {
1353
+ let r = n.sql, i = n.nextAlias(), a = Oi(i, e.target, e.children, n);
1343
1354
  if (a === null) return null;
1344
- let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1355
+ let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1345
1356
  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)}`;
1346
- }, ji = (e, t, n) => {
1357
+ }, Mi = (e, t, n) => {
1347
1358
  if (e.offset !== void 0) {
1348
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${B(e.offset, n)} ROWS` : n`${r} OFFSET ${B(e.offset, n)} ROWS FETCH NEXT ${B(e.limit, n)} ROWS ONLY`;
1359
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
1349
1360
  return {
1350
1361
  top: n``,
1351
1362
  pagination: i,
@@ -1353,33 +1364,33 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1353
1364
  };
1354
1365
  }
1355
1366
  return {
1356
- top: e.limit === void 0 ? n`` : n`TOP ${B(e.limit, n)} `,
1367
+ top: e.limit === void 0 ? n`` : n`TOP ${H(e.limit, n)} `,
1357
1368
  pagination: n``,
1358
1369
  finalOrder: t
1359
1370
  };
1360
- }, Mi = (e, t, n) => {
1361
- let r = n.sql, i = n.nextAlias(), a = Di(i, e.target, e.children, n);
1362
- if (a === null) return null;
1363
- let o = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, s = I(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ji(e.branch, s, r);
1364
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1365
1371
  }, Ni = (e, t, n) => {
1366
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Di(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1372
+ let r = n.sql, i = n.nextAlias(), a = Oi(i, e.target, e.children, n);
1373
+ if (a === null) return null;
1374
+ let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Mi(e.branch, s, r);
1375
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1376
+ }, Pi = (e, t, n) => {
1377
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Oi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1367
1378
  projection: e.junction,
1368
- source: mi(s)
1379
+ source: hi(s)
1369
1380
  });
1370
1381
  if (c === null) return null;
1371
- let l = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, o, r)}`, u = Pi(e, s, r), d = I(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ji(e.branch, d, r);
1372
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1373
- }, R = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, z = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), B = (e, t) => {
1382
+ let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = Fi(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Mi(e.branch, d, r);
1383
+ return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1384
+ }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
1374
1385
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1375
1386
  return t.unsafe(String(e));
1376
- }, V = (e, t, n) => F(Fi(e, t), n), Pi = (e, t, n, r = !1) => {
1387
+ }, U = (e, t, n) => L(Ii(e, t), n), Fi = (e, t, n, r = !1) => {
1377
1388
  let i = e.branch.onJunction;
1378
- return i === void 0 ? n`` : n` AND ${V(r ? H(i) : i, t, n)}`;
1379
- }, Fi = (e, t) => {
1380
- if ("not" in e) return { not: Fi(e.not, t) };
1381
- if ("and" in e) return { and: e.and.map((e) => Fi(e, t)) };
1382
- if ("or" in e) return { or: e.or.map((e) => Fi(e, t)) };
1389
+ return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1390
+ }, Ii = (e, t) => {
1391
+ if ("not" in e) return { not: Ii(e.not, t) };
1392
+ if ("and" in e) return { and: e.and.map((e) => Ii(e, t)) };
1393
+ if ("or" in e) return { or: e.or.map((e) => Ii(e, t)) };
1383
1394
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1384
1395
  let n = e;
1385
1396
  return {
@@ -1393,99 +1404,99 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1393
1404
  ...n,
1394
1405
  column: `${t}.${n.column}`
1395
1406
  };
1396
- }, H = (e) => {
1397
- if ("not" in e) return { not: H(e.not) };
1398
- if ("and" in e) return { and: e.and.map((e) => H(e)) };
1399
- if ("or" in e) return { or: e.or.map((e) => H(e)) };
1407
+ }, W = (e) => {
1408
+ if ("not" in e) return { not: W(e.not) };
1409
+ if ("and" in e) return { and: e.and.map((e) => W(e)) };
1410
+ if ("or" in e) return { or: e.or.map((e) => W(e)) };
1400
1411
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1401
1412
  let t = e;
1402
1413
  return {
1403
1414
  ...t,
1404
- value: Ii(t.value)
1415
+ value: Li(t.value)
1405
1416
  };
1406
- }, Ii = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Ii(e)) : e, Li = Symbol.for("@voltro/database/coreTablesRegistry"), Ri = globalThis, zi = Ri[Li] ?? (Ri[Li] = {}), Bi = (e) => {
1407
- e.actors !== void 0 && (zi.actors = e.actors), e.tenants !== void 0 && (zi.tenants = e.tenants);
1408
- }, Vi = (e, t) => () => {
1417
+ }, Li = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Li(e)) : e, Ri = Symbol.for("@voltro/database/coreTablesRegistry"), zi = globalThis, Bi = zi[Ri] ?? (zi[Ri] = {}), Vi = (e) => {
1418
+ e.actors !== void 0 && (Bi.actors = e.actors), e.tenants !== void 0 && (Bi.tenants = e.tenants);
1419
+ }, Hi = (e, t) => () => {
1409
1420
  let n = e();
1410
1421
  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`);
1411
1422
  return n();
1412
- }, Hi = () => Vi(() => zi.actors, "actors"), Ui = () => Vi(() => zi.tenants, "tenants"), Wi = T("actors", {
1423
+ }, Ui = () => Hi(() => Bi.actors, "actors"), Wi = () => Hi(() => Bi.tenants, "tenants"), Gi = T("actors", {
1413
1424
  id: b(),
1414
- kind: v().oneOf([
1425
+ kind: C().oneOf([
1415
1426
  "user",
1416
1427
  "serviceAccount",
1417
1428
  "apiKey",
1418
1429
  "system"
1419
1430
  ]),
1420
- displayName: v().nullable(),
1431
+ displayName: C().nullable(),
1421
1432
  createdAt: S().default("now")
1422
- }), Gi = (e, t) => ({
1433
+ }), Ki = (e, t) => ({
1423
1434
  column: e,
1424
1435
  op: "eq",
1425
1436
  value: t
1426
- }), Ki = (e, t) => ({
1437
+ }), qi = (e, t) => ({
1427
1438
  column: e,
1428
1439
  op: "neq",
1429
1440
  value: t
1430
- }), qi = (e, t) => ({
1441
+ }), Ji = (e, t) => ({
1431
1442
  column: e,
1432
1443
  op: "gt",
1433
1444
  value: t
1434
- }), Ji = (e, t) => ({
1445
+ }), Yi = (e, t) => ({
1435
1446
  column: e,
1436
1447
  op: "gte",
1437
1448
  value: t
1438
- }), Yi = (e, t) => ({
1449
+ }), Xi = (e, t) => ({
1439
1450
  column: e,
1440
1451
  op: "lt",
1441
1452
  value: t
1442
- }), Xi = (e, t) => ({
1453
+ }), Zi = (e, t) => ({
1443
1454
  column: e,
1444
1455
  op: "lte",
1445
1456
  value: t
1446
- }), Zi = (e, t) => ({
1457
+ }), Qi = (e, t) => ({
1447
1458
  column: e,
1448
1459
  op: "in",
1449
1460
  value: t
1450
- }), Qi = (e, t) => ({
1461
+ }), $i = (e, t) => ({
1451
1462
  column: e,
1452
1463
  op: "notIn",
1453
1464
  value: t
1454
- }), $i = (e, t) => ({
1465
+ }), ea = (e, t) => ({
1455
1466
  column: e,
1456
1467
  op: "contains",
1457
1468
  value: t
1458
- }), ea = (e, t) => ({
1469
+ }), ta = (e, t) => ({
1459
1470
  column: e,
1460
1471
  op: "startsWith",
1461
1472
  value: t
1462
- }), ta = (e, t) => ({
1473
+ }), na = (e, t) => ({
1463
1474
  column: e,
1464
1475
  op: "arrayContains",
1465
1476
  value: t
1466
- }), na = (e, t) => ({
1477
+ }), ra = (e, t) => ({
1467
1478
  column: e,
1468
1479
  op: "arrayOverlaps",
1469
1480
  value: t
1470
- }), ra = (e, t) => ({
1481
+ }), ia = (e, t) => ({
1471
1482
  column: e,
1472
1483
  op: "arrayHas",
1473
1484
  value: t
1474
- }), ia = {
1485
+ }), aa = {
1475
1486
  column: "id",
1476
1487
  op: "in",
1477
1488
  value: []
1478
- }, aa = (e) => ({
1489
+ }, oa = (e) => ({
1479
1490
  column: e,
1480
1491
  op: "isNull"
1481
- }), oa = (e) => ({
1492
+ }), sa = (e) => ({
1482
1493
  column: e,
1483
1494
  op: "isNotNull"
1484
- }), sa = (e, t) => ({
1495
+ }), ca = (e, t) => ({
1485
1496
  column: e,
1486
1497
  op: "spatial",
1487
1498
  value: t
1488
- }), ca = (...e) => ({ and: e }), la = (...e) => ({ or: e }), ua = (e) => ({ not: e }), da = (e, ...t) => {
1499
+ }), la = (...e) => ({ and: e }), ua = (...e) => ({ or: e }), da = (e) => ({ not: e }), fa = (e, ...t) => {
1489
1500
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1490
1501
  let n = (n, r) => ({
1491
1502
  column: e,
@@ -1507,33 +1518,33 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1507
1518
  isNull: () => n("isNull"),
1508
1519
  isNotNull: () => n("isNotNull")
1509
1520
  };
1510
- }, fa = (e) => "descriptor" in e ? e.descriptor : e, pa = (e, t) => ({
1521
+ }, pa = (e) => "descriptor" in e ? e.descriptor : e, ma = (e, t) => ({
1511
1522
  column: e,
1512
1523
  op: "subquery-in",
1513
- subquery: fa(t)
1514
- }), ma = (e, t) => ({
1524
+ subquery: pa(t)
1525
+ }), ha = (e, t) => ({
1515
1526
  column: e,
1516
1527
  op: "subquery-not-in",
1517
- subquery: fa(t)
1518
- }), ha = (e) => ({
1519
- op: "exists",
1520
- subquery: fa(e)
1528
+ subquery: pa(t)
1521
1529
  }), ga = (e) => ({
1530
+ op: "exists",
1531
+ subquery: pa(e)
1532
+ }), _a = (e) => ({
1522
1533
  op: "not-exists",
1523
- subquery: fa(e)
1524
- }), _a = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), va = (e, t) => {
1534
+ subquery: pa(e)
1535
+ }), va = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), ya = (e, t) => {
1525
1536
  if (e == null || t == null) return null;
1526
1537
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1527
1538
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1528
- }, ya = (e, t, n = null) => {
1539
+ }, ba = (e, t, n = null) => {
1529
1540
  if (!t) return !1;
1530
- if ("not" in e) return !ya(e.not, t, n);
1541
+ if ("not" in e) return !ba(e.not, t, n);
1531
1542
  if ("and" in e) {
1532
- for (let r of e.and) if (!ya(r, t, n)) return !1;
1543
+ for (let r of e.and) if (!ba(r, t, n)) return !1;
1533
1544
  return !0;
1534
1545
  }
1535
1546
  if ("or" in e) {
1536
- for (let r of e.or) if (ya(r, t, n)) return !0;
1547
+ for (let r of e.or) if (ba(r, t, n)) return !0;
1537
1548
  return !1;
1538
1549
  }
1539
1550
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1550,14 +1561,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1550
1561
  }
1551
1562
  let r = e, i = t[r.column];
1552
1563
  switch (r.op) {
1553
- case "eq": return _a(i, r.value);
1554
- case "neq": return !_a(i, r.value);
1555
- case "gt": return (va(i, r.value) ?? -1) > 0;
1556
- case "gte": return (va(i, r.value) ?? -1) >= 0;
1557
- case "lt": return (va(i, r.value) ?? 1) < 0;
1558
- case "lte": return (va(i, r.value) ?? 1) <= 0;
1559
- case "in": return Array.isArray(r.value) && r.value.some((e) => _a(i, e));
1560
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => _a(i, e));
1564
+ case "eq": return va(i, r.value);
1565
+ case "neq": return !va(i, r.value);
1566
+ case "gt": return (ya(i, r.value) ?? -1) > 0;
1567
+ case "gte": return (ya(i, r.value) ?? -1) >= 0;
1568
+ case "lt": return (ya(i, r.value) ?? 1) < 0;
1569
+ case "lte": return (ya(i, r.value) ?? 1) <= 0;
1570
+ case "in": return Array.isArray(r.value) && r.value.some((e) => va(i, e));
1571
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => va(i, e));
1561
1572
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1562
1573
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1563
1574
  case "arrayContains": {
@@ -1573,17 +1584,17 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1573
1584
  case "isNotNull": return i != null;
1574
1585
  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.");
1575
1586
  }
1576
- }, ba = function* (e) {
1587
+ }, xa = function* (e) {
1577
1588
  if ("not" in e) {
1578
- yield* ba(e.not);
1589
+ yield* xa(e.not);
1579
1590
  return;
1580
1591
  }
1581
1592
  if ("and" in e) {
1582
- for (let t of e.and) yield* ba(t);
1593
+ for (let t of e.and) yield* xa(t);
1583
1594
  return;
1584
1595
  }
1585
1596
  if ("or" in e) {
1586
- for (let t of e.or) yield* ba(t);
1597
+ for (let t of e.or) yield* xa(t);
1587
1598
  return;
1588
1599
  }
1589
1600
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1593,46 +1604,46 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1593
1604
  kind: "exists",
1594
1605
  descriptor: e.subquery
1595
1606
  });
1596
- }, xa = function* (e, t = !0) {
1607
+ }, Sa = function* (e, t = !0) {
1597
1608
  if ("not" in e) {
1598
- yield* xa(e.not, !1);
1609
+ yield* Sa(e.not, !1);
1599
1610
  return;
1600
1611
  }
1601
1612
  if ("and" in e) {
1602
- for (let n of e.and) yield* xa(n, t);
1613
+ for (let n of e.and) yield* Sa(n, t);
1603
1614
  return;
1604
1615
  }
1605
1616
  if ("or" in e) {
1606
- for (let t of e.or) yield* xa(t, !1);
1617
+ for (let t of e.or) yield* Sa(t, !1);
1607
1618
  return;
1608
1619
  }
1609
1620
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1610
1621
  ...e,
1611
1622
  conjunctive: t
1612
1623
  });
1613
- }, Sa = (e, t) => ({
1624
+ }, Ca = (e, t) => ({
1614
1625
  ...t,
1615
1626
  ...e,
1616
1627
  origin: e.origin ?? "injected"
1617
- }), Ca = (e, t, n = {}) => ({
1628
+ }), wa = (e, t, n = {}) => ({
1618
1629
  table: e,
1619
1630
  op: "insert",
1620
1631
  old: null,
1621
1632
  new: t,
1622
1633
  ...n
1623
- }), wa = (e, t, n, r = {}) => ({
1634
+ }), Ta = (e, t, n, r = {}) => ({
1624
1635
  table: e,
1625
1636
  op: "update",
1626
1637
  old: t,
1627
1638
  new: n,
1628
1639
  ...r
1629
- }), Ta = (e, t, n = {}) => ({
1640
+ }), Ea = (e, t, n = {}) => ({
1630
1641
  table: e,
1631
1642
  op: "delete",
1632
1643
  old: t,
1633
1644
  new: null,
1634
1645
  ...n
1635
- }), Ea = (e, t, n = {}) => {
1646
+ }), Da = (e, t, n = {}) => {
1636
1647
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1637
1648
  return {
1638
1649
  table: e,
@@ -1647,67 +1658,67 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1647
1658
  },
1648
1659
  ...a
1649
1660
  };
1650
- }, Da = new Nt(), Oa = (e, t) => Da.run(e, t), ka = () => Da.getStore(), Aa = (e) => {
1651
- let t = e ?? Da.getStore();
1661
+ }, Oa = new jt(), ka = (e, t) => Oa.run(e, t), Aa = () => Oa.getStore(), ja = (e) => {
1662
+ let t = e ?? Oa.getStore();
1652
1663
  return t === void 0 ? {} : {
1653
1664
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1654
1665
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1655
1666
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1656
1667
  ...t.via === void 0 ? {} : { via: t.via }
1657
1668
  };
1658
- }, ja = (e) => {
1659
- let t = Da.getStore();
1660
- return t === void 0 ? e(void 0) : Da.run(t, () => e(t));
1661
- }, Ma = 3e4, Na = 1e4, U = /* @__PURE__ */ new Map(), W = 0, Pa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Fa = (e) => {
1662
- for (let [t, n] of U) {
1663
- let r = n.filter((t) => e - t.at < Ma);
1664
- W -= n.length - r.length, r.length === 0 ? U.delete(t) : r.length !== n.length && U.set(t, r);
1665
- }
1666
- }, Ia = (e, t) => {
1669
+ }, Ma = (e) => {
1670
+ let t = Oa.getStore();
1671
+ return t === void 0 ? e(void 0) : Oa.run(t, () => e(t));
1672
+ }, Na = 3e4, Pa = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Fa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Ia = (e) => {
1673
+ for (let [t, n] of G) {
1674
+ let r = n.filter((t) => e - t.at < Na);
1675
+ K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1676
+ }
1677
+ }, La = (e, t) => {
1667
1678
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1668
1679
  let n = Date.now();
1669
- if (W >= Na && Fa(n), W >= Na) return;
1670
- let r = U.get(e);
1671
- r === void 0 ? U.set(e, [{
1680
+ if (K >= Pa && Ia(n), K >= Pa) return;
1681
+ let r = G.get(e);
1682
+ r === void 0 ? G.set(e, [{
1672
1683
  attribution: t,
1673
1684
  at: n
1674
1685
  }]) : r.push({
1675
1686
  attribution: t,
1676
1687
  at: n
1677
- }), W += 1;
1678
- }, La = (e) => {
1679
- let t = U.get(e);
1688
+ }), K += 1;
1689
+ }, Ra = (e) => {
1690
+ let t = G.get(e);
1680
1691
  if (t === void 0 || t.length === 0) return;
1681
1692
  let n = t.shift();
1682
- if (--W, t.length === 0 && U.delete(e), !(Date.now() - n.at >= Ma)) return n.attribution;
1683
- }, Ra = (e) => (U.get(e)?.length ?? 0) > 0, G = /* @__PURE__ */ new Map(), za = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = 250, Ha = (e) => {
1684
- let t = za.get(e);
1693
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= Na)) return n.attribution;
1694
+ }, za = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = /* @__PURE__ */ new Map(), Ha = 250, Ua = (e) => {
1695
+ let t = Ba.get(e);
1685
1696
  if (t === void 0) return;
1686
- za.delete(e);
1687
- let n = Ba.get(e);
1688
- n !== void 0 && (clearTimeout(n), Ba.delete(e));
1697
+ Ba.delete(e);
1698
+ let n = Va.get(e);
1699
+ n !== void 0 && (clearTimeout(n), Va.delete(e));
1689
1700
  for (let e of t) e();
1690
- }, Ua = (e) => {
1691
- G.set(e, (G.get(e) ?? 0) + 1);
1692
1701
  }, Wa = (e) => {
1693
- let t = (G.get(e) ?? 0) - 1;
1702
+ q.set(e, (q.get(e) ?? 0) + 1);
1703
+ }, Ga = (e) => {
1704
+ let t = (q.get(e) ?? 0) - 1;
1694
1705
  if (t > 0) {
1695
- G.set(e, t);
1706
+ q.set(e, t);
1696
1707
  return;
1697
1708
  }
1698
- G.delete(e), Ha(e);
1699
- }, Ga = (e, t, n, r) => {
1700
- let i = n == null ? void 0 : Pa(e, t, n), a = () => r(i === void 0 ? void 0 : La(i));
1709
+ q.delete(e), Ua(e);
1710
+ }, Ka = (e, t, n, r) => {
1711
+ let i = n == null ? void 0 : Fa(e, t, n), a = () => r(i === void 0 ? void 0 : Ra(i));
1701
1712
  if (i === void 0) {
1702
1713
  a();
1703
1714
  return;
1704
1715
  }
1705
- if (Ra(i)) {
1716
+ if (za(i)) {
1706
1717
  a();
1707
1718
  return;
1708
1719
  }
1709
- let o = za.get(e);
1710
- if (o === void 0 && (G.get(e) ?? 0) === 0) {
1720
+ let o = Ba.get(e);
1721
+ if (o === void 0 && (q.get(e) ?? 0) === 0) {
1711
1722
  a();
1712
1723
  return;
1713
1724
  }
@@ -1715,82 +1726,82 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1715
1726
  o.push(a);
1716
1727
  return;
1717
1728
  }
1718
- za.set(e, [a]);
1719
- let s = setTimeout(() => Ha(e), Va);
1720
- typeof s == "object" && typeof s.unref == "function" && s.unref(), Ba.set(e, s);
1721
- }, Ka = () => {
1722
- U.clear(), W = 0, G.clear();
1723
- for (let e of Ba.values()) clearTimeout(e);
1724
- Ba.clear(), za.clear();
1725
- }, qa = () => W, K = /* @__PURE__ */ new Map(), Ja = (e, t) => {
1726
- K.set(e, {
1729
+ Ba.set(e, [a]);
1730
+ let s = setTimeout(() => Ua(e), Ha);
1731
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Va.set(e, s);
1732
+ }, qa = () => {
1733
+ G.clear(), K = 0, q.clear();
1734
+ for (let e of Va.values()) clearTimeout(e);
1735
+ Va.clear(), Ba.clear();
1736
+ }, Ja = () => K, Ya = 64, Xa = "\0", Za = 32, Qa = (e, ...t) => `${e}_${Mt("sha256").update(t.map(String).join(Xa)).digest("hex").slice(0, Za)}`, $a = (e) => e.length + 1 + Za, J = /* @__PURE__ */ new Map(), eo = (e, t) => {
1737
+ J.set(e, {
1727
1738
  recorder: t.recorder,
1728
1739
  tables: new Set(t.tables),
1729
1740
  ownTables: new Set(t.ownTables)
1730
1741
  });
1731
- }, Ya = (e) => {
1732
- K.delete(e);
1733
- }, Xa = () => K.clear(), Za = (e) => {
1734
- if (K.size === 0) return !1;
1735
- for (let t of K.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1742
+ }, to = (e) => {
1743
+ J.delete(e);
1744
+ }, no = () => J.clear(), ro = (e) => {
1745
+ if (J.size === 0) return !1;
1746
+ for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1736
1747
  return !1;
1737
- }, Qa = async (e, t) => {
1738
- if (K.size !== 0) {
1739
- for (let [n, r] of K.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1748
+ }, io = async (e, t) => {
1749
+ if (J.size !== 0) {
1750
+ for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1740
1751
  await r.recorder(e, t);
1741
1752
  } catch (e) {
1742
- let r = fn(e);
1753
+ let r = un(e);
1743
1754
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1744
1755
  }
1745
1756
  }
1746
- }, $a = kt.exponential({
1757
+ }, ao = Dt.exponential({
1747
1758
  start: 5e-4,
1748
1759
  factor: 2,
1749
1760
  count: 16
1750
- }), eo = D.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), to = D.histogram("voltro_db_query_duration_seconds", $a, "Database operation duration in seconds, by dialect and operation kind."), no = D.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), ro = D.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), io = D.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), ao = [], oo = /* @__PURE__ */ new Map(), so = /* @__PURE__ */ new Map(), co = /* @__PURE__ */ new Map(), lo = (e, t) => {
1751
- let n = `${e}\u0000${t}`, r = oo.get(n);
1761
+ }), oo = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), so = A.histogram("voltro_db_query_duration_seconds", ao, "Database operation duration in seconds, by dialect and operation kind."), co = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), lo = A.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), uo = A.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), fo = [], po = /* @__PURE__ */ new Map(), mo = /* @__PURE__ */ new Map(), ho = /* @__PURE__ */ new Map(), go = (e, t) => {
1762
+ let n = `${e}\u0000${t}`, r = po.get(n);
1752
1763
  if (r !== void 0) return r;
1753
- let i = (n) => D.tagged(D.tagged(n, "dialect", e), "op", t), a = {
1754
- count: i(eo),
1755
- duration: i(to),
1756
- errors: i(no)
1764
+ let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1765
+ count: i(oo),
1766
+ duration: i(so),
1767
+ errors: i(co)
1757
1768
  };
1758
- return oo.set(n, a), a;
1759
- }, uo = () => {
1760
- oo.clear(), so.clear(), co.clear();
1761
- }, fo = () => oo.size + so.size + co.size, po = /* @__PURE__ */ new Map(), mo = (e, t) => {
1762
- let n = Math.max(0, (po.get(e) ?? 0) + t);
1763
- n === 0 ? po.delete(e) : po.set(e, n);
1764
- let r = so.get(e);
1765
- r === void 0 && (r = D.tagged(ro, "dialect", e), so.set(e, r)), r.unsafeUpdate(n, ao);
1766
- }, ho = (e) => po.get(e) ?? 0, go = (e) => {
1767
- let t = lo(String(e.dialect), e.op);
1768
- t.count.unsafeUpdate(1, ao), t.duration.unsafeUpdate(e.durationMs / 1e3, ao), e.status === "error" && t.errors.unsafeUpdate(1, ao);
1769
- }, _o = async (e, t, n) => {
1769
+ return po.set(n, a), a;
1770
+ }, _o = () => {
1771
+ po.clear(), mo.clear(), ho.clear();
1772
+ }, vo = () => po.size + mo.size + ho.size, yo = /* @__PURE__ */ new Map(), bo = (e, t) => {
1773
+ let n = Math.max(0, (yo.get(e) ?? 0) + t);
1774
+ n === 0 ? yo.delete(e) : yo.set(e, n);
1775
+ let r = mo.get(e);
1776
+ r === void 0 && (r = A.tagged(lo, "dialect", e), mo.set(e, r)), r.unsafeUpdate(n, fo);
1777
+ }, xo = (e) => yo.get(e) ?? 0, So = (e) => {
1778
+ let t = go(String(e.dialect), e.op);
1779
+ t.count.unsafeUpdate(1, fo), t.duration.unsafeUpdate(e.durationMs / 1e3, fo), e.status === "error" && t.errors.unsafeUpdate(1, fo);
1780
+ }, Co = async (e, t, n) => {
1770
1781
  let r = performance.now(), i = String(e);
1771
- mo(i, 1);
1782
+ bo(i, 1);
1772
1783
  let a = "ok";
1773
1784
  try {
1774
1785
  return await n();
1775
1786
  } catch (e) {
1776
1787
  throw a = "error", e;
1777
1788
  } finally {
1778
- mo(i, -1), go({
1789
+ bo(i, -1), So({
1779
1790
  dialect: e,
1780
1791
  op: t,
1781
1792
  durationMs: performance.now() - r,
1782
1793
  status: a
1783
1794
  });
1784
1795
  }
1785
- }, vo = 3e5, yo = (e) => {
1796
+ }, wo = 3e5, To = (e) => {
1786
1797
  if (e == null || e === "") return;
1787
1798
  let t = Number(e);
1788
1799
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1789
- }, bo = (e, t = process.env) => yo(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? yo(e) ?? 3e5, xo = (e, t = {}) => {
1790
- let n = bo(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1800
+ }, Eo = (e, t = process.env) => To(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? To(e) ?? 3e5, Do = (e, t = {}) => {
1801
+ let n = Eo(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1791
1802
  return (t) => {
1792
- let a = `${t.dialect} ${t.reason}`, o = co.get(a);
1793
- o === void 0 && (o = D.tagged(D.tagged(io, "dialect", String(t.dialect)), "reason", t.reason), co.set(a, o)), o.unsafeUpdate(1, ao);
1803
+ let a = `${t.dialect} ${t.reason}`, o = ho.get(a);
1804
+ o === void 0 && (o = A.tagged(A.tagged(uo, "dialect", String(t.dialect)), "reason", t.reason), ho.set(a, o)), o.unsafeUpdate(1, fo);
1794
1805
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1795
1806
  table: t.table,
1796
1807
  dialect: String(t.dialect),
@@ -1804,24 +1815,24 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1804
1815
  }
1805
1816
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1806
1817
  };
1807
- }, So = (e) => {
1808
- if (Ot.isSuccess(e)) return e.value;
1809
- throw Tt.squash(e.cause);
1810
- }, Co = "10 millis", wo = 3, To = async (e) => {
1811
- let t = 0, n = E.suspend(() => {
1818
+ }, Oo = (e) => {
1819
+ if (Et.isSuccess(e)) return e.value;
1820
+ throw O.squash(e.cause);
1821
+ }, ko = "10 millis", Ao = 3, jo = async (e) => {
1822
+ let t = 0, n = k.suspend(() => {
1812
1823
  let n = ++t;
1813
- return e.withTransaction(E.flatMap(E.serviceOption(Pt), (t) => {
1814
- if (O.isNone(t)) return E.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1815
- let r = t.value, i = E.tryPromise({
1824
+ return e.withTransaction(k.flatMap(k.serviceOption(Nt), (t) => {
1825
+ if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1826
+ let r = t.value, i = k.tryPromise({
1816
1827
  try: () => e.body(r, n),
1817
1828
  catch: (e) => e
1818
1829
  });
1819
- return e.prepare === void 0 ? i : E.flatMap(e.prepare(r), () => i);
1820
- })).pipe(E.catchAllDefect((t) => e.isRetryable(t) ? E.fail(t) : E.die(t)));
1821
- }), r = jt.exponential(Co).pipe(jt.compose(jt.recurs(wo)), jt.whileInput(e.isRetryable)), i = n.pipe(E.retry(r), E.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1822
- return _o(e.dialect, "transaction", async () => So(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1823
- }, Eo = async (e) => {
1824
- let t = ka(), n = t === void 0 ? (e) => e() : (e) => Oa(t, e), r = await To({
1830
+ return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1831
+ })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1832
+ }), r = kt.exponential(ko).pipe(kt.compose(kt.recurs(Ao)), kt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1833
+ return Co(e.dialect, "transaction", async () => Oo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1834
+ }, Mo = async (e) => {
1835
+ let t = Aa(), n = t === void 0 ? (e) => e() : (e) => ka(t, e), r = await jo({
1825
1836
  ...e,
1826
1837
  body: (r) => {
1827
1838
  let i = e.makeView(r, t);
@@ -1832,14 +1843,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1832
1843
  }
1833
1844
  });
1834
1845
  return r.view.commitEvents(), r.result;
1835
- }, Do = class extends k.TaggedError()("VersionConflict", {
1836
- table: k.String,
1837
- id: k.String,
1838
- expected: k.Number,
1839
- actual: k.NullOr(k.Number)
1840
- }) {}, Oo = (e) => {
1846
+ }, No = class extends M.TaggedError()("VersionConflict", {
1847
+ table: M.String,
1848
+ id: M.String,
1849
+ expected: M.Number,
1850
+ actual: M.NullOr(M.Number)
1851
+ }) {}, Po = (e) => {
1841
1852
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1842
- }, ko = (e) => {
1853
+ }, Fo = (e) => {
1843
1854
  let { versionColumn: t, patch: n } = e;
1844
1855
  if (t === void 0) return {
1845
1856
  nextVersion: void 0,
@@ -1852,28 +1863,28 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1852
1863
  expected: i,
1853
1864
  patch: a
1854
1865
  };
1855
- }, Ao = (e) => {
1856
- if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Do({
1866
+ }, Io = (e) => {
1867
+ if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new No({
1857
1868
  table: e.table,
1858
1869
  id: e.id,
1859
1870
  expected: e.expected,
1860
1871
  actual: e.current
1861
1872
  });
1862
- }, jo = 1, Mo = "voltro/expires", No = () => st({
1863
- id: Mo,
1873
+ }, Lo = 1, Ro = "voltro/expires", zo = () => Ke({
1874
+ id: Ro,
1864
1875
  fields: { expiresAt: S().nullable() },
1865
1876
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1866
- }), Po = "voltro/localFirst", Fo = () => st({
1867
- id: Po,
1877
+ }), Bo = "voltro/localFirst", Vo = () => Ke({
1878
+ id: Bo,
1868
1879
  fields: {}
1869
- }), Io = (e) => e.appliedMixins.some((e) => e.id === Po), Lo = (e) => {
1880
+ }), Ho = (e) => e.appliedMixins.some((e) => e.id === Bo), Uo = (e) => {
1870
1881
  let t = [];
1871
- for (let n of Object.values(e)) Io(n) && t.push(n.tableName);
1882
+ for (let n of Object.values(e)) Ho(n) && t.push(n.tableName);
1872
1883
  return t;
1873
- }, Ro = class extends Dt.TaggedError("TableStreamError") {}, zo = 1e3, Bo = (e, t, n, r) => {
1874
- let i = O.match(r, {
1884
+ }, Wo = class extends Tt.TaggedError("TableStreamError") {}, Go = 1e3, Ko = (e, t, n, r) => {
1885
+ let i = j.match(r, {
1875
1886
  onNone: () => e.where,
1876
- onSome: (n) => e.where ? ca(e.where, qi(t, n)) : qi(t, n)
1887
+ onSome: (n) => e.where ? la(e.where, Ji(t, n)) : Ji(t, n)
1877
1888
  });
1878
1889
  return {
1879
1890
  table: e.table,
@@ -1888,19 +1899,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1888
1899
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1889
1900
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1890
1901
  };
1891
- }, Vo = (e, t) => {
1892
- let n = t.pk ?? "id", r = t.chunkSize ?? zo;
1893
- return Mt.paginateChunkEffect(O.none(), (i) => {
1894
- let a = E.tryPromise({
1895
- try: () => e.query(Bo(t, n, r, i)),
1896
- catch: (e) => new Ro({
1902
+ }, qo = (e, t) => {
1903
+ let n = t.pk ?? "id", r = t.chunkSize ?? Go;
1904
+ return At.paginateChunkEffect(j.none(), (i) => {
1905
+ let a = k.tryPromise({
1906
+ try: () => e.query(Ko(t, n, r, i)),
1907
+ catch: (e) => new Wo({
1897
1908
  table: t.table,
1898
1909
  cause: e
1899
1910
  })
1900
1911
  });
1901
- return (t.retry ? a.pipe(E.retry(t.retry)) : a).pipe(E.map((e) => [Et.fromIterable(e), e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1912
+ return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [wt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
1902
1913
  });
1903
- }, Ho = (e) => {
1914
+ }, Jo = (e) => {
1904
1915
  let t = e.alpha ?? .5;
1905
1916
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1906
1917
  return (n) => {
@@ -1927,17 +1938,17 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1927
1938
  }
1928
1939
  };
1929
1940
  };
1930
- }, Uo = async (e, t) => {
1941
+ }, Yo = async (e, t) => {
1931
1942
  let n = e.as ?? "embedding", r = t.row[e.from];
1932
1943
  if (typeof r != "string" || r.length === 0) return {};
1933
1944
  let i = await t.embed(r);
1934
1945
  return { [n]: i };
1935
- }, Wo = (e) => {
1946
+ }, Xo = (e) => {
1936
1947
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1937
- let t = e.as ?? "embedding", n = (t) => Uo(e, t);
1938
- return st({
1948
+ let t = e.as ?? "embedding", n = (t) => Yo(e, t);
1949
+ return Ke({
1939
1950
  id: "voltro/vectorEmbedding",
1940
- fields: { [t]: Te(e.dimensions) },
1951
+ fields: { [t]: De(e.dimensions) },
1941
1952
  ...e.index === !1 ? {} : { indexes: [{
1942
1953
  fields: [t],
1943
1954
  kind: "hnsw",
@@ -1952,19 +1963,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1952
1963
  beforeUpdate: n
1953
1964
  }
1954
1965
  });
1955
- }, Go = 63, Ko = "br_pr", q = class extends Error {
1966
+ }, Zo = 63, Qo = "br_pr", Y = class extends Error {
1956
1967
  _tag = "BranchNameInvalid";
1957
1968
  constructor(e) {
1958
1969
  super(e), this.name = "BranchNameInvalid";
1959
1970
  }
1960
- }, qo = (e, t) => {
1961
- if (!Number.isInteger(t) || t < 0) throw new q(`prNumber must be a non-negative integer, got ${String(t)}`);
1962
- let n = yr(e);
1963
- if (n.replace(/_/g, "") === "") throw new q(`app slug '${e}' has no usable identifier characters`);
1964
- let r = `${Ko}${t}_${n}`;
1965
- if (r.length > Go) throw new q(`branch namespace '${r}' exceeds the ${Go}-byte identifier limit — use a shorter app slug`);
1971
+ }, $o = (e, t) => {
1972
+ if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1973
+ let n = br(e);
1974
+ if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1975
+ let r = `${Qo}${t}_${n}`;
1976
+ if (r.length > Zo) throw new Y(`branch namespace '${r}' exceeds the ${Zo}-byte identifier limit — use a shorter app slug`);
1966
1977
  return r;
1967
- }, Jo = (e) => e.startsWith(Ko), Yo = {
1978
+ }, es = (e) => e.startsWith(Qo), ts = {
1968
1979
  requested: {
1969
1980
  provision: "provisioning",
1970
1981
  destroy: "destroying"
@@ -1983,19 +1994,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1983
1994
  fail: "failed"
1984
1995
  },
1985
1996
  destroyed: {}
1986
- }, Xo = class extends Error {
1997
+ }, ns = class extends Error {
1987
1998
  from;
1988
1999
  event;
1989
2000
  _tag = "BranchTransitionInvalid";
1990
2001
  constructor(e, t) {
1991
2002
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1992
2003
  }
1993
- }, Zo = (e, t) => {
1994
- let n = Yo[e][t];
1995
- if (n === void 0) throw new Xo(e, t);
2004
+ }, rs = (e, t) => {
2005
+ let n = ts[e][t];
2006
+ if (n === void 0) throw new ns(e, t);
1996
2007
  return n;
1997
- }, Qo = (e, t, n, r, i = [], a = []) => {
1998
- if (n === "copy" && (r === void 0 || r === "")) throw new q("seed 'copy' requires a parentNamespace to snapshot from");
2008
+ }, is = (e, t, n, r, i = [], a = []) => {
2009
+ if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
1999
2010
  let o = [{
2000
2011
  kind: "create-namespace",
2001
2012
  detail: e
@@ -2024,13 +2035,13 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2024
2035
  kind: "seed",
2025
2036
  detail: `run boot seeds into ${e}`
2026
2037
  }), o;
2027
- }, $o = (e) => {
2028
- if (!Jo(e)) throw new q(`refusing to plan teardown of '${e}' — not a branch namespace`);
2038
+ }, as = (e) => {
2039
+ if (!es(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2029
2040
  return [{
2030
2041
  kind: "drop-namespace",
2031
2042
  detail: e
2032
2043
  }];
2033
- }, es = (e) => {
2044
+ }, os = (e) => {
2034
2045
  if (e === void 0 || e === "") return !1;
2035
2046
  try {
2036
2047
  let t = new URL(e).hostname.toLowerCase();
@@ -2038,27 +2049,27 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2038
2049
  } catch {
2039
2050
  return /\bneon\.(tech|build)\b/i.test(e);
2040
2051
  }
2041
- }, ts = (e) => e.prefer === void 0 ? e.seed === "copy" && es(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, ns = (e, t = {}) => [{
2052
+ }, ss = (e) => e.prefer === void 0 ? e.seed === "copy" && os(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, cs = (e, t = {}) => [{
2042
2053
  kind: "neon-branch-create",
2043
2054
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2044
- }], rs = (e) => {
2045
- if (!Jo(e)) throw new q(`refusing to plan teardown of '${e}' — not a branch namespace`);
2055
+ }], ls = (e) => {
2056
+ if (!es(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2046
2057
  return [{
2047
2058
  kind: "neon-branch-delete",
2048
2059
  detail: e
2049
2060
  }];
2050
- }, is = (e) => e.mechanism === "neon-cow" ? ns(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Qo(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), as = (e, t) => e === "neon-cow" ? rs(t) : $o(t), os = (e, t, n) => {
2061
+ }, us = (e) => e.mechanism === "neon-cow" ? cs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : is(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ds = (e, t) => e === "neon-cow" ? ls(t) : as(t), fs = (e, t, n) => {
2051
2062
  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);
2052
2063
  return {
2053
2064
  evict: i,
2054
2065
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2055
2066
  };
2056
- }, ss = async (e, t) => {
2057
- let n = qo(e.appSlug, e.prNumber), r = ts({
2067
+ }, ps = async (e, t) => {
2068
+ let n = $o(e.appSlug, e.prNumber), r = ss({
2058
2069
  seed: e.seed,
2059
2070
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2060
2071
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2061
- }), i = is({
2072
+ }), i = us({
2062
2073
  mechanism: r,
2063
2074
  branchId: n,
2064
2075
  tableNames: e.tableNames,
@@ -2087,16 +2098,16 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2087
2098
  mechanism: r,
2088
2099
  steps: i
2089
2100
  };
2090
- }, cs = async (e, t, n) => {
2091
- let r = as(t, e);
2101
+ }, ms = async (e, t, n) => {
2102
+ let r = ds(t, e);
2092
2103
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2093
- }, ls = (e, t, n) => os(e, t, n), J = (e) => `"${e.replace(/"/g, "\"\"")}"`, us = {
2104
+ }, hs = (e, t, n) => fs(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, gs = {
2094
2105
  cascade: "CASCADE",
2095
2106
  restrict: "RESTRICT",
2096
2107
  setNull: "SET NULL",
2097
2108
  noAction: "NO ACTION"
2098
- }, Y = (e) => `'${e.replace(/'/g, "''")}'`, ds = (e, t) => {
2099
- let n = t.columns.map(Y).join(", ");
2109
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, _s = (e, t) => {
2110
+ let n = t.columns.map(Z).join(", ");
2100
2111
  return `DO $voltro_branch$
2101
2112
  DECLARE derived name;
2102
2113
  BEGIN
@@ -2105,11 +2116,11 @@ BEGIN
2105
2116
  JOIN pg_class i ON i.oid = x.indexrelid
2106
2117
  JOIN pg_class c ON c.oid = x.indrelid
2107
2118
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
2108
- WHERE nsp.nspname = ${Y(e)}
2109
- AND c.relname = ${Y(t.table)}
2119
+ WHERE nsp.nspname = ${Z(e)}
2120
+ AND c.relname = ${Z(t.table)}
2110
2121
  AND NOT x.indisprimary
2111
2122
  AND x.indisunique = ${t.unique ? "true" : "false"}
2112
- AND i.relname <> ${Y(t.name)}
2123
+ AND i.relname <> ${Z(t.name)}
2113
2124
  AND (
2114
2125
  SELECT array_agg(att.attname::text ORDER BY k.ord)
2115
2126
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -2118,39 +2129,39 @@ BEGIN
2118
2129
  LIMIT 1;
2119
2130
  IF derived IS NOT NULL THEN
2120
2131
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
2121
- ${Y(e)}, derived, ${Y(t.name)});
2132
+ ${Z(e)}, derived, ${Z(t.name)});
2122
2133
  END IF;
2123
2134
  END
2124
2135
  $voltro_branch$`;
2125
- }, fs = (e, t) => {
2126
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${us[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${us[t.onUpdate]}`;
2127
- return `ALTER TABLE ${J(e)}.${J(t.table)} ADD FOREIGN KEY (${J(t.column)}) REFERENCES ${J(e)}.${J(t.targetTable)} (${J(t.targetColumn)})${n}${r}`;
2128
- }, ps = (e) => {
2136
+ }, vs = (e, t) => {
2137
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${gs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${gs[t.onUpdate]}`;
2138
+ return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2139
+ }, ys = (e) => {
2129
2140
  let t = () => {
2130
2141
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2131
2142
  };
2132
2143
  return {
2133
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${J(t)}`),
2134
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${J(t)}.${J(n)} (LIKE ${J(n)} INCLUDING ALL)`),
2135
- copyTable: (t, n, r) => e.run(`INSERT INTO ${J(n)}.${J(r)} SELECT * FROM ${J(t)}.${J(r)}`),
2136
- addForeignKey: (t, n) => e.run(fs(t, n)),
2137
- restoreIndexName: (t, n) => e.run(ds(t, n)),
2138
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${J(t)} CASCADE`),
2144
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2145
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2146
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2147
+ addForeignKey: (t, n) => e.run(vs(t, n)),
2148
+ restoreIndexName: (t, n) => e.run(_s(t, n)),
2149
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2139
2150
  neonBranchCreate: t,
2140
2151
  neonBranchDelete: t
2141
2152
  };
2142
- }, ms = class extends Error {
2153
+ }, bs = class extends Error {
2143
2154
  _tag = "TenantResidencyUnresolved";
2144
2155
  constructor(e) {
2145
2156
  super(e), this.name = "TenantResidencyUnresolved";
2146
2157
  }
2147
- }, hs = class extends Error {
2158
+ }, xs = class extends Error {
2148
2159
  region;
2149
2160
  _tag = "TenantRegionUnavailable";
2150
2161
  constructor(e, t) {
2151
2162
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2152
2163
  }
2153
- }, gs, _s = (e) => {
2164
+ }, Ss, Cs = (e) => {
2154
2165
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2155
2166
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2156
2167
  let t = /* @__PURE__ */ new Map();
@@ -2159,98 +2170,98 @@ $voltro_branch$`;
2159
2170
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2160
2171
  t.set(n.tenantId, n.region);
2161
2172
  }
2162
- return gs = e, e;
2163
- }, vs = () => gs, ys = () => {
2164
- gs = void 0;
2165
- }, bs = (e, t) => {
2166
- if (e == null || e === "") throw new ms("residency is on but the request has no resolvable tenant — refusing to bind a store");
2173
+ return Ss = e, e;
2174
+ }, ws = () => Ss, Ts = () => {
2175
+ Ss = void 0;
2176
+ }, Es = (e, t) => {
2177
+ if (e == null || e === "") throw new bs("residency is on but the request has no resolvable tenant — refusing to bind a store");
2167
2178
  let n = t.homes.find((t) => t.tenantId === e);
2168
- if (n === void 0) throw new ms(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2179
+ if (n === void 0) throw new bs(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2169
2180
  return n;
2170
- }, xs = (e, t) => t.servableRegions.includes(e), Ss = (e, t) => {
2171
- let n = bs(e.tenantId, t), r = br(n.tenantId);
2181
+ }, Ds = (e, t) => t.servableRegions.includes(e), Os = (e, t) => {
2182
+ let n = Es(e.tenantId, t), r = xr(n.tenantId);
2172
2183
  return {
2173
2184
  region: n.region,
2174
2185
  namespace: r,
2175
2186
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2176
2187
  };
2177
- }, Cs = (e, t, n) => {
2178
- let r = Ss(e, t);
2179
- if (!xs(r.region, t)) throw new hs(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2188
+ }, ks = (e, t, n) => {
2189
+ let r = Os(e, t);
2190
+ if (!Ds(r.region, t)) throw new xs(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2180
2191
  let i = n.get(r.region);
2181
- if (i === void 0) throw new hs(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2192
+ if (i === void 0) throw new xs(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2182
2193
  return {
2183
2194
  store: i,
2184
2195
  placement: r
2185
2196
  };
2186
- }, ws = async (e, t, n, r) => {
2187
- let { store: i, placement: a } = Cs(e, t, n);
2197
+ }, As = async (e, t, n, r) => {
2198
+ let { store: i, placement: a } = ks(e, t, n);
2188
2199
  return await r(i, a), a;
2189
- }, X = (e) => {
2200
+ }, js = (e) => {
2190
2201
  if (typeof e == "string") return e;
2191
2202
  if ("jsonPath" in e) {
2192
2203
  let { column: t, path: n, numeric: r } = e.jsonPath;
2193
2204
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2194
2205
  }
2195
2206
  return `(${e.expr})`;
2196
- }, Z = (e) => e.map(X), Ts = (e, t) => {
2207
+ }, Q = (e) => e.map(js), Ms = (e, t) => {
2197
2208
  if (e.length !== t.length) return !1;
2198
- for (let n = 0; n < e.length; n++) if (X(e[n]) !== X(t[n])) return !1;
2209
+ for (let n = 0; n < e.length; n++) if (js(e[n]) !== js(t[n])) return !1;
2199
2210
  return !0;
2200
- }, Es = (e, t) => {
2211
+ }, Ns = (e, t) => {
2201
2212
  if (e.length >= t.length) return !1;
2202
- for (let n = 0; n < e.length; n++) if (X(e[n]) !== X(t[n])) return !1;
2213
+ for (let n = 0; n < e.length; n++) if (js(e[n]) !== js(t[n])) return !1;
2203
2214
  return !0;
2204
- }, Ds = (e) => {
2215
+ }, Ps = (e) => {
2205
2216
  let t = [], n = e.appliedIndexes, r = e.tableName;
2206
2217
  for (let e = 0; e < n.length; e++) {
2207
2218
  let i = n[e];
2208
2219
  for (let a = e + 1; a < n.length; a++) {
2209
2220
  let e = n[a];
2210
- if (Ts(i.fields, e.fields)) {
2221
+ if (Ms(i.fields, e.fields)) {
2211
2222
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2212
2223
  t.push({
2213
2224
  kind: "duplicate-fields",
2214
2225
  table: r,
2215
2226
  redundant: n,
2216
2227
  coveredBy: a,
2217
- 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).`
2228
+ 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).`
2218
2229
  });
2219
2230
  continue;
2220
2231
  }
2221
- Es(i.fields, e.fields) ? t.push({
2232
+ Ns(i.fields, e.fields) ? t.push({
2222
2233
  kind: "redundant-prefix",
2223
2234
  table: r,
2224
2235
  redundant: i,
2225
2236
  coveredBy: e,
2226
- 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).`
2227
- }) : Es(e.fields, i.fields) && t.push({
2237
+ 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).`
2238
+ }) : Ns(e.fields, i.fields) && t.push({
2228
2239
  kind: "redundant-prefix",
2229
2240
  table: r,
2230
2241
  redundant: e,
2231
2242
  coveredBy: i,
2232
- 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).`
2243
+ 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).`
2233
2244
  });
2234
2245
  }
2235
2246
  }
2236
2247
  return t;
2237
- }, Os = (e) => {
2248
+ }, Fs = (e) => {
2238
2249
  let t = [];
2239
- for (let n of e) t.push(...Ds(n));
2250
+ for (let n of e) t.push(...Ps(n));
2240
2251
  return t;
2241
- }, ks = "\x1B[", As = `${ks}38;2;245;158;11m`, js = `${ks}38;2;16;185;129m`, Ms = (e, t) => `${e}${t}${A.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : Ms(t, n) : n, Ns = (e, t = {}) => {
2242
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, A.dim, e.padEnd(11)), a = (e) => Q(n, (e) => A.bold(A.brand(e)), e), o = (e) => Q(n, A.brightRed24, e), s = (e) => Q(n, js, e), c = (e) => Q(n, As, e), l = (e) => Q(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
2252
+ }, Is = "\x1B[", Ls = `${Is}38;2;245;158;11m`, Rs = `${Is}38;2;16;185;129m`, zs = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : zs(t, n) : n, Bs = (e, t = {}) => {
2253
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, N.dim, e.padEnd(11)), a = (e) => $(n, (e) => N.bold(N.brand(e)), e), o = (e) => $(n, N.brightRed24, e), s = (e) => $(n, Rs, e), c = (e) => $(n, Ls, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2243
2254
  let n = e.slice(0, t), r = e.slice(t), i = [];
2244
2255
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2245
2256
  }, m = [];
2246
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${Q(n, A.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2247
- }, Ps = (e, { apply: t, undo: n }) => ({
2257
+ 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, N.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");
2258
+ }, Vs = (e, { apply: t, undo: n }) => ({
2248
2259
  name: e,
2249
2260
  apply: t,
2250
2261
  undo: n
2251
- }), Fs = (e) => {
2262
+ }), Hs = (e) => {
2252
2263
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2253
- let t = e.steps({ step: Ps });
2264
+ let t = e.steps({ step: Vs });
2254
2265
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2255
2266
  return {
2256
2267
  __migration: !0,
@@ -2258,99 +2269,117 @@ $voltro_branch$`;
2258
2269
  name: e.name,
2259
2270
  steps: t
2260
2271
  };
2261
- }, Is = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Ls = T("_voltro_migrations", {
2272
+ }, Us = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Ws = T("_voltro_migrations", {
2262
2273
  id: b({ prefix: "mig" }),
2263
- name: v(),
2264
- hash: v(),
2265
- status: v(),
2274
+ name: C(),
2275
+ hash: C(),
2276
+ status: C(),
2266
2277
  appliedAt: S().nullable(),
2267
- durationMs: x().nullable(),
2268
- errorMessage: v().nullable(),
2269
- errorStack: v().nullable(),
2270
- workflowRunId: v().nullable(),
2278
+ durationMs: D().nullable(),
2279
+ errorMessage: C().nullable(),
2280
+ errorStack: C().nullable(),
2281
+ workflowRunId: C().nullable(),
2271
2282
  createdAt: S().default("now"),
2272
2283
  updatedAt: S().default("now").onUpdate("now")
2273
- }).index(["status"]), Rs = T("_voltro_seeds", {
2284
+ }).index(["status"]), Gs = T("_voltro_seeds", {
2274
2285
  id: b({ prefix: "seed" }),
2275
- name: v(),
2276
- lifecycle: v(),
2277
- fingerprint: v(),
2278
- cronSchedule: v().nullable(),
2279
- watchedTables: i().nullable(),
2286
+ name: C(),
2287
+ lifecycle: C(),
2288
+ fingerprint: C(),
2289
+ cronSchedule: C().nullable(),
2290
+ watchedTables: x().nullable(),
2280
2291
  nextRunAt: S().nullable(),
2281
- lastRunStatus: v().nullable(),
2292
+ lastRunStatus: C().nullable(),
2282
2293
  lastRunAt: S().nullable(),
2283
- lastRunDurationMs: x().nullable(),
2284
- lastRunRowsTouched: x().nullable(),
2285
- lastError: v().nullable(),
2286
- workflowRunId: v().nullable(),
2294
+ lastRunDurationMs: D().nullable(),
2295
+ lastRunRowsTouched: D().nullable(),
2296
+ lastError: C().nullable(),
2297
+ workflowRunId: C().nullable(),
2287
2298
  createdAt: S().default("now"),
2288
2299
  updatedAt: S().default("now").onUpdate("now")
2289
- }).index(["lifecycle"]).index(["nextRunAt"]), zs = T("_voltro_migration_plans", {
2300
+ }).index(["lifecycle"]).index(["nextRunAt"]), Ks = T("_voltro_migration_plans", {
2290
2301
  id: b({ prefix: "plan" }),
2291
- fingerprint: v(),
2292
- liveFingerprint: v().nullable(),
2293
- operations: i(),
2294
- rollbackPlan: i().nullable(),
2295
- appliedBy: v(),
2296
- environment: v(),
2297
- source: v(),
2298
- onlineStrategy: v().nullable(),
2299
- durationMs: x(),
2300
- notes: v().nullable(),
2302
+ fingerprint: C(),
2303
+ liveFingerprint: C().nullable(),
2304
+ operations: x(),
2305
+ rollbackPlan: x().nullable(),
2306
+ appliedBy: C(),
2307
+ environment: C(),
2308
+ source: C(),
2309
+ onlineStrategy: C().nullable(),
2310
+ durationMs: D(),
2311
+ notes: C().nullable(),
2301
2312
  squashedAt: S().nullable(),
2302
2313
  appliedAt: S().default("now"),
2303
2314
  createdAt: S().default("now"),
2304
2315
  updatedAt: S().default("now").onUpdate("now")
2305
- }).index(["fingerprint"]).index(["environment"]), Bs = T("_voltro_idempotency", {
2316
+ }).index(["fingerprint"]).index(["environment"]), qs = T("_voltro_idempotency", {
2306
2317
  id: b({ prefix: "idem" }),
2307
- scope: v(),
2308
- key: v(),
2309
- status: v(),
2310
- response: i().nullable(),
2318
+ scope: C(),
2319
+ key: C(),
2320
+ status: C(),
2321
+ response: x().nullable(),
2311
2322
  createdAt: S().default("now")
2312
- }).unique(["scope", "key"]).index(["createdAt"]), Vs = T("_voltro_kv", {
2323
+ }).unique(["scope", "key"]).index(["createdAt"]), Js = T("_voltro_kv", {
2313
2324
  id: b({ prefix: "kv" }),
2314
- key: v().unique(),
2315
- value: v().nullable(),
2325
+ key: C().unique(),
2326
+ value: C().nullable(),
2316
2327
  expiresAt: S().nullable(),
2317
2328
  createdAt: S().default("now"),
2318
2329
  updatedAt: S().default("now").onUpdate("now")
2319
- }).index(["expiresAt"]), Hs = T("_voltro_api_keys", {
2330
+ }).index(["expiresAt"]), Ys = T("_voltro_api_keys", {
2320
2331
  id: b({ prefix: "apikey" }),
2321
- tenantId: v().nullable(),
2322
- name: v(),
2323
- hashedKey: v().maxLength(64).unique(),
2324
- keyPrefix: v(),
2325
- scopes: i().nullable(),
2332
+ tenantId: C().nullable(),
2333
+ name: C(),
2334
+ hashedKey: C().maxLength(64).unique(),
2335
+ keyPrefix: C(),
2336
+ scopes: x().nullable(),
2326
2337
  lastUsedAt: S().nullable(),
2327
- requestCount: x().default(0),
2338
+ requestCount: D().default(0),
2328
2339
  expiresAt: S().nullable(),
2329
2340
  revokedAt: S().nullable(),
2330
- createdBy: v().nullable(),
2331
- onBehalfOf: v().nullable(),
2332
- metadata: i().nullable(),
2341
+ createdBy: C().nullable(),
2342
+ onBehalfOf: C().nullable(),
2343
+ metadata: x().nullable(),
2333
2344
  createdAt: S().default("now")
2334
- }).index("byApiKeyTenant", ["tenantId"]), Us = [
2335
- Ls,
2336
- Rs,
2337
- zs
2338
- ], $ = "id", Ws = (e, t) => {
2345
+ }).index("byApiKeyTenant", ["tenantId"]), Xs = [
2346
+ Ws,
2347
+ Gs,
2348
+ Ks
2349
+ ], Zs = "_voltro_replace_in_progress", Qs = T(Zs, {
2350
+ id: b({ prefix: "repl" }),
2351
+ startedAt: S().default("now"),
2352
+ tables: C(),
2353
+ capture: C().nullable(),
2354
+ via: C()
2355
+ }), $s = (e) => {
2356
+ if (e.length !== 0) return `refusing to start: a destructive import did not finish.
2357
+ ${e.map((e) => {
2358
+ let t = Number.isFinite(e.startedAt.getTime()) ? `${Math.max(0, Math.round((Date.now() - e.startedAt.getTime()) / 6e4))} minute(s) ago` : "at an unknown time";
2359
+ return ` - a \`replace\` over ${e.via} began emptying ${e.tables} table(s) ${t} and never reported finishing.\n` + (e.capture === null ? " NO capture was taken for that run, so the previous rows are not recoverable from here.\n Restore from your own backup." : ` The target's previous rows were captured first:\n ${e.capture}\n Restore them with: voltro data import ${e.capture} --mode replace`);
2360
+ }).join("\n")}\n
2361
+ A half-replaced database is indistinguishable from an empty one from the inside — every table
2362
+ exists, every constraint holds, and every query returns nothing without erroring. That is why
2363
+ this is a refusal and not a warning.
2364
+
2365
+ When the data is back, or you have decided the current state is correct, clear the marker:
2366
+ voltro data clear-replace-marker --yes`;
2367
+ }, ec = "id", tc = (e, t) => {
2339
2368
  let n = p(e);
2340
2369
  if (n === void 0) return t;
2341
- let r = n.fields[$]?.idScheme;
2342
- if (r === void 0 || t[$] != null) return t;
2370
+ let r = n.fields[ec]?.idScheme;
2371
+ if (r === void 0 || t[ec] != null) return t;
2343
2372
  if (r.kind === "numeric") {
2344
- if (!($ in t)) return t;
2373
+ if (!(ec in t)) return t;
2345
2374
  let e = { ...t };
2346
- return delete e[$], e;
2375
+ return delete e[ec], e;
2347
2376
  }
2348
- let i = lt(r, e);
2377
+ let i = Fe(r, e);
2349
2378
  return i === null ? t : {
2350
2379
  ...t,
2351
- [$]: i
2380
+ [ec]: i
2352
2381
  };
2353
- }, Gs = (e, t) => t.map((t) => Ws(e, t)), Ks = {
2382
+ }, nc = (e, t) => t.map((t) => tc(e, t)), rc = {
2354
2383
  postgres: { maxBindParameters: 65535 },
2355
2384
  mysql: { maxBindParameters: 65535 },
2356
2385
  mariadb: { maxBindParameters: 65535 },
@@ -2360,49 +2389,49 @@ $voltro_branch$`;
2360
2389
  },
2361
2390
  sqlite: { maxBindParameters: 32766 },
2362
2391
  turso: { maxBindParameters: 32766 }
2363
- }, qs = (e) => Ks[e], Js = (e) => {
2392
+ }, ic = (e) => rc[e], ac = (e) => {
2364
2393
  let t = /* @__PURE__ */ new Set();
2365
2394
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2366
2395
  return t.size;
2367
- }, Ys = (e, t) => {
2396
+ }, oc = (e, t) => {
2368
2397
  if (t === void 0 || e.length === 0) return [e];
2369
- let n = Math.max(1, Js(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2398
+ let n = Math.max(1, ac(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2370
2399
  if (e.length <= a) return [e];
2371
2400
  let o = [];
2372
2401
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2373
2402
  return o;
2374
- }, Xs = (e, t) => {
2403
+ }, sc = (e, t) => {
2375
2404
  let n = [], r = t;
2376
2405
  for (let [t, i] of Object.entries(e.fields)) {
2377
2406
  let e = i;
2378
2407
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2379
2408
  }
2380
2409
  return n;
2381
- }, Zs = (e, t) => {
2410
+ }, cc = (e, t) => {
2382
2411
  let n = t;
2383
2412
  return e.filter((e) => n[e] === void 0 || n[e] === null);
2384
- }, Qs = (e, t, n) => e.insert(t.tableName, n), $s = (e, t, n, r) => e.upsert(t.tableName, n, {
2413
+ }, lc = (e, t, n) => e.insert(t.tableName, n), uc = (e, t, n, r) => e.upsert(t.tableName, n, {
2385
2414
  conflictColumns: r.conflictColumns,
2386
2415
  ...r.update === void 0 ? {} : { update: r.update }
2387
- }), ec = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), tc = 512, nc = (e) => {
2416
+ }), dc = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), fc = 512, pc = (e) => {
2388
2417
  e.setMaxListeners(512);
2389
- }, rc = (e, t, n) => ({
2418
+ }, mc = (e, t, n) => ({
2390
2419
  _tag: "PrimaryKeyConflictError",
2391
2420
  table: e,
2392
2421
  key: t,
2393
2422
  cause: n
2394
- }), ic = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", ac = {
2423
+ }), hc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", gc = {
2395
2424
  postgres: 5432,
2396
2425
  mysql: 3306,
2397
2426
  mariadb: 3306,
2398
2427
  mssql: 1433
2399
- }, oc = /* @__PURE__ */ new Set([
2428
+ }, _c = /* @__PURE__ */ new Set([
2400
2429
  "localhost",
2401
2430
  "127.0.0.1",
2402
2431
  "::1",
2403
2432
  "[::1]",
2404
2433
  "0.0.0.0"
2405
- ]), sc = (e) => {
2434
+ ]), vc = (e) => {
2406
2435
  let t = e.host, n = e.port, r = e.database;
2407
2436
  if (e.url !== void 0 && e.url !== "") try {
2408
2437
  let i = new URL(e.url);
@@ -2411,29 +2440,29 @@ $voltro_branch$`;
2411
2440
  return;
2412
2441
  }
2413
2442
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2414
- let i = n ?? ac[(e.dialect ?? "").toLowerCase()];
2443
+ let i = n ?? gc[(e.dialect ?? "").toLowerCase()];
2415
2444
  if (i === void 0 || !Number.isFinite(i)) return;
2416
2445
  let a = t.toLowerCase();
2417
2446
  return {
2418
- host: oc.has(a) ? "localhost" : a,
2447
+ host: _c.has(a) ? "localhost" : a,
2419
2448
  port: i,
2420
2449
  database: r.toLowerCase()
2421
2450
  };
2422
- }, cc = (e) => {
2423
- let t = sc(e);
2424
- if (t !== void 0) return It("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2425
- }, lc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", uc = {
2451
+ }, yc = (e) => {
2452
+ let t = vc(e);
2453
+ if (t !== void 0) return Mt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2454
+ }, bc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", xc = {
2426
2455
  app: 3,
2427
2456
  plugin: 2,
2428
2457
  framework: 1
2429
- }, dc = /* @__PURE__ */ new Map(), fc = [], pc = () => [...fc], mc = (e) => {
2458
+ }, Sc = /* @__PURE__ */ new Map(), Cc = [], wc = () => [...Cc], Tc = (e) => {
2430
2459
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2431
2460
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2432
- let t = e.source ?? "app", n = dc.get(e.table);
2461
+ let t = e.source ?? "app", n = Sc.get(e.table);
2433
2462
  if (n !== void 0) {
2434
2463
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2435
- if (uc[t] < uc[r]) {
2436
- i && fc.push({
2464
+ if (xc[t] < xc[r]) {
2465
+ i && Cc.push({
2437
2466
  table: e.table,
2438
2467
  kept: {
2439
2468
  source: r,
@@ -2446,7 +2475,7 @@ $voltro_branch$`;
2446
2475
  });
2447
2476
  return;
2448
2477
  }
2449
- i && r !== t && fc.push({
2478
+ i && r !== t && Cc.push({
2450
2479
  table: e.table,
2451
2480
  kept: {
2452
2481
  source: t,
@@ -2458,35 +2487,35 @@ $voltro_branch$`;
2458
2487
  }
2459
2488
  });
2460
2489
  }
2461
- dc.set(e.table, {
2490
+ Sc.set(e.table, {
2462
2491
  ...e,
2463
2492
  source: t
2464
2493
  });
2465
- }, hc = () => [...dc.values()], gc = () => {
2466
- dc.clear(), fc.length = 0;
2467
- }, _c = async (e, t, n, r = 2e4) => {
2494
+ }, Ec = () => [...Sc.values()], Dc = () => {
2495
+ Sc.clear(), Cc.length = 0;
2496
+ }, Oc = async (e, t, n, r = 2e4) => {
2468
2497
  let i = new Date(t - e.ttlMs), a = 0;
2469
2498
  for (;;) {
2470
2499
  let t = await n(e.table, e.timeColumn, i, r, e.where);
2471
2500
  if (a += t, t < r) break;
2472
2501
  }
2473
2502
  return a;
2474
- }, vc = (e, t) => {
2503
+ }, kc = (e, t) => {
2475
2504
  let n = Number(e ?? String(t));
2476
2505
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2477
- }, yc = "_voltro_cdc_offsets", bc = T(yc, {
2506
+ }, Ac = "_voltro_cdc_offsets", jc = T(Ac, {
2478
2507
  id: b({ prefix: "cdcoff" }),
2479
- replicaId: v(),
2480
- streamName: v(),
2481
- binlogFile: v(),
2482
- binlogPosition: v(),
2508
+ replicaId: C(),
2509
+ streamName: C(),
2510
+ binlogFile: C(),
2511
+ binlogPosition: C(),
2483
2512
  updatedAt: S()
2484
- }).index(["replicaId"]), xc = T(yc, {
2513
+ }).index(["replicaId"]), Mc = T(Ac, {
2485
2514
  id: b({ prefix: "cdcoff" }),
2486
- replicaId: v(),
2487
- streamName: v(),
2488
- ctVersion: v(),
2515
+ replicaId: C(),
2516
+ streamName: C(),
2517
+ ctVersion: C(),
2489
2518
  updatedAt: S()
2490
- }).index(["replicaId"]), Sc = "postgres";
2519
+ }).index(["replicaId"]), Nc = "postgres";
2491
2520
  //#endregion
2492
- export { e as AUTO_FILLED_COLUMNS, Ks as BULK_INSERT_LIMITS, q as BranchNameInvalid, Xo as BranchTransitionInvalid, yc as CDC_OFFSETS_TABLE, tc as CHANGE_LISTENER_CEILING, gt as ColumnBuilder, Ee as DEFAULT_ACQUIRE_TIMEOUT_MS, vo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, zn as DEFAULT_SUBJECT_GRAPH_DEPTH, Ut as ENCRYPTED_PREFIX, Sc as ENGINE, nr as EagerCardinalityError, Ge as FILE_MIGRATION_PATTERN, ut as FRAMEWORK_LIVE_TABLES, Wt as FieldDecryptionError, jo as INITIAL_VERSION, ia as MATCHES_NO_ROWS, Le as MAX_IDENTIFIER_LENGTH, Ft as SqlClient, Ro as TableStreamError, gr as TenantNamespaceInvalid, hr as TenantNamespaceUnresolved, hs as TenantRegionUnavailable, ms as TenantResidencyUnresolved, Mo as VOLTRO_EXPIRES_MIXIN_ID, Po as VOLTRO_LOCAL_FIRST_MIXIN_ID, Do as VersionConflict, Be as WARN_IDENTIFIER_LENGTH, Hs as _voltroApiKeysTable, bc as _voltroCdcOffsetsTable, Bs as _voltroIdempotencyTable, Vs as _voltroKvTable, zs as _voltroMigrationPlansTable, Ls as _voltroMigrationsTable, xc as _voltroMssqlCdcOffsetsTable, Rs as _voltroSeedsTable, Wi as actorsTable, ls as admitBranch, mt as allEnumRenames, In as allRegisteredRelations, h as allRegisteredTables, ca as and, _e as array, ta as arrayContains, ra as arrayHas, na as arrayOverlaps, ir as attachEagerLoads, Aa as attributionFields, Pa as attributionKey, Os as auditAllTableIndexes, Ds as auditTableIndexes, pt as avg, yt as avgOver, Ua as beginLocalWrite, u as bigint, Cs as bindResidentStore, c as boolean, qo as branchNamespaceName, qs as bulkInsertLimitsFor, le as bytes, Ta as changeDelete, Ca as changeInsert, Ea as changeSoftDelete, wa as changeUpdate, Ys as chunkRowsForInsert, La as claimPendingAttribution, ln as classifyConstraintViolation, bt as clearEnumRenames, Ka as clearPendingAttribution, Rn as clearRelationsRegistry, ys as clearResidencyConfig, gc as clearRetentions, ve as clearTableRegistry, Xa as clearWriteRecorders, wr as coercePredicateValue, Tr as coercePredicateValues, ba as collectSubqueries, Me as column, pn as columnSchema, Js as columnsPerRow, zr as compileEagerJson, F as compilePredicate, Er as compileRawFragment, Rr as compileSelect, Uo as computeEmbedding, cc as connectionIdentity, $i as contains, _t as count, me as countDistinct, Ye as crdtManagedColumns, n as crdtText, ka as currentWriteAttribution, a as databaseHandle, qe as date, ae as dbEnum, fo as dbMetricTagCacheSizeForTests, ho as dbOperationsInFlight, se as decimal, Ne as declareEnumRename, Yt as decodeFieldValue, $n as decodeRowsFromSchema, en as decryptFieldsOnRead, Fs as defineMigration, st as defineMixin, ct as defineSeed, ht as denseRank, Kn as deriveSubjectGraph, rt as deriveTypeIdPrefix, fn as describeDriverError, Ht as deserializeArraysOnRead, it as drainIdentifierWarnings, de as dropped, qt as encodeFieldValue, tr as encodeRowForSchema, $t as encryptFieldsForWrite, Qt as encryptedColumnsOf, Wa as endLocalWrite, os as enforceBranchLimits, Se as ensureTableRegistered, Gi as eq, Dr as escapeLike, ya as evaluatePredicate, ge as except, ha as exists, No as expires, Sa as externalChangeEvent, on as extractDbCause, Pe as fireSchemaChangeSeeds, Xe as fireTenantCreateSeeds, Ns as formatIndexAuditIssue, qn as formatSubjectGraph, Us as frameworkTables, lt as generateId, Ze as generateSnowflake, f as geography, te as geometry, vt as getEnumRenames, Fn as getRelation, Pn as getRelations, vs as getResidencyConfig, p as getTable, qi as gt, Ji as gte, mr as hasEagerLoads, Ho as hybridSearch, b as id, Zi as inSet, pa as inSubquery, N as inferForeignKey, Qs as insertRow, x as integer, l as intersect, St as interval, Jo as isBranchNamespace, xn as isEmptyRelationsSpec, Kt as isEncrypted, Gt as isFieldDecryptionError, Ae as isFileMigration, un as isForeignKeyViolation, et as isFrameworkOwnedLiveTable, Io as isLocalFirst, Is as isMigrationDefinition, we as isMysqlFamily, es as isNeonConnection, oa as isNotNull, aa as isNull, ic as isPrimaryKeyConflictError, dn as isQueryTimeout, Xt as isRawEncoding, xs as isRegionServable, Sn as isRelationsSpec, dt as isSeedDefinition, De as isSqliteFamily, ne as isTableReactive, Qe as isView, i as json, da as jsonField, Re as jsonIndex, s as lag, ce as lead, pc as listRetentionConflicts, hc as listRetentions, Fo as localFirst, Lo as localFirstTables, Yi as lt, Xi as lte, xo as makeEagerFallbackReporter, ps as makeNamespaceBranchExecutor, wn as many, Tn as manyToMany, xe as materializeFields, Je as max, nt as migration, t as min, Zs as missingConflictColumns, Xs as missingRequiredColumns, Ke as mixin, Ki as neq, Zo as nextBranchState, sc as normaliseTarget, ua as not, ga as notExists, Qi as notInSet, ma as notInSubquery, g as numeric, _o as observeDbOp, Cn as one, rr as oneCardinalityMessage, la as or, C as orderClausesOf, ie as paginateBy, oe as paginateById, qa as pendingAttributionCount, is as planBranch, Qo as planBranchProvision, $o as planBranchTeardown, as as planBranchTeardownFor, ns as planNeonBranchProvision, rs as planNeonBranchTeardown, ko as planVersionedUpdate, he as pluginRef, o as pluginRefSpecOf, rc as primaryKeyConflictError, ss as provisionBranch, ws as provisionResidentTenant, xr as qualifyTable, ue as queryFor, Ue as queryForView, fe as quoteIdent, nc as raiseChangeListenerCeiling, d as rank, ye as raw, Ce as readableByColumns, m as real, go as recordDbOp, Za as recordsTable, y as reference, Bi as registerCoreTables, Nn as registerDiscoveredRelations, Ia as registerPendingAttribution, Mn as registerRelations, mc as registerRetention, at as registerTable, Ja as registerWriteRecorder, bn as relations, Hi as requireActors, _ as requireTable, Ui as requireTenants, uo as resetDbMetricTagCacheForTests, ft as resetSnowflake, Ss as residentPlacement, Rt as resolveActorSnapshot, ts as resolveBranchMechanism, bo as resolveEagerFallbackWarnIntervalMs, Ga as resolveEchoAttribution, ee as resolveFullTextIndex, Fe as resolveIdScheme, je as resolveMixinGraph, bs as resolveTenantHome, br as resolveTenantNamespace, vc as retentionTtlMsFromEnv, re as rowNumber, mn as rowSchema, To as runRetryingTransaction, Eo as runStoreTransaction, Oa as runWithWriteAttribution, Qa as runWriteRecorders, lc as sameDatabase, yr as sanitizeIdentifierFragment, Vt as serializeArraysForWrite, ot as serverOnlyColumns, _s as setResidencyConfig, Ie as setSchemaChangeSeedHook, ze as setTenantCreateSeedHook, So as settleTransactionExit, Ao as settleVersionedUpdate, sa as spatialPredicate, Ws as stampGeneratedId, Gs as stampGeneratedIds, ea as startsWith, Vo as streamTable, pe as sum, xt as sumOver, _c as sweepRetention, T as table, cs as teardownBranch, v as text, S as timestamp, Ct as timestampMs, wt as timestampMsOrNull, r as union, be as unionAll, Ya as unregisterWriteRecorder, ec as updateManyRow, $s as upsertRow, $e as validateColumnName, We as validateIndexName, Ln as validateRegisteredRelations, kn as validateRelationConfig, He as validateTableName, ke as validateTypeIdPrefix, Te as vector, tt as vectorDistanceToOpclass, Wo as vectorEmbedding, Oo as versionColumnOf, Ve as view, Oe as viewSql, xa as walkLeaves, ja as withCapturedAttribution };
2521
+ export { Re as AUTO_FILLED_COLUMNS, rc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, ns as BranchTransitionInvalid, Ac as CDC_OFFSETS_TABLE, fc as CHANGE_LISTENER_CEILING, ve as ColumnBuilder, we as DEFAULT_ACQUIRE_TIMEOUT_MS, wo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Bn as DEFAULT_SUBJECT_GRAPH_DEPTH, Vt as ENCRYPTED_PREFIX, Nc as ENGINE, rr as EagerCardinalityError, Ge as FILE_MIGRATION_PATTERN, lt as FRAMEWORK_LIVE_TABLES, Ht as FieldDecryptionError, Ya as ID_COLUMN_MAX_LENGTH, Lo as INITIAL_VERSION, aa as MATCHES_NO_ROWS, Be as MAX_IDENTIFIER_LENGTH, Zs as REPLACE_IN_PROGRESS_TABLE, Pt as SqlClient, Wo as TableStreamError, _r as TenantNamespaceInvalid, gr as TenantNamespaceUnresolved, xs as TenantRegionUnavailable, bs as TenantResidencyUnresolved, Ro as VOLTRO_EXPIRES_MIXIN_ID, Bo as VOLTRO_LOCAL_FIRST_MIXIN_ID, No as VersionConflict, rt as WARN_IDENTIFIER_LENGTH, Ys as _voltroApiKeysTable, jc as _voltroCdcOffsetsTable, qs as _voltroIdempotencyTable, Js as _voltroKvTable, Ks as _voltroMigrationPlansTable, Ws as _voltroMigrationsTable, Mc as _voltroMssqlCdcOffsetsTable, Qs as _voltroReplaceInProgressTable, Gs as _voltroSeedsTable, Gi as actorsTable, hs as admitBranch, bt as allEnumRenames, Ln as allRegisteredRelations, h as allRegisteredTables, la as and, u as array, na as arrayContains, ia as arrayHas, ra as arrayOverlaps, ar as attachEagerLoads, ja as attributionFields, Fa as attributionKey, Fs as auditAllTableIndexes, Ps as auditTableIndexes, pt as avg, yt as avgOver, Wa as beginLocalWrite, c as bigint, ks as bindResidentStore, ue as boolean, $o as branchNamespaceName, ic as bulkInsertLimitsFor, Ye as bytes, Ea as changeDelete, wa as changeInsert, Da as changeSoftDelete, Ta as changeUpdate, oc as chunkRowsForInsert, Ra as claimPendingAttribution, sn as classifyConstraintViolation, Ne as clearEnumRenames, qa as clearPendingAttribution, zn as clearRelationsRegistry, Ts as clearResidencyConfig, Dc as clearRetentions, ye as clearTableRegistry, no as clearWriteRecorders, Tr as coercePredicateValue, Er as coercePredicateValues, xa as collectSubqueries, Me as column, pn as columnSchema, ac as columnsPerRow, Br as compileEagerJson, L as compilePredicate, Dr as compileRawFragment, zr as compileSelect, Yo as computeEmbedding, yc as connectionIdentity, ea as contains, _t as count, he as countDistinct, n as crdtManagedColumns, qe as crdtText, Aa as currentWriteAttribution, a as databaseHandle, oe as date, ce as dbEnum, vo as dbMetricTagCacheSizeForTests, xo as dbOperationsInFlight, fe as decimal, vt as declareEnumRename, qt as decodeFieldValue, er as decodeRowsFromSchema, Qt as decryptFieldsOnRead, Hs as defineMigration, Ke as defineMixin, st as defineSeed, ht as denseRank, qn as deriveSubjectGraph, ct as deriveTypeIdPrefix, Qa as derivedRowId, $a as derivedRowIdLength, un as describeDriverError, dn as describeRowBindings, Bt as deserializeArraysOnRead, $e as drainIdentifierWarnings, f as dropped, Gt as encodeFieldValue, nr as encodeRowForSchema, Zt as encryptFieldsForWrite, Xt as encryptedColumnsOf, Ga as endLocalWrite, fs as enforceBranchLimits, Se as ensureTableRegistered, Ki as eq, Or as escapeLike, ba as evaluatePredicate, _e as except, ga as exists, zo as expires, Ca as externalChangeEvent, rn as extractDbCause, Pe as fireSchemaChangeSeeds, Xe as fireTenantCreateSeeds, Bs as formatIndexAuditIssue, Jn as formatSubjectGraph, Xs as frameworkTables, Fe as generateId, ft as generateSnowflake, te as geography, y as geometry, ge as getEnumRenames, In as getRelation, Fn as getRelations, ws as getResidencyConfig, p as getTable, Ji as gt, Yi as gte, hr as hasEagerLoads, Jo as hybridSearch, b as id, Qi as inSet, ma as inSubquery, En as inferForeignKey, lc as insertRow, D as integer, $s as interruptedReplaceRefusal, l as intersect, i as interval, es as isBranchNamespace, xn as isEmptyRelationsSpec, Wt as isEncrypted, Ut as isFieldDecryptionError, Ae as isFileMigration, cn as isForeignKeyViolation, et as isFrameworkOwnedLiveTable, Ho as isLocalFirst, Us as isMigrationDefinition, Ee as isMysqlFamily, os as isNeonConnection, sa as isNotNull, oa as isNull, hc as isPrimaryKeyConflictError, ln as isQueryTimeout, Jt as isRawEncoding, Ds as isRegionServable, Sn as isRelationsSpec, dt as isSeedDefinition, pe as isSqliteFamily, re as isTableReactive, Qe as isView, x as json, fa as jsonField, ut as jsonIndex, s as lag, le as lead, wc as listRetentionConflicts, Ec as listRetentions, Vo as localFirst, Uo as localFirstTables, Xi as lt, Zi as lte, Do as makeEagerFallbackReporter, ys as makeNamespaceBranchExecutor, wn as many, Tn as manyToMany, g as materializeFields, Je as max, tt as migration, t as min, cc as missingConflictColumns, sc as missingRequiredColumns, je as mixin, qi as neq, rs as nextBranchState, vc as normaliseTarget, da as not, _a as notExists, $i as notInSet, ha as notInSubquery, be as numeric, Co as observeDbOp, Cn as one, ir as oneCardinalityMessage, ua as or, w as orderClausesOf, ae as paginateBy, se as paginateById, Ja as pendingAttributionCount, us as planBranch, is as planBranchProvision, as as planBranchTeardown, ds as planBranchTeardownFor, cs as planNeonBranchProvision, ls as planNeonBranchTeardown, Fo as planVersionedUpdate, o as pluginRef, gt as pluginRefSpecOf, mc as primaryKeyConflictError, ps as provisionBranch, As as provisionResidentTenant, Sr as qualifyTable, de as queryFor, Ue as queryForView, e as quoteIdent, pc as raiseChangeListenerCeiling, d as rank, Ce as raw, m as readableByColumns, v as real, So as recordDbOp, ro as recordsTable, at as reference, Vi as registerCoreTables, Pn as registerDiscoveredRelations, La as registerPendingAttribution, Nn as registerRelations, Tc as registerRetention, it as registerTable, eo as registerWriteRecorder, bn as relations, Ui as requireActors, _ as requireTable, Wi as requireTenants, _o as resetDbMetricTagCacheForTests, Le as resetSnowflake, Os as residentPlacement, It as resolveActorSnapshot, ss as resolveBranchMechanism, Eo as resolveEagerFallbackWarnIntervalMs, Ka as resolveEchoAttribution, ee as resolveFullTextIndex, Ze as resolveIdScheme, nt as resolveMixinGraph, Es as resolveTenantHome, xr as resolveTenantNamespace, kc as retentionTtlMsFromEnv, ie as rowNumber, mn as rowSchema, jo as runRetryingTransaction, Mo as runStoreTransaction, ka as runWithWriteAttribution, io as runWriteRecorders, bc as sameDatabase, br as sanitizeIdentifierFragment, zt as serializeArraysForWrite, ne as serverOnlyColumns, Cs as setResidencyConfig, Ie as setSchemaChangeSeedHook, ze as setTenantCreateSeedHook, Oo as settleTransactionExit, Io as settleVersionedUpdate, ca as spatialPredicate, tc as stampGeneratedId, nc as stampGeneratedIds, ta as startsWith, qo as streamTable, me as sum, xt as sumOver, Oc as sweepRetention, T as table, ms as teardownBranch, C as text, S as timestamp, St as timestampMs, Ct as timestampMsOrNull, r as union, xe as unionAll, Te as unregisterTable, to as unregisterWriteRecorder, dc as updateManyRow, uc as upsertRow, We as validateColumnName, He as validateIndexName, Rn as validateRegisteredRelations, An as validateRelationConfig, ke as validateTableName, mt as validateTypeIdPrefix, De as vector, ot as vectorDistanceToOpclass, Xo as vectorEmbedding, Po as versionColumnOf, Ve as view, Oe as viewSql, Sa as walkLeaves, Ma as withCapturedAttribution };