@ocap/indexdb-sqlite 1.30.26 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/db/base.mjs CHANGED
@@ -140,10 +140,8 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
140
140
  ]);
141
141
  total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
142
142
  } else if (isMultiTypeOnly) total = (await Promise.all(types.map((t) => this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("type", "=", t).executeTakeFirst()))).reduce((sum, c) => sum + (c?.count ?? 0), 0);
143
- else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
144
- const [approx, invalidCount] = await Promise.all([sql`SELECT max(rowid) as c FROM tx`.execute(this.db), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
145
- total = (approx.rows[0]?.c ?? 0) - (invalidCount?.count ?? 0);
146
- } else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await sql`SELECT max(rowid) as c FROM tx`.execute(this.db)).rows[0]?.c ?? 0;
143
+ else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) total = (await this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 1).executeTakeFirst())?.count ?? 0;
144
+ else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
147
145
  else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
148
146
  const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
149
147
  let rawResults;
@@ -1,3 +1,4 @@
1
+ import { SqliteOperationContext } from "../interfaces.mjs";
1
2
  import SqliteTable from "./base.mjs";
2
3
  import { TIndexedAccountState } from "@ocap/types";
3
4
 
@@ -10,22 +11,22 @@ import { TIndexedAccountState } from "@ocap/types";
10
11
  */
11
12
  declare class AccountTable extends SqliteTable<TIndexedAccountState> {
12
13
  /**
13
- * Override _insert to sync balance table after inserting an account.
14
+ * Override _insert to sync balance table atomically after inserting an account.
14
15
  */
15
- _insert(row: TIndexedAccountState | Record<string, unknown>): Promise<TIndexedAccountState>;
16
+ _insert(row: TIndexedAccountState | Record<string, unknown>, context?: SqliteOperationContext): Promise<TIndexedAccountState>;
16
17
  /**
17
- * Override _update to sync balance table after updating an account.
18
+ * Override _update to sync balance table atomically after updating an account.
18
19
  */
19
- _update(key: string | Record<string, unknown>, updates: Partial<TIndexedAccountState>): Promise<TIndexedAccountState>;
20
+ _update(key: string | Record<string, unknown>, updates: Partial<TIndexedAccountState>, context?: SqliteOperationContext): Promise<TIndexedAccountState>;
20
21
  /**
21
22
  * Sync the balance table from account tokens.
22
23
  * Deletes existing entries for this address, then inserts current token balances.
23
24
  */
24
25
  private syncBalance;
25
26
  /**
26
- * Override _reset to also clear the balance table
27
+ * Override _reset to also clear the balance table atomically
27
28
  */
28
- _reset(): Promise<void>;
29
+ _reset(context?: SqliteOperationContext): Promise<void>;
29
30
  }
30
31
  //#endregion
31
32
  export { AccountTable as default };
@@ -9,26 +9,40 @@ import { sql } from "kysely";
9
9
  */
10
10
  var AccountTable = class extends base_default {
11
11
  /**
12
- * Override _insert to sync balance table after inserting an account.
12
+ * Override _insert to sync balance table atomically after inserting an account.
13
13
  */
14
- async _insert(row) {
15
- const result = await super._insert(row);
16
- await this.syncBalance(row);
17
- return result;
14
+ async _insert(row, context) {
15
+ const run = async (txnCtx) => {
16
+ const result = await super._insert(row, txnCtx);
17
+ await this.syncBalance(row, this.getExecutor(txnCtx));
18
+ return result;
19
+ };
20
+ if (context?.txn) return run(context);
21
+ return this.db.transaction().execute((txn) => run({
22
+ ...context,
23
+ txn
24
+ }));
18
25
  }
19
26
  /**
20
- * Override _update to sync balance table after updating an account.
27
+ * Override _update to sync balance table atomically after updating an account.
21
28
  */
22
- async _update(key, updates) {
23
- const result = await super._update(key, updates);
24
- await this.syncBalance(result);
25
- return result;
29
+ async _update(key, updates, context) {
30
+ const run = async (txnCtx) => {
31
+ const result = await super._update(key, updates, txnCtx);
32
+ await this.syncBalance(result, this.getExecutor(txnCtx));
33
+ return result;
34
+ };
35
+ if (context?.txn) return run(context);
36
+ return this.db.transaction().execute((txn) => run({
37
+ ...context,
38
+ txn
39
+ }));
26
40
  }
27
41
  /**
28
42
  * Sync the balance table from account tokens.
29
43
  * Deletes existing entries for this address, then inserts current token balances.
30
44
  */
31
- async syncBalance(data) {
45
+ async syncBalance(data, executor = this.db) {
32
46
  const address = data.address;
33
47
  if (!address) return;
34
48
  let tokens = data.tokens;
@@ -38,18 +52,28 @@ var AccountTable = class extends base_default {
38
52
  return;
39
53
  }
40
54
  if (!Array.isArray(tokens)) return;
41
- await sql`DELETE FROM balance WHERE address = ${address}`.execute(this.db);
55
+ await sql`DELETE FROM balance WHERE address = ${address}`.execute(executor);
42
56
  for (const t of tokens) if (t.address && t.balance && t.balance !== "0") {
43
57
  const balanceNum = (t.balance.replace(/^0+/, "") || "0").padStart(40, "0");
44
- await sql`INSERT INTO balance (address, tokenAddress, balance, balanceNum) VALUES (${address}, ${t.address}, ${t.balance}, ${balanceNum})`.execute(this.db);
58
+ await sql`INSERT OR REPLACE INTO balance (address, tokenAddress, balance, balanceNum) VALUES (${address}, ${t.address}, ${t.balance}, ${balanceNum})`.execute(executor);
45
59
  }
46
60
  }
47
61
  /**
48
- * Override _reset to also clear the balance table
62
+ * Override _reset to also clear the balance table atomically
49
63
  */
50
- async _reset() {
51
- await super._reset();
52
- await this.db.deleteFrom("balance").execute();
64
+ async _reset(context) {
65
+ const run = async (txnCtx) => {
66
+ await super._reset(txnCtx);
67
+ await this.getExecutor(txnCtx).deleteFrom("balance").execute();
68
+ };
69
+ if (context?.txn) {
70
+ await run(context);
71
+ return;
72
+ }
73
+ await this.db.transaction().execute((txn) => run({
74
+ ...context,
75
+ txn
76
+ }));
53
77
  }
54
78
  };
55
79
  var account_default = AccountTable;
@@ -85,23 +85,23 @@ declare class SqliteTable<T = unknown> extends BaseIndex<T> implements IIndexTab
85
85
  /**
86
86
  * Internal get implementation - called by BaseIndex.get() via hooks
87
87
  */
88
- _get(key: string | Record<string, unknown>): Promise<T | null>;
88
+ _get(key: string | Record<string, unknown>, context?: SqliteOperationContext): Promise<T | null>;
89
89
  /**
90
90
  * Internal insert implementation - called by BaseIndex.insert() via hooks
91
91
  */
92
- _insert(doc: T | Record<string, unknown>): Promise<T>;
92
+ _insert(doc: T | Record<string, unknown>, context?: SqliteOperationContext): Promise<T>;
93
93
  /**
94
94
  * Internal update implementation - called by BaseIndex.update() via hooks
95
95
  */
96
- _update(key: string | Record<string, unknown>, updates: Partial<T>): Promise<T>;
96
+ _update(key: string | Record<string, unknown>, updates: Partial<T>, context?: SqliteOperationContext): Promise<T>;
97
97
  /**
98
98
  * Count documents matching a query
99
99
  */
100
- count(query?: unknown): Promise<number>;
100
+ count(query?: unknown, context?: SqliteOperationContext): Promise<number>;
101
101
  /**
102
102
  * Internal reset implementation - called by BaseIndex.reset() via hooks
103
103
  */
104
- _reset(): Promise<void>;
104
+ _reset(context?: SqliteOperationContext): Promise<void>;
105
105
  }
106
106
  //#endregion
107
107
  export { SqliteTableConfig, TableSchema, SqliteTable as default };
@@ -178,7 +178,7 @@ var SqliteTable = class extends BaseIndex {
178
178
  /**
179
179
  * Internal get implementation - called by BaseIndex.get() via hooks
180
180
  */
181
- async _get(key) {
181
+ async _get(key, context) {
182
182
  if (!key) return null;
183
183
  let query;
184
184
  if (Array.isArray(this.uniqIndex)) if (typeof key === "object") {
@@ -189,7 +189,7 @@ var SqliteTable = class extends BaseIndex {
189
189
  const id = typeof key === "string" ? key : key[this.primaryKey];
190
190
  query = { [this.mapColumnName(this.primaryKey)]: id };
191
191
  }
192
- let qb = this.db.selectFrom(this.name).selectAll();
192
+ let qb = this.getExecutor(context).selectFrom(this.name).selectAll();
193
193
  for (const [k, v] of Object.entries(query)) {
194
194
  if (v === void 0) continue;
195
195
  qb = qb.where(k, "=", v);
@@ -200,17 +200,17 @@ var SqliteTable = class extends BaseIndex {
200
200
  /**
201
201
  * Internal insert implementation - called by BaseIndex.insert() via hooks
202
202
  */
203
- async _insert(doc) {
203
+ async _insert(doc, context) {
204
204
  const data = doc;
205
205
  const serialized = this.serializeForDb(data);
206
- await this.db.insertInto(this.name).values(serialized).execute();
206
+ await this.getExecutor(context).insertInto(this.name).values(serialized).execute();
207
207
  return data;
208
208
  }
209
209
  /**
210
210
  * Internal update implementation - called by BaseIndex.update() via hooks
211
211
  */
212
- async _update(key, updates) {
213
- const existing = await this._get(key);
212
+ async _update(key, updates, context) {
213
+ const existing = await this._get(key, context);
214
214
  if (!existing) throw new Error(`${this.name} does not exist: ${JSON.stringify(key)}`);
215
215
  let query;
216
216
  if (Array.isArray(this.uniqIndex)) {
@@ -225,7 +225,7 @@ var SqliteTable = class extends BaseIndex {
225
225
  else delete updateAttrs[this.primaryKey];
226
226
  if (Object.keys(updateAttrs).length > 0) {
227
227
  const serialized = this.serializeForDbUpdate(updateAttrs, existing);
228
- let qb = this.db.updateTable(this.name).set(serialized);
228
+ let qb = this.getExecutor(context).updateTable(this.name).set(serialized);
229
229
  for (const [k, v] of Object.entries(query)) {
230
230
  if (v === void 0) continue;
231
231
  qb = qb.where(k, "=", v);
@@ -240,8 +240,9 @@ var SqliteTable = class extends BaseIndex {
240
240
  /**
241
241
  * Count documents matching a query
242
242
  */
243
- async count(query) {
244
- let qb = this.db.selectFrom(this.name).select(this.db.fn.countAll().as("count"));
243
+ async count(query, context) {
244
+ const executor = this.getExecutor(context);
245
+ let qb = executor.selectFrom(this.name).select(executor.fn.countAll().as("count"));
245
246
  if (query && typeof query === "object") for (const [k, v] of Object.entries(query)) {
246
247
  const mappedKey = this.mapColumnName(k);
247
248
  if (v && typeof v === "object" && "$in" in v) qb = qb.where(mappedKey, "in", v.$in);
@@ -252,8 +253,8 @@ var SqliteTable = class extends BaseIndex {
252
253
  /**
253
254
  * Internal reset implementation - called by BaseIndex.reset() via hooks
254
255
  */
255
- async _reset() {
256
- await this.db.deleteFrom(this.name).execute();
256
+ async _reset(context) {
257
+ await this.getExecutor(context).deleteFrom(this.name).execute();
257
258
  }
258
259
  };
259
260
  var base_default = SqliteTable;
@@ -1,3 +1,4 @@
1
+ import { SqliteOperationContext } from "../interfaces.mjs";
1
2
  import SqliteTable from "./base.mjs";
2
3
  import { TIndexedTransaction } from "@ocap/types";
3
4
 
@@ -14,11 +15,16 @@ declare class TransactionTable extends SqliteTable<TIndexedTransaction> {
14
15
  * This populates assets, tokens, factories, etc. from itxJson,
15
16
  * then inserts corresponding rows into tx_ref for indexed lookups.
16
17
  */
17
- _insert(row: TIndexedTransaction | Record<string, unknown>): Promise<TIndexedTransaction>;
18
+ _insert(row: TIndexedTransaction | Record<string, unknown>, context?: SqliteOperationContext): Promise<TIndexedTransaction>;
19
+ /**
20
+ * Override _update to also keep tx_ref junction table synchronized atomically
21
+ */
22
+ _update(key: string | Record<string, unknown>, updates: Partial<TIndexedTransaction>, context?: SqliteOperationContext): Promise<TIndexedTransaction>;
23
+ private syncTxRefs;
18
24
  /**
19
25
  * Override _reset to also clear the tx_ref junction table
20
26
  */
21
- _reset(): Promise<void>;
27
+ _reset(context?: SqliteOperationContext): Promise<void>;
22
28
  }
23
29
  //#endregion
24
30
  export { TransactionTable as default };
@@ -24,25 +24,67 @@ var TransactionTable = class extends base_default {
24
24
  * This populates assets, tokens, factories, etc. from itxJson,
25
25
  * then inserts corresponding rows into tx_ref for indexed lookups.
26
26
  */
27
- async _insert(row) {
27
+ async _insert(row, context) {
28
28
  const formatted = formatTxBeforeInsert(row);
29
- const result = await super._insert(formatted);
30
- const data = formatted;
29
+ const run = async (txnCtx) => {
30
+ const result = await super._insert(formatted, txnCtx);
31
+ await this.syncTxRefs(formatted, txnCtx, false);
32
+ return result;
33
+ };
34
+ if (context?.txn) return run(context);
35
+ return this.db.transaction().execute((txn) => run({
36
+ ...context,
37
+ txn
38
+ }));
39
+ }
40
+ /**
41
+ * Override _update to also keep tx_ref junction table synchronized atomically
42
+ */
43
+ async _update(key, updates, context) {
44
+ const run = async (txnCtx) => {
45
+ const result = await super._update(key, updates, txnCtx);
46
+ await this.syncTxRefs(result, txnCtx, true);
47
+ return result;
48
+ };
49
+ if (context?.txn) return run(context);
50
+ return this.db.transaction().execute((txn) => run({
51
+ ...context,
52
+ txn
53
+ }));
54
+ }
55
+ async syncTxRefs(data, context, replaceExisting = false) {
31
56
  const hash = data.hash;
57
+ if (!hash) return;
58
+ const executor = this.getExecutor(context);
59
+ if (replaceExisting) await sql`DELETE FROM tx_ref WHERE hash = ${hash}`.execute(executor);
32
60
  const time = data.time || null;
33
61
  for (const [type, field] of TX_REF_TYPES) {
34
- const values = data[field];
62
+ let values = data[field];
63
+ if (typeof values === "string") try {
64
+ values = JSON.parse(values);
65
+ } catch {
66
+ continue;
67
+ }
35
68
  if (!Array.isArray(values) || values.length === 0) continue;
36
- for (const v of values) if (typeof v === "string" && v) await sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(this.db);
69
+ for (const v of values) if (typeof v === "string" && v) await sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(executor);
37
70
  }
38
- return result;
39
71
  }
40
72
  /**
41
73
  * Override _reset to also clear the tx_ref junction table
42
74
  */
43
- async _reset() {
44
- await super._reset();
45
- await this.db.deleteFrom("tx_ref").execute();
75
+ async _reset(context) {
76
+ const run = async (txnCtx) => {
77
+ await super._reset(txnCtx);
78
+ await this.getExecutor(txnCtx).deleteFrom("tx_ref").execute();
79
+ };
80
+ if (context?.txn) {
81
+ await run(context);
82
+ return;
83
+ }
84
+ await this.db.transaction().execute((txn) => run({
85
+ ...context,
86
+ txn
87
+ }));
46
88
  }
47
89
  };
48
90
  var transaction_default = TransactionTable;
package/lib/db/base.cjs CHANGED
@@ -144,10 +144,8 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
144
144
  ]);
145
145
  total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
146
146
  } else if (isMultiTypeOnly) total = (await Promise.all(types.map((t) => this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("type", "=", t).executeTakeFirst()))).reduce((sum, c) => sum + (c?.count ?? 0), 0);
147
- else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
148
- const [approx, invalidCount] = await Promise.all([kysely.sql`SELECT max(rowid) as c FROM tx`.execute(this.db), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
149
- total = (approx.rows[0]?.c ?? 0) - (invalidCount?.count ?? 0);
150
- } else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await kysely.sql`SELECT max(rowid) as c FROM tx`.execute(this.db)).rows[0]?.c ?? 0;
147
+ else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) total = (await this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 1).executeTakeFirst())?.count ?? 0;
148
+ else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
151
149
  else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
152
150
  const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
153
151
  let rawResults;
@@ -11,26 +11,40 @@ let kysely = require("kysely");
11
11
  */
12
12
  var AccountTable = class extends require_table_base.default {
13
13
  /**
14
- * Override _insert to sync balance table after inserting an account.
14
+ * Override _insert to sync balance table atomically after inserting an account.
15
15
  */
16
- async _insert(row) {
17
- const result = await super._insert(row);
18
- await this.syncBalance(row);
19
- return result;
16
+ async _insert(row, context) {
17
+ const run = async (txnCtx) => {
18
+ const result = await super._insert(row, txnCtx);
19
+ await this.syncBalance(row, this.getExecutor(txnCtx));
20
+ return result;
21
+ };
22
+ if (context?.txn) return run(context);
23
+ return this.db.transaction().execute((txn) => run({
24
+ ...context,
25
+ txn
26
+ }));
20
27
  }
21
28
  /**
22
- * Override _update to sync balance table after updating an account.
29
+ * Override _update to sync balance table atomically after updating an account.
23
30
  */
24
- async _update(key, updates) {
25
- const result = await super._update(key, updates);
26
- await this.syncBalance(result);
27
- return result;
31
+ async _update(key, updates, context) {
32
+ const run = async (txnCtx) => {
33
+ const result = await super._update(key, updates, txnCtx);
34
+ await this.syncBalance(result, this.getExecutor(txnCtx));
35
+ return result;
36
+ };
37
+ if (context?.txn) return run(context);
38
+ return this.db.transaction().execute((txn) => run({
39
+ ...context,
40
+ txn
41
+ }));
28
42
  }
29
43
  /**
30
44
  * Sync the balance table from account tokens.
31
45
  * Deletes existing entries for this address, then inserts current token balances.
32
46
  */
33
- async syncBalance(data) {
47
+ async syncBalance(data, executor = this.db) {
34
48
  const address = data.address;
35
49
  if (!address) return;
36
50
  let tokens = data.tokens;
@@ -40,18 +54,28 @@ var AccountTable = class extends require_table_base.default {
40
54
  return;
41
55
  }
42
56
  if (!Array.isArray(tokens)) return;
43
- await kysely.sql`DELETE FROM balance WHERE address = ${address}`.execute(this.db);
57
+ await kysely.sql`DELETE FROM balance WHERE address = ${address}`.execute(executor);
44
58
  for (const t of tokens) if (t.address && t.balance && t.balance !== "0") {
45
59
  const balanceNum = (t.balance.replace(/^0+/, "") || "0").padStart(40, "0");
46
- await kysely.sql`INSERT INTO balance (address, tokenAddress, balance, balanceNum) VALUES (${address}, ${t.address}, ${t.balance}, ${balanceNum})`.execute(this.db);
60
+ await kysely.sql`INSERT OR REPLACE INTO balance (address, tokenAddress, balance, balanceNum) VALUES (${address}, ${t.address}, ${t.balance}, ${balanceNum})`.execute(executor);
47
61
  }
48
62
  }
49
63
  /**
50
- * Override _reset to also clear the balance table
64
+ * Override _reset to also clear the balance table atomically
51
65
  */
52
- async _reset() {
53
- await super._reset();
54
- await this.db.deleteFrom("balance").execute();
66
+ async _reset(context) {
67
+ const run = async (txnCtx) => {
68
+ await super._reset(txnCtx);
69
+ await this.getExecutor(txnCtx).deleteFrom("balance").execute();
70
+ };
71
+ if (context?.txn) {
72
+ await run(context);
73
+ return;
74
+ }
75
+ await this.db.transaction().execute((txn) => run({
76
+ ...context,
77
+ txn
78
+ }));
55
79
  }
56
80
  };
57
81
  var account_default = AccountTable;
@@ -1,3 +1,4 @@
1
+ import { SqliteOperationContext } from "../interfaces.cjs";
1
2
  import SqliteTable from "./base.cjs";
2
3
  import { TIndexedAccountState } from "@ocap/types";
3
4
 
@@ -10,22 +11,22 @@ import { TIndexedAccountState } from "@ocap/types";
10
11
  */
11
12
  declare class AccountTable extends SqliteTable<TIndexedAccountState> {
12
13
  /**
13
- * Override _insert to sync balance table after inserting an account.
14
+ * Override _insert to sync balance table atomically after inserting an account.
14
15
  */
15
- _insert(row: TIndexedAccountState | Record<string, unknown>): Promise<TIndexedAccountState>;
16
+ _insert(row: TIndexedAccountState | Record<string, unknown>, context?: SqliteOperationContext): Promise<TIndexedAccountState>;
16
17
  /**
17
- * Override _update to sync balance table after updating an account.
18
+ * Override _update to sync balance table atomically after updating an account.
18
19
  */
19
- _update(key: string | Record<string, unknown>, updates: Partial<TIndexedAccountState>): Promise<TIndexedAccountState>;
20
+ _update(key: string | Record<string, unknown>, updates: Partial<TIndexedAccountState>, context?: SqliteOperationContext): Promise<TIndexedAccountState>;
20
21
  /**
21
22
  * Sync the balance table from account tokens.
22
23
  * Deletes existing entries for this address, then inserts current token balances.
23
24
  */
24
25
  private syncBalance;
25
26
  /**
26
- * Override _reset to also clear the balance table
27
+ * Override _reset to also clear the balance table atomically
27
28
  */
28
- _reset(): Promise<void>;
29
+ _reset(context?: SqliteOperationContext): Promise<void>;
29
30
  }
30
31
  //#endregion
31
32
  export { AccountTable as default };
@@ -181,7 +181,7 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
181
181
  /**
182
182
  * Internal get implementation - called by BaseIndex.get() via hooks
183
183
  */
184
- async _get(key) {
184
+ async _get(key, context) {
185
185
  if (!key) return null;
186
186
  let query;
187
187
  if (Array.isArray(this.uniqIndex)) if (typeof key === "object") {
@@ -192,7 +192,7 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
192
192
  const id = typeof key === "string" ? key : key[this.primaryKey];
193
193
  query = { [this.mapColumnName(this.primaryKey)]: id };
194
194
  }
195
- let qb = this.db.selectFrom(this.name).selectAll();
195
+ let qb = this.getExecutor(context).selectFrom(this.name).selectAll();
196
196
  for (const [k, v] of Object.entries(query)) {
197
197
  if (v === void 0) continue;
198
198
  qb = qb.where(k, "=", v);
@@ -203,17 +203,17 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
203
203
  /**
204
204
  * Internal insert implementation - called by BaseIndex.insert() via hooks
205
205
  */
206
- async _insert(doc) {
206
+ async _insert(doc, context) {
207
207
  const data = doc;
208
208
  const serialized = this.serializeForDb(data);
209
- await this.db.insertInto(this.name).values(serialized).execute();
209
+ await this.getExecutor(context).insertInto(this.name).values(serialized).execute();
210
210
  return data;
211
211
  }
212
212
  /**
213
213
  * Internal update implementation - called by BaseIndex.update() via hooks
214
214
  */
215
- async _update(key, updates) {
216
- const existing = await this._get(key);
215
+ async _update(key, updates, context) {
216
+ const existing = await this._get(key, context);
217
217
  if (!existing) throw new Error(`${this.name} does not exist: ${JSON.stringify(key)}`);
218
218
  let query;
219
219
  if (Array.isArray(this.uniqIndex)) {
@@ -228,7 +228,7 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
228
228
  else delete updateAttrs[this.primaryKey];
229
229
  if (Object.keys(updateAttrs).length > 0) {
230
230
  const serialized = this.serializeForDbUpdate(updateAttrs, existing);
231
- let qb = this.db.updateTable(this.name).set(serialized);
231
+ let qb = this.getExecutor(context).updateTable(this.name).set(serialized);
232
232
  for (const [k, v] of Object.entries(query)) {
233
233
  if (v === void 0) continue;
234
234
  qb = qb.where(k, "=", v);
@@ -243,8 +243,9 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
243
243
  /**
244
244
  * Count documents matching a query
245
245
  */
246
- async count(query) {
247
- let qb = this.db.selectFrom(this.name).select(this.db.fn.countAll().as("count"));
246
+ async count(query, context) {
247
+ const executor = this.getExecutor(context);
248
+ let qb = executor.selectFrom(this.name).select(executor.fn.countAll().as("count"));
248
249
  if (query && typeof query === "object") for (const [k, v] of Object.entries(query)) {
249
250
  const mappedKey = this.mapColumnName(k);
250
251
  if (v && typeof v === "object" && "$in" in v) qb = qb.where(mappedKey, "in", v.$in);
@@ -255,8 +256,8 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
255
256
  /**
256
257
  * Internal reset implementation - called by BaseIndex.reset() via hooks
257
258
  */
258
- async _reset() {
259
- await this.db.deleteFrom(this.name).execute();
259
+ async _reset(context) {
260
+ await this.getExecutor(context).deleteFrom(this.name).execute();
260
261
  }
261
262
  };
262
263
  var base_default = SqliteTable;
@@ -85,23 +85,23 @@ declare class SqliteTable<T = unknown> extends BaseIndex<T> implements IIndexTab
85
85
  /**
86
86
  * Internal get implementation - called by BaseIndex.get() via hooks
87
87
  */
88
- _get(key: string | Record<string, unknown>): Promise<T | null>;
88
+ _get(key: string | Record<string, unknown>, context?: SqliteOperationContext): Promise<T | null>;
89
89
  /**
90
90
  * Internal insert implementation - called by BaseIndex.insert() via hooks
91
91
  */
92
- _insert(doc: T | Record<string, unknown>): Promise<T>;
92
+ _insert(doc: T | Record<string, unknown>, context?: SqliteOperationContext): Promise<T>;
93
93
  /**
94
94
  * Internal update implementation - called by BaseIndex.update() via hooks
95
95
  */
96
- _update(key: string | Record<string, unknown>, updates: Partial<T>): Promise<T>;
96
+ _update(key: string | Record<string, unknown>, updates: Partial<T>, context?: SqliteOperationContext): Promise<T>;
97
97
  /**
98
98
  * Count documents matching a query
99
99
  */
100
- count(query?: unknown): Promise<number>;
100
+ count(query?: unknown, context?: SqliteOperationContext): Promise<number>;
101
101
  /**
102
102
  * Internal reset implementation - called by BaseIndex.reset() via hooks
103
103
  */
104
- _reset(): Promise<void>;
104
+ _reset(context?: SqliteOperationContext): Promise<void>;
105
105
  }
106
106
  //#endregion
107
107
  export { SqliteTableConfig, TableSchema, SqliteTable as default };
@@ -26,25 +26,67 @@ var TransactionTable = class extends require_table_base.default {
26
26
  * This populates assets, tokens, factories, etc. from itxJson,
27
27
  * then inserts corresponding rows into tx_ref for indexed lookups.
28
28
  */
29
- async _insert(row) {
29
+ async _insert(row, context) {
30
30
  const formatted = (0, _ocap_indexdb.formatTxBeforeInsert)(row);
31
- const result = await super._insert(formatted);
32
- const data = formatted;
31
+ const run = async (txnCtx) => {
32
+ const result = await super._insert(formatted, txnCtx);
33
+ await this.syncTxRefs(formatted, txnCtx, false);
34
+ return result;
35
+ };
36
+ if (context?.txn) return run(context);
37
+ return this.db.transaction().execute((txn) => run({
38
+ ...context,
39
+ txn
40
+ }));
41
+ }
42
+ /**
43
+ * Override _update to also keep tx_ref junction table synchronized atomically
44
+ */
45
+ async _update(key, updates, context) {
46
+ const run = async (txnCtx) => {
47
+ const result = await super._update(key, updates, txnCtx);
48
+ await this.syncTxRefs(result, txnCtx, true);
49
+ return result;
50
+ };
51
+ if (context?.txn) return run(context);
52
+ return this.db.transaction().execute((txn) => run({
53
+ ...context,
54
+ txn
55
+ }));
56
+ }
57
+ async syncTxRefs(data, context, replaceExisting = false) {
33
58
  const hash = data.hash;
59
+ if (!hash) return;
60
+ const executor = this.getExecutor(context);
61
+ if (replaceExisting) await kysely.sql`DELETE FROM tx_ref WHERE hash = ${hash}`.execute(executor);
34
62
  const time = data.time || null;
35
63
  for (const [type, field] of TX_REF_TYPES) {
36
- const values = data[field];
64
+ let values = data[field];
65
+ if (typeof values === "string") try {
66
+ values = JSON.parse(values);
67
+ } catch {
68
+ continue;
69
+ }
37
70
  if (!Array.isArray(values) || values.length === 0) continue;
38
- for (const v of values) if (typeof v === "string" && v) await kysely.sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(this.db);
71
+ for (const v of values) if (typeof v === "string" && v) await kysely.sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(executor);
39
72
  }
40
- return result;
41
73
  }
42
74
  /**
43
75
  * Override _reset to also clear the tx_ref junction table
44
76
  */
45
- async _reset() {
46
- await super._reset();
47
- await this.db.deleteFrom("tx_ref").execute();
77
+ async _reset(context) {
78
+ const run = async (txnCtx) => {
79
+ await super._reset(txnCtx);
80
+ await this.getExecutor(txnCtx).deleteFrom("tx_ref").execute();
81
+ };
82
+ if (context?.txn) {
83
+ await run(context);
84
+ return;
85
+ }
86
+ await this.db.transaction().execute((txn) => run({
87
+ ...context,
88
+ txn
89
+ }));
48
90
  }
49
91
  };
50
92
  var transaction_default = TransactionTable;
@@ -1,3 +1,4 @@
1
+ import { SqliteOperationContext } from "../interfaces.cjs";
1
2
  import SqliteTable from "./base.cjs";
2
3
  import { TIndexedTransaction } from "@ocap/types";
3
4
 
@@ -14,11 +15,16 @@ declare class TransactionTable extends SqliteTable<TIndexedTransaction> {
14
15
  * This populates assets, tokens, factories, etc. from itxJson,
15
16
  * then inserts corresponding rows into tx_ref for indexed lookups.
16
17
  */
17
- _insert(row: TIndexedTransaction | Record<string, unknown>): Promise<TIndexedTransaction>;
18
+ _insert(row: TIndexedTransaction | Record<string, unknown>, context?: SqliteOperationContext): Promise<TIndexedTransaction>;
19
+ /**
20
+ * Override _update to also keep tx_ref junction table synchronized atomically
21
+ */
22
+ _update(key: string | Record<string, unknown>, updates: Partial<TIndexedTransaction>, context?: SqliteOperationContext): Promise<TIndexedTransaction>;
23
+ private syncTxRefs;
18
24
  /**
19
25
  * Override _reset to also clear the tx_ref junction table
20
26
  */
21
- _reset(): Promise<void>;
27
+ _reset(context?: SqliteOperationContext): Promise<void>;
22
28
  }
23
29
  //#endregion
24
30
  export { TransactionTable as default };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ocap/indexdb-sqlite",
3
3
  "description": "OCAP indexdb adapter that uses SQLite as backend",
4
- "version": "1.30.26",
4
+ "version": "1.31.0",
5
5
  "author": "wangshijun <shijun@arcblock.io> (https://www.arcblock.io)",
6
6
  "bugs": {
7
7
  "url": "https://github.com/ArcBlock/blockchain/issues",
@@ -14,7 +14,7 @@
14
14
  "wangshijun <shijun@arcblock.io> (https://www.arcblock.io)"
15
15
  ],
16
16
  "devDependencies": {
17
- "@ocap/indexdb-test": "1.30.26"
17
+ "@ocap/indexdb-test": "1.31.0"
18
18
  },
19
19
  "homepage": "https://github.com/ArcBlock/blockchain/tree/master/indexdb/sqlite",
20
20
  "keywords": [
@@ -63,10 +63,10 @@
63
63
  "clean": "rm -rf lib esm"
64
64
  },
65
65
  "dependencies": {
66
- "@arcblock/did": "1.30.26",
67
- "@ocap/indexdb": "1.30.26",
68
- "@ocap/types": "1.30.26",
69
- "@ocap/util": "1.30.26",
66
+ "@arcblock/did": "1.31.0",
67
+ "@ocap/indexdb": "1.31.0",
68
+ "@ocap/types": "1.31.0",
69
+ "@ocap/util": "1.31.0",
70
70
  "debug": "^4.4.3",
71
71
  "better-sqlite3": "^11.8.1",
72
72
  "kysely": "^0.28.14",