@aiao/rxdb-adapter-sqlite 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { getEntityMetadata as w, PropertyType as y, RelationKind as A, isRuleGroup as ce, getEntityStatus as C, RepositoryBase as je, RxDBChange as F, EntityLocalCreatedEvent as k, EntityLocalRemovedEvent as ne, EntityLocalUpdatedEvent as K, parseRxDBChangeKey as J, RxDBBranch as W, getEntityType as Y, TransactionBeginEvent as Fe, TransactionRollbackEvent as Pe, TransactionCommitEvent as Be, RxDBAdapterLocalBase as ke, getEntityMutations as le, uuid as We } from "@aiao/rxdb";
2
- import { pickBy as ye, isString as Ue, isNil as Ve, traverseObjectKeys as He, EventDispatcher as Qe, AsyncQueueExecutor as ge, get as Ke, isFunction as de } from "@aiao/utils";
3
- import { wrap as ue, proxy as Ge } from "comlink";
4
- import $e from "object-hash";
5
- import { defer as X, of as z, from as Z, map as Je } from "rxjs";
6
- import { Factory as Ye, SQLITE_ROW as Xe, SQLITE_UTF8 as Te, SQLITE_DETERMINISTIC as we } from "wa-sqlite";
1
+ import { getEntityMetadata as w, PropertyType as y, RelationKind as A, isRuleGroup as le, getEntityStatus as j, RepositoryBase as De, RxDBChange as k, EntityLocalCreatedEvent as B, EntityLocalRemovedEvent as re, EntityLocalUpdatedEvent as G, parseRxDBChangeKey as Y, RxDBBranch as W, getEntityType as X, TransactionBeginEvent as ke, TransactionRollbackEvent as Pe, TransactionCommitEvent as Fe, RxDBAdapterLocalBase as Be, getEntityMutations as ue, uuid as We } from "@aiao/rxdb";
2
+ import { isString as Ue, isNil as Ke, traverseObjectKeys as Ve, EventDispatcher as He, AsyncQueueExecutor as ge, get as Qe, isFunction as de } from "@aiao/utils";
3
+ import { wrap as fe, proxy as Ge } from "comlink";
4
+ import Ne from "object-hash";
5
+ import { defer as z, of as Z, from as ee, map as Je } from "rxjs";
6
+ import { Factory as Ye, SQLITE_ROW as Xe, SQLITE_UTF8 as $e, SQLITE_DETERMINISTIC as Te } from "wa-sqlite";
7
7
  const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}' limit 1;`, Ze = (e) => !!e.sql && (e.results.length === 0 || e.results[0].rows.length === 0), L = "__rowid", et = (e) => {
8
8
  switch (e.type) {
9
9
  case y.uuid:
@@ -21,7 +21,7 @@ const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}
21
21
  default:
22
22
  return "TEXT";
23
23
  }
24
- }, se = (e, t) => {
24
+ }, U = (e, t) => {
25
25
  if (e === null && t.nullable) return null;
26
26
  if (e !== void 0)
27
27
  switch (t.type) {
@@ -34,7 +34,7 @@ const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}
34
34
  if (t.properties && typeof e == "object" && !Array.isArray(e)) {
35
35
  const n = { ...e };
36
36
  return t.properties.forEach((s) => {
37
- s.name in n && (n[s.name] = se(n[s.name], s));
37
+ s.name in n && (n[s.name] = U(n[s.name], s));
38
38
  }), JSON.stringify(n);
39
39
  }
40
40
  return JSON.stringify(e);
@@ -46,7 +46,7 @@ const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}
46
46
  default:
47
47
  return e;
48
48
  }
49
- }, D = (e, t) => {
49
+ }, v = (e, t) => {
50
50
  if (e === null && t.nullable) return null;
51
51
  if (e !== void 0)
52
52
  switch (t.type) {
@@ -58,7 +58,7 @@ const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}
58
58
  if (!e) return null;
59
59
  const n = JSON.parse(e);
60
60
  return t.properties && n && typeof n == "object" && t.properties.forEach((s) => {
61
- s.name in n && (n[s.name] = D(n[s.name], s));
61
+ s.name in n && (n[s.name] = v(n[s.name], s));
62
62
  }), n;
63
63
  }
64
64
  case y.json:
@@ -71,43 +71,94 @@ const ze = (e) => `SELECT * FROM sqlite_master WHERE type='table' AND name='${e}
71
71
  }, q = (e, t) => `${t}$${e}`, tt = (e) => {
72
72
  const t = e.indexOf("$");
73
73
  return t === -1 ? ["", e] : [e.substring(0, t), e.substring(t + 1)];
74
- }, S = (e) => q(e.name, e.namespace), he = (e) => S(w(e)), pe = (e, t) => `idx_${e.name}_${t.name}`;
75
- class b extends Error {
74
+ }, S = (e) => q(e.tableName, e.namespace), pe = (e) => S(w(e)), he = (e, t) => `idx_${e.name}_${t.name}`;
75
+ class O extends Error {
76
76
  constructor(t) {
77
- super(t), this.name = "RxDBAdapterSqliteError", Object.setPrototypeOf(this, b.prototype);
77
+ super(t), this.name = "RxDBAdapterSqliteError", Object.setPrototypeOf(this, O.prototype);
78
78
  }
79
79
  }
80
- const re = (e, t) => {
81
- const n = {}, s = Object.keys(t);
82
- for (let r = 0; r < s.length; r++) {
83
- const a = s[r];
84
- if (a.endsWith("Id")) {
85
- n[a] = t[a];
80
+ const oe = (e, t) => {
81
+ const n = {}, s = Object.keys(t), r = e.foreignKeyNames || [], o = e.foreignKeyColumnNames || r;
82
+ for (let i = 0; i < s.length; i++) {
83
+ const c = s[i], a = r.indexOf(c);
84
+ if (a !== -1) {
85
+ n[o[a]] = t[c];
86
+ continue;
87
+ }
88
+ if (o.indexOf(c) !== -1) {
89
+ n[c] = t[c];
90
+ continue;
91
+ }
92
+ if (r.length === 0 && c.endsWith("Id")) {
93
+ n[c] = t[c];
94
+ continue;
95
+ }
96
+ const u = e.propertyMap.get(c);
97
+ if (u) {
98
+ n[u.columnName] = U(t[c], u);
86
99
  continue;
87
100
  }
88
- const i = e.propertyMap.get(a);
89
- i && (n[a] = se(t[a], i));
101
+ const d = e.columnNameToPropertyName?.get(c);
102
+ if (d) {
103
+ const p = e.propertyMap.get(d);
104
+ p && (n[c] = U(t[c], p));
105
+ }
90
106
  }
91
107
  return n;
92
- }, Ne = (e, t) => ye(t, (n, s) => e.propertyMap.has(s) || e.foreignKeyNames.includes(s)), nt = (e, t) => ye(t, (n, s) => {
93
- const r = e.propertyMap.get(s);
94
- if (r)
95
- return r.readonly !== !0;
96
- const a = e.foreignKeyRelationMap.get(s);
97
- return a ? a.readonly !== !0 : e.computedPropertyMap.has(s) === !1;
98
- }), R = (e) => Ue(e) ? `'${e.replaceAll("'", "''")}'` : Ve(e) ? "NULL" : e, P = (e, t = []) => e.replace(/\?/g, () => R(t.shift())), ee = (e, t, n) => {
108
+ }, we = (e, t) => {
109
+ const n = {};
110
+ for (const [o, i] of e.propertyMap)
111
+ o in t && (n[i.columnName] = t[o]);
112
+ const s = e.foreignKeyNames || [], r = e.foreignKeyColumnNames || s;
113
+ for (let o = 0; o < s.length; o++) {
114
+ const i = s[o];
115
+ i in t && (n[r[o]] = t[i]);
116
+ }
117
+ return n;
118
+ }, nt = (e, t) => {
119
+ const n = {};
120
+ for (const [o, i] of e.propertyMap)
121
+ o in t && i.readonly !== !0 && (n[i.columnName] = t[o]);
122
+ const s = e.foreignKeyNames || [], r = e.foreignKeyColumnNames || s;
123
+ for (let o = 0; o < s.length; o++) {
124
+ const i = s[o];
125
+ if (i in t) {
126
+ const c = e.foreignKeyRelationMap.get(i);
127
+ c && c.readonly !== !0 && (n[r[o]] = t[i]);
128
+ }
129
+ }
130
+ return n;
131
+ }, R = (e) => Ue(e) ? `'${e.replaceAll("'", "''")}'` : Ke(e) ? "NULL" : e, P = (e, t = []) => e.replace(/\?/g, () => R(t.shift())), te = (e, t, n) => {
99
132
  const s = {};
100
- return n.forEach((r, a) => {
101
- const i = t[a];
102
- if (!i.startsWith("__"))
103
- if (e.isForeignKey(i))
104
- s[i] = r;
105
- else {
106
- const c = e.propertyMap.get(i) || e.computedPropertyMap.get(i);
107
- c ? s[i] = D(r, c) : console.log(`Property ${i}=${r} not found in metadata ${e.name}`);
133
+ return n.forEach((r, o) => {
134
+ const i = t[o];
135
+ if (i.startsWith("__")) return;
136
+ const c = e.foreignKeyNames || [], l = (e.foreignKeyColumnNames || c).indexOf(i);
137
+ if (l !== -1) {
138
+ s[c[l]] = r;
139
+ return;
140
+ }
141
+ const u = e.columnNameToPropertyName, f = u?.get(i);
142
+ if (f) {
143
+ const p = e.propertyMap.get(f);
144
+ p ? s[f] = v(r, p) : console.log(`Property ${f} not found in metadata ${e.name}`);
145
+ return;
146
+ }
147
+ const d = e.computedPropertyMap?.get(i);
148
+ if (d) {
149
+ s[i] = v(r, d);
150
+ return;
151
+ }
152
+ if (!u) {
153
+ const p = e.propertyMap.get(i);
154
+ if (p) {
155
+ s[i] = v(r, p);
156
+ return;
108
157
  }
158
+ }
159
+ console.log(`Column ${i}=${r} not found in metadata ${e.name}`);
109
160
  }), s;
110
- }, N = "_", st = {
161
+ }, b = "_", st = {
111
162
  "=": "=",
112
163
  "!=": "!=",
113
164
  ">": ">",
@@ -124,20 +175,47 @@ const re = (e, t) => {
124
175
  notStartsWith: "NOT LIKE",
125
176
  endsWith: "LIKE",
126
177
  notEndsWith: "NOT LIKE"
127
- }, fe = (e, t) => {
178
+ }, ne = (e, t) => {
179
+ if (t && e.includes(".")) {
180
+ const n = e.split("."), s = t.propertyMap.get(n[0]);
181
+ if (!s) return e;
182
+ if (s.type === y.keyValue)
183
+ return s.columnName;
184
+ for (let o = 0; o < n.length - 1; o++) {
185
+ const i = t.propertyMap.get(n[o]);
186
+ if (!i) return e;
187
+ if (i.type === y.keyValue)
188
+ return i.columnName;
189
+ }
190
+ const r = t.propertyMap.get(n[n.length - 1]);
191
+ return r ? r.columnName : e;
192
+ }
193
+ if (t) {
194
+ const n = t.propertyMap.get(e);
195
+ if (n)
196
+ return n.columnName;
197
+ const s = t.foreignKeyNames || [], r = t.foreignKeyColumnNames || s, o = s.indexOf(e);
198
+ if (o !== -1)
199
+ return r[o];
200
+ }
201
+ return e;
202
+ }, me = (e, t, n) => {
128
203
  if (t) return t;
129
- if (!e.includes(".")) return `${N}."${e}"`;
130
- const n = e.lastIndexOf("."), s = e.slice(0, n), r = e.slice(n + 1);
131
- return `"${s}"."${r}"`;
132
- }, Se = (e) => {
204
+ if (!e.includes(".")) {
205
+ const c = ne(e, n);
206
+ return `${b}."${c}"`;
207
+ }
208
+ const s = e.lastIndexOf("."), r = e.slice(0, s), o = e.slice(s + 1), i = ne(o, n);
209
+ return `"${r}"."${i}"`;
210
+ }, be = (e) => {
133
211
  const { operator: t, value: n } = e;
134
212
  switch (t) {
135
213
  case "in":
136
214
  case "notIn":
137
- return at(n);
215
+ return ot(n);
138
216
  case "between":
139
217
  case "notBetween":
140
- return ot(n);
218
+ return at(n);
141
219
  case "contains":
142
220
  case "notContains":
143
221
  return R(`%${n}%`);
@@ -150,7 +228,7 @@ const re = (e, t) => {
150
228
  default:
151
229
  return it(n);
152
230
  }
153
- }, rt = (e) => st[e] || e, U = (e, t, n) => e.length === 1 ? n.name : `${t}_${n.name}`, at = (e) => !Array.isArray(e) || !e.length ? "(NULL)" : `(${e.map(R).join(", ")})`, ot = (e) => {
231
+ }, rt = (e) => st[e] || e, K = (e, t, n) => e.length === 1 ? n.name : `${t}_${n.name}`, ot = (e) => !Array.isArray(e) || !e.length ? "(NULL)" : `(${e.map(R).join(", ")})`, at = (e) => {
154
232
  if (!Array.isArray(e) || e.length < 2) return "";
155
233
  const [t, n] = e;
156
234
  if (t == null || n == null) return "";
@@ -159,228 +237,257 @@ const re = (e, t) => {
159
237
  }, it = (e) => typeof e == "boolean" ? e ? "1" : "0" : typeof e == "string" ? R(e) : typeof e == "number" ? e.toString() : e instanceof Date ? R(e.toISOString()) : R(e), ct = (e, t, n) => {
160
238
  const s = e.propertyMap.get(t);
161
239
  if (!s || s.type !== y.keyValue || typeof n.value != "object" || Array.isArray(n.value)) return null;
162
- const r = Object.entries(n.value).filter(([, o]) => o != null);
240
+ const r = Object.entries(n.value).filter(([, a]) => a != null);
163
241
  if (!r.length) return "";
164
- const a = n.operator === "notContains" ? "NOT LIKE" : "LIKE", i = n.operator === "contains" ? " OR " : " AND ";
165
- return `(${r.map(([o, l]) => {
166
- const h = l instanceof Date ? l.toISOString() : typeof l == "string" ? l : String(l);
167
- return `json_extract(${N}."${t}", '$.${o}') ${a} ${R(`%${h}%`)}`;
242
+ const o = n.operator === "notContains" ? "NOT LIKE" : "LIKE", i = n.operator === "contains" ? " OR " : " AND ";
243
+ return `(${r.map(([a, l]) => {
244
+ const u = l instanceof Date ? l.toISOString() : typeof l == "string" ? l : String(l);
245
+ return `json_extract(${b}."${s.columnName}", '$.${a}') ${o} ${R(`%${u}%`)}`;
168
246
  }).join(i)})`;
169
247
  }, lt = (e, t, n) => {
170
248
  const s = e.propertyMap.get(t);
171
249
  if (!s || s.type !== y.stringArray && s.type !== y.numberArray) return null;
172
- const r = Se(n), a = `EXISTS (SELECT 1 FROM json_each(${N}."${t}") WHERE json_each.value IN ${r})`;
173
- return n.operator === "notIn" ? `NOT ${a}` : a;
174
- }, dt = (e, t, n, s, r) => {
250
+ const r = be(n), o = `EXISTS (SELECT 1 FROM json_each(${b}."${s.columnName}") WHERE json_each.value IN ${r})`;
251
+ return n.operator === "notIn" ? `NOT ${o}` : o;
252
+ }, ut = (e, t, n, s, r) => {
175
253
  if (n && s && r && (e.operator === "exists" || e.operator === "notExists")) {
176
- const u = Et(e, n, s, (p, f) => {
177
- const _ = /* @__PURE__ */ new Map();
178
- return f.propertyMap.forEach((E, g) => {
179
- _.set(g, `"child"."${g}"`);
180
- }), r(p, _, f, s);
254
+ const d = mt(e, n, s, (p, h) => {
255
+ const E = /* @__PURE__ */ new Map();
256
+ return h.propertyMap.forEach((m, N) => {
257
+ E.set(N, `"child"."${m.columnName}"`);
258
+ }), r(p, E, h, s);
181
259
  });
182
- if (u !== null) return u;
260
+ if (d !== null) return d;
183
261
  }
184
262
  if (e.operator === "null" || e.operator === "notNull") {
185
- const d = String(e.field), u = t.get(d), p = fe(d, u);
263
+ const f = String(e.field), d = t.get(f), p = me(f, d, n);
186
264
  return e.operator === "null" ? `${p} IS NULL` : `${p} IS NOT NULL`;
187
265
  }
188
- const a = e.value === null, i = a ? "" : rt(e.operator).toLowerCase(), c = a ? e.operator === "=" ? "IS NULL" : e.operator === "!=" ? "IS NOT NULL" : "" : Se(e);
266
+ const o = e.value === null, i = o ? "" : rt(e.operator).toLowerCase(), c = o ? e.operator === "=" ? "IS NULL" : e.operator === "!=" ? "IS NOT NULL" : "" : be(e);
189
267
  if (!c && ["in", "notIn", "between", "notBetween"].includes(e.operator)) return "";
190
- const o = String(e.field), l = t.get(o);
191
- if (n && !o.includes(".") && (e.operator === "contains" || e.operator === "notContains")) {
192
- const d = ct(n, o, e);
193
- if (d !== null) return d;
268
+ const a = String(e.field), l = t.get(a);
269
+ if (n && !a.includes(".") && (e.operator === "contains" || e.operator === "notContains")) {
270
+ const f = ct(n, a, e);
271
+ if (f !== null) return f;
194
272
  }
195
- if (n && !o.includes(".") && (e.operator === "in" || e.operator === "notIn")) {
196
- const d = lt(n, o, e);
197
- if (d !== null) return d;
273
+ if (n && !a.includes(".") && (e.operator === "in" || e.operator === "notIn")) {
274
+ const f = lt(n, a, e);
275
+ if (f !== null) return f;
198
276
  }
199
- return `${fe(o, l)} ${i} ${c}`.replace(/\s+/g, " ").trim();
200
- }, ae = (e) => e === N ? e : `"${e}"`, ut = (e, t, n) => {
277
+ return `${me(a, l, n)} ${i} ${c}`.replace(/\s+/g, " ").trim();
278
+ }, ae = (e) => e === b ? e : `"${e}"`, dt = (e, t, n) => {
201
279
  if (e.kind !== A.ONE_TO_MANY)
202
280
  throw new Error("_build_one_to_many_exists requires ONE_TO_MANY relation");
203
- const s = q(t.name, t.namespace), r = "child", a = `${e.mappedProperty}Id`;
204
- let i = `EXISTS (SELECT 1 FROM "${s}" "${r}"`;
205
- return i += ` WHERE "${r}"."${a}" = ${N}."id"`, n && (i += ` AND ${n}`), i += ")", i;
206
- }, ht = (e, t, n) => {
207
- const s = `${e.name}Id`;
281
+ const s = q(t.tableName, t.namespace), r = "child", o = t.relations.find((a) => a.name === e.mappedProperty);
282
+ if (!o)
283
+ throw new Error(
284
+ `Cannot find mappedProperty relation "${e.mappedProperty}" in entity "${t.name}"`
285
+ );
286
+ const i = o.columnName;
287
+ let c = `EXISTS (SELECT 1 FROM "${s}" "${r}"`;
288
+ return c += ` WHERE "${r}"."${i}" = ${b}."id"`, n && (c += ` AND ${n}`), c += ")", c;
289
+ }, ft = (e, t, n) => {
290
+ const s = e.columnName;
208
291
  if (!n)
209
- return `${N}."${s}" IS NOT NULL`;
210
- const r = q(t.name, t.namespace), a = "child";
211
- let i = `EXISTS (SELECT 1 FROM "${r}" "${a}"`;
212
- return i += ` WHERE ${N}."${s}" = "${a}"."id"`, i += ` AND ${n}`, i += ")", i;
292
+ return `${b}."${s}" IS NOT NULL`;
293
+ const r = q(t.tableName, t.namespace), o = "child";
294
+ let i = `EXISTS (SELECT 1 FROM "${r}" "${o}"`;
295
+ return i += ` WHERE ${b}."${s}" = "${o}"."id"`, i += ` AND ${n}`, i += ")", i;
213
296
  }, pt = (e, t, n, s, r) => {
214
- const a = s.rxdb.schemaManager.findMappedRelation(e, t);
215
- if (a?.relation) {
216
- const i = q(n.name, n.namespace), c = "child", o = `${a.relation.name}Id`;
297
+ const o = s.rxdb.schemaManager.findMappedRelation(e, t);
298
+ if (o?.relation) {
299
+ const i = q(n.tableName, n.namespace), c = "child", a = o.relation.columnName;
217
300
  let l = `EXISTS (SELECT 1 FROM "${i}" "${c}"`;
218
- return l += ` WHERE "${c}"."${o}" = ${N}."id"`, r && (l += ` AND ${r}`), l += ")", l;
301
+ return l += ` WHERE "${c}"."${a}" = ${b}."id"`, r && (l += ` AND ${r}`), l += ")", l;
219
302
  } else {
220
- const i = `${t.name}Id`;
303
+ const i = t.columnName;
221
304
  if (!r)
222
- return `${N}."${i}" IS NOT NULL`;
223
- const c = q(n.name, n.namespace), o = "child";
224
- let l = `EXISTS (SELECT 1 FROM "${c}" "${o}"`;
225
- return l += ` WHERE ${N}."${i}" = "${o}"."id"`, l += ` AND ${r}`, l += ")", l;
305
+ return `${b}."${i}" IS NOT NULL`;
306
+ const c = q(n.tableName, n.namespace), a = "child";
307
+ let l = `EXISTS (SELECT 1 FROM "${c}" "${a}"`;
308
+ return l += ` WHERE ${b}."${i}" = "${a}"."id"`, l += ` AND ${r}`, l += ")", l;
226
309
  }
227
- }, ft = (e, t, n, s) => {
228
- const r = q(n.name, n.namespace), a = "child", i = t.junctionEntityType;
310
+ }, ht = (e, t, n, s) => {
311
+ const r = q(n.tableName, n.namespace), o = "child", i = t.junctionEntityType;
229
312
  if (!i)
230
313
  throw new Error(`MANY_TO_MANY relation "${t.name}" missing junctionEntityType`);
231
314
  const c = w(i);
232
315
  if (!c)
233
316
  throw new Error("Cannot find metadata for junction entity");
234
- const o = q(c.name, c.namespace), l = "junction", h = c.relations.find(
235
- (_) => _.mappedEntity === e.name && _.mappedNamespace === e.namespace
317
+ const a = q(c.tableName, c.namespace), l = "junction", u = c.relations.find(
318
+ (E) => E.mappedEntity === e.name && E.mappedNamespace === e.namespace
236
319
  );
237
- if (!h)
320
+ if (!u)
238
321
  throw new Error(
239
322
  `Cannot find relation in junction entity ${c.name} pointing to ${e.name}`
240
323
  );
241
- const d = c.relations.find(
242
- (_) => _.mappedEntity === n.name && _.mappedNamespace === n.namespace
324
+ const f = c.relations.find(
325
+ (E) => E.mappedEntity === n.name && E.mappedNamespace === n.namespace
243
326
  );
244
- if (!d)
327
+ if (!f)
245
328
  throw new Error(
246
329
  `Cannot find relation in junction entity ${c.name} pointing to ${n.name}`
247
330
  );
248
- const u = `${h.name}Id`, p = `${d.name}Id`;
249
- let f = `EXISTS (SELECT 1 FROM "${r}" "${a}"`;
250
- return f += ` INNER JOIN "${o}" "${l}"`, f += ` ON "${l}"."${p}" = "${a}"."id"`, f += ` WHERE "${l}"."${u}" = ${N}."id"`, s && (f += ` AND ${s}`), f += ")", f;
251
- }, Et = (e, t, n, s) => {
331
+ const d = u.columnName, p = f.columnName;
332
+ let h = `EXISTS (SELECT 1 FROM "${r}" "${o}"`;
333
+ return h += ` INNER JOIN "${a}" "${l}"`, h += ` ON "${l}"."${p}" = "${o}"."id"`, h += ` WHERE "${l}"."${d}" = ${b}."id"`, s && (h += ` AND ${s}`), h += ")", h;
334
+ }, mt = (e, t, n, s) => {
252
335
  if (e.operator !== "exists" && e.operator !== "notExists")
253
336
  return null;
254
337
  const r = t.relationMap.get(e.field);
255
338
  if (!r) return null;
256
- const a = n.rxdb.schemaManager.getEntityMetadata(
339
+ const o = n.rxdb.schemaManager.getEntityMetadata(
257
340
  r.mappedEntity,
258
341
  r.mappedNamespace
259
342
  );
260
- if (!a)
343
+ if (!o)
261
344
  throw new Error(`Cannot find metadata for entity: ${r.mappedNamespace}.${r.mappedEntity}`);
262
345
  let i;
263
- e.where && s && (i = s(e.where, a));
346
+ e.where && s && (i = s(e.where, o));
264
347
  let c;
265
348
  switch (r.kind) {
266
349
  case A.ONE_TO_MANY:
267
- c = ut(r, a, i);
350
+ c = dt(r, o, i);
268
351
  break;
269
352
  case A.MANY_TO_ONE:
270
- c = ht(r, a, i);
353
+ c = ft(r, o, i);
271
354
  break;
272
355
  case A.ONE_TO_ONE:
273
- c = pt(t, r, a, n, i);
356
+ c = pt(t, r, o, n, i);
274
357
  break;
275
358
  case A.MANY_TO_MANY:
276
- c = ft(t, r, a, i);
359
+ c = ht(t, r, o, i);
277
360
  break;
278
361
  }
279
362
  return e.operator === "notExists" ? `NOT ${c}` : c;
280
363
  }, V = (e, t) => {
281
364
  if (e.relationAliasMap.has(t))
282
365
  return e.relationAliasMap.get(t);
283
- const n = t.includes("_") ? t : t.split("_")[0], s = be(e, n);
366
+ const n = t.includes("_") ? t : t.split("_")[0], s = Ae(e, n);
284
367
  return e.relationAliasMap.set(t, s), s;
285
- }, _t = (e, t, n, s) => {
368
+ }, Et = (e, t, n, s) => {
286
369
  const r = n.slice(0, s);
287
- let a = t;
370
+ let o = t;
288
371
  const i = [];
289
372
  for (const c of r) {
290
- if (!a?.relationMap.has(c))
373
+ if (!o?.relationMap.has(c))
291
374
  return { relPairs: [] };
292
- const o = a.relationMap.get(c);
293
- i.push({ metadata: a, relation: o }), a = e.rxdb.schemaManager.getEntityMetadata(o.mappedEntity, o.mappedNamespace);
375
+ const a = o.relationMap.get(c);
376
+ i.push({ metadata: o, relation: a }), o = e.rxdb.schemaManager.getEntityMetadata(a.mappedEntity, a.mappedNamespace);
294
377
  }
295
- return { metaWalker: a, relPairs: i };
296
- }, mt = (e, t, n, s, r) => {
297
- for (let a = r.length - 1; a > 0; a--) {
298
- const i = r.slice(a);
378
+ return { metaWalker: o, relPairs: i };
379
+ }, _t = (e, t, n, s, r) => {
380
+ for (let o = r.length - 1; o > 0; o--) {
381
+ const i = r.slice(o);
299
382
  if (i.length === 0) continue;
300
- const { metaWalker: c, relPairs: o } = _t(e, n, r, a);
301
- if (!c || o.length === 0) continue;
302
- const l = i[0], h = i.slice(1).join("."), d = c.propertyMap.get(l);
303
- if (d && d.type === y.keyValue) {
304
- const u = r.slice(0, a).join(".");
305
- Ae(e, t, o, u);
306
- const p = o[o.length - 1].relation, f = U(o, u, p), _ = V(t, f), E = h ? `$.${h}` : "$";
307
- return t.fieldAliasMap.set(s, `json_extract("${_}"."${l}", '${E}')`), !0;
383
+ const { metaWalker: c, relPairs: a } = Et(e, n, r, o);
384
+ if (!c || a.length === 0) continue;
385
+ const l = i[0], u = i.slice(1).join("."), f = c.propertyMap.get(l);
386
+ if (f && f.type === y.keyValue) {
387
+ const d = r.slice(0, o).join(".");
388
+ Se(e, t, a, d);
389
+ const p = a[a.length - 1].relation, h = K(a, d, p), E = V(t, h), m = u ? `$.${u}` : "$";
390
+ return t.fieldAliasMap.set(s, `json_extract("${E}"."${f.columnName}", '${m}')`), !0;
308
391
  }
309
392
  }
310
393
  return !1;
311
- }, Ae = (e, t, n, s) => {
312
- n.forEach(({ metadata: r, relation: a }, i) => {
313
- let c = e.rxdb.schemaManager.findMappedRelation(r, a);
394
+ }, Se = (e, t, n, s) => {
395
+ n.forEach(({ metadata: r, relation: o }, i) => {
396
+ let c = e.rxdb.schemaManager.findMappedRelation(r, o);
314
397
  if (!c)
315
- if ((a.kind === A.ONE_TO_MANY || a.kind === A.MANY_TO_MANY) && "mappedProperty" in a) {
316
- const d = r.relationMap.get(a.mappedProperty);
317
- d && (c = { metadata: r, relation: d });
318
- } else (a.kind === A.MANY_TO_ONE || a.kind === A.ONE_TO_ONE) && (c = { metadata: r, relation: a });
319
- if (!c) throw new b("mappedRelation not found");
320
- const o = U(n, s, a), l = V(t, o);
321
- let h = N;
398
+ if (o.kind === A.ONE_TO_MANY || o.kind === A.MANY_TO_MANY) {
399
+ const f = r.relationMap.get(o.mappedProperty);
400
+ f && (c = { metadata: r, relation: f });
401
+ } else (o.kind === A.MANY_TO_ONE || o.kind === A.ONE_TO_ONE) && (c = { metadata: r, relation: o });
402
+ if (!c) throw new O("mappedRelation not found");
403
+ const a = K(n, s, o), l = V(t, a);
404
+ let u = b;
322
405
  if (i > 0) {
323
- const d = n[i - 1], u = U(n, s, d.relation);
324
- h = V(t, u);
406
+ const f = n[i - 1], d = K(n, s, f.relation);
407
+ u = V(t, d);
325
408
  }
326
- switch (a.kind) {
409
+ switch (o.kind) {
327
410
  case A.ONE_TO_MANY:
328
- yt(t, c, l, h);
411
+ yt(
412
+ t,
413
+ c,
414
+ l,
415
+ u
416
+ );
329
417
  break;
330
418
  case A.ONE_TO_ONE:
331
419
  case A.MANY_TO_ONE:
332
- gt(t, c, l, h, a);
420
+ gt(
421
+ t,
422
+ c,
423
+ l,
424
+ u,
425
+ o
426
+ );
333
427
  break;
334
428
  case A.MANY_TO_MANY:
335
- $t(e, t, c, l, h, a);
429
+ Nt(
430
+ e,
431
+ t,
432
+ c,
433
+ l,
434
+ u,
435
+ o
436
+ );
336
437
  break;
337
438
  }
338
439
  });
339
440
  }, yt = (e, t, n, s) => {
340
- const r = H(e, t.metadata), a = `"${n}".${t.relation.name}Id = ${ae(s)}.id`;
341
- r.find((c) => c.joinTableName === n && c.on === a) || r.push({
441
+ const r = H(e, t.metadata), o = `"${n}".${t.relation.columnName} = ${ae(s)}.id`;
442
+ r.find((c) => c.joinTableName === n && c.on === o) || r.push({
342
443
  joinTableName: n,
343
- on: a
444
+ on: o
344
445
  });
345
446
  }, gt = (e, t, n, s, r) => {
346
- const a = H(e, t.metadata), i = `"${n}".id = ${ae(s)}.${r.name}Id`;
347
- a.find((o) => o.joinTableName === n && o.on === i) || a.push({
447
+ const o = H(e, t.metadata), i = `"${n}".id = ${ae(s)}.${r.columnName}`;
448
+ o.find((a) => a.joinTableName === n && a.on === i) || o.push({
348
449
  joinTableName: n,
349
450
  on: i
350
451
  });
351
- }, $t = (e, t, n, s, r, a) => {
352
- const i = w(a.junctionEntityType), c = H(t, i), o = be(t, `${a.name}_m_n`), l = `"${o}".${n.relation.name}Id = ${ae(r)}.id`;
452
+ }, Nt = (e, t, n, s, r, o) => {
453
+ const i = w(o.junctionEntityType), c = H(t, i), a = Ae(t, `${o.name}_m_n`), l = `"${a}".${n.relation.columnName} = ${ae(r)}.id`;
353
454
  c.find(
354
- (f) => f.joinTableName === o && f.on === l
455
+ (h) => h.joinTableName === a && h.on === l
355
456
  ) || c.push({
356
- joinTableName: o,
457
+ joinTableName: a,
357
458
  on: l
358
459
  });
359
- const d = H(t, n.metadata), u = `"${s}".id = "${o}".${a.name}Id`;
360
- d.find((f) => f.joinTableName === s && f.on === u) || d.push({
460
+ const f = H(t, n.metadata), d = `"${s}".id = "${a}".${o.columnName}`;
461
+ f.find((h) => h.joinTableName === s && h.on === d) || f.push({
361
462
  joinTableName: s,
362
- on: u
463
+ on: d
363
464
  });
364
- }, H = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), be = (e, t) => {
465
+ }, H = (e, t) => (e.joinMap.has(t) || e.joinMap.set(t, []), e.joinMap.get(t)), Ae = (e, t) => {
365
466
  let n = t, s = 1;
366
467
  for (; e.usedAliases.has(n); )
367
468
  n = `${t}_${s}`, s++;
368
469
  return e.usedAliases.add(n), n;
369
- }, Tt = (e) => {
470
+ }, $t = (e, t) => {
370
471
  if (e?.length)
371
- return e.map((t) => `${N}."${t.field}" ${t.sort}`).join(", ");
372
- }, B = (e, t = /* @__PURE__ */ new Map(), n, s) => {
472
+ return e.map((n) => {
473
+ const s = ne(n.field, t);
474
+ return `${b}."${s}" ${n.sort}`;
475
+ }).join(", ");
476
+ }, F = (e, t = /* @__PURE__ */ new Map(), n, s) => {
373
477
  if (!e?.rules) return "";
374
478
  const r = e.rules.map(
375
- (a) => ce(a) ? B(a, t, n, s) : dt(a, t, n, s, B)
479
+ (o) => le(o) ? F(o, t, n, s) : ut(o, t, n, s, F)
376
480
  ).filter(Boolean);
377
- return r.length ? r.length === 1 ? r[0] : `(${r.join(ce(e) ? ` ${e.combinator} ` : " ")})` : "";
481
+ return r.length ? r.length === 1 ? r[0] : `(${r.join(le(e) ? ` ${e.combinator} ` : " ")})` : "";
378
482
  }, Re = (e) => {
379
- const { tableName: t, where: n, limit: s, offset: r, orderBy: a, join: i, hasJoin: c, metadata: o } = e;
380
- let l = `${N}.rowid as ${L}, ${N}.*`;
381
- o.features?.tree?.hasChildren && o.features?.tree?.type === "adjacency-list" && (l += `, EXISTS(SELECT 1 FROM "${t}" __sub WHERE __sub."parentId" = ${N}."id") AS "hasChildren"`);
382
- const h = [`SELECT ${c ? "DISTINCT " : ""}${l} FROM "${t}" ${N}`];
383
- return i && h.push(i), n && h.push(` WHERE ${n}`), a && h.push(` ORDER BY ${a}`), s && h.push(` LIMIT ${s}`), r && h.push(` OFFSET ${r}`), h.join("") + ";";
483
+ const { tableName: t, where: n, limit: s, offset: r, orderBy: o, join: i, hasJoin: c, metadata: a } = e;
484
+ let l = `${b}.rowid as ${L}, ${b}.*`;
485
+ if (a.features?.tree?.hasChildren && a.features?.tree?.type === "adjacency-list") {
486
+ const d = a.relationMap.get("parent").columnName;
487
+ l += `, EXISTS(SELECT 1 FROM "${t}" __sub WHERE __sub."${d}" = ${b}."id") AS "hasChildren"`;
488
+ }
489
+ const u = [`SELECT ${c ? "DISTINCT " : ""}${l} FROM "${t}" ${b}`];
490
+ return i && u.push(i), n && u.push(` WHERE ${n}`), o && u.push(` ORDER BY ${o}`), s && u.push(` LIMIT ${s}`), r && u.push(` OFFSET ${r}`), u.join("") + ";";
384
491
  }, Ie = (e, t, n) => {
385
492
  const s = {
386
493
  joinMap: /* @__PURE__ */ new Map(),
@@ -388,27 +495,27 @@ const re = (e, t) => {
388
495
  fieldAliasMap: /* @__PURE__ */ new Map(),
389
496
  relationAliasMap: /* @__PURE__ */ new Map()
390
497
  };
391
- He(n, (a, i, c) => {
392
- const o = i;
393
- a !== "field" || !o.includes(".") || Nt(e, s, t, o, c);
498
+ Ve(n, (o, i, c) => {
499
+ const a = i;
500
+ o !== "field" || !a.includes(".") || wt(e, s, t, a, c);
394
501
  });
395
502
  const r = [];
396
- for (const [a, i] of s.joinMap.entries()) {
397
- const c = S(a);
398
- for (const o of i)
399
- r.push(` LEFT JOIN "${c}" "${o.joinTableName}" ON ${o.on}`);
503
+ for (const [o, i] of s.joinMap.entries()) {
504
+ const c = S(o);
505
+ for (const a of i)
506
+ r.push(` LEFT JOIN "${c}" "${a.joinTableName}" ON ${a.on}`);
400
507
  }
401
508
  return { joinSQL: r.join(""), fieldAliasMap: s.fieldAliasMap };
402
- }, wt = (e, t, n, s) => {
509
+ }, Tt = (e, t, n, s) => {
403
510
  if (s.length <= 1) return !1;
404
- const [r, ...a] = s, i = t.propertyMap.get(r);
405
- if (i && i.type === y.keyValue && a.length > 0) {
406
- const c = a.join(".");
407
- return e.fieldAliasMap.set(n, `json_extract(${N}."${r}", '$.${c}')`), !0;
511
+ const [r, ...o] = s, i = t.propertyMap.get(r);
512
+ if (i && i.type === y.keyValue && o.length > 0) {
513
+ const c = o.join(".");
514
+ return e.fieldAliasMap.set(n, `json_extract(${b}."${i.columnName}", '$.${c}')`), !0;
408
515
  }
409
516
  return !1;
410
- }, Nt = (e, t, n, s, r) => {
411
- const a = s.split(".");
517
+ }, wt = (e, t, n, s, r) => {
518
+ const o = s.split(".");
412
519
  try {
413
520
  const i = e.rxdb.schemaManager.getFieldRelations(n, s);
414
521
  if (i.isForeignKey) {
@@ -416,109 +523,103 @@ const re = (e, t) => {
416
523
  return;
417
524
  }
418
525
  const c = s.replace(`.${i.propertyName}`, "");
419
- Ae(e, t, i.relations, c);
420
- const o = i.relations[i.relations.length - 1];
421
- if (e.rxdb.schemaManager.findMappedRelation(
422
- o.metadata,
423
- o.relation
424
- )) {
425
- const h = U(i.relations, c, o.relation), d = V(t, h);
426
- t.fieldAliasMap.set(s, `"${d}"."${i.propertyName}"`);
427
- }
526
+ Se(e, t, i.relations, c);
527
+ const a = i.relations[i.relations.length - 1], l = K(i.relations, c, a.relation), u = V(t, l);
528
+ t.fieldAliasMap.set(s, `"${u}"."${i.property.columnName}"`);
428
529
  return;
429
530
  } catch {
430
531
  }
431
- wt(t, n, s, a) || mt(e, t, n, s, a);
432
- }, St = (e, t) => {
532
+ Tt(t, n, s, o) || _t(e, t, n, s, o);
533
+ }, bt = (e, t) => {
433
534
  const n = S(e), s = [t.id];
434
535
  return {
435
536
  sql: `DELETE FROM "${n}" WHERE id = ?;`,
436
537
  params: s
437
538
  };
438
539
  }, Oe = (e, t, n) => {
439
- const s = S(e), r = Ne(e, t);
540
+ const s = S(e), r = we(e, t);
440
541
  n?.userId && (e.propertyMap.has("createdBy") && (r.createdBy = n.userId), e.propertyMap.has("updatedBy") && (r.updatedBy = n.userId));
441
- const a = /* @__PURE__ */ new Date();
442
- e.propertyMap.has("createdAt") && r.createdAt === void 0 && (r.createdAt = n?.createdAt ?? a), e.propertyMap.has("updatedAt") && r.updatedAt === void 0 && (r.updatedAt = n?.updatedAt ?? a);
443
- const i = Object.keys(r), c = re(e, r), o = Array(i.length).fill("?").join(","), l = Object.values(c);
444
- let d = `${n?.useReplace ? "INSERT OR REPLACE" : "INSERT"} INTO "${s}" (${i.join(",")}) VALUES (${o})`;
445
- return n?.returning !== !1 ? d += ` RETURNING rowid as ${L}, *;` : d += ";", {
446
- sql: d,
542
+ const o = /* @__PURE__ */ new Date();
543
+ e.propertyMap.has("createdAt") && r.createdAt === void 0 && (r.createdAt = n?.createdAt ?? o), e.propertyMap.has("updatedAt") && r.updatedAt === void 0 && (r.updatedAt = n?.updatedAt ?? o);
544
+ const i = oe(e, r), c = Object.keys(i), a = Array(c.length).fill("?").join(","), l = Object.values(i);
545
+ let f = `${n?.useReplace ? "INSERT OR REPLACE" : "INSERT"} INTO "${s}" (${c.join(",")}) VALUES (${a})`;
546
+ return n?.returning !== !1 ? f += ` RETURNING rowid as ${L}, *;` : f += ";", {
547
+ sql: f,
447
548
  params: l
448
549
  };
449
- }, oe = (e, t, n, s) => {
550
+ }, ie = (e, t, n, s) => {
450
551
  const r = nt(e, n);
451
552
  e.propertyMap.has("updatedAt") && (r.updatedAt = s?.updatedAt ?? /* @__PURE__ */ new Date()), s?.userId && e.propertyMap.has("updatedBy") && (r.updatedBy = s.userId);
452
- const a = re(e, r), i = Object.keys(r).map((u) => `${u} = ?`).join(","), c = [...Object.values(a)], o = S(e), l = Array.isArray(t), h = l ? t : [t];
453
- let d = `UPDATE "${o}" SET ${i} WHERE id `;
454
- return l ? d += `in (${h.map((u) => R(u.id)).join(",")})` : (c.push(t.id), d += "= ?"), s?.returning !== !1 ? d += ` RETURNING rowid as ${L}, *;` : d += ";", {
455
- sql: d,
553
+ const o = oe(e, r), i = Object.keys(o).map((d) => `${d} = ?`).join(","), c = [...Object.values(o)], a = S(e), l = Array.isArray(t), u = l ? t : [t];
554
+ let f = `UPDATE "${a}" SET ${i} WHERE id `;
555
+ return l ? f += `in (${u.map((d) => R(d.id)).join(",")})` : (c.push(t.id), f += "= ?"), s?.returning !== !1 ? f += ` RETURNING rowid as ${L}, *;` : f += ";", {
556
+ sql: f,
456
557
  params: c
457
558
  };
458
- }, At = (e, t, n) => {
559
+ }, St = (e, t, n) => {
459
560
  if (n.groupBy)
460
- throw new b("groupBy not supported yet");
461
- const { joinSQL: s, fieldAliasMap: r } = Ie(e, t, n.where), a = S(t), i = B(n.where, r, t, e), c = [`SELECT COUNT(${N}.rowid) AS count FROM "${a}" ${N}`];
561
+ throw new O("groupBy not supported yet");
562
+ const { joinSQL: s, fieldAliasMap: r } = Ie(e, t, n.where), o = S(t), i = F(n.where, r, t, e), c = [`SELECT COUNT(${b}.rowid) AS count FROM "${o}" ${b}`];
462
563
  return s && c.push(s), i && c.push(` WHERE ${i}`), { sql: c.join("") };
463
- }, te = (e, t, n) => {
564
+ }, se = (e, t, n) => {
464
565
  const { joinSQL: s, fieldAliasMap: r } = Ie(e, t, n.where);
465
566
  return { sql: Re({
466
567
  tableName: S(t),
467
- where: B(n.where, r, t, e),
468
- orderBy: Tt(n.orderBy),
568
+ where: F(n.where, r, t, e),
569
+ orderBy: $t(n.orderBy, t),
469
570
  join: s,
470
571
  hasJoin: !!s,
471
572
  metadata: t,
472
573
  limit: n.limit,
473
574
  offset: n.offset
474
575
  }) };
475
- }, bt = (e, t) => ({ sql: Re({
576
+ }, At = (e, t) => ({ sql: Re({
476
577
  tableName: S(e),
477
578
  where: `${L} IN (${t.join(",")})`,
478
579
  metadata: e
479
580
  }) }), Q = (e, t, n, s = !1) => {
480
- const r = [], a = w(t), i = e.rxdb.entityManager;
481
- return n.results.forEach(({ columns: c, rows: o }) => {
482
- const l = c.findIndex((d) => d === "id"), h = c.findIndex((d) => d === L);
483
- o.forEach((d) => {
484
- const u = d[l];
581
+ const r = [], o = w(t), i = e.rxdb.entityManager;
582
+ return n.results.forEach(({ columns: c, rows: a }) => {
583
+ const l = c.findIndex((f) => f === "id"), u = c.findIndex((f) => f === L);
584
+ a.forEach((f) => {
585
+ const d = f[l];
485
586
  let p;
486
- if (e.rxdb.entityManager.hasEntityRef(t, u)) {
487
- p = i.getEntityRef(t, u);
488
- const E = ee(a, c, d);
489
- if (a.computedPropertyMap.forEach((g, $) => {
490
- $ in E && (p[$] = E[$]);
587
+ if (e.rxdb.entityManager.hasEntityRef(t, d)) {
588
+ p = i.getEntityRef(t, d);
589
+ const m = te(o, c, f);
590
+ if (o.computedPropertyMap.forEach((N, g) => {
591
+ g in m && (p[g] = m[g]);
491
592
  }), s) {
492
- const g = C(p);
493
- g.origin = { ...E }, Object.assign(p, E);
593
+ const N = j(p);
594
+ N.origin = { ...m }, Object.assign(p, m);
494
595
  }
495
596
  } else {
496
- const E = ee(a, c, d);
497
- p = i.createEntityRef(t, E);
597
+ const m = te(o, c, f);
598
+ p = i.createEntityRef(t, m);
498
599
  }
499
600
  r.push(p);
500
- const _ = C(p);
501
- if (_.local = !0, _.modified = !1, h !== -1) {
502
- const E = BigInt(d[h]);
503
- e.cacheRowIdEntity(E, p);
601
+ const E = j(p);
602
+ if (E.local = !0, E.modified = !1, u !== -1) {
603
+ const m = BigInt(f[u]);
604
+ e.cacheRowIdEntity(m, p);
504
605
  }
505
606
  });
506
607
  }), r;
507
608
  }, Rt = (e, t, n) => {
508
609
  n.forEach((s) => {
509
610
  if (e.rxdb.entityManager.hasEntityRef(t, s)) {
510
- const r = e.rxdb.entityManager.getEntityRef(t, s), a = C(r);
511
- a.local = !1, a.removed = !0, a.modified = !1;
611
+ const r = e.rxdb.entityManager.getEntityRef(t, s), o = j(r);
612
+ o.local = !1, o.removed = !0, o.modified = !1;
512
613
  }
513
614
  });
514
615
  };
515
- class It extends je {
616
+ class It extends De {
516
617
  constructor(t, n) {
517
618
  super(t.rxdb, n), this.adapter = t, this.metadata = w(n);
518
619
  }
519
620
  metadata;
520
621
  async findByRowIds(t) {
521
- const { sql: n, params: s } = bt(this.metadata, t), r = await this.adapter.query(n, s);
622
+ const { sql: n, params: s } = At(this.metadata, t), r = await this.adapter.query(n, s);
522
623
  return this.addQueryCache(r);
523
624
  }
524
625
  /**
@@ -530,7 +631,7 @@ class It extends je {
530
631
  return Q(this.adapter, this.EntityType, t, n);
531
632
  }
532
633
  }
533
- class Me extends It {
634
+ class Ce extends It {
534
635
  async get(t) {
535
636
  const n = {
536
637
  where: {
@@ -538,18 +639,18 @@ class Me extends It {
538
639
  rules: [{ field: "id", operator: "=", value: t }]
539
640
  }
540
641
  }, s = await this.findOne(n);
541
- if (!s) throw new b(`Entity (${t}) not found`);
642
+ if (!s) throw new O(`Entity (${t}) not found`);
542
643
  return s;
543
644
  }
544
645
  async findOne(t) {
545
646
  return (await this.find({ ...t, limit: 1, offset: 0 }))[0];
546
647
  }
547
648
  async find(t) {
548
- const { sql: n, params: s } = te(this.adapter, this.metadata, t), r = await this.adapter.query(n, s);
649
+ const { sql: n, params: s } = se(this.adapter, this.metadata, t), r = await this.adapter.query(n, s);
549
650
  return this.addQueryCache(r);
550
651
  }
551
652
  async count(t) {
552
- const { sql: n, params: s } = At(this.adapter, this.metadata, t);
653
+ const { sql: n, params: s } = St(this.adapter, this.metadata, t);
553
654
  return (await this.adapter.query(n, s)).results[0].rows[0][0];
554
655
  }
555
656
  async create(t) {
@@ -557,22 +658,22 @@ class Me extends It {
557
658
  return this.addQueryCache(r, !0), t;
558
659
  }
559
660
  async update(t, n) {
560
- const { sql: s, params: r } = oe(this.metadata, t, n, this.rxdb.context), a = await this.adapter.query(s, r);
561
- return this.addQueryCache(a, !0), t;
661
+ const { sql: s, params: r } = ie(this.metadata, t, n, this.rxdb.context), o = await this.adapter.query(s, r);
662
+ return this.addQueryCache(o, !0), t;
562
663
  }
563
664
  async remove(t) {
564
- const n = C(t), s = () => {
665
+ const n = j(t), s = () => {
565
666
  n.origin = structuredClone({ ...t }), n.modified = !1, n.removed = !0;
566
667
  };
567
668
  if (n.local === !0) {
568
- const { sql: a, params: i } = St(this.metadata, t);
569
- return await this.adapter.query(a, i), s(), t;
669
+ const { sql: o, params: i } = bt(this.metadata, t);
670
+ return await this.adapter.query(o, i), s(), t;
570
671
  }
571
672
  const r = w(t);
572
- throw new b(`Remove Error${r.name}(${t.id}) not saved local.`);
673
+ throw new O(`Remove Error${r.name}(${t.id}) not saved local.`);
573
674
  }
574
675
  }
575
- var v = /* @__PURE__ */ ((e) => (e[e.SQLITE_DELETE = 9] = "SQLITE_DELETE", e[e.SQLITE_INSERT = 18] = "SQLITE_INSERT", e[e.SQLITE_UPDATE = 23] = "SQLITE_UPDATE", e))(v || {});
676
+ var x = /* @__PURE__ */ ((e) => (e[e.SQLITE_DELETE = 9] = "SQLITE_DELETE", e[e.SQLITE_INSERT = 18] = "SQLITE_INSERT", e[e.SQLITE_UPDATE = 23] = "SQLITE_UPDATE", e))(x || {});
576
677
  const Ot = (e) => {
577
678
  switch (e) {
578
679
  case 18:
@@ -582,7 +683,7 @@ const Ot = (e) => {
582
683
  case 23:
583
684
  return "UPDATE";
584
685
  }
585
- }, Mt = "sqlite", Lt = () => import("wa-sqlite/dist/wa-sqlite-async.mjs").then((e) => e.default), Ct = () => import("wa-sqlite/dist/wa-sqlite.mjs").then((e) => e.default), vt = [
686
+ }, Ct = "sqlite", Mt = () => import("wa-sqlite/dist/wa-sqlite-async.mjs").then((e) => e.default), Lt = () => import("wa-sqlite/dist/wa-sqlite.mjs").then((e) => e.default), jt = [
586
687
  {
587
688
  name: "MemoryVFS",
588
689
  vfsModule: () => import("wa-sqlite/src/examples/MemoryVFS.js").then((e) => e.MemoryVFS),
@@ -666,61 +767,63 @@ const Ot = (e) => {
666
767
  jsContext: !1,
667
768
  multipleConnections: !0
668
769
  }
669
- ], Le = (e) => {
670
- const t = vt.find((a) => a.name === e.vfs), { vfs: n, async: s, worker: r } = e;
671
- if (!t) throw new b(`vfs ${n} not found`);
770
+ ], Me = (e) => {
771
+ const t = jt.find((o) => o.name === e.vfs), { vfs: n, async: s, worker: r } = e;
772
+ if (!t) throw new O(`vfs ${n} not found`);
672
773
  if (s !== void 0) {
673
774
  if (s && !t.async)
674
- throw new b(`vfs ${n} not support async: true`);
775
+ throw new O(`vfs ${n} not support async: true`);
675
776
  if (!s && !t.sync)
676
- throw new b(`vfs ${n} not support async: false`);
777
+ throw new O(`vfs ${n} not support async: false`);
677
778
  }
678
- if (r && !t.worker) throw new b(`vfs ${n} not support worker`);
679
- if (!r && !t.jsContext) throw new b(`vfs ${n} only support worker`);
779
+ if (r && !t.worker) throw new O(`vfs ${n} not support worker`);
780
+ if (!r && !t.jsContext) throw new O(`vfs ${n} only support worker`);
680
781
  return t;
681
- }, qt = async (e) => {
682
- const t = Le(e), n = e.async ?? !0;
782
+ }, xt = async (e) => {
783
+ const t = Me(e), n = e.async ?? !0;
683
784
  let s;
684
- n ? s = Lt : s = Ct;
685
- const [r, a] = await Promise.all([s(), t.vfsModule()]), i = {};
785
+ n ? s = Mt : s = Lt;
786
+ const [r, o] = await Promise.all([s(), t.vfsModule()]), i = {};
686
787
  e.locateFile ? i.locateFile = e.locateFile : e.wasmPath && (i.locateFile = () => e.wasmPath);
687
- const c = await r(i), o = Ye(c), l = await a.create(e.vfs, c, t.vfsOptions);
688
- return o.vfs_register(l, !0), o;
689
- }, xt = async (e, t, n, s) => {
690
- const r = performance.now(), a = s ? [s] : [[]], i = [];
788
+ const c = await r(i), a = Ye(c), l = await o.create(e.vfs, c, t.vfsOptions);
789
+ return a.vfs_register(l, !0), a;
790
+ };
791
+ async function vt(e, t, n, s) {
792
+ const r = performance.now(), o = s ? [s] : [[]], i = [];
691
793
  let c = 0;
692
- const o = {
794
+ const a = {
693
795
  sql: n,
694
796
  results: i
695
797
  };
696
798
  for await (const l of e.statements(t, n)) {
697
799
  if (s)
698
- for (const u of a)
699
- e.reset(l), e.bind_collection(l, u);
700
- const h = [];
800
+ for (const d of o)
801
+ e.reset(l), e.bind_collection(l, d);
802
+ const u = [];
701
803
  for (; await e.step(l) === Xe; ) {
702
- const u = e.row(l);
703
- h.push(u);
804
+ const d = e.row(l);
805
+ u.push(d);
704
806
  }
705
- const d = e.column_names(l);
706
- d.length && i.push({ columns: d, rows: h }), c += e.changes(t);
807
+ const f = e.column_names(l);
808
+ f.length && i.push({ columns: f, rows: u }), c += e.changes(t);
707
809
  }
708
810
  return {
709
- ...o,
811
+ ...a,
710
812
  rowsAffected: c,
711
813
  elapsed: performance.now() - r
712
814
  };
713
- }, Dt = {
815
+ }
816
+ const qt = {
714
817
  BALANCED: 16
715
- }, Ee = Dt.BALANCED, jt = 50 * 1024, Ft = /* @__PURE__ */ new Set(["public$RxDBChange", "public$RxDBBranch", "public$RxDBMigration"]);
716
- class Pt extends Qe {
818
+ }, Ee = qt.BALANCED, Dt = 50 * 1024, kt = /* @__PURE__ */ new Set(["public$rxdb_change", "public$rxdb_branch", "public$rxdb_migration"]);
819
+ class Pt extends He {
717
820
  #n;
718
821
  #e;
719
822
  #r = !1;
720
823
  #s = !1;
721
824
  #c;
722
- #a = [];
723
- #o;
825
+ #o = [];
826
+ #a;
724
827
  #t = Ee;
725
828
  /**
726
829
  * 初始化数据库
@@ -731,15 +834,15 @@ class Pt extends Qe {
731
834
  async init(t, n) {
732
835
  if (this.#r) return;
733
836
  this.#r = !0, this.#c = new ge(1);
734
- const s = await qt(n), r = `${t}.sqlite`;
735
- this.#e = await s.open_v2(r), this.#n = s, this.#d(s, this.#e), this.#t = n?.batchTimeout ?? Ee;
736
- const a = n?.cacheSizeKb ?? jt;
837
+ const s = await xt(n), r = `${t}.sqlite`;
838
+ this.#e = await s.open_v2(r), this.#n = s, this.#u(s, this.#e), this.#t = n?.batchTimeout ?? Ee;
839
+ const o = n?.cacheSizeKb ?? Dt;
737
840
  await this.execute(`
738
841
  PRAGMA temp_store = memory;
739
842
  PRAGMA foreign_keys = ON;
740
- PRAGMA cache_size = -${a};
741
- `), this.#n.update_hook(this.#e, (i, c, o, l) => {
742
- !c || !o || !Ft.has(o) || (this.#a.push({ type: i, dbName: c, tableName: o, rowId: l }), this.#i());
843
+ PRAGMA cache_size = -${o};
844
+ `), this.#n.update_hook(this.#e, (i, c, a, l) => {
845
+ !c || !a || !kt.has(a) || (this.#o.push({ type: i, dbName: c, tableName: a, rowId: l }), this.#i());
743
846
  });
744
847
  }
745
848
  /**
@@ -749,7 +852,7 @@ class Pt extends Qe {
749
852
  */
750
853
  async version() {
751
854
  const t = await this.execute("SELECT sqlite_version()");
752
- return Ke(t, "results[0].rows[0][0]");
855
+ return Qe(t, "results[0].rows[0][0]");
753
856
  }
754
857
  /**
755
858
  * 断开数据库连接
@@ -780,15 +883,15 @@ class Pt extends Qe {
780
883
  async execute(t, n) {
781
884
  if (this.#s)
782
885
  throw new Error("SqliteClient has been disconnected");
783
- return this.#c.addTask(() => xt(this.#n, this.#e, t, n));
886
+ return this.#c.addTask(() => vt(this.#n, this.#e, t, n));
784
887
  }
785
888
  /**
786
889
  * 调度批量发送
787
890
  * 使用防抖机制合并连续的变更事件
788
891
  */
789
892
  #i() {
790
- this.#o && clearTimeout(this.#o), this.#o = setTimeout(() => {
791
- this.#l(), this.#o = void 0;
893
+ this.#a && clearTimeout(this.#a), this.#a = setTimeout(() => {
894
+ this.#l(), this.#a = void 0;
792
895
  }, this.#t);
793
896
  }
794
897
  /**
@@ -796,7 +899,7 @@ class Pt extends Qe {
796
899
  * 将同类型、同表的事件合并后分发
797
900
  */
798
901
  #l() {
799
- const t = Object.groupBy(this.#a, (n) => `${n.type}_${n.dbName}_${n.tableName}`);
902
+ const t = Object.groupBy(this.#o, (n) => `${n.type}_${n.dbName}_${n.tableName}`);
800
903
  for (const n of Object.values(t)) {
801
904
  if (!n || n.length === 0) continue;
802
905
  const s = n[0];
@@ -808,7 +911,7 @@ class Pt extends Qe {
808
911
  recordAt: /* @__PURE__ */ new Date()
809
912
  });
810
913
  }
811
- this.#a.length = 0;
914
+ this.#o.length = 0;
812
915
  }
813
916
  /**
814
917
  * 注册自定义 SQL 函数
@@ -817,143 +920,152 @@ class Pt extends Qe {
817
920
  * - `regexp(pattern, text)` - 正则匹配
818
921
  * - `regexp_replace(pattern, text, replacement[, flags])` - 正则替换
819
922
  */
820
- #d(t, n) {
821
- Bt(t, n), kt(t, n);
923
+ #u(t, n) {
924
+ Ft(t, n), Bt(t, n);
822
925
  }
823
926
  }
824
- function Bt(e, t) {
825
- e.create_function(t, "regexp", 2, Te | we, 0, (n, s) => {
826
- const r = new RegExp(e.value_text(s[0])), a = e.value_text(s[1]);
827
- e.result(n, r.test(a) ? 1 : 0);
927
+ function Ft(e, t) {
928
+ e.create_function(t, "regexp", 2, $e | Te, 0, (n, s) => {
929
+ try {
930
+ const r = new RegExp(e.value_text(s[0])), o = e.value_text(s[1]);
931
+ e.result(n, r.test(o) ? 1 : 0);
932
+ } catch {
933
+ e.result(n, 0);
934
+ }
828
935
  });
829
936
  }
830
- function kt(e, t) {
831
- e.create_function(t, "regexp_replace", -1, Te | we, 0, (n, s) => {
937
+ function Bt(e, t) {
938
+ e.create_function(t, "regexp_replace", -1, $e | Te, 0, (n, s) => {
832
939
  if (s.length < 3) {
833
940
  e.result(n, "");
834
941
  return;
835
942
  }
836
- const r = e.value_text(s[0]), a = e.value_text(s[1]), i = e.value_text(s[2]), c = s.length > 3 ? e.value_text(s[3]) : "";
837
- e.result(n, a.replace(new RegExp(r, c), i));
943
+ try {
944
+ const r = e.value_text(s[0]), o = e.value_text(s[1]), i = e.value_text(s[2]), c = s.length > 3 ? e.value_text(s[3]) : "";
945
+ e.result(n, o.replace(new RegExp(r, c), i));
946
+ } catch {
947
+ e.result(n, e.value_text(s[1]));
948
+ }
838
949
  });
839
950
  }
840
- const Wt = async (e, t) => {
841
- const { vfs: n, async: s, worker: r, wasmPath: a, locateFile: i, workerInstance: c, sharedWorkerInstance: o, sharedWorker: l } = t, h = {
951
+ async function Wt(e, t) {
952
+ const { vfs: n, async: s, worker: r, wasmPath: o, locateFile: i, workerInstance: c, sharedWorkerInstance: a, sharedWorker: l } = t, u = {
842
953
  vfs: n,
843
954
  async: s,
844
955
  worker: r,
845
- wasmPath: a,
956
+ wasmPath: o,
846
957
  locateFile: i
847
958
  };
848
- Le(h);
849
- let d;
850
- return r && c ? d = ue(c) : l && o ? d = ue(o.port) : d = new Pt(), await d.init(e, h), d;
851
- }, Ut = (e, t) => t.map((n) => {
959
+ Me(u);
960
+ let f;
961
+ return r && c ? f = fe(c) : l && a ? f = fe(a.port) : f = new Pt(), await f.init(e, u), f;
962
+ }
963
+ const Ut = (e, t) => t.map((n) => {
852
964
  const s = e.rxdb.schemaManager.getEntityMetadata(n.entity, n.namespace);
853
965
  return s ? (n.inversePatch && Object.keys(n.inversePatch).forEach((r) => {
854
- const a = s.propertyMap.get(r);
855
- a && (n.inversePatch[r] = D(n.inversePatch[r], a));
966
+ const o = s.propertyMap.get(r);
967
+ o && (n.inversePatch[r] = v(n.inversePatch[r], o));
856
968
  }), n.patch && Object.keys(n.patch).forEach((r) => {
857
- const a = s.propertyMap.get(r);
858
- a && (n.patch[r] = D(n.patch[r], a));
969
+ const o = s.propertyMap.get(r);
970
+ o && (n.patch[r] = v(n.patch[r], o));
859
971
  })) : console.warn(`Entity metadata not found for ${n.namespace}.${n.entity}`), n;
860
- }), Vt = (e, t) => {
972
+ }), Kt = (e, t) => {
861
973
  const n = Object.groupBy(t, (r) => r.type), s = Object.entries(n);
862
974
  for (let r = 0; r < s.length; r++) {
863
- const [a, i] = s[r];
975
+ const [o, i] = s[r];
864
976
  if (!i || i.length === 0) continue;
865
- const c = i.map((o) => ({
866
- namespace: o.namespace,
867
- entity: o.entity,
868
- type: o.type,
869
- id: o.entityId,
870
- patch: o.patch,
871
- inversePatch: o.inversePatch,
872
- recordAt: o.createdAt
977
+ const c = i.map((a) => ({
978
+ namespace: a.namespace,
979
+ entity: a.entity,
980
+ type: a.type,
981
+ id: a.entityId,
982
+ patch: a.patch,
983
+ inversePatch: a.inversePatch,
984
+ recordAt: a.createdAt
873
985
  }));
874
- switch (a) {
986
+ switch (o) {
875
987
  case "INSERT":
876
988
  e.rxdb.dispatchEvent(
877
- new k(c)
989
+ new B(c)
878
990
  );
879
991
  break;
880
992
  case "UPDATE":
881
993
  e.rxdb.dispatchEvent(
882
- new K(c)
994
+ new G(c)
883
995
  );
884
996
  break;
885
997
  case "DELETE":
886
998
  e.rxdb.dispatchEvent(
887
- new ne(c)
999
+ new re(c)
888
1000
  );
889
1001
  break;
890
1002
  }
891
1003
  }
892
- }, Ht = (e, t) => {
893
- const { tableName: n } = t, [s, r] = tt(n), a = e.rxdb.schemaManager.getEntityType(r, s);
894
- if (!a) return;
895
- const i = e.getRepository(a), c = w(a), o = w(F);
1004
+ }, Vt = (e, t) => {
1005
+ const { tableName: n } = t, [s, r] = tt(n), o = e.rxdb.schemaManager.getEntityTypeByTableName(r, s);
1006
+ if (!o) return;
1007
+ const i = e.getRepository(o), c = w(o), a = w(k);
896
1008
  i.findByRowIds(t.rowIds).then((l) => {
897
- let h = l;
898
- if (c === o) {
899
- if (h = Ut(e, l), t.type === v.SQLITE_INSERT) {
900
- Vt(e, h);
901
- const d = h.map((u) => ({
1009
+ let u = l;
1010
+ if (c === a) {
1011
+ if (u = Ut(e, l), t.type === x.SQLITE_INSERT) {
1012
+ Kt(e, u);
1013
+ const f = u.map((d) => ({
902
1014
  namespace: c.namespace,
903
1015
  entity: c.name,
904
- type: u.type,
905
- id: u.id,
906
- patch: { ...u },
1016
+ type: d.type,
1017
+ id: d.id,
1018
+ patch: { ...d },
907
1019
  inversePatch: null,
908
- recordAt: u.createdAt
1020
+ recordAt: d.createdAt
909
1021
  }));
910
- e.rxdb.dispatchEvent(new k(d));
1022
+ e.rxdb.dispatchEvent(new B(f));
911
1023
  }
912
1024
  } else {
913
- const d = Ot(t.type), u = h.map((p) => {
914
- const f = {
1025
+ const f = Ot(t.type), d = u.map((p) => {
1026
+ const h = {
915
1027
  namespace: c.namespace,
916
1028
  entity: c.name,
917
- type: d,
1029
+ type: f,
918
1030
  id: p.id,
919
1031
  recordAt: p.createdAt || /* @__PURE__ */ new Date()
920
1032
  };
921
1033
  switch (t.type) {
922
- case v.SQLITE_INSERT:
1034
+ case x.SQLITE_INSERT:
923
1035
  return {
924
- ...f,
1036
+ ...h,
925
1037
  patch: { ...p },
926
1038
  inversePatch: null
927
1039
  };
928
- case v.SQLITE_DELETE:
1040
+ case x.SQLITE_DELETE:
929
1041
  return {
930
- ...f,
1042
+ ...h,
931
1043
  patch: null,
932
1044
  inversePatch: { ...p }
933
1045
  };
934
- case v.SQLITE_UPDATE:
1046
+ case x.SQLITE_UPDATE:
935
1047
  return {
936
- ...f,
1048
+ ...h,
937
1049
  // TODO: 这里没有办法拿到变更前的数据,只能把整个 entity 作为 patch 返回, 可能会有问题,先这样处理
938
1050
  inversePatch: null,
939
1051
  patch: { ...p }
940
1052
  };
941
1053
  }
942
1054
  });
943
- switch (d) {
1055
+ switch (f) {
944
1056
  case "UPDATE":
945
1057
  e.rxdb.dispatchEvent(
946
- new K(u)
1058
+ new G(d)
947
1059
  );
948
1060
  break;
949
1061
  case "DELETE":
950
1062
  e.rxdb.dispatchEvent(
951
- new ne(u)
1063
+ new re(d)
952
1064
  );
953
1065
  break;
954
1066
  case "INSERT":
955
1067
  e.rxdb.dispatchEvent(
956
- new k(u)
1068
+ new B(d)
957
1069
  );
958
1070
  break;
959
1071
  }
@@ -961,44 +1073,44 @@ const Wt = async (e, t) => {
961
1073
  }).catch((l) => {
962
1074
  console.error("Failed to handle RxDBChange insert event", l);
963
1075
  });
964
- }, G = (e, t, n) => {
965
- const { isCount: s, isFindDescendants: r, entityId: a, where: i } = n, c = !a, o = S(t);
966
- let l = "";
967
- const d = [`c.__level < ${n.level || 0}`, i && B(i, /* @__PURE__ */ new Map(), t, e)].filter(Boolean).join(" AND ");
968
- d && (l = `WHERE ${d}`);
969
- let u = "__children.*";
970
- s ? c ? u = "count(*)" : u = "count(*)-1" : n.hasChildren && (u += `, EXISTS(SELECT 1 FROM "${o}" __sub WHERE __sub.parentId = __children.id) AS hasChildren`);
971
- const p = c ? "parentId is null" : `id = '${a}'`;
1076
+ }, J = (e, t, n) => {
1077
+ const { isCount: s, isFindDescendants: r, entityId: o, where: i } = n, c = !o, a = S(t), u = t.relationMap.get("parent").columnName;
1078
+ let f = "";
1079
+ const p = [`c.__level < ${n.level || 0}`, i && F(i, /* @__PURE__ */ new Map(), t, e)].filter(Boolean).join(" AND ");
1080
+ p && (f = `WHERE ${p}`);
1081
+ let h = "__children.*";
1082
+ s ? c ? h = "count(*)" : h = "count(*)-1" : n.hasChildren && (h += `, EXISTS(SELECT 1 FROM "${a}" __sub WHERE __sub."${u}" = __children.id) AS hasChildren`);
1083
+ const E = c ? `"${u}" is null` : `id = '${o}'`;
972
1084
  return {
973
1085
  sql: `WITH RECURSIVE __children AS (
974
1086
  SELECT *,rowid as ${L}, 0 AS __level
975
- FROM "${o}"
976
- WHERE ${p}
1087
+ FROM "${a}"
1088
+ WHERE ${E}
977
1089
  UNION ALL
978
1090
  SELECT children.*,children.rowid as ${L}, c.__level + 1 AS __level
979
- FROM "${o}" children
980
- JOIN __children c ON ${r ? "children.parentId = c.id" : "children.id = c.parentId"}
981
- ${l}
1091
+ FROM "${a}" children
1092
+ JOIN __children c ON ${r ? `children."${u}" = c.id` : `children.id = c."${u}"`}
1093
+ ${f}
982
1094
  )
983
1095
 
984
- SELECT ${u} FROM __children ORDER BY __level, id;`
1096
+ SELECT ${h} FROM __children ORDER BY __level, id;`
985
1097
  };
986
- }, Qt = (e, t, n) => G(e, t, {
1098
+ }, Ht = (e, t, n) => J(e, t, {
987
1099
  ...n,
988
1100
  isFindDescendants: !0,
989
1101
  hasChildren: t.features?.tree?.hasChildren
990
- }), Kt = (e, t, n) => G(e, t, { ...n, isFindDescendants: !0, isCount: !0 }), Gt = (e, t, n) => G(e, t, {
1102
+ }), Qt = (e, t, n) => J(e, t, { ...n, isFindDescendants: !0, isCount: !0 }), Gt = (e, t, n) => J(e, t, {
991
1103
  ...n,
992
1104
  isFindDescendants: !1,
993
1105
  hasChildren: t.features?.tree?.hasChildren
994
- }), Jt = (e, t, n) => G(e, t, { ...n, isFindDescendants: !1, isCount: !0 });
995
- class Yt extends Me {
1106
+ }), Jt = (e, t, n) => J(e, t, { ...n, isFindDescendants: !1, isCount: !0 });
1107
+ class Yt extends Ce {
996
1108
  async findDescendants(t) {
997
- const { sql: n } = Qt(this.adapter, this.metadata, t), s = await this.adapter.query(n);
1109
+ const { sql: n } = Ht(this.adapter, this.metadata, t), s = await this.adapter.query(n);
998
1110
  return this.addQueryCache(s, !0);
999
1111
  }
1000
1112
  async countDescendants(t) {
1001
- const { sql: n } = Kt(this.adapter, this.metadata, t);
1113
+ const { sql: n } = Qt(this.adapter, this.metadata, t);
1002
1114
  return (await this.adapter.query(n)).results[0].rows[0][0];
1003
1115
  }
1004
1116
  async findAncestors(t) {
@@ -1011,212 +1123,237 @@ class Yt extends Me {
1011
1123
  }
1012
1124
  }
1013
1125
  const Xt = (e, t) => {
1014
- const n = S(e), s = t.map((r) => `'${r.id}'`).join(",");
1126
+ const n = S(e), s = t.map((r) => R(r.id)).join(",");
1015
1127
  return `DELETE FROM "${n}" WHERE id in (${s});`;
1016
- }, Ce = (e, t, n) => {
1017
- const s = S(e), r = n?.userId && e.propertyMap.has("createdBy"), a = n?.userId && e.propertyMap.has("updatedBy"), i = [...e.propertyMap.keys(), ...e.foreignKeyNames], c = [];
1128
+ }, Le = (e, t, n) => {
1129
+ const s = S(e), r = n?.userId && e.propertyMap.has("createdBy"), o = n?.userId && e.propertyMap.has("updatedBy"), i = [
1130
+ ...Array.from(e.propertyMap.values()).map((l) => l.columnName),
1131
+ ...e.foreignKeyColumnNames || e.foreignKeyNames
1132
+ ], c = [];
1018
1133
  t.forEach((l) => {
1019
- const h = Ne(e, l);
1020
- r && (h.createdBy = n.userId), a && (h.updatedBy = n.userId);
1021
- const d = re(e, h), u = [];
1134
+ const u = we(e, l);
1135
+ r && (u.createdBy = n.userId), o && (u.updatedBy = n.userId);
1136
+ const f = oe(e, u), d = [];
1022
1137
  i.forEach((p) => {
1023
- const f = R(d[p]);
1024
- u.push(f);
1025
- }), c.push(u);
1138
+ const h = R(f[p]);
1139
+ d.push(h);
1140
+ }), c.push(d);
1026
1141
  });
1027
- const o = c.map((l) => `(${l.join(",")})`).join(",");
1028
- return `INSERT INTO "${s}" (${i.join(",")}) VALUES ${o};`;
1142
+ const a = c.map((l) => `(${l.join(",")})`).join(",");
1143
+ return `INSERT INTO "${s}" (${i.join(",")}) VALUES ${a};`;
1029
1144
  }, _e = async (e, t, n) => {
1030
1145
  const s = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Date();
1031
- let a = "";
1146
+ let o = "";
1032
1147
  const i = /* @__PURE__ */ new Set();
1033
- return t.create.forEach((c, o) => {
1148
+ return t.create.forEach((c, a) => {
1034
1149
  const l = Array.from(c);
1035
- l.forEach((E) => i.add(E));
1036
- const h = w(o), d = Ce(h, l, e.rxdb.context), u = l.map((E) => E.id);
1037
- u.forEach((E) => s.set(E, o));
1038
- const { sql: p, params: f } = te(e, h, {
1150
+ l.forEach((m) => i.add(m));
1151
+ const u = w(a), f = Le(u, l, e.rxdb.context), d = l.map((m) => m.id);
1152
+ d.forEach((m) => s.set(m, a));
1153
+ const { sql: p, params: h } = se(e, u, {
1039
1154
  where: {
1040
1155
  combinator: "and",
1041
- rules: [{ field: "id", operator: "in", value: u }]
1156
+ rules: [{ field: "id", operator: "in", value: d }]
1042
1157
  }
1043
- }), _ = P(p, f);
1044
- a += d + _;
1045
- }), t.update.forEach((c, o) => {
1158
+ }), E = P(p, h);
1159
+ o += f + E;
1160
+ }), t.update.forEach((c, a) => {
1046
1161
  const l = Array.from(c);
1047
- l.forEach((u) => i.add(u));
1048
- const h = w(o), d = Object.groupBy(l, (u) => {
1049
- const p = C(u);
1050
- return $e(Object.keys(p.patch).sort());
1162
+ l.forEach((d) => i.add(d));
1163
+ const u = w(a), f = Object.groupBy(l, (d) => {
1164
+ const p = j(d);
1165
+ return Ne(Object.keys(p.patch).sort());
1051
1166
  });
1052
- Object.values(d).forEach((u) => {
1053
- const p = u[0], f = C(p), _ = oe(h, u, f.patch, {
1167
+ Object.values(f).forEach((d) => {
1168
+ const p = d[0], h = j(p), E = ie(u, d, h.patch, {
1054
1169
  ...e.rxdb.context,
1055
1170
  returning: !1,
1056
1171
  updatedAt: r
1057
- }), E = P(_.sql, _.params);
1058
- a += E;
1059
- const g = u.map((m) => m.id);
1060
- g.forEach((m) => s.set(m, o));
1061
- const $ = te(e, h, {
1172
+ }), m = P(E.sql, E.params);
1173
+ o += m;
1174
+ const N = d.map((T) => T.id);
1175
+ N.forEach((T) => s.set(T, a));
1176
+ const g = se(e, u, {
1062
1177
  where: {
1063
1178
  combinator: "and",
1064
- rules: [{ field: "id", operator: "in", value: g }]
1179
+ rules: [{ field: "id", operator: "in", value: N }]
1065
1180
  }
1066
- }), T = P($.sql, $.params);
1067
- a += T;
1181
+ }), $ = P(g.sql, g.params);
1182
+ o += $;
1068
1183
  });
1069
- }), t.remove.forEach((c, o) => {
1070
- const l = Array.from(c), h = w(o), d = Xt(h, l);
1071
- a += d;
1072
- }), a && (await e.query(a)).results.forEach(({ columns: o, rows: l }) => {
1073
- const h = o.findIndex((p) => p === "id"), d = o.findIndex((p) => p === L), u = e.rxdb.entityManager;
1184
+ }), t.remove.forEach((c, a) => {
1185
+ const l = Array.from(c), u = w(a), f = Xt(u, l);
1186
+ o += f;
1187
+ }), o && (await e.query(o)).results.forEach(({ columns: a, rows: l }) => {
1188
+ const u = a.findIndex((p) => p === "id"), f = a.findIndex((p) => p === L), d = e.rxdb.entityManager;
1074
1189
  l.forEach((p) => {
1075
- const f = p[h], _ = s.get(f), E = w(_);
1076
- if (u.hasEntityRef(_, f)) {
1077
- const g = u.getEntityRef(_, f), $ = ee(E, o, p);
1078
- e.getRepository(_).updateEntity(g, $);
1079
- const T = C(g);
1080
- if (T.local = !0, d !== -1) {
1081
- const m = BigInt(p[d]);
1082
- e.cacheRowIdEntity(m, g);
1190
+ const h = p[u], E = s.get(h), m = w(E);
1191
+ if (d.hasEntityRef(E, h)) {
1192
+ const N = d.getEntityRef(E, h), g = te(m, a, p);
1193
+ e.getRepository(E).updateEntity(N, g);
1194
+ const $ = j(N);
1195
+ if ($.local = !0, f !== -1) {
1196
+ const T = BigInt(p[f]);
1197
+ e.cacheRowIdEntity(T, N);
1083
1198
  }
1084
- T.modified = !1;
1199
+ $.modified = !1;
1085
1200
  }
1086
1201
  });
1087
1202
  }), t.remove.forEach(
1088
- (c) => c.forEach((o) => {
1089
- i.add(o);
1090
- const l = C(o);
1091
- l.origin = structuredClone({ ...o }), l.modified = !1, l.removed = !0, l.local = !1;
1203
+ (c) => c.forEach((a) => {
1204
+ i.add(a);
1205
+ const l = j(a);
1206
+ l.origin = structuredClone({ ...a }), l.modified = !1, l.removed = !0, l.local = !1;
1092
1207
  })
1093
1208
  ), Array.from(i);
1094
1209
  }, zt = (e, t) => {
1095
1210
  const n = S(t);
1096
1211
  let s = `CREATE TABLE "${n}" (`;
1097
- const r = [], a = [], i = [];
1098
- t.propertyMap.forEach((o) => {
1099
- let l = `"${o.name}" ${et(o)}`;
1100
- if (o.type === y.integer && o.primary ? l += " PRIMARY KEY AUTOINCREMENT" : (o.type === y.uuid || o.type === y.string) && o.primary && (l += " PRIMARY KEY", o.type === y.uuid && (l += " DEFAULT (lower(hex(randomblob(16))))")), !(o.type === y.uuid && o.primary) && Reflect.get(o, "default") !== void 0) {
1101
- let d = o.default;
1102
- de(o.default) && (d = o.default()), d === "CURRENT_TIMESTAMP" ? l += " DEFAULT(strftime('%FT%H:%M:%fZ'))" : (d = se(d, o), o.type === y.boolean || o.type === y.integer || o.type === y.number ? l += ` DEFAULT ${d}` : l += ` DEFAULT '${d}'`);
1212
+ const r = [], o = [], i = [];
1213
+ t.propertyMap.forEach((a) => {
1214
+ const l = a.columnName;
1215
+ let u = `"${l}" ${et(a)}`;
1216
+ if (a.type === y.integer && a.primary ? u += " PRIMARY KEY AUTOINCREMENT" : (a.type === y.uuid || a.type === y.string) && a.primary && (u += " PRIMARY KEY", a.type === y.uuid && (u += " DEFAULT (lower(hex(randomblob(16))))")), !(a.type === y.uuid && a.primary) && Reflect.get(a, "default") !== void 0) {
1217
+ let d = a.default;
1218
+ de(a.default) && (d = a.default()), d === "CURRENT_TIMESTAMP" ? u += " DEFAULT(strftime('%FT%H:%M:%fZ'))" : (d = U(d, a), a.type === y.boolean || a.type === y.integer || a.type === y.number ? u += ` DEFAULT ${d}` : u += ` DEFAULT '${d}'`);
1103
1219
  }
1104
- switch (o.nullable || (l += " NOT NULL"), o.type) {
1220
+ switch (a.nullable || (u += " NOT NULL"), a.type) {
1105
1221
  case y.json:
1106
1222
  case y.keyValue:
1107
1223
  case y.stringArray:
1108
1224
  case y.numberArray:
1109
- a.push(`CHECK ( JSON_VALID(${o.name})=1 )`);
1225
+ o.push(`CHECK ( JSON_VALID(${l})=1 )`);
1110
1226
  break;
1111
1227
  case y.boolean:
1112
- a.push(`CHECK (${o.name} in(0,1))`);
1228
+ o.push(`CHECK (${l} in(0,1))`);
1113
1229
  break;
1114
1230
  }
1115
- o.unique && r.push(
1116
- `CREATE UNIQUE INDEX ${pe(t, o)} on "${n}"(${o.name});`
1117
- ), i.push(l);
1118
- }), t.relationMap.forEach((o) => {
1119
- if (o.kind === A.ONE_TO_ONE || o.kind === A.MANY_TO_ONE) {
1120
- const l = `${o.name}Id`, h = e.rxdb.schemaManager.getEntityMetadata(
1121
- o.mappedEntity,
1122
- o.mappedNamespace
1231
+ a.unique && r.push(
1232
+ `CREATE UNIQUE INDEX ${he(t, a)} on "${n}"(${l});`
1233
+ ), i.push(u);
1234
+ }), t.relationMap.forEach((a) => {
1235
+ if (a.kind === A.ONE_TO_ONE || a.kind === A.MANY_TO_ONE) {
1236
+ const l = a.columnName, u = e.rxdb.schemaManager.getEntityMetadata(
1237
+ a.mappedEntity,
1238
+ a.mappedNamespace
1123
1239
  );
1124
- let d = "TEXT";
1125
- const u = h.propertyMap.get("id");
1126
- u.type === y.integer ? d = "INTEGER" : (u.type === y.uuid || u.type === y.string) && (d = "TEXT");
1127
- const p = o.onDelete === "SET NULL" || o.onUpdate === "SET NULL";
1128
- let f = `"${l}" ${d}`;
1129
- if (!o.nullable && !p && (f += " NOT NULL"), o.kind === A.MANY_TO_ONE && Reflect.get(o, "default") !== void 0) {
1130
- const _ = o;
1131
- let E = _.default;
1132
- de(_.default) && (E = _.default()), f += ` DEFAULT ${E}`;
1240
+ let f = "TEXT";
1241
+ const d = u.propertyMap.get("id");
1242
+ d.type === y.integer ? f = "INTEGER" : (d.type === y.uuid || d.type === y.string) && (f = "TEXT");
1243
+ const p = a.onDelete === "SET NULL" || a.onUpdate === "SET NULL";
1244
+ let h = `"${l}" ${f}`;
1245
+ if (!a.nullable && !p && (h += " NOT NULL"), a.kind === A.MANY_TO_ONE && Reflect.get(a, "default") !== void 0) {
1246
+ const E = a;
1247
+ let m = E.default;
1248
+ de(E.default) && (m = E.default()), h += ` DEFAULT ${m}`;
1133
1249
  }
1134
- if (o.mappedEntity) {
1135
- const _ = q(o.mappedEntity, o.mappedNamespace);
1136
- f += ` REFERENCES ${_}(id)`, o.onDelete && (f += ` ON DELETE ${o.onDelete}`), o.onUpdate && (f += ` ON UPDATE ${o.onUpdate}`);
1250
+ if (a.mappedEntity) {
1251
+ const E = e.rxdb.schemaManager.getEntityMetadata(
1252
+ a.mappedEntity,
1253
+ a.mappedNamespace
1254
+ ), m = q(
1255
+ E?.tableName ?? a.mappedEntity,
1256
+ a.mappedNamespace
1257
+ );
1258
+ h += ` REFERENCES ${m}(id)`, a.onDelete && (h += ` ON DELETE ${a.onDelete}`), a.onUpdate && (h += ` ON UPDATE ${a.onUpdate}`);
1137
1259
  }
1138
- i.push(f), (o.unique || o.kind === A.ONE_TO_ONE) && r.push(
1139
- `CREATE UNIQUE INDEX ${pe(t, o)} on "${n}"(${l});`
1260
+ i.push(h), (a.unique || a.kind === A.ONE_TO_ONE) && r.push(
1261
+ `CREATE UNIQUE INDEX ${he(t, a)} on "${n}"(${l});`
1140
1262
  );
1141
1263
  }
1142
1264
  });
1143
- const c = [...i, ...a];
1265
+ const c = [...i, ...o];
1144
1266
  if (c.length)
1145
- s += c.map((o) => `
1146
- ${o}`).join(","), s += `
1267
+ s += c.map((a) => `
1268
+ ${a}`).join(","), s += `
1147
1269
  );`;
1148
1270
  else
1149
- throw new b("columns is empty!");
1271
+ throw new O("columns is empty!");
1150
1272
  return r.length && (s += `
1151
1273
  ` + r.join(`
1152
- `)), t.indexes && t.indexes.length > 0 && t.indexes.forEach((o) => {
1153
- const l = `idx_${t.name}_${o.name}`, h = o.properties?.map((u) => `"${u}"`).join(", ") || `"${o.name}"`, d = o.unique ? "UNIQUE " : "";
1274
+ `)), t.indexes && t.indexes.length > 0 && t.indexes.forEach((a) => {
1275
+ const l = `idx_${t.name}_${a.name}`, u = a.properties?.map((d) => {
1276
+ const p = t.propertyMap.get(d);
1277
+ if (p) return `"${p.columnName}"`;
1278
+ const h = t.foreignKeyNames, E = t.foreignKeyColumnNames;
1279
+ if (h && E) {
1280
+ const m = h.indexOf(d);
1281
+ if (m >= 0) return `"${E[m]}"`;
1282
+ }
1283
+ return `"${d}"`;
1284
+ }).join(", ") || `"${a.name}"`, f = a.unique ? "UNIQUE " : "";
1154
1285
  s += `
1155
- CREATE ${d}INDEX "${l}" ON "${n}"(${h});`;
1286
+ CREATE ${f}INDEX "${l}" ON "${n}"(${u});`;
1156
1287
  }), s;
1157
- }, Zt = (e, t) => zt(e, t), ie = (e, t = {}) => {
1158
- const n = S(e), s = w(F), r = S(s), { propertyMap: a, name: i, foreignKeyNames: c, namespace: o } = e, l = [...a.keys(), ...c].filter((m) => ["id"].includes(m) === !1), h = " type, namespace, entity, branchId, transactionId, entityId, inversePatch, patch", { transactionId: d, branchId: u } = t, p = R(d), f = R(u || "main"), _ = `'${o}','${i}',${f},${p}`, E = (m, I) => a.get(m)?.type === y.boolean ? `CASE WHEN ${I}.${m} = 1 THEN 1 ELSE 0 END` : `${I}.${m}`, g = `
1288
+ }, Zt = (e, t) => zt(e, t), ce = (e, t = {}) => {
1289
+ const n = S(e), s = w(k), r = S(s), { propertyMap: o, name: i, foreignKeyNames: c, foreignKeyColumnNames: a, namespace: l } = e, u = [];
1290
+ for (const [_, I] of o)
1291
+ _ !== "id" && u.push({ jsName: _, dbColumn: I.columnName });
1292
+ const f = a || c;
1293
+ for (let _ = 0; _ < c.length; _++)
1294
+ c[_] !== "id" && u.push({ jsName: c[_], dbColumn: f[_] });
1295
+ const d = " type, namespace, entity, branchId, transactionId, entityId, inversePatch, patch", { transactionId: p, branchId: h } = t, E = R(p), m = R(h || "main"), N = `'${l}','${i}',${m},${E}`, g = (_, I, M) => o.get(I)?.type === y.boolean ? `CASE WHEN ${M}.${_} = 1 THEN 1 ELSE 0 END` : `${M}.${_}`, $ = `
1159
1296
  DROP TRIGGER IF EXISTS ${n}_insert;
1160
1297
  CREATE TRIGGER ${n}_insert AFTER INSERT ON "${n}"
1161
1298
  BEGIN
1162
- INSERT INTO ${r} (${h}) VALUES (
1163
- 'INSERT',${_}, NEW.id, NULL,
1164
- json_object(${l.map((m) => `'${m}', ${E(m, "NEW")}`).join(`,
1299
+ INSERT INTO ${r} (${d}) VALUES (
1300
+ 'INSERT',${N}, NEW.id, NULL,
1301
+ json_object(${u.map((_) => `'${_.jsName}', ${g(_.dbColumn, _.jsName, "NEW")}`).join(`,
1165
1302
  `)})
1166
1303
  );
1167
- END;`, $ = `
1304
+ END;`, T = `
1168
1305
  DROP TRIGGER IF EXISTS ${n}_update;
1169
1306
  CREATE TRIGGER ${n}_update AFTER UPDATE ON "${n}"
1170
- WHEN ( ${l.map((m) => `OLD.${m} IS NOT NEW.${m}`).join(` OR
1307
+ WHEN ( ${u.map((_) => `OLD.${_.dbColumn} IS NOT NEW.${_.dbColumn}`).join(` OR
1171
1308
  `)} )
1172
1309
  BEGIN
1173
- INSERT INTO ${r} (${h}) VALUES (
1174
- 'UPDATE',${_}, NEW.id,
1310
+ INSERT INTO ${r} (${d}) VALUES (
1311
+ 'UPDATE',${N}, NEW.id,
1175
1312
  (
1176
1313
  SELECT json_group_object(key, value) FROM (
1177
- ${l.map((m) => `SELECT '${m}' AS key, ${E(m, "OLD")} AS value WHERE OLD.${m} IS NOT NEW.${m}`).join(`
1314
+ ${u.map((_) => `SELECT '${_.jsName}' AS key, ${g(_.dbColumn, _.jsName, "OLD")} AS value WHERE OLD.${_.dbColumn} IS NOT NEW.${_.dbColumn}`).join(`
1178
1315
  UNION `)}
1179
1316
  )
1180
1317
  ),
1181
1318
  (
1182
1319
  SELECT json_group_object(key, value) FROM (
1183
- ${l.map((m) => `SELECT '${m}' AS key, ${E(m, "NEW")} AS value WHERE OLD.${m} IS NOT NEW.${m}`).join(`
1320
+ ${u.map((_) => `SELECT '${_.jsName}' AS key, ${g(_.dbColumn, _.jsName, "NEW")} AS value WHERE OLD.${_.dbColumn} IS NOT NEW.${_.dbColumn}`).join(`
1184
1321
  UNION `)}
1185
1322
  )
1186
1323
  )
1187
1324
  );
1188
- END;`, T = `
1325
+ END;`, C = `
1189
1326
  DROP TRIGGER IF EXISTS ${n}_delete;
1190
1327
  CREATE TRIGGER ${n}_delete AFTER DELETE ON "${n}"
1191
1328
  BEGIN
1192
- INSERT INTO ${r} (${h}) VALUES (
1193
- 'DELETE',${_}, OLD.id,
1194
- json_object(${l.map((m) => `'${m}', ${E(m, "OLD")}`).join(`,
1329
+ INSERT INTO ${r} (${d}) VALUES (
1330
+ 'DELETE',${N}, OLD.id,
1331
+ json_object(${u.map((_) => `'${_.jsName}', ${g(_.dbColumn, _.jsName, "OLD")}`).join(`,
1195
1332
  `)}), NULL
1196
1333
  );
1197
1334
  END;`;
1198
- return g + `
1199
- ` + $ + `
1200
- ` + T;
1335
+ return $ + `
1336
+ ` + T + `
1337
+ ` + C;
1201
1338
  }, en = (e, t, n) => {
1202
1339
  let s = "";
1203
1340
  for (let r = 0; r < t.length; r++) {
1204
- const a = t[r], i = w(a);
1341
+ const o = t[r], i = w(o);
1205
1342
  if (s += `
1206
1343
  ` + Zt(e, i), i.log !== !1) {
1207
- const c = ie(i);
1344
+ const c = ce(i);
1208
1345
  s += `
1209
1346
  ` + c;
1210
1347
  }
1211
1348
  }
1212
1349
  if (n) {
1213
1350
  const r = /* @__PURE__ */ new Map();
1214
- n.forEach((a) => {
1215
- const i = w(a);
1216
- r.has(i) === !1 && r.set(i, /* @__PURE__ */ new Set()), r.get(i).add(a);
1351
+ n.forEach((o) => {
1352
+ const i = w(o);
1353
+ r.has(i) === !1 && r.set(i, /* @__PURE__ */ new Set()), r.get(i).add(o);
1217
1354
  });
1218
- for (const a of r.keys()) {
1219
- const i = Ce(a, Array.from(r.get(a)), e.rxdb.context);
1355
+ for (const o of r.keys()) {
1356
+ const i = Le(o, Array.from(r.get(o)), e.rxdb.context);
1220
1357
  s += `
1221
1358
  ` + i;
1222
1359
  }
@@ -1227,194 +1364,194 @@ CREATE ${d}INDEX "${l}" ON "${n}"(${h});`;
1227
1364
  return `DROP TRIGGER IF EXISTS ${t}_insert;
1228
1365
  DROP TRIGGER IF EXISTS ${t}_update;
1229
1366
  DROP TRIGGER IF EXISTS ${t}_delete;`;
1230
- }, ve = (e) => {
1367
+ }, je = (e) => {
1231
1368
  let t = "";
1232
1369
  return e.rxdb.config.entities.forEach((n) => {
1233
1370
  const s = w(n);
1234
1371
  s.log !== !1 && (t += tn(s));
1235
1372
  }), t;
1236
- }, qe = (e, t) => {
1237
- const { deletes: n, inserts: s, updates: r } = t, a = { deletes: [], inserts: [], updates: [] }, i = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
1238
- for (const [u, p] of n.entries()) {
1239
- const [f, _, E] = J(u), g = `${f}:${_}`, $ = i.get(g);
1240
- $ ? $.add(E) : i.set(g, /* @__PURE__ */ new Set([E]));
1241
- let T = c.get(g);
1242
- T || (T = /* @__PURE__ */ new Map(), c.set(g, T)), T.set(E, {
1373
+ }, xe = (e, t) => {
1374
+ const { deletes: n, inserts: s, updates: r } = t, o = { deletes: [], inserts: [], updates: [] }, i = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
1375
+ for (const [d, p] of n.entries()) {
1376
+ const [h, E, m] = Y(d), N = `${h}:${E}`, g = i.get(N);
1377
+ g ? g.add(m) : i.set(N, /* @__PURE__ */ new Set([m]));
1378
+ let $ = c.get(N);
1379
+ $ || ($ = /* @__PURE__ */ new Map(), c.set(N, $)), $.set(m, {
1243
1380
  patch: p.patch,
1244
1381
  inversePatch: p.inversePatch
1245
1382
  });
1246
1383
  }
1247
- for (const [u, p] of i) {
1248
- const [f, _] = u.split(":"), E = e.rxdb.schemaManager.getEntityMetadata(_, f), g = S(E), $ = E.propertyMap.get("id").type === "integer";
1249
- let T = "";
1250
- $ ? T = Array.from(p).join(",") : T = Array.from(p).map((I) => `'${I}'`).join(",");
1251
- const m = `DELETE FROM "${g}" WHERE id in (${T});`;
1252
- a.deletes.push({
1253
- metadata: E,
1384
+ for (const [d, p] of i) {
1385
+ const [h, E] = d.split(":"), m = e.rxdb.schemaManager.getEntityMetadata(E, h), N = S(m), g = m.propertyMap.get("id").type === "integer";
1386
+ let $ = "";
1387
+ g ? $ = Array.from(p).join(",") : $ = Array.from(p).map((C) => R(C)).join(",");
1388
+ const T = `DELETE FROM "${N}" WHERE id in (${$});`;
1389
+ o.deletes.push({
1390
+ metadata: m,
1254
1391
  ids: p,
1255
- sql: m,
1256
- changes: c.get(u)
1392
+ sql: T,
1393
+ changes: c.get(d)
1257
1394
  });
1258
1395
  }
1259
- const o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
1260
- for (const [u, p] of s.entries()) {
1261
- const [f, _, E] = J(u), g = `${f}:${_}`, $ = o.get(g), T = { ...p.patch, id: E };
1262
- $ ? $.push(T) : o.set(g, [T]);
1263
- let m = l.get(g);
1264
- m || (m = /* @__PURE__ */ new Map(), l.set(g, m)), m.set(E, {
1396
+ const a = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
1397
+ for (const [d, p] of s.entries()) {
1398
+ const [h, E, m] = Y(d), N = `${h}:${E}`, g = a.get(N), $ = { ...p.patch, id: m };
1399
+ g ? g.push($) : a.set(N, [$]);
1400
+ let T = l.get(N);
1401
+ T || (T = /* @__PURE__ */ new Map(), l.set(N, T)), T.set(m, {
1265
1402
  patch: p.patch,
1266
1403
  inversePatch: p.inversePatch
1267
1404
  });
1268
1405
  }
1269
- for (const [u, p] of o) {
1270
- const [f, _] = u.split(":"), E = e.rxdb.schemaManager.getEntityMetadata(_, f);
1271
- let g = "";
1272
- p.forEach(($) => {
1273
- for (const [O, M] of E.propertyMap)
1274
- $[O] === void 0 && M.default !== void 0 && (typeof M.default == "function" ? $[O] = M.default() : $[O] = M.default);
1275
- const { sql: T, params: m } = Oe(E, $, { useReplace: !0 }), I = P(T, m);
1276
- g += I;
1277
- }), a.inserts.push({
1278
- metadata: E,
1279
- ids: new Set(p.filter(($) => $ != null).map(($) => $.id)),
1280
- sql: g,
1281
- changes: l.get(u)
1406
+ for (const [d, p] of a) {
1407
+ const [h, E] = d.split(":"), m = e.rxdb.schemaManager.getEntityMetadata(E, h);
1408
+ let N = "";
1409
+ p.forEach((g) => {
1410
+ for (const [_, I] of m.propertyMap)
1411
+ g[_] === void 0 && I.default !== void 0 && (typeof I.default == "function" ? g[_] = I.default() : g[_] = I.default);
1412
+ const { sql: $, params: T } = Oe(m, g, { useReplace: !0 }), C = P($, T);
1413
+ N += C;
1414
+ }), o.inserts.push({
1415
+ metadata: m,
1416
+ ids: new Set(p.filter((g) => g != null).map((g) => g.id)),
1417
+ sql: N,
1418
+ changes: l.get(d)
1282
1419
  });
1283
1420
  }
1284
- const h = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map();
1285
- for (const [u, p] of r.entries()) {
1286
- const [f, _, E] = J(u), g = `${f}:${_}`, $ = h.get(g), T = { ...p.patch, id: E };
1287
- $ ? $.push(T) : h.set(g, [T]);
1288
- let m = d.get(g);
1289
- m || (m = /* @__PURE__ */ new Map(), d.set(g, m));
1290
- const I = e.rxdb.schemaManager.getEntityMetadata(_, f), O = p.patch ? { ...p.patch } : null, M = p.inversePatch ? { ...p.inversePatch } : null;
1291
- I && (O && Object.keys(O).forEach((x) => {
1292
- const j = I.propertyMap.get(x);
1293
- j && (O[x] = D(O[x], j));
1294
- }), M && Object.keys(M).forEach((x) => {
1295
- const j = I.propertyMap.get(x);
1296
- j && (M[x] = D(M[x], j));
1297
- })), m.set(E, {
1298
- patch: O,
1299
- inversePatch: M
1421
+ const u = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map();
1422
+ for (const [d, p] of r.entries()) {
1423
+ const [h, E, m] = Y(d), N = `${h}:${E}`, g = u.get(N), $ = { ...p.patch, id: m };
1424
+ g ? g.push($) : u.set(N, [$]);
1425
+ let T = f.get(N);
1426
+ T || (T = /* @__PURE__ */ new Map(), f.set(N, T));
1427
+ const C = e.rxdb.schemaManager.getEntityMetadata(E, h), _ = p.patch ? { ...p.patch } : null, I = p.inversePatch ? { ...p.inversePatch } : null;
1428
+ C && (_ && Object.keys(_).forEach((M) => {
1429
+ const D = C.propertyMap.get(M);
1430
+ D && (_[M] = v(_[M], D));
1431
+ }), I && Object.keys(I).forEach((M) => {
1432
+ const D = C.propertyMap.get(M);
1433
+ D && (I[M] = v(I[M], D));
1434
+ })), T.set(m, {
1435
+ patch: _,
1436
+ inversePatch: I
1300
1437
  });
1301
1438
  }
1302
- for (const [u, p] of h) {
1303
- const [f, _] = u.split(":"), E = e.rxdb.schemaManager.getEntityMetadata(_, f);
1304
- let g = "";
1305
- p.forEach(($) => {
1306
- let T;
1307
- E.propertyMap.has("updatedAt") && (T = $.updatedAt);
1308
- const { id: m, ...I } = $, { sql: O, params: M } = oe(E, { id: m }, I, {
1309
- updatedAt: T
1439
+ for (const [d, p] of u) {
1440
+ const [h, E] = d.split(":"), m = e.rxdb.schemaManager.getEntityMetadata(E, h);
1441
+ let N = "";
1442
+ p.forEach((g) => {
1443
+ let $;
1444
+ m.propertyMap.has("updatedAt") && ($ = g.updatedAt);
1445
+ const { id: T, ...C } = g, { sql: _, params: I } = ie(m, { id: T }, C, {
1446
+ updatedAt: $
1310
1447
  });
1311
- g += P(O, M);
1312
- }), a.updates.push({
1313
- metadata: E,
1314
- ids: new Set(p.filter(($) => $ != null).map(($) => $.id)),
1315
- sql: g,
1316
- changes: d.get(u)
1448
+ N += P(_, I);
1449
+ }), o.updates.push({
1450
+ metadata: m,
1451
+ ids: new Set(p.filter((g) => g != null).map((g) => g.id)),
1452
+ sql: N,
1453
+ changes: f.get(d)
1317
1454
  });
1318
1455
  }
1319
- return a;
1320
- }, xe = (e, t) => {
1456
+ return o;
1457
+ }, ve = (e, t) => {
1321
1458
  let n = "";
1322
1459
  e.rxdb.config.entities.forEach((i) => {
1323
1460
  const c = w(i);
1324
1461
  if (c.log !== !1)
1325
1462
  try {
1326
- const o = ie(c, {
1463
+ const a = ce(c, {
1327
1464
  branchId: t
1328
1465
  });
1329
- o.trim() && (n += o);
1330
- } catch (o) {
1331
- console.warn(`Failed to generate trigger SQL for entity ${c.name}:`, o);
1466
+ a.trim() && (n += a);
1467
+ } catch (a) {
1468
+ console.warn(`Failed to generate trigger SQL for entity ${c.name}:`, a);
1332
1469
  }
1333
1470
  });
1334
- const s = w(W), r = S(s), a = t.replace(/'/g, "''");
1471
+ const s = w(W), r = S(s), o = t.replace(/'/g, "''");
1335
1472
  return n += `
1336
1473
  UPDATE "${r}"
1337
1474
  SET
1338
1475
  activated = CASE
1339
- WHEN id = '${a}' THEN 1
1476
+ WHEN id = '${o}' THEN 1
1340
1477
  ELSE 0
1341
1478
  END,
1342
1479
  updatedAt = CASE
1343
- WHEN (id = '${a}' AND activated = 0) OR (id != '${a}' AND activated = 1) THEN CURRENT_TIMESTAMP
1480
+ WHEN (id = '${o}' AND activated = 0) OR (id != '${o}' AND activated = 1) THEN CURRENT_TIMESTAMP
1344
1481
  ELSE updatedAt
1345
1482
  END
1346
- WHERE id = '${a}' OR activated = 1
1483
+ WHERE id = '${o}' OR activated = 1
1347
1484
  RETURNING rowid as ${L},*;
1348
1485
  `, n;
1349
1486
  }, nn = async (e, t) => {
1350
- const { branchId: n, actions: s } = t, r = s && qe(e, s);
1351
- let a;
1487
+ const { branchId: n, actions: s } = t, r = s && xe(e, s);
1488
+ let o;
1352
1489
  try {
1353
- await e.transaction(async (o) => {
1354
- const l = ve(e);
1355
- if (l && await o.execute(l), r) {
1490
+ await e.transaction(async (a) => {
1491
+ const l = je(e);
1492
+ if (l && await a.execute(l), r) {
1356
1493
  if (r.deletes.length)
1357
- for (const h of r.deletes)
1358
- await o.execute(h.sql);
1494
+ for (const u of r.deletes)
1495
+ await a.execute(u.sql);
1359
1496
  if (r.inserts.length)
1360
- for (const h of r.inserts)
1361
- h.successResults = await o.execute(h.sql);
1497
+ for (const u of r.inserts)
1498
+ u.successResults = await a.execute(u.sql);
1362
1499
  if (r.updates.length)
1363
- for (const h of r.updates)
1364
- h.successResults = await o.execute(h.sql);
1500
+ for (const u of r.updates)
1501
+ u.successResults = await a.execute(u.sql);
1365
1502
  }
1366
1503
  s?.updateRxDBChangeSequence !== void 0 && await e.setRxDBChangeSequence(s.updateRxDBChangeSequence);
1367
1504
  }, !1);
1368
- const i = xe(e, n);
1369
- a = await e.internalQuery(i);
1370
- const c = (o, l) => {
1505
+ const i = ve(e, n);
1506
+ o = await e.internalQuery(i);
1507
+ const c = (a, l) => {
1371
1508
  if (l.length === 0) return;
1372
- const h = l.map((d) => {
1373
- const u = { ...d };
1509
+ const u = l.map((f) => {
1510
+ const d = { ...f };
1374
1511
  return {
1375
- namespace: o.namespace,
1376
- entity: o.name,
1512
+ namespace: a.namespace,
1513
+ entity: a.name,
1377
1514
  type: "UPDATE",
1378
- id: d.id,
1379
- patch: u,
1380
- inversePatch: u,
1381
- recordAt: d.createdAt
1515
+ id: f.id,
1516
+ patch: d,
1517
+ inversePatch: d,
1518
+ recordAt: f.createdAt
1382
1519
  };
1383
1520
  });
1384
- e.rxdb.dispatchEvent(new K(h));
1521
+ e.rxdb.dispatchEvent(new G(u));
1385
1522
  };
1386
- if (a) {
1387
- const o = Q(e, W, a, !0), l = w(W);
1388
- c(l, o);
1523
+ if (o) {
1524
+ const a = Q(e, W, o, !0), l = w(W);
1525
+ c(l, a);
1389
1526
  }
1390
- r && De(e, r);
1527
+ r && qe(e, r);
1391
1528
  } catch (i) {
1392
- throw new b(`switch branch ${n} failed: ` + i);
1529
+ throw new O(`switch branch ${n} failed: ` + i);
1393
1530
  }
1394
1531
  };
1395
- async function sn(e, t, n, s = !1) {
1396
- if (await e.transaction(async (r) => {
1397
- if (s) {
1398
- const a = ve(e);
1399
- a && await r.execute(a);
1532
+ async function sn(e, t, n = !1) {
1533
+ if (await e.transaction(async (s) => {
1534
+ if (n) {
1535
+ const r = je(e);
1536
+ r && await s.execute(r);
1400
1537
  }
1401
- for (const a of t.deletes)
1402
- await r.execute(a.sql);
1403
- for (const a of t.inserts)
1404
- a.successResults = await r.execute(a.sql);
1405
- for (const a of t.updates)
1406
- a.successResults = await r.execute(a.sql);
1407
- }, !1), s) {
1408
- const r = await e.rxdb.versionManager.getCurrentBranch(), a = xe(e, r.id);
1409
- await e.internalQuery(a);
1410
- }
1411
- De(e, t);
1538
+ for (const r of t.deletes)
1539
+ await s.execute(r.sql);
1540
+ for (const r of t.inserts)
1541
+ r.successResults = await s.execute(r.sql);
1542
+ for (const r of t.updates)
1543
+ r.successResults = await s.execute(r.sql);
1544
+ }, !1), n) {
1545
+ const s = await e.rxdb.versionManager.getCurrentBranch(), r = ve(e, s.id);
1546
+ await e.internalQuery(r);
1547
+ }
1548
+ qe(e, t);
1412
1549
  }
1413
- function De(e, t) {
1550
+ function qe(e, t) {
1414
1551
  for (const n of t.deletes) {
1415
- const s = Y(n.metadata);
1552
+ const s = X(n.metadata);
1416
1553
  Rt(e, s, Array.from(n.ids));
1417
- const r = n.metadata, a = Array.from(n.ids).map((i) => {
1554
+ const r = n.metadata, o = Array.from(n.ids).map((i) => {
1418
1555
  const c = n.changes.get(String(i));
1419
1556
  return {
1420
1557
  namespace: r.namespace,
@@ -1426,45 +1563,45 @@ function De(e, t) {
1426
1563
  recordAt: /* @__PURE__ */ new Date()
1427
1564
  };
1428
1565
  });
1429
- e.rxdb.dispatchEvent(new ne(a));
1566
+ e.rxdb.dispatchEvent(new re(o));
1430
1567
  }
1431
1568
  for (const n of t.inserts) {
1432
- const s = Y(n.metadata), r = Q(e, s, n.successResults), a = n.metadata, i = r.map((c) => {
1433
- const o = n.changes.get(String(c.id));
1569
+ const s = X(n.metadata), r = Q(e, s, n.successResults), o = n.metadata, i = r.map((c) => {
1570
+ const a = n.changes.get(String(c.id));
1434
1571
  return {
1435
- namespace: a.namespace,
1436
- entity: a.name,
1572
+ namespace: o.namespace,
1573
+ entity: o.name,
1437
1574
  type: "INSERT",
1438
1575
  id: c.id,
1439
- patch: o?.patch ?? { ...c },
1440
- inversePatch: o?.inversePatch ?? null,
1576
+ patch: a?.patch ?? { ...c },
1577
+ inversePatch: a?.inversePatch ?? null,
1441
1578
  recordAt: c.createdAt
1442
1579
  };
1443
1580
  });
1444
- e.rxdb.dispatchEvent(new k(i));
1581
+ e.rxdb.dispatchEvent(new B(i));
1445
1582
  }
1446
1583
  for (const n of t.updates) {
1447
- const s = Y(n.metadata), r = Q(e, s, n.successResults, !0), a = n.metadata, i = r.map((c) => {
1448
- const o = n.changes.get(String(c.id));
1584
+ const s = X(n.metadata), r = Q(e, s, n.successResults, !0), o = n.metadata, i = r.map((c) => {
1585
+ const a = n.changes.get(String(c.id));
1449
1586
  return {
1450
- namespace: a.namespace,
1451
- entity: a.name,
1587
+ namespace: o.namespace,
1588
+ entity: o.name,
1452
1589
  type: "UPDATE",
1453
1590
  id: c.id,
1454
- patch: o?.patch ?? { ...c },
1455
- inversePatch: o?.inversePatch ?? null,
1591
+ patch: a?.patch ?? { ...c },
1592
+ inversePatch: a?.inversePatch ?? null,
1456
1593
  recordAt: c.updatedAt || c.createdAt || /* @__PURE__ */ new Date()
1457
1594
  };
1458
1595
  });
1459
- e.rxdb.dispatchEvent(new K(i));
1596
+ e.rxdb.dispatchEvent(new G(i));
1460
1597
  }
1461
1598
  }
1462
- const me = (e, t, n) => {
1599
+ const ye = (e, t, n) => {
1463
1600
  let s = "";
1464
1601
  return e.rxdb.config.entities.forEach((r) => {
1465
- const a = w(r);
1466
- if (a.log !== !1) {
1467
- const i = ie(a, {
1602
+ const o = w(r);
1603
+ if (o.log !== !1) {
1604
+ const i = ce(o, {
1468
1605
  branchId: t,
1469
1606
  transactionId: n
1470
1607
  });
@@ -1473,17 +1610,17 @@ const me = (e, t, n) => {
1473
1610
  }
1474
1611
  }), s;
1475
1612
  };
1476
- class fn extends ke {
1613
+ class hn extends Be {
1477
1614
  constructor(t, n) {
1478
1615
  super(t), this.options = n, n.repositories && Object.keys(n.repositories).forEach((r) => {
1479
1616
  this.repository(r, n.repositories[r]);
1480
1617
  });
1481
1618
  const s = Ge((r) => {
1482
- this.#o || Ht(this, r);
1619
+ this.#a || Vt(this, r);
1483
1620
  });
1484
1621
  this.#t().then((r) => {
1485
- r.addEventListener(v.SQLITE_INSERT, s), r.addEventListener(v.SQLITE_UPDATE, s), r.addEventListener(v.SQLITE_DELETE, s);
1486
- }), this.repository("Repository", Me), this.repository("TreeRepository", Yt);
1622
+ r.addEventListener(x.SQLITE_INSERT, s), r.addEventListener(x.SQLITE_UPDATE, s), r.addEventListener(x.SQLITE_DELETE, s);
1623
+ }), this.repository("Repository", Ce), this.repository("TreeRepository", Yt);
1487
1624
  }
1488
1625
  // SQLite 客户端缓存
1489
1626
  #n;
@@ -1499,13 +1636,13 @@ class fn extends ke {
1499
1636
  // 查询任务队列执行器
1500
1637
  #c = new ge(1);
1501
1638
  // sqlite 客户端
1502
- #a;
1639
+ #o;
1503
1640
  // 是否已断开连接
1504
- #o = !1;
1641
+ #a = !1;
1505
1642
  /**
1506
1643
  * 适配器名称
1507
1644
  */
1508
- name = Mt;
1645
+ name = Ct;
1509
1646
  /**
1510
1647
  * 获取实体仓库
1511
1648
  * @param EntityType 实体类
@@ -1514,7 +1651,7 @@ class fn extends ke {
1514
1651
  if (!this.repository_cache.has(t)) {
1515
1652
  const n = w(t), s = this.repository_map.get(n.repository);
1516
1653
  if (!s)
1517
- throw new b(`Repository '${n.repository}' not found`);
1654
+ throw new O(`Repository '${n.repository}' not found`);
1518
1655
  const r = new s(this, t);
1519
1656
  return this.repository_cache.set(t, r), r;
1520
1657
  }
@@ -1530,7 +1667,7 @@ class fn extends ke {
1530
1667
  * 断开连接
1531
1668
  */
1532
1669
  async disconnect() {
1533
- this.#o = !0, await this.#c.waitForAll(), this.#n && await this.#n.disconnect();
1670
+ this.#a = !0, await this.#c.waitForAll(), this.#n && await this.#n.disconnect();
1534
1671
  }
1535
1672
  /**
1536
1673
  * 获取版本
@@ -1544,7 +1681,7 @@ class fn extends ke {
1544
1681
  * @param entities
1545
1682
  */
1546
1683
  async saveMany(t) {
1547
- const n = le({
1684
+ const n = ue({
1548
1685
  need_save_entities: t,
1549
1686
  need_remove_entities: []
1550
1687
  });
@@ -1556,7 +1693,7 @@ class fn extends ke {
1556
1693
  * @returns
1557
1694
  */
1558
1695
  async removeMany(t) {
1559
- const n = le({
1696
+ const n = ue({
1560
1697
  need_save_entities: [],
1561
1698
  need_remove_entities: t
1562
1699
  });
@@ -1601,13 +1738,12 @@ class fn extends ke {
1601
1738
  * 将 actions 转换为 SQL 操作实体表。
1602
1739
  *
1603
1740
  * @param actions - 压缩后的变更操作
1604
- * @param localChanges - (已废弃)不再使用,Pull 来的数据不应该生成 RxDBChange 记录
1741
+ * @param _localChanges - (已废弃)不再使用
1605
1742
  * @param disableTriggers - 是否禁用触发器(用于 pull 等操作,避免创建 RxDBChange)
1606
- * @deprecated localChanges 参数已废弃,将在未来版本中移除
1607
1743
  */
1608
1744
  async mergeChanges(t, n, s = !1) {
1609
- const r = qe(this, t);
1610
- await sn(this, r, n, s);
1745
+ const r = xe(this, t);
1746
+ await sn(this, r, s);
1611
1747
  }
1612
1748
  /**
1613
1749
  * 缓存 RowId 与实体映射
@@ -1653,7 +1789,7 @@ class fn extends ke {
1653
1789
  query(t, n) {
1654
1790
  return this.#c.addTask(
1655
1791
  async () => (await this.rxdb.connect(this.name), (await this.#t()).execute(t, n)),
1656
- $e([t, n])
1792
+ Ne([t, n])
1657
1793
  );
1658
1794
  }
1659
1795
  /**
@@ -1666,12 +1802,12 @@ class fn extends ke {
1666
1802
  await this.rxdb.connect(this.name);
1667
1803
  const s = await this.#t();
1668
1804
  this.#e = !0, this.rxdb.dispatchEvent(rn);
1669
- let r = "", a = "";
1805
+ let r = "", o = "";
1670
1806
  if (n) {
1671
1807
  const i = We(), c = await this.rxdb.versionManager.getCurrentBranch();
1672
1808
  if (!c)
1673
1809
  throw new Error("currentBranch is undefined! Cannot start transaction with logging.");
1674
- r = me(this, c.id, i), a = me(this, c.id);
1810
+ r = ye(this, c.id, i), o = ye(this, c.id);
1675
1811
  }
1676
1812
  await s.execute(`
1677
1813
  BEGIN;
@@ -1680,12 +1816,12 @@ class fn extends ke {
1680
1816
  `);
1681
1817
  try {
1682
1818
  const i = await t(s);
1683
- return await s.execute(`${a}
1684
- COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1819
+ return await s.execute(`${o}
1820
+ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(an), i;
1685
1821
  } catch (i) {
1686
- await s.execute("ROLLBACK"), this.#e = !1, this.rxdb.dispatchEvent(an);
1822
+ await s.execute("ROLLBACK"), this.#e = !1, this.rxdb.dispatchEvent(on);
1687
1823
  const c = i?.message || "Transaction Error";
1688
- throw new b(c);
1824
+ throw new O(c);
1689
1825
  }
1690
1826
  }
1691
1827
  /**
@@ -1707,14 +1843,14 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1707
1843
  * 本地变更仓库
1708
1844
  */
1709
1845
  localRxDBChange() {
1710
- return this.getRepository(F);
1846
+ return this.getRepository(k);
1711
1847
  }
1712
1848
  /**
1713
1849
  * 获取 RxDBChange 表的当前序列值
1714
1850
  * @returns
1715
1851
  */
1716
1852
  async getRxDBChangeSequence() {
1717
- const t = he(F);
1853
+ const t = pe(k);
1718
1854
  return (await this.#i(`SELECT seq FROM sqlite_sequence WHERE name='${t}'`)).results[0].rows[0][0];
1719
1855
  }
1720
1856
  /**
@@ -1722,7 +1858,7 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1722
1858
  * @param sequence 序列值
1723
1859
  */
1724
1860
  async setRxDBChangeSequence(t) {
1725
- const n = he(F);
1861
+ const n = pe(k);
1726
1862
  await this.#i("UPDATE sqlite_sequence SET seq = ? WHERE name = ?", [t, n]);
1727
1863
  }
1728
1864
  // ============================================
@@ -1744,15 +1880,15 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1744
1880
  * ```
1745
1881
  */
1746
1882
  getMetadataByIds(t, n) {
1747
- return X(() => {
1883
+ return z(() => {
1748
1884
  if (n.length === 0)
1749
- return z(/* @__PURE__ */ new Map());
1750
- const s = n.map(() => "?").join(", "), r = `SELECT id, updatedAt FROM ${t} WHERE id IN (${s})`;
1751
- return Z(this.internalQuery(r, n)).pipe(
1752
- Je((a) => {
1885
+ return Z(/* @__PURE__ */ new Map());
1886
+ const s = n.map(() => "?").join(", "), r = `SELECT id, updatedAt FROM "${t}" WHERE id IN (${s})`;
1887
+ return ee(this.internalQuery(r, n)).pipe(
1888
+ Je((o) => {
1753
1889
  const i = /* @__PURE__ */ new Map();
1754
- if (a.results?.[0]?.rows)
1755
- for (const c of a.results[0].rows)
1890
+ if (o.results?.[0]?.rows)
1891
+ for (const c of o.results[0].rows)
1756
1892
  i.set(c[0], c[1]);
1757
1893
  return i;
1758
1894
  })
@@ -1775,9 +1911,9 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1775
1911
  * ```
1776
1912
  */
1777
1913
  upsertMany(t, n) {
1778
- return X(() => n.length === 0 ? z(void 0) : Z(
1914
+ return z(() => n.length === 0 ? Z(void 0) : ee(
1779
1915
  (async () => {
1780
- const s = Object.keys(n[0]), r = `(${s.map(() => "?").join(", ")})`, a = n.map(() => r).join(", "), i = `INSERT OR REPLACE INTO ${t} (${s.join(", ")}) VALUES ${a}`, c = n.flatMap((o) => s.map((l) => o[l]));
1916
+ const s = Object.keys(n[0]), r = `(${s.map(() => "?").join(", ")})`, o = n.map(() => r).join(", "), i = `INSERT OR REPLACE INTO "${t}" (${s.join(", ")}) VALUES ${o}`, c = n.flatMap((a) => s.map((l) => a[l]));
1781
1917
  await this.internalQuery(i, c);
1782
1918
  })()
1783
1919
  ));
@@ -1796,11 +1932,11 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1796
1932
  * ```
1797
1933
  */
1798
1934
  deleteByIds(t, n) {
1799
- return X(() => {
1935
+ return z(() => {
1800
1936
  if (n.length === 0)
1801
- return z(void 0);
1802
- const s = n.map(() => "?").join(", "), r = `DELETE FROM ${t} WHERE id IN (${s})`;
1803
- return Z(this.internalQuery(r, n).then(() => {
1937
+ return Z(void 0);
1938
+ const s = n.map(() => "?").join(", "), r = `DELETE FROM "${t}" WHERE id IN (${s})`;
1939
+ return ee(this.internalQuery(r, n).then(() => {
1804
1940
  }));
1805
1941
  });
1806
1942
  }
@@ -1811,9 +1947,9 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1811
1947
  * 获取 SQLite 客户端
1812
1948
  */
1813
1949
  #t() {
1814
- return this.#a || (this.#a = Wt(this.rxdb.config.dbName, this.options).then(
1950
+ return this.#o || (this.#o = Wt(this.rxdb.config.dbName, this.options).then(
1815
1951
  (t) => (this.#n = t, t)
1816
- )), this.#a;
1952
+ )), this.#o;
1817
1953
  }
1818
1954
  /**
1819
1955
  * 内部执行 sql
@@ -1828,16 +1964,16 @@ COMMIT;`), this.#e = !1, this.rxdb.dispatchEvent(on), i;
1828
1964
  return this.#r.has(t) === !1 && this.#r.set(t, /* @__PURE__ */ new Map()), this.#r.get(t);
1829
1965
  }
1830
1966
  }
1831
- const rn = new Fe(), an = new Pe(), on = new Be();
1967
+ const rn = new ke(), on = new Pe(), an = new Fe();
1832
1968
  export {
1833
1969
  L as ROWID,
1834
- fn as RxDBAdapterSqlite,
1835
- b as RxDBAdapterSqliteError,
1970
+ hn as RxDBAdapterSqlite,
1971
+ O as RxDBAdapterSqliteError,
1836
1972
  Pt as SqliteClient,
1837
- Me as SqliteRepository,
1838
- vt as WA_SQLITE_VFS_LIST,
1839
- B as buildRuleGroup,
1973
+ Ce as SqliteRepository,
1974
+ jt as WA_SQLITE_VFS_LIST,
1975
+ F as buildRuleGroup,
1840
1976
  q as sqliteGetTableName,
1841
1977
  S as sqliteGetTableNameByMetadata,
1842
- qt as sqliteLoad
1978
+ xt as sqliteLoad
1843
1979
  };