@aiao/rxdb-adapter-pglite 0.0.15 → 0.0.17

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,8 +1,7 @@
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";
1
+ import { PropertyType as _, RxDBChange as le, getEntityMetadata as C, EntityLocalCreatedEvent as ue, EntityLocalRemovedEvent as Ke, EntityLocalUpdatedEvent as ge, RelationKind as B, RepositoryBase as Bn, getEntityStatus as J, RxDBBranch as re, parseRxDBChangeKey as Re, getEntityType as Se, RxDBAdapterLocalBase as kn } from "@aiao/rxdb";
2
+ import { EventDispatcher as Wn, traverseObjectKeys as Gn, isFunction as Ot, isString as Hn, AsyncQueueExecutor as Vn } from "@aiao/utils";
3
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";
4
+ import { ReplaySubject as Jn, defer as Ie, of as Oe, from as De, map as Yn } from "rxjs";
6
5
  const Qn = "pglite";
7
6
  var K = /* @__PURE__ */ ((e) => (e.INSERT = "INSERT", e.UPDATE = "UPDATE", e.DELETE = "DELETE", e))(K || {});
8
7
  class x extends Error {
@@ -18,205 +17,222 @@ 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 Dt = (e, t = "public") => `"${t}"."${e}"`, P = (e) => Dt(e.tableName, e.namespace), Ct = (e) => {
22
21
  switch (e.type) {
23
- case N.uuid:
22
+ case _.uuid:
24
23
  return "uuid";
25
- case N.string:
26
- case N.enum:
24
+ case _.string:
25
+ case _.enum:
27
26
  return "varchar";
28
- case N.json:
27
+ case _.json:
28
+ case _.keyValue:
29
29
  return "jsonb";
30
- case N.number:
30
+ case _.number:
31
31
  return "numeric";
32
- case N.integer:
32
+ case _.integer:
33
33
  return "integer";
34
- case N.boolean:
34
+ case _.boolean:
35
35
  return "boolean";
36
- case N.date:
36
+ case _.date:
37
37
  return "timestamptz";
38
+ case _.stringArray:
39
+ return "text[]";
40
+ case _.numberArray:
41
+ return "numeric[]";
38
42
  }
39
43
  throw new x("rxDBColumnTypeToPGliteType: type '" + e.type + "' not support");
40
44
  }, Xn = (e) => {
41
45
  switch (e.type) {
42
- case N.uuid:
46
+ case _.uuid:
43
47
  return "uuid_ops";
44
- case N.string:
45
- case N.enum:
48
+ case _.string:
49
+ case _.enum:
46
50
  return "bpchar_ops";
47
- case N.json:
51
+ case _.json:
48
52
  return "jsonb_ops";
49
- case N.number:
53
+ case _.number:
50
54
  return "numeric_ops";
51
- case N.integer:
55
+ case _.integer:
52
56
  return "int4_ops";
53
57
  default:
54
58
  throw new x(`rxDBColumnTypeToPGliteTypeIndexName: type '${e.type}' not support`);
55
59
  }
56
- }, Ct = (e, t) => `idx_${e.namespace}_${e.tableName}_${t.name}`, tt = (e, t) => {
60
+ }, Lt = (e, t) => `idx_${e.namespace}_${e.tableName}_${t.name}`, nt = (e, t) => {
57
61
  if (e == null)
58
62
  return null;
59
63
  switch (t.type) {
60
- case N.json:
61
- case N.keyValue:
62
- case N.stringArray:
63
- case N.numberArray:
64
+ case _.json:
65
+ case _.keyValue:
64
66
  return JSON.stringify(e);
65
- case N.date:
67
+ case _.stringArray:
68
+ return Array.isArray(e) ? e : JSON.parse(String(e));
69
+ case _.numberArray:
70
+ return (Array.isArray(e) ? e : JSON.parse(String(e))).map(Number);
71
+ case _.date:
66
72
  return e instanceof Date ? e.toISOString() : e;
67
- case N.boolean:
73
+ case _.boolean:
68
74
  return !!e;
69
- case N.number:
70
- case N.integer:
75
+ case _.number:
76
+ case _.integer:
71
77
  return Number(e);
72
- case N.enum:
73
- case N.string:
74
- case N.uuid:
78
+ case _.enum:
79
+ case _.string:
80
+ case _.uuid:
75
81
  default:
76
82
  return String(e);
77
83
  }
78
- }, Ke = (e, t) => {
84
+ }, Je = (e, t) => {
79
85
  const n = {}, r = Object.keys(t), s = e.foreignKeyNames || [], a = e.foreignKeyColumnNames || s;
80
- for (let i = 0; i < r.length; i++) {
81
- const o = r[i], c = s.indexOf(o);
86
+ for (let o = 0; o < r.length; o++) {
87
+ const i = r[o], c = s.indexOf(i);
82
88
  if (c !== -1) {
83
- n[a[c]] = t[o];
89
+ n[a[c]] = t[i];
84
90
  continue;
85
91
  }
86
- if (a.indexOf(o) !== -1) {
87
- n[o] = t[o];
92
+ if (a.indexOf(i) !== -1) {
93
+ n[i] = t[i];
88
94
  continue;
89
95
  }
90
- const l = e.propertyMap.get(o);
91
- if (l) {
92
- n[l.columnName] = tt(t[o], l);
96
+ const u = e.propertyMap.get(i);
97
+ if (u) {
98
+ n[u.columnName] = nt(t[i], u);
93
99
  continue;
94
100
  }
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));
101
+ const h = e.columnNameToPropertyName?.get(i);
102
+ if (h) {
103
+ const p = e.propertyMap.get(h);
104
+ p && (n[i] = nt(t[i], p));
99
105
  }
100
106
  }
101
107
  return n;
102
- }, Lt = (e, t) => {
108
+ }, vt = (e, t) => {
103
109
  const n = {};
104
- for (const [a, i] of e.propertyMap)
105
- a in t && (n[i.columnName] = t[a]);
110
+ for (const [a, o] of e.propertyMap)
111
+ a in t && (n[o.columnName] = t[a]);
106
112
  const r = e.foreignKeyNames || [], s = e.foreignKeyColumnNames || r;
107
113
  for (let a = 0; a < r.length; a++) {
108
- const i = r[a];
109
- i in t && (n[s[a]] = t[i]);
114
+ const o = r[a];
115
+ o in t && (n[s[a]] = t[o]);
110
116
  }
111
117
  return n;
112
118
  }, zn = (e, t) => {
113
119
  const n = {};
114
- for (const [a, i] of e.propertyMap)
115
- a in t && i.readonly !== !0 && (n[i.columnName] = t[a]);
120
+ for (const [a, o] of e.propertyMap)
121
+ a in t && o.readonly !== !0 && (n[o.columnName] = t[a]);
116
122
  const r = e.foreignKeyNames || [], s = e.foreignKeyColumnNames || r;
117
123
  for (let a = 0; a < r.length; a++) {
118
- const i = r[a];
119
- i in t && (n[s[a]] = t[i]);
124
+ const o = r[a];
125
+ o in t && (n[s[a]] = t[o]);
120
126
  }
121
127
  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) => {
128
+ }, Zn = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, Ye = (e) => {
123
129
  if (typeof e == "string") {
124
130
  const t = e.replaceAll("'", "''");
125
131
  return Zn.test(e) ? `'${t}'::uuid` : `'${t}'`;
126
132
  }
127
- 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
- }, nt = (e, t = []) => !t || t.length === 0 ? e : e.replace(/\$(\d+)/g, (n, r) => {
133
+ return e == null ? "NULL" : typeof e == "boolean" ? e ? "TRUE" : "FALSE" : e instanceof Date ? `'${e.toISOString()}'` : Array.isArray(e) ? `ARRAY[${e.map((n) => Ye(n)).join(", ")}]` : typeof e == "object" ? `'${JSON.stringify(e).replaceAll("'", "''")}'::jsonb` : String(e);
134
+ }, st = (e, t = []) => !t || t.length === 0 ? e : e.replace(/\$(\d+)/g, (n, r) => {
129
135
  const s = parseInt(r, 10) - 1;
130
136
  if (s < 0 || s >= t.length)
131
137
  throw new x(`Parameter index ${r} out of range (have ${t.length} params)`);
132
- return Je(t[s]);
133
- }), Z = (e, t) => {
138
+ return Ye(t[s]);
139
+ }), ee = (e, t) => {
134
140
  const n = {}, r = e.foreignKeyNames || [], s = e.foreignKeyColumnNames || r, a = e.columnNameToPropertyName;
135
- return Object.keys(t).forEach((i) => {
136
- const o = t[i], c = s.indexOf(i);
141
+ return Object.keys(t).forEach((o) => {
142
+ const i = t[o], c = s.indexOf(o);
137
143
  if (c !== -1) {
138
- n[r[c]] = o;
144
+ n[r[c]] = i;
139
145
  return;
140
146
  }
141
- const u = a?.get(i);
142
- if (u) {
143
- const l = e.propertyMap.get(u);
144
- l && (l.type === N.number && typeof o == "string" ? n[u] = parseFloat(o) : l.type === N.integer && typeof o == "string" ? n[u] = parseInt(o, 10) : n[u] = o);
147
+ const l = a?.get(o);
148
+ if (l) {
149
+ const u = e.propertyMap.get(l);
150
+ u && (u.type === _.number && typeof i == "string" ? n[l] = parseFloat(i) : u.type === _.integer && typeof i == "string" ? n[l] = parseInt(i, 10) : u.type === _.numberArray && Array.isArray(i) ? n[l] = i.map((h) => typeof h == "string" ? parseFloat(h) : Number(h)) : u.type === _.keyValue ? n[l] = ae(i, u) : n[l] = i);
145
151
  return;
146
152
  }
147
153
  if (!a) {
148
- const l = e.propertyMap.get(i);
149
- if (l) {
150
- l.type === N.number && typeof o == "string" ? n[i] = parseFloat(o) : l.type === N.integer && typeof o == "string" ? n[i] = parseInt(o, 10) : n[i] = o;
154
+ const u = e.propertyMap.get(o);
155
+ if (u) {
156
+ u.type === _.number && typeof i == "string" ? n[o] = parseFloat(i) : u.type === _.integer && typeof i == "string" ? n[o] = parseInt(i, 10) : u.type === _.numberArray && Array.isArray(i) ? n[o] = i.map((h) => typeof h == "string" ? parseFloat(h) : Number(h)) : u.type === _.keyValue ? n[o] = ae(i, u) : n[o] = i;
151
157
  return;
152
158
  }
153
159
  }
154
- e.isForeignKey(i), n[i] = o;
160
+ e.isForeignKey(o), n[o] = i;
155
161
  }), n;
156
- }, Le = (e, t) => {
162
+ }, ae = (e, t) => {
157
163
  if (e == null) return e;
158
164
  switch (t.type) {
159
- case N.date:
165
+ case _.date:
160
166
  return e instanceof Date ? e : new Date(e);
161
- case N.json:
162
- case N.keyValue:
163
- case N.stringArray:
164
- case N.numberArray:
167
+ case _.keyValue: {
168
+ if (!e || typeof e != "object") return e;
169
+ const n = t.properties;
170
+ if (n && n.length > 0) {
171
+ const r = { ...e };
172
+ for (const s of n)
173
+ s.name in r && (r[s.name] = ae(r[s.name], s));
174
+ return r;
175
+ }
165
176
  return e;
166
- case N.boolean:
177
+ }
178
+ case _.json:
179
+ case _.stringArray:
180
+ case _.numberArray:
181
+ return e;
182
+ case _.boolean:
167
183
  return !!e;
168
184
  default:
169
185
  return e;
170
186
  }
171
- }, st = (e, t) => (Object.keys(t).forEach((n) => {
187
+ }, rt = (e, t) => (Object.keys(t).forEach((n) => {
172
188
  const r = t[n], s = e.propertyMap.get(n);
173
- s && (t[n] = Le(r, s));
189
+ s && (t[n] = ae(r, s));
174
190
  }), t);
175
191
  var es = Object.defineProperty, Mt = (e) => {
176
192
  throw TypeError(e);
177
- }, ts = (e, t) => () => (e && (t = e(e = 0)), t), ye = (e, t) => {
193
+ }, ts = (e, t) => () => (e && (t = e(e = 0)), t), _e = (e, t) => {
178
194
  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) {
180
- v(e, t, s);
195
+ }, Qe = (e, t, n) => t.has(e) || Mt("Cannot " + n), d = (e, t, n) => (Qe(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), D = (e, t, n, r) => (Qe(e, t, "write to private field"), t.set(e, n), n), O = (e, t, n) => (Qe(e, t, "access private method"), n), qt = (e, t, n, r) => ({ set _(s) {
196
+ D(e, t, s);
181
197
  }, get _() {
182
- return h(e, t, r);
198
+ return d(e, t, r);
183
199
  } }), H = ts(() => {
184
200
  }), 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 });
201
+ _e(ns, { ABSTIME: () => ms, ACLITEM: () => $s, BIT: () => Is, BOOL: () => qe, BPCHAR: () => Bt, BYTEA: () => Pe, CHAR: () => as, CID: () => ls, CIDR: () => Es, CIRCLE: () => _s, DATE: () => Wt, FLOAT4: () => xt, FLOAT8: () => Ft, GTSVECTOR: () => Gs, INET: () => As, INT2: () => Pt, INT4: () => Ut, INT8: () => Ue, INTERVAL: () => Rs, JSON: () => je, JSONB: () => Ht, MACADDR: () => Ns, MACADDR8: () => Ts, MONEY: () => ws, NUMERIC: () => Ds, OID: () => jt, PATH: () => ds, PG_DEPENDENCIES: () => Bs, PG_LSN: () => xs, PG_NDISTINCT: () => Fs, PG_NODE_TREE: () => hs, POLYGON: () => ps, REFCURSOR: () => Cs, REGCLASS: () => qs, REGCONFIG: () => Hs, REGDICTIONARY: () => Vs, REGNAMESPACE: () => Ks, REGOPER: () => vs, REGOPERATOR: () => Ms, REGPROC: () => is, REGPROCEDURE: () => Ls, REGROLE: () => Js, REGTYPE: () => Ps, RELTIME: () => ys, SMGR: () => fs, TEXT: () => he, TID: () => os, TIME: () => bs, TIMESTAMP: () => Gt, TIMESTAMPTZ: () => xe, 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: () => Fe, parsers: () => Ys, serializers: () => Qs, types: () => Vt });
186
202
  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) => {
203
+ var ss = globalThis.JSON.parse, rs = globalThis.JSON.stringify, qe = 16, Pe = 17, as = 18, Ue = 20, Pt = 21, Ut = 23, is = 24, he = 25, jt = 26, os = 27, cs = 28, ls = 29, je = 114, us = 142, hs = 194, fs = 210, ds = 602, ps = 604, Es = 650, xt = 700, Ft = 701, ms = 702, ys = 703, gs = 704, _s = 718, Ts = 774, ws = 790, Ns = 829, As = 869, $s = 1033, Bt = 1042, kt = 1043, Wt = 1082, bs = 1083, Gt = 1114, xe = 1184, Rs = 1186, Ss = 1266, Is = 1560, Os = 1562, Ds = 1700, Cs = 1790, Ls = 2202, vs = 2203, Ms = 2204, qs = 2205, Ps = 2206, Us = 2950, js = 2970, xs = 3220, Fs = 3361, Bs = 3402, ks = 3614, Ws = 3615, Gs = 3642, Hs = 3734, Vs = 3769, Ht = 3802, Ks = 4089, Js = 4096, Vt = { string: { to: he, from: [he, kt, Bt], serialize: (e) => {
188
204
  if (typeof e == "string") return e;
189
205
  if (typeof e == "number") return e.toString();
190
206
  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) => {
207
+ }, parse: (e) => e }, number: { to: 0, from: [Pt, Ut, jt, xt, Ft], serialize: (e) => e.toString(), parse: (e) => +e }, bigint: { to: Ue, from: [Ue], serialize: (e) => e.toString(), parse: (e) => {
192
208
  let t = BigInt(e);
193
209
  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) => {
210
+ } }, json: { to: je, from: [je, Ht], serialize: (e) => typeof e == "string" ? e : rs(e), parse: (e) => ss(e) }, boolean: { to: qe, from: [qe], serialize: (e) => {
195
211
  if (typeof e != "boolean") throw new Error("Invalid input for boolean type");
196
212
  return e ? "t" : "f";
197
- }, parse: (e) => e === "t" }, date: { to: je, from: [Wt, Gt, je], serialize: (e) => {
213
+ }, parse: (e) => e === "t" }, date: { to: xe, from: [Wt, Gt, xe], serialize: (e) => {
198
214
  if (typeof e == "string") return e;
199
215
  if (typeof e == "number") return new Date(e).toISOString();
200
216
  if (e instanceof Date) return e.toISOString();
201
217
  throw new Error("Invalid input for date type");
202
- }, parse: (e) => new Date(e) }, bytea: { to: qe, from: [qe], serialize: (e) => {
218
+ }, parse: (e) => new Date(e) }, bytea: { to: Pe, from: [Pe], serialize: (e) => {
203
219
  if (!(e instanceof Uint8Array)) throw new Error("Invalid input for bytea type");
204
220
  return "\\x" + Array.from(e).map((t) => t.toString(16).padStart(2, "0")).join("");
205
221
  }, parse: (e) => {
206
222
  let t = e.slice(2);
207
223
  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;
209
- function xe(e, t, n) {
224
+ } } }, Xe = Xs(Vt), Ys = Xe.parsers, Qs = Xe.serializers;
225
+ function Fe(e, t, n) {
210
226
  if (e === null) return null;
211
- let r = n?.[t] ?? Qe.parsers[t];
227
+ let r = n?.[t] ?? Xe.parsers[t];
212
228
  return r ? r(e, t) : e;
213
229
  }
214
230
  function Xs(e) {
215
231
  return Object.keys(e).reduce(({ parsers: t, serializers: n }, r) => {
216
- let { to: s, from: a, serialize: i, parse: o } = e[r];
217
- return n[s] = i, n[r] = i, t[r] = o, Array.isArray(a) ? a.forEach((c) => {
218
- t[c] = o, n[c] = i;
219
- }) : (t[a] = o, n[a] = i), { parsers: t, serializers: n };
232
+ let { to: s, from: a, serialize: o, parse: i } = e[r];
233
+ return n[s] = o, n[r] = o, t[r] = i, Array.isArray(a) ? a.forEach((c) => {
234
+ t[c] = i, n[c] = o;
235
+ }) : (t[a] = i, n[a] = o), { parsers: t, serializers: n };
220
236
  }, { parsers: {}, serializers: {} });
221
237
  }
222
238
  var zs = /\\/g, Zs = /"/g;
@@ -229,9 +245,9 @@ function Kt(e, t, n) {
229
245
  let r = e[0], s = n === 1020 ? ";" : ",";
230
246
  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)}}`;
231
247
  }
232
- var Oe = { i: 0, char: null, str: "", quoted: !1, last: 0, p: null };
248
+ var Ce = { i: 0, char: null, str: "", quoted: !1, last: 0, p: null };
233
249
  function tr(e, t, n) {
234
- return Oe.i = Oe.last = 0, Jt(Oe, e, t, n)[0];
250
+ return Ce.i = Ce.last = 0, Jt(Ce, e, t, n)[0];
235
251
  }
236
252
  function Jt(e, t, n, r) {
237
253
  let s = [], a = r === 1020 ? ";" : ",";
@@ -248,25 +264,25 @@ function Jt(e, t, n, r) {
248
264
  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
265
  }
250
266
  var nr = {};
251
- ye(nr, { parseDescribeStatementResults: () => Yt, parseResults: () => sr });
267
+ _e(nr, { parseDescribeStatementResults: () => Yt, parseResults: () => sr });
252
268
  H();
253
269
  function sr(e, t, n, r) {
254
- let s = [], a = { rows: [], fields: [] }, i = 0, o = { ...t, ...n?.parsers };
270
+ let s = [], a = { rows: [], fields: [] }, o = 0, i = { ...t, ...n?.parsers };
255
271
  return e.forEach((c) => {
256
272
  switch (c.name) {
257
273
  case "rowDescription": {
258
- let u = c;
259
- a.fields = u.fields.map((l) => ({ name: l.name, dataTypeID: l.dataTypeID }));
274
+ let l = c;
275
+ a.fields = l.fields.map((u) => ({ name: u.name, dataTypeID: u.dataTypeID }));
260
276
  break;
261
277
  }
262
278
  case "dataRow": {
263
279
  if (!a) break;
264
- 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)])));
280
+ let l = c;
281
+ n?.rowMode === "array" ? a.rows.push(l.fields.map((u, h) => Fe(u, a.fields[h].dataTypeID, i))) : a.rows.push(Object.fromEntries(l.fields.map((u, h) => [a.fields[h].name, Fe(u, a.fields[h].dataTypeID, i)])));
266
282
  break;
267
283
  }
268
284
  case "commandComplete": {
269
- i += rr(c), s.push({ ...a, affectedRows: i, ...r ? { blob: r } : {} }), a = { rows: [], fields: [] };
285
+ o += rr(c), s.push({ ...a, affectedRows: o, ...r ? { blob: r } : {} }), a = { rows: [], fields: [] };
270
286
  break;
271
287
  }
272
288
  }
@@ -291,7 +307,7 @@ function Yt(e) {
291
307
  return t ? t.dataTypeIDs : [];
292
308
  }
293
309
  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 });
310
+ _e(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: () => An, 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 });
295
311
  H();
296
312
  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 {
297
313
  constructor(t) {
@@ -330,8 +346,8 @@ var Xt = { name: "parseComplete", length: 5 }, zt = { name: "bindComplete", leng
330
346
  this.length = e, this.name = t, this.binary = n, this.columnTypes = new Array(r);
331
347
  }
332
348
  }, pn = class {
333
- constructor(e, t, n, r, s, a, i) {
334
- this.name = e, this.tableID = t, this.columnID = n, this.dataTypeID = r, this.dataTypeSize = s, this.dataTypeModifier = a, this.format = i;
349
+ constructor(e, t, n, r, s, a, o) {
350
+ this.name = e, this.tableID = t, this.columnID = n, this.dataTypeID = r, this.dataTypeSize = s, this.dataTypeModifier = a, this.format = o;
335
351
  }
336
352
  }, En = class {
337
353
  constructor(t, n) {
@@ -365,17 +381,17 @@ var Xt = { name: "parseComplete", length: 5 }, zt = { name: "bindComplete", leng
365
381
  constructor(e, t) {
366
382
  this.length = e, this.fields = t, this.name = "dataRow", this.fieldCount = t.length;
367
383
  }
368
- }, $n = class {
384
+ }, An = class {
369
385
  constructor(e, t) {
370
386
  this.length = e, this.message = t, this.name = "notice";
371
387
  }
372
388
  }, ar = {};
373
- ye(ar, { Parser: () => Cr, messages: () => Qt, serialize: () => re });
389
+ _e(ar, { Parser: () => Lr, messages: () => Qt, serialize: () => oe });
374
390
  H();
375
391
  H();
376
392
  H();
377
393
  H();
378
- function ge(e) {
394
+ function Te(e) {
379
395
  let t = e.length;
380
396
  for (let n = e.length - 1; n >= 0; n--) {
381
397
  let r = e.charCodeAt(n);
@@ -383,157 +399,157 @@ function ge(e) {
383
399
  }
384
400
  return t;
385
401
  }
386
- var U, M, te, Fe, ee, V, le, X, An, _e = class {
402
+ var U, M, se, ke, ne, V, fe, z, $n, we = class {
387
403
  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));
404
+ this.size = e, j(this, V), j(this, U), j(this, M, 5), j(this, se, !1), j(this, ke, new TextEncoder()), j(this, ne, 0), D(this, U, O(this, V, fe).call(this, e));
389
405
  }
390
406
  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;
407
+ return O(this, V, z).call(this, 4), d(this, U).setInt32(d(this, M), e, d(this, se)), D(this, M, d(this, M) + 4), this;
392
408
  }
393
409
  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;
410
+ return O(this, V, z).call(this, 2), d(this, U).setInt16(d(this, M), e, d(this, se)), D(this, M, d(this, M) + 2), this;
395
411
  }
396
412
  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;
413
+ return e && this.addString(e), O(this, V, z).call(this, 1), d(this, U).setUint8(d(this, M), 0), qt(this, M)._++, this;
398
414
  }
399
415
  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;
416
+ let t = Te(e);
417
+ return O(this, V, z).call(this, t), d(this, ke).encodeInto(e, new Uint8Array(d(this, U).buffer, d(this, M))), D(this, M, d(this, M) + t), this;
402
418
  }
403
419
  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;
420
+ return O(this, V, z).call(this, e.byteLength), new Uint8Array(d(this, U).buffer).set(new Uint8Array(e), d(this, M)), D(this, M, d(this, M) + e.byteLength), this;
405
421
  }
406
422
  flush(e) {
407
- let t = O(this, V, An).call(this, e);
408
- return v(this, M, 5), v(this, U, O(this, V, le).call(this, this.size)), new Uint8Array(t);
423
+ let t = O(this, V, $n).call(this, e);
424
+ return D(this, M, 5), D(this, U, O(this, V, fe).call(this, this.size)), new Uint8Array(t);
409
425
  }
410
426
  };
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) {
427
+ U = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), se = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), ne = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakSet(), fe = function(e) {
412
428
  return new DataView(new ArrayBuffer(e));
413
- }, 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));
429
+ }, z = function(e) {
430
+ if (d(this, U).byteLength - d(this, M) < e) {
431
+ let t = d(this, U).buffer, n = t.byteLength + (t.byteLength >> 1) + e;
432
+ D(this, U, O(this, V, fe).call(this, n)), new Uint8Array(d(this, U).buffer).set(new Uint8Array(t));
417
433
  }
418
- }, An = function(e) {
434
+ }, $n = function(e) {
419
435
  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));
436
+ d(this, U).setUint8(d(this, ne), e);
437
+ let t = d(this, M) - (d(this, ne) + 1);
438
+ d(this, U).setInt32(d(this, ne) + 1, t, d(this, se));
423
439
  }
424
- return h(this, U).buffer.slice(e ? 0 : 5, h(this, M));
440
+ return d(this, U).buffer.slice(e ? 0 : 5, d(this, M));
425
441
  };
426
- var C = new _e(), ir = (e) => {
427
- C.addInt16(3).addInt16(0);
428
- for (let r of Object.keys(e)) C.addCString(r).addCString(e[r]);
429
- C.addCString("client_encoding").addCString("UTF8");
430
- let t = C.addCString("").flush(), n = t.byteLength + 4;
431
- return new _e().addInt32(n).add(t).flush();
442
+ var L = new we(), ir = (e) => {
443
+ L.addInt16(3).addInt16(0);
444
+ for (let r of Object.keys(e)) L.addCString(r).addCString(e[r]);
445
+ L.addCString("client_encoding").addCString("UTF8");
446
+ let t = L.addCString("").flush(), n = t.byteLength + 4;
447
+ return new we().addInt32(n).add(t).flush();
432
448
  }, or = () => {
433
449
  let e = new DataView(new ArrayBuffer(8));
434
450
  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) => {
451
+ }, cr = (e) => L.addCString(e).flush(112), lr = (e, t) => (L.addCString(e).addInt32(Te(t)).addString(t), L.flush(112)), ur = (e) => L.addString(e).flush(112), hr = (e) => L.addCString(e).flush(81), fr = [], dr = (e) => {
436
452
  let t = e.name ?? "";
437
453
  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
- let n = C.addCString(t).addCString(e.text).addInt16(e.types?.length ?? 0);
439
- return e.types?.forEach((r) => n.addInt32(r)), C.flush(80);
440
- }, z = new _e(), pr = (e, t) => {
454
+ let n = L.addCString(t).addCString(e.text).addInt16(e.types?.length ?? 0);
455
+ return e.types?.forEach((r) => n.addInt32(r)), L.flush(80);
456
+ }, Z = new we(), pr = (e, t) => {
441
457
  for (let n = 0; n < e.length; n++) {
442
458
  let r = t ? t(e[n], n) : e[n];
443
- if (r === null) C.addInt16(0), z.addInt32(-1);
459
+ if (r === null) L.addInt16(0), Z.addInt32(-1);
444
460
  else if (r instanceof ArrayBuffer || ArrayBuffer.isView(r)) {
445
461
  let s = ArrayBuffer.isView(r) ? r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength) : r;
446
- C.addInt16(1), z.addInt32(s.byteLength), z.add(s);
447
- } else C.addInt16(0), z.addInt32(ge(r)), z.addString(r);
462
+ L.addInt16(1), Z.addInt32(s.byteLength), Z.add(s);
463
+ } else L.addInt16(0), Z.addInt32(Te(r)), Z.addString(r);
448
464
  }
449
465
  }, Er = (e = {}) => {
450
466
  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);
467
+ return L.addCString(t).addCString(n), L.addInt16(a), pr(s, e.valueMapper), L.addInt16(a), L.add(Z.flush()), L.addInt16(r ? 1 : 0), L.flush(66);
452
468
  }, mr = new Uint8Array([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]), yr = (e) => {
453
469
  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));
470
+ let t = e.portal ?? "", n = e.rows ?? 0, r = Te(t), s = 4 + r + 1 + 4, a = new DataView(new ArrayBuffer(1 + s));
455
471
  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
472
  }, gr = (e, t) => {
457
473
  let n = new DataView(new ArrayBuffer(16));
458
474
  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
- }, Xe = (e, t) => {
460
- let n = new _e();
475
+ }, ze = (e, t) => {
476
+ let n = new we();
461
477
  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) => {
478
+ }, _r = L.addCString("P").flush(68), Tr = L.addCString("S").flush(68), wr = (e) => e.name ? ze(68, `${e.type}${e.name ?? ""}`) : e.type === "P" ? _r : Tr, Nr = (e) => {
463
479
  let t = `${e.type}${e.name ?? ""}`;
464
- 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 };
480
+ return ze(67, t);
481
+ }, Ar = (e) => L.add(e).flush(100), $r = (e) => ze(102, e), Ne = (e) => new Uint8Array([e, 0, 0, 0, 4]), br = Ne(72), Rr = Ne(83), Sr = Ne(88), Ir = Ne(99), oe = { startup: ir, password: cr, requestSsl: or, sendSASLInitialResponseMessage: lr, sendSCRAMClientFinalMessage: ur, query: hr, parse: dr, bind: Er, execute: yr, describe: wr, close: Nr, flush: () => br, sync: () => Rr, end: () => Sr, copyData: Ar, copyDone: () => Ir, copyFail: $r, cancel: gr };
466
482
  H();
467
483
  H();
468
- var rt = { text: 0, binary: 1 };
484
+ var at = { text: 0, binary: 1 };
469
485
  H();
470
- var Or = new ArrayBuffer(0), Y, q, ke, We, ae, vr = class {
486
+ var Or = new ArrayBuffer(0), Y, q, We, Ge, ce, Dr = class {
471
487
  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);
488
+ j(this, Y, new DataView(Or)), j(this, q), j(this, We, "utf-8"), j(this, Ge, new TextDecoder(d(this, We))), j(this, ce, !1), D(this, q, e);
473
489
  }
474
490
  setBuffer(e, t) {
475
- v(this, q, e), v(this, Y, new DataView(t));
491
+ D(this, q, e), D(this, Y, new DataView(t));
476
492
  }
477
493
  int16() {
478
- let e = h(this, Y).getInt16(h(this, q), h(this, ae));
479
- return v(this, q, h(this, q) + 2), e;
494
+ let e = d(this, Y).getInt16(d(this, q), d(this, ce));
495
+ return D(this, q, d(this, q) + 2), e;
480
496
  }
481
497
  byte() {
482
- let e = h(this, Y).getUint8(h(this, q));
498
+ let e = d(this, Y).getUint8(d(this, q));
483
499
  return qt(this, q)._++, e;
484
500
  }
485
501
  int32() {
486
- let e = h(this, Y).getInt32(h(this, q), h(this, ae));
487
- return v(this, q, h(this, q) + 4), e;
502
+ let e = d(this, Y).getInt32(d(this, q), d(this, ce));
503
+ return D(this, q, d(this, q) + 4), e;
488
504
  }
489
505
  string(e) {
490
- return h(this, We).decode(this.bytes(e));
506
+ return d(this, Ge).decode(this.bytes(e));
491
507
  }
492
508
  cstring() {
493
- let e = h(this, q), t = e;
494
- for (; h(this, Y).getUint8(t++) !== 0; ) ;
509
+ let e = d(this, q), t = e;
510
+ for (; d(this, Y).getUint8(t++) !== 0; ) ;
495
511
  let n = this.string(t - e - 1);
496
- return v(this, q, t), n;
512
+ return D(this, q, t), n;
497
513
  }
498
514
  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);
515
+ let t = d(this, Y).buffer.slice(d(this, q), d(this, q) + e);
516
+ return D(this, q, d(this, q) + e), new Uint8Array(t);
501
517
  }
502
518
  };
503
- 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 {
519
+ Y = /* @__PURE__ */ new WeakMap(), q = /* @__PURE__ */ new WeakMap(), We = /* @__PURE__ */ new WeakMap(), Ge = /* @__PURE__ */ new WeakMap(), ce = /* @__PURE__ */ new WeakMap();
520
+ var He = 1, Cr = 4, it = He + Cr, ot = new ArrayBuffer(0), F, W, G, w, v, bn, Rn, ct, lt, ut, ht, ft, Le, dt, pt, Et, mt, yt, gt, _t, Tt, ve, Lr = class {
505
521
  constructor() {
506
- j(this, L), j(this, B, new DataView(it)), j(this, W, 0), j(this, G, 0), j(this, w, new vr());
522
+ j(this, v), j(this, F, new DataView(ot)), j(this, W, 0), j(this, G, 0), j(this, w, new Dr());
507
523
  }
508
524
  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);
511
- for (; r + at <= n; ) {
512
- let s = h(this, B).getUint8(r), a = h(this, B).getUint32(r + Ge, !1), i = Ge + a;
513
- if (i + r <= n && a > 0) {
514
- let o = O(this, L, bn).call(this, r + at, s, a, h(this, B).buffer);
515
- t(o), r += i;
525
+ O(this, v, bn).call(this, ArrayBuffer.isView(e) ? e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength) : e);
526
+ let n = d(this, G) + d(this, W), r = d(this, G);
527
+ for (; r + it <= n; ) {
528
+ let s = d(this, F).getUint8(r), a = d(this, F).getUint32(r + He, !1), o = He + a;
529
+ if (o + r <= n && a > 0) {
530
+ let i = O(this, v, Rn).call(this, r + it, s, a, d(this, F).buffer);
531
+ t(i), r += o;
516
532
  } else break;
517
533
  }
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));
534
+ r === n ? (D(this, F, new DataView(ot)), D(this, W, 0), D(this, G, 0)) : (D(this, W, n - r), D(this, G, r));
519
535
  }
520
536
  };
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) {
537
+ F = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__PURE__ */ new WeakMap(), w = /* @__PURE__ */ new WeakMap(), v = /* @__PURE__ */ new WeakSet(), bn = function(e) {
538
+ if (d(this, W) > 0) {
539
+ let t = d(this, W) + e.byteLength;
540
+ if (t + d(this, G) > d(this, F).byteLength) {
525
541
  let n;
526
- if (t <= h(this, B).byteLength && h(this, G) >= h(this, W)) n = h(this, B).buffer;
542
+ if (t <= d(this, F).byteLength && d(this, G) >= d(this, W)) n = d(this, F).buffer;
527
543
  else {
528
- let r = h(this, B).byteLength * 2;
544
+ let r = d(this, F).byteLength * 2;
529
545
  for (; t >= r; ) r *= 2;
530
546
  n = new ArrayBuffer(r);
531
547
  }
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);
548
+ new Uint8Array(n).set(new Uint8Array(d(this, F).buffer, d(this, G), d(this, W))), D(this, F, new DataView(n)), D(this, G, 0);
533
549
  }
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) {
550
+ new Uint8Array(d(this, F).buffer).set(new Uint8Array(e), d(this, G) + d(this, W)), D(this, W, t);
551
+ } else D(this, F, new DataView(e)), D(this, G, 0), D(this, W, e.byteLength);
552
+ }, Rn = function(e, t, n, r) {
537
553
  switch (t) {
538
554
  case 50:
539
555
  return zt;
@@ -552,124 +568,124 @@ B = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), G = /* @__
552
568
  case 73:
553
569
  return sn;
554
570
  case 68:
555
- return O(this, L, mt).call(this, e, n, r);
571
+ return O(this, v, yt).call(this, e, n, r);
556
572
  case 67:
557
- return O(this, L, ct).call(this, e, n, r);
573
+ return O(this, v, lt).call(this, e, n, r);
558
574
  case 90:
559
- return O(this, L, ot).call(this, e, n, r);
575
+ return O(this, v, ct).call(this, e, n, r);
560
576
  case 65:
561
- return O(this, L, ft).call(this, e, n, r);
577
+ return O(this, v, dt).call(this, e, n, r);
562
578
  case 82:
563
- return O(this, L, _t).call(this, e, n, r);
579
+ return O(this, v, Tt).call(this, e, n, r);
564
580
  case 83:
565
- return O(this, L, yt).call(this, e, n, r);
581
+ return O(this, v, gt).call(this, e, n, r);
566
582
  case 75:
567
- return O(this, L, gt).call(this, e, n, r);
583
+ return O(this, v, _t).call(this, e, n, r);
568
584
  case 69:
569
- return O(this, L, De).call(this, e, n, r, "error");
585
+ return O(this, v, ve).call(this, e, n, r, "error");
570
586
  case 78:
571
- return O(this, L, De).call(this, e, n, r, "notice");
587
+ return O(this, v, ve).call(this, e, n, r, "notice");
572
588
  case 84:
573
- return O(this, L, dt).call(this, e, n, r);
589
+ return O(this, v, pt).call(this, e, n, r);
574
590
  case 116:
575
- return O(this, L, Et).call(this, e, n, r);
591
+ return O(this, v, mt).call(this, e, n, r);
576
592
  case 71:
577
- return O(this, L, ut).call(this, e, n, r);
593
+ return O(this, v, ht).call(this, e, n, r);
578
594
  case 72:
579
- return O(this, L, ht).call(this, e, n, r);
595
+ return O(this, v, ft).call(this, e, n, r);
580
596
  case 100:
581
- return O(this, L, lt).call(this, e, n, r);
597
+ return O(this, v, ut).call(this, e, n, r);
582
598
  default:
583
599
  return new Be("received invalid response: " + t.toString(16), n, "error");
584
600
  }
585
- }, 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);
589
601
  }, 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);
602
+ d(this, w).setBuffer(e, n);
603
+ let r = d(this, w).string(1);
604
+ return new Tn(t, r);
593
605
  }, lt = function(e, t, n) {
606
+ d(this, w).setBuffer(e, n);
607
+ let r = d(this, w).cstring();
608
+ return new wn(t, r);
609
+ }, ut = function(e, t, n) {
594
610
  let r = n.slice(e, e + (t - 4));
595
611
  return new fn(t, new Uint8Array(r));
596
- }, ut = function(e, t, n) {
597
- return O(this, L, ve).call(this, e, t, n, "copyInResponse");
598
612
  }, ht = function(e, t, n) {
599
- return O(this, L, ve).call(this, e, t, n, "copyOutResponse");
600
- }, 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();
604
- return i;
613
+ return O(this, v, Le).call(this, e, t, n, "copyInResponse");
605
614
  }, 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();
608
- return new _n(t, r, s, a);
615
+ return O(this, v, Le).call(this, e, t, n, "copyOutResponse");
616
+ }, Le = function(e, t, n, r) {
617
+ d(this, w).setBuffer(e, n);
618
+ let s = d(this, w).byte() !== 0, a = d(this, w).int16(), o = new dn(t, r, s, a);
619
+ for (let i = 0; i < a; i++) o.columnTypes[i] = d(this, w).int16();
620
+ return o;
609
621
  }, dt = function(e, t, n) {
610
- h(this, w).setBuffer(e, n);
611
- let r = h(this, w).int16(), s = new En(t, r);
612
- for (let a = 0; a < r; a++) s.fields[a] = O(this, L, pt).call(this);
613
- return s;
614
- }, 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);
617
- }, 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();
622
+ d(this, w).setBuffer(e, n);
623
+ let r = d(this, w).int32(), s = d(this, w).cstring(), a = d(this, w).cstring();
624
+ return new _n(t, r, s, a);
625
+ }, pt = function(e, t, n) {
626
+ d(this, w).setBuffer(e, n);
627
+ let r = d(this, w).int16(), s = new En(t, r);
628
+ for (let a = 0; a < r; a++) s.fields[a] = O(this, v, Et).call(this);
621
629
  return s;
630
+ }, Et = function() {
631
+ let e = d(this, w).cstring(), t = d(this, w).int32(), n = d(this, w).int16(), r = d(this, w).int32(), s = d(this, w).int16(), a = d(this, w).int32(), o = d(this, w).int16() === 0 ? at.text : at.binary;
632
+ return new pn(e, t, n, r, s, a, o);
622
633
  }, mt = function(e, t, n) {
623
- h(this, w).setBuffer(e, n);
624
- let r = h(this, w).int16(), s = new Array(r);
634
+ d(this, w).setBuffer(e, n);
635
+ let r = d(this, w).int16(), s = new mn(t, r);
636
+ for (let a = 0; a < r; a++) s.dataTypeIDs[a] = d(this, w).int32();
637
+ return s;
638
+ }, yt = function(e, t, n) {
639
+ d(this, w).setBuffer(e, n);
640
+ let r = d(this, w).int16(), s = new Array(r);
625
641
  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);
642
+ let o = d(this, w).int32();
643
+ s[a] = o === -1 ? null : d(this, w).string(o);
628
644
  }
629
645
  return new Nn(t, s);
630
- }, yt = function(e, t, n) {
631
- h(this, w).setBuffer(e, n);
632
- let r = h(this, w).cstring(), s = h(this, w).cstring();
633
- return new yn(t, r, s);
634
646
  }, 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);
647
+ d(this, w).setBuffer(e, n);
648
+ let r = d(this, w).cstring(), s = d(this, w).cstring();
649
+ return new yn(t, r, s);
638
650
  }, _t = function(e, t, n) {
639
- h(this, w).setBuffer(e, n);
640
- let r = h(this, w).int32();
651
+ d(this, w).setBuffer(e, n);
652
+ let r = d(this, w).int32(), s = d(this, w).int32();
653
+ return new gn(t, r, s);
654
+ }, Tt = function(e, t, n) {
655
+ d(this, w).setBuffer(e, n);
656
+ let r = d(this, w).int32();
641
657
  switch (r) {
642
658
  case 0:
643
659
  return new an(t);
644
660
  case 3:
645
661
  return new on(t);
646
662
  case 5:
647
- return new cn(t, h(this, w).bytes(4));
663
+ return new cn(t, d(this, w).bytes(4));
648
664
  case 10: {
649
665
  let s = [];
650
666
  for (; ; ) {
651
- let a = h(this, w).cstring();
667
+ let a = d(this, w).cstring();
652
668
  if (a.length === 0) return new ln(t, s);
653
669
  s.push(a);
654
670
  }
655
671
  }
656
672
  case 11:
657
- return new un(t, h(this, w).string(t - 8));
673
+ return new un(t, d(this, w).string(t - 8));
658
674
  case 12:
659
- return new hn(t, h(this, w).string(t - 8));
675
+ return new hn(t, d(this, w).string(t - 8));
660
676
  default:
661
677
  throw new Error("Unknown authenticationOk message type " + r);
662
678
  }
663
- }, 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);
668
- 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;
679
+ }, ve = function(e, t, n, r) {
680
+ d(this, w).setBuffer(e, n);
681
+ let s = {}, a = d(this, w).string(1);
682
+ for (; a !== "\0"; ) s[a] = d(this, w).cstring(), a = d(this, w).string(1);
683
+ let o = s.M, i = r === "notice" ? new An(t, o) : new Be(o, t, r);
684
+ return i.severity = s.S, i.code = s.C, i.detail = s.D, i.hint = s.H, i.position = s.P, i.internalPosition = s.p, i.internalQuery = s.q, i.where = s.W, i.schema = s.s, i.table = s.t, i.column = s.c, i.dataType = s.d, i.constraint = s.n, i.file = s.F, i.line = s.L, i.routine = s.R, i;
669
685
  };
670
686
  H();
671
687
  typeof process == "object" && typeof process.versions == "object" && process.versions.node;
672
- var Tt = () => {
688
+ var wt = () => {
673
689
  if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
674
690
  let e = new Uint8Array(16);
675
691
  if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(e);
@@ -680,262 +696,262 @@ var Tt = () => {
680
696
  t.push(n.toString(16).padStart(2, "0"));
681
697
  }), t.slice(0, 4).join("") + "-" + t.slice(4, 6).join("") + "-" + t.slice(6, 8).join("") + "-" + t.slice(8, 10).join("") + "-" + t.slice(10).join("");
682
698
  };
683
- async function wt(e, t, n, r) {
699
+ async function Nt(e, t, n, r) {
684
700
  if (!n || n.length === 0) return t;
685
701
  r = r ?? e;
686
702
  let s = [];
687
703
  try {
688
- await e.execProtocol(re.parse({ text: t }), { syncToFs: !1 }), s.push(...(await e.execProtocol(re.describe({ type: "S" }), { syncToFs: !1 })).messages);
704
+ await e.execProtocol(oe.parse({ text: t }), { syncToFs: !1 }), s.push(...(await e.execProtocol(oe.describe({ type: "S" }), { syncToFs: !1 })).messages);
689
705
  } finally {
690
- s.push(...(await e.execProtocol(re.sync(), { syncToFs: !1 })).messages);
706
+ s.push(...(await e.execProtocol(oe.sync(), { syncToFs: !1 })).messages);
691
707
  }
692
- let a = Yt(s), i = t.replace(/\$([0-9]+)/g, (o, c) => "%" + c + "L");
693
- return (await r.query(`SELECT format($1, ${n.map((o, c) => `$${c + 2}`).join(", ")}) as query`, [i, ...n], { paramTypes: [ce, ...a] })).rows[0].query;
708
+ let a = Yt(s), o = t.replace(/\$([0-9]+)/g, (i, c) => "%" + c + "L");
709
+ return (await r.query(`SELECT format($1, ${n.map((i, c) => `$${c + 2}`).join(", ")}) as query`, [o, ...n], { paramTypes: [he, ...a] })).rows[0].query;
694
710
  }
695
- function Nt(e) {
711
+ function At(e) {
696
712
  let t, n = !1, r = async () => {
697
713
  if (!t) {
698
714
  n = !1;
699
715
  return;
700
716
  }
701
717
  n = !0;
702
- let { args: s, resolve: a, reject: i } = t;
718
+ let { args: s, resolve: a, reject: o } = t;
703
719
  t = void 0;
704
720
  try {
705
- let o = await e(...s);
706
- a(o);
707
- } catch (o) {
708
- i(o);
721
+ let i = await e(...s);
722
+ a(i);
723
+ } catch (i) {
724
+ o(i);
709
725
  } finally {
710
726
  r();
711
727
  }
712
728
  };
713
729
  return async (...s) => {
714
730
  t && t.resolve(void 0);
715
- let a = new Promise((i, o) => {
716
- t = { args: s, resolve: i, reject: o };
731
+ let a = new Promise((o, i) => {
732
+ t = { args: s, resolve: o, reject: i };
717
733
  });
718
734
  return n || r(), a;
719
735
  };
720
736
  }
721
737
  H();
722
- var Lr = 5, Mr = async (e, t) => {
723
- let n = /* @__PURE__ */ new Set(), r = { async query(s, a, i) {
724
- let o, c, u;
725
- 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;
727
- 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 () => {
738
+ var vr = 5, Mr = async (e, t) => {
739
+ let n = /* @__PURE__ */ new Set(), r = { async query(s, a, o) {
740
+ let i, c, l;
741
+ if (typeof s != "string" && (i = s.signal, a = s.params, o = s.callback, c = s.offset, l = s.limit, s = s.query), c === void 0 != (l === void 0)) throw new Error("offset and limit must be provided together");
742
+ let u = c !== void 0 && l !== void 0, h;
743
+ if (u && (typeof c != "number" || isNaN(c) || typeof l != "number" || isNaN(l))) throw new Error("offset and limit must be numbers");
744
+ let p = o ? [o] : [], f = wt().replace(/-/g, ""), E = !1, $, A, b = async () => {
729
745
  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
746
+ let S = a && a.length > 0 ? await Nt(e, s, a, g) : s;
747
+ await g.exec(`CREATE OR REPLACE TEMP VIEW live_query_${f}_view AS ${S}`);
748
+ let I = await $t(g, `live_query_${f}_view`);
749
+ await bt(g, I, n), u ? (await g.exec(`
750
+ PREPARE live_query_${f}_get(int, int) AS
751
+ SELECT * FROM live_query_${f}_view
736
752
  LIMIT $1 OFFSET $2;
737
753
  `), 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();
754
+ PREPARE live_query_${f}_get_total_count AS
755
+ SELECT COUNT(*) FROM live_query_${f}_view;
756
+ `), h = (await g.query(`EXECUTE live_query_${f}_get_total_count;`)).rows[0].count, $ = { ...await g.query(`EXECUTE live_query_${f}_get(${l}, ${c});`), offset: c, limit: l, totalCount: h }) : (await g.exec(`
757
+ PREPARE live_query_${f}_get AS
758
+ SELECT * FROM live_query_${f}_view;
759
+ `), $ = await g.query(`EXECUTE live_query_${f}_get;`)), A = await Promise.all(I.map((T) => g.listen(`"table_change__${T.schema_oid}__${T.table_oid}"`, async () => {
760
+ R();
745
761
  })));
746
762
  });
747
763
  };
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) {
764
+ await b();
765
+ let R = At(async ({ offset: g, limit: S } = {}) => {
766
+ if (!u && (g !== void 0 || S !== void 0)) throw new Error("offset and limit cannot be provided for non-windowed queries");
767
+ if (g && (typeof g != "number" || isNaN(g)) || S && (typeof S != "number" || isNaN(S))) throw new Error("offset and limit must be numbers");
768
+ c = g ?? c, l = S ?? l;
769
+ let I = async (T = 0) => {
770
+ if (p.length !== 0) {
755
771
  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;
772
+ u ? $ = { ...await e.query(`EXECUTE live_query_${f}_get(${l}, ${c});`), offset: c, limit: l, totalCount: h } : $ = await e.query(`EXECUTE live_query_${f}_get;`);
773
+ } catch (N) {
774
+ let k = N.message;
775
+ if (k.startsWith(`prepared statement "live_query_${f}`) && k.endsWith("does not exist")) {
776
+ if (T > vr) throw N;
777
+ await b(), I(T + 1);
778
+ } else throw N;
763
779
  }
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());
780
+ if (ie(p, $), u) {
781
+ let N = (await e.query(`EXECUTE live_query_${f}_get_total_count;`)).rows[0].count;
782
+ N !== h && (h = N, R());
767
783
  }
768
784
  }
769
785
  };
770
786
  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;
787
+ }), m = (g) => {
788
+ if (E) throw new Error("Live query is no longer active and cannot be subscribed to");
789
+ p.push(g);
790
+ }, y = async (g) => {
791
+ g ? p = p.filter((S) => S !== S) : p = [], p.length === 0 && !E && (E = !0, await e.transaction(async (S) => {
792
+ await Promise.all(A.map((I) => I(S))), await S.exec(`
793
+ DROP VIEW IF EXISTS live_query_${f}_view;
794
+ DEALLOCATE live_query_${f}_get;
779
795
  `);
780
796
  }));
781
797
  };
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 };
785
- }, async changes(s, a, i, o) {
798
+ return i?.aborted ? await y() : i?.addEventListener("abort", () => {
799
+ y();
800
+ }, { once: !0 }), ie(p, $), { initialResults: $, subscribe: m, unsubscribe: y, refresh: R };
801
+ }, async changes(s, a, o, i) {
786
802
  let c;
787
- 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 () => {
789
- 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(`
803
+ if (typeof s != "string" && (c = s.signal, a = s.params, o = s.key, i = s.callback, s = s.query), !o) throw new Error("key is required for changes queries");
804
+ let l = i ? [i] : [], u = wt().replace(/-/g, ""), h = !1, p = 1, f, E, $ = async () => {
805
+ await e.transaction(async (m) => {
806
+ let y = await Nt(e, s, a, m);
807
+ await m.query(`CREATE OR REPLACE TEMP VIEW live_query_${u}_view AS ${y}`);
808
+ let g = await $t(m, `live_query_${u}_view`);
809
+ await bt(m, g, n);
810
+ let S = [...(await m.query(`
795
811
  SELECT column_name, data_type, udt_name
796
812
  FROM information_schema.columns
797
- WHERE table_name = 'live_query_${l}_view'
813
+ WHERE table_name = 'live_query_${u}_view'
798
814
  `)).rows, { column_name: "__after__", data_type: "integer" }];
799
- await E.exec(`
800
- CREATE TEMP TABLE live_query_${l}_state1 (LIKE live_query_${l}_view INCLUDING ALL);
801
- CREATE TEMP TABLE live_query_${l}_state2 (LIKE live_query_${l}_view INCLUDING ALL);
815
+ await m.exec(`
816
+ CREATE TEMP TABLE live_query_${u}_state1 (LIKE live_query_${u}_view INCLUDING ALL);
817
+ CREATE TEMP TABLE live_query_${u}_state2 (LIKE live_query_${u}_view INCLUDING ALL);
802
818
  `);
803
819
  for (let I of [1, 2]) {
804
- let y = I === 1 ? 2 : 1;
805
- await E.exec(`
806
- PREPARE live_query_${l}_diff${I} AS
820
+ let T = I === 1 ? 2 : 1;
821
+ await m.exec(`
822
+ PREPARE live_query_${u}_diff${I} AS
807
823
  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}),
824
+ prev AS (SELECT LAG("${o}") OVER () as __after__, * FROM live_query_${u}_state${T}),
825
+ curr AS (SELECT LAG("${o}") OVER () as __after__, * FROM live_query_${u}_state${I}),
810
826
  data_diff AS (
811
827
  -- INSERT operations: Include all columns
812
828
  SELECT
813
829
  'INSERT' AS __op__,
814
- ${R.map(({ column_name: T }) => `curr."${T}" AS "${T}"`).join(`,
830
+ ${S.map(({ column_name: N }) => `curr."${N}" AS "${N}"`).join(`,
815
831
  `)},
816
832
  ARRAY[]::text[] AS __changed_columns__
817
833
  FROM curr
818
- LEFT JOIN prev ON curr.${i} = prev.${i}
819
- WHERE prev.${i} IS NULL
834
+ LEFT JOIN prev ON curr.${o} = prev.${o}
835
+ WHERE prev.${o} IS NULL
820
836
  UNION ALL
821
837
  -- DELETE operations: Include only the primary key
822
838
  SELECT
823
839
  '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(`,
840
+ ${S.map(({ column_name: N, data_type: k, udt_name: Q }) => N === o ? `prev."${N}" AS "${N}"` : `NULL${k === "USER-DEFINED" ? `::${Q}` : ""} AS "${N}"`).join(`,
825
841
  `)},
826
842
  ARRAY[]::text[] AS __changed_columns__
827
843
  FROM prev
828
- LEFT JOIN curr ON prev.${i} = curr.${i}
829
- WHERE curr.${i} IS NULL
844
+ LEFT JOIN curr ON prev.${o} = curr.${o}
845
+ WHERE curr.${o} IS NULL
830
846
  UNION ALL
831
847
  -- UPDATE operations: Include only changed columns
832
848
  SELECT
833
849
  '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}"
850
+ ${S.map(({ column_name: N, data_type: k, udt_name: Q }) => N === o ? `curr."${N}" AS "${N}"` : `CASE
851
+ WHEN curr."${N}" IS DISTINCT FROM prev."${N}"
852
+ THEN curr."${N}"
837
853
  ELSE NULL${k === "USER-DEFINED" ? `::${Q}` : ""}
838
- END AS "${T}"`).join(`,
854
+ END AS "${N}"`).join(`,
839
855
  `)},
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}'
856
+ ARRAY(SELECT unnest FROM unnest(ARRAY[${S.filter(({ column_name: N }) => N !== o).map(({ column_name: N }) => `CASE
857
+ WHEN curr."${N}" IS DISTINCT FROM prev."${N}"
858
+ THEN '${N}'
843
859
  ELSE NULL
844
860
  END`).join(", ")}]) WHERE unnest IS NOT NULL) AS __changed_columns__
845
861
  FROM curr
846
- INNER JOIN prev ON curr.${i} = prev.${i}
862
+ INNER JOIN prev ON curr.${o} = prev.${o}
847
863
  WHERE NOT (curr IS NOT DISTINCT FROM prev)
848
864
  )
849
865
  SELECT * FROM data_diff;
850
866
  `);
851
867
  }
852
- _ = await Promise.all(g.map((I) => E.listen(`"table_change__${I.schema_oid}__${I.table_oid}"`, async () => {
853
- $();
868
+ E = await Promise.all(g.map((I) => m.listen(`"table_change__${I.schema_oid}__${I.table_oid}"`, async () => {
869
+ A();
854
870
  })));
855
871
  });
856
872
  };
857
- await S();
858
- let $ = Nt(async () => {
859
- if (u.length === 0 && p) return;
860
- let E = !1;
861
- for (let m = 0; m < 5; m++) try {
873
+ await $();
874
+ let A = At(async () => {
875
+ if (l.length === 0 && f) return;
876
+ let m = !1;
877
+ for (let y = 0; y < 5; y++) try {
862
878
  await e.transaction(async (g) => {
863
879
  await g.exec(`
864
- INSERT INTO live_query_${l}_state${f}
865
- 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};
880
+ INSERT INTO live_query_${u}_state${p}
881
+ SELECT * FROM live_query_${u}_view;
882
+ `), f = await g.query(`EXECUTE live_query_${u}_diff${p};`), p = p === 1 ? 2 : 1, await g.exec(`
883
+ TRUNCATE live_query_${u}_state${p};
868
884
  `);
869
885
  });
870
886
  break;
871
887
  } catch (g) {
872
- if (g.message === `relation "live_query_${l}_state${f}" does not exist`) {
873
- E = !0, await S();
888
+ if (g.message === `relation "live_query_${u}_state${p}" does not exist`) {
889
+ m = !0, await $();
874
890
  continue;
875
891
  } else throw g;
876
892
  }
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");
880
- 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(`
884
- DROP VIEW IF EXISTS live_query_${l}_view;
885
- DROP TABLE IF EXISTS live_query_${l}_state1;
886
- DROP TABLE IF EXISTS live_query_${l}_state2;
887
- DEALLOCATE live_query_${l}_diff1;
888
- DEALLOCATE live_query_${l}_diff2;
893
+ Pr(l, [...m ? [{ __op__: "RESET" }] : [], ...f.rows]);
894
+ }), b = (m) => {
895
+ if (h) throw new Error("Live query is no longer active and cannot be subscribed to");
896
+ l.push(m);
897
+ }, R = async (m) => {
898
+ m ? l = l.filter((y) => y !== y) : l = [], l.length === 0 && !h && (h = !0, await e.transaction(async (y) => {
899
+ await Promise.all(E.map((g) => g(y))), await y.exec(`
900
+ DROP VIEW IF EXISTS live_query_${u}_view;
901
+ DROP TABLE IF EXISTS live_query_${u}_state1;
902
+ DROP TABLE IF EXISTS live_query_${u}_state2;
903
+ DEALLOCATE live_query_${u}_diff1;
904
+ DEALLOCATE live_query_${u}_diff2;
889
905
  `);
890
906
  }));
891
907
  };
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: $ };
895
- }, async incrementalQuery(s, a, i, o) {
908
+ return c?.aborted ? await R() : c?.addEventListener("abort", () => {
909
+ R();
910
+ }, { once: !0 }), await A(), { fields: f.fields.filter((m) => !["__after__", "__op__", "__changed_columns__"].includes(m.name)), initialChanges: f.rows, subscribe: b, unsubscribe: R, refresh: A };
911
+ }, async incrementalQuery(s, a, o, i) {
896
912
  let c;
897
- 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;
913
+ if (typeof s != "string" && (c = s.signal, a = s.params, o = s.key, i = s.callback, s = s.query), !o) throw new Error("key is required for incremental queries");
914
+ let l = i ? [i] : [], u = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), p = [], f = !0, { fields: E, unsubscribe: $, refresh: A } = await r.changes(s, a, o, (m) => {
915
+ for (let S of m) {
916
+ let { __op__: I, __changed_columns__: T, ...N } = S;
901
917
  switch (I) {
902
918
  case "RESET":
903
- l.clear(), d.clear();
919
+ u.clear(), h.clear();
904
920
  break;
905
921
  case "INSERT":
906
- l.set(T[i], T), d.set(T.__after__, T[i]);
922
+ u.set(N[o], N), h.set(N.__after__, N[o]);
907
923
  break;
908
924
  case "DELETE": {
909
- let k = l.get(T[i]);
910
- l.delete(T[i]), k.__after__ !== null && d.delete(k.__after__);
925
+ let k = u.get(N[o]);
926
+ u.delete(N[o]), k.__after__ !== null && h.delete(k.__after__);
911
927
  break;
912
928
  }
913
929
  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);
930
+ let k = { ...u.get(N[o]) ?? {} };
931
+ for (let Q of T) k[Q] = N[Q], Q === "__after__" && h.set(N.__after__, N[o]);
932
+ u.set(N[o], k);
917
933
  break;
918
934
  }
919
935
  }
920
936
  }
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;
937
+ let y = [], g = null;
938
+ for (let S = 0; S < u.size; S++) {
939
+ let I = h.get(g), T = u.get(I);
940
+ if (!T) break;
941
+ let N = { ...T };
942
+ delete N.__after__, y.push(N), g = I;
927
943
  }
