@aiao/rxdb-adapter-pglite 0.0.15 → 0.0.16

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,9 +1,8 @@
1
- import { PropertyType as N, RxDBChange as ie, getEntityMetadata as D, EntityLocalCreatedEvent as oe, EntityLocalRemovedEvent as Ve, EntityLocalUpdatedEvent as me, RelationKind as F, RepositoryBase as Fn, getEntityStatus as J, RxDBBranch as ne, parseRxDBChangeKey as Ae, getEntityType as Re, RxDBAdapterLocalBase as kn } from "@aiao/rxdb";
2
- import { EventDispatcher as Wn, traverseObjectKeys as Gn, isFunction as It, isString as Hn, AsyncQueueExecutor as Vn } from "@aiao/utils";
3
- import { PGlite as Kn } from "@electric-sql/pglite";
4
- import Ot from "object-hash";
5
- import { ReplaySubject as Jn, defer as be, of as Se, from as Ie, map as Yn } from "rxjs";
6
- const Qn = "pglite";
1
+ import { PropertyType as N, RxDBChange as ie, getEntityMetadata as D, EntityLocalCreatedEvent as oe, EntityLocalRemovedEvent as Ve, EntityLocalUpdatedEvent as me, RelationKind as B, RepositoryBase as Fn, getEntityStatus as J, RxDBBranch as ne, parseRxDBChangeKey as Ae, getEntityType as Re, RxDBAdapterLocalBase as Bn } from "@aiao/rxdb";
2
+ import { EventDispatcher as kn, traverseObjectKeys as Wn, isFunction as It, isString as Gn, AsyncQueueExecutor as Hn } from "@aiao/utils";
3
+ import { PGlite as Vn } from "@electric-sql/pglite";
4
+ import { ReplaySubject as Kn, defer as be, of as Se, from as Ie, map as Jn } from "rxjs";
5
+ const Yn = "pglite";
7
6
  var K = /* @__PURE__ */ ((e) => (e.INSERT = "INSERT", e.UPDATE = "UPDATE", e.DELETE = "DELETE", e))(K || {});
