@aiao/rxdb-adapter-sqlite 0.0.12 → 0.0.14

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