928
- f = m, p || se(u, { rows: m, fields: _ });
944
+ p = y, f || ie(l, { rows: y, fields: E });
929
945
  });
930
- p = !1, se(u, { rows: f, fields: _ });
931
- let A = (E) => {
932
- u.push(E);
933
- }, b = async (E) => {
934
- E ? u = u.filter((m) => m !== m) : u = [], u.length === 0 && await S();
946
+ f = !1, ie(l, { rows: p, fields: E });
947
+ let b = (m) => {
948
+ l.push(m);
949
+ }, R = async (m) => {
950
+ m ? l = l.filter((y) => y !== y) : l = [], l.length === 0 && await $();
935
951
  };
936
- return c?.aborted ? await b() : c?.addEventListener("abort", () => {
937
- b();
938
- }, { once: !0 }), { initialResults: { rows: f, fields: _ }, subscribe: A, unsubscribe: b, refresh: $ };
952
+ return c?.aborted ? await R() : c?.addEventListener("abort", () => {
953
+ R();
954
+ }, { once: !0 }), { initialResults: { rows: p, fields: E }, subscribe: b, unsubscribe: R, refresh: A };
939
955
  } };
940
956
  return { namespaceObj: r };
941
957
  }, qr = { name: "Live Queries", setup: Mr };