8
7
  class x extends Error {
9
8
  /**
@@ -18,7 +17,7 @@ class x extends Error {
18
17
  super(t), this.name = "RxdbAdapterPGliteError", this.code = n, this.originalError = r, Object.setPrototypeOf(this, x.prototype);
19
18
  }
20
19
  }
21
- const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.namespace), Dt = (e) => {
20
+ const Ot = (e, t = "public") => `"${t}"."${e}"`, P = (e) => Ot(e.tableName, e.namespace), vt = (e) => {
22
21
  switch (e.type) {
23
22
  case N.uuid:
24
23
  return "uuid";
@@ -37,7 +36,7 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
37
36
  return "timestamptz";
38
37
  }
39
38
  throw new x("rxDBColumnTypeToPGliteType: type '" + e.type + "' not support");
40
- }, Xn = (e) => {
39
+ }, Qn = (e) => {
41
40
  switch (e.type) {
42
41
  case N.uuid:
43
42
  return "uuid_ops";
@@ -53,7 +52,7 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
53
52
  default:
54
53
  throw new x(`rxDBColumnTypeToPGliteTypeIndexName: type '${e.type}' not support`);
55
54
  }
56
- }, Ct = (e, t) => `idx_${e.namespace}_${e.tableName}_${t.name}`, tt = (e, t) => {
55
+ }, Dt = (e, t) => `idx_${e.namespace}_${e.tableName}_${t.name}`, tt = (e, t) => {
57
56
  if (e == null)
58
57
  return null;
59
58
  switch (t.type) {
@@ -92,14 +91,14 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
92
91
  n[l.columnName] = tt(t[o], l);
93
92
  continue;
94
93
  }
95
- const d = e.columnNameToPropertyName?.get(o);
96
- if (d) {
97
- const f = e.propertyMap.get(d);
98
- f && (n[o] = tt(t[o], f));
94
+ const p = e.columnNameToPropertyName?.get(o);
95
+ if (p) {
96
+ const h = e.propertyMap.get(p);
97
+ h && (n[o] = tt(t[o], h));
99
98
  }
100
99
  }
101
100
  return n;
102
- }, Lt = (e, t) => {
101
+ }, Ct = (e, t) => {
103
102
  const n = {};
104
103
  for (const [a, i] of e.propertyMap)
105
104
  a in t && (n[i.columnName] = t[a]);
@@ -109,7 +108,7 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
109
108
  i in t && (n[s[a]] = t[i]);
110
109
  }
111
110
  return n;
112
- }, zn = (e, t) => {
111
+ }, Xn = (e, t) => {
113
112
  const n = {};
114
113
  for (const [a, i] of e.propertyMap)
115
114
  a in t && i.readonly !== !0 && (n[i.columnName] = t[a]);
@@ -119,10 +118,10 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
119
118
  i in t && (n[s[a]] = t[i]);
120
119
  }
121
120
  return n;
122
- }, Zn = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, Je = (e) => {
121
+ }, zn = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, Je = (e) => {
123
122
  if (typeof e == "string") {
124
123
  const t = e.replaceAll("'", "''");
125
- return Zn.test(e) ? `'${t}'::uuid` : `'${t}'`;
124
+ return zn.test(e) ? `'${t}'::uuid` : `'${t}'`;
126
125
  }
127
126
  return e == null ? "NULL" : typeof e == "boolean" ? e ? "TRUE" : "FALSE" : e instanceof Date ? `'${e.toISOString()}'` : Array.isArray(e) ? `ARRAY[${e.map((n) => Je(n)).join(", ")}]` : typeof e == "object" ? `'${JSON.stringify(e).replaceAll("'", "''")}'::jsonb` : String(e);
128
127
  }, nt = (e, t = []) => !t || t.length === 0 ? e : e.replace(/\$(\d+)/g, (n, r) => {
@@ -172,29 +171,29 @@ const vt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => vt(e.tableName, e.na
172
171
  const r = t[n], s = e.propertyMap.get(n);
173
172
  s && (t[n] = Le(r, s));
174
173
  }), t);
175
- var es = Object.defineProperty, Mt = (e) => {
174
+ var Zn = Object.defineProperty, Lt = (e) => {
176
175
  throw TypeError(e);
177
- }, ts = (e, t) => () => (e && (t = e(e = 0)), t), ye = (e, t) => {
178
- for (var n in t) es(e, n, { get: t[n], enumerable: !0 });
179
- }, Ye = (e, t, n) => t.has(e) || Mt("Cannot " + n), h = (e, t, n) => (Ye(e, t, "read from private field"), n ? n.call(e) : t.get(e)), j = (e, t, n) => t.has(e) ? Mt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), v = (e, t, n, r) => (Ye(e, t, "write to private field"), t.set(e, n), n), O = (e, t, n) => (Ye(e, t, "access private method"), n), qt = (e, t, n, r) => ({ set _(s) {
176
+ }, es = (e, t) => () => (e && (t = e(e = 0)), t), ye = (e, t) => {
177
+ for (var n in t) Zn(e, n, { get: t[n], enumerable: !0 });
178
+ }, Ye = (e, t, n) => t.has(e) || Lt("Cannot " + n), f = (e, t, n) => (Ye(e, t, "read from private field"), n ? n.call(e) : t.get(e)), j = (e, t, n) => t.has(e) ? Lt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), v = (e, t, n, r) => (Ye(e, t, "write to private field"), t.set(e, n), n), O = (e, t, n) => (Ye(e, t, "access private method"), n), Mt = (e, t, n, r) => ({ set _(s) {
180
179
  v(e, t, s);
181
180
  }, get _() {
182
- return h(e, t, r);
183
- } }), H = ts(() => {
184
- }), ns = {};
185
- ye(ns, { ABSTIME: () => ms, ACLITEM: () => As, BIT: () => Is, BOOL: () => Me, BPCHAR: () => Ft, BYTEA: () => qe, CHAR: () => as, CID: () => ls, CIDR: () => Es, CIRCLE: () => _s, DATE: () => Wt, FLOAT4: () => xt, FLOAT8: () => Bt, GTSVECTOR: () => Gs, INET: () => $s, INT2: () => Pt, INT4: () => Ut, INT8: () => Pe, INTERVAL: () => bs, JSON: () => Ue, JSONB: () => Ht, MACADDR: () => Ns, MACADDR8: () => Ts, MONEY: () => ws, NUMERIC: () => vs, OID: () => jt, PATH: () => ds, PG_DEPENDENCIES: () => Fs, PG_LSN: () => xs, PG_NDISTINCT: () => Bs, PG_NODE_TREE: () => hs, POLYGON: () => ps, REFCURSOR: () => Ds, REGCLASS: () => qs, REGCONFIG: () => Hs, REGDICTIONARY: () => Vs, REGNAMESPACE: () => Ks, REGOPER: () => Ls, REGOPERATOR: () => Ms, REGPROC: () => is, REGPROCEDURE: () => Cs, REGROLE: () => Js, REGTYPE: () => Ps, RELTIME: () => ys, SMGR: () => fs, TEXT: () => ce, TID: () => os, TIME: () => Rs, TIMESTAMP: () => Gt, TIMESTAMPTZ: () => je, TIMETZ: () => Ss, TINTERVAL: () => gs, TSQUERY: () => Ws, TSVECTOR: () => ks, TXID_SNAPSHOT: () => js, UUID: () => Us, VARBIT: () => Os, VARCHAR: () => kt, XID: () => cs, XML: () => us, arrayParser: () => tr, arraySerializer: () => Kt, parseType: () => xe, parsers: () => Ys, serializers: () => Qs, types: () => Vt });
181
+ return f(e, t, r);
182
+ } }), H = es(() => {
183
+ }), ts = {};
184
+ ye(ts, { ABSTIME: () => Es, ACLITEM: () => $s, BIT: () => Ss, BOOL: () => Me, BPCHAR: () => Ft, BYTEA: () => qe, CHAR: () => rs, CID: () => cs, CIDR: () => ps, CIRCLE: () => _s, DATE: () => kt, FLOAT4: () => jt, FLOAT8: () => xt, GTSVECTOR: () => Ws, INET: () => Ns, INT2: () => qt, INT4: () => Pt, INT8: () => Pe, INTERVAL: () => Rs, JSON: () => Ue, JSONB: () => Gt, MACADDR: () => ws, MACADDR8: () => gs, MONEY: () => Ts, NUMERIC: () => Os, OID: () => Ut, PATH: () => fs, PG_DEPENDENCIES: () => Fs, PG_LSN: () => js, PG_NDISTINCT: () => xs, PG_NODE_TREE: () => us, POLYGON: () => ds, REFCURSOR: () => vs, REGCLASS: () => Ms, REGCONFIG: () => Gs, REGDICTIONARY: () => Hs, REGNAMESPACE: () => Vs, REGOPER: () => Cs, REGOPERATOR: () => Ls, REGPROC: () => as, REGPROCEDURE: () => Ds, REGROLE: () => Ks, REGTYPE: () => qs, RELTIME: () => ms, SMGR: () => hs, TEXT: () => ce, TID: () => is, TIME: () => As, TIMESTAMP: () => Wt, TIMESTAMPTZ: () => je, TIMETZ: () => bs, TINTERVAL: () => ys, TSQUERY: () => ks, TSVECTOR: () => Bs, TXID_SNAPSHOT: () => Us, UUID: () => Ps, VARBIT: () => Is, VARCHAR: () => Bt, XID: () => os, XML: () => ls, arrayParser: () => er, arraySerializer: () => Vt, parseType: () => xe, parsers: () => Js, serializers: () => Ys, types: () => Ht });
186
185
  H();
187
- var ss = globalThis.JSON.parse, rs = globalThis.JSON.stringify, Me = 16, qe = 17, as = 18, Pe = 20, Pt = 21, Ut = 23, is = 24, ce = 25, jt = 26, os = 27, cs = 28, ls = 29, Ue = 114, us = 142, hs = 194, fs = 210, ds = 602, ps = 604, Es = 650, xt = 700, Bt = 701, ms = 702, ys = 703, gs = 704, _s = 718, Ts = 774, ws = 790, Ns = 829, $s = 869, As = 1033, Ft = 1042, kt = 1043, Wt = 1082, Rs = 1083, Gt = 1114, je = 1184, bs = 1186, Ss = 1266, Is = 1560, Os = 1562, vs = 1700, Ds = 1790, Cs = 2202, Ls = 2203, Ms = 2204, qs = 2205, Ps = 2206, Us = 2950, js = 2970, xs = 3220, Bs = 3361, Fs = 3402, ks = 3614, Ws = 3615, Gs = 3642, Hs = 3734, Vs = 3769, Ht = 3802, Ks = 4089, Js = 4096, Vt = { string: { to: ce, from: [ce, kt, Ft], serialize: (e) => {
186
+ var ns = globalThis.JSON.parse, ss = globalThis.JSON.stringify, Me = 16, qe = 17, rs = 18, Pe = 20, qt = 21, Pt = 23, as = 24, ce = 25, Ut = 26, is = 27, os = 28, cs = 29, Ue = 114, ls = 142, us = 194, hs = 210, fs = 602, ds = 604, ps = 650, jt = 700, xt = 701, Es = 702, ms = 703, ys = 704, _s = 718, gs = 774, Ts = 790, ws = 829, Ns = 869, $s = 1033, Ft = 1042, Bt = 1043, kt = 1082, As = 1083, Wt = 1114, je = 1184, Rs = 1186, bs = 1266, Ss = 1560, Is = 1562, Os = 1700, vs = 1790, Ds = 2202, Cs = 2203, Ls = 2204, Ms = 2205, qs = 2206, Ps = 2950, Us = 2970, js = 3220, xs = 3361, Fs = 3402, Bs = 3614, ks = 3615, Ws = 3642, Gs = 3734, Hs = 3769, Gt = 3802, Vs = 4089, Ks = 4096, Ht = { string: { to: ce, from: [ce, Bt, Ft], serialize: (e) => {
188
187
  if (typeof e == "string") return e;
189
188
  if (typeof e == "number") return e.toString();
190
189
  throw new Error("Invalid input for string type");
191
- }, parse: (e) => e }, number: { to: 0, from: [Pt, Ut, jt, xt, Bt], serialize: (e) => e.toString(), parse: (e) => +e }, bigint: { to: Pe, from: [Pe], serialize: (e) => e.toString(), parse: (e) => {
190
+ }, parse: (e) => e }, number: { to: 0, from: [qt, Pt, Ut, jt, xt], serialize: (e) => e.toString(), parse: (e) => +e }, bigint: { to: Pe, from: [Pe], serialize: (e) => e.toString(), parse: (e) => {
192
191
  let t = BigInt(e);
193
192
  return t < Number.MIN_SAFE_INTEGER || t > Number.MAX_SAFE_INTEGER ? t : Number(t);
194
- } }, json: { to: Ue, from: [Ue, Ht], serialize: (e) => typeof e == "string" ? e : rs(e), parse: (e) => ss(e) }, boolean: { to: Me, from: [Me], serialize: (e) => {
193
+ } }, json: { to: Ue, from: [Ue, Gt], serialize: (e) => typeof e == "string" ? e : ss(e), parse: (e) => ns(e) }, boolean: { to: Me, from: [Me], serialize: (e) => {
195
194
  if (typeof e != "boolean") throw new Error("Invalid input for boolean type");
196
195
  return e ? "t" : "f";
197
- }, parse: (e) => e === "t" }, date: { to: je, from: [Wt, Gt, je], serialize: (e) => {
196
+ }, parse: (e) => e === "t" }, date: { to: je, from: [kt, Wt, je], serialize: (e) => {
198
197
  if (typeof e == "string") return e;
199
198
  if (typeof e == "number") return new Date(e).toISOString();
200
199
  if (e instanceof Date) return e.toISOString();
@@ -205,13 +204,13 @@ var ss = globalThis.JSON.parse, rs = globalThis.JSON.stringify, Me = 16, qe = 17
205
204
  }, parse: (e) => {
206
205
  let t = e.slice(2);
207
206
  return Uint8Array.from({ length: t.length / 2 }, (n, r) => parseInt(t.substring(r * 2, (r + 1) * 2), 16));
208
- } } }, Qe = Xs(Vt), Ys = Qe.parsers, Qs = Qe.serializers;
207
+ } } }, Qe = Qs(Ht), Js = Qe.parsers, Ys = Qe.serializers;
209
208
  function xe(e, t, n) {
210
209
  if (e === null) return null;
211
210
  let r = n?.[t] ?? Qe.parsers[t];
212
211
  return r ? r(e, t) : e;
213
212
  }
214
- function Xs(e) {
213
+ function Qs(e) {
215
214
  return Object.keys(e).reduce(({ parsers: t, serializers: n }, r) => {
216
215
  let { to: s, from: a, serialize: i, parse: o } = e[r];
217
216
  return n[s] = i, n[r] = i, t[r] = o, Array.isArray(a) ? a.forEach((c) => {
@@ -219,26 +218,26 @@ function Xs(e) {
219
218
  }) : (t[a] = o, n[a] = i), { parsers: t, serializers: n };
220
219
  }, { parsers: {}, serializers: {} });
221
220
  }
222
- var zs = /\\/g, Zs = /"/g;
223
- function er(e) {
224
- return e.replace(zs, "\\\\").replace(Zs, '\\"');
221
+ var Xs = /\\/g, zs = /"/g;
222
+ function Zs(e) {
223
+ return e.replace(Xs, "\\\\").replace(zs, '\\"');
225
224
  }
226
- function Kt(e, t, n) {
225
+ function Vt(e, t, n) {
227
226
  if (Array.isArray(e) === !1) return e;
228
227
  if (!e.length) return "{}";
229
228
  let r = e[0], s = n === 1020 ? ";" : ",";
230
- return Array.isArray(r) ? `{${e.map((a) => Kt(a, t, n)).join(s)}}` : `{${e.map((a) => (a === void 0 && (a = null), a === null ? "null" : '"' + er(t ? t(a) : a.toString()) + '"')).join(s)}}`;
229
+ return Array.isArray(r) ? `{${e.map((a) => Vt(a, t, n)).join(s)}}` : `{${e.map((a) => (a === void 0 && (a = null), a === null ? "null" : '"' + Zs(t ? t(a) : a.toString()) + '"')).join(s)}}`;
231
230
  }
232
231
  var Oe = { i: 0, char: null, str: "", quoted: !1, last: 0, p: null };
233
- function tr(e, t, n) {
234
- return Oe.i = Oe.last = 0, Jt(Oe, e, t, n)[0];
232
+ function er(e, t, n) {
233
+ return Oe.i = Oe.last = 0, Kt(Oe, e, t, n)[0];
235
234
  }
236
- function Jt(e, t, n, r) {
235
+ function Kt(e, t, n, r) {
237
236
  let s = [], a = r === 1020 ? ";" : ",";
238
237
  for (; e.i < t.length; e.i++) {
239
238
  if (e.char = t[e.i], e.quoted) e.char === "\\" ? e.str += t[++e.i] : e.char === '"' ? (s.push(n ? n(e.str) : e.str), e.str = "", e.quoted = t[e.i + 1] === '"', e.last = e.i + 2) : e.str += e.char;
240
239
  else if (e.char === '"') e.quoted = !0;
241
- else if (e.char === "{") e.last = ++e.i, s.push(Jt(e, t, n, r));
240
+ else if (e.char === "{") e.last = ++e.i, s.push(Kt(e, t, n, r));
242
241
  else if (e.char === "}") {
243
242
  e.quoted = !1, e.last < e.i && s.push(n ? n(t.slice(e.last, e.i)) : t.slice(e.last, e.i)), e.last = e.i + 1;
244
243
  break;
@@ -247,10 +246,10 @@ function Jt(e, t, n, r) {
247
246
  }
248
247
  return e.last < e.i && s.push(n ? n(t.slice(e.last, e.i + 1)) : t.slice(e.last, e.i + 1)), s;
249
248
  }
250
- var nr = {};
251
- ye(nr, { parseDescribeStatementResults: () => Yt, parseResults: () => sr });
249
+ var tr = {};
250
+ ye(tr, { parseDescribeStatementResults: () => Jt, parseResults: () => nr });
252
251
  H();
253
- function sr(e, t, n, r) {
252
+ function nr(e, t, n, r) {
254
253
  let s = [], a = { rows: [], fields: [] }, i = 0, o = { ...t, ...n?.parsers };
255
254
  return e.forEach((c) => {
256
255
  switch (c.name) {
@@ -262,17 +261,17 @@ function sr(e, t, n, r) {
262
261
  case "dataRow": {
263
262
  if (!a) break;
264
263
  let u = c;
265
- n?.rowMode === "array" ? a.rows.push(u.fields.map((l, d) => xe(l, a.fields[d].dataTypeID, o))) : a.rows.push(Object.fromEntries(u.fields.map((l, d) => [a.fields[d].name, xe(l, a.fields[d].dataTypeID, o)])));
264
+ n?.rowMode === "array" ? a.rows.push(u.fields.map((l, p) => xe(l, a.fields[p].dataTypeID, o))) : a.rows.push(Object.fromEntries(u.fields.map((l, p) => [a.fields[p].name, xe(l, a.fields[p].dataTypeID, o)])));
266
265
  break;
267
266
  }
268
267
  case "commandComplete": {
269
- i += rr(c), s.push({ ...a, affectedRows: i, ...r ? { blob: r } : {} }), a = { rows: [], fields: [] };
268
+ i += sr(c), s.push({ ...a, affectedRows: i, ...r ? { blob: r } : {} }), a = { rows: [], fields: [] };
270
269
  break;
271
270
  }
272
271
  }
273
272
  }), s.length === 0 && s.push({ affectedRows: 0, rows: [], fields: [] }), s;
274
273
  }
275
- function rr(e) {
274
+ function sr(e) {
276
275
  let t = e.text.split(" ");
277
276
  switch (t[0]) {
278
277
  case "INSERT":
@@ -286,66 +285,66 @@ function rr(e) {
286
285
  return 0;
287
286
  }
288
287
  }
289
- function Yt(e) {
288
+ function Jt(e) {
290
289
  let t = e.find((n) => n.name === "parameterDescription");
291
290
  return t ? t.dataTypeIDs : [];
292
291
  }
293
- var Qt = {};
294
- ye(Qt, { AuthenticationCleartextPassword: () => on, AuthenticationMD5Password: () => cn, AuthenticationOk: () => an, AuthenticationSASL: () => ln, AuthenticationSASLContinue: () => un, AuthenticationSASLFinal: () => hn, BackendKeyDataMessage: () => gn, CommandCompleteMessage: () => wn, CopyDataMessage: () => fn, CopyResponse: () => dn, DataRowMessage: () => Nn, DatabaseError: () => Be, Field: () => pn, NoticeMessage: () => $n, NotificationResponseMessage: () => _n, ParameterDescriptionMessage: () => mn, ParameterStatusMessage: () => yn, ReadyForQueryMessage: () => Tn, RowDescriptionMessage: () => En, bindComplete: () => zt, closeComplete: () => Zt, copyDone: () => rn, emptyQuery: () => sn, noData: () => en, parseComplete: () => Xt, portalSuspended: () => tn, replicationStart: () => nn });
292
+ var Yt = {};
293
+ ye(Yt, { AuthenticationCleartextPassword: () => an, AuthenticationMD5Password: () => on, AuthenticationOk: () => rn, AuthenticationSASL: () => cn, AuthenticationSASLContinue: () => ln, AuthenticationSASLFinal: () => un, BackendKeyDataMessage: () => yn, CommandCompleteMessage: () => Tn, CopyDataMessage: () => hn, CopyResponse: () => fn, DataRowMessage: () => wn, DatabaseError: () => Fe, Field: () => dn, NoticeMessage: () => Nn, NotificationResponseMessage: () => _n, ParameterDescriptionMessage: () => En, ParameterStatusMessage: () => mn, ReadyForQueryMessage: () => gn, RowDescriptionMessage: () => pn, bindComplete: () => Xt, closeComplete: () => zt, copyDone: () => sn, emptyQuery: () => nn, noData: () => Zt, parseComplete: () => Qt, portalSuspended: () => en, replicationStart: () => tn });
295
294
  H();
296
- var Xt = { name: "parseComplete", length: 5 }, zt = { name: "bindComplete", length: 5 }, Zt = { name: "closeComplete", length: 5 }, en = { name: "noData", length: 5 }, tn = { name: "portalSuspended", length: 5 }, nn = { name: "replicationStart", length: 4 }, sn = { name: "emptyQuery", length: 4 }, rn = { name: "copyDone", length: 4 }, an = class {
295
+ var Qt = { name: "parseComplete", length: 5 }, Xt = { name: "bindComplete", length: 5 }, zt = { name: "closeComplete", length: 5 }, Zt = { name: "noData", length: 5 }, en = { name: "portalSuspended", length: 5 }, tn = { name: "replicationStart", length: 4 }, nn = { name: "emptyQuery", length: 4 }, sn = { name: "copyDone", length: 4 }, rn = class {
297
296
  constructor(t) {
298
297
  this.length = t, this.name = "authenticationOk";
299
298
  }
300
- }, on = class {
299
+ }, an = class {
301
300
  constructor(e) {
302
301
  this.length = e, this.name = "authenticationCleartextPassword";
303
302
  }
304
- }, cn = class {
303
+ }, on = class {
305
304
  constructor(e, t) {
306
305
  this.length = e, this.salt = t, this.name = "authenticationMD5Password";
307
306
  }
308
- }, ln = class {
307
+ }, cn = class {
309
308
  constructor(t, n) {
310
309
  this.length = t, this.mechanisms = n, this.name = "authenticationSASL";
311
310
  }
312
- }, un = class {
311
+ }, ln = class {
313
312
  constructor(e, t) {
314
313
  this.length = e, this.data = t, this.name = "authenticationSASLContinue";
315
314
  }
316
- }, hn = class {
315
+ }, un = class {
317
316
  constructor(e, t) {
318
317
  this.length = e, this.data = t, this.name = "authenticationSASLFinal";
319
318
  }
320
- }, Be = class extends Error {
319
+ }, Fe = class extends Error {
321
320
  constructor(e, t, n) {
322
321
  super(e), this.length = t, this.name = n;
323
322
  }
324
- }, fn = class {
323
+ }, hn = class {
325
324
  constructor(e, t) {
326
325
  this.length = e, this.chunk = t, this.name = "copyData";
327
326
  }
328
- }, dn = class {
327
+ }, fn = class {
329
328
  constructor(e, t, n, r) {
330
329
  this.length = e, this.name = t, this.binary = n, this.columnTypes = new Array(r);
331
330
  }
332
- }, pn = class {
331
+ }, dn = class {
333
332
  constructor(e, t, n, r, s, a, i) {
334
333
  this.name = e, this.tableID = t, this.columnID = n, this.dataTypeID = r, this.dataTypeSize = s, this.dataTypeModifier = a, this.format = i;
335
334
  }
336
- }, En = class {
335
+ }, pn = class {
337
336
  constructor(t, n) {
338
337
  this.length = t, this.fieldCount = n, this.name = "rowDescription", this.fields = new Array(this.fieldCount);
339
338
  }
340
- }, mn = class {
339
+ }, En = class {
341
340
  constructor(e, t) {
342
341
  this.length = e, this.parameterCount = t, this.name = "parameterDescription", this.dataTypeIDs = new Array(this.parameterCount);
343
342
  }
344
- }, yn = class {
343
+ }, mn = class {
345
344
  constructor(e, t, n) {
346
345
  this.length = e, this.parameterName = t, this.parameterValue = n, this.name = "parameterStatus";
347
346
  }
348
- }, gn = class {
347
+ }, yn = class {
349
348
  constructor(e, t, n) {
350
349
  this.length = e, this.processID = t, this.secretKey = n, this.name = "backendKeyData";
351
350
  }
@@ -353,29 +352,29 @@ var Xt = { name: "parseComplete", length: 5 }, zt = { name: "bindComplete", leng
353
352
  constructor(e, t, n, r) {
354
353
  this.length = e, this.processId = t, this.channel = n, this.payload = r, this.name = "notification";
355
354
  }
356
- }, Tn = class {
355
+ }, gn = class {
357
356
  constructor(e, t) {
358
357
  this.length = e, this.status = t, this.name = "readyForQuery";
359
358
  }
360
- }, wn = class {
359
+ }, Tn = class {
361
360
  constructor(e, t) {
362
361
  this.length = e, this.text = t, this.name = "commandComplete";
363
362
  }
364
- }, Nn = class {
363
+ }, wn = class {
365
364
  constructor(e, t) {
366
365
  this.length = e, this.fields = t, this.name = "dataRow", this.fieldCount = t.length;
367
366
  }
368
- }, $n = class {
367
+ }, Nn = class {
369
368
  constructor(e, t) {
370
369
  this.length = e, this.message = t, this.name = "notice";
371
370
  }
372
- }, ar = {};
373
- ye(ar, { Parser: () => Cr, messages: () => Qt, serialize: () => re });
371
+ }, rr = {};
372
+ ye(rr, { Parser: () => Dr, messages: () => Yt, serialize: () => re });
374
373
  H();
375
374
  H();
376
375
  H();
377
376
  H();
378
- function ge(e) {
377
+ function _e(e) {
379
378
  let t = e.length;
380
379
  for (let n = e.length - 1; n >= 0; n--) {
381
380
  let r = e.charCodeAt(n);
@@ -383,174 +382,174 @@ function ge(e) {
383
382
  }
384
383
  return t;
385
384
  }
386
- var U, M, te, Fe, ee, V, le, X, An, _e = class {
385
+ var U, M, te, Be, ee, V, le, X, $n, ge = class {
387
386
  constructor(e = 256) {
388
- this.size = e, j(this, V), j(this, U), j(this, M, 5), j(this, te, !1), j(this, Fe, new TextEncoder()), j(this, ee, 0), v(this, U, O(this, V, le).call(this, e));
387
+ this.size = e, j(this, V), j(this, U), j(this, M, 5), j(this, te, !1), j(this, Be, new TextEncoder()), j(this, ee, 0), v(this, U, O(this, V, le).call(this, e));
389
388
  }
390
389
  addInt32(e) {
391
- return O(this, V, X).call(this, 4), h(this, U).setInt32(h(this, M), e, h(this, te)), v(this, M, h(this, M) + 4), this;
390
+ return O(this, V, X).call(this, 4), f(this, U).setInt32(f(this, M), e, f(this, te)), v(this, M, f(this, M) + 4), this;
392
391
  }
393
392
  addInt16(e) {
394
- return O(this, V, X).call(this, 2), h(this, U).setInt16(h(this, M), e, h(this, te)), v(this, M, h(this, M) + 2), this;
393
+ return O(this, V, X).call(this, 2), f(this, U).setInt16(f(this, M), e, f(this, te)), v(this, M, f(this, M) + 2), this;
395
394
  }
396
395
  addCString(e) {
397
- return e && this.addString(e), O(this, V, X).call(this, 1), h(this, U).setUint8(h(this, M), 0), qt(this, M)._++, this;
396
+ return e && this.addString(e), O(this, V, X).call(this, 1), f(this, U).setUint8(f(this, M), 0), Mt(this, M)._++, this;
398
397
  }
399
398
  addString(e = "") {
400
- let t = ge(e);
401
- return O(this, V, X).call(this, t), h(this, Fe).encodeInto(e, new Uint8Array(h(this, U).buffer, h(this, M))), v(this, M, h(this, M) + t), this;
399
+ let t = _e(e);
400
+ return O(this, V, X).call(this, t), f(this, Be).encodeInto(e, new Uint8Array(f(this, U).buffer, f(this, M))), v(this, M, f(this, M) + t), this;
402
401
  }
403
402
  add(e) {
404
- return O(this, V, X).call(this, e.byteLength), new Uint8Array(h(this, U).buffer).set(new Uint8Array(e), h(this, M)), v(this, M, h(this, M) + e.byteLength), this;
403
+ return O(this, V, X).call(this, e.byteLength), new Uint8Array(f(this, U).buffer).set(new Uint8Array(e), f(this, M)), v(this, M, f(this, M) + e.byteLength), this;
405
404
  }
406
405
  flush(e) {
407
- let t = O(this, V, An).call(this, e);
406
+ let t = O(this, V, $n).call(this, e);
408
407
  return v(this, M, 5), v(this, U, O(this, V, le).call(this, this.size)), new Uint8Array(t);
409
408
  }
410
409
  };
411
- U = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), te = /* @__PURE__ */ new WeakMap(), Fe = /* @__PURE__ */ new WeakMap(), ee = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakSet(), le = function(e) {
410
+ U = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), te = /* @__PURE__ */ new WeakMap(), Be = /* @__PURE__ */ new WeakMap(), ee = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakSet(), le = function(e) {
412
411
  return new DataView(new ArrayBuffer(e));
413
412
  }, X = function(e) {
414
- if (h(this, U).byteLength - h(this, M) < e) {
415
- let t = h(this, U).buffer, n = t.byteLength + (t.byteLength >> 1) + e;
416
- v(this, U, O(this, V, le).call(this, n)), new Uint8Array(h(this, U).buffer).set(new Uint8Array(t));
413
+ if (f(this, U).byteLength - f(this, M) < e) {
414
+ let t = f(this, U).buffer, n = t.byteLength + (t.byteLength >> 1) + e;
415
+ v(this, U, O(this, V, le).call(this, n)), new Uint8Array(f(this, U).buffer).set(new Uint8Array(t));
417
416
  }
418
- }, An = function(e) {
417
+ }, $n = function(e) {
419
418
  if (e) {
420
- h(this, U).setUint8(h(this, ee), e);
421
- let t = h(this, M) - (h(this, ee) + 1);
422
- h(this, U).setInt32(h(this, ee) + 1, t, h(this, te));
419
+ f(this, U).setUint8(f(this, ee), e);
420
+ let t = f(this, M) - (f(this, ee) + 1);
421
+ f(this, U).setInt32(f(this, ee) + 1, t, f(this, te));
423
422
  }
424
- return h(this, U).buffer.slice(e ? 0 : 5, h(this, M));
423
+ return f(this, U).buffer.slice(e ? 0 : 5, f(this, M));
425
424
  };
426
- var C = new _e(), ir = (e) => {
425
+ var C = new ge(), ar = (e) => {
427
426
  C.addInt16(3).addInt16(0);
428
427
  for (let r of Object.keys(e)) C.addCString(r).addCString(e[r]);
429
428
  C.addCString("client_encoding").addCString("UTF8");
430
429
  let t = C.addCString("").flush(), n = t.byteLength + 4;
431
- return new _e().addInt32(n).add(t).flush();
432
- }, or = () => {
430
+ return new ge().addInt32(n).add(t).flush();
431
+ }, ir = () => {
433
432
  let e = new DataView(new ArrayBuffer(8));
434
433
  return e.setInt32(0, 8, !1), e.setInt32(4, 80877103, !1), new Uint8Array(e.buffer);
435
- }, cr = (e) => C.addCString(e).flush(112), lr = (e, t) => (C.addCString(e).addInt32(ge(t)).addString(t), C.flush(112)), ur = (e) => C.addString(e).flush(112), hr = (e) => C.addCString(e).flush(81), fr = [], dr = (e) => {
434
+ }, or = (e) => C.addCString(e).flush(112), cr = (e, t) => (C.addCString(e).addInt32(_e(t)).addString(t), C.flush(112)), lr = (e) => C.addString(e).flush(112), ur = (e) => C.addCString(e).flush(81), hr = [], fr = (e) => {
436
435
  let t = e.name ?? "";
437
436
  t.length > 63 && (console.error("Warning! Postgres only supports 63 characters for query names."), console.error("You supplied %s (%s)", t, t.length), console.error("This can cause conflicts and silent errors executing queries"));
438
437
  let n = C.addCString(t).addCString(e.text).addInt16(e.types?.length ?? 0);
439
438
  return e.types?.forEach((r) => n.addInt32(r)), C.flush(80);
440
- }, z = new _e(), pr = (e, t) => {
439
+ }, z = new ge(), dr = (e, t) => {
441
440
  for (let n = 0; n < e.length; n++) {
442
441
  let r = t ? t(e[n], n) : e[n];
443
442
  if (r === null) C.addInt16(0), z.addInt32(-1);
444
443
  else if (r instanceof ArrayBuffer || ArrayBuffer.isView(r)) {
445
444
  let s = ArrayBuffer.isView(r) ? r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength) : r;
446
445
  C.addInt16(1), z.addInt32(s.byteLength), z.add(s);
447
- } else C.addInt16(0), z.addInt32(ge(r)), z.addString(r);
448
- }
449
- }, Er = (e = {}) => {
450
- let t = e.portal ?? "", n = e.statement ?? "", r = e.binary ?? !1, s = e.values ?? fr, a = s.length;
451
- return C.addCString(t).addCString(n), C.addInt16(a), pr(s, e.valueMapper), C.addInt16(a), C.add(z.flush()), C.addInt16(r ? 1 : 0), C.flush(66);
452
- }, mr = new Uint8Array([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]), yr = (e) => {
453
- if (!e || !e.portal && !e.rows) return mr;
454
- let t = e.portal ?? "", n = e.rows ?? 0, r = ge(t), s = 4 + r + 1 + 4, a = new DataView(new ArrayBuffer(1 + s));
446
+ } else C.addInt16(0), z.addInt32(_e(r)), z.addString(r);
447
+ }
448
+ }, pr = (e = {}) => {
449
+ let t = e.portal ?? "", n = e.statement ?? "", r = e.binary ?? !1, s = e.values ?? hr, a = s.length;
450
+ return C.addCString(t).addCString(n), C.addInt16(a), dr(s, e.valueMapper), C.addInt16(a), C.add(z.flush()), C.addInt16(r ? 1 : 0), C.flush(66);
451
+ }, Er = new Uint8Array([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]), mr = (e) => {
452
+ if (!e || !e.portal && !e.rows) return Er;
453
+ let t = e.portal ?? "", n = e.rows ?? 0, r = _e(t), s = 4 + r + 1 + 4, a = new DataView(new ArrayBuffer(1 + s));
455
454
  return a.setUint8(0, 69), a.setInt32(1, s, !1), new TextEncoder().encodeInto(t, new Uint8Array(a.buffer, 5)), a.setUint8(r + 5, 0), a.setUint32(a.byteLength - 4, n, !1), new Uint8Array(a.buffer);
456
- }, gr = (e, t) => {
455
+ }, yr = (e, t) => {
457
456
  let n = new DataView(new ArrayBuffer(16));
458
457
  return n.setInt32(0, 16, !1), n.setInt16(4, 1234, !1), n.setInt16(6, 5678, !1), n.setInt32(8, e, !1), n.setInt32(12, t, !1), new Uint8Array(n.buffer);
459
458
  }, Xe = (e, t) => {
460
- let n = new _e();
459
+ let n = new ge();
461
460
  return n.addCString(t), n.flush(e);
462
- }, _r = C.addCString("P").flush(68), Tr = C.addCString("S").flush(68), wr = (e) => e.name ? Xe(68, `${e.type}${e.name ?? ""}`) : e.type === "P" ? _r : Tr, Nr = (e) => {
461
+ }, _r = C.addCString("P").flush(68), gr = C.addCString("S").flush(68), Tr = (e) => e.name ? Xe(68, `${e.type}${e.name ?? ""}`) : e.type === "P" ? _r : gr, wr = (e) => {
463
462
  let t = `${e.type}${e.name ?? ""}`;
464
463
  return Xe(67, t);
465
- }, $r = (e) => C.add(e).flush(100), Ar = (e) => Xe(102, e), Te = (e) => new Uint8Array([e, 0, 0, 0, 4]), Rr = Te(72), br = Te(83), Sr = Te(88), Ir = Te(99), re = { startup: ir, password: cr, requestSsl: or, sendSASLInitialResponseMessage: lr, sendSCRAMClientFinalMessage: ur, query: hr, parse: dr, bind: Er, execute: yr, describe: wr, close: Nr, flush: () => Rr, sync: () => br, end: () => Sr, copyData: $r, copyDone: () => Ir, copyFail: Ar, cancel: gr };
464
+ }, Nr = (e) => C.add(e).flush(100), $r = (e) => Xe(102, e), Te = (e) => new Uint8Array([e, 0, 0, 0, 4]), Ar = Te(72), Rr = Te(83), br = Te(88), Sr = Te(99), re = { startup: ar, password: or, requestSsl: ir, sendSASLInitialResponseMessage: cr, sendSCRAMClientFinalMessage: lr, query: ur, parse: fr, bind: pr, execute: mr, describe: Tr, close: wr, flush: () => Ar, sync: () => Rr, end: () => br, copyData: Nr, copyDone: () => Sr, copyFail: $r, cancel: yr };
466
465
  H();
467
466
  H();
468
467
  var rt = { text: 0, binary: 1 };
469
468
  H();
