@aiao/rxdb-adapter-sqlite 0.0.6 → 0.0.7

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