@@ -986,7 +1002,7 @@ async function $t(e, t) {
986
1002
  WHERE NOT is_view; -- Exclude intermediate views
987
1003
  `, [t])).rows.map((n) => ({ table_name: n.table_name, schema_name: n.schema_name, table_oid: n.table_oid, schema_oid: n.schema_oid }));
988
1004
  }
989
- async function At(e, t, n) {
1005
+ async function bt(e, t, n) {
990
1006
  let r = t.filter((s) => !n.has(`${s.schema_oid}_${s.table_oid}`)).map((s) => `
991
1007
  CREATE OR REPLACE FUNCTION "_notify_${s.schema_oid}_${s.table_oid}"() RETURNS TRIGGER AS $$
992
1008
  BEGIN
@@ -1001,7 +1017,7 @@ async function At(e, t, n) {
1001
1017
  `);
1002
1018
  r.trim() !== "" && await e.exec(r), t.map((s) => n.add(`${s.schema_oid}_${s.table_oid}`));
1003
1019
  }
1004
- var se = (e, t) => {
1020
+ var ie = (e, t) => {
1005
1021
  for (let n of e) n(t);
1006
1022
  }, Pr = (e, t) => {
1007
1023
  for (let n of e) n(t);
@@ -1009,7 +1025,7 @@ var se = (e, t) => {
1009
1025
  class Rt extends Wn {
1010
1026
  #e;
1011
1027
  #s;
1012
- #i = 16;
1028
+ #o = 16;
1013
1029
  // 批量发送间隔 (ms)
1014
1030
  #t = [];
1015
1031
  #r;
@@ -1026,7 +1042,7 @@ class Rt extends Wn {
1026
1042
  for (const s of r)
1027
1043
  await this.#e.exec(`LISTEN "${s}_notify"`);
1028
1044
  this.#e.onNotification((s, a) => {
1029
- this.#o(s, a);
1045
+ this.#c(s, a);
1030
1046
  });
1031
1047
  }
1032
1048
  sql(t, ...n) {
@@ -1058,7 +1074,7 @@ class Rt extends Wn {
1058
1074
  * @param channel - 通知频道名称
1059
1075
  * @param payload - JSON 格式的 payload
1060
1076
  */
1061
- #o(t, n) {
1077
+ #c(t, n) {
1062
1078
  try {
1063
1079
  const r = JSON.parse(n), s = t.replace("_notify", "");
1064
1080
  for (const a of r.ids)
@@ -1069,7 +1085,7 @@ class Rt extends Wn {
1069
1085
  });
1070
1086
  this.#r && clearTimeout(this.#r), this.#r = setTimeout(() => {
1071
1087
  this.#a(), this.#r = void 0;
1072
- }, this.#i);
1088
+ }, this.#o);
1073
1089
  } catch (r) {
1074
1090
  console.error("Failed to parse NOTIFY payload:", r);
1075
1091
  }
@@ -1081,7 +1097,7 @@ class Rt extends Wn {
1081
1097
  const t = Object.groupBy(this.#t, (n) => `${n.type}_${n.tableName}`);
1082
1098
  for (const [, n] of Object.entries(t)) {
1083
1099
  if (!n || n.length === 0) continue;
1084
- const r = n[0], s = n.map((i) => i.id), a = {
1100
+ const r = n[0], s = n.map((o) => o.id), a = {
1085
1101
  type: r.type,
1086
1102
  dbName: this.#s,
1087
1103
  tableName: r.tableName,
@@ -1096,22 +1112,22 @@ class Rt extends Wn {
1096
1112
  const Sn = (e, t) => {
1097
1113
  const n = P(e), r = t.map((s) => `'${s.id}'`).join(",");
1098
1114
  return `DELETE FROM ${n} WHERE id IN (${r});`;
1099
- }, ue = (e, t, n) => {
1100
- const r = P(e), s = n?.userId && e.propertyMap.has("createdBy"), a = n?.userId && e.propertyMap.has("updatedBy"), i = [
1101
- ...Array.from(e.propertyMap.values()).map((u) => u.columnName),
1115
+ }, de = (e, t, n) => {
1116
+ const r = P(e), s = n?.userId && e.propertyMap.has("createdBy"), a = n?.userId && e.propertyMap.has("updatedBy"), o = [
1117
+ ...Array.from(e.propertyMap.values()).map((l) => l.columnName),
1102
1118
  ...e.foreignKeyColumnNames || e.foreignKeyNames
1103
- ], o = [];
1104
- t.forEach((u) => {
1105
- const l = Lt(e, u);
1106
- 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(",")})`);
1119
+ ], i = [];
1120
+ t.forEach((l) => {
1121
+ const u = vt(e, l);
1122
+ s && (u.createdBy = n.userId), a && (u.updatedBy = n.userId);
1123
+ const h = Je(e, u), p = [];
1124
+ o.forEach((f) => {
1125
+ const E = h[f];
1126
+ p.push(Ye(E));
1127
+ }), i.push(`(${p.join(",")})`);
1112
1128
  });