470
- var Or = new ArrayBuffer(0), Y, q, ke, We, ae, vr = class {
469
+ var Ir = new ArrayBuffer(0), Y, q, ke, We, ae, Or = class {
471
470
  constructor(e = 0) {
472
- j(this, Y, new DataView(Or)), j(this, q), j(this, ke, "utf-8"), j(this, We, new TextDecoder(h(this, ke))), j(this, ae, !1), v(this, q, e);
471
+ j(this, Y, new DataView(Ir)), j(this, q), j(this, ke, "utf-8"), j(this, We, new TextDecoder(f(this, ke))), j(this, ae, !1), v(this, q, e);
473
472
  }
474
473
  setBuffer(e, t) {
475
474
  v(this, q, e), v(this, Y, new DataView(t));
476
475
  }
477
476
  int16() {
478
- let e = h(this, Y).getInt16(h(this, q), h(this, ae));
479
- return v(this, q, h(this, q) + 2), e;
477
+ let e = f(this, Y).getInt16(f(this, q), f(this, ae));
478
+ return v(this, q, f(this, q) + 2), e;
480
479
  }
481
480
  byte() {
482
- let e = h(this, Y).getUint8(h(this, q));
483
- return qt(this, q)._++, e;
481
+ let e = f(this, Y).getUint8(f(this, q));
482
+ return Mt(this, q)._++, e;
484
483
  }
485
484
  int32() {
486
- let e = h(this, Y).getInt32(h(this, q), h(this, ae));
487
- return v(this, q, h(this, q) + 4), e;
485
+ let e = f(this, Y).getInt32(f(this, q), f(this, ae));
486
+ return v(this, q, f(this, q) + 4), e;
488
487
  }
489
488
  string(e) {
490
- return h(this, We).decode(this.bytes(e));
489
+ return f(this, We).decode(this.bytes(e));
491
490
  }
492
491
  cstring() {
493
- let e = h(this, q), t = e;
494
- for (; h(this, Y).getUint8(t++) !== 0; ) ;
492
+ let e = f(this, q), t = e;
493
+ for (; f(this, Y).getUint8(t++) !== 0; ) ;
495
494
  let n = this.string(t - e - 1);
496
495
  return v(this, q, t), n;
497
496
  }
498
497
  bytes(e) {
499
- let t = h(this, Y).buffer.slice(h(this, q), h(this, q) + e);
500
- return v(this, q, h(this, q) + e), new Uint8Array(t);
498
+ let t = f(this, Y).buffer.slice(f(this, q), f(this, q) + e);
499
+ return v(this, q, f(this, q) + e), new Uint8Array(t);
501
500
  }
502
501
  };
503
502
  Y = /* @__PURE__ */ new WeakMap(), q = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), We = /* @__PURE__ */ new WeakMap(), ae = /* @__PURE__ */ new WeakMap();
504
- var Ge = 1, Dr = 4, at = Ge + Dr, it = new ArrayBuffer(0), B, W, G, w, L, Rn, bn, ot, ct, lt, ut, ht, ve, ft, dt, pt, Et, mt, yt, gt, _t, De, Cr = class {
503
+ var Ge = 1, vr = 4, at = Ge + vr, it = new ArrayBuffer(0), F, W, G, w, L, An, Rn, ot, ct, lt, ut, ht, ve, ft, dt, pt, Et, mt, yt, _t, gt, De, Dr = class {
505
504
  constructor() {
506
- j(this, L), j(this, B, new DataView(it)), j(this, W, 0), j(this, G, 0), j(this, w, new vr());
505
+ j(this, L), j(this, F, new DataView(it)), j(this, W, 0), j(this, G, 0), j(this, w, new Or());
507
506
  }
508
507
  parse(e, t) {
509
- O(this, L, Rn).call(this, ArrayBuffer.isView(e) ? e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength) : e);
510
- let n = h(this, G) + h(this, W), r = h(this, G);
508
+ O(this, L, An).call(this, ArrayBuffer.isView(e) ? e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength) : e);
509
+ let n = f(this, G) + f(this, W), r = f(this, G);
511
510
  for (; r + at <= n; ) {
512
- let s = h(this, B).getUint8(r), a = h(this, B).getUint32(r + Ge, !1), i = Ge + a;
511
+ let s = f(this, F).getUint8(r), a = f(this, F).getUint32(r + Ge, !1), i = Ge + a;
513
512
  if (i + r <= n && a > 0) {
514
- let o = O(this, L, bn).call(this, r + at, s, a, h(this, B).buffer);
513
+ let o = O(this, L, Rn).call(this, r + at, s, a, f(this, F).buffer);
515
514
  t(o), r += i;
516
515
  } else break;
517
516
  }
518
- r === n ? (v(this, B, new DataView(it)), v(this, W, 0), v(this, G, 0)) : (v(this, W, n - r), v(this, G, r));
517
+ r === n ? (v(this, F, new DataView(it)), v(this, W, 0), v(this, G, 0)) : (v(this, W, n - r), v(this, G, r));
519
518
  }
520
519
  };
521
- B = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__PURE__ */ new WeakMap(), w = /* @__PURE__ */ new WeakMap(), L = /* @__PURE__ */ new WeakSet(), Rn = function(e) {
522
- if (h(this, W) > 0) {
523
- let t = h(this, W) + e.byteLength;
524
- if (t + h(this, G) > h(this, B).byteLength) {
520
+ F = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__PURE__ */ new WeakMap(), w = /* @__PURE__ */ new WeakMap(), L = /* @__PURE__ */ new WeakSet(), An = function(e) {
521
+ if (f(this, W) > 0) {
522
+ let t = f(this, W) + e.byteLength;
523
+ if (t + f(this, G) > f(this, F).byteLength) {
525
524
  let n;
526
- if (t <= h(this, B).byteLength && h(this, G) >= h(this, W)) n = h(this, B).buffer;
525
+ if (t <= f(this, F).byteLength && f(this, G) >= f(this, W)) n = f(this, F).buffer;
527
526
  else {
528
- let r = h(this, B).byteLength * 2;
527
+ let r = f(this, F).byteLength * 2;
529
528
  for (; t >= r; ) r *= 2;
530
529
  n = new ArrayBuffer(r);
531
530
  }
532
- new Uint8Array(n).set(new Uint8Array(h(this, B).buffer, h(this, G), h(this, W))), v(this, B, new DataView(n)), v(this, G, 0);
531
+ new Uint8Array(n).set(new Uint8Array(f(this, F).buffer, f(this, G), f(this, W))), v(this, F, new DataView(n)), v(this, G, 0);
533
532
  }
534
- new Uint8Array(h(this, B).buffer).set(new Uint8Array(e), h(this, G) + h(this, W)), v(this, W, t);
535
- } else v(this, B, new DataView(e)), v(this, G, 0), v(this, W, e.byteLength);
536
- }, bn = function(e, t, n, r) {
533
+ new Uint8Array(f(this, F).buffer).set(new Uint8Array(e), f(this, G) + f(this, W)), v(this, W, t);
534
+ } else v(this, F, new DataView(e)), v(this, G, 0), v(this, W, e.byteLength);
535
+ }, Rn = function(e, t, n, r) {
537
536
  switch (t) {
538
537
  case 50:
539
- return zt;
540
- case 49:
541
538
  return Xt;
539
+ case 49:
540
+ return Qt;
542
541
  case 51:
543
- return Zt;
542
+ return zt;
544
543
  case 110:
545
- return en;
544
+ return Zt;
546
545
  case 115:
547
- return tn;
546
+ return en;
548
547
  case 99:
549
- return rn;
548
+ return sn;
550
549
  case 87:
551
- return nn;
550
+ return tn;
552
551
  case 73:
553
- return sn;
552
+ return nn;
554
553
  case 68:
555
554
  return O(this, L, mt).call(this, e, n, r);
556
555
  case 67:
@@ -560,11 +559,11 @@ B = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__
560
559
  case 65:
561
560
  return O(this, L, ft).call(this, e, n, r);
562
561
  case 82:
563
- return O(this, L, _t).call(this, e, n, r);
562
+ return O(this, L, gt).call(this, e, n, r);
564
563
  case 83:
565
564
  return O(this, L, yt).call(this, e, n, r);
566
565
  case 75:
567
- return O(this, L, gt).call(this, e, n, r);
566
+ return O(this, L, _t).call(this, e, n, r);
568
567
  case 69:
569
568
  return O(this, L, De).call(this, e, n, r, "error");
570
569
  case 78:
@@ -580,91 +579,91 @@ B = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__
580
579
  case 100:
581
580
  return O(this, L, lt).call(this, e, n, r);
582
581
  default:
583
- return new Be("received invalid response: " + t.toString(16), n, "error");
582
+ return new Fe("received invalid response: " + t.toString(16), n, "error");
584
583
  }
585
584
  }, ot = function(e, t, n) {
586
- h(this, w).setBuffer(e, n);
587
- let r = h(this, w).string(1);
588
- return new Tn(t, r);
585
+ f(this, w).setBuffer(e, n);
586
+ let r = f(this, w).string(1);
587
+ return new gn(t, r);
589
588
  }, ct = function(e, t, n) {
590
- h(this, w).setBuffer(e, n);
591
- let r = h(this, w).cstring();
592
- return new wn(t, r);
589
+ f(this, w).setBuffer(e, n);
590
+ let r = f(this, w).cstring();
591
+ return new Tn(t, r);
593
592
  }, lt = function(e, t, n) {
594
593
  let r = n.slice(e, e + (t - 4));
595
- return new fn(t, new Uint8Array(r));
594
+ return new hn(t, new Uint8Array(r));
596
595
  }, ut = function(e, t, n) {
597
596
  return O(this, L, ve).call(this, e, t, n, "copyInResponse");
598
597
  }, ht = function(e, t, n) {
599
598
  return O(this, L, ve).call(this, e, t, n, "copyOutResponse");
600
599
  }, ve = function(e, t, n, r) {
601
- h(this, w).setBuffer(e, n);
602
- let s = h(this, w).byte() !== 0, a = h(this, w).int16(), i = new dn(t, r, s, a);
603
- for (let o = 0; o < a; o++) i.columnTypes[o] = h(this, w).int16();
600
+ f(this, w).setBuffer(e, n);
601
+ let s = f(this, w).byte() !== 0, a = f(this, w).int16(), i = new fn(t, r, s, a);
602
+ for (let o = 0; o < a; o++) i.columnTypes[o] = f(this, w).int16();
604
603
  return i;
605
604
  }, ft = function(e, t, n) {
606
- h(this, w).setBuffer(e, n);
607
- let r = h(this, w).int32(), s = h(this, w).cstring(), a = h(this, w).cstring();
605
+ f(this, w).setBuffer(e, n);
606
+ let r = f(this, w).int32(), s = f(this, w).cstring(), a = f(this, w).cstring();
608
607
  return new _n(t, r, s, a);
609
608
  }, dt = function(e, t, n) {
610
- h(this, w).setBuffer(e, n);
611
- let r = h(this, w).int16(), s = new En(t, r);
609
+ f(this, w).setBuffer(e, n);
610
+ let r = f(this, w).int16(), s = new pn(t, r);
612
611
  for (let a = 0; a < r; a++) s.fields[a] = O(this, L, pt).call(this);
613
612
  return s;
614
613
  }, pt = function() {
615
- let e = h(this, w).cstring(), t = h(this, w).int32(), n = h(this, w).int16(), r = h(this, w).int32(), s = h(this, w).int16(), a = h(this, w).int32(), i = h(this, w).int16() === 0 ? rt.text : rt.binary;
616
- return new pn(e, t, n, r, s, a, i);
614
+ let e = f(this, w).cstring(), t = f(this, w).int32(), n = f(this, w).int16(), r = f(this, w).int32(), s = f(this, w).int16(), a = f(this, w).int32(), i = f(this, w).int16() === 0 ? rt.text : rt.binary;
615
+ return new dn(e, t, n, r, s, a, i);
617
616
  }, Et = function(e, t, n) {
618
- h(this, w).setBuffer(e, n);
619
- let r = h(this, w).int16(), s = new mn(t, r);
620
- for (let a = 0; a < r; a++) s.dataTypeIDs[a] = h(this, w).int32();
617
+ f(this, w).setBuffer(e, n);
618
+ let r = f(this, w).int16(), s = new En(t, r);
619
+ for (let a = 0; a < r; a++) s.dataTypeIDs[a] = f(this, w).int32();
621
620
  return s;
622
621
  }, mt = function(e, t, n) {
623
- h(this, w).setBuffer(e, n);
624
- let r = h(this, w).int16(), s = new Array(r);
622
+ f(this, w).setBuffer(e, n);
623
+ let r = f(this, w).int16(), s = new Array(r);
625
624
  for (let a = 0; a < r; a++) {
626
- let i = h(this, w).int32();
627
- s[a] = i === -1 ? null : h(this, w).string(i);
625
+ let i = f(this, w).int32();
626
+ s[a] = i === -1 ? null : f(this, w).string(i);
628
627
  }
629
- return new Nn(t, s);
628
+ return new wn(t, s);
630
629
  }, yt = function(e, t, n) {
631
- h(this, w).setBuffer(e, n);
632
- let r = h(this, w).cstring(), s = h(this, w).cstring();
630
+ f(this, w).setBuffer(e, n);
631
+ let r = f(this, w).cstring(), s = f(this, w).cstring();
632
+ return new mn(t, r, s);
633
+ }, _t = function(e, t, n) {
634
+ f(this, w).setBuffer(e, n);
635
+ let r = f(this, w).int32(), s = f(this, w).int32();
633
636
  return new yn(t, r, s);
634
637
  }, gt = function(e, t, n) {
635
- h(this, w).setBuffer(e, n);
636
- let r = h(this, w).int32(), s = h(this, w).int32();
637
- return new gn(t, r, s);
638
- }, _t = function(e, t, n) {
639
- h(this, w).setBuffer(e, n);
640
- let r = h(this, w).int32();
638
+ f(this, w).setBuffer(e, n);
639
+ let r = f(this, w).int32();
641
640
  switch (r) {
642
641
  case 0:
643
- return new an(t);
642
+ return new rn(t);
644
643
  case 3:
645
- return new on(t);
644
+ return new an(t);
646
645
  case 5:
647
- return new cn(t, h(this, w).bytes(4));
646
+ return new on(t, f(this, w).bytes(4));
648
647
  case 10: {
649
648
  let s = [];
650
649
  for (; ; ) {
651
- let a = h(this, w).cstring();
652
- if (a.length === 0) return new ln(t, s);
650
+ let a = f(this, w).cstring();
651
+ if (a.length === 0) return new cn(t, s);
653
652
  s.push(a);
654
653
  }
655
654
  }
656
655
  case 11:
657
- return new un(t, h(this, w).string(t - 8));
656
+ return new ln(t, f(this, w).string(t - 8));
658
657
  case 12:
659
- return new hn(t, h(this, w).string(t - 8));
658
+ return new un(t, f(this, w).string(t - 8));
660
659
  default:
661
660
  throw new Error("Unknown authenticationOk message type " + r);
662
661
  }
663
662
  }, De = function(e, t, n, r) {
664
- h(this, w).setBuffer(e, n);
665
- let s = {}, a = h(this, w).string(1);
666
- for (; a !== "\0"; ) s[a] = h(this, w).cstring(), a = h(this, w).string(1);
667
- let i = s.M, o = r === "notice" ? new $n(t, i) : new Be(i, t, r);
663
+ f(this, w).setBuffer(e, n);
664
+ let s = {}, a = f(this, w).string(1);
665
+ for (; a !== "\0"; ) s[a] = f(this, w).cstring(), a = f(this, w).string(1);
666
+ let i = s.M, o = r === "notice" ? new Nn(t, i) : new Fe(i, t, r);
668
667
  return o.severity = s.S, o.code = s.C, o.detail = s.D, o.hint = s.H, o.position = s.P, o.internalPosition = s.p, o.internalQuery = s.q, o.where = s.W, o.schema = s.s, o.table = s.t, o.column = s.c, o.dataType = s.d, o.constraint = s.n, o.file = s.F, o.line = s.L, o.routine = s.R, o;
669
668
  };
670
669
  H();
@@ -689,7 +688,7 @@ async function wt(e, t, n, r) {
689
688
  } finally {
690
689
  s.push(...(await e.execProtocol(re.sync(), { syncToFs: !1 })).messages);
691
690
  }
692
- let a = Yt(s), i = t.replace(/\$([0-9]+)/g, (o, c) => "%" + c + "L");
691
+ let a = Jt(s), i = t.replace(/\$([0-9]+)/g, (o, c) => "%" + c + "L");
693
692
  return (await r.query(`SELECT format($1, ${n.map((o, c) => `$${c + 2}`).join(", ")}) as query`, [i, ...n], { paramTypes: [ce, ...a] })).rows[0].query;
694
693
  }
695
694
  function Nt(e) {
@@ -719,79 +718,79 @@ function Nt(e) {
719
718
  };
720
719
  }
721
720
  H();
722
- var Lr = 5, Mr = async (e, t) => {
721
+ var Cr = 5, Lr = async (e, t) => {
723
722
  let n = /* @__PURE__ */ new Set(), r = { async query(s, a, i) {
724
723
  let o, c, u;
725
724
  if (typeof s != "string" && (o = s.signal, a = s.params, i = s.callback, c = s.offset, u = s.limit, s = s.query), c === void 0 != (u === void 0)) throw new Error("offset and limit must be provided together");
726
- let l = c !== void 0 && u !== void 0, d;
725
+ let l = c !== void 0 && u !== void 0, p;
727
726
  if (l && (typeof c != "number" || isNaN(c) || typeof u != "number" || isNaN(u))) throw new Error("offset and limit must be numbers");
728
- let f = i ? [i] : [], p = Tt().replace(/-/g, ""), _ = !1, S, $, A = async () => {
729
- await e.transaction(async (g) => {
730
- let R = a && a.length > 0 ? await wt(e, s, a, g) : s;
731
- await g.exec(`CREATE OR REPLACE TEMP VIEW live_query_${p}_view AS ${R}`);
732
- let I = await $t(g, `live_query_${p}_view`);
733
- await At(g, I, n), l ? (await g.exec(`
734
- PREPARE live_query_${p}_get(int, int) AS
735
- SELECT * FROM live_query_${p}_view
727
+ let h = i ? [i] : [], d = Tt().replace(/-/g, ""), y = !1, A, $, R = async () => {
728
+ await e.transaction(async (T) => {
729
+ let b = a && a.length > 0 ? await wt(e, s, a, T) : s;
730
+ await T.exec(`CREATE OR REPLACE TEMP VIEW live_query_${d}_view AS ${b}`);
731
+ let S = await $t(T, `live_query_${d}_view`);
732
+ await At(T, S, n), l ? (await T.exec(`
733
+ PREPARE live_query_${d}_get(int, int) AS
734
+ SELECT * FROM live_query_${d}_view
736
735
  LIMIT $1 OFFSET $2;
737
- `), await g.exec(`
738
- PREPARE live_query_${p}_get_total_count AS
739
- SELECT COUNT(*) FROM live_query_${p}_view;
740
- `), d = (await g.query(`EXECUTE live_query_${p}_get_total_count;`)).rows[0].count, S = { ...await g.query(`EXECUTE live_query_${p}_get(${u}, ${c});`), offset: c, limit: u, totalCount: d }) : (await g.exec(`
741
- PREPARE live_query_${p}_get AS
742
- SELECT * FROM live_query_${p}_view;
743
- `), S = await g.query(`EXECUTE live_query_${p}_get;`)), $ = await Promise.all(I.map((y) => g.listen(`"table_change__${y.schema_oid}__${y.table_oid}"`, async () => {
744
- b();
736
+ `), await T.exec(`
737
+ PREPARE live_query_${d}_get_total_count AS
738
+ SELECT COUNT(*) FROM live_query_${d}_view;
739
+ `), p = (await T.query(`EXECUTE live_query_${d}_get_total_count;`)).rows[0].count, A = { ...await T.query(`EXECUTE live_query_${d}_get(${u}, ${c});`), offset: c, limit: u, totalCount: p }) : (await T.exec(`
740
+ PREPARE live_query_${d}_get AS
741
+ SELECT * FROM live_query_${d}_view;
742
+ `), A = await T.query(`EXECUTE live_query_${d}_get;`)), $ = await Promise.all(S.map((m) => T.listen(`"table_change__${m.schema_oid}__${m.table_oid}"`, async () => {
743
+ I();
745
744
  })));
746
745
  });
747
746
  };
748
- await A();
749
- let b = Nt(async ({ offset: g, limit: R } = {}) => {
750
- if (!l && (g !== void 0 || R !== void 0)) throw new Error("offset and limit cannot be provided for non-windowed queries");
751
- if (g && (typeof g != "number" || isNaN(g)) || R && (typeof R != "number" || isNaN(R))) throw new Error("offset and limit must be numbers");
752
- c = g ?? c, u = R ?? u;
753
- let I = async (y = 0) => {
754
- if (f.length !== 0) {
747
+ await R();
748
+ let I = Nt(async ({ offset: T, limit: b } = {}) => {
749
+ if (!l && (T !== void 0 || b !== void 0)) throw new Error("offset and limit cannot be provided for non-windowed queries");
750
+ if (T && (typeof T != "number" || isNaN(T)) || b && (typeof b != "number" || isNaN(b))) throw new Error("offset and limit must be numbers");
751
+ c = T ?? c, u = b ?? u;
752
+ let S = async (m = 0) => {
753
+ if (h.length !== 0) {
755
754
  try {
756
- l ? S = { ...await e.query(`EXECUTE live_query_${p}_get(${u}, ${c});`), offset: c, limit: u, totalCount: d } : S = await e.query(`EXECUTE live_query_${p}_get;`);
757
- } catch (T) {
758
- let k = T.message;
759
- if (k.startsWith(`prepared statement "live_query_${p}`) && k.endsWith("does not exist")) {
760
- if (y > Lr) throw T;
761
- await A(), I(y + 1);
762
- } else throw T;
755
+ l ? A = { ...await e.query(`EXECUTE live_query_${d}_get(${u}, ${c});`), offset: c, limit: u, totalCount: p } : A = await e.query(`EXECUTE live_query_${d}_get;`);
756
+ } catch (g) {
757
+ let k = g.message;
758
+ if (k.startsWith(`prepared statement "live_query_${d}`) && k.endsWith("does not exist")) {
759
+ if (m > Cr) throw g;
760
+ await R(), S(m + 1);
761
+ } else throw g;
763
762
  }
764
- if (se(f, S), l) {
765
- let T = (await e.query(`EXECUTE live_query_${p}_get_total_count;`)).rows[0].count;
766
- T !== d && (d = T, b());
763
+ if (se(h, A), l) {
764
+ let g = (await e.query(`EXECUTE live_query_${d}_get_total_count;`)).rows[0].count;
765
+ g !== p && (p = g, I());
767
766
  }
768
767
  }
769
768
  };
770
- await I();
771
- }), E = (g) => {
772
- if (_) throw new Error("Live query is no longer active and cannot be subscribed to");
773
- f.push(g);
774
- }, m = async (g) => {
775
- g ? f = f.filter((R) => R !== R) : f = [], f.length === 0 && !_ && (_ = !0, await e.transaction(async (R) => {
776
- await Promise.all($.map((I) => I(R))), await R.exec(`
777
- DROP VIEW IF EXISTS live_query_${p}_view;
778
- DEALLOCATE live_query_${p}_get;
769
+ await S();
770
+ }), E = (T) => {
771
+ if (y) throw new Error("Live query is no longer active and cannot be subscribed to");
772
+ h.push(T);
773
+ }, _ = async (T) => {
774
+ T ? h = h.filter((b) => b !== b) : h = [], h.length === 0 && !y && (y = !0, await e.transaction(async (b) => {
775
+ await Promise.all($.map((S) => S(b))), await b.exec(`
776
+ DROP VIEW IF EXISTS live_query_${d}_view;
777
+ DEALLOCATE live_query_${d}_get;
779
778
  `);
780
779
  }));
781
780
  };
782
- return o?.aborted ? await m() : o?.addEventListener("abort", () => {
783
- m();
784
- }, { once: !0 }), se(f, S), { initialResults: S, subscribe: E, unsubscribe: m, refresh: b };
781
+ return o?.aborted ? await _() : o?.addEventListener("abort", () => {
782
+ _();
783
+ }, { once: !0 }), se(h, A), { initialResults: A, subscribe: E, unsubscribe: _, refresh: I };
785
784
  }, async changes(s, a, i, o) {
786
785
  let c;
787
786
  if (typeof s != "string" && (c = s.signal, a = s.params, i = s.key, o = s.callback, s = s.query), !i) throw new Error("key is required for changes queries");
788
- let u = o ? [o] : [], l = Tt().replace(/-/g, ""), d = !1, f = 1, p, _, S = async () => {
787
+ let u = o ? [o] : [], l = Tt().replace(/-/g, ""), p = !1, h = 1, d, y, A = async () => {
789
788
  await e.transaction(async (E) => {
790
- let m = await wt(e, s, a, E);
791
- await E.query(`CREATE OR REPLACE TEMP VIEW live_query_${l}_view AS ${m}`);
792
- let g = await $t(E, `live_query_${l}_view`);
793
- await At(E, g, n);
794
- let R = [...(await E.query(`
789
+ let _ = await wt(e, s, a, E);
790
+ await E.query(`CREATE OR REPLACE TEMP VIEW live_query_${l}_view AS ${_}`);
791
+ let T = await $t(E, `live_query_${l}_view`);
792
+ await At(E, T, n);
793
+ let b = [...(await E.query(`
795
794
  SELECT column_name, data_type, udt_name
796
795
  FROM information_schema.columns
797
796
  WHERE table_name = 'live_query_${l}_view'
@@ -800,18 +799,18 @@ var Lr = 5, Mr = async (e, t) => {
800
799
  CREATE TEMP TABLE live_query_${l}_state1 (LIKE live_query_${l}_view INCLUDING ALL);
801
800
  CREATE TEMP TABLE live_query_${l}_state2 (LIKE live_query_${l}_view INCLUDING ALL);
802
801
  `);
803
- for (let I of [1, 2]) {
804
- let y = I === 1 ? 2 : 1;
802
+ for (let S of [1, 2]) {
803
+ let m = S === 1 ? 2 : 1;
805
804
  await E.exec(`
806
- PREPARE live_query_${l}_diff${I} AS
805
+ PREPARE live_query_${l}_diff${S} AS
807
806
  WITH
808
- prev AS (SELECT LAG("${i}") OVER () as __after__, * FROM live_query_${l}_state${y}),
809
- curr AS (SELECT LAG("${i}") OVER () as __after__, * FROM live_query_${l}_state${I}),
807
+ prev AS (SELECT LAG("${i}") OVER () as __after__, * FROM live_query_${l}_state${m}),
808
+ curr AS (SELECT LAG("${i}") OVER () as __after__, * FROM live_query_${l}_state${S}),
810
809
  data_diff AS (
811
810
  -- INSERT operations: Include all columns
812
811
  SELECT
813
812
  'INSERT' AS __op__,
814
- ${R.map(({ column_name: T }) => `curr."${T}" AS "${T}"`).join(`,
813
+ ${b.map(({ column_name: g }) => `curr."${g}" AS "${g}"`).join(`,
815
814
  `)},
816
815
  ARRAY[]::text[] AS __changed_columns__
817
816
  FROM curr
@@ -821,7 +820,7 @@ var Lr = 5, Mr = async (e, t) => {
821
820
  -- DELETE operations: Include only the primary key
822
821
  SELECT
823
822
  'DELETE' AS __op__,
824
- ${R.map(({ column_name: T, data_type: k, udt_name: Q }) => T === i ? `prev."${T}" AS "${T}"` : `NULL${k === "USER-DEFINED" ? `::${Q}` : ""} AS "${T}"`).join(`,
823
+ ${b.map(({ column_name: g, data_type: k, udt_name: Q }) => g === i ? `prev."${g}" AS "${g}"` : `NULL${k === "USER-DEFINED" ? `::${Q}` : ""} AS "${g}"`).join(`,
825
824
  `)},
826
825
  ARRAY[]::text[] AS __changed_columns__
827
826
  FROM prev
@@ -831,15 +830,15 @@ var Lr = 5, Mr = async (e, t) => {
831
830
  -- UPDATE operations: Include only changed columns
832
831
  SELECT
833
832
  'UPDATE' AS __op__,
834
- ${R.map(({ column_name: T, data_type: k, udt_name: Q }) => T === i ? `curr."${T}" AS "${T}"` : `CASE
835
- WHEN curr."${T}" IS DISTINCT FROM prev."${T}"
836
- THEN curr."${T}"
833
+ ${b.map(({ column_name: g, data_type: k, udt_name: Q }) => g === i ? `curr."${g}" AS "${g}"` : `CASE
834
+ WHEN curr."${g}" IS DISTINCT FROM prev."${g}"
835
+ THEN curr."${g}"
837
836
  ELSE NULL${k === "USER-DEFINED" ? `::${Q}` : ""}
838
- END AS "${T}"`).join(`,
837
+ END AS "${g}"`).join(`,
839
838
  `)},
840
- ARRAY(SELECT unnest FROM unnest(ARRAY[${R.filter(({ column_name: T }) => T !== i).map(({ column_name: T }) => `CASE
841
- WHEN curr."${T}" IS DISTINCT FROM prev."${T}"
842
- THEN '${T}'
839
+ ARRAY(SELECT unnest FROM unnest(ARRAY[${b.filter(({ column_name: g }) => g !== i).map(({ column_name: g }) => `CASE
840
+ WHEN curr."${g}" IS DISTINCT FROM prev."${g}"
841
+ THEN '${g}'
843
842
  ELSE NULL
844
843
  END`).join(", ")}]) WHERE unnest IS NOT NULL) AS __changed_columns__
845
844
  FROM curr
@@ -849,38 +848,38 @@ var Lr = 5, Mr = async (e, t) => {
849
848
  SELECT * FROM data_diff;
850
849
  `);
851
850
  }
852
- _ = await Promise.all(g.map((I) => E.listen(`"table_change__${I.schema_oid}__${I.table_oid}"`, async () => {
851
+ y = await Promise.all(T.map((S) => E.listen(`"table_change__${S.schema_oid}__${S.table_oid}"`, async () => {
853
852
  $();
854
853
  })));
855
854
  });
856
855
  };
857
- await S();
856
+ await A();
858
857
  let $ = Nt(async () => {
859
- if (u.length === 0 && p) return;
858
+ if (u.length === 0 && d) return;
860
859
  let E = !1;
861
- for (let m = 0; m < 5; m++) try {
862
- await e.transaction(async (g) => {
863
- await g.exec(`
864
- INSERT INTO live_query_${l}_state${f}
860
+ for (let _ = 0; _ < 5; _++) try {
861
+ await e.transaction(async (T) => {
862
+ await T.exec(`
863
+ INSERT INTO live_query_${l}_state${h}
865
864
  SELECT * FROM live_query_${l}_view;
866
- `), p = await g.query(`EXECUTE live_query_${l}_diff${f};`), f = f === 1 ? 2 : 1, await g.exec(`
867
- TRUNCATE live_query_${l}_state${f};
865
+ `), d = await T.query(`EXECUTE live_query_${l}_diff${h};`), h = h === 1 ? 2 : 1, await T.exec(`
866
+ TRUNCATE live_query_${l}_state${h};
868
867
  `);
869
868
  });
870
869
  break;
871
- } catch (g) {
872
- if (g.message === `relation "live_query_${l}_state${f}" does not exist`) {
873
- E = !0, await S();
870
+ } catch (T) {
871
+ if (T.message === `relation "live_query_${l}_state${h}" does not exist`) {
872
+ E = !0, await A();
874
873
  continue;
875
- } else throw g;
874
+ } else throw T;
876
875
  }
877
- Pr(u, [...E ? [{ __op__: "RESET" }] : [], ...p.rows]);
878
- }), A = (E) => {
879
- if (d) throw new Error("Live query is no longer active and cannot be subscribed to");
876
+ qr(u, [...E ? [{ __op__: "RESET" }] : [], ...d.rows]);
877
+ }), R = (E) => {
878
+ if (p) throw new Error("Live query is no longer active and cannot be subscribed to");
880
879
  u.push(E);
881
- }, b = async (E) => {
882
- E ? u = u.filter((m) => m !== m) : u = [], u.length === 0 && !d && (d = !0, await e.transaction(async (m) => {
883
- await Promise.all(_.map((g) => g(m))), await m.exec(`
880
+ }, I = async (E) => {
881
+ E ? u = u.filter((_) => _ !== _) : u = [], u.length === 0 && !p && (p = !0, await e.transaction(async (_) => {
882
+ await Promise.all(y.map((T) => T(_))), await _.exec(`
884
883
  DROP VIEW IF EXISTS live_query_${l}_view;
885
884
  DROP TABLE IF EXISTS live_query_${l}_state1;
886
885
  DROP TABLE IF EXISTS live_query_${l}_state2;
@@ -889,56 +888,56 @@ var Lr = 5, Mr = async (e, t) => {
889
888
  `);
890
889
  }));
891
890
  };
892
- return c?.aborted ? await b() : c?.addEventListener("abort", () => {
893
- b();
894
- }, { once: !0 }), await $(), { fields: p.fields.filter((E) => !["__after__", "__op__", "__changed_columns__"].includes(E.name)), initialChanges: p.rows, subscribe: A, unsubscribe: b, refresh: $ };
891
+ return c?.aborted ? await I() : c?.addEventListener("abort", () => {
892
+ I();
893
+ }, { once: !0 }), await $(), { fields: d.fields.filter((E) => !["__after__", "__op__", "__changed_columns__"].includes(E.name)), initialChanges: d.rows, subscribe: R, unsubscribe: I, refresh: $ };
895
894
  }, async incrementalQuery(s, a, i, o) {
896
895
  let c;
897
896
  if (typeof s != "string" && (c = s.signal, a = s.params, i = s.key, o = s.callback, s = s.query), !i) throw new Error("key is required for incremental queries");
898
- let u = o ? [o] : [], l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = [], p = !0, { fields: _, unsubscribe: S, refresh: $ } = await r.changes(s, a, i, (E) => {
899
- for (let R of E) {
900
- let { __op__: I, __changed_columns__: y, ...T } = R;
901
- switch (I) {
897
+ let u = o ? [o] : [], l = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), h = [], d = !0, { fields: y, unsubscribe: A, refresh: $ } = await r.changes(s, a, i, (E) => {
898
+ for (let b of E) {
899
+ let { __op__: S, __changed_columns__: m, ...g } = b;
900
+ switch (S) {
902
901
  case "RESET":
903
- l.clear(), d.clear();
902
+ l.clear(), p.clear();
904
903
  break;
905
904
  case "INSERT":
906
- l.set(T[i], T), d.set(T.__after__, T[i]);
905
+ l.set(g[i], g), p.set(g.__after__, g[i]);
907
906
  break;
908
907
  case "DELETE": {
909
- let k = l.get(T[i]);
910
- l.delete(T[i]), k.__after__ !== null && d.delete(k.__after__);
908
+ let k = l.get(g[i]);
909
+ l.delete(g[i]), k.__after__ !== null && p.delete(k.__after__);
911
910
  break;
912
911
  }
913
912
  case "UPDATE": {
914
- let k = { ...l.get(T[i]) ?? {} };
915
- for (let Q of y) k[Q] = T[Q], Q === "__after__" && d.set(T.__after__, T[i]);
916
- l.set(T[i], k);
913
+ let k = { ...l.get(g[i]) ?? {} };
914
+ for (let Q of m) k[Q] = g[Q], Q === "__after__" && p.set(g.__after__, g[i]);
915
+ l.set(g[i], k);
917
916
  break;
918
917
  }
919
918
  }
920
919
  }
921
- let m = [], g = null;
922
- for (let R = 0; R < l.size; R++) {
923
- let I = d.get(g), y = l.get(I);
924
- if (!y) break;
925
- let T = { ...y };
926
- delete T.__after__, m.push(T), g = I;
920
+ let _ = [], T = null;
921
+ for (let b = 0; b < l.size; b++) {
922
+ let S = p.get(T), m = l.get(S);
923
+ if (!m) break;
924
+ let g = { ...m };
925
+ delete g.__after__, _.push(g), T = S;
927
926
  }
928
- f = m, p || se(u, { rows: m, fields: _ });
927
+ h = _, d || se(u, { rows: _, fields: y });
929
928
  });
930
- p = !1, se(u, { rows: f, fields: _ });
931
- let A = (E) => {
929
+ d = !1, se(u, { rows: h, fields: y });
930
+ let R = (E) => {
932
931
  u.push(E);
933
- }, b = async (E) => {
934
- E ? u = u.filter((m) => m !== m) : u = [], u.length === 0 && await S();
932
+ }, I = async (E) => {
933
+ E ? u = u.filter((_) => _ !== _) : u = [], u.length === 0 && await A();
935
934
  };
936
- return c?.aborted ? await b() : c?.addEventListener("abort", () => {
937
- b();
938
- }, { once: !0 }), { initialResults: { rows: f, fields: _ }, subscribe: A, unsubscribe: b, refresh: $ };
935
+ return c?.aborted ? await I() : c?.addEventListener("abort", () => {
936
+ I();
937
+ }, { once: !0 }), { initialResults: { rows: h, fields: y }, subscribe: R, unsubscribe: I, refresh: $ };
939
938
  } };
940
939
  return { namespaceObj: r };
941
- }, qr = { name: "Live Queries", setup: Mr };
940
+ }, Mr = { name: "Live Queries", setup: Lr };
942
941
  async function $t(e, t) {
943
942
  return (await e.query(`
944
943
  WITH RECURSIVE view_dependencies AS (
@@ -1003,10 +1002,10 @@ async function At(e, t, n) {
1003
1002
  }
1004
1003
  var se = (e, t) => {
1005
1004
  for (let n of e) n(t);
1006
- }, Pr = (e, t) => {
1005
+ }, qr = (e, t) => {
1007
1006
  for (let n of e) n(t);
1008
1007
  };
1009
- class Rt extends Wn {
1008
+ class Rt extends kn {
1010
1009
  #e;
1011
1010
  #s;
1012
1011
  #i = 16;
@@ -1014,12 +1013,12 @@ class Rt extends Wn {
1014
1013
  #t = [];
1015
1014
  #r;
1016
1015
  async init(t, n) {
1017
- this.#s = t, this.#e = new Kn({
1016
+ this.#s = t, this.#e = new Vn({
1018
1017
  ...n,
1019
1018
  dataDir: n.store === "memory" ? void 0 : `idb://${t}`,
1020
1019
  database: t,
1021
1020
  extensions: {
1022
- live: qr
1021
+ live: Mr
1023
1022
  }
1024
1023
  }), await this.#e.waitReady;
1025
1024
  const r = ["rxdb_change", "rxdb_branch", "rxdb_migration"];
@@ -1093,7 +1092,7 @@ class Rt extends Wn {
1093
1092
  this.#t.length = 0;
1094
1093
  }
1095
1094
  }
1096
- const Sn = (e, t) => {
1095
+ const bn = (e, t) => {
1097
1096
  const n = P(e), r = t.map((s) => `'${s.id}'`).join(",");
1098
1097
  return `DELETE FROM ${n} WHERE id IN (${r});`;
1099
1098
  }, ue = (e, t, n) => {
@@ -1102,23 +1101,23 @@ const Sn = (e, t) => {
1102
1101
  ...e.foreignKeyColumnNames || e.foreignKeyNames
1103
1102
  ], o = [];
1104
1103
  t.forEach((u) => {
1105
- const l = Lt(e, u);
1104
+ const l = Ct(e, u);
1106
1105
  s && (l.createdBy = n.userId), a && (l.updatedBy = n.userId);
1107
- const d = Ke(e, l), f = [];
1108
- i.forEach((p) => {
1109
- const _ = d[p];
1110
- f.push(Je(_));
1111
- }), o.push(`(${f.join(",")})`);
1106
+ const p = Ke(e, l), h = [];
1107
+ i.forEach((d) => {
1108
+ const y = p[d];
1109
+ h.push(Je(y));
1110
+ }), o.push(`(${h.join(",")})`);
1112
1111
  });
1113
1112
  const c = i.map((u) => `"${u}"`).join(",");
1114
1113
  return `INSERT INTO ${r} (${c}) VALUES ${o.join(",")};`;
1115
- }, Ur = (e) => {
1114
+ }, Pr = (e) => {
1116
1115
  if (e.includes("$")) {
1117
1116
  const [t, n] = e.split("$");
1118
1117
  return [t, n];
1119
1118
  }
1120
1119
  return ["public", e];
1121
- }, jr = (e) => {
1120
+ }, Ur = (e) => {
1122
1121
  switch (e) {
1123
1122
  case K.INSERT:
1124
1123
  return "INSERT";
@@ -1127,7 +1126,7 @@ const Sn = (e, t) => {
1127
1126
  case K.DELETE:
1128
1127
  return "DELETE";
1129
1128
  }
1130
- }, xr = (e, t) => {
1129
+ }, jr = (e, t) => {
1131
1130
  t.forEach((s) => {
1132
1131
  if (!s.namespace || !s.entity) {
1133
1132
  console.warn(`RxDBChange record missing namespace or entity: id=${s.id}`);
@@ -1165,7 +1164,7 @@ const Sn = (e, t) => {
1165
1164
  }
1166
1165
  }
1167
1166
  }, Ce = (e, t) => {
1168
- const { tableName: n } = t, [r, s] = Ur(n), a = e.rxdb.schemaManager.getEntityTypeByTableName(s, r);
1167
+ const { tableName: n } = t, [r, s] = Pr(n), a = e.rxdb.schemaManager.getEntityTypeByTableName(s, r);
1169
1168
  if (!a) return;
1170
1169
  const i = e.getRepository(a), o = e.rxdb.schemaManager.getEntityMetadataByTableName(s, r);
1171
1170
  if (!o) {
@@ -1176,64 +1175,64 @@ const Sn = (e, t) => {
1176
1175
  const u = c;
1177
1176
  if (!(!u || u.length === 0))
1178
1177
  if (a === ie) {
1179
- if (xr(e, c), t.type === K.INSERT) {
1180
- const l = D(ie), d = c.map((f) => ({
1178
+ if (jr(e, c), t.type === K.INSERT) {
1179
+ const l = D(ie), p = c.map((h) => ({
1181
1180
  namespace: l.namespace,
1182
1181
  entity: l.name,
1183
- type: f.type,
1184
- id: f.id,
1185
- patch: { ...f },
1182
+ type: h.type,
1183
+ id: h.id,
1184
+ patch: { ...h },
1186
1185
  inversePatch: null,
1187
- recordAt: f.createdAt || /* @__PURE__ */ new Date()
1186
+ recordAt: h.createdAt || /* @__PURE__ */ new Date()
1188
1187
  }));
1189
- e.rxdb.dispatchEvent(new oe(d));
1188
+ e.rxdb.dispatchEvent(new oe(p));
1190
1189
  }
1191
1190
  } else {
1192
- const l = jr(t.type), d = u.map((f) => {
1193
- const p = {
1191
+ const l = Ur(t.type), p = u.map((h) => {
1192
+ const d = {
1194
1193
  namespace: o.namespace,
1195
1194
  entity: o.name,
1196
1195
  type: l,
1197
- id: f.id,
1196
+ id: h.id,
1198
1197
  patch: null,
1199
1198
  inversePatch: null,
1200
- recordAt: f.createdAt || /* @__PURE__ */ new Date()
1199
+ recordAt: h.createdAt || /* @__PURE__ */ new Date()
1201
1200
  };
1202
1201
  switch (t.type) {
1203
1202
  case K.INSERT:
1204
1203
  return {
1205
- ...p,
1206
- patch: { ...f }
1204
+ ...d,
1205
+ patch: { ...h }
1207
1206
  };
1208
1207
  case K.DELETE:
1209
1208
  return {
1210
- ...p,
1211
- inversePatch: { ...f }
1209
+ ...d,
1210
+ inversePatch: { ...h }
1212
1211
  };
1213
1212
  case K.UPDATE:
1214
1213
  return {
1215
- ...p,
1214
+ ...d,
1216
1215
  // 注意:这里无法获取变更前的数据,只能把整个 entity 作为 patch
1217
1216
  // 这是 UPDATE hook 的限制,完整的 patch/inversePatch 应该从 RxDBChange 表获取
1218
1217
  inversePatch: null,
1219
- patch: { ...f }
1218
+ patch: { ...h }
1220
1219
  };
1221
1220
  }
1222
1221
  });
1223
1222
  switch (l) {
1224
1223
  case "UPDATE":
1225
1224
  e.rxdb.dispatchEvent(
1226
- new me(d)
1225
+ new me(p)
1227
1226
  );
1228
1227
  break;
1229
1228
  case "DELETE":
1230
1229
  e.rxdb.dispatchEvent(
1231
- new Ve(d)
1230
+ new Ve(p)
1232
1231
  );
1233
1232
  break;
1234
1233
  case "INSERT":
1235
1234
  e.rxdb.dispatchEvent(
1236
- new oe(d)
1235
+ new oe(p)
1237
1236
  );
1238
1237
  break;
1239
1238
  }
@@ -1241,42 +1240,42 @@ const Sn = (e, t) => {
1241
1240
  }).catch((c) => {
1242
1241
  c.message?.includes("closed") || console.error("Failed to handle RxDBChange event", c);
1243
1242
  });
1244
- }, Br = (e, t) => {
1243
+ }, xr = (e, t) => {
1245
1244
  const n = P(e), r = [t.id];
1246
1245
  return {
1247
1246
  sql: `DELETE FROM ${n} WHERE id = $1;`,
1248
1247
  params: r
1249
1248
  };
1250
- }, In = (e, t, n) => {
1251
- const r = P(e), s = Lt(e, t);
1249
+ }, Sn = (e, t, n) => {
1250
+ const r = P(e), s = Ct(e, t);
1252
1251
  n?.userId && (e.propertyMap.has("createdBy") && (s.createdBy = n.userId), e.propertyMap.has("updatedBy") && (s.updatedBy = n.userId));
1253
1252
  const a = {};
1254
- Object.keys(s).forEach((f) => {
1255
- const p = s[f];
1256
- p != null && (a[f] = p);
1253
+ Object.keys(s).forEach((h) => {
1254
+ const d = s[h];
1255
+ d != null && (a[h] = d);
1257
1256
  });
1258
- const i = Object.keys(a), o = Ke(e, a), c = [], u = i.map((f, p) => (c.push(o[f]), `$${p + 1}`)), l = i.map((f) => `"${f}"`).join(",");
1259
- let d = `INSERT INTO ${r} (${l}) VALUES (${u.join(",")})`;
1260
- return n?.returning !== !1 ? d += " RETURNING *;" : d += ";", { sql: d, params: c };
1257
+ const i = Object.keys(a), o = Ke(e, a), c = [], u = i.map((h, d) => (c.push(o[h]), `$${d + 1}`)), l = i.map((h) => `"${h}"`).join(",");
1258
+ let p = `INSERT INTO ${r} (${l}) VALUES (${u.join(",")})`;
1259
+ return n?.returning !== !1 ? p += " RETURNING *;" : p += ";", { sql: p, params: c };
1261
1260
  }, ze = (e, t, n, r) => {
1262
- const s = zn(e, n);
1261
+ const s = Xn(e, n);
1263
1262
  e.propertyMap.has("updatedAt") && (s.updatedAt = r?.updatedAt ?? /* @__PURE__ */ new Date()), r?.userId && e.propertyMap.has("updatedBy") && (s.updatedBy = r.userId);
1264
- const a = Ke(e, s), o = Object.keys(s).map((f, p) => `"${f}" = $${p + 1}`).join(","), c = [...Object.values(a)], u = P(e), l = Array.isArray(t) ? t : [t];
1265
- let d = `UPDATE ${u} SET ${o} WHERE id `;
1263
+ const a = Ke(e, s), o = Object.keys(s).map((h, d) => `"${h}" = $${d + 1}`).join(","), c = [...Object.values(a)], u = P(e), l = Array.isArray(t) ? t : [t];
1264
+ let p = `UPDATE ${u} SET ${o} WHERE id `;
1266
1265
  if (Array.isArray(t)) {
1267
- const f = c.length + 1;
1268
- d += `= ANY($${f})`, c.push(l.map((p) => p.id));
1266
+ const h = c.length + 1;
1267
+ p += `= ANY($${h})`, c.push(l.map((d) => d.id));
1269
1268
  } else {
1270
- const f = c.length + 1;
1271
- d += `= $${f}`, c.push(t.id);
1269
+ const h = c.length + 1;
1270
+ p += `= $${h}`, c.push(t.id);
1272
1271
  }
1273
- return r?.returning !== !1 ? d += " RETURNING *;" : d += ";", {
1274
- sql: d,
1272
+ return r?.returning !== !1 ? p += " RETURNING *;" : p += ";", {
1273
+ sql: p,
1275
1274
  params: c
1276
1275
  };
1277
- }, Ze = "_", On = (e) => e.replaceAll(".", "_"), he = (e, t) => {
1276
+ }, Ze = "_", In = (e) => e.replaceAll(".", "_"), he = (e, t) => {
1278
1277
  if (e.relationAliasMap.has(t)) return e.relationAliasMap.get(t);
1279
- const n = t.includes("_") ? t : t.split("_")[0], r = Dn(e, On(n));
1278
+ const n = t.includes("_") ? t : t.split("_")[0], r = vn(e, In(n));
1280
1279
  return e.relationAliasMap.set(t, r), r;
1281
1280
  }, Fr = (e, t, n, r) => {
1282
1281
  const s = n.slice(0, r);
@@ -1288,48 +1287,48 @@ const Sn = (e, t) => {
1288
1287
  i.push({ metadata: a, relation: c }), a = e.rxdb.schemaManager.getEntityMetadata(c.mappedEntity, c.mappedNamespace);
1289
1288
  }
1290
1289
  return { metaWalker: a, relPairs: i };
1291
- }, kr = (e, t, n, r, s) => {
1290
+ }, Br = (e, t, n, r, s) => {
1292
1291
  for (let a = s.length - 1; a > 0; a--) {
1293
1292
  const i = s.slice(a);
1294
1293
  if (i.length === 0) continue;
1295
1294
  const { metaWalker: o, relPairs: c } = Fr(e, n, s, a);
1296
1295
  if (!o || c.length === 0) continue;
1297
- const u = i[0], l = i.slice(1).join("."), d = o.propertyMap.get(u);
1298
- if (d && d.type === N.keyValue) {
1299
- const f = s.slice(0, a).join(".");
1300
- vn(e, t, c, f);
1301
- const p = c[c.length - 1].relation, _ = de(c, f, p), S = he(t, _), $ = l ? `$.${l}` : "$";
1302
- return t.fieldAliasMap.set(r, `"${S}"."${d.columnName}" ->> '${$.replace("$.", "")}'`), !0;
1296
+ const u = i[0], l = i.slice(1).join("."), p = o.propertyMap.get(u);
1297
+ if (p && p.type === N.keyValue) {
1298
+ const h = s.slice(0, a).join(".");
1299
+ On(e, t, c, h);
1300
+ const d = c[c.length - 1].relation, y = de(c, h, d), A = he(t, y), $ = l ? `$.${l}` : "$";
1301
+ return t.fieldAliasMap.set(r, `"${A}"."${p.columnName}" ->> '${$.replace("$.", "")}'`), !0;
1303
1302
  }
1304
1303
  }
1305
1304
  return !1;
1306
- }, vn = (e, t, n, r) => {
1305
+ }, On = (e, t, n, r) => {
1307
1306
  n.forEach(({ metadata: s, relation: a }, i) => {
1308
1307
  let o = e.rxdb.schemaManager.findMappedRelation(s, a);
1309
1308
  if (!o)
1310
- if (a.kind === F.ONE_TO_MANY || a.kind === F.MANY_TO_MANY) {
1311
- const d = s.relationMap.get(a.mappedProperty);
1312
- d && (o = { metadata: s, relation: d });
1313
- } else (a.kind === F.MANY_TO_ONE || a.kind === F.ONE_TO_ONE) && (o = { metadata: s, relation: a });
1309
+ if (a.kind === B.ONE_TO_MANY || a.kind === B.MANY_TO_MANY) {
1310
+ const p = s.relationMap.get(a.mappedProperty);
1311
+ p && (o = { metadata: s, relation: p });
1312
+ } else (a.kind === B.MANY_TO_ONE || a.kind === B.ONE_TO_ONE) && (o = { metadata: s, relation: a });
1314
1313
  if (!o) throw new x("mappedRelation not found");
1315
1314
  const c = de(n, r, a), u = he(t, c);
1316
1315
  let l = Ze;
1317
1316
  if (i > 0) {
1318
- const d = n[i - 1], f = de(n, r, d.relation);
1319
- l = he(t, f);
1317
+ const p = n[i - 1], h = de(n, r, p.relation);
1318
+ l = he(t, h);
1320
1319
  }
1321
1320
  switch (a.kind) {
1322
- case F.ONE_TO_MANY:
1323
- Wr(
1321
+ case B.ONE_TO_MANY:
1322
+ kr(
1324
1323
  t,
1325
1324
  o,
1326
1325
  u,
1327
1326
  l
1328
1327
  );
1329
1328
  break;
1330
- case F.ONE_TO_ONE:
1331
- case F.MANY_TO_ONE:
1332
- Gr(
1329
+ case B.ONE_TO_ONE:
1330
+ case B.MANY_TO_ONE:
1331
+ Wr(
1333
1332
  t,
1334
1333
  o,
1335
1334
  u,
@@ -1337,8 +1336,8 @@ const Sn = (e, t) => {
1337
1336
  a
1338
1337
  );
1339
1338
  break;
1340
- case F.MANY_TO_MANY:
1341
- Hr(
1339
+ case B.MANY_TO_MANY:
1340
+ Gr(
1342
1341
  t,
1343
1342
  o,
1344
1343
  u,
@@ -1348,46 +1347,46 @@ const Sn = (e, t) => {
1348
1347
  break;
1349
1348
  }
1350
1349
  });
1351
- }, Wr = (e, t, n, r) => {
1350
+ }, kr = (e, t, n, r) => {
1352
1351
  const s = fe(e, t.metadata), a = t.relation.columnName, i = `"${n}"."${a}" = ${et(r)}."id"`;
1353
1352
  s.find((c) => c.joinTableName === n && c.on === i) || s.push({
1354
1353
  joinTableName: n,
1355
1354
  on: i
1356
1355
  });
1357
- }, Gr = (e, t, n, r, s) => {
1356
+ }, Wr = (e, t, n, r, s) => {
1358
1357
  const a = fe(e, t.metadata), i = `"${n}"."id" = ${et(r)}."${s.columnName}"`;
1359
1358
  a.find((c) => c.joinTableName === n && c.on === i) || a.push({
1360
1359
  joinTableName: n,
1361
1360
  on: i
1362
1361
  });
1363
- }, Hr = (e, t, n, r, s) => {
1364
- const a = D(s.junctionEntityType), i = fe(e, a), o = Dn(e, On(`${s.name}_m_n`)), c = `"${o}"."${t.relation.columnName}" = ${et(r)}."id"`;
1362
+ }, Gr = (e, t, n, r, s) => {
1363
+ const a = D(s.junctionEntityType), i = fe(e, a), o = vn(e, In(`${s.name}_m_n`)), c = `"${o}"."${t.relation.columnName}" = ${et(r)}."id"`;
1365
1364
  i.find(
1366
- (p) => p.joinTableName === o && p.on === c
1365
+ (d) => d.joinTableName === o && d.on === c
1367
1366
  ) || i.push({
1368
1367
  joinTableName: o,
1369
1368
  on: c
1370
1369
  });
1371
- const l = fe(e, t.metadata), d = `"${n}"."id" = "${o}"."${s.columnName}"`;
1372
- l.find((p) => p.joinTableName === n && p.on === d) || l.push({
1370
+ const l = fe(e, t.metadata), p = `"${n}"."id" = "${o}"."${s.columnName}"`;
1371
+ l.find((d) => d.joinTableName === n && d.on === p) || l.push({
1373
1372
  joinTableName: n,
1374
- on: d
1373
+ on: p
1375
1374
  });
1376
- }, fe = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), Dn = (e, t) => {
1375
+ }, fe = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), vn = (e, t) => {
1377
1376
  let n = t, r = 1;
1378
1377
  for (; e.usedAliases.has(n); )
1379
1378
  n = `${t}_${r++}`;
1380
1379
  return e.usedAliases.add(n), n;
1381
- }, de = (e, t, n) => e.length === 1 ? n.name : `${t}_${n.name}`, et = (e) => e === Ze ? e : `"${e}"`, Cn = (e, t, n) => {
1380
+ }, de = (e, t, n) => e.length === 1 ? n.name : `${t}_${n.name}`, et = (e) => e === Ze ? e : `"${e}"`, Dn = (e, t, n) => {
1382
1381
  const r = {
1383
1382
  joinMap: /* @__PURE__ */ new Map(),
1384
1383
  usedAliases: /* @__PURE__ */ new Set(),
1385
1384
  fieldAliasMap: /* @__PURE__ */ new Map(),
1386
1385
  relationAliasMap: /* @__PURE__ */ new Map()
1387
1386
  };
1388
- Gn(n, (a, i, o) => {
1387
+ Wn(n, (a, i, o) => {
1389
1388
  const c = i;
1390
- a !== "field" || !c.includes(".") || Vr(e, r, t, c, o);
1389
+ a !== "field" || !c.includes(".") || Hr(e, r, t, c, o);
1391
1390
  });
1392
1391
  const s = [];
1393
1392
  for (const [a, i] of r.joinMap.entries()) {
@@ -1396,7 +1395,7 @@ const Sn = (e, t) => {
1396
1395
  s.push(` LEFT JOIN ${o} "${c.joinTableName}" ON ${c.on}`);
1397
1396
  }
1398
1397
  return { joinSQL: s.join(""), fieldAliasMap: r.fieldAliasMap };
1399
- }, Vr = (e, t, n, r, s) => {
1398
+ }, Hr = (e, t, n, r, s) => {
1400
1399
  const a = r.split(".");
1401
1400
  try {
1402
1401
  const u = e.rxdb.schemaManager.getFieldRelations(n, r);
@@ -1405,9 +1404,9 @@ const Sn = (e, t) => {
1405
1404
  return;
1406
1405
  }
1407
1406
  const l = r.replace(`.${u.propertyName}`, "");
1408
- vn(e, t, u.relations, l);
1409
- const d = u.relations[u.relations.length - 1], f = de(u.relations, l, d.relation), p = he(t, f);
1410
- t.fieldAliasMap.set(r, `"${p}"."${u.property.columnName}"`);
1407
+ On(e, t, u.relations, l);
1408
+ const p = u.relations[u.relations.length - 1], h = de(u.relations, l, p.relation), d = he(t, h);
1409
+ t.fieldAliasMap.set(r, `"${d}"."${u.property.columnName}"`);
1411
1410
  return;
1412
1411
  } catch {
1413
1412
  }
@@ -1417,8 +1416,8 @@ const Sn = (e, t) => {
1417
1416
  t.fieldAliasMap.set(r, `"${Ze}"."${c.columnName}" ->> '${u}'`);
1418
1417
  return;
1419
1418
  }
1420
- kr(e, t, n, r, a);
1421
- }, pe = "_", Kr = {
1419
+ Br(e, t, n, r, a);
1420
+ }, pe = "_", Vr = {
1422
1421
  "=": "=",
1423
1422
  "!=": "!=",
1424
1423
  ">": ">",
@@ -1435,13 +1434,13 @@ const Sn = (e, t) => {
1435
1434
  notStartsWith: "NOT LIKE",
1436
1435
  endsWith: "LIKE",
1437
1436
  notEndsWith: "NOT LIKE"
1438
- }, Jr = (e, t) => {
1437
+ }, Kr = (e, t) => {
1439
1438
  if (e?.length)
1440
1439
  return e.map((n) => {
1441
- const r = Ln(n.field, t);
1440
+ const r = Cn(n.field, t);
1442
1441
  return `${pe}."${r}" ${n.sort.toUpperCase()}`;
1443
1442
  }).join(", ");
1444
- }, Yr = (e) => Kr[e] || e, Qr = (e) => e && typeof e == "object" && "rules" in e && Array.isArray(e.rules), Ln = (e, t) => {
1443
+ }, Jr = (e) => Vr[e] || e, Yr = (e) => e && typeof e == "object" && "rules" in e && Array.isArray(e.rules), Cn = (e, t) => {
1445
1444
  if (t && !e.includes(".")) {
1446
1445
  const n = t.propertyMap.get(e);
1447
1446
  if (n)
@@ -1451,10 +1450,10 @@ const Sn = (e, t) => {
1451
1450
  return s[a];
1452
1451
  }
1453
1452
  return e;
1454
- }, Xr = (e, t, n) => {
1453
+ }, Qr = (e, t, n) => {
1455
1454
  if (t) return t;
1456
1455
  if (!e.includes(".")) {
1457
- const o = Ln(e, n);
1456
+ const o = Cn(e, n);
1458
1457
  return o.toLowerCase() !== o ? `"${o}"` : o;
1459
1458
  }
1460
1459
  const r = e.split("."), s = r[0], a = n?.propertyMap.get(s);
@@ -1462,8 +1461,8 @@ const Sn = (e, t) => {
1462
1461
  return `"${a.columnName}" ->> '${r[1]}'`;
1463
1462
  const i = e.lastIndexOf(".");
1464
1463
  return `"${e.slice(0, i)}".${e.slice(i + 1)}`;
1465
- }, zr = (e, t, n = /* @__PURE__ */ new Map(), r) => {
1466
- const s = String(e.field), a = n.get(s), i = Xr(s, a, r), o = e.value, c = e.operator;
1464
+ }, Xr = (e, t, n = /* @__PURE__ */ new Map(), r) => {
1465
+ const s = String(e.field), a = n.get(s), i = Qr(s, a, r), o = e.value, c = e.operator;
1467
1466
  if (c === "null" || c === "notNull")
1468
1467
  return c === "null" ? `${i} IS NULL` : `${i} IS NOT NULL`;
1469
1468
  if (o === null)
@@ -1480,38 +1479,38 @@ const Sn = (e, t) => {
1480
1479
  if (l && (l.type === N.stringArray || l.type === N.numberArray) && (c === "in" || c === "notIn")) {
1481
1480
  if (!Array.isArray(o)) return "";
1482
1481
  t.push(JSON.stringify(o));
1483
- const f = `${i} @> $${t.length}::jsonb`;
1484
- return c === "notIn" ? `NOT ${f}` : f;
1482
+ const h = `${i} @> $${t.length}::jsonb`;
1483
+ return c === "notIn" ? `NOT ${h}` : h;
1485
1484
  }
1486
1485
  if (c === "in" || c === "notIn")
1487
1486
  return Array.isArray(o) ? o.length === 0 ? c === "in" ? "1=0" : "1=1" : (t.push(o), `${i} ${c === "in" ? "= ANY" : "!= ALL"}($${t.length})`) : "";
1488
1487
  if (c === "between" || c === "notBetween")
1489
1488
  return !Array.isArray(o) || o.length !== 2 ? "" : (t.push(o[0], o[1]), `${i} ${c === "between" ? "BETWEEN" : "NOT BETWEEN"} $${t.length - 1} AND $${t.length}`);
1490
1489
  if (["contains", "notContains", "startsWith", "notStartsWith", "endsWith", "notEndsWith"].includes(c)) {
1491
- let f = "";
1492
- c === "contains" || c === "notContains" ? f = `%${o}%` : c === "startsWith" || c === "notStartsWith" ? f = `${o}%` : (c === "endsWith" || c === "notEndsWith") && (f = `%${o}`), t.push(f);
1493
- const p = c.startsWith("not") ? "NOT LIKE" : "LIKE";
1494
- return `${i} ${p} $${t.length}`;
1490
+ let h = "";
1491
+ c === "contains" || c === "notContains" ? h = `%${o}%` : c === "startsWith" || c === "notStartsWith" ? h = `${o}%` : (c === "endsWith" || c === "notEndsWith") && (h = `%${o}`), t.push(h);
1492
+ const d = c.startsWith("not") ? "NOT LIKE" : "LIKE";
1493
+ return `${i} ${d} $${t.length}`;
1495
1494
  }
1496
- const d = Yr(c);
1497
- return t.push(o), l && l.type === N.uuid ? `${i}::uuid ${d} $${t.length}::uuid` : `${i} ${d} $${t.length}`;
1495
+ const p = Jr(c);
1496
+ return t.push(o), l && l.type === N.uuid ? `${i}::uuid ${p} $${t.length}::uuid` : `${i} ${p} $${t.length}`;
1498
1497
  }, we = (e, t, n = /* @__PURE__ */ new Map(), r) => {
1499
1498
  const s = e.rules.map(
1500
- (i) => Qr(i) ? we(i, t, n, r) : zr(i, t, n, r)
1499
+ (i) => Yr(i) ? we(i, t, n, r) : Xr(i, t, n, r)
1501
1500
  ).filter(Boolean);
1502
1501
  if (!s.length) return "";
1503
1502
  if (s.length === 1) return s[0];
1504
1503
  const a = e.combinator.toUpperCase();
1505
1504
  return `(${s.join(` ${a} `)})`;
1506
- }, Zr = (e, t) => {
1505
+ }, zr = (e, t) => {
1507
1506
  let n = `SELECT ${pe}.* FROM ${e.tableName} AS ${pe}`;
1508
1507
  return e.join && (n += ` ${e.join}`), e.where && (n += ` WHERE ${e.where}`), e.orderBy && (n += ` ORDER BY ${e.orderBy}`), e.limit !== void 0 && (t.push(e.limit), n += ` LIMIT $${t.length}`), e.offset !== void 0 && e.offset > 0 && (t.push(e.offset), n += ` OFFSET $${t.length}`), n;
1509
- }, ea = (e) => {
1508
+ }, Zr = (e) => {
1510
1509
  let t = `SELECT COUNT(*) as count FROM ${e.tableName} AS ${pe}`;
1511
1510
  return e.join && (t += ` ${e.join}`), e.where && (t += ` WHERE ${e.where}`), t;
1512
1511
  }, Ee = (e, t, n) => {
1513
- const r = P(t), s = [], { joinSQL: a, fieldAliasMap: i } = n.where ? Cn(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, o = n.where ? we(n.where, s, i, t) : void 0, c = Jr(n.orderBy, t), u = "limit" in n ? n.limit : void 0, l = "offset" in n ? n.offset : void 0;
1514
- return { sql: Zr(
1512
+ const r = P(t), s = [], { joinSQL: a, fieldAliasMap: i } = n.where ? Dn(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, o = n.where ? we(n.where, s, i, t) : void 0, c = Kr(n.orderBy, t), u = "limit" in n ? n.limit : void 0, l = "offset" in n ? n.offset : void 0;
1513
+ return { sql: zr(
1515
1514
  {
1516
1515
  tableName: r,
1517
1516
  where: o,
@@ -1522,23 +1521,23 @@ const Sn = (e, t) => {
1522
1521
  },
1523
1522
  s
1524
1523
  ), params: s };
1525
- }, ta = (e, t, n) => {
1524
+ }, ea = (e, t, n) => {
1526
1525
  if (n.groupBy)
1527
1526
  throw new x("groupBy not supported in count queries");
1528
- const r = P(t), s = [], { joinSQL: a, fieldAliasMap: i } = n.where ? Cn(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, o = n.where ? we(n.where, s, i, t) : void 0;
1529
- return { sql: ea({
1527
+ const r = P(t), s = [], { joinSQL: a, fieldAliasMap: i } = n.where ? Dn(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, o = n.where ? we(n.where, s, i, t) : void 0;
1528
+ return { sql: Zr({
1530
1529
  tableName: r,
1531
1530
  where: o,
1532
1531
  join: a
1533
1532
  }), params: s };
1534
- }, na = (e, t) => {
1533
+ }, ta = (e, t) => {
1535
1534
  const n = P(e), r = t.map((a, i) => `$${i + 1}`).join(", ");
1536
1535
  return {
1537
1536
  sql: `SELECT * FROM ${n} WHERE id IN (${r})`,
1538
1537
  params: t
1539
1538
  };
1540
1539
  };
1541
- class sa extends Fn {
1540
+ class na extends Fn {
1542
1541
  constructor(t, n) {
1543
1542
  super(t.rxdb, n), this.adapter = t, this.metadata = D(n);
1544
1543
  }
@@ -1552,7 +1551,7 @@ class sa extends Fn {
1552
1551
  */
1553
1552
  async findByRowIds(t) {
1554
1553
  if (t.length === 0) return [];
1555
- const { sql: n, params: r } = na(this.metadata, t), s = await this.adapter.query(n, r);
1554
+ const { sql: n, params: r } = ta(this.metadata, t), s = await this.adapter.query(n, r);
1556
1555
  return this.addQueryCache(s);
1557
1556
  }
1558
1557
  addQueryCache(t, n = !0) {
@@ -1565,7 +1564,7 @@ class sa extends Fn {
1565
1564
  });
1566
1565
  }
1567
1566
  }
1568
- class Mn extends sa {
1567
+ class Ln extends na {
1569
1568
  async get(t) {
1570
1569
  const n = {
1571
1570
  where: {
@@ -1588,11 +1587,11 @@ class Mn extends sa {
1588
1587
  return this.addQueryCache(s);
1589
1588
  }
1590
1589
  async count(t) {
1591
- const { sql: n, params: r } = ta(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1590
+ const { sql: n, params: r } = ea(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1592
1591
  return parseInt(s.rows[0].count);
1593
1592
  }
1594
1593
  async create(t) {
1595
- const { sql: n, params: r } = In(this.metadata, t, this.rxdb.context), s = await this.adapter.query(n, r);
1594
+ const { sql: n, params: r } = Sn(this.metadata, t, this.rxdb.context), s = await this.adapter.query(n, r);
1596
1595
  return this.addQueryCache(s, !0), t;
1597
1596
  }
1598
1597
  async update(t, n) {
@@ -1601,32 +1600,32 @@ class Mn extends sa {
1601
1600
  return await this.adapter.query(r, s), t;
1602
1601
  }
1603
1602
  async remove(t) {
1604
- const { sql: n, params: r } = Br(this.metadata, t);
1603
+ const { sql: n, params: r } = xr(this.metadata, t);
1605
1604
  return await this.adapter.query(n, r), t;
1606
1605
  }
1607
1606
  }
1608
1607
  const Ne = (e, t, n) => {
1609
1608
  const { isCount: r, isFindDescendants: s, entityId: a, where: i } = n, o = !a, c = P(t);
1610
1609
  let u = "";
1611
- const d = [`c.level < ${n.level || 0}`], f = [];
1612
- if (o || f.push(a), i) {
1613
- const A = /* @__PURE__ */ new Map(), b = (m) => {
1614
- if ("rules" in m)
1615
- return { ...m, rules: m.rules.map(b) };
1616
- if (m.field && typeof m.field == "string" && m.field.startsWith("children.")) {
1617
- const g = m.field.substring(9), I = t.propertyMap.get(g)?.columnName ?? g;
1618
- A.set(m.field, `children."${I}"`);
1610
+ const p = [`c.level < ${n.level || 0}`], h = [];
1611
+ if (o || h.push(a), i) {
1612
+ const R = /* @__PURE__ */ new Map(), I = (_) => {
1613
+ if ("rules" in _)
1614
+ return { ..._, rules: _.rules.map(I) };
1615
+ if (_.field && typeof _.field == "string" && _.field.startsWith("children.")) {
1616
+ const T = _.field.substring(9), S = t.propertyMap.get(T)?.columnName ?? T;
1617
+ R.set(_.field, `children."${S}"`);
1619
1618
  }
1620
- return m;
1619
+ return _;
1621
1620
  };
1622
- b(i);
1623
- const E = we(i, f, A, t);
1624
- E && d.push(E);
1625
- }
1626
- const p = d.filter(Boolean).join(" AND ");
1627
- p && (u = `WHERE ${p}`);
1628
- let _ = "*";
1629
- return r && (o ? _ = "count(*) AS count" : _ = "(count(*) - 1) AS count"), {
1621
+ I(i);
1622
+ const E = we(i, h, R, t);
1623
+ E && p.push(E);
1624
+ }
1625
+ const d = p.filter(Boolean).join(" AND ");
1626
+ d && (u = `WHERE ${d}`);
1627
+ let y = "*";
1628
+ return r && (o ? y = "count(*) AS count" : y = "(count(*) - 1) AS count"), {
1630
1629
  sql: `WITH RECURSIVE __children AS (
1631
1630
  SELECT *, 0 AS level
1632
1631
  FROM ${c}
@@ -1638,88 +1637,83 @@ const Ne = (e, t, n) => {
1638
1637
  ${u}
1639
1638
  )
1640
1639
 
1641
- SELECT ${_} FROM __children${r ? "" : " ORDER BY level, id"};`,
1642
- params: f
1640
+ SELECT ${y} FROM __children${r ? "" : " ORDER BY level, id"};`,
1641
+ params: h
1643
1642
  };
1644
- }, ra = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !0 }), aa = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !0, isCount: !0 }), ia = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !1 }), oa = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !1, isCount: !0 });
1645
- class ca extends Mn {
1643
+ }, sa = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !0 }), ra = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !0, isCount: !0 }), aa = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !1 }), ia = (e, t, n) => Ne(e, t, { ...n, isFindDescendants: !1, isCount: !0 });
1644
+ class oa extends Ln {
1646
1645
  async findDescendants(t) {
1647
- const { sql: n, params: r } = ra(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1646
+ const { sql: n, params: r } = sa(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1648
1647
  return !s.rows || s.rows.length === 0 ? [] : s.rows.map((i) => {
1649
1648
  const o = Z(this.metadata, i);
1650
1649
  return this.createEntityRef(o);
1651
1650
  });
1652
1651
  }
1653
1652
  async countDescendants(t) {
1654
- const { sql: n, params: r } = aa(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], i = a.count || a["?column?"];
1653
+ const { sql: n, params: r } = ra(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], i = a.count || a["?column?"];
1655
1654
  return parseInt(String(i), 10) || 0;
1656
1655
  }
1657
1656
  async findAncestors(t) {
1658
- const { sql: n, params: r } = ia(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1657
+ const { sql: n, params: r } = aa(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1659
1658
  return !s.rows || s.rows.length === 0 ? [] : s.rows.map((i) => {
1660
1659
  const o = Z(this.metadata, i);
1661
1660
  return this.createEntityRef(o);
1662
1661
  });
1663
1662
  }
1664
1663
  async countAncestors(t) {
1665
- const { sql: n, params: r } = oa(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], i = a.count || a["?column?"];
1664
+ const { sql: n, params: r } = ia(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], i = a.count || a["?column?"];
1666
1665
  return parseInt(String(i), 10) || 0;
1667
1666
  }
1668
1667
  }
1669
- const la = async (e, t) => {
1668
+ const ca = async (e, t) => {
1670
1669
  const n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Date();
1671
1670
  for (const [s, a] of t.create.entries()) {
1672
1671
  const i = Array.from(a);
1673
- i.forEach((_) => n.add(_));
1672
+ i.forEach((y) => n.add(y));
1674
1673
  const o = D(s), c = ue(o, i, e.rxdb.context);
1675
1674
  await e.query(c);
1676
- const u = i.map((_) => _.id), { sql: l, params: d } = Ee(e, o, {
1675
+ const u = i.map((y) => y.id), { sql: l, params: p } = Ee(e, o, {
1677
1676
  where: { combinator: "and", rules: [{ field: "id", operator: "in", value: u }] }
1678
- }), f = await e.query(l, d), p = e.getRepository(s);
1679
- for (const _ of f.rows) {
1680
- const S = Z(o, _), $ = S.id;
1681
- if (p.hasEntityRef($)) {
1682
- const A = p.getEntityRef($);
1683
- p.updateEntity(A, S);
1684
- const b = J(A);
1685
- b.local = !0, b.modified = !1;
1677
+ }), h = await e.query(l, p), d = e.getRepository(s);
1678
+ for (const y of h.rows) {
1679
+ const A = Z(o, y), $ = A.id;
1680
+ if (d.hasEntityRef($)) {
1681
+ const R = d.getEntityRef($);
1682
+ d.updateEntity(R, A);
1683
+ const I = J(R);
1684
+ I.local = !0, I.modified = !1;
1686
1685
  }
1687
1686
  }
1688
1687
  }
1689
1688
  for (const [s, a] of t.update.entries()) {
1690
1689
  const i = Array.from(a);
1691
- i.forEach((l) => n.add(l));
1692
- const o = D(s), c = Object.groupBy(i, (l) => {
1693
- const d = J(l);
1694
- return Ot(Object.keys(d.patch || {}).sort());
1695
- }), u = e.getRepository(s);
1696
- for (const l of Object.values(c)) {
1697
- if (!l || l.length === 0) continue;
1698
- const d = l[0], f = J(d), { sql: p, params: _ } = ze(o, l, f.patch || {}, {
1690
+ i.forEach((h) => n.add(h));
1691
+ const o = D(s), c = e.getRepository(s);
1692
+ for (const h of i) {
1693
+ const d = J(h), { sql: y, params: A } = ze(o, h, d.patch || {}, {
1699
1694
  ...e.rxdb.context,
1700
1695
  returning: !1,
1701
- // 后续用 SELECT 获取
1702
1696
  updatedAt: r
1703
1697
  });
1704
- await e.query(p, _);
1705
- const S = l.map((b) => b.id), $ = Ee(e, o, {
1706
- where: { combinator: "and", rules: [{ field: "id", operator: "in", value: S }] }
1707
- }), A = await e.query($.sql, $.params);
1708
- for (const b of A.rows) {
1709
- const E = Z(o, b), m = E.id;
1710
- if (u.hasEntityRef(m)) {
1711
- const g = u.getEntityRef(m);
1712
- u.updateEntity(g, E);
1713
- const R = J(g);
1714
- R.local = !0, R.modified = !1;
1715
- }
1698
+ await e.query(y, A);
1699
+ }
1700
+ const u = i.map((h) => h.id), l = Ee(e, o, {
1701
+ where: { combinator: "and", rules: [{ field: "id", operator: "in", value: u }] }
1702
+ }), p = await e.query(l.sql, l.params);
1703
+ for (const h of p.rows) {
1704
+ const d = Z(o, h), y = d.id;
1705
+ if (c.hasEntityRef(y)) {
1706
+ const A = c.getEntityRef(y);
1707
+ c.updateEntity(A, d);
1708
+ const $ = J(A);
1709
+ $.local = !0, $.modified = !1;
1716
1710
  }
1717
1711
  }
1718
1712
  }
1719
1713
  for (const [, s] of t.remove.entries()) {
1720
1714
  const a = Array.from(s), i = D(a[0]?.constructor);
1721
1715
  if (a.length > 0) {
1722
- const o = Sn(i, a);
1716
+ const o = bn(i, a);
1723
1717
  await e.query(o);
1724
1718
  }
1725
1719
  for (const o of a) {
@@ -1729,25 +1723,25 @@ const la = async (e, t) => {
1729
1723
  }
1730
1724
  }
1731
1725
  return Array.from(n);
1732
- }, ua = (e, t) => {
1726
+ }, la = (e, t) => {
1733
1727
  const n = P(t);
1734
1728
  let r = `CREATE TABLE ${n} (`;
1735
1729
  const s = [], a = [], i = [];
1736
1730
  t.propertyMap.forEach((c) => {
1737
1731
  let u = "";
1738
1732
  u += `"${c.columnName}"`;
1739
- const l = Dt(c);
1733
+ const l = vt(c);
1740
1734
  if (c.primary ? c.type === N.integer ? u += " serial PRIMARY KEY" : u += ` ${l} PRIMARY KEY` : u += ` ${l}`, Reflect.get(c, "default") !== void 0) {
1741
- let d = c.default;
1742
- It(c.default) && (d = c.default()), Hn(d) ? ["CURRENT_TIMESTAMP", "now()"].includes(d) ? u += " DEFAULT now()" : u += ` DEFAULT '${d}'` : d instanceof Date ? u += ` DEFAULT '${d.toISOString()}'` : typeof d == "boolean" || typeof d == "number" ? u += ` DEFAULT ${String(d)}` : u += ` DEFAULT '${String(d)}'`;
1735
+ let p = c.default;
1736
+ It(c.default) && (p = c.default()), Gn(p) ? ["CURRENT_TIMESTAMP", "now()"].includes(p) ? u += " DEFAULT now()" : u += ` DEFAULT '${p}'` : p instanceof Date ? u += ` DEFAULT '${p.toISOString()}'` : typeof p == "boolean" || typeof p == "number" ? u += ` DEFAULT ${String(p)}` : u += ` DEFAULT '${String(p)}'`;
1743
1737
  }
1744
1738
  if (c.nullable || (u += " NOT NULL"), c.unique && s.push(
1745
- `CREATE UNIQUE INDEX "${Ct(t, c)}" on ${n} ("${c.columnName}" ${Xn(c)});`
1739
+ `CREATE UNIQUE INDEX "${Dt(t, c)}" on ${n} ("${c.columnName}" ${Qn(c)});`
1746
1740
  ), c.type === N.enum) {
1747
- const d = c;
1748
- if (d.enum && d.enum.length > 0) {
1749
- const f = d.enum.map((p) => `'${String(p).replace(/'/g, "''")}'`).join(", ");
1750
- a.push(`CHECK ("${c.columnName}" IN (${f}))`);
1741
+ const p = c;
1742
+ if (p.enum && p.enum.length > 0) {
1743
+ const h = p.enum.map((d) => `'${String(d).replace(/'/g, "''")}'`).join(", ");
1744
+ a.push(`CHECK ("${c.columnName}" IN (${h}))`);
1751
1745
  }
1752
1746
  }
1753
1747
  i.push(u);
@@ -1762,7 +1756,7 @@ ${c}`).join(","), r += `
1762
1756
  return s.length && (r += `
1763
1757
  ` + s.join(`
1764
1758
  `)), r;
1765
- }, ha = (e, t) => {
1759
+ }, ua = (e, t) => {
1766
1760
  let n = "";
1767
1761
  const r = P(t);
1768
1762
  return t.indexes && t.indexes.length > 0 && t.indexes.forEach((s) => {
@@ -1770,13 +1764,13 @@ ${c}`).join(","), r += `
1770
1764
  n += `
1771
1765
  CREATE ${o}INDEX "${a}" ON ${r}(${i});`;
1772
1766
  }), n;
1773
- }, fa = (e, t) => {
1767
+ }, ha = (e, t) => {
1774
1768
  let n = "";
1775
1769
  const r = P(t);
1776
1770
  return Array.from(t.relationMap.values()).forEach((s) => {
1777
1771
  switch (s.kind) {
1778
- case F.ONE_TO_ONE:
1779
- case F.MANY_TO_ONE:
1772
+ case B.ONE_TO_ONE:
1773
+ case B.MANY_TO_ONE:
1780
1774
  {
1781
1775
  const a = s.columnName;
1782
1776
  let i = "uuid";
@@ -1790,12 +1784,12 @@ CREATE ${o}INDEX "${a}" ON ${r}(${i});`;
1790
1784
  const u = Array.from(c.propertyMap.values()).find(
1791
1785
  (l) => l.primary
1792
1786
  );
1793
- u && (i = Dt(u));
1787
+ u && (i = vt(u));
1794
1788
  }
1795
1789
  } catch {
1796
1790
  }
1797
1791
  if (n += `
1798
- ALTER TABLE ${r} ADD COLUMN "${a}" ${i}`, s.nullable || (n += " NOT NULL"), s.kind === F.MANY_TO_ONE && Reflect.get(s, "default") !== void 0) {
1792
+ ALTER TABLE ${r} ADD COLUMN "${a}" ${i}`, s.nullable || (n += " NOT NULL"), s.kind === B.MANY_TO_ONE && Reflect.get(s, "default") !== void 0) {
1799
1793
  const c = s;
1800
1794
  let u = c.default;
1801
1795
  It(c.default) && (u = c.default()), n += ` DEFAULT '${u}'`;
@@ -1806,24 +1800,24 @@ ALTER TABLE ${r} ADD COLUMN "${a}" ${i}`, s.nullable || (n += " NOT NULL"), s.ki
1806
1800
  const c = e.rxdb.schemaManager.getEntityMetadata(
1807
1801
  s.mappedEntity,
1808
1802
  s.mappedNamespace
1809
- ), u = vt(
1803
+ ), u = Ot(
1810
1804
  c?.tableName ?? s.mappedEntity,
1811
1805
  s.mappedNamespace || t.namespace
1812
1806
  ), l = `${r}_${a}_fk`.replace(/"/g, "");
1813
1807
  n += `
1814
- ALTER TABLE ${r} ADD CONSTRAINT "${l}" FOREIGN KEY ("${a}") REFERENCES ${u}(id)`, s.onDelete ? n += ` ON DELETE ${s.onDelete}` : s.kind === F.MANY_TO_ONE && (s.nullable ? n += " ON DELETE SET NULL" : n += " ON DELETE CASCADE"), n += " DEFERRABLE INITIALLY DEFERRED", n += ";";
1808
+ ALTER TABLE ${r} ADD CONSTRAINT "${l}" FOREIGN KEY ("${a}") REFERENCES ${u}(id)`, s.onDelete ? n += ` ON DELETE ${s.onDelete}` : s.kind === B.MANY_TO_ONE && (s.nullable ? n += " ON DELETE SET NULL" : n += " ON DELETE CASCADE"), n += " DEFERRABLE INITIALLY DEFERRED", n += ";";
1815
1809
  }
1816
- (s.unique || s.kind === F.ONE_TO_ONE) && (n += `
1817
- CREATE UNIQUE INDEX "${Ct(t, s)}" ON ${r}("${a}");`);
1810
+ (s.unique || s.kind === B.ONE_TO_ONE) && (n += `
1811
+ CREATE UNIQUE INDEX "${Dt(t, s)}" ON ${r}("${a}");`);
1818
1812
  }
1819
1813
  break;
1820
1814
  }
1821
1815
  }), n;
1822
- }, qn = (e, t) => {
1816
+ }, Mn = (e, t) => {
1823
1817
  let n = "";
1824
- return n += ua(e, t), n += fa(e, t), n += ha(e, t), n;
1818
+ return n += la(e, t), n += ha(e, t), n += ua(e, t), n;
1825
1819
  };
1826
- function da() {
1820
+ function fa() {
1827
1821
  return `
1828
1822
  -- 创建触发器函数(如果不存在)
1829
1823
  CREATE OR REPLACE FUNCTION notify_change()
@@ -1863,7 +1857,7 @@ END;
1863
1857
  $$ LANGUAGE plpgsql;
1864
1858
  `.trim();
1865
1859
  }
1866
- function Pn(e) {
1860
+ function qn(e) {
1867
1861
  const t = `${e}_notify_trigger`;
1868
1862
  return `
1869
1863
  -- 只在表存在时创建触发器
@@ -1887,14 +1881,14 @@ BEGIN
1887
1881
  END $$;
1888
1882
  `.trim();
1889
1883
  }
1890
- function Da(e) {
1884
+ function Oa(e) {
1891
1885
  return `DROP TRIGGER IF EXISTS "${`${e}_notify_trigger`}" ON "${e}";`;
1892
1886
  }
1893
- function pa(e = ["RxDBChange", "RxDBBranch", "RxDBMigration"]) {
1887
+ function da(e = ["RxDBChange", "RxDBBranch", "RxDBMigration"]) {
1894
1888
  const t = [];
1895
- t.push(da());
1889
+ t.push(fa());
1896
1890
  for (const n of e)
1897
- t.push(Pn(n));
1891
+ t.push(qn(n));
1898
1892
  return t.join(`
1899
1893
 
1900
1894
  `);
@@ -1907,13 +1901,13 @@ function $e(e, t = {}) {
1907
1901
  foreignKeyNames: c,
1908
1902
  foreignKeyColumnNames: u,
1909
1903
  namespace: l
1910
- } = e, { branchId: d, transactionId: f } = t, p = `"${o}_change_trigger"`, _ = [];
1911
- for (const [y, T] of a)
1912
- y !== "id" && _.push({ jsName: y, dbColumn: T.columnName });
1913
- const S = u || c;
1914
- for (let y = 0; y < c.length; y++)
1915
- c[y] !== "id" && _.push({ jsName: c[y], dbColumn: S[y] });
1916
- const $ = 'type, namespace, entity, "branchId", "transactionId", "entityId", "inversePatch", patch', A = f ? `'${f}'` : "NULL", b = d || "main", E = `"${l}"."${o}_change_trigger_fn"`, m = `'${l}','${i}','${b}',${A}`, g = `
1904
+ } = e, { branchId: p, transactionId: h } = t, d = `"${o}_change_trigger"`, y = [];
1905
+ for (const [m, g] of a)
1906
+ m !== "id" && y.push({ jsName: m, dbColumn: g.columnName });
1907
+ const A = u || c;
1908
+ for (let m = 0; m < c.length; m++)
1909
+ c[m] !== "id" && y.push({ jsName: c[m], dbColumn: A[m] });
1910
+ const $ = 'type, namespace, entity, "branchId", "transactionId", "entityId", "inversePatch", patch', R = h ? `'${h}'` : "NULL", I = p || "main", E = `"${l}"."${o}_change_trigger_fn"`, _ = `'${l}','${i}','${I}',${R}`, T = `
1917
1911
  -- 创建或替换触发器函数
1918
1912
  CREATE OR REPLACE FUNCTION ${E}()
1919
1913
  RETURNS TRIGGER AS $$
@@ -1926,29 +1920,29 @@ BEGIN
1926
1920
  INSERT INTO ${s} (${$})
1927
1921
  VALUES (
1928
1922
  'INSERT',
1929
- ${m},
1923
+ ${_},
1930
1924
  NEW.id,
1931
1925
  NULL,
1932
- jsonb_build_object(${_.map((y) => `'${y.jsName}', NEW."${y.dbColumn}"`).join(", ")})
1926
+ jsonb_build_object(${y.map((m) => `'${m.jsName}', NEW."${m.dbColumn}"`).join(", ")})
1933
1927
  );
1934
1928
  RETURN NEW;
1935
1929
 
1936
1930
  -- UPDATE 操作
1937
1931
  ELSIF (TG_OP = 'UPDATE') THEN
1938
1932
  -- 只在字段真正变更时记录
1939
- IF (${_.map((y) => `OLD."${y.dbColumn}" IS DISTINCT FROM NEW."${y.dbColumn}"`).join(" OR ")}) THEN
1933
+ IF (${y.map((m) => `OLD."${m.dbColumn}" IS DISTINCT FROM NEW."${m.dbColumn}"`).join(" OR ")}) THEN
1940
1934
  -- 构建变更前的值 (inversePatch - 只包含变更的字段)
1941
- old_values := jsonb_build_object(${_.map((y) => `'${y.jsName}', CASE WHEN OLD."${y.dbColumn}" IS DISTINCT FROM NEW."${y.dbColumn}" THEN to_jsonb(OLD."${y.dbColumn}") ELSE NULL END`).join(", ")});
1935
+ old_values := jsonb_build_object(${y.map((m) => `'${m.jsName}', CASE WHEN OLD."${m.dbColumn}" IS DISTINCT FROM NEW."${m.dbColumn}" THEN to_jsonb(OLD."${m.dbColumn}") ELSE NULL END`).join(", ")});
1942
1936
  old_values := jsonb_strip_nulls(old_values);
1943
1937
 
1944
1938
  -- 构建变更后的值 (patch - 只包含变更的字段)
1945
- new_values := jsonb_build_object(${_.map((y) => `'${y.jsName}', CASE WHEN OLD."${y.dbColumn}" IS DISTINCT FROM NEW."${y.dbColumn}" THEN to_jsonb(NEW."${y.dbColumn}") ELSE NULL END`).join(", ")});
1939
+ new_values := jsonb_build_object(${y.map((m) => `'${m.jsName}', CASE WHEN OLD."${m.dbColumn}" IS DISTINCT FROM NEW."${m.dbColumn}" THEN to_jsonb(NEW."${m.dbColumn}") ELSE NULL END`).join(", ")});
1946
1940
  new_values := jsonb_strip_nulls(new_values);
1947
1941
 
1948
1942
  INSERT INTO ${s} (${$})
1949
1943
  VALUES (
1950
1944
  'UPDATE',
1951
- ${m},
1945
+ ${_},
1952
1946
  NEW.id,
1953
1947
  old_values,
1954
1948
  new_values
@@ -1961,9 +1955,9 @@ BEGIN
1961
1955
  INSERT INTO ${s} (${$})
1962
1956
  VALUES (
1963
1957
  'DELETE',
1964
- ${m},
1958
+ ${_},
1965
1959
  OLD.id,
1966
- jsonb_build_object(${_.map((y) => `'${y.jsName}', OLD."${y.dbColumn}"`).join(", ")}),
1960
+ jsonb_build_object(${y.map((m) => `'${m.jsName}', OLD."${m.dbColumn}"`).join(", ")}),
1967
1961
  NULL
1968
1962
  );
1969
1963
  RETURN OLD;
@@ -1971,19 +1965,19 @@ BEGIN
1971
1965
 
1972
1966
  RETURN NULL;
1973
1967
  END;
1974
- $$ LANGUAGE plpgsql;`, R = `
1968
+ $$ LANGUAGE plpgsql;`, b = `
1975
1969
  -- 删除已存在的触发器
1976
- DROP TRIGGER IF EXISTS ${p} ON ${n}`, I = `
1970
+ DROP TRIGGER IF EXISTS ${d} ON ${n}`, S = `
1977
1971
  -- 创建触发器 (监听 INSERT, UPDATE, DELETE)
1978
- CREATE TRIGGER ${p}
1972
+ CREATE TRIGGER ${d}
1979
1973
  AFTER INSERT OR UPDATE OR DELETE ON ${n}
1980
1974
  FOR EACH ROW
1981
1975
  EXECUTE FUNCTION ${E}()`;
1982
- return [g, R, I].join(`
1976
+ return [T, b, S].join(`
1983
1977
  ---STATEMENT_SEPARATOR---
1984
1978
  `);
1985
1979
  }
1986
- const Ea = async (e, t, n) => {
1980
+ const pa = async (e, t, n) => {
1987
1981
  const r = e.localRxDBBranch(), s = e.localRxDBChange();
1988
1982
  if ((await r.find({
1989
1983
  where: {
@@ -2025,17 +2019,17 @@ const Ea = async (e, t, n) => {
2025
2019
  const o = new ne();
2026
2020
  return o.id = t, o.activated = !1, o.local = !0, o.remote = !1, o.fromChangeId = n ?? null, o.parentId = i.id, await r.create(o);
2027
2021
  };
2028
- function ma(e) {
2022
+ function Ea(e) {
2029
2023
  const t = P(e), { tableName: n, namespace: r } = e, s = `"${n}_change_trigger"`, a = `"${r}"."${n}_change_trigger_fn"`, i = `DROP TRIGGER IF EXISTS ${s} ON ${t}`, o = `DROP FUNCTION IF EXISTS ${a}() CASCADE`;
2030
2024
  return [i, o].join(`
2031
2025
  ---STATEMENT_SEPARATOR---
2032
2026
  `);
2033
2027
  }
2034
- function Un(e) {
2028
+ function Pn(e) {
2035
2029
  const t = [];
2036
2030
  return e.rxdb.config.entities.forEach((n) => {
2037
2031
  const r = D(n);
2038
- r.log !== !1 && t.push(ma(r));
2032
+ r.log !== !1 && t.push(Ea(r));
2039
2033
  }), t.join(`
2040
2034
  ---STATEMENT_SEPARATOR---
2041
2035
  `);
@@ -2048,19 +2042,19 @@ const He = (e, t, n, r = !1) => {
2048
2042
  const c = Z(s, o), u = c.id;
2049
2043
  let l;
2050
2044
  if (i.hasEntityRef(t, u)) {
2051
- if (l = i.getEntityRef(t, u), s.computedPropertyMap.forEach((p, _) => {
2052
- _ in c && (l[_] = c[_]);
2045
+ if (l = i.getEntityRef(t, u), s.computedPropertyMap.forEach((d, y) => {
2046
+ y in c && (l[y] = c[y]);
2053
2047
  }), r) {
2054
- const p = J(l);
2055
- p.origin = { ...c }, Object.assign(l, c), p.local = !0, p.modified = !1;
2048
+ const d = J(l);
2049
+ d.origin = { ...c }, Object.assign(l, c), d.local = !0, d.modified = !1;
2056
2050
  }
2057
2051
  } else
2058
2052
  l = i.createEntityRef(t, c);
2059
- const f = J(l);
2060
- f.local = !0, f.modified = !1, a.push(l);
2053
+ const h = J(l);
2054
+ h.local = !0, h.modified = !1, a.push(l);
2061
2055
  }
2062
2056
  return a;
2063
- }, ya = (e, t, n) => {
2057
+ }, ma = (e, t, n) => {
2064
2058
  for (const r of n) {
2065
2059
  const s = e.rxdb.entityManager.getEntityRef(t, r);
2066
2060
  if (s) {
@@ -2068,96 +2062,96 @@ const He = (e, t, n, r = !1) => {
2068
2062
  a.local = !1, a.removed = !0, a.modified = !1;
2069
2063
  }
2070
2064
  }
2071
- }, jn = (e, t) => {
2065
+ }, Un = (e, t) => {
2072
2066
  const { deletes: n, inserts: r, updates: s } = t, a = { deletes: [], inserts: [], updates: [] }, i = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map();
2073
- for (const [f, p] of n.entries()) {
2074
- const [_, S, $] = Ae(f), A = `${_}:${S}`, b = i.get(A);
2075
- b ? b.add($) : i.set(A, /* @__PURE__ */ new Set([$]));
2076
- let E = o.get(A);
2077
- E || (E = /* @__PURE__ */ new Map(), o.set(A, E)), E.set($, {
2078
- patch: p.patch,
2079
- inversePatch: p.inversePatch
2067
+ for (const [h, d] of n.entries()) {
2068
+ const [y, A, $] = Ae(h), R = `${y}:${A}`, I = i.get(R);
2069
+ I ? I.add($) : i.set(R, /* @__PURE__ */ new Set([$]));
2070
+ let E = o.get(R);
2071
+ E || (E = /* @__PURE__ */ new Map(), o.set(R, E)), E.set($, {
2072
+ patch: d.patch,
2073
+ inversePatch: d.inversePatch
2080
2074
  });
2081
2075
  }
2082
- for (const [f, p] of i) {
2083
- const [_, S] = f.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(S, _), A = P($), b = $.propertyMap.get("id").type === "integer", E = Array.from(p), m = b ? `DELETE FROM ${A} WHERE id = ANY($1::integer[]);` : `DELETE FROM ${A} WHERE id = ANY($1);`;
2076
+ for (const [h, d] of i) {
2077
+ const [y, A] = h.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(A, y), R = P($), I = $.propertyMap.get("id").type === "integer", E = Array.from(d), _ = I ? `DELETE FROM ${R} WHERE id = ANY($1::integer[]);` : `DELETE FROM ${R} WHERE id = ANY($1);`;
2084
2078
  a.deletes.push({
2085
2079
  metadata: $,
2086
- ids: p,
2087
- sql: m,
2080
+ ids: d,
2081
+ sql: _,
2088
2082
  params: [E],
2089
- changes: o.get(f)
2083
+ changes: o.get(h)
2090
2084
  });
2091
2085
  }
2092
2086
  const c = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map();
2093
- for (const [f, p] of r.entries()) {
2094
- const [_, S, $] = Ae(f), A = `${_}:${S}`, b = c.get(A), E = { ...p.patch, id: $ };
2095
- b ? b.push(E) : c.set(A, [E]);
2096
- let m = u.get(A);
2097
- m || (m = /* @__PURE__ */ new Map(), u.set(A, m)), m.set($, {
2098
- patch: p.patch,
2099
- inversePatch: p.inversePatch
2087
+ for (const [h, d] of r.entries()) {
2088
+ const [y, A, $] = Ae(h), R = `${y}:${A}`, I = c.get(R), E = { ...d.patch, id: $ };
2089
+ I ? I.push(E) : c.set(R, [E]);
2090
+ let _ = u.get(R);
2091
+ _ || (_ = /* @__PURE__ */ new Map(), u.set(R, _)), _.set($, {
2092
+ patch: d.patch,
2093
+ inversePatch: d.inversePatch
2100
2094
  });
2101
2095
  }
2102
- for (const [f, p] of c) {
2103
- const [_, S] = f.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(S, _), A = [];
2104
- p.forEach((E) => {
2105
- for (const [I, y] of $.propertyMap)
2106
- E[I] === void 0 && y.default !== void 0 && (typeof y.default == "function" ? E[I] = y.default() : E[I] = y.default);
2107
- const { sql: m, params: g } = In($, E, { returning: !1 }), R = m.replace(";", ga($));
2108
- A.push(nt(R, g));
2096
+ for (const [h, d] of c) {
2097
+ const [y, A] = h.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(A, y), R = [];
2098
+ d.forEach((E) => {
2099
+ for (const [S, m] of $.propertyMap)
2100
+ E[S] === void 0 && m.default !== void 0 && (typeof m.default == "function" ? E[S] = m.default() : E[S] = m.default);
2101
+ const { sql: _, params: T } = Sn($, E, { returning: !1 }), b = _.replace(";", ya($));
2102
+ R.push(nt(b, T));
2109
2103
  });
2110
- const b = A.join("---STATEMENT_SEPARATOR---");
2104
+ const I = R.join("---STATEMENT_SEPARATOR---");
2111
2105
  a.inserts.push({
2112
2106
  metadata: $,
2113
- ids: new Set(p.filter((E) => E != null).map((E) => E.id)),
2114
- sql: b,
2107
+ ids: new Set(d.filter((E) => E != null).map((E) => E.id)),
2108
+ sql: I,
2115
2109
  params: [],
2116
2110
  // 已经内联到 SQL 中
2117
- changes: u.get(f)
2111
+ changes: u.get(h)
2118
2112
  });
2119
2113
  }
2120
- const l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map();
2121
- for (const [f, p] of s.entries()) {
2122
- const [_, S, $] = Ae(f), A = `${_}:${S}`, b = l.get(A), E = { ...p.patch, id: $ };
2123
- b ? b.push(E) : l.set(A, [E]);
2124
- let m = d.get(A);
2125
- m || (m = /* @__PURE__ */ new Map(), d.set(A, m));
2126
- const g = e.rxdb.schemaManager.getEntityMetadata(S, _), R = p.patch ? { ...p.patch } : null, I = p.inversePatch ? { ...p.inversePatch } : null;
2127
- g && (R && Object.keys(R).forEach((y) => {
2128
- const T = g.propertyMap.get(y);
2129
- T && (R[y] = Le(R[y], T));
2130
- }), I && Object.keys(I).forEach((y) => {
2131
- const T = g.propertyMap.get(y);
2132
- T && (I[y] = Le(I[y], T));
2133
- })), m.set($, {
2134
- patch: R,
2135
- inversePatch: I
2114
+ const l = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
2115
+ for (const [h, d] of s.entries()) {
2116
+ const [y, A, $] = Ae(h), R = `${y}:${A}`, I = l.get(R), E = { ...d.patch, id: $ };
2117
+ I ? I.push(E) : l.set(R, [E]);
2118
+ let _ = p.get(R);
2119
+ _ || (_ = /* @__PURE__ */ new Map(), p.set(R, _));
2120
+ const T = e.rxdb.schemaManager.getEntityMetadata(A, y), b = d.patch ? { ...d.patch } : null, S = d.inversePatch ? { ...d.inversePatch } : null;
2121
+ T && (b && Object.keys(b).forEach((m) => {
2122
+ const g = T.propertyMap.get(m);
2123
+ g && (b[m] = Le(b[m], g));
2124
+ }), S && Object.keys(S).forEach((m) => {
2125
+ const g = T.propertyMap.get(m);
2126
+ g && (S[m] = Le(S[m], g));
2127
+ })), _.set($, {
2128
+ patch: b,
2129
+ inversePatch: S
2136
2130
  });
2137
2131
  }
2138
- for (const [f, p] of l) {
2139
- const [_, S] = f.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(S, _), A = [];
2140
- p.forEach((E) => {
2141
- let m;
2142
- $.propertyMap.has("updatedAt") && (m = E.updatedAt);
2143
- const { id: g, ...R } = E, { sql: I, params: y } = ze($, { id: g }, R, {
2144
- updatedAt: m,
2132
+ for (const [h, d] of l) {
2133
+ const [y, A] = h.split(":"), $ = e.rxdb.schemaManager.getEntityMetadata(A, y), R = [];
2134
+ d.forEach((E) => {
2135
+ let _;
2136
+ $.propertyMap.has("updatedAt") && (_ = E.updatedAt);
2137
+ const { id: T, ...b } = E, { sql: S, params: m } = ze($, { id: T }, b, {
2138
+ updatedAt: _,
2145
2139
  returning: !1
2146
2140
  });
2147
- A.push(nt(I, y));
2141
+ R.push(nt(S, m));
2148
2142
  });
2149
- const b = A.join("---STATEMENT_SEPARATOR---");
2143
+ const I = R.join("---STATEMENT_SEPARATOR---");
2150
2144
  a.updates.push({
2151
2145
  metadata: $,
2152
- ids: new Set(p.filter((E) => E != null).map((E) => E.id)),
2153
- sql: b,
2146
+ ids: new Set(d.filter((E) => E != null).map((E) => E.id)),
2147
+ sql: I,
2154
2148
  params: [],
2155
2149
  // 已经内联到 SQL 中
2156
- changes: d.get(f)
2150
+ changes: p.get(h)
2157
2151
  });
2158
2152
  }
2159
2153
  return a;
2160
- }, ga = (e) => ` ON CONFLICT (id) DO UPDATE SET ${Array.from(e.propertyMap.values()).filter((n) => n.name !== "id" && n.name !== "createdAt" && n.name !== "createdBy").map((n) => `"${n.columnName}" = EXCLUDED."${n.columnName}"`).join(", ")};`;
2154
+ }, ya = (e) => ` ON CONFLICT (id) DO UPDATE SET ${Array.from(e.propertyMap.values()).filter((n) => n.name !== "id" && n.name !== "createdAt" && n.name !== "createdBy").map((n) => `"${n.columnName}" = EXCLUDED."${n.columnName}"`).join(", ")};`;
2161
2155
  function _a(e) {
2162
2156
  return {
2163
2157
  rows: e.rows,
@@ -2165,7 +2159,7 @@ function _a(e) {
2165
2159
  elapsed: 0
2166
2160
  };
2167
2161
  }
2168
- const xn = (e, t) => {
2162
+ const jn = (e, t) => {
2169
2163
  const n = [];
2170
2164
  e.rxdb.config.entities.forEach((o) => {
2171
2165
  const c = D(o);
@@ -2195,16 +2189,16 @@ const xn = (e, t) => {
2195
2189
  return n.push(i), n.join(`
2196
2190
  ---STATEMENT_SEPARATOR---
2197
2191
  `);
2198
- }, Ta = async (e, t) => {
2199
- const { branchId: n, actions: r } = t, s = r && jn(e, r);
2192
+ }, ga = async (e, t) => {
2193
+ const { branchId: n, actions: r } = t, s = r && Un(e, r);
2200
2194
  let a;
2201
2195
  try {
2202
2196
  await e.transaction(async () => {
2203
- const u = Un(e);
2197
+ const u = Pn(e);
2204
2198
  if (u) {
2205
- const l = u.split("---STATEMENT_SEPARATOR---").filter((d) => d.trim());
2206
- for (const d of l)
2207
- await e.query(d.trim());
2199
+ const l = u.split("---STATEMENT_SEPARATOR---").filter((p) => p.trim());
2200
+ for (const p of l)
2201
+ await e.query(p.trim());
2208
2202
  }
2209
2203
  if (s) {
2210
2204
  if (s.deletes.length)
@@ -2219,40 +2213,40 @@ const xn = (e, t) => {
2219
2213
  }
2220
2214
  r?.updateRxDBChangeSequence !== void 0 && await e.setRxDBChangeSequence(r.updateRxDBChangeSequence);
2221
2215
  }, !1);
2222
- const o = xn(e, n).split("---STATEMENT_SEPARATOR---").filter((u) => u.trim());
2216
+ const o = jn(e, n).split("---STATEMENT_SEPARATOR---").filter((u) => u.trim());
2223
2217
  for (const u of o) {
2224
2218
  const l = await e.query(u.trim());
2225
2219
  u.includes("RETURNING") && (a = l);
2226
2220
  }
2227
2221
  const c = (u, l) => {
2228
2222
  if (l.length === 0) return;
2229
- const d = l.map((f) => {
2230
- const p = { ...f };
2223
+ const p = l.map((h) => {
2224
+ const d = { ...h };
2231
2225
  return {
2232
2226
  namespace: u.namespace,
2233
2227
  entity: u.name,
2234
2228
  type: "UPDATE",
2235
- id: f.id,
2236
- patch: p,
2237
- inversePatch: p,
2238
- recordAt: f.createdAt
2229
+ id: h.id,
2230
+ patch: d,
2231
+ inversePatch: d,
2232
+ recordAt: h.createdAt
2239
2233
  };
2240
2234
  });
2241
- e.rxdb.dispatchEvent(new me(d));
2235
+ e.rxdb.dispatchEvent(new me(p));
2242
2236
  };
2243
2237
  if (a) {
2244
- const u = _a(a), l = He(e, ne, u, !0), d = D(ne);
2245
- c(d, l);
2238
+ const u = _a(a), l = He(e, ne, u, !0), p = D(ne);
2239
+ c(p, l);
2246
2240
  }
2247
- s && Bn(e, s);
2241
+ s && xn(e, s);
2248
2242
  } catch (i) {
2249
2243
  throw new x(`switch branch ${n} failed: ` + i);
2250
2244
  }
2251
2245
  };
2252
- async function wa(e, t, n, r = !1) {
2246
+ async function Ta(e, t, n, r = !1) {
2253
2247
  if (await e.transaction(async () => {
2254
2248
  if (r) {
2255
- const s = Un(e);
2249
+ const s = Pn(e);
2256
2250
  if (s) {
2257
2251
  const a = s.split("---STATEMENT_SEPARATOR---").filter((i) => i.trim());
2258
2252
  for (const i of a)
@@ -2274,16 +2268,16 @@ async function wa(e, t, n, r = !1) {
2274
2268
  s.successResults = { rows: [], affectedRows: a.length, fields: [] };
2275
2269
  }
2276
2270
  }, !1), r) {
2277
- const s = await e.rxdb.versionManager.getCurrentBranch(), i = xn(e, s.id).split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2271
+ const s = await e.rxdb.versionManager.getCurrentBranch(), i = jn(e, s.id).split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2278
2272
  for (const o of i)
2279
2273
  await e.query(o.trim());
2280
2274
  }
2281
- Bn(e, t);
2275
+ xn(e, t);
2282
2276
  }
2283
- function Bn(e, t) {
2277
+ function xn(e, t) {
2284
2278
  for (const n of t.deletes) {
2285
2279
  const r = Re(n.metadata);
2286
- ya(e, r, Array.from(n.ids));
2280
+ ma(e, r, Array.from(n.ids));
2287
2281
  const s = n.metadata, a = Array.from(n.ids).map((i) => {
2288
2282
  const o = n.changes.get(String(i));
2289
2283
  return {
@@ -2346,7 +2340,7 @@ function St(e, t, n) {
2346
2340
  }
2347
2341
  }), r;
2348
2342
  }
2349
- class Ca extends kn {
2343
+ class va extends Bn {
2350
2344
  /**
2351
2345
  * 构造函数
2352
2346
  *
@@ -2357,7 +2351,7 @@ class Ca extends kn {
2357
2351
  super(t), this.options = n;
2358
2352
  }
2359
2353
  /** 销毁信号主题,用于清理资源 */
2360
- #e = new Jn();
2354
+ #e = new Kn();
2361
2355
  /** 仓库实例缓存,避免重复创建 */
2362
2356
  #s = /* @__PURE__ */ new Map();
2363
2357
  /** PGlite 客户端缓存 */
@@ -2365,13 +2359,13 @@ class Ca extends kn {
2365
2359
  /** 事务锁标志,防止事务嵌套 */
2366
2360
  #t = !1;
2367
2361
  /** 查询任务队列执行器,确保查询按顺序执行 */
2368
- #r = new Vn(1);
2362
+ #r = new Hn(1);
2369
2363
  /** 客户端初始化 Promise,确保单例 */
2370
2364
  #o;
2371
2365
  /** 当前活跃的事务对象 */
2372
2366
  #a;
2373
2367
  /** 适配器名称 */
2374
- name = Qn;
2368
+ name = Yn;
2375
2369
  /**
2376
2370
  * 批量获取实体元数据(QueryCache 专用)
2377
2371
  *
@@ -2387,7 +2381,7 @@ class Ca extends kn {
2387
2381
  return Se(/* @__PURE__ */ new Map());
2388
2382
  const a = `SELECT id, "updatedAt" FROM "public"."${this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t}" WHERE id = ANY($1)`;
2389
2383
  return Ie(this.internalQuery(a, [n])).pipe(
2390
- Yn((i) => {
2384
+ Jn((i) => {
2391
2385
  const o = /* @__PURE__ */ new Map();
2392
2386
  for (const c of i.rows)
2393
2387
  o.set(c.id, c.updatedAt);
@@ -2410,8 +2404,8 @@ class Ca extends kn {
2410
2404
  (async () => {
2411
2405
  const s = this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t, a = Object.keys(n[0]), i = a.map((o) => `"${o}"`).join(", ");
2412
2406
  for (const o of n) {
2413
- const c = a.map((f) => o[f]), u = a.map((f, p) => `$${p + 1}`).join(", "), l = a.filter((f) => f !== "id").map((f) => `"${f}" = EXCLUDED."${f}"`).join(", "), d = `INSERT INTO "public"."${s}" (${i}) VALUES (${u}) ON CONFLICT (id) DO UPDATE SET ${l}`;
2414
- await this.internalQuery(d, c);
2407
+ const c = a.map((h) => o[h]), u = a.map((h, d) => `$${d + 1}`).join(", "), l = a.filter((h) => h !== "id").map((h) => `"${h}" = EXCLUDED."${h}"`).join(", "), p = `INSERT INTO "public"."${s}" (${i}) VALUES (${u}) ON CONFLICT (id) DO UPDATE SET ${l}`;
2408
+ await this.internalQuery(p, c);
2415
2409
  }
2416
2410
  })()
2417
2411
  ));
@@ -2433,7 +2427,7 @@ class Ca extends kn {
2433
2427
  });
2434
2428
  }
2435
2429
  async mutations(t) {
2436
- const n = async () => await la(this, t);
2430
+ const n = async () => await ca(this, t);
2437
2431
  return this.#t ? await n() : await this.transaction(() => n());
2438
2432
  }
2439
2433
  /**
@@ -2447,8 +2441,8 @@ class Ca extends kn {
2447
2441
  * @deprecated localChanges 参数已废弃,将在未来版本中移除
2448
2442
  */
2449
2443
  async mergeChanges(t, n, r = !1) {
2450
- const s = jn(this, t);
2451
- await wa(this, s, n, r);
2444
+ const s = Un(this, t);
2445
+ await Ta(this, s, n, r);
2452
2446
  }
2453
2447
  /**
2454
2448
  * 获取 RxDBChange 表当前序列值
@@ -2482,7 +2476,7 @@ class Ca extends kn {
2482
2476
  */
2483
2477
  async removeMany(t) {
2484
2478
  if (!t || t.length === 0) return Promise.resolve([]);
2485
- const n = D(t[0].constructor), r = Sn(n, t);
2479
+ const n = D(t[0].constructor), r = bn(n, t);
2486
2480
  return await this.query(r), t;
2487
2481
  }
2488
2482
  /**
@@ -2522,7 +2516,7 @@ class Ca extends kn {
2522
2516
  * @returns 适配器实例
2523
2517
  */
2524
2518
  async connect() {
2525
- const t = await this.#n(), n = pa();
2519
+ const t = await this.#n(), n = da();
2526
2520
  return await t.exec(n), t instanceof Rt && (t.addEventListener(K.INSERT, (r) => Ce(this, r)), t.addEventListener(K.UPDATE, (r) => Ce(this, r)), t.addEventListener(K.DELETE, (r) => Ce(this, r))), this;
2527
2521
  }
2528
2522
  /**
@@ -2546,7 +2540,7 @@ class Ca extends kn {
2546
2540
  * @throws {RxdbAdapterPGliteError} 分支 ID 已存在或源分支未找到
2547
2541
  */
2548
2542
  async createBranch(t, n) {
2549
- return Ea(this, t, n);
2543
+ return pa(this, t, n);
2550
2544
  }
2551
2545
  /**
2552
2546
  * 切换到指定分支
@@ -2557,7 +2551,7 @@ class Ca extends kn {
2557
2551
  * @throws {RxdbAdapterPGliteError} 分支切换失败
2558
2552
  */
2559
2553
  async switchBranch(t) {
2560
- return Ta(this, t);
2554
+ return ga(this, t);
2561
2555
  }
2562
2556
  /**
2563
2557
  * 恢复实体到指定状态
@@ -2599,10 +2593,10 @@ class Ca extends kn {
2599
2593
  let r;
2600
2594
  switch (n.repository) {
2601
2595
  case "Repository":
2602
- r = new Mn(this, t);
2596
+ r = new Ln(this, t);
2603
2597
  break;
2604
2598
  case "TreeRepository":
2605
- r = new ca(this, t);
2599
+ r = new oa(this, t);
2606
2600
  break;
2607
2601
  default:
2608
2602
  throw new x("Unsupported repository type: " + n.repository);
@@ -2628,7 +2622,7 @@ class Ca extends kn {
2628
2622
  async createTables(t, n) {
2629
2623
  const r = [], s = [];
2630
2624
  for (const i of t) {
2631
- const o = D(i), u = qn(this, o).split(/;\s*\n/).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("--"));
2625
+ const o = D(i), u = Mn(this, o).split(/;\s*\n/).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("--"));
2632
2626
  for (const l of u)
2633
2627
  l && (l.includes("ADD CONSTRAINT") && l.includes("FOREIGN KEY") ? r.push(l) : s.push(l));
2634
2628
  }
@@ -2666,7 +2660,7 @@ class Ca extends kn {
2666
2660
  }
2667
2661
  const a = ["rxdb_change", "rxdb_branch", "rxdb_migration"];
2668
2662
  for (const i of a) {
2669
- const o = Pn(i);
2663
+ const o = qn(i);
2670
2664
  await this.#c(o);
2671
2665
  }
2672
2666
  return !0;
@@ -2765,7 +2759,7 @@ class Ca extends kn {
2765
2759
  query(t, n) {
2766
2760
  return this.#t && this.#a ? this.#a.query(t, n) : this.#r.addTask(
2767
2761
  async () => (await this.rxdb.connect(this.name), (await this.#n()).query(t, n)),
2768
- Ot([t, n])
2762
+ JSON.stringify([t, n])
2769
2763
  );
2770
2764
  }
2771
2765
  /**
@@ -2815,7 +2809,7 @@ class Ca extends kn {
2815
2809
  return this.#o;
2816
2810
  }
2817
2811
  }
2818
- class Na {
2812
+ class wa {
2819
2813
  getReturningClause() {
2820
2814
  return "RETURNING *";
2821
2815
  }
@@ -2859,11 +2853,11 @@ class Na {
2859
2853
  return `UPDATE ${s} SET ${i} FROM (VALUES ($1)) AS temp(${a}, ${r.join(", ")}) WHERE ${s}.${a} = temp.${a} ${this.getReturningClause()}`;
2860
2854
  }
2861
2855
  }
2862
- const La = new Na();
2863
- function Ma(e, t, n) {
2856
+ const Da = new wa();
2857
+ function Ca(e, t, n) {
2864
2858
  let r = "";
2865
2859
  for (let s = 0; s < t.length; s++) {
2866
- const a = t[s], i = D(a), o = qn(e, i);
2860
+ const a = t[s], i = D(a), o = Mn(e, i);
2867
2861
  if (r += `
2868
2862
  ` + o, i.log !== !1) {
2869
2863
  const c = $e(i);
@@ -2886,31 +2880,31 @@ function Ma(e, t, n) {
2886
2880
  return r;
2887
2881
  }
2888
2882
  export {
2889
- Qn as ADAPTER_NAME,
2883
+ Yn as ADAPTER_NAME,
2890
2884
  K as PGliteChangeType,
2891
2885
  Rt as PGliteClient,
2892
- Na as PostgreSQLDialect,
2893
- Ca as RxDBAdapterPGlite,
2886
+ wa as PostgreSQLDialect,
2887
+ va as RxDBAdapterPGlite,
2894
2888
  x as RxdbAdapterPGliteError,
2895
- Ma as create_tables_sql,
2896
- da as generateNotifyFunctionSQL,
2897
- pa as generateNotifyInfrastructureSQL,
2898
- Pn as generateNotifyTriggerSQL,
2889
+ Ca as create_tables_sql,
2890
+ fa as generateNotifyFunctionSQL,
2891
+ da as generateNotifyInfrastructureSQL,
2892
+ qn as generateNotifyTriggerSQL,
2899
2893
  $e as generate_trigger_sql,
2900
2894
  Z as getEntityObjectFromResult,
2901
2895
  Je as getSqlValue,
2902
2896
  nt as getSqlWithParams,
2903
- Ct as getTableColumnIndexName,
2904
- vt as getTableName,
2897
+ Dt as getTableColumnIndexName,
2898
+ Ot as getTableName,
2905
2899
  P as getTableNameByMetadata,
2906
- Lt as normalizeCreateEntity,
2907
- zn as normalizeEntity,
2908
- La as pgDialect,
2909
- Da as removeNotifyTriggerSQL,
2910
- Un as remove_all_triggers_sql,
2911
- ma as remove_trigger_sql,
2912
- Dt as rxDBColumnTypeToPGliteType,
2913
- Xn as rxDBColumnTypeToPGliteTypeIndexName,
2900
+ Ct as normalizeCreateEntity,
2901
+ Xn as normalizeEntity,
2902
+ Da as pgDialect,
2903
+ Oa as removeNotifyTriggerSQL,
2904
+ Pn as remove_all_triggers_sql,
2905
+ Ea as remove_trigger_sql,
2906
+ vt as rxDBColumnTypeToPGliteType,
2907
+ Qn as rxDBColumnTypeToPGliteTypeIndexName,
2914
2908
  st as transformEntityValuePGliteToJs,
2915
2909
  Ke as transformEntityValueToSql,
2916
2910
  tt as transformValueJsToPGlite,