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