1113
- const c = i.map((u) => `"${u}"`).join(",");
1114
- return `INSERT INTO ${r} (${c}) VALUES ${o.join(",")};`;
1129
+ const c = o.map((l) => `"${l}"`).join(",");
1130
+ return `INSERT INTO ${r} (${c}) VALUES ${i.join(",")};`;
1115
1131
  }, Ur = (e) => {
1116
1132
  if (e.includes("$")) {
1117
1133
  const [t, n] = e.split("$");
@@ -1134,13 +1150,13 @@ const Sn = (e, t) => {
1134
1150
  return;
1135
1151
  }
1136
1152
  const a = e.rxdb.schemaManager.getEntityMetadata(s.entity, s.namespace);
1137
- a ? (s.inversePatch && st(a, s.inversePatch), s.patch && st(a, s.patch)) : console.warn(`Entity metadata not found for ${s.namespace}.${s.entity}`);
1153
+ a ? (s.inversePatch && rt(a, s.inversePatch), s.patch && rt(a, s.patch)) : console.warn(`Entity metadata not found for ${s.namespace}.${s.entity}`);
1138
1154
  });
1139
1155
  const n = Object.groupBy(t, (s) => s.type), r = Object.entries(n);
1140
1156
  for (let s = 0; s < r.length; s++) {
1141
- const [a, i] = r[s];
1142
- if (!i || i.length === 0) continue;
1143
- const o = i.filter((c) => c.namespace && c.entity).map(
1157
+ const [a, o] = r[s];
1158
+ if (!o || o.length === 0) continue;
1159
+ const i = o.filter((c) => c.namespace && c.entity).map(
1144
1160
  (c) => ({
1145
1161
  namespace: c.namespace,
1146
1162
  entity: c.entity,
@@ -1151,89 +1167,89 @@ const Sn = (e, t) => {
1151
1167
  recordAt: c.createdAt
1152
1168
  })
1153
1169
  );
1154
- if (o.length !== 0)
1170
+ if (i.length !== 0)
1155
1171
  switch (a) {
1156
1172
  case "INSERT":
1157
- e.rxdb.dispatchEvent(new oe(o));
1173
+ e.rxdb.dispatchEvent(new ue(i));
1158
1174
  break;
1159
1175
  case "UPDATE":
1160
- e.rxdb.dispatchEvent(new me(o));
1176
+ e.rxdb.dispatchEvent(new ge(i));
1161
1177
  break;
1162
1178
  case "DELETE":
1163
- e.rxdb.dispatchEvent(new Ve(o));
1179
+ e.rxdb.dispatchEvent(new Ke(i));
1164
1180
  break;
1165
1181
  }
1166
1182
  }
1167
- }, Ce = (e, t) => {
1183
+ }, Me = (e, t) => {
1168
1184
  const { tableName: n } = t, [r, s] = Ur(n), a = e.rxdb.schemaManager.getEntityTypeByTableName(s, r);
1169
1185
  if (!a) return;
1170
- const i = e.getRepository(a), o = e.rxdb.schemaManager.getEntityMetadataByTableName(s, r);
1171
- if (!o) {
1186
+ const o = e.getRepository(a), i = e.rxdb.schemaManager.getEntityMetadataByTableName(s, r);
1187
+ if (!i) {
1172
1188
  console.warn(`Metadata not found for entity ${r}.${s}`);
1173
1189
  return;
1174
1190
  }
1175
- i.findByRowIds(t.rowIds).then((c) => {
1176
- const u = c;
1177
- if (!(!u || u.length === 0))
1178
- if (a === ie) {
1191
+ o.findByRowIds(t.rowIds).then((c) => {
1192
+ const l = c;
1193
+ if (!(!l || l.length === 0))
1194
+ if (a === le) {
1179
1195
  if (xr(e, c), t.type === K.INSERT) {
1180
- const l = D(ie), d = c.map((f) => ({
1181
- namespace: l.namespace,
1182
- entity: l.name,
1183
- type: f.type,
1184
- id: f.id,
1185
- patch: { ...f },
1196
+ const u = C(le), h = c.map((p) => ({
1197
+ namespace: u.namespace,
1198
+ entity: u.name,
1199
+ type: p.type,
1200
+ id: p.id,
1201
+ patch: { ...p },
1186
1202
  inversePatch: null,
1187
- recordAt: f.createdAt || /* @__PURE__ */ new Date()
1203
+ recordAt: p.createdAt || /* @__PURE__ */ new Date()
1188
1204
  }));
1189
- e.rxdb.dispatchEvent(new oe(d));
1205
+ e.rxdb.dispatchEvent(new ue(h));
1190
1206
  }
1191
1207
  } else {
1192
- const l = jr(t.type), d = u.map((f) => {
1193
- const p = {
1194
- namespace: o.namespace,
1195
- entity: o.name,
1196
- type: l,
1197
- id: f.id,
1208
+ const u = jr(t.type), h = l.map((p) => {
1209
+ const f = {
1210
+ namespace: i.namespace,
1211
+ entity: i.name,
1212
+ type: u,
1213
+ id: p.id,
1198
1214
  patch: null,
1199
1215
  inversePatch: null,
1200
- recordAt: f.createdAt || /* @__PURE__ */ new Date()
1216
+ recordAt: p.createdAt || /* @__PURE__ */ new Date()
1201
1217
  };
1202
1218
  switch (t.type) {
1203
1219
  case K.INSERT:
1204
1220
  return {
1205
- ...p,
1206
- patch: { ...f }
1221
+ ...f,
1222
+ patch: { ...p }
1207
1223
  };
1208
1224
  case K.DELETE:
1209
1225
  return {
1210
- ...p,
1211
- inversePatch: { ...f }
1226
+ ...f,
1227
+ inversePatch: { ...p }
1212
1228
  };
1213
1229
  case K.UPDATE:
1214
1230
  return {
1215
- ...p,
1231
+ ...f,
1216
1232
  // 注意:这里无法获取变更前的数据,只能把整个 entity 作为 patch
1217
1233
  // 这是 UPDATE hook 的限制,完整的 patch/inversePatch 应该从 RxDBChange 表获取
1218
1234
  inversePatch: null,
1219
- patch: { ...f }
1235
+ patch: { ...p }
1220
1236
  };
1221
1237
  }
1222
1238
  });
1223
- switch (l) {
1239
+ switch (u) {
1224
1240
  case "UPDATE":
1225
1241
  e.rxdb.dispatchEvent(
1226
- new me(d)
1242
+ new ge(h)
1227
1243
  );
1228
1244
  break;
1229
1245
  case "DELETE":
1230
1246
  e.rxdb.dispatchEvent(
1231
- new Ve(d)
1247
+ new Ke(h)
1232
1248
  );
1233
1249
  break;
1234
1250
  case "INSERT":
1235
1251
  e.rxdb.dispatchEvent(
1236
- new oe(d)
1252
+ new ue(h)
1237
1253
  );
1238
1254
  break;
1239
1255
  }
@@ -1241,184 +1257,184 @@ const Sn = (e, t) => {
1241
1257
  }).catch((c) => {
1242
1258
  c.message?.includes("closed") || console.error("Failed to handle RxDBChange event", c);
1243
1259
  });
1244
- }, Br = (e, t) => {
1260
+ }, Fr = (e, t) => {
1245
1261
  const n = P(e), r = [t.id];
1246
1262
  return {
1247
1263
  sql: `DELETE FROM ${n} WHERE id = $1;`,
1248
1264
  params: r
1249
1265
  };
1250
1266
  }, In = (e, t, n) => {
1251
- const r = P(e), s = Lt(e, t);
1267
+ const r = P(e), s = vt(e, t);
1252
1268
  n?.userId && (e.propertyMap.has("createdBy") && (s.createdBy = n.userId), e.propertyMap.has("updatedBy") && (s.updatedBy = n.userId));
1253
1269
  const a = {};
1254
- Object.keys(s).forEach((f) => {
1255
- const p = s[f];
1256
- p != null && (a[f] = p);
1270
+ Object.keys(s).forEach((p) => {
1271
+ const f = s[p];
1272
+ f != null && (a[p] = f);
1257
1273
  });
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 };
1261
- }, ze = (e, t, n, r) => {
1274
+ const o = Object.keys(a), i = Je(e, a), c = [], l = o.map((p, f) => (c.push(i[p]), `$${f + 1}`)), u = o.map((p) => `"${p}"`).join(",");
1275
+ let h = `INSERT INTO ${r} (${u}) VALUES (${l.join(",")})`;
1276
+ return n?.returning !== !1 ? h += " RETURNING *;" : h += ";", { sql: h, params: c };
1277
+ }, Ze = (e, t, n, r) => {
1262
1278
  const s = zn(e, n);
1263
1279
  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 `;
1280
+ const a = Je(e, s), i = Object.keys(s).map((p, f) => `"${p}" = $${f + 1}`).join(","), c = [...Object.values(a)], l = P(e), u = Array.isArray(t) ? t : [t];
1281
+ let h = `UPDATE ${l} SET ${i} WHERE id `;
1266
1282
  if (Array.isArray(t)) {
1267
- const f = c.length + 1;
1268
- d += `= ANY($${f})`, c.push(l.map((p) => p.id));
1283
+ const p = c.length + 1;
1284
+ h += `= ANY($${p})`, c.push(u.map((f) => f.id));
1269
1285
  } else {
1270
- const f = c.length + 1;
1271
- d += `= $${f}`, c.push(t.id);
1286
+ const p = c.length + 1;
1287
+ h += `= $${p}`, c.push(t.id);
1272
1288
  }
1273
- return r?.returning !== !1 ? d += " RETURNING *;" : d += ";", {
1274
- sql: d,
1289
+ return r?.returning !== !1 ? h += " RETURNING *;" : h += ";", {
1290
+ sql: h,
1275
1291
  params: c
1276
1292
  };
1277
- }, Ze = "_", On = (e) => e.replaceAll(".", "_"), he = (e, t) => {
1293
+ }, et = "_", On = (e) => e.replaceAll(".", "_"), pe = (e, t) => {
1278
1294
  if (e.relationAliasMap.has(t)) return e.relationAliasMap.get(t);
1279
- const n = t.includes("_") ? t : t.split("_")[0], r = Dn(e, On(n));
1295
+ const n = t.includes("_") ? t : t.split("_")[0], r = Cn(e, On(n));
1280
1296
  return e.relationAliasMap.set(t, r), r;
1281
- }, Fr = (e, t, n, r) => {
1297
+ }, Br = (e, t, n, r) => {
1282
1298
  const s = n.slice(0, r);
1283
1299
  let a = t;
1284
- const i = [];
1285
- for (const o of s) {
1286
- if (!a?.relationMap.has(o)) return { relPairs: [] };
1287
- const c = a.relationMap.get(o);
1288
- i.push({ metadata: a, relation: c }), a = e.rxdb.schemaManager.getEntityMetadata(c.mappedEntity, c.mappedNamespace);
1300
+ const o = [];
1301
+ for (const i of s) {
1302
+ if (!a?.relationMap.has(i)) return { relPairs: [] };
1303
+ const c = a.relationMap.get(i);
1304
+ o.push({ metadata: a, relation: c }), a = e.rxdb.schemaManager.getEntityMetadata(c.mappedEntity, c.mappedNamespace);
1289
1305
  }
1290
- return { metaWalker: a, relPairs: i };
1306
+ return { metaWalker: a, relPairs: o };
1291
1307
  }, kr = (e, t, n, r, s) => {
1292
1308
  for (let a = s.length - 1; a > 0; a--) {
1293
- const i = s.slice(a);
1294
- if (i.length === 0) continue;
1295
- const { metaWalker: o, relPairs: c } = Fr(e, n, s, a);
1296
- 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;
1309
+ const o = s.slice(a);
1310
+ if (o.length === 0) continue;
1311
+ const { metaWalker: i, relPairs: c } = Br(e, n, s, a);
1312
+ if (!i || c.length === 0) continue;
1313
+ const l = o[0], u = o.slice(1).join("."), h = i.propertyMap.get(l);
1314
+ if (h && h.type === _.keyValue) {
1315
+ const p = s.slice(0, a).join(".");
1316
+ Dn(e, t, c, p);
1317
+ const f = c[c.length - 1].relation, E = me(c, p, f), $ = pe(t, E), A = u ? `$.${u}` : "$";
1318
+ return t.fieldAliasMap.set(r, `"${$}"."${h.columnName}" ->> '${A.replace("$.", "")}'`), !0;
1303
1319
  }
1304
1320
  }
1305
1321
  return !1;
1306
- }, vn = (e, t, n, r) => {
1307
- n.forEach(({ metadata: s, relation: a }, i) => {
1308
- let o = e.rxdb.schemaManager.findMappedRelation(s, a);
1309
- 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 });
1314
- if (!o) throw new x("mappedRelation not found");
1315
- const c = de(n, r, a), u = he(t, c);
1316
- let l = Ze;
1317
- if (i > 0) {
1318
- const d = n[i - 1], f = de(n, r, d.relation);
1319
- l = he(t, f);
1322
+ }, Dn = (e, t, n, r) => {
1323
+ n.forEach(({ metadata: s, relation: a }, o) => {
1324
+ let i = e.rxdb.schemaManager.findMappedRelation(s, a);
1325
+ if (!i)
1326
+ if (a.kind === B.ONE_TO_MANY || a.kind === B.MANY_TO_MANY) {
1327
+ const h = s.relationMap.get(a.mappedProperty);
1328
+ h && (i = { metadata: s, relation: h });
1329
+ } else (a.kind === B.MANY_TO_ONE || a.kind === B.ONE_TO_ONE) && (i = { metadata: s, relation: a });
1330
+ if (!i) throw new x("mappedRelation not found");
1331
+ const c = me(n, r, a), l = pe(t, c);
1332
+ let u = et;
1333
+ if (o > 0) {
1334
+ const h = n[o - 1], p = me(n, r, h.relation);
1335
+ u = pe(t, p);
1320
1336
  }
1321
1337
  switch (a.kind) {
1322
- case F.ONE_TO_MANY:
1338
+ case B.ONE_TO_MANY:
1323
1339
  Wr(
1324
1340
  t,
1325
- o,
1326
- u,
1327
- l
1341
+ i,
1342
+ l,
1343
+ u
1328
1344
  );
1329
1345
  break;
1330
- case F.ONE_TO_ONE:
1331
- case F.MANY_TO_ONE:
1346
+ case B.ONE_TO_ONE:
1347
+ case B.MANY_TO_ONE:
1332
1348
  Gr(
1333
1349
  t,
1334
- o,
1335
- u,
1350
+ i,
1336
1351
  l,
1352
+ u,
1337
1353
  a
1338
1354
  );
1339
1355
  break;
1340
- case F.MANY_TO_MANY:
1356
+ case B.MANY_TO_MANY:
1341
1357
  Hr(
1342
1358
  t,
1343
- o,
1344
- u,
1359
+ i,
1345
1360
  l,
1361
+ u,
1346
1362
  a
1347
1363
  );
1348
1364
  break;
1349
1365
  }
1350
1366
  });
1351
1367
  }, Wr = (e, t, n, r) => {
1352
- const s = fe(e, t.metadata), a = t.relation.columnName, i = `"${n}"."${a}" = ${et(r)}."id"`;
1353
- s.find((c) => c.joinTableName === n && c.on === i) || s.push({
1368
+ const s = Ee(e, t.metadata), a = t.relation.columnName, o = `"${n}"."${a}" = ${tt(r)}."id"`;
1369
+ s.find((c) => c.joinTableName === n && c.on === o) || s.push({
1354
1370
  joinTableName: n,
1355
- on: i
1371
+ on: o
1356
1372
  });
1357
1373
  }, Gr = (e, t, n, r, s) => {
1358
- const a = fe(e, t.metadata), i = `"${n}"."id" = ${et(r)}."${s.columnName}"`;
1359
- a.find((c) => c.joinTableName === n && c.on === i) || a.push({
1374
+ const a = Ee(e, t.metadata), o = `"${n}"."id" = ${tt(r)}."${s.columnName}"`;
1375
+ a.find((c) => c.joinTableName === n && c.on === o) || a.push({
1360
1376
  joinTableName: n,
1361
- on: i
1377
+ on: o
1362
1378
  });
1363
1379
  }, 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"`;
1365
- i.find(
1366
- (p) => p.joinTableName === o && p.on === c
1367
- ) || i.push({
1368
- joinTableName: o,
1380
+ const a = C(s.junctionEntityType), o = Ee(e, a), i = Cn(e, On(`${s.name}_m_n`)), c = `"${i}"."${t.relation.columnName}" = ${tt(r)}."id"`;
1381
+ o.find(
1382
+ (f) => f.joinTableName === i && f.on === c
1383
+ ) || o.push({
1384
+ joinTableName: i,
1369
1385
  on: c
1370
1386
  });
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({
1387
+ const u = Ee(e, t.metadata), h = `"${n}"."id" = "${i}"."${s.columnName}"`;
1388
+ u.find((f) => f.joinTableName === n && f.on === h) || u.push({
1373
1389
  joinTableName: n,
1374
- on: d
1390
+ on: h
1375
1391
  });
1376
- }, fe = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), Dn = (e, t) => {
1392
+ }, Ee = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), Cn = (e, t) => {
1377
1393
  let n = t, r = 1;
1378
1394
  for (; e.usedAliases.has(n); )
1379
1395
  n = `${t}_${r++}`;
1380
1396
  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) => {
1397
+ }, me = (e, t, n) => e.length === 1 ? n.name : `${t}_${n.name}`, tt = (e) => e === et ? e : `"${e}"`, Ln = (e, t, n) => {
1382
1398
  const r = {
1383
1399
  joinMap: /* @__PURE__ */ new Map(),
1384
1400
  usedAliases: /* @__PURE__ */ new Set(),
1385
1401
  fieldAliasMap: /* @__PURE__ */ new Map(),
1386
1402
  relationAliasMap: /* @__PURE__ */ new Map()
1387
1403
  };
1388
- Gn(n, (a, i, o) => {
1389
- const c = i;
1390
- a !== "field" || !c.includes(".") || Vr(e, r, t, c, o);
1404
+ Gn(n, (a, o, i) => {
1405
+ const c = o;
1406
+ a !== "field" || !c.includes(".") || Vr(e, r, t, c, i);
1391
1407
  });
1392
1408
  const s = [];
1393
- for (const [a, i] of r.joinMap.entries()) {
1394
- const o = P(a);
1395
- for (const c of i)
1396
- s.push(` LEFT JOIN ${o} "${c.joinTableName}" ON ${c.on}`);
1409
+ for (const [a, o] of r.joinMap.entries()) {
1410
+ const i = P(a);
1411
+ for (const c of o)
1412
+ s.push(` LEFT JOIN ${i} "${c.joinTableName}" ON ${c.on}`);
1397
1413
  }
1398
1414
  return { joinSQL: s.join(""), fieldAliasMap: r.fieldAliasMap };
1399
1415
  }, Vr = (e, t, n, r, s) => {
1400
1416
  const a = r.split(".");
1401
1417
  try {
1402
- const u = e.rxdb.schemaManager.getFieldRelations(n, r);
1403
- if (u.isForeignKey) {
1404
- s.field = u.propertyName;
1418
+ const l = e.rxdb.schemaManager.getFieldRelations(n, r);
1419
+ if (l.isForeignKey) {
1420
+ s.field = l.propertyName;
1405
1421
  return;
1406
1422
  }
1407
- 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}"`);
1423
+ const u = r.replace(`.${l.propertyName}`, "");
1424
+ Dn(e, t, l.relations, u);
1425
+ const h = l.relations[l.relations.length - 1], p = me(l.relations, u, h.relation), f = pe(t, p);
1426
+ t.fieldAliasMap.set(r, `"${f}"."${l.property.columnName}"`);
1411
1427
  return;
1412
1428
  } catch {
1413
1429
  }
1414
- const [i, ...o] = a, c = n.propertyMap.get(i);
1415
- if (c && c.type === N.keyValue && o.length > 0) {
1416
- const u = o.join(".");
1417
- t.fieldAliasMap.set(r, `"${Ze}"."${c.columnName}" ->> '${u}'`);
1430
+ const [o, ...i] = a, c = n.propertyMap.get(o);
1431
+ if (c && c.type === _.keyValue && i.length > 0) {
1432
+ const l = i.join(".");
1433
+ t.fieldAliasMap.set(r, `"${et}"."${c.columnName}" ->> '${l}'`);
1418
1434
  return;
1419
1435
  }
1420
1436
  kr(e, t, n, r, a);
1421
- }, pe = "_", Kr = {
1437
+ }, te = "_", Kr = {
1422
1438
  "=": "=",
1423
1439
  "!=": "!=",
1424
1440
  ">": ">",
@@ -1438,10 +1454,10 @@ const Sn = (e, t) => {
1438
1454
  }, Jr = (e, t) => {
1439
1455
  if (e?.length)
1440
1456
  return e.map((n) => {
1441
- const r = Ln(n.field, t);
1442
- return `${pe}."${r}" ${n.sort.toUpperCase()}`;
1457
+ const r = vn(n.field, t);
1458
+ return `${te}."${r}" ${n.sort.toUpperCase()}`;
1443
1459
  }).join(", ");
1444
- }, Yr = (e) => Kr[e] || e, Qr = (e) => e && typeof e == "object" && "rules" in e && Array.isArray(e.rules), Ln = (e, t) => {
1460
+ }, Yr = (e) => Kr[e] || e, Qr = (e) => e && typeof e == "object" && "rules" in e && Array.isArray(e.rules), vn = (e, t) => {
1445
1461
  if (t && !e.includes(".")) {
1446
1462
  const n = t.propertyMap.get(e);
1447
1463
  if (n)
@@ -1451,96 +1467,97 @@ const Sn = (e, t) => {
1451
1467
  return s[a];
1452
1468
  }
1453
1469
  return e;
1454
- }, Xr = (e, t, n) => {
1470
+ }, Xr = (e, t, n, r) => {
1455
1471
  if (t) return t;
1456
1472
  if (!e.includes(".")) {
1457
- const o = Ln(e, n);
1458
- return o.toLowerCase() !== o ? `"${o}"` : o;
1473
+ const c = vn(e, n), l = r ? `${te}.` : "";
1474
+ return c.toLowerCase() !== c ? `${l}"${c}"` : `${l}${c}`;
1459
1475
  }
1460
- const r = e.split("."), s = r[0], a = n?.propertyMap.get(s);
1461
- if (a && (a.type === N.json || a.type === N.keyValue) && r.length === 2)
1462
- return `"${a.columnName}" ->> '${r[1]}'`;
1476
+ const s = e.split("."), a = s[0], o = n?.propertyMap.get(a);
1477
+ if (o && (o.type === _.json || o.type === _.keyValue) && s.length === 2)
1478
+ return `"${o.columnName}" ->> '${s[1]}'`;
1463
1479
  const i = e.lastIndexOf(".");
1464
1480
  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;
1467
- if (c === "null" || c === "notNull")
1468
- return c === "null" ? `${i} IS NULL` : `${i} IS NOT NULL`;
1469
- if (o === null)
1470
- return c === "=" ? `${i} IS NULL` : c === "!=" ? `${i} IS NOT NULL` : "";
1471
- let u = s;
1472
- a && s.includes(".") && (u = s.split(".").pop() || s);
1473
- const l = r?.propertyMap.get(u.split(".")[0]);
1474
- if (l && (l.type === N.json || l.type === N.keyValue)) {
1475
- if (c === "contains" && typeof o == "object" && !Array.isArray(o))
1476
- return t.push(JSON.stringify(o)), `${i} @> $${t.length}::jsonb`;
1477
- if (c === "notContains" && typeof o == "object" && !Array.isArray(o))
1478
- return t.push(JSON.stringify(o)), `NOT (${i} @> $${t.length}::jsonb)`;
1479
- }
1480
- if (l && (l.type === N.stringArray || l.type === N.numberArray) && (c === "in" || c === "notIn")) {
1481
- if (!Array.isArray(o)) return "";
1482
- t.push(JSON.stringify(o));
1483
- const f = `${i} @> $${t.length}::jsonb`;
1484
- return c === "notIn" ? `NOT ${f}` : f;
1485
- }
1486
- if (c === "in" || c === "notIn")
1487
- return Array.isArray(o) ? o.length === 0 ? c === "in" ? "1=0" : "1=1" : (t.push(o), `${i} ${c === "in" ? "= ANY" : "!= ALL"}($${t.length})`) : "";
1488
- if (c === "between" || c === "notBetween")
1489
- 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
- if (["contains", "notContains", "startsWith", "notStartsWith", "endsWith", "notEndsWith"].includes(c)) {
1481
+ }, zr = (e, t, n = /* @__PURE__ */ new Map(), r, s) => {
1482
+ const a = String(e.field), o = n.get(a), i = Xr(a, o, r, s), c = e.value, l = e.operator;
1483
+ if (l === "null" || l === "notNull")
1484
+ return l === "null" ? `${i} IS NULL` : `${i} IS NOT NULL`;
1485
+ if (c === null)
1486
+ return l === "=" ? `${i} IS NULL` : l === "!=" ? `${i} IS NOT NULL` : "";
1487
+ let u = a;
1488
+ o && a.includes(".") && (u = a.split(".").pop() || a);
1489
+ const h = r?.propertyMap.get(u.split(".")[0]);
1490
+ if (h && (h.type === _.json || h.type === _.keyValue)) {
1491
+ if (l === "contains" && typeof c == "object" && !Array.isArray(c))
1492
+ return t.push(JSON.stringify(c)), `${i} @> $${t.length}::jsonb`;
1493
+ if (l === "notContains" && typeof c == "object" && !Array.isArray(c))
1494
+ return t.push(JSON.stringify(c)), `NOT (${i} @> $${t.length}::jsonb)`;
1495
+ }
1496
+ if (h && (h.type === _.stringArray || h.type === _.numberArray) && (l === "in" || l === "notIn")) {
1497
+ if (!Array.isArray(c)) return "";
1498
+ const f = h.type === _.stringArray ? "text[]" : "numeric[]";
1499
+ t.push(c);
1500
+ const E = `${i} @> $${t.length}::${f}`;
1501
+ return l === "notIn" ? `NOT ${E}` : E;
1502
+ }
1503
+ if (l === "in" || l === "notIn")
1504
+ return Array.isArray(c) ? c.length === 0 ? l === "in" ? "1=0" : "1=1" : (t.push(c), `${i} ${l === "in" ? "= ANY" : "!= ALL"}($${t.length})`) : "";
1505
+ if (l === "between" || l === "notBetween")
1506
+ return !Array.isArray(c) || c.length !== 2 ? "" : (t.push(c[0], c[1]), `${i} ${l === "between" ? "BETWEEN" : "NOT BETWEEN"} $${t.length - 1} AND $${t.length}`);
1507
+ if (["contains", "notContains", "startsWith", "notStartsWith", "endsWith", "notEndsWith"].includes(l)) {
1491
1508
  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}`;
1495
- }
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}`;
1498
- }, we = (e, t, n = /* @__PURE__ */ new Map(), r) => {
1499
- const s = e.rules.map(
1500
- (i) => Qr(i) ? we(i, t, n, r) : zr(i, t, n, r)
1509
+ l === "contains" || l === "notContains" ? f = `%${c}%` : l === "startsWith" || l === "notStartsWith" ? f = `${c}%` : (l === "endsWith" || l === "notEndsWith") && (f = `%${c}`), t.push(f);
1510
+ const E = l.startsWith("not") ? "NOT LIKE" : "LIKE";
1511
+ return `${i} ${E} $${t.length}`;
1512
+ }
1513
+ const p = Yr(l);
1514
+ return t.push(c), h && h.type === _.uuid ? `${i}::uuid ${p} $${t.length}::uuid` : `${i} ${p} $${t.length}`;
1515
+ }, Ae = (e, t, n = /* @__PURE__ */ new Map(), r, s) => {
1516
+ const a = e.rules.map(
1517
+ (i) => Qr(i) ? Ae(i, t, n, r, s) : zr(i, t, n, r, s)
1501
1518
  ).filter(Boolean);
1502
- if (!s.length) return "";
1503
- if (s.length === 1) return s[0];
1504
- const a = e.combinator.toUpperCase();
1505
- return `(${s.join(` ${a} `)})`;
1519
+ if (!a.length) return "";
1520
+ if (a.length === 1) return a[0];
1521
+ const o = e.combinator.toUpperCase();
1522
+ return `(${a.join(` ${o} `)})`;
1506
1523
  }, Zr = (e, t) => {
1507
- let n = `SELECT ${pe}.* FROM ${e.tableName} AS ${pe}`;
1508
- 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;
1524
+ let r = `SELECT ${e.join ? "DISTINCT " : ""}${te}.* FROM ${e.tableName} AS ${te}`;
1525
+ return e.join && (r += ` ${e.join}`), e.where && (r += ` WHERE ${e.where}`), e.orderBy && (r += ` ORDER BY ${e.orderBy}`), e.limit !== void 0 && (t.push(e.limit), r += ` LIMIT $${t.length}`), e.offset !== void 0 && e.offset > 0 && (t.push(e.offset), r += ` OFFSET $${t.length}`), r;
1509
1526
  }, ea = (e) => {
1510
- let t = `SELECT COUNT(*) as count FROM ${e.tableName} AS ${pe}`;
1511
- return e.join && (t += ` ${e.join}`), e.where && (t += ` WHERE ${e.where}`), t;
1512
- }, 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;
1527
+ let n = `SELECT ${e.join ? `COUNT(DISTINCT ${te}.id)` : "COUNT(*)"} as count FROM ${e.tableName} AS ${te}`;
1528
+ return e.join && (n += ` ${e.join}`), e.where && (n += ` WHERE ${e.where}`), n;
1529
+ }, ye = (e, t, n) => {
1530
+ const r = P(t), s = [], { joinSQL: a, fieldAliasMap: o } = n.where ? Ln(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, i = !!a, c = n.where ? Ae(n.where, s, o, t, i) : void 0, l = Jr(n.orderBy, t), u = "limit" in n ? n.limit : void 0, h = "offset" in n ? n.offset : void 0;
1514
1531
  return { sql: Zr(
1515
1532
  {
1516
1533
  tableName: r,
1517
- where: o,
1534
+ where: c,
1518
1535
  join: a,
1519
- orderBy: c,
1536
+ orderBy: l,
1520
1537
  limit: u,
1521
- offset: l
1538
+ offset: h
1522
1539
  },
1523
1540
  s
1524
1541
  ), params: s };
1525
1542
  }, ta = (e, t, n) => {
1526
1543
  if (n.groupBy)
1527
1544
  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;
1545
+ const r = P(t), s = [], { joinSQL: a, fieldAliasMap: o } = n.where ? Ln(e, t, n.where) : { joinSQL: "", fieldAliasMap: /* @__PURE__ */ new Map() }, i = !!a, c = n.where ? Ae(n.where, s, o, t, i) : void 0;
1529
1546
  return { sql: ea({
1530
1547
  tableName: r,
1531
- where: o,
1548
+ where: c,
1532
1549
  join: a
1533
1550
  }), params: s };
1534
1551
  }, na = (e, t) => {
1535
- const n = P(e), r = t.map((a, i) => `$${i + 1}`).join(", ");
1552
+ const n = P(e), r = t.map((a, o) => `$${o + 1}`).join(", ");
1536
1553
  return {
1537
1554
  sql: `SELECT * FROM ${n} WHERE id IN (${r})`,
1538
1555
  params: t
1539
1556
  };
1540
1557
  };
1541
- class sa extends Fn {
1558
+ class sa extends Bn {
1542
1559
  constructor(t, n) {
1543
- super(t.rxdb, n), this.adapter = t, this.metadata = D(n);
1560
+ super(t.rxdb, n), this.adapter = t, this.metadata = C(n);
1544
1561
  }
1545
1562
  metadata;
1546
1563
  /**
@@ -1557,11 +1574,11 @@ class sa extends Fn {
1557
1574
  }
1558
1575
  addQueryCache(t, n = !0) {
1559
1576
  return t.rows.map((r) => {
1560
- const s = Z(this.metadata, r), a = s.id;
1561
- let i;
1562
- super.hasEntityRef(a) ? (i = super.getEntityRef(a), n && super.updateEntity(i, s)) : i = this.createEntityRef(s);
1563
- const o = J(i);
1564
- return o.local = !0, o.modified = !1, i;
1577
+ const s = ee(this.metadata, r), a = s.id;
1578
+ let o;
1579
+ super.hasEntityRef(a) ? (o = super.getEntityRef(a), n && super.updateEntity(o, s)) : o = this.createEntityRef(s);
1580
+ const i = J(o);
1581
+ return i.local = !0, i.modified = !1, o;
1565
1582
  });
1566
1583
  }
1567
1584
  }
@@ -1580,11 +1597,11 @@ class Mn extends sa {
1580
1597
  return (await this.find({ ...t, limit: 1, offset: 0 }))[0];
1581
1598
  }
1582
1599
  async find(t) {
1583
- const { sql: n, params: r } = Ee(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1600
+ const { sql: n, params: r } = ye(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1584
1601
  return this.addQueryCache(s);
1585
1602
  }
1586
1603
  async findAll(t) {
1587
- const { sql: n, params: r } = Ee(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1604
+ const { sql: n, params: r } = ye(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1588
1605
  return this.addQueryCache(s);
1589
1606
  }
1590
1607
  async count(t) {
@@ -1597,164 +1614,159 @@ class Mn extends sa {
1597
1614
  }
1598
1615
  async update(t, n) {
1599
1616
  Object.assign(t, n);
1600
- const { sql: r, params: s } = ze(this.metadata, t, n, this.rxdb.context);
1601
- return await this.adapter.query(r, s), t;
1617
+ const { sql: r, params: s } = Ze(this.metadata, t, n, this.rxdb.context), a = await this.adapter.query(r, s);
1618
+ return this.addQueryCache(a), t;
1602
1619
  }
1603
1620
  async remove(t) {
1604
- const { sql: n, params: r } = Br(this.metadata, t);
1621
+ const { sql: n, params: r } = Fr(this.metadata, t);
1605
1622
  return await this.adapter.query(n, r), t;
1606
1623
  }
1607
1624
  }
1608
- const Ne = (e, t, n) => {
1609
- const { isCount: r, isFindDescendants: s, entityId: a, where: i } = n, o = !a, c = P(t);
1610
- 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}"`);
1625
+ const $e = (e, t, n) => {
1626
+ const { isCount: r, isFindDescendants: s, entityId: a, where: o } = n, i = !a, c = P(t);
1627
+ let l = "";
1628
+ const h = [`c.level < ${n.level || 0}`], p = [];
1629
+ if (i || p.push(a), o) {
1630
+ const b = /* @__PURE__ */ new Map(), R = (y) => {
1631
+ if ("rules" in y)
1632
+ return { ...y, rules: y.rules.map(R) };
1633
+ if (y.field && typeof y.field == "string" && y.field.startsWith("children.")) {
1634
+ const g = y.field.substring(9), I = t.propertyMap.get(g)?.columnName ?? g;
1635
+ b.set(y.field, `children."${I}"`);
1619
1636
  }
1620
- return m;
1637
+ return y;
1621
1638
  };
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"), {
1639
+ R(o);
1640
+ const m = Ae(o, p, b, t);
1641
+ m && h.push(m);
1642
+ }
1643
+ const f = h.filter(Boolean).join(" AND ");
1644
+ f && (l = `WHERE ${f}`);
1645
+ let E = "*";
1646
+ return r && (i ? E = "count(*) AS count" : E = "(count(*) - 1) AS count"), {
1630
1647
  sql: `WITH RECURSIVE __children AS (
1631
1648
  SELECT *, 0 AS level
1632
1649
  FROM ${c}
1633
- WHERE ${o ? '"parentId" IS NULL' : "id = $1"}
1650
+ WHERE ${i ? '"parentId" IS NULL' : "id = $1"}
1634
1651
  UNION ALL
1635
1652
  SELECT children.*, c.level + 1 AS level
1636
1653
  FROM ${c} children
1637
1654
  JOIN __children c ON ${s ? 'children."parentId"::uuid = c.id::uuid' : 'children.id::uuid = c."parentId"::uuid'}
1638
- ${u}
1655
+ ${l}
1639
1656
  )
1640
1657
 
1641
- SELECT ${_} FROM __children${r ? "" : " ORDER BY level, id"};`,
1642
- params: f
1658
+ SELECT ${E} FROM __children${r ? "" : " ORDER BY level, id"};`,
1659
+ params: p
1643
1660
  };
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 });
1661
+ }, ra = (e, t, n) => $e(e, t, { ...n, isFindDescendants: !0 }), aa = (e, t, n) => $e(e, t, { ...n, isFindDescendants: !0, isCount: !0 }), ia = (e, t, n) => $e(e, t, { ...n, isFindDescendants: !1 }), oa = (e, t, n) => $e(e, t, { ...n, isFindDescendants: !1, isCount: !0 });
1645
1662
  class ca extends Mn {
1646
1663
  async findDescendants(t) {
1647
1664
  const { sql: n, params: r } = ra(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1648
- return !s.rows || s.rows.length === 0 ? [] : s.rows.map((i) => {
1649
- const o = Z(this.metadata, i);
1650
- return this.createEntityRef(o);
1665
+ return !s.rows || s.rows.length === 0 ? [] : s.rows.map((o) => {
1666
+ const i = ee(this.metadata, o);
1667
+ return this.createEntityRef(i);
1651
1668
  });
1652
1669
  }
1653
1670
  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?"];
1655
- return parseInt(String(i), 10) || 0;
1671
+ const { sql: n, params: r } = aa(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], o = a.count || a["?column?"];
1672
+ return parseInt(String(o), 10) || 0;
1656
1673
  }
1657
1674
  async findAncestors(t) {
1658
1675
  const { sql: n, params: r } = ia(this.adapter, this.metadata, t), s = await this.adapter.query(n, r);
1659
- return !s.rows || s.rows.length === 0 ? [] : s.rows.map((i) => {
1660
- const o = Z(this.metadata, i);
1661
- return this.createEntityRef(o);
1676
+ return !s.rows || s.rows.length === 0 ? [] : s.rows.map((o) => {
1677
+ const i = ee(this.metadata, o);
1678
+ return this.createEntityRef(i);
1662
1679
  });
1663
1680
  }
1664
1681
  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?"];
1666
- return parseInt(String(i), 10) || 0;
1682
+ const { sql: n, params: r } = oa(this.adapter, this.metadata, t), a = (await this.adapter.query(n, r)).rows[0], o = a.count || a["?column?"];
1683
+ return parseInt(String(o), 10) || 0;
1667
1684
  }
1668
1685
  }
1669
1686
  const la = async (e, t) => {
1670
1687
  const n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Date();
1671
1688
  for (const [s, a] of t.create.entries()) {
1672
- const i = Array.from(a);
1673
- i.forEach((_) => n.add(_));
1674
- const o = D(s), c = ue(o, i, e.rxdb.context);
1689
+ const o = Array.from(a);
1690
+ o.forEach((E) => n.add(E));
1691
+ const i = C(s), c = de(i, o, e.rxdb.context);
1675
1692
  await e.query(c);
1676
- const u = i.map((_) => _.id), { sql: l, params: d } = Ee(e, o, {
1677
- 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;
1693
+ const l = o.map((E) => E.id), { sql: u, params: h } = ye(e, i, {
1694
+ where: { combinator: "and", rules: [{ field: "id", operator: "in", value: l }] }
1695
+ }), p = await e.query(u, h), f = e.getRepository(s);
1696
+ for (const E of p.rows) {
1697
+ const $ = ee(i, E), A = $.id;
1698
+ if (f.hasEntityRef(A)) {
1699
+ const b = f.getEntityRef(A);
1700
+ f.updateEntity(b, $);
1701
+ const R = J(b);
1702
+ R.local = !0, R.modified = !1;
1686
1703
  }
1687
1704
  }
1688
1705
  }
1689
1706
  for (const [s, a] of t.update.entries()) {
1690
- 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 || {}, {
1707
+ const o = Array.from(a);
1708
+ o.forEach((p) => n.add(p));
1709
+ const i = C(s), c = e.getRepository(s);
1710
+ for (const p of o) {
1711
+ const f = J(p), { sql: E, params: $ } = Ze(i, p, f.patch || {}, {
1699
1712
  ...e.rxdb.context,
1700
1713
  returning: !1,
1701
- // 后续用 SELECT 获取
1702
1714
  updatedAt: r
1703
1715
  });
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
- }
1716
+ await e.query(E, $);
1717
+ }
1718
+ const l = o.map((p) => p.id), u = ye(e, i, {
1719
+ where: { combinator: "and", rules: [{ field: "id", operator: "in", value: l }] }
1720
+ }), h = await e.query(u.sql, u.params);
1721
+ for (const p of h.rows) {
1722
+ const f = ee(i, p), E = f.id;
1723
+ if (c.hasEntityRef(E)) {
1724
+ const $ = c.getEntityRef(E);
1725
+ c.updateEntity($, f);
1726
+ const A = J($);
1727
+ A.local = !0, A.modified = !1;
1716
1728
  }
1717
1729
  }
1718
1730
  }
1719
1731
  for (const [, s] of t.remove.entries()) {
1720
- const a = Array.from(s), i = D(a[0]?.constructor);
1732
+ const a = Array.from(s), o = C(a[0]?.constructor);
1721
1733
  if (a.length > 0) {
1722
- const o = Sn(i, a);
1723
- await e.query(o);
1734
+ const i = Sn(o, a);
1735
+ await e.query(i);
1724
1736
  }
1725
- for (const o of a) {
1726
- n.add(o);
1727
- const c = J(o);
1728
- c.origin = structuredClone({ ...o }), c.modified = !1, c.removed = !0, c.local = !1;
1737
+ for (const i of a) {
1738
+ n.add(i);
1739
+ const c = J(i);
1740
+ c.origin = structuredClone({ ...i }), c.modified = !1, c.removed = !0, c.local = !1;
1729
1741
  }
1730
1742
  }
1731
1743
  return Array.from(n);
1732
1744
  }, ua = (e, t) => {
1733
1745
  const n = P(t);
1734
1746
  let r = `CREATE TABLE ${n} (`;
1735
- const s = [], a = [], i = [];
1747
+ const s = [], a = [], o = [];
1736
1748
  t.propertyMap.forEach((c) => {
1737
- let u = "";
1738
- u += `"${c.columnName}"`;
1739
- const l = Dt(c);
1740
- 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)}'`;
1749
+ let l = "";
1750
+ l += `"${c.columnName}"`;
1751
+ const u = Ct(c);
1752
+ if (c.primary ? c.type === _.integer ? l += " serial PRIMARY KEY" : l += ` ${u} PRIMARY KEY` : l += ` ${u}`, Reflect.get(c, "default") !== void 0) {
1753
+ let h = c.default;
1754
+ Ot(c.default) && (h = c.default()), Hn(h) ? ["CURRENT_TIMESTAMP", "now()"].includes(h) ? l += " DEFAULT now()" : l += ` DEFAULT '${h}'` : h instanceof Date ? l += ` DEFAULT '${h.toISOString()}'` : typeof h == "boolean" || typeof h == "number" ? l += ` DEFAULT ${String(h)}` : l += ` DEFAULT '${String(h)}'`;
1743
1755
  }
1744
- if (c.nullable || (u += " NOT NULL"), c.unique && s.push(
1745
- `CREATE UNIQUE INDEX "${Ct(t, c)}" on ${n} ("${c.columnName}" ${Xn(c)});`
1746
- ), 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}))`);
1756
+ if (c.nullable || (l += " NOT NULL"), c.unique && s.push(
1757
+ `CREATE UNIQUE INDEX "${Lt(t, c)}" on ${n} ("${c.columnName}" ${Xn(c)});`
1758
+ ), c.type === _.enum) {
1759
+ const h = c;
1760
+ if (h.enum && h.enum.length > 0) {
1761
+ const p = h.enum.map((f) => `'${String(f).replace(/'/g, "''")}'`).join(", ");
1762
+ a.push(`CHECK ("${c.columnName}" IN (${p}))`);
1751
1763
  }
1752
1764
  }
1753
- i.push(u);
1765
+ o.push(l);
1754
1766
  });
1755
- const o = [...i, ...a];
1756
- if (o.length)
1757
- r += o.map((c) => `
1767
+ const i = [...o, ...a];
1768
+ if (i.length)
1769
+ r += i.map((c) => `
1758
1770
  ${c}`).join(","), r += `
1759
1771
  );`;
1760
1772
  else
@@ -1766,55 +1778,53 @@ ${c}`).join(","), r += `
1766
1778
  let n = "";
1767
1779
  const r = P(t);
1768
1780
  return t.indexes && t.indexes.length > 0 && t.indexes.forEach((s) => {
1769
- const a = `idx_${t.tableName}_${s.name}`, i = s.properties?.map((c) => `"${c}"`).join(", ") || `"${s.name}"`, o = s.unique ? "UNIQUE " : "";
1781
+ const a = `idx_${t.tableName}_${s.name}`, o = s.properties?.map((c) => `"${c}"`).join(", ") || `"${s.name}"`, i = s.unique ? "UNIQUE " : "";
1770
1782
  n += `
1771
- CREATE ${o}INDEX "${a}" ON ${r}(${i});`;
1783
+ CREATE ${i}INDEX "${a}" ON ${r}(${o});`;
1772
1784
  }), n;
1773
1785
  }, fa = (e, t) => {
1774
1786
  let n = "";
1775
1787
  const r = P(t);
1776
1788
  return Array.from(t.relationMap.values()).forEach((s) => {
1777
1789
  switch (s.kind) {
1778
- case F.ONE_TO_ONE:
1779
- case F.MANY_TO_ONE:
1790
+ case B.ONE_TO_ONE:
1791
+ case B.MANY_TO_ONE:
1780
1792
  {
1781
1793
  const a = s.columnName;
1782
- let i = "uuid";
1794
+ let o = "uuid";
1783
1795
  if (s.mappedEntity)
1784
1796
  try {
1785
- const c = e.rxdb.schemaManager.getEntityMetadata(
1797
+ const i = e.rxdb.schemaManager.getEntityMetadata(
1786
1798
  s.mappedEntity,
1787
1799
  s.mappedNamespace
1788
1800
  );
1789
- if (c) {
1790
- const u = Array.from(c.propertyMap.values()).find(
1801
+ if (i) {
1802
+ const c = Array.from(i.propertyMap.values()).find(
1791
1803
  (l) => l.primary
1792
1804
  );
1793
- u && (i = Dt(u));
1805
+ c && (o = Ct(c));
1794
1806
  }
1795
1807
  } catch {
1796
1808
  }
1797
1809
  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) {
1799
- const c = s;
1800
- let u = c.default;
1801
- It(c.default) && (u = c.default()), n += ` DEFAULT '${u}'`;
1810
+ ALTER TABLE ${r} ADD COLUMN "${a}" ${o}`, s.nullable || (n += " NOT NULL"), s.kind === B.MANY_TO_ONE && Reflect.get(s, "default") !== void 0) {
1811
+ const i = s;
1812
+ let c = i.default;
1813
+ Ot(i.default) && (c = i.default()), n += ` DEFAULT '${c}'`;
1802
1814
  }
1803
- n += ";";
1804
- const o = s.mappedEntity === t.name;
1805
- if (s.mappedEntity && !o) {
1806
- const c = e.rxdb.schemaManager.getEntityMetadata(
1815
+ if (n += ";", s.mappedEntity) {
1816
+ const i = e.rxdb.schemaManager.getEntityMetadata(
1807
1817
  s.mappedEntity,
1808
1818
  s.mappedNamespace
1809
- ), u = vt(
1810
- c?.tableName ?? s.mappedEntity,
1819
+ ), c = Dt(
1820
+ i?.tableName ?? s.mappedEntity,
1811
1821
  s.mappedNamespace || t.namespace
1812
1822
  ), l = `${r}_${a}_fk`.replace(/"/g, "");
1813
1823
  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 += ";";
1824
+ ALTER TABLE ${r} ADD CONSTRAINT "${l}" FOREIGN KEY ("${a}") REFERENCES ${c}(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
1825
  }
1816
- (s.unique || s.kind === F.ONE_TO_ONE) && (n += `
1817
- CREATE UNIQUE INDEX "${Ct(t, s)}" ON ${r}("${a}");`);
1826
+ (s.unique || s.kind === B.ONE_TO_ONE) && (n += `
1827
+ CREATE UNIQUE INDEX "${Lt(t, s)}" ON ${r}("${a}");`);
1818
1828
  }
1819
1829
  break;
1820
1830
  }
@@ -1890,7 +1900,7 @@ END $$;
1890
1900
  function Da(e) {
1891
1901
  return `DROP TRIGGER IF EXISTS "${`${e}_notify_trigger`}" ON "${e}";`;
1892
1902
  }
1893
- function pa(e = ["RxDBChange", "RxDBBranch", "RxDBMigration"]) {
1903
+ function pa(e = ["rxdb_change", "rxdb_branch", "rxdb_migration"]) {
1894
1904
  const t = [];
1895
1905
  t.push(da());
1896
1906
  for (const n of e)
@@ -1899,23 +1909,23 @@ function pa(e = ["RxDBChange", "RxDBBranch", "RxDBMigration"]) {
1899
1909
 
1900
1910
  `);
1901
1911
  }
1902
- function $e(e, t = {}) {
1903
- const n = P(e), r = D(ie), s = P(r), {
1912
+ function be(e, t = {}) {
1913
+ const n = P(e), r = C(le), s = P(r), {
1904
1914
  propertyMap: a,
1905
- name: i,
1906
- tableName: o,
1915
+ name: o,
1916
+ tableName: i,
1907
1917
  foreignKeyNames: c,
1908
- foreignKeyColumnNames: u,
1909
- 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 = `
1918
+ foreignKeyColumnNames: l,
1919
+ namespace: u
1920
+ } = e, { branchId: h, transactionId: p } = t, f = `"${i}_change_trigger"`, E = [];
1921
+ for (const [T, N] of a)
1922
+ T !== "id" && E.push({ jsName: T, dbColumn: N.columnName });
1923
+ const $ = l || c;
1924
+ for (let T = 0; T < c.length; T++)
1925
+ c[T] !== "id" && E.push({ jsName: c[T], dbColumn: $[T] });
1926
+ const A = 'type, namespace, entity, "branchId", "transactionId", "entityId", "inversePatch", patch', b = p ? `'${p}'` : "NULL", R = h || "main", m = `"${u}"."${i}_change_trigger_fn"`, y = `'${u}','${o}','${R}',${b}`, g = `
1917
1927
  -- 创建或替换触发器函数
1918
- CREATE OR REPLACE FUNCTION ${E}()
1928
+ CREATE OR REPLACE FUNCTION ${m}()
1919
1929
  RETURNS TRIGGER AS $$
1920
1930
  DECLARE
1921
1931
  old_values JSONB;
@@ -1923,32 +1933,34 @@ DECLARE
1923
1933
  BEGIN
1924
1934
  -- INSERT 操作
1925
1935
  IF (TG_OP = 'INSERT') THEN
1926
- INSERT INTO ${s} (${$})
1936
+ INSERT INTO ${s} (${A})
1927
1937
  VALUES (
1928
1938
  'INSERT',
1929
- ${m},
1939
+ ${y},
1930
1940
  NEW.id,
1931
1941
  NULL,
1932
- jsonb_build_object(${_.map((y) => `'${y.jsName}', NEW."${y.dbColumn}"`).join(", ")})
1942
+ jsonb_build_object(${E.map((T) => `'${T.jsName}', NEW."${T.dbColumn}"`).join(", ")})
1933
1943
  );
1934
1944
  RETURN NEW;
1935
1945
 
1936
1946
  -- UPDATE 操作
1937
1947
  ELSIF (TG_OP = 'UPDATE') THEN
1938
1948
  -- 只在字段真正变更时记录
1939
- IF (${_.map((y) => `OLD."${y.dbColumn}" IS DISTINCT FROM NEW."${y.dbColumn}"`).join(" OR ")}) THEN
1940
- -- 构建变更前的值 (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(", ")});
1942
- old_values := jsonb_strip_nulls(old_values);
1949
+ IF (${E.map((T) => `OLD."${T.dbColumn}" IS DISTINCT FROM NEW."${T.dbColumn}"`).join(" OR ")}) THEN
1950
+ -- 构建变更前的值 (inversePatch - 只包含变更的字段,保留 NULL 值)
1951
+ old_values := '{}'::jsonb;
1952
+ ${E.map((T) => `IF OLD."${T.dbColumn}" IS DISTINCT FROM NEW."${T.dbColumn}" THEN old_values := old_values || jsonb_build_object('${T.jsName}', to_jsonb(OLD."${T.dbColumn}")); END IF;`).join(`
1953
+ `)}
1943
1954
 
1944
- -- 构建变更后的值 (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(", ")});
1946
- new_values := jsonb_strip_nulls(new_values);
1955
+ -- 构建变更后的值 (patch - 只包含变更的字段,保留 NULL 值)
1956
+ new_values := '{}'::jsonb;
1957
+ ${E.map((T) => `IF OLD."${T.dbColumn}" IS DISTINCT FROM NEW."${T.dbColumn}" THEN new_values := new_values || jsonb_build_object('${T.jsName}', to_jsonb(NEW."${T.dbColumn}")); END IF;`).join(`
1958
+ `)}
1947
1959
 
1948
- INSERT INTO ${s} (${$})
1960
+ INSERT INTO ${s} (${A})
1949
1961
  VALUES (
1950
1962
  'UPDATE',
1951
- ${m},
1963
+ ${y},
1952
1964
  NEW.id,
1953
1965
  old_values,
1954
1966
  new_values
@@ -1958,12 +1970,12 @@ BEGIN
1958
1970
 
1959
1971
  -- DELETE 操作
1960
1972
  ELSIF (TG_OP = 'DELETE') THEN
1961
- INSERT INTO ${s} (${$})
1973
+ INSERT INTO ${s} (${A})
1962
1974
  VALUES (
1963
1975
  'DELETE',
1964
- ${m},
1976
+ ${y},
1965
1977
  OLD.id,
1966
- jsonb_build_object(${_.map((y) => `'${y.jsName}', OLD."${y.dbColumn}"`).join(", ")}),
1978
+ jsonb_build_object(${E.map((T) => `'${T.jsName}', OLD."${T.dbColumn}"`).join(", ")}),
1967
1979
  NULL
1968
1980
  );
1969
1981
  RETURN OLD;
@@ -1971,15 +1983,15 @@ BEGIN
1971
1983
 
1972
1984
  RETURN NULL;
1973
1985
  END;
1974
- $$ LANGUAGE plpgsql;`, R = `
1986
+ $$ LANGUAGE plpgsql;`, S = `
1975
1987
  -- 删除已存在的触发器
1976
- DROP TRIGGER IF EXISTS ${p} ON ${n}`, I = `
1988
+ DROP TRIGGER IF EXISTS ${f} ON ${n}`, I = `
1977
1989
  -- 创建触发器 (监听 INSERT, UPDATE, DELETE)
1978
- CREATE TRIGGER ${p}
1990
+ CREATE TRIGGER ${f}
1979
1991
  AFTER INSERT OR UPDATE OR DELETE ON ${n}
1980
1992
  FOR EACH ROW
1981
- EXECUTE FUNCTION ${E}()`;
1982
- return [g, R, I].join(`
1993
+ EXECUTE FUNCTION ${m}()`;
1994
+ return [g, S, I].join(`
1983
1995
  ---STATEMENT_SEPARATOR---
1984
1996
  `);
1985
1997
  }
@@ -1993,71 +2005,71 @@ const Ea = async (e, t, n) => {
1993
2005
  limit: 1
1994
2006
  })).length > 0)
1995
2007
  throw new x(`Branch ID (${t}) already exists`);
1996
- let i;
2008
+ let o;
1997
2009
  if (n) {
1998
2010
  const c = await s.get(n);
1999
2011
  if (!c)
2000
2012
  throw new x(`Change ID (${n}) not found`);
2001
2013
  if (!c.branchId)
2002
2014
  throw new x(`Change record (${n}) has no branchId`);
2003
- i = await r.get(c.branchId);
2015
+ o = await r.get(c.branchId);
2004
2016
  } else
2005
- i = (await r.find({
2017
+ o = (await r.find({
2006
2018
  where: {
2007
2019
  combinator: "and",
2008
2020
  rules: [{ field: "activated", operator: "=", value: !0 }]
2009
2021
  },
2010
2022
  limit: 1
2011
2023
  }))[0];
2012
- if (!i)
2024
+ if (!o)
2013
2025
  throw new x("Source branch not found");
2014
2026
  n || (n = (await s.find({
2015
2027
  where: {
2016
2028
  combinator: "and",
2017
2029
  rules: [
2018
- { field: "branchId", operator: "=", value: i.id },
2030
+ { field: "branchId", operator: "=", value: o.id },
2019
2031
  { field: "revertChangeId", operator: "=", value: null }
2020
2032
  ]
2021
2033
  },
2022
2034
  orderBy: [{ field: "id", sort: "desc" }],
2023
2035
  limit: 1
2024
2036
  }))[0]?.id ?? null);
2025
- const o = new ne();
2026
- 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);
2037
+ const i = new re();
2038
+ return i.id = t, i.activated = !1, i.local = !0, i.remote = !1, i.fromChangeId = n ?? null, i.parentId = o.id, await r.create(i);
2027
2039
  };
2028
2040
  function ma(e) {
2029
- 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
- return [i, o].join(`
2041
+ const t = P(e), { tableName: n, namespace: r } = e, s = `"${n}_change_trigger"`, a = `"${r}"."${n}_change_trigger_fn"`, o = `DROP TRIGGER IF EXISTS ${s} ON ${t}`, i = `DROP FUNCTION IF EXISTS ${a}() CASCADE`;
2042
+ return [o, i].join(`
2031
2043
  ---STATEMENT_SEPARATOR---
2032
2044
  `);
2033
2045
  }
2034
2046
  function Un(e) {
2035
2047
  const t = [];
2036
2048
  return e.rxdb.config.entities.forEach((n) => {
2037
- const r = D(n);
2049
+ const r = C(n);
2038
2050
  r.log !== !1 && t.push(ma(r));
2039
2051
  }), t.join(`
2040
2052
  ---STATEMENT_SEPARATOR---
2041
2053
  `);
2042
2054
  }
2043
- const He = (e, t, n, r = !1) => {
2055
+ const Ve = (e, t, n, r = !1) => {
2044
2056
  if (!n.rows || n.rows.length === 0)
2045
2057
  return [];
2046
- const s = D(t), a = [], i = e.rxdb.entityManager;
2047
- for (const o of n.rows) {
2048
- const c = Z(s, o), u = c.id;
2049
- let l;
2050
- if (i.hasEntityRef(t, u)) {
2051
- if (l = i.getEntityRef(t, u), s.computedPropertyMap.forEach((p, _) => {
2052
- _ in c && (l[_] = c[_]);
2058
+ const s = C(t), a = [], o = e.rxdb.entityManager;
2059
+ for (const i of n.rows) {
2060
+ const c = ee(s, i), l = c.id;
2061
+ let u;
2062
+ if (o.hasEntityRef(t, l)) {
2063
+ if (u = o.getEntityRef(t, l), s.computedPropertyMap.forEach((f, E) => {
2064
+ E in c && (u[E] = c[E]);
2053
2065
  }), r) {
2054
- const p = J(l);
2055
- p.origin = { ...c }, Object.assign(l, c), p.local = !0, p.modified = !1;
2066
+ const f = J(u);
2067
+ f.origin = { ...c }, Object.assign(u, c), f.local = !0, f.modified = !1;
2056
2068
  }
2057
2069
  } else
2058
- l = i.createEntityRef(t, c);
2059
- const f = J(l);
2060
- f.local = !0, f.modified = !1, a.push(l);
2070
+ u = o.createEntityRef(t, c);
2071
+ const p = J(u);
2072
+ p.local = !0, p.modified = !1, a.push(u);
2061
2073
  }
2062
2074
  return a;
2063
2075
  }, ya = (e, t, n) => {
@@ -2068,92 +2080,98 @@ const He = (e, t, n, r = !1) => {
2068
2080
  a.local = !1, a.removed = !0, a.modified = !1;
2069
2081
  }
2070
2082
  }
2083
+ }, X = (e, t) => {
2084
+ if (!e) return null;
2085
+ const n = { ...e };
2086
+ for (const r of Object.keys(n)) {
2087
+ const s = t.propertyMap.get(r);
2088
+ s && (n[r] = ae(n[r], s));
2089
+ }
2090
+ return n;
2071
2091
  }, jn = (e, t) => {
2072
- 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
2092
+ const { deletes: n, inserts: r, updates: s } = t, a = { deletes: [], inserts: [], updates: [] }, o = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
2093
+ for (const [p, f] of n.entries()) {
2094
+ const [E, $, A] = Re(p), b = `${E}:${$}`, R = o.get(b);
2095
+ R ? R.add(A) : o.set(b, /* @__PURE__ */ new Set([A]));
2096
+ let m = i.get(b);
2097
+ m || (m = /* @__PURE__ */ new Map(), i.set(b, m));
2098
+ const y = e.rxdb.schemaManager.getEntityMetadata($, E);
2099
+ m.set(A, {
2100
+ patch: y ? X(f.patch, y) : f.patch,
2101
+ inversePatch: y ? X(f.inversePatch, y) : f.inversePatch
2080
2102
  });
2081
2103
  }
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);`;
2104
+ for (const [p, f] of o) {
2105
+ const [E, $] = p.split(":"), A = e.rxdb.schemaManager.getEntityMetadata($, E), b = P(A), R = A.propertyMap.get("id").type === "integer", m = Array.from(f), y = R ? `DELETE FROM ${b} WHERE id = ANY($1::integer[]);` : `DELETE FROM ${b} WHERE id = ANY($1);`;
2084
2106
  a.deletes.push({
2085
- metadata: $,
2086
- ids: p,
2087
- sql: m,
2088
- params: [E],
2089
- changes: o.get(f)
2107
+ metadata: A,
2108
+ ids: f,
2109
+ sql: y,
2110
+ params: [m],
2111
+ changes: i.get(p)
2090
2112
  });
2091
2113
  }
2092
- 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
2114
+ const c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
2115
+ for (const [p, f] of r.entries()) {
2116
+ const [E, $, A] = Re(p), b = `${E}:${$}`, R = c.get(b), m = { ...f.patch, id: A };
2117
+ R ? R.push(m) : c.set(b, [m]);
2118
+ let y = l.get(b);
2119
+ y || (y = /* @__PURE__ */ new Map(), l.set(b, y));
2120
+ const g = e.rxdb.schemaManager.getEntityMetadata($, E);
2121
+ y.set(A, {
2122
+ patch: g ? X(f.patch, g) : f.patch,
2123
+ inversePatch: g ? X(f.inversePatch, g) : f.inversePatch
2100
2124
  });
2101
2125
  }
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));
2126
+ for (const [p, f] of c) {
2127
+ const [E, $] = p.split(":"), A = e.rxdb.schemaManager.getEntityMetadata($, E), b = [];
2128
+ f.forEach((m) => {
2129
+ for (const [I, T] of A.propertyMap)
2130
+ m[I] === void 0 && T.default !== void 0 && (typeof T.default == "function" ? m[I] = T.default() : m[I] = T.default);
2131
+ const { sql: y, params: g } = In(A, m, { returning: !1 }), S = y.replace(";", ga(A));
2132
+ b.push(st(S, g));
2109
2133
  });
2110
- const b = A.join("---STATEMENT_SEPARATOR---");
2134
+ const R = b.join("---STATEMENT_SEPARATOR---");
2111
2135
  a.inserts.push({
2112
- metadata: $,
2113
- ids: new Set(p.filter((E) => E != null).map((E) => E.id)),
2114
- sql: b,
2136
+ metadata: A,
2137
+ ids: new Set(f.filter((m) => m != null).map((m) => m.id)),
2138
+ sql: R,
2115
2139
  params: [],
2116
2140
  // 已经内联到 SQL 中
2117
- changes: u.get(f)
2141
+ changes: l.get(p)
2118
2142
  });
2119
2143
  }
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
2144
+ const u = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map();
2145
+ for (const [p, f] of s.entries()) {
2146
+ const [E, $, A] = Re(p), b = `${E}:${$}`, R = u.get(b), m = { ...f.patch, id: A };
2147
+ R ? R.push(m) : u.set(b, [m]);
2148
+ let y = h.get(b);
2149
+ y || (y = /* @__PURE__ */ new Map(), h.set(b, y));
2150
+ const g = e.rxdb.schemaManager.getEntityMetadata($, E);
2151
+ y.set(A, {
2152
+ patch: g ? X(f.patch, g) : f.patch,
2153
+ inversePatch: g ? X(f.inversePatch, g) : f.inversePatch
2136
2154
  });
2137
2155
  }
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,
2156
+ for (const [p, f] of u) {
2157
+ const [E, $] = p.split(":"), A = e.rxdb.schemaManager.getEntityMetadata($, E), b = [];
2158
+ f.forEach((m) => {
2159
+ let y;
2160
+ A.propertyMap.has("updatedAt") && (y = m.updatedAt);
2161
+ const { id: g, ...S } = m, { sql: I, params: T } = Ze(A, { id: g }, S, {
2162
+ updatedAt: y,
2145
2163
  returning: !1
2146
2164
  });
2147
- A.push(nt(I, y));
2165
+ b.push(st(I, T));
2148
2166
  });
2149
- const b = A.join("---STATEMENT_SEPARATOR---");
2167
+ const R = b.join("---STATEMENT_SEPARATOR---");
2150
2168
  a.updates.push({
2151
- metadata: $,
2152
- ids: new Set(p.filter((E) => E != null).map((E) => E.id)),
2153
- sql: b,
2169
+ metadata: A,
2170
+ ids: new Set(f.filter((m) => m != null).map((m) => m.id)),
2171
+ sql: R,
2154
2172
  params: [],
2155
2173
  // 已经内联到 SQL 中
2156
- changes: d.get(f)
2174
+ changes: h.get(p)
2157
2175
  });
2158
2176
  }
2159
2177
  return a;
@@ -2167,19 +2185,19 @@ function _a(e) {
2167
2185
  }
2168
2186
  const xn = (e, t) => {
2169
2187
  const n = [];
2170
- e.rxdb.config.entities.forEach((o) => {
2171
- const c = D(o);
2188
+ e.rxdb.config.entities.forEach((i) => {
2189
+ const c = C(i);
2172
2190
  if (c.log !== !1)
2173
2191
  try {
2174
- const u = $e(c, {
2192
+ const l = be(c, {
2175
2193
  branchId: t
2176
2194
  });
2177
- u.trim() && n.push(u);
2178
- } catch (u) {
2179
- console.warn(`Failed to generate trigger SQL for entity ${c.name}:`, u);
2195
+ l.trim() && n.push(l);
2196
+ } catch (l) {
2197
+ console.warn(`Failed to generate trigger SQL for entity ${c.name}:`, l);
2180
2198
  }
2181
2199
  });
2182
- const r = D(ne), s = P(r), a = t.replace(/'/g, "''"), i = `
2200
+ const r = C(re), s = P(r), a = t.replace(/'/g, "''"), o = `
2183
2201
  UPDATE ${s}
2184
2202
  SET
2185
2203
  activated = CASE
@@ -2192,7 +2210,7 @@ const xn = (e, t) => {
2192
2210
  END
2193
2211
  WHERE id = '${a}' OR activated = TRUE
2194
2212
  RETURNING *`;
2195
- return n.push(i), n.join(`
2213
+ return n.push(o), n.join(`
2196
2214
  ---STATEMENT_SEPARATOR---
2197
2215
  `);
2198
2216
  }, Ta = async (e, t) => {
@@ -2200,53 +2218,53 @@ const xn = (e, t) => {
2200
2218
  let a;
2201
2219
  try {
2202
2220
  await e.transaction(async () => {
2203
- const u = Un(e);
2204
- 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());
2221
+ const l = Un(e);
2222
+ if (l) {
2223
+ const u = l.split("---STATEMENT_SEPARATOR---").filter((h) => h.trim());
2224
+ for (const h of u)
2225
+ await e.query(h.trim());
2208
2226
  }
2209
2227
  if (s) {
2210
2228
  if (s.deletes.length)
2211
- for (const l of s.deletes)
2212
- l.params.length > 0 ? await e.query(l.sql, l.params) : await e.query(l.sql);
2229
+ for (const u of s.deletes)
2230
+ u.params.length > 0 ? await e.query(u.sql, u.params) : await e.query(u.sql);
2213
2231
  if (s.inserts.length)
2214
- for (const l of s.inserts)
2215
- l.successResults = await e.query(l.sql);
2232
+ for (const u of s.inserts)
2233
+ u.successResults = await e.query(u.sql);
2216
2234
  if (s.updates.length)
2217
- for (const l of s.updates)
2218
- l.successResults = await e.query(l.sql);
2235
+ for (const u of s.updates)
2236
+ u.successResults = await e.query(u.sql);
2219
2237
  }
2220
2238
  r?.updateRxDBChangeSequence !== void 0 && await e.setRxDBChangeSequence(r.updateRxDBChangeSequence);
2221
2239
  }, !1);
2222
- const o = xn(e, n).split("---STATEMENT_SEPARATOR---").filter((u) => u.trim());
2223
- for (const u of o) {
2224
- const l = await e.query(u.trim());
2225
- u.includes("RETURNING") && (a = l);
2240
+ const i = xn(e, n).split("---STATEMENT_SEPARATOR---").filter((l) => l.trim());
2241
+ for (const l of i) {
2242
+ const u = await e.query(l.trim());
2243
+ l.includes("RETURNING") && (a = u);
2226
2244
  }
2227
- const c = (u, l) => {
2228
- if (l.length === 0) return;
2229
- const d = l.map((f) => {
2230
- const p = { ...f };
2245
+ const c = (l, u) => {
2246
+ if (u.length === 0) return;
2247
+ const h = u.map((p) => {
2248
+ const f = { ...p };
2231
2249
  return {
2232
- namespace: u.namespace,
2233
- entity: u.name,
2250
+ namespace: l.namespace,
2251
+ entity: l.name,
2234
2252
  type: "UPDATE",
2235
- id: f.id,
2236
- patch: p,
2237
- inversePatch: p,
2238
- recordAt: f.createdAt
2253
+ id: p.id,
2254
+ patch: f,
2255
+ inversePatch: f,
2256
+ recordAt: p.createdAt
2239
2257
  };
2240
2258
  });
2241
- e.rxdb.dispatchEvent(new me(d));
2259
+ e.rxdb.dispatchEvent(new ge(h));
2242
2260
  };
2243
2261
  if (a) {
2244
- const u = _a(a), l = He(e, ne, u, !0), d = D(ne);
2245
- c(d, l);
2262
+ const l = _a(a), u = Ve(e, re, l, !0), h = C(re);
2263
+ c(h, u);
2246
2264
  }
2247
- s && Bn(e, s);
2248
- } catch (i) {
2249
- throw new x(`switch branch ${n} failed: ` + i);
2265
+ s && Fn(e, s);
2266
+ } catch (o) {
2267
+ throw new x(`switch branch ${n} failed: ` + o);
2250
2268
  }
2251
2269
  };
2252
2270
  async function wa(e, t, n, r = !1) {
@@ -2254,95 +2272,95 @@ async function wa(e, t, n, r = !1) {
2254
2272
  if (r) {
2255
2273
  const s = Un(e);
2256
2274
  if (s) {
2257
- const a = s.split("---STATEMENT_SEPARATOR---").filter((i) => i.trim());
2258
- for (const i of a)
2259
- await e.query(i.trim());
2275
+ const a = s.split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2276
+ for (const o of a)
2277
+ await e.query(o.trim());
2260
2278
  }
2261
2279
  }
2262
2280
  for (const s of t.deletes)
2263
2281
  s.params.length > 0 ? await e.query(s.sql, s.params) : await e.query(s.sql);
2264
2282
  for (const s of t.inserts) {
2265
- const a = s.sql.split("---STATEMENT_SEPARATOR---").filter((i) => i.trim());
2266
- for (const i of a)
2267
- await e.query(i.trim());
2283
+ const a = s.sql.split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2284
+ for (const o of a)
2285
+ await e.query(o.trim());
2268
2286
  s.successResults = { rows: [], affectedRows: a.length, fields: [] };
2269
2287
  }
2270
2288
  for (const s of t.updates) {
2271
- const a = s.sql.split("---STATEMENT_SEPARATOR---").filter((i) => i.trim());
2272
- for (const i of a)
2273
- await e.query(i.trim());
2289
+ const a = s.sql.split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2290
+ for (const o of a)
2291
+ await e.query(o.trim());
2274
2292
  s.successResults = { rows: [], affectedRows: a.length, fields: [] };
2275
2293
  }
2276
2294
  }, !1), r) {
2277
- const s = await e.rxdb.versionManager.getCurrentBranch(), i = xn(e, s.id).split("---STATEMENT_SEPARATOR---").filter((o) => o.trim());
2278
- for (const o of i)
2279
- await e.query(o.trim());
2295
+ const s = await e.rxdb.versionManager.getCurrentBranch(), o = xn(e, s.id).split("---STATEMENT_SEPARATOR---").filter((i) => i.trim());
2296
+ for (const i of o)
2297
+ await e.query(i.trim());
2280
2298
  }
2281
- Bn(e, t);
2299
+ Fn(e, t);
2282
2300
  }
2283
- function Bn(e, t) {
2301
+ function Fn(e, t) {
2284
2302
  for (const n of t.deletes) {
2285
- const r = Re(n.metadata);
2303
+ const r = Se(n.metadata);
2286
2304
  ya(e, r, Array.from(n.ids));
2287
- const s = n.metadata, a = Array.from(n.ids).map((i) => {
2288
- const o = n.changes.get(String(i));
2305
+ const s = n.metadata, a = Array.from(n.ids).map((o) => {
2306
+ const i = n.changes.get(String(o));
2289
2307
  return {
2290
2308
  namespace: s.namespace,
2291
2309
  entity: s.name,
2292
2310
  type: "DELETE",
2293
- id: i,
2311
+ id: o,
2294
2312
  patch: null,
2295
- inversePatch: o?.inversePatch ?? null,
2313
+ inversePatch: i?.inversePatch ?? null,
2296
2314
  recordAt: /* @__PURE__ */ new Date()
2297
2315
  };
2298
2316
  });
2299
- e.rxdb.dispatchEvent(new Ve(a));
2317
+ e.rxdb.dispatchEvent(new Ke(a));
2300
2318
  }
2301
2319
  for (const n of t.inserts) {
2302
- const r = Re(n.metadata), s = bt(n.successResults), a = He(e, r, s), i = n.metadata, o = a.map((c) => {
2303
- const u = n.changes.get(String(c.id));
2320
+ const r = Se(n.metadata), s = St(n.successResults), a = Ve(e, r, s), o = n.metadata, i = a.map((c) => {
2321
+ const l = n.changes.get(String(c.id));
2304
2322
  return {
2305
- namespace: i.namespace,
2306
- entity: i.name,
2323
+ namespace: o.namespace,
2324
+ entity: o.name,
2307
2325
  type: "INSERT",
2308
2326
  id: c.id,
2309
- patch: u?.patch ?? { ...c },
2310
- inversePatch: u?.inversePatch ?? null,
2327
+ patch: l?.patch ?? { ...c },
2328
+ inversePatch: l?.inversePatch ?? null,
2311
2329
  recordAt: c.createdAt
2312
2330
  };
2313
2331
  });
2314
- e.rxdb.dispatchEvent(new oe(o));
2332
+ e.rxdb.dispatchEvent(new ue(i));
2315
2333
  }
2316
2334
  for (const n of t.updates) {
2317
- const r = Re(n.metadata), s = bt(n.successResults), a = He(e, r, s, !0), i = n.metadata, o = a.map((c) => {
2318
- const u = n.changes.get(String(c.id));
2335
+ const r = Se(n.metadata), s = St(n.successResults), a = Ve(e, r, s, !0), o = n.metadata, i = a.map((c) => {
2336
+ const l = n.changes.get(String(c.id));
2319
2337
  return {
2320
- namespace: i.namespace,
2321
- entity: i.name,
2338
+ namespace: o.namespace,
2339
+ entity: o.name,
2322
2340
  type: "UPDATE",
2323
2341
  id: c.id,
2324
- patch: u?.patch ?? { ...c },
2325
- inversePatch: u?.inversePatch ?? null,
2342
+ patch: l?.patch ?? { ...c },
2343
+ inversePatch: l?.inversePatch ?? null,
2326
2344
  recordAt: c.updatedAt || c.createdAt || /* @__PURE__ */ new Date()
2327
2345
  };
2328
2346
  });
2329
- e.rxdb.dispatchEvent(new me(o));
2347
+ e.rxdb.dispatchEvent(new ge(i));
2330
2348
  }
2331
2349
  }
2332
- function bt(e) {
2350
+ function St(e) {
2333
2351
  return {
2334
2352
  rows: e.rows,
2335
2353
  rowsAffected: e.affectedRows ?? e.rows.length,
2336
2354
  elapsed: 0
2337
2355
  };
2338
2356
  }
2339
- function St(e, t, n) {
2357
+ function It(e, t, n) {
2340
2358
  const r = [];
2341
2359
  return e.rxdb.config.entities.forEach((s) => {
2342
- const a = D(s);
2360
+ const a = C(s);
2343
2361
  if (a.log !== !1) {
2344
- const o = $e(a, { branchId: t, transactionId: n }).split("---STATEMENT_SEPARATOR---").map((c) => c.trim()).filter((c) => c.length > 0);
2345
- r.push(...o);
2362
+ const i = be(a, { branchId: t, transactionId: n }).split("---STATEMENT_SEPARATOR---").map((c) => c.trim()).filter((c) => c.length > 0);
2363
+ r.push(...i);
2346
2364
  }
2347
2365
  }), r;
2348
2366
  }
@@ -2361,13 +2379,13 @@ class Ca extends kn {
2361
2379
  /** 仓库实例缓存,避免重复创建 */
2362
2380
  #s = /* @__PURE__ */ new Map();
2363
2381
  /** PGlite 客户端缓存 */
2364
- #i;
2382
+ #o;
2365
2383
  /** 事务锁标志,防止事务嵌套 */
2366
2384
  #t = !1;
2367
2385
  /** 查询任务队列执行器,确保查询按顺序执行 */
2368
2386
  #r = new Vn(1);
2369
2387
  /** 客户端初始化 Promise,确保单例 */
2370
- #o;
2388
+ #c;
2371
2389
  /** 当前活跃的事务对象 */
2372
2390
  #a;
2373
2391
  /** 适配器名称 */
@@ -2382,16 +2400,16 @@ class Ca extends kn {
2382
2400
  * @returns Observable<Map<string, string>> - id → updatedAt 映射
2383
2401
  */
2384
2402
  getMetadataByIds(t, n) {
2385
- return be(() => {
2403
+ return Ie(() => {
2386
2404
  if (n.length === 0)
2387
- return Se(/* @__PURE__ */ new Map());
2405
+ return Oe(/* @__PURE__ */ new Map());
2388
2406
  const a = `SELECT id, "updatedAt" FROM "public"."${this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t}" WHERE id = ANY($1)`;
2389
- return Ie(this.internalQuery(a, [n])).pipe(
2390
- Yn((i) => {
2391
- const o = /* @__PURE__ */ new Map();
2392
- for (const c of i.rows)
2393
- o.set(c.id, c.updatedAt);
2394
- return o;
2407
+ return De(this.internalQuery(a, [n])).pipe(
2408
+ Yn((o) => {
2409
+ const i = /* @__PURE__ */ new Map();
2410
+ for (const c of o.rows)
2411
+ i.set(c.id, c.updatedAt);
2412
+ return i;
2395
2413
  })
2396
2414
  );
2397
2415
  });
@@ -2406,12 +2424,12 @@ class Ca extends kn {
2406
2424
  * @returns Observable<void>
2407
2425
  */
2408
2426
  upsertMany(t, n) {
2409
- return be(() => n.length === 0 ? Se(void 0) : Ie(
2427
+ return Ie(() => n.length === 0 ? Oe(void 0) : De(
2410
2428
  (async () => {
2411
- const s = this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t, a = Object.keys(n[0]), i = a.map((o) => `"${o}"`).join(", ");
2412
- 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);
2429
+ const s = this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t, a = Object.keys(n[0]), o = a.map((i) => `"${i}"`).join(", ");
2430
+ for (const i of n) {
2431
+ const c = a.map((p) => i[p]), l = a.map((p, f) => `$${f + 1}`).join(", "), u = a.filter((p) => p !== "id").map((p) => `"${p}" = EXCLUDED."${p}"`).join(", "), h = `INSERT INTO "public"."${s}" (${o}) VALUES (${l}) ON CONFLICT (id) DO UPDATE SET ${u}`;
2432
+ await this.internalQuery(h, c);
2415
2433
  }
2416
2434
  })()
2417
2435
  ));
@@ -2424,11 +2442,11 @@ class Ca extends kn {
2424
2442
  * @returns Observable<void>
2425
2443
  */
2426
2444
  deleteByIds(t, n) {
2427
- return be(() => {
2445
+ return Ie(() => {
2428
2446
  if (n.length === 0)
2429
- return Se(void 0);
2447
+ return Oe(void 0);
2430
2448
  const a = `DELETE FROM "public"."${this.rxdb.schemaManager.getEntityMetadata(t, "public")?.tableName ?? t}" WHERE id = ANY($1)`;
2431
- return Ie(this.internalQuery(a, [n]).then(() => {
2449
+ return De(this.internalQuery(a, [n]).then(() => {
2432
2450
  }));
2433
2451
  });
2434
2452
  }
@@ -2482,8 +2500,16 @@ class Ca extends kn {
2482
2500
  */
2483
2501
  async removeMany(t) {
2484
2502
  if (!t || t.length === 0) return Promise.resolve([]);
2485
- const n = D(t[0].constructor), r = Sn(n, t);
2486
- return await this.query(r), t;
2503
+ const n = /* @__PURE__ */ new Map();
2504
+ for (const r of t) {
2505
+ const s = r.constructor;
2506
+ n.has(s) || n.set(s, []), n.get(s).push(r);
2507
+ }
2508
+ for (const [r, s] of n) {
2509
+ const a = C(r), o = Sn(a, s);
2510
+ await this.query(o);
2511
+ }
2512
+ return t;
2487
2513
  }
2488
2514
  /**
2489
2515
  * 批量保存实体
@@ -2506,11 +2532,11 @@ class Ca extends kn {
2506
2532
  }
2507
2533
  const r = async () => {
2508
2534
  for (const [s, a] of n.entries()) {
2509
- const i = D(s), o = ue(i, a, this.rxdb.context);
2510
- await this.query(o);
2535
+ const o = C(s), i = de(o, a, this.rxdb.context);
2536
+ await this.query(i);
2511
2537
  for (const c of a) {
2512
- const u = J(c);
2513
- u.local = !0, u.modified = !1;
2538
+ const l = J(c);
2539
+ l.local = !0, l.modified = !1;
2514
2540
  }
2515
2541
  }
2516
2542
  };
@@ -2523,7 +2549,7 @@ class Ca extends kn {
2523
2549
  */
2524
2550
  async connect() {
2525
2551
  const t = await this.#n(), n = pa();
2526
- 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;
2552
+ return await t.exec(n), t instanceof Rt && (t.addEventListener(K.INSERT, (r) => Me(this, r)), t.addEventListener(K.UPDATE, (r) => Me(this, r)), t.addEventListener(K.DELETE, (r) => Me(this, r))), this;
2527
2553
  }
2528
2554
  /**
2529
2555
  * 断开数据库连接
@@ -2531,7 +2557,7 @@ class Ca extends kn {
2531
2557
  * 清理资源并发送销毁信号
2532
2558
  */
2533
2559
  async disconnect() {
2534
- this.#i && (await this.#i.disconnect(), this.#e.next(), this.#e.complete());
2560
+ this.#o && (await this.#o.disconnect(), this.#e.next(), this.#e.complete());
2535
2561
  }
2536
2562
  /**
2537
2563
  * 创建分支
@@ -2595,7 +2621,7 @@ class Ca extends kn {
2595
2621
  */
2596
2622
  getRepository(t) {
2597
2623
  if (!this.#s.has(t)) {
2598
- const n = D(t);
2624
+ const n = C(t);
2599
2625
  let r;
2600
2626
  switch (n.repository) {
2601
2627
  case "Repository":
@@ -2626,48 +2652,57 @@ class Ca extends kn {
2626
2652
  * @returns 是否成功创建
2627
2653
  */
2628
2654
  async createTables(t, n) {
2629
- const r = [], s = [];
2655
+ const r = [], s = [], a = /* @__PURE__ */ new Set();
2656
+ for (const i of t) {
2657
+ const c = C(i);
2658
+ c.namespace && c.namespace !== "public" && a.add(c.namespace);
2659
+ }
2660
+ if (a.size > 0) {
2661
+ const i = Array.from(a).map((c) => `CREATE SCHEMA IF NOT EXISTS "${c}"`).join(`;
2662
+ `) + ";";
2663
+ await this.#i(i);
2664
+ }
2630
2665
  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("--"));
2632
- for (const l of u)
2633
- l && (l.includes("ADD CONSTRAINT") && l.includes("FOREIGN KEY") ? r.push(l) : s.push(l));
2666
+ const c = C(i), u = qn(this, c).split(/;\s*\n/).map((h) => h.trim()).filter((h) => h.length > 0 && !h.startsWith("--"));
2667
+ for (const h of u)
2668
+ h && (h.includes("ADD CONSTRAINT") && h.includes("FOREIGN KEY") ? r.push(h) : s.push(h));
2634
2669
  }
2635
2670
  if (s.length > 0) {
2636
2671
  const i = s.join(`;
2637
2672
  `) + ";";
2638
- await this.#c(i);
2673
+ await this.#i(i);
2639
2674
  }
2640
2675
  if (r.length > 0) {
2641
2676
  const i = r.join(`;
2642
2677
  `) + ";";
2643
2678
  try {
2644
- await this.#c(i);
2645
- } catch (o) {
2646
- console.warn("Failed to add foreign key constraints:", o);
2679
+ await this.#i(i);
2680
+ } catch (c) {
2681
+ console.warn("Failed to add foreign key constraints:", c);
2647
2682
  }
2648
2683
  }
2649
2684
  for (const i of t) {
2650
- const o = D(i);
2651
- if (o.log !== !1) {
2652
- const c = $e(o);
2653
- await this.#c(c.replace(/---STATEMENT_SEPARATOR---/g, ";"));
2685
+ const c = C(i);
2686
+ if (c.log !== !1) {
2687
+ const l = be(c);
2688
+ await this.#i(l.replace(/---STATEMENT_SEPARATOR---/g, ";"));
2654
2689
  }
2655
2690
  }
2656
2691
  if (n && n.length > 0) {
2657
2692
  const i = /* @__PURE__ */ new Map();
2658
- for (const o of n) {
2659
- const c = o.constructor;
2660
- i.has(c) || i.set(c, []), i.get(c).push(o);
2693
+ for (const c of n) {
2694
+ const l = c.constructor;
2695
+ i.has(l) || i.set(l, []), i.get(l).push(c);
2661
2696
  }
2662
- for (const [o, c] of i) {
2663
- const u = D(o), l = ue(u, c, this.rxdb.context);
2664
- await this.#c(l);
2697
+ for (const [c, l] of i) {
2698
+ const u = C(c), h = de(u, l, this.rxdb.context);
2699
+ await this.#i(h);
2665
2700
  }
2666
2701
  }
2667
- const a = ["rxdb_change", "rxdb_branch", "rxdb_migration"];
2668
- for (const i of a) {
2669
- const o = Pn(i);
2670
- await this.#c(o);
2702
+ const o = ["rxdb_change", "rxdb_branch", "rxdb_migration"];
2703
+ for (const i of o) {
2704
+ const c = Pn(i);
2705
+ await this.#i(c);
2671
2706
  }
2672
2707
  return !0;
2673
2708
  }
@@ -2678,7 +2713,7 @@ class Ca extends kn {
2678
2713
  * @returns 表是否存在
2679
2714
  */
2680
2715
  async isTableExisted(t) {
2681
- const n = D(t);
2716
+ const n = C(t);
2682
2717
  return (await this.#l(
2683
2718
  `SELECT EXISTS (
2684
2719
  SELECT 1 FROM information_schema.tables
@@ -2694,7 +2729,7 @@ class Ca extends kn {
2694
2729
  * @returns 列信息数组
2695
2730
  */
2696
2731
  async getTableColumns(t) {
2697
- const n = D(t);
2732
+ const n = C(t);
2698
2733
  return (await this.#l(
2699
2734
  `SELECT * FROM information_schema.columns
2700
2735
  WHERE table_schema = '${n.namespace}'
@@ -2708,7 +2743,7 @@ class Ca extends kn {
2708
2743
  * @returns 分支仓库实例
2709
2744
  */
2710
2745
  localRxDBBranch() {
2711
- return this.getRepository(ne);
2746
+ return this.getRepository(re);
2712
2747
  }
2713
2748
  /**
2714
2749
  * 获取本地变更仓库
@@ -2716,7 +2751,7 @@ class Ca extends kn {
2716
2751
  * @returns 变更仓库实例
2717
2752
  */
2718
2753
  localRxDBChange() {
2719
- return this.getRepository(ie);
2754
+ return this.getRepository(le);
2720
2755
  }
2721
2756
  /**
2722
2757
  * 执行事务
@@ -2736,19 +2771,19 @@ class Ca extends kn {
2736
2771
  async transaction(t, n = !0) {
2737
2772
  await this.rxdb.connect(this.name);
2738
2773
  const r = await this.#n(), s = n ? crypto.randomUUID() : void 0;
2739
- return await r.transaction(async (i) => {
2740
- if (this.#t = !0, this.#a = i, await i.query("SET CONSTRAINTS ALL DEFERRED"), n && s) {
2741
- const c = St(this, "main", s);
2742
- for (const u of c)
2743
- await i.query(u);
2774
+ return await r.transaction(async (o) => {
2775
+ if (this.#t = !0, this.#a = o, await o.query("SET CONSTRAINTS ALL DEFERRED"), n && s) {
2776
+ const c = It(this, "main", s);
2777
+ for (const l of c)
2778
+ await o.query(l);
2744
2779
  }
2745
- const o = await t();
2780
+ const i = await t();
2746
2781
  if (n && s) {
2747
- const c = St(this, "main");
2748
- for (const u of c)
2749
- await i.query(u);
2782
+ const c = It(this, "main");
2783
+ for (const l of c)
2784
+ await o.query(l);
2750
2785
  }
2751
- return this.#a = void 0, this.#t = !1, o;
2786
+ return this.#a = void 0, this.#t = !1, i;
2752
2787
  });
2753
2788
  }
2754
2789
  /**
@@ -2765,7 +2800,7 @@ class Ca extends kn {
2765
2800
  query(t, n) {
2766
2801
  return this.#t && this.#a ? this.#a.query(t, n) : this.#r.addTask(
2767
2802
  async () => (await this.rxdb.connect(this.name), (await this.#n()).query(t, n)),
2768
- Ot([t, n])
2803
+ JSON.stringify([t, n])
2769
2804
  );
2770
2805
  }
2771
2806
  /**
@@ -2797,7 +2832,7 @@ class Ca extends kn {
2797
2832
  * @param options - 执行选项
2798
2833
  * @returns 执行结果数组
2799
2834
  */
2800
- async #c(t, n) {
2835
+ async #i(t, n) {
2801
2836
  return (await this.#n()).exec(t, n);
2802
2837
  }
2803
2838
  /**
@@ -2808,11 +2843,11 @@ class Ca extends kn {
2808
2843
  * @returns PGlite 客户端 Promise
2809
2844
  */
2810
2845
  #n() {
2811
- if (!this.#o) {
2846
+ if (!this.#c) {
2812
2847
  const t = new Rt();
2813
- this.#o = t.init(this.rxdb.config.dbName, this.options).then(() => (this.#i = t, t));
2848
+ this.#c = t.init(this.rxdb.config.dbName, this.options).then(() => (this.#o = t, t));
2814
2849
  }
2815
- return this.#o;
2850
+ return this.#c;
2816
2851
  }
2817
2852
  }
2818
2853
  class Na {
@@ -2839,13 +2874,13 @@ class Na {
2839
2874
  * @returns SQL 语句
2840
2875
  */
2841
2876
  generateBatchInsert(t, n, r) {
2842
- const s = this.escapeIdentifier(t), a = n.map((c) => this.escapeIdentifier(c)).join(", "), i = [];
2843
- let o = 1;
2877
+ const s = this.escapeIdentifier(t), a = n.map((c) => this.escapeIdentifier(c)).join(", "), o = [];
2878
+ let i = 1;
2844
2879
  for (let c = 0; c < r; c++) {
2845
- const u = n.map(() => this.getParameterPlaceholder(o++)).join(", ");
2846
- i.push(`(${u})`);
2880
+ const l = n.map(() => this.getParameterPlaceholder(i++)).join(", ");
2881
+ o.push(`(${l})`);
2847
2882
  }
2848
- return `INSERT INTO ${s} (${a}) VALUES ${i.join(", ")} ${this.getReturningClause()}`;
2883
+ return `INSERT INTO ${s} (${a}) VALUES ${o.join(", ")} ${this.getReturningClause()}`;
2849
2884
  }
2850
2885
  /**
2851
2886
  * 生成批量更新 SQL(使用 UPDATE ... FROM 模式)
@@ -2855,18 +2890,18 @@ class Na {
2855
2890
  * @returns SQL 模板
2856
2891
  */
2857
2892
  generateBatchUpdate(t, n, r) {
2858
- const s = this.escapeIdentifier(t), a = this.escapeIdentifier(n), i = r.map((o) => `${this.escapeIdentifier(o)} = temp.${this.escapeIdentifier(o)}`).join(", ");
2859
- return `UPDATE ${s} SET ${i} FROM (VALUES ($1)) AS temp(${a}, ${r.join(", ")}) WHERE ${s}.${a} = temp.${a} ${this.getReturningClause()}`;
2893
+ const s = this.escapeIdentifier(t), a = this.escapeIdentifier(n), o = r.map((i) => `${this.escapeIdentifier(i)} = temp.${this.escapeIdentifier(i)}`).join(", ");
2894
+ return `UPDATE ${s} SET ${o} FROM (VALUES ($1)) AS temp(${a}, ${r.join(", ")}) WHERE ${s}.${a} = temp.${a} ${this.getReturningClause()}`;
2860
2895
  }
2861
2896
  }
2862
2897
  const La = new Na();
2863
- function Ma(e, t, n) {
2898
+ function va(e, t, n) {
2864
2899
  let r = "";
2865
2900
  for (let s = 0; s < t.length; s++) {
2866
- const a = t[s], i = D(a), o = qn(e, i);
2901
+ const a = t[s], o = C(a), i = qn(e, o);
2867
2902
  if (r += `
2868
- ` + o, i.log !== !1) {
2869
- const c = $e(i);
2903
+ ` + i, o.log !== !1) {
2904
+ const c = be(o);
2870
2905
  r += `
2871
2906
  ` + c;
2872
2907
  }
@@ -2874,13 +2909,13 @@ function Ma(e, t, n) {
2874
2909
  if (n && n.length > 0) {
2875
2910
  const s = /* @__PURE__ */ new Map();
2876
2911
  n.forEach((a) => {
2877
- const i = D(a);
2878
- s.has(i) || s.set(i, /* @__PURE__ */ new Set()), s.get(i).add(a);
2912
+ const o = C(a);
2913
+ s.has(o) || s.set(o, /* @__PURE__ */ new Set()), s.get(o).add(a);
2879
2914
  });
2880
- for (const [a, i] of s.entries()) {
2881
- const o = ue(a, Array.from(i), e.rxdb.context);
2915
+ for (const [a, o] of s.entries()) {
2916
+ const i = de(a, Array.from(o), e.rxdb.context);
2882
2917
  r += `
2883
- ` + o;
2918
+ ` + i;
2884
2919
  }
2885
2920
  }
2886
2921
  return r;
@@ -2892,27 +2927,27 @@ export {
2892
2927
  Na as PostgreSQLDialect,
2893
2928
  Ca as RxDBAdapterPGlite,
2894
2929
  x as RxdbAdapterPGliteError,
2895
- Ma as create_tables_sql,
2930
+ va as create_tables_sql,
2896
2931
  da as generateNotifyFunctionSQL,
2897
2932
  pa as generateNotifyInfrastructureSQL,
2898
2933
  Pn as generateNotifyTriggerSQL,
2899
- $e as generate_trigger_sql,
2900
- Z as getEntityObjectFromResult,
2901
- Je as getSqlValue,
2902
- nt as getSqlWithParams,
2903
- Ct as getTableColumnIndexName,
2904
- vt as getTableName,
2934
+ be as generate_trigger_sql,
2935
+ ee as getEntityObjectFromResult,
2936
+ Ye as getSqlValue,
2937
+ st as getSqlWithParams,
2938
+ Lt as getTableColumnIndexName,
2939
+ Dt as getTableName,
2905
2940
  P as getTableNameByMetadata,
2906
- Lt as normalizeCreateEntity,
2941
+ vt as normalizeCreateEntity,
2907
2942
  zn as normalizeEntity,
2908
2943
  La as pgDialect,
2909
2944
  Da as removeNotifyTriggerSQL,
2910
2945
  Un as remove_all_triggers_sql,
2911
2946
  ma as remove_trigger_sql,
2912
- Dt as rxDBColumnTypeToPGliteType,
2947
+ Ct as rxDBColumnTypeToPGliteType,
2913
2948
  Xn as rxDBColumnTypeToPGliteTypeIndexName,
2914
- st as transformEntityValuePGliteToJs,
2915
- Ke as transformEntityValueToSql,
2916
- tt as transformValueJsToPGlite,
2917
- Le as transformValuePGliteToJs
2949
+ rt as transformEntityValuePGliteToJs,
2950
+ Je as transformEntityValueToSql,
2951
+ nt as transformValueJsToPGlite,
2952
+ ae as transformValuePGliteToJs
2918
2953
  };