@ocap/indexdb-sqlite 1.30.26 → 1.31.1
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.d.mts +18 -0
- package/esm/db/base.mjs +64 -12
- package/esm/db/index.mjs +2 -0
- package/esm/interfaces.d.mts +1 -0
- package/esm/migrations/001-genesis.mjs +2 -1
- package/esm/migrations/009-tx-gas-payer.d.mts +17 -0
- package/esm/migrations/009-tx-gas-payer.mjs +28 -0
- package/esm/migrations/index.mjs +3 -1
- package/esm/table/account.d.mts +7 -6
- package/esm/table/account.mjs +41 -17
- package/esm/table/base.d.mts +5 -5
- package/esm/table/base.mjs +12 -11
- package/esm/table/transaction.d.mts +8 -2
- package/esm/table/transaction.mjs +51 -9
- package/lib/db/base.cjs +64 -12
- package/lib/db/base.d.cts +18 -0
- package/lib/db/index.cjs +2 -0
- package/lib/interfaces.d.cts +1 -0
- package/lib/migrations/001-genesis.cjs +2 -1
- package/lib/migrations/009-tx-gas-payer.cjs +35 -0
- package/lib/migrations/009-tx-gas-payer.d.cts +17 -0
- package/lib/migrations/index.cjs +3 -1
- package/lib/table/account.cjs +41 -17
- package/lib/table/account.d.cts +7 -6
- package/lib/table/base.cjs +12 -11
- package/lib/table/base.d.cts +5 -5
- package/lib/table/transaction.cjs +51 -9
- package/lib/table/transaction.d.cts +8 -2
- package/package.json +6 -6
package/esm/db/base.d.mts
CHANGED
|
@@ -23,6 +23,24 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
|
|
|
23
23
|
rollupValidator: IIndexTable<IndexTableTypeMap['rollupValidator']>;
|
|
24
24
|
tokenDistribution: IIndexTable<IndexTableTypeMap['tokenDistribution']>;
|
|
25
25
|
tokenFactory: IIndexTable<IndexTableTypeMap['tokenFactory']>;
|
|
26
|
+
protected txCountCache: {
|
|
27
|
+
total: number;
|
|
28
|
+
invalid: number;
|
|
29
|
+
totalChanges: number;
|
|
30
|
+
dataVersion: number;
|
|
31
|
+
maxRowId: number;
|
|
32
|
+
} | null;
|
|
33
|
+
/**
|
|
34
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
35
|
+
*
|
|
36
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
37
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
38
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
39
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
40
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
41
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
42
|
+
*/
|
|
43
|
+
private getExactTxCounts;
|
|
26
44
|
/**
|
|
27
45
|
* List transactions with filtering and pagination
|
|
28
46
|
*/
|
package/esm/db/base.mjs
CHANGED
|
@@ -32,18 +32,65 @@ function buildPagingResult(total, pagination, itemCount) {
|
|
|
32
32
|
* Contains all the list methods with SQL-based filtering
|
|
33
33
|
*/
|
|
34
34
|
var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
35
|
+
constructor(..._args) {
|
|
36
|
+
super(..._args);
|
|
37
|
+
this.txCountCache = null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
41
|
+
*
|
|
42
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
43
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
44
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
45
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
46
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
47
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
48
|
+
*/
|
|
49
|
+
async getExactTxCounts() {
|
|
50
|
+
const probeRow = (await sql`
|
|
51
|
+
SELECT
|
|
52
|
+
total_changes() as tc,
|
|
53
|
+
(SELECT data_version FROM pragma_data_version) as dv,
|
|
54
|
+
COALESCE((SELECT max(rowid) FROM tx), 0) as maxRowId
|
|
55
|
+
`.execute(this.db)).rows[0];
|
|
56
|
+
const tc = Number(probeRow?.tc ?? -1);
|
|
57
|
+
const dv = Number(probeRow?.dv ?? -1);
|
|
58
|
+
const maxRowId = Number(probeRow?.maxRowId ?? 0);
|
|
59
|
+
const cached = this.txCountCache;
|
|
60
|
+
if (cached && tc >= 0 && dv >= 0 && cached.totalChanges === tc && cached.dataVersion === dv && cached.maxRowId === maxRowId) return {
|
|
61
|
+
total: cached.total,
|
|
62
|
+
valid: Math.max(0, cached.total - cached.invalid),
|
|
63
|
+
invalid: cached.invalid
|
|
64
|
+
};
|
|
65
|
+
const [allCount, invalidCount] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
|
|
66
|
+
const total = Number(allCount?.count ?? 0);
|
|
67
|
+
const invalid = Number(invalidCount?.count ?? 0);
|
|
68
|
+
this.txCountCache = {
|
|
69
|
+
total,
|
|
70
|
+
invalid,
|
|
71
|
+
totalChanges: tc,
|
|
72
|
+
dataVersion: dv,
|
|
73
|
+
maxRowId
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
total,
|
|
77
|
+
valid: Math.max(0, total - invalid),
|
|
78
|
+
invalid
|
|
79
|
+
};
|
|
80
|
+
}
|
|
35
81
|
/**
|
|
36
82
|
* List transactions with filtering and pagination
|
|
37
83
|
*/
|
|
38
84
|
async listTransactions(params = {}) {
|
|
39
85
|
const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
|
|
40
|
-
const { sender, receiver, direction = "UNION" } = addressFilter;
|
|
86
|
+
const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
|
|
41
87
|
const { types = [] } = typeFilter;
|
|
42
88
|
const { factories = [] } = factoryFilter;
|
|
43
89
|
const { assets = [] } = assetFilter;
|
|
44
90
|
const { tokens = [] } = tokenFilter;
|
|
45
91
|
const { accounts = [] } = accountFilter;
|
|
46
|
-
const { txs = [] } = txFilter;
|
|
92
|
+
const { txs = [], gasPayer: txGasPayer } = txFilter;
|
|
93
|
+
const gasPayer = addressGasPayer || txGasPayer || "";
|
|
47
94
|
const { rollups = [] } = rollupFilter;
|
|
48
95
|
const { stakes = [] } = stakeFilter;
|
|
49
96
|
const { delegations = [] } = delegationFilter;
|
|
@@ -56,12 +103,14 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
56
103
|
"renaissanceTime",
|
|
57
104
|
"time",
|
|
58
105
|
"sender",
|
|
59
|
-
"receiver"
|
|
106
|
+
"receiver",
|
|
107
|
+
"gasPayer"
|
|
60
108
|
]
|
|
61
109
|
});
|
|
62
110
|
debug("listTransactions", {
|
|
63
111
|
sender,
|
|
64
112
|
receiver,
|
|
113
|
+
gasPayer,
|
|
65
114
|
pagination,
|
|
66
115
|
types,
|
|
67
116
|
factories,
|
|
@@ -74,12 +123,15 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
74
123
|
includeItxData
|
|
75
124
|
});
|
|
76
125
|
let qb = this.db.selectFrom("tx").selectAll();
|
|
77
|
-
const isMutual = !!(sender && receiver && direction === "MUTUAL");
|
|
126
|
+
const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
|
|
78
127
|
const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
|
|
79
|
-
if (sender && receiver) if (direction === "MUTUAL") {
|
|
128
|
+
if (sender && receiver) if (direction === "MUTUAL") {
|
|
129
|
+
if (!isMutual) qb = qb.where((eb) => eb.or([eb.and([eb("sender", "=", sender), eb("receiver", "=", receiver)]), eb.and([eb("sender", "=", receiver), eb("receiver", "=", sender)])]));
|
|
130
|
+
} else if (direction === "ONE_WAY") qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
|
|
80
131
|
else qb = qb.where((eb) => eb.or([eb("sender", "=", sender), eb("receiver", "=", receiver)]));
|
|
81
132
|
else if (sender) qb = qb.where("sender", "=", sender);
|
|
82
133
|
else if (receiver) qb = qb.where("receiver", "=", receiver);
|
|
134
|
+
if (gasPayer) qb = qb.where("gasPayer", "=", gasPayer);
|
|
83
135
|
if (types.length) qb = qb.where("type", "in", types);
|
|
84
136
|
if (txs.length) qb = qb.where("hash", "in", txs);
|
|
85
137
|
const { startDateTime, endDateTime } = timeFilter;
|
|
@@ -123,9 +175,9 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
123
175
|
if (stakes.length) activeJsonFilters.push(["stake", stakes]);
|
|
124
176
|
if (delegations.length) activeJsonFilters.push(["delegation", delegations]);
|
|
125
177
|
if (tokenFactories.length) activeJsonFilters.push(["tokenFactory", tokenFactories]);
|
|
126
|
-
const hasNonJsonFilters = !!(sender || receiver || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
127
|
-
const isUnionOnly = isUnion && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
128
|
-
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
178
|
+
const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
179
|
+
const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
180
|
+
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
129
181
|
if (isMutual) {
|
|
130
182
|
const [c1, c2] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).where("receiver", "=", receiver).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", receiver).where("receiver", "=", sender).executeTakeFirst()]);
|
|
131
183
|
total = (c1?.count ?? 0) + (c2?.count ?? 0);
|
|
@@ -140,10 +192,10 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
140
192
|
]);
|
|
141
193
|
total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
|
|
142
194
|
} 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
|
|
145
|
-
total =
|
|
146
|
-
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await
|
|
195
|
+
else if ((validity === "VALID" || validity === "INVALID") && !sender && !receiver && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
|
|
196
|
+
const counts = await this.getExactTxCounts();
|
|
197
|
+
total = validity === "VALID" ? counts.valid : counts.invalid;
|
|
198
|
+
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.getExactTxCounts()).total;
|
|
147
199
|
else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
|
|
148
200
|
const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
|
|
149
201
|
let rawResults;
|
package/esm/db/index.mjs
CHANGED
|
@@ -77,6 +77,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
77
77
|
"receiptsVerified",
|
|
78
78
|
"receiver",
|
|
79
79
|
"sender",
|
|
80
|
+
"gasPayer",
|
|
80
81
|
"time",
|
|
81
82
|
"tx",
|
|
82
83
|
"type",
|
|
@@ -544,6 +545,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
544
545
|
* Reset all tables (for testing)
|
|
545
546
|
*/
|
|
546
547
|
async reset() {
|
|
548
|
+
this.txCountCache = null;
|
|
547
549
|
for (const table of [
|
|
548
550
|
"tx",
|
|
549
551
|
"account",
|
package/esm/interfaces.d.mts
CHANGED
|
@@ -10,9 +10,10 @@ var _001_genesis_exports = /* @__PURE__ */ __exportAll({
|
|
|
10
10
|
* Genesis migration - creates all IndexDB tables
|
|
11
11
|
*/
|
|
12
12
|
async function up(db) {
|
|
13
|
-
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
13
|
+
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("gasPayer", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
14
14
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_sender ON tx(sender)`.execute(db);
|
|
15
15
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_receiver ON tx(receiver)`.execute(db);
|
|
16
|
+
await sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
16
17
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_type ON tx(type)`.execute(db);
|
|
17
18
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_time ON tx(time)`.execute(db);
|
|
18
19
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_height ON tx(height)`.execute(db);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/009-tx-gas-payer.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
7
|
+
*
|
|
8
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
9
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
10
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
11
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
12
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
13
|
+
*/
|
|
14
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { down, up };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { __exportAll } from "../_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/009-tx-gas-payer.ts
|
|
5
|
+
var _009_tx_gas_payer_exports = /* @__PURE__ */ __exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
11
|
+
*
|
|
12
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
13
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
14
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
15
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
16
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
17
|
+
*/
|
|
18
|
+
async function up(db) {
|
|
19
|
+
const columnsResult = await sql`PRAGMA table_info('tx')`.execute(db);
|
|
20
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("gasPayer")) await sql`ALTER TABLE tx ADD COLUMN gasPayer TEXT`.execute(db);
|
|
21
|
+
await sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
22
|
+
}
|
|
23
|
+
async function down(db) {
|
|
24
|
+
await sql`DROP INDEX IF EXISTS idx_tx_gasPayer`.execute(db);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { _009_tx_gas_payer_exports, down, up };
|
package/esm/migrations/index.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { _005_rollup_missing_columns_exports } from "./005-rollup-missing-column
|
|
|
6
6
|
import { _006_rollup_block_height_integer_exports } from "./006-rollup-block-height-integer.mjs";
|
|
7
7
|
import { _007_token_factory_feerate_integer_exports } from "./007-token-factory-feerate-integer.mjs";
|
|
8
8
|
import { _008_index_failure_exports } from "./008-index-failure.mjs";
|
|
9
|
+
import { _009_tx_gas_payer_exports } from "./009-tx-gas-payer.mjs";
|
|
9
10
|
import { Migrator } from "kysely";
|
|
10
11
|
|
|
11
12
|
//#region src/migrations/index.ts
|
|
@@ -23,7 +24,8 @@ var InMemoryMigrationProvider = class {
|
|
|
23
24
|
"005-rollup-missing-columns": _005_rollup_missing_columns_exports,
|
|
24
25
|
"006-rollup-block-height-integer": _006_rollup_block_height_integer_exports,
|
|
25
26
|
"007-token-factory-feerate-integer": _007_token_factory_feerate_integer_exports,
|
|
26
|
-
"008-index-failure": _008_index_failure_exports
|
|
27
|
+
"008-index-failure": _008_index_failure_exports,
|
|
28
|
+
"009-tx-gas-payer": _009_tx_gas_payer_exports
|
|
27
29
|
};
|
|
28
30
|
}
|
|
29
31
|
};
|
package/esm/table/account.d.mts
CHANGED
|
@@ -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
|
|
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
|
|
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 };
|
package/esm/table/account.mjs
CHANGED
|
@@ -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
|
|
16
|
-
|
|
17
|
-
|
|
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
|
|
24
|
-
|
|
25
|
-
|
|
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(
|
|
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(
|
|
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
|
-
|
|
52
|
-
|
|
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;
|
package/esm/table/base.d.mts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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 };
|
package/esm/table/base.mjs
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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
|
|
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
|
|
30
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
45
|
-
|
|
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
|
@@ -36,18 +36,65 @@ function buildPagingResult(total, pagination, itemCount) {
|
|
|
36
36
|
* Contains all the list methods with SQL-based filtering
|
|
37
37
|
*/
|
|
38
38
|
var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
39
|
+
constructor(..._args) {
|
|
40
|
+
super(..._args);
|
|
41
|
+
this.txCountCache = null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
45
|
+
*
|
|
46
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
47
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
48
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
49
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
50
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
51
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
52
|
+
*/
|
|
53
|
+
async getExactTxCounts() {
|
|
54
|
+
const probeRow = (await kysely.sql`
|
|
55
|
+
SELECT
|
|
56
|
+
total_changes() as tc,
|
|
57
|
+
(SELECT data_version FROM pragma_data_version) as dv,
|
|
58
|
+
COALESCE((SELECT max(rowid) FROM tx), 0) as maxRowId
|
|
59
|
+
`.execute(this.db)).rows[0];
|
|
60
|
+
const tc = Number(probeRow?.tc ?? -1);
|
|
61
|
+
const dv = Number(probeRow?.dv ?? -1);
|
|
62
|
+
const maxRowId = Number(probeRow?.maxRowId ?? 0);
|
|
63
|
+
const cached = this.txCountCache;
|
|
64
|
+
if (cached && tc >= 0 && dv >= 0 && cached.totalChanges === tc && cached.dataVersion === dv && cached.maxRowId === maxRowId) return {
|
|
65
|
+
total: cached.total,
|
|
66
|
+
valid: Math.max(0, cached.total - cached.invalid),
|
|
67
|
+
invalid: cached.invalid
|
|
68
|
+
};
|
|
69
|
+
const [allCount, invalidCount] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
|
|
70
|
+
const total = Number(allCount?.count ?? 0);
|
|
71
|
+
const invalid = Number(invalidCount?.count ?? 0);
|
|
72
|
+
this.txCountCache = {
|
|
73
|
+
total,
|
|
74
|
+
invalid,
|
|
75
|
+
totalChanges: tc,
|
|
76
|
+
dataVersion: dv,
|
|
77
|
+
maxRowId
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
total,
|
|
81
|
+
valid: Math.max(0, total - invalid),
|
|
82
|
+
invalid
|
|
83
|
+
};
|
|
84
|
+
}
|
|
39
85
|
/**
|
|
40
86
|
* List transactions with filtering and pagination
|
|
41
87
|
*/
|
|
42
88
|
async listTransactions(params = {}) {
|
|
43
89
|
const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
|
|
44
|
-
const { sender, receiver, direction = "UNION" } = addressFilter;
|
|
90
|
+
const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
|
|
45
91
|
const { types = [] } = typeFilter;
|
|
46
92
|
const { factories = [] } = factoryFilter;
|
|
47
93
|
const { assets = [] } = assetFilter;
|
|
48
94
|
const { tokens = [] } = tokenFilter;
|
|
49
95
|
const { accounts = [] } = accountFilter;
|
|
50
|
-
const { txs = [] } = txFilter;
|
|
96
|
+
const { txs = [], gasPayer: txGasPayer } = txFilter;
|
|
97
|
+
const gasPayer = addressGasPayer || txGasPayer || "";
|
|
51
98
|
const { rollups = [] } = rollupFilter;
|
|
52
99
|
const { stakes = [] } = stakeFilter;
|
|
53
100
|
const { delegations = [] } = delegationFilter;
|
|
@@ -60,12 +107,14 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
60
107
|
"renaissanceTime",
|
|
61
108
|
"time",
|
|
62
109
|
"sender",
|
|
63
|
-
"receiver"
|
|
110
|
+
"receiver",
|
|
111
|
+
"gasPayer"
|
|
64
112
|
]
|
|
65
113
|
});
|
|
66
114
|
debug$1("listTransactions", {
|
|
67
115
|
sender,
|
|
68
116
|
receiver,
|
|
117
|
+
gasPayer,
|
|
69
118
|
pagination,
|
|
70
119
|
types,
|
|
71
120
|
factories,
|
|
@@ -78,12 +127,15 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
78
127
|
includeItxData
|
|
79
128
|
});
|
|
80
129
|
let qb = this.db.selectFrom("tx").selectAll();
|
|
81
|
-
const isMutual = !!(sender && receiver && direction === "MUTUAL");
|
|
130
|
+
const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
|
|
82
131
|
const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
|
|
83
|
-
if (sender && receiver) if (direction === "MUTUAL") {
|
|
132
|
+
if (sender && receiver) if (direction === "MUTUAL") {
|
|
133
|
+
if (!isMutual) qb = qb.where((eb) => eb.or([eb.and([eb("sender", "=", sender), eb("receiver", "=", receiver)]), eb.and([eb("sender", "=", receiver), eb("receiver", "=", sender)])]));
|
|
134
|
+
} else if (direction === "ONE_WAY") qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
|
|
84
135
|
else qb = qb.where((eb) => eb.or([eb("sender", "=", sender), eb("receiver", "=", receiver)]));
|
|
85
136
|
else if (sender) qb = qb.where("sender", "=", sender);
|
|
86
137
|
else if (receiver) qb = qb.where("receiver", "=", receiver);
|
|
138
|
+
if (gasPayer) qb = qb.where("gasPayer", "=", gasPayer);
|
|
87
139
|
if (types.length) qb = qb.where("type", "in", types);
|
|
88
140
|
if (txs.length) qb = qb.where("hash", "in", txs);
|
|
89
141
|
const { startDateTime, endDateTime } = timeFilter;
|
|
@@ -127,9 +179,9 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
127
179
|
if (stakes.length) activeJsonFilters.push(["stake", stakes]);
|
|
128
180
|
if (delegations.length) activeJsonFilters.push(["delegation", delegations]);
|
|
129
181
|
if (tokenFactories.length) activeJsonFilters.push(["tokenFactory", tokenFactories]);
|
|
130
|
-
const hasNonJsonFilters = !!(sender || receiver || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
131
|
-
const isUnionOnly = isUnion && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
132
|
-
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
182
|
+
const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
183
|
+
const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
184
|
+
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
133
185
|
if (isMutual) {
|
|
134
186
|
const [c1, c2] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).where("receiver", "=", receiver).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", receiver).where("receiver", "=", sender).executeTakeFirst()]);
|
|
135
187
|
total = (c1?.count ?? 0) + (c2?.count ?? 0);
|
|
@@ -144,10 +196,10 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
144
196
|
]);
|
|
145
197
|
total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
|
|
146
198
|
} 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
|
|
149
|
-
total =
|
|
150
|
-
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await
|
|
199
|
+
else if ((validity === "VALID" || validity === "INVALID") && !sender && !receiver && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
|
|
200
|
+
const counts = await this.getExactTxCounts();
|
|
201
|
+
total = validity === "VALID" ? counts.valid : counts.invalid;
|
|
202
|
+
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.getExactTxCounts()).total;
|
|
151
203
|
else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
|
|
152
204
|
const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
|
|
153
205
|
let rawResults;
|
package/lib/db/base.d.cts
CHANGED
|
@@ -23,6 +23,24 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
|
|
|
23
23
|
rollupValidator: IIndexTable<IndexTableTypeMap['rollupValidator']>;
|
|
24
24
|
tokenDistribution: IIndexTable<IndexTableTypeMap['tokenDistribution']>;
|
|
25
25
|
tokenFactory: IIndexTable<IndexTableTypeMap['tokenFactory']>;
|
|
26
|
+
protected txCountCache: {
|
|
27
|
+
total: number;
|
|
28
|
+
invalid: number;
|
|
29
|
+
totalChanges: number;
|
|
30
|
+
dataVersion: number;
|
|
31
|
+
maxRowId: number;
|
|
32
|
+
} | null;
|
|
33
|
+
/**
|
|
34
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
35
|
+
*
|
|
36
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
37
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
38
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
39
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
40
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
41
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
42
|
+
*/
|
|
43
|
+
private getExactTxCounts;
|
|
26
44
|
/**
|
|
27
45
|
* List transactions with filtering and pagination
|
|
28
46
|
*/
|
package/lib/db/index.cjs
CHANGED
|
@@ -78,6 +78,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
78
78
|
"receiptsVerified",
|
|
79
79
|
"receiver",
|
|
80
80
|
"sender",
|
|
81
|
+
"gasPayer",
|
|
81
82
|
"time",
|
|
82
83
|
"tx",
|
|
83
84
|
"type",
|
|
@@ -545,6 +546,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
545
546
|
* Reset all tables (for testing)
|
|
546
547
|
*/
|
|
547
548
|
async reset() {
|
|
549
|
+
this.txCountCache = null;
|
|
548
550
|
for (const table of [
|
|
549
551
|
"tx",
|
|
550
552
|
"account",
|
package/lib/interfaces.d.cts
CHANGED
|
@@ -10,9 +10,10 @@ var _001_genesis_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll(
|
|
|
10
10
|
* Genesis migration - creates all IndexDB tables
|
|
11
11
|
*/
|
|
12
12
|
async function up(db) {
|
|
13
|
-
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
13
|
+
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("gasPayer", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
14
14
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_sender ON tx(sender)`.execute(db);
|
|
15
15
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_receiver ON tx(receiver)`.execute(db);
|
|
16
|
+
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
16
17
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_type ON tx(type)`.execute(db);
|
|
17
18
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_time ON tx(time)`.execute(db);
|
|
18
19
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_height ON tx(height)`.execute(db);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let kysely = require("kysely");
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/009-tx-gas-payer.ts
|
|
5
|
+
var _009_tx_gas_payer_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
11
|
+
*
|
|
12
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
13
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
14
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
15
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
16
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
17
|
+
*/
|
|
18
|
+
async function up(db) {
|
|
19
|
+
const columnsResult = await kysely.sql`PRAGMA table_info('tx')`.execute(db);
|
|
20
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("gasPayer")) await kysely.sql`ALTER TABLE tx ADD COLUMN gasPayer TEXT`.execute(db);
|
|
21
|
+
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
22
|
+
}
|
|
23
|
+
async function down(db) {
|
|
24
|
+
await kysely.sql`DROP INDEX IF EXISTS idx_tx_gasPayer`.execute(db);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
Object.defineProperty(exports, '_009_tx_gas_payer_exports', {
|
|
29
|
+
enumerable: true,
|
|
30
|
+
get: function () {
|
|
31
|
+
return _009_tx_gas_payer_exports;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
exports.down = down;
|
|
35
|
+
exports.up = up;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/009-tx-gas-payer.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
7
|
+
*
|
|
8
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
9
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
10
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
11
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
12
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
13
|
+
*/
|
|
14
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { down, up };
|
package/lib/migrations/index.cjs
CHANGED
|
@@ -7,6 +7,7 @@ const require_migrations_005_rollup_missing_columns = require('./005-rollup-miss
|
|
|
7
7
|
const require_migrations_006_rollup_block_height_integer = require('./006-rollup-block-height-integer.cjs');
|
|
8
8
|
const require_migrations_007_token_factory_feerate_integer = require('./007-token-factory-feerate-integer.cjs');
|
|
9
9
|
const require_migrations_008_index_failure = require('./008-index-failure.cjs');
|
|
10
|
+
const require_migrations_009_tx_gas_payer = require('./009-tx-gas-payer.cjs');
|
|
10
11
|
let kysely = require("kysely");
|
|
11
12
|
|
|
12
13
|
//#region src/migrations/index.ts
|
|
@@ -24,7 +25,8 @@ var InMemoryMigrationProvider = class {
|
|
|
24
25
|
"005-rollup-missing-columns": require_migrations_005_rollup_missing_columns._005_rollup_missing_columns_exports,
|
|
25
26
|
"006-rollup-block-height-integer": require_migrations_006_rollup_block_height_integer._006_rollup_block_height_integer_exports,
|
|
26
27
|
"007-token-factory-feerate-integer": require_migrations_007_token_factory_feerate_integer._007_token_factory_feerate_integer_exports,
|
|
27
|
-
"008-index-failure": require_migrations_008_index_failure._008_index_failure_exports
|
|
28
|
+
"008-index-failure": require_migrations_008_index_failure._008_index_failure_exports,
|
|
29
|
+
"009-tx-gas-payer": require_migrations_009_tx_gas_payer._009_tx_gas_payer_exports
|
|
28
30
|
};
|
|
29
31
|
}
|
|
30
32
|
};
|
package/lib/table/account.cjs
CHANGED
|
@@ -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
|
|
18
|
-
|
|
19
|
-
|
|
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
|
|
26
|
-
|
|
27
|
-
|
|
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(
|
|
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(
|
|
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
|
-
|
|
54
|
-
|
|
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;
|
package/lib/table/account.d.cts
CHANGED
|
@@ -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
|
|
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
|
|
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 };
|
package/lib/table/base.cjs
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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.
|
|
259
|
+
async _reset(context) {
|
|
260
|
+
await this.getExecutor(context).deleteFrom(this.name).execute();
|
|
260
261
|
}
|
|
261
262
|
};
|
|
262
263
|
var base_default = SqliteTable;
|
package/lib/table/base.d.cts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
32
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
47
|
-
|
|
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
|
|
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.
|
|
4
|
+
"version": "1.31.1",
|
|
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.
|
|
17
|
+
"@ocap/indexdb-test": "1.31.1"
|
|
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.
|
|
67
|
-
"@ocap/indexdb": "1.
|
|
68
|
-
"@ocap/types": "1.
|
|
69
|
-
"@ocap/util": "1.
|
|
66
|
+
"@arcblock/did": "1.31.1",
|
|
67
|
+
"@ocap/indexdb": "1.31.1",
|
|
68
|
+
"@ocap/types": "1.31.1",
|
|
69
|
+
"@ocap/util": "1.31.1",
|
|
70
70
|
"debug": "^4.4.3",
|
|
71
71
|
"better-sqlite3": "^11.8.1",
|
|
72
72
|
"kysely": "^0.28.14",
|