@ocap/indexdb-sqlite 1.31.6 → 1.31.8

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.
@@ -0,0 +1,131 @@
1
+ import { Kysely } from "kysely";
2
+
3
+ //#region src/tx-ref-tx-type.d.ts
4
+
5
+ /**
6
+ * tx_ref.tx_type + idx_tx_ref_type_value_txtype_time (#1870, step 2 of #1861) - OFFLINE ONLY (#1885)
7
+ *
8
+ * `tx_ref.tx_type` is a denormalized copy of `tx.type`, so a type-filtered count of an account's history
9
+ * (`tx_ref type/value + tx.type in (...)`, the wallet's `page { total }`) is answered from one covering index
10
+ * on tx_ref instead of probing every `tx` row of the account.
11
+ *
12
+ * Not part of the startup migration chain (migration 011 is a recorded no-op): a chain node never adds the
13
+ * column, back-fills or builds the index while starting. The only entry point is `migrateTxRefTxType`, run by
14
+ * `scripts/ops/indexdb-migrate.mjs` with the chain stopped. SqliteIndexDB.initialize() only detects the state:
15
+ * - no column (1.31.7 schema): writes and queries use exactly the 1.31.7 SQL
16
+ * - column but no index (offline run interrupted): writes fill tx_type, queries stay on the 1.31.7 SQL
17
+ * - column + index: writes fill tx_type, listTransactions uses the tx_type path
18
+ *
19
+ * `migrateTxRefTxType` steps (each idempotent, so an interrupted run is simply re-run):
20
+ * 1. `ALTER TABLE tx_ref ADD COLUMN tx_type` (instant, metadata only).
21
+ * 2. Back-fill driven by `tx` rowid batches: `UPDATE tx_ref ... FROM (SELECT hash, type FROM tx WHERE rowid
22
+ * in batch)`, one transaction per batch that also stores the next rowid in `tx_ref_tx_type_backfill`, so a
23
+ * resumed run continues where the killed one stopped. Yields to the event loop between batches.
24
+ * Driving from `tx` reads every tx row once, in order. Driving from tx_ref would read a tx row once per
25
+ * tx_ref row (2.4M vs 0.7M on main), and reading `tx.type` walks the overflow pages of the big `tx`
26
+ * JSON column that precedes it, so that is several passes over a table larger than main's RAM.
27
+ * Only `tx_type IS NULL` rows are written. Rows written meanwhile by TransactionTable (same process, or a
28
+ * node started on a half-migrated file) already carry tx_type.
29
+ * 3. `CREATE INDEX` - only after the back-fill finished. Query-side readiness is "this index exists"
30
+ * (see isTxRefTxTypeReady), so a partially filled column is never queried. Then the progress table is
31
+ * dropped.
32
+ *
33
+ * Rows left NULL after the back-fill have no `tx` row (orphans) or a NULL `tx.type`; neither can match a
34
+ * `type in (...)` filter on either path, so results stay identical.
35
+ */
36
+ declare const TX_REF_TX_TYPE_INDEX = "idx_tx_ref_type_value_txtype_time";
37
+ /** Progress of an unfinished back-fill: one row, the next tx rowid to process. Dropped once the index exists. */
38
+ declare const TX_REF_TX_TYPE_PROGRESS_TABLE = "tx_ref_tx_type_backfill";
39
+ /** tx rows per back-fill batch (~3.4 tx_ref rows each on main); keeps each write-lock hold short. */
40
+ declare const TX_REF_TX_TYPE_BATCH_SIZE = 5000;
41
+ interface TxRefTxTypeBatch {
42
+ /** inclusive tx rowid lower bound */
43
+ from: number;
44
+ /** exclusive tx rowid upper bound */
45
+ to: number;
46
+ /** tx_ref rows updated */
47
+ updated: number;
48
+ ms: number;
49
+ /** current max(rowid) of tx, for progress reporting */
50
+ maxRowid: number;
51
+ }
52
+ interface TxRefTxTypeBackfillOptions {
53
+ batchSize?: number;
54
+ /** called after each committed batch (progress logging; tests use it to interrupt or write concurrently) */
55
+ onBatch?: (batch: TxRefTxTypeBatch) => void | Promise<void>;
56
+ }
57
+ interface TxRefTxTypeBackfillStats {
58
+ batches: number;
59
+ updated: number;
60
+ maxBatchMs: number;
61
+ /** rows fixed by the final sweep (0 unless the progress was stale, e.g. VACUUM renumbered tx rowids) */
62
+ sweepUpdated: number;
63
+ sweepMs: number;
64
+ totalMs: number;
65
+ }
66
+ /** Whether tx_ref has the tx_type column (added only by migrateTxRefTxType). */
67
+ declare function hasTxRefTxTypeColumn(db: Kysely<unknown>): Promise<boolean>;
68
+ /**
69
+ * Whether listTransactions may use tx_ref.tx_type: the column exists and the index (created only after a
70
+ * complete back-fill) exists.
71
+ */
72
+ declare function isTxRefTxTypeReady(db: Kysely<unknown>): Promise<boolean>;
73
+ /**
74
+ * Fill tx_ref.tx_type from tx.type for rows where it is NULL, in committed tx-rowid batches, resuming from the
75
+ * stored progress. Requires the column.
76
+ */
77
+ declare function backfillTxRefTxType(db: Kysely<unknown>, {
78
+ batchSize,
79
+ onBatch
80
+ }?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeBackfillStats>;
81
+ /** tx_ref rows per sweep batch (rowid range; only the `tx_type IS NULL` rows in it are looked up in tx). */
82
+ declare const TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = 50000;
83
+ interface TxRefTxTypeSweepStats {
84
+ updated: number;
85
+ batches: number;
86
+ ms: number;
87
+ }
88
+ /**
89
+ * Fill tx_ref.tx_type for rows still NULL whose tx has a type, in committed tx_ref-rowid batches (one short write
90
+ * transaction each, not one statement over the whole table). Catches what the back-fill missed (stale progress)
91
+ * and rows written without tx_type after the migration, e.g. by a release that predates the column (downgrade,
92
+ * then upgrade again). Orphans and NULL tx.type stay NULL.
93
+ */
94
+ declare function sweepTxRefTxTypeNulls(db: Kysely<unknown>, {
95
+ batchSize
96
+ }?: {
97
+ batchSize?: number;
98
+ }): Promise<TxRefTxTypeSweepStats>;
99
+ /** Step 1 of migrateTxRefTxType: add the column if missing (metadata only). Returns whether it was added. */
100
+ declare function addTxRefTxTypeColumn(db: Kysely<unknown>): Promise<boolean>;
101
+ interface TxRefTxTypeMigrationResult {
102
+ /** the column was missing and this run added it */
103
+ columnAdded: boolean;
104
+ /** the index already existed: no back-fill, only the NULL sweep (`sweep`) */
105
+ alreadyMigrated: boolean;
106
+ /** null when alreadyMigrated */
107
+ backfill: TxRefTxTypeBackfillStats | null;
108
+ /** NULL sweep of an already migrated database (rows written without tx_type, e.g. during a downgrade); null otherwise */
109
+ sweep: TxRefTxTypeSweepStats | null;
110
+ /** time spent building the index (0 when alreadyMigrated) */
111
+ indexMs: number;
112
+ totalMs: number;
113
+ }
114
+ /**
115
+ * The offline tx_ref.tx_type migration (#1870, #1885): add the column if missing, resumable batched back-fill,
116
+ * final sweep, then the index. On an already migrated database it only sweeps rows still NULL (written by a
117
+ * release without tx_type between two runs). Idempotent and resumable after an interruption. Never called at
118
+ * startup; a node detects the result at its next start.
119
+ *
120
+ * No other SqliteIndexDB instance or process may have the file open while this runs: their cached "tx_ref has
121
+ * tx_type" flag (TransactionTable#txRefHasTxType) is not refreshed, so their later writes would leave tx_type NULL.
122
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
123
+ */
124
+ declare function migrateTxRefTxType(db: Kysely<unknown>, options?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeMigrationResult>;
125
+ /**
126
+ * Undo migrateTxRefTxType (index, progress table, column): back to the 1.31.7 schema, e.g. before running a
127
+ * release that does not write tx_type on this file. Offline only, like the migration.
128
+ */
129
+ declare function dropTxRefTxType(db: Kysely<unknown>): Promise<void>;
130
+ //#endregion
131
+ export { TX_REF_TX_TYPE_BATCH_SIZE, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, TxRefTxTypeBackfillOptions, TxRefTxTypeBackfillStats, TxRefTxTypeBatch, TxRefTxTypeMigrationResult, TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, dropTxRefTxType, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };
@@ -0,0 +1,211 @@
1
+ import { sql } from "kysely";
2
+
3
+ //#region src/tx-ref-tx-type.ts
4
+ /**
5
+ * tx_ref.tx_type + idx_tx_ref_type_value_txtype_time (#1870, step 2 of #1861) - OFFLINE ONLY (#1885)
6
+ *
7
+ * `tx_ref.tx_type` is a denormalized copy of `tx.type`, so a type-filtered count of an account's history
8
+ * (`tx_ref type/value + tx.type in (...)`, the wallet's `page { total }`) is answered from one covering index
9
+ * on tx_ref instead of probing every `tx` row of the account.
10
+ *
11
+ * Not part of the startup migration chain (migration 011 is a recorded no-op): a chain node never adds the
12
+ * column, back-fills or builds the index while starting. The only entry point is `migrateTxRefTxType`, run by
13
+ * `scripts/ops/indexdb-migrate.mjs` with the chain stopped. SqliteIndexDB.initialize() only detects the state:
14
+ * - no column (1.31.7 schema): writes and queries use exactly the 1.31.7 SQL
15
+ * - column but no index (offline run interrupted): writes fill tx_type, queries stay on the 1.31.7 SQL
16
+ * - column + index: writes fill tx_type, listTransactions uses the tx_type path
17
+ *
18
+ * `migrateTxRefTxType` steps (each idempotent, so an interrupted run is simply re-run):
19
+ * 1. `ALTER TABLE tx_ref ADD COLUMN tx_type` (instant, metadata only).
20
+ * 2. Back-fill driven by `tx` rowid batches: `UPDATE tx_ref ... FROM (SELECT hash, type FROM tx WHERE rowid
21
+ * in batch)`, one transaction per batch that also stores the next rowid in `tx_ref_tx_type_backfill`, so a
22
+ * resumed run continues where the killed one stopped. Yields to the event loop between batches.
23
+ * Driving from `tx` reads every tx row once, in order. Driving from tx_ref would read a tx row once per
24
+ * tx_ref row (2.4M vs 0.7M on main), and reading `tx.type` walks the overflow pages of the big `tx`
25
+ * JSON column that precedes it, so that is several passes over a table larger than main's RAM.
26
+ * Only `tx_type IS NULL` rows are written. Rows written meanwhile by TransactionTable (same process, or a
27
+ * node started on a half-migrated file) already carry tx_type.
28
+ * 3. `CREATE INDEX` - only after the back-fill finished. Query-side readiness is "this index exists"
29
+ * (see isTxRefTxTypeReady), so a partially filled column is never queried. Then the progress table is
30
+ * dropped.
31
+ *
32
+ * Rows left NULL after the back-fill have no `tx` row (orphans) or a NULL `tx.type`; neither can match a
33
+ * `type in (...)` filter on either path, so results stay identical.
34
+ */
35
+ const TX_REF_TX_TYPE_INDEX = "idx_tx_ref_type_value_txtype_time";
36
+ /** Progress of an unfinished back-fill: one row, the next tx rowid to process. Dropped once the index exists. */
37
+ const TX_REF_TX_TYPE_PROGRESS_TABLE = "tx_ref_tx_type_backfill";
38
+ /** tx rows per back-fill batch (~3.4 tx_ref rows each on main); keeps each write-lock hold short. */
39
+ const TX_REF_TX_TYPE_BATCH_SIZE = 5e3;
40
+ const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
41
+ const yieldToEventLoop = () => new Promise((resolve) => {
42
+ if (typeof setImmediate === "function") setImmediate(resolve);
43
+ else setTimeout(resolve, 0);
44
+ });
45
+ /** Whether tx_ref has the tx_type column (added only by migrateTxRefTxType). */
46
+ async function hasTxRefTxTypeColumn(db) {
47
+ return ((await sql`PRAGMA table_info('tx_ref')`.execute(db)).rows || []).some((r) => r.name === "tx_type");
48
+ }
49
+ /**
50
+ * Whether listTransactions may use tx_ref.tx_type: the column exists and the index (created only after a
51
+ * complete back-fill) exists.
52
+ */
53
+ async function isTxRefTxTypeReady(db) {
54
+ if (!await hasTxRefTxTypeColumn(db)) return false;
55
+ return (await sql`
56
+ SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'tx_ref' AND name = ${TX_REF_TX_TYPE_INDEX}
57
+ `.execute(db)).rows.length > 0;
58
+ }
59
+ /**
60
+ * Fill tx_ref.tx_type from tx.type for rows where it is NULL, in committed tx-rowid batches, resuming from the
61
+ * stored progress. Requires the column.
62
+ */
63
+ async function backfillTxRefTxType(db, { batchSize = TX_REF_TX_TYPE_BATCH_SIZE, onBatch } = {}) {
64
+ const started = now();
65
+ const stats = {
66
+ batches: 0,
67
+ updated: 0,
68
+ maxBatchMs: 0,
69
+ sweepUpdated: 0,
70
+ sweepMs: 0,
71
+ totalMs: 0
72
+ };
73
+ await sql`
74
+ CREATE TABLE IF NOT EXISTS tx_ref_tx_type_backfill (id INTEGER PRIMARY KEY CHECK (id = 1), next_rowid INTEGER NOT NULL)
75
+ `.execute(db);
76
+ const progress = await sql`SELECT next_rowid AS next FROM tx_ref_tx_type_backfill WHERE id = 1`.execute(db);
77
+ const bounds = await sql`
78
+ SELECT min(rowid) AS lo, max(rowid) AS hi FROM tx
79
+ `.execute(db);
80
+ const readMaxRowid = async () => {
81
+ const r = await sql`SELECT max(rowid) AS id FROM tx`.execute(db);
82
+ return Number(r.rows[0]?.id ?? 0);
83
+ };
84
+ let from = progress.rows.length ? Number(progress.rows[0].next) : Number(bounds.rows[0]?.lo ?? 1);
85
+ let max = Number(bounds.rows[0]?.hi ?? 0);
86
+ while (from <= max) {
87
+ const to = from + batchSize;
88
+ const t0 = now();
89
+ const updated = await db.transaction().execute(async (trx) => {
90
+ const res = await sql`
91
+ UPDATE tx_ref SET tx_type = t.type
92
+ FROM (SELECT hash, type FROM tx WHERE rowid >= ${from} AND rowid < ${to}) AS t
93
+ WHERE tx_ref.hash = t.hash AND tx_ref.tx_type IS NULL
94
+ `.execute(trx);
95
+ await sql`
96
+ INSERT INTO tx_ref_tx_type_backfill (id, next_rowid) VALUES (1, ${to})
97
+ ON CONFLICT (id) DO UPDATE SET next_rowid = excluded.next_rowid
98
+ `.execute(trx);
99
+ return Number(res.numAffectedRows ?? 0);
100
+ });
101
+ const ms = now() - t0;
102
+ stats.batches++;
103
+ stats.updated += updated;
104
+ stats.maxBatchMs = Math.max(stats.maxBatchMs, ms);
105
+ await onBatch?.({
106
+ from,
107
+ to,
108
+ updated,
109
+ ms,
110
+ maxRowid: max
111
+ });
112
+ await yieldToEventLoop();
113
+ from = to;
114
+ if (from > max) max = await readMaxRowid();
115
+ }
116
+ const sweep = await sweepTxRefTxTypeNulls(db);
117
+ stats.sweepUpdated = sweep.updated;
118
+ stats.updated += stats.sweepUpdated;
119
+ stats.sweepMs = sweep.ms;
120
+ stats.totalMs = now() - started;
121
+ return stats;
122
+ }
123
+ /** tx_ref rows per sweep batch (rowid range; only the `tx_type IS NULL` rows in it are looked up in tx). */
124
+ const TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = 5e4;
125
+ /**
126
+ * Fill tx_ref.tx_type for rows still NULL whose tx has a type, in committed tx_ref-rowid batches (one short write
127
+ * transaction each, not one statement over the whole table). Catches what the back-fill missed (stale progress)
128
+ * and rows written without tx_type after the migration, e.g. by a release that predates the column (downgrade,
129
+ * then upgrade again). Orphans and NULL tx.type stay NULL.
130
+ */
131
+ async function sweepTxRefTxTypeNulls(db, { batchSize = TX_REF_TX_TYPE_SWEEP_BATCH_SIZE } = {}) {
132
+ const t0 = now();
133
+ const stats = {
134
+ updated: 0,
135
+ batches: 0,
136
+ ms: 0
137
+ };
138
+ const bounds = await sql`
139
+ SELECT min(rowid) AS lo, max(rowid) AS hi FROM tx_ref
140
+ `.execute(db);
141
+ const lo = bounds.rows[0]?.lo;
142
+ const hi = bounds.rows[0]?.hi;
143
+ if (lo !== null && lo !== void 0 && hi !== null && hi !== void 0) for (let from = Number(lo); from <= Number(hi); from += batchSize) {
144
+ const to = from + batchSize;
145
+ const res = await sql`
146
+ UPDATE tx_ref SET tx_type = (SELECT tx.type FROM tx WHERE tx.hash = tx_ref.hash)
147
+ WHERE rowid >= ${from} AND rowid < ${to} AND tx_type IS NULL
148
+ AND (SELECT tx.type FROM tx WHERE tx.hash = tx_ref.hash) IS NOT NULL
149
+ `.execute(db);
150
+ stats.updated += Number(res.numAffectedRows ?? 0);
151
+ stats.batches++;
152
+ await yieldToEventLoop();
153
+ }
154
+ stats.ms = now() - t0;
155
+ return stats;
156
+ }
157
+ /** Step 1 of migrateTxRefTxType: add the column if missing (metadata only). Returns whether it was added. */
158
+ async function addTxRefTxTypeColumn(db) {
159
+ if (await hasTxRefTxTypeColumn(db)) return false;
160
+ await sql`ALTER TABLE tx_ref ADD COLUMN tx_type TEXT`.execute(db);
161
+ return true;
162
+ }
163
+ /**
164
+ * The offline tx_ref.tx_type migration (#1870, #1885): add the column if missing, resumable batched back-fill,
165
+ * final sweep, then the index. On an already migrated database it only sweeps rows still NULL (written by a
166
+ * release without tx_type between two runs). Idempotent and resumable after an interruption. Never called at
167
+ * startup; a node detects the result at its next start.
168
+ *
169
+ * No other SqliteIndexDB instance or process may have the file open while this runs: their cached "tx_ref has
170
+ * tx_type" flag (TransactionTable#txRefHasTxType) is not refreshed, so their later writes would leave tx_type NULL.
171
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
172
+ */
173
+ async function migrateTxRefTxType(db, options = {}) {
174
+ const started = now();
175
+ const columnAdded = await addTxRefTxTypeColumn(db);
176
+ if (await isTxRefTxTypeReady(db)) {
177
+ await sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
178
+ return {
179
+ columnAdded,
180
+ alreadyMigrated: true,
181
+ backfill: null,
182
+ sweep: await sweepTxRefTxTypeNulls(db),
183
+ indexMs: 0,
184
+ totalMs: now() - started
185
+ };
186
+ }
187
+ const backfill = await backfillTxRefTxType(db, options);
188
+ const t0 = now();
189
+ await sql`CREATE INDEX IF NOT EXISTS idx_tx_ref_type_value_txtype_time ON tx_ref(type, value, tx_type, time)`.execute(db);
190
+ await sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
191
+ return {
192
+ columnAdded,
193
+ alreadyMigrated: false,
194
+ backfill,
195
+ sweep: null,
196
+ indexMs: now() - t0,
197
+ totalMs: now() - started
198
+ };
199
+ }
200
+ /**
201
+ * Undo migrateTxRefTxType (index, progress table, column): back to the 1.31.7 schema, e.g. before running a
202
+ * release that does not write tx_type on this file. Offline only, like the migration.
203
+ */
204
+ async function dropTxRefTxType(db) {
205
+ await sql`DROP INDEX IF EXISTS idx_tx_ref_type_value_txtype_time`.execute(db);
206
+ await sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
207
+ if (await hasTxRefTxTypeColumn(db)) await sql`ALTER TABLE tx_ref DROP COLUMN tx_type`.execute(db);
208
+ }
209
+
210
+ //#endregion
211
+ export { TX_REF_TX_TYPE_BATCH_SIZE, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, addTxRefTxTypeColumn, backfillTxRefTxType, dropTxRefTxType, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };
package/lib/db/base.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ const require_db_tx_ref_query = require('./tx-ref-query.cjs');
3
4
  let kysely = require("kysely");
4
5
  let _ocap_indexdb = require("@ocap/indexdb");
5
6
  let _arcblock_did_lib_type = require("@arcblock/did/lib/type");
@@ -38,6 +39,7 @@ function buildPagingResult(total, pagination, itemCount) {
38
39
  var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
39
40
  constructor(..._args) {
40
41
  super(..._args);
42
+ this.txRefTxTypeReady = false;
41
43
  this.txCountCache = null;
42
44
  }
43
45
  /**
@@ -185,12 +187,33 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
185
187
  const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
186
188
  const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
187
189
  const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
190
+ const txRefDriven = !isMutual && activeJsonFilters.length >= 1 && (hasNonJsonFilters || activeJsonFilters.length > 1);
191
+ const txRefDrivenInput = (limit, offset) => ({
192
+ refFilters: activeJsonFilters,
193
+ sender,
194
+ receiver,
195
+ gasPayer,
196
+ direction,
197
+ types,
198
+ txs,
199
+ validity,
200
+ txType: this.txRefTxTypeReady,
201
+ start: parsedStart || void 0,
202
+ end: parsedEnd || void 0,
203
+ order: pagination.order.type === "desc" ? "desc" : "asc",
204
+ limit,
205
+ offset
206
+ });
188
207
  if (isMutual) {
189
208
  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()]);
190
209
  total = (c1?.count ?? 0) + (c2?.count ?? 0);
191
210
  } else if (!hasNonJsonFilters && activeJsonFilters.length === 1) {
192
211
  const [refType, values] = activeJsonFilters[0];
193
212
  total = (await this.db.selectFrom("tx_ref").select(this.db.fn.countAll().as("count")).where("type", "=", refType).where("value", "in", values).executeTakeFirst())?.count ?? 0;
213
+ } else if (txRefDriven) {
214
+ const { count } = require_db_tx_ref_query.buildTxRefDrivenQuery(txRefDrivenInput(0, 0));
215
+ const countRows = await count.execute(this.db);
216
+ total = Number(countRows.rows[0]?.count ?? 0);
194
217
  } else if (isUnionOnly) {
195
218
  const [senderCount, receiverCount, overlapCount] = await Promise.all([
196
219
  this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).executeTakeFirst(),
@@ -240,6 +263,9 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
240
263
  const hashOrder = new Map(hashes.map((h, i) => [h, i]));
241
264
  rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
242
265
  } else rawResults = [];
266
+ } else if (txRefDriven && pagination.order.field === "time") {
267
+ const { page } = require_db_tx_ref_query.buildTxRefDrivenQuery(txRefDrivenInput(pagination.size, pagination.cursor));
268
+ rawResults = (await page.execute(this.db)).rows;
243
269
  } else {
244
270
  qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
245
271
  rawResults = await qb.execute();
package/lib/db/base.d.cts CHANGED
@@ -23,6 +23,11 @@ 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
+ /**
27
+ * tx_ref.tx_type is back-filled and indexed (offline migrateTxRefTxType, #1870/#1885). Detected once by initialize();
28
+ * false keeps listTransactions on the 1.31.7 SQL.
29
+ */
30
+ protected txRefTxTypeReady: boolean;
26
31
  protected txCountCache: {
27
32
  total: number;
28
33
  invalid: number;
package/lib/db/index.cjs CHANGED
@@ -3,6 +3,7 @@ const require_kysely = require('../kysely.cjs');
3
3
  const require_migrations_index = require('../migrations/index.cjs');
4
4
  const require_table_base = require('../table/base.cjs');
5
5
  const require_table_account = require('../table/account.cjs');
6
+ const require_tx_ref_tx_type = require('../tx-ref-tx-type.cjs');
6
7
  const require_table_transaction = require('../table/transaction.cjs');
7
8
  const require_db_base = require('./base.cjs');
8
9
  const require_package = require('../package.cjs');
@@ -533,9 +534,39 @@ var SqliteIndexDB = class extends require_db_base.default {
533
534
  async initialize() {
534
535
  if (this.initialized) return;
535
536
  await require_migrations_index.runMigrations(this.db);
537
+ await this.detectTxRefTxType();
536
538
  this.initialized = true;
537
539
  }
538
540
  /**
541
+ * Detect the tx_ref.tx_type state once (#1885). Read-only: startup never adds the column, back-fills or builds
542
+ * the index; that is migrateTxRefTxType, run offline.
543
+ */
544
+ async detectTxRefTxType() {
545
+ const k = this.db;
546
+ this.tx.setTxRefTxTypeColumn(await require_tx_ref_tx_type.hasTxRefTxTypeColumn(k));
547
+ this.txRefTxTypeReady = await require_tx_ref_tx_type.isTxRefTxTypeReady(k);
548
+ }
549
+ /**
550
+ * Run the offline tx_ref.tx_type migration on this database (#1870, #1885), then switch this instance's write
551
+ * and query paths to the result. Only for scripts/ops/indexdb-migrate.mjs and tests, with the chain stopped;
552
+ * never part of initialize().
553
+ *
554
+ * This instance must be the only SqliteIndexDB (in any process) with the file open: other instances keep their
555
+ * cached "tx_ref has tx_type" flag (TransactionTable#txRefHasTxType) and their later writes leave tx_type NULL.
556
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
557
+ */
558
+ async migrateTxRefTxType(options) {
559
+ const k = this.db;
560
+ const columnAdded = await require_tx_ref_tx_type.addTxRefTxTypeColumn(k);
561
+ this.tx.setTxRefTxTypeColumn(true);
562
+ const result = await require_tx_ref_tx_type.migrateTxRefTxType(k, options);
563
+ await this.detectTxRefTxType();
564
+ return {
565
+ ...result,
566
+ columnAdded
567
+ };
568
+ }
569
+ /**
539
570
  * Execute multiple operations within a database transaction
540
571
  *
541
572
  * @param fn - Function receiving Kysely transaction object
@@ -1,6 +1,7 @@
1
1
  import { Database } from "../interfaces.cjs";
2
2
  import SqliteBaseIndexDB from "./base.cjs";
3
3
  import { SqliteConfig } from "../kysely.cjs";
4
+ import { TxRefTxTypeBackfillOptions, TxRefTxTypeMigrationResult } from "../tx-ref-tx-type.cjs";
4
5
  import { IIndexDB, IIndexTable, IndexTableTypeMap } from "@ocap/types";
5
6
  import { Kysely, Transaction } from "kysely";
6
7
 
@@ -57,6 +58,21 @@ declare class SqliteIndexDB extends SqliteBaseIndexDB implements IIndexDB {
57
58
  * Call this after constructor to ensure database schema is ready
58
59
  */
59
60
  initialize(): Promise<void>;
61
+ /**
62
+ * Detect the tx_ref.tx_type state once (#1885). Read-only: startup never adds the column, back-fills or builds
63
+ * the index; that is migrateTxRefTxType, run offline.
64
+ */
65
+ private detectTxRefTxType;
66
+ /**
67
+ * Run the offline tx_ref.tx_type migration on this database (#1870, #1885), then switch this instance's write
68
+ * and query paths to the result. Only for scripts/ops/indexdb-migrate.mjs and tests, with the chain stopped;
69
+ * never part of initialize().
70
+ *
71
+ * This instance must be the only SqliteIndexDB (in any process) with the file open: other instances keep their
72
+ * cached "tx_ref has tx_type" flag (TransactionTable#txRefHasTxType) and their later writes leave tx_type NULL.
73
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
74
+ */
75
+ migrateTxRefTxType(options?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeMigrationResult>;
60
76
  /**
61
77
  * Execute multiple operations within a database transaction
62
78
  *
@@ -0,0 +1,130 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ let kysely = require("kysely");
3
+
4
+ //#region src/db/tx-ref-query.ts
5
+ /**
6
+ * tx_ref-driven SQL for `listTransactions` (issue #1861).
7
+ *
8
+ * The generic path (`select * from tx where <conds> and hash in (select hash from tx_ref ...) order by time`)
9
+ * makes SQLite walk every tx_ref row of the account, look up every full `tx` row, filter, sort in a temp
10
+ * b-tree and only then apply offset/limit: cost is O(total history of the account), twice (count + page).
11
+ *
12
+ * Here tx_ref is the OUTER loop (`cross join` pins the join order), ordered by `idx_tx_ref_time_lookup
13
+ * (type, value, time DESC)`. `tx` is probed by primary key (`hash = ?`) only for rows that are actually
14
+ * needed, and time filters are pushed down to `tx_ref.time` so they become index range bounds.
15
+ *
16
+ * Correctness notes:
17
+ * - `tx_ref.time` is copied from `tx.time` on insert and rewritten on every update (TransactionTable.syncTxRefs),
18
+ * so ordering/filtering on `r.time` equals ordering/filtering on `tx.time`.
19
+ * Only difference: an empty-string `tx.time` is stored as NULL in tx_ref (never produced by the chain).
20
+ * - Single-value driver: `(hash, type, value)` is unique, so no duplicates are possible; ties on `time` come out
21
+ * in tx_ref index order (same as the pre-existing single-filter fast path).
22
+ * - Multi-value driver (`value in (a, b)`): a tx can match twice. The driver is a `select distinct hash, time`
23
+ * subquery over tx_ref only (index-only, no `tx` lookups), ordered by `(time, hash)`; `tx` rows are looked up
24
+ * lazily, only until offset+limit rows pass the remaining filters.
25
+ * - Additional JSON filters are `exists (select 1 from tx_ref x where x.hash = r.hash ...)` probes on idx_tx_ref_pk.
26
+ *
27
+ * tx_type (#1870, `txType: true` once the offline migrateTxRefTxType (#1885) has back-filled tx_ref.tx_type and built
28
+ * idx_tx_ref_type_value_txtype_time):
29
+ * - The type filter moves from `tx.type in (...)` to `r.tx_type in (...)` (into the deduping subquery for a
30
+ * multi-value driver), so rows of other types are dropped before `tx` is probed.
31
+ * - In the page query it is written `+r.tx_type`: the unary plus keeps the planner on the time index
32
+ * (no sort; the page stops after offset+limit rows) instead of seeking the new index per type and sorting.
33
+ * - If the type filter (plus time / other tx_ref filters) is all there is, the count does not join `tx` at all:
34
+ * `SEARCH r USING COVERING INDEX idx_tx_ref_type_value_txtype_time (type=? AND value=? AND tx_type=?)`.
35
+ * Same result as the join: a non-NULL tx_type is only ever written from an existing tx row (and tx rows are
36
+ * never deleted without their tx_ref rows), and a NULL one cannot match `in (...)`. Counts without a type
37
+ * filter keep the join, so orphan tx_ref rows (if any) are still excluded there.
38
+ */
39
+ const and = (parts) => kysely.sql.join(parts, kysely.sql` and `);
40
+ /** Conditions that need the `tx` row (the type filter is not one of them when tx_type is ready). */
41
+ function txConditions(input) {
42
+ const { sender, receiver, gasPayer, direction, types = [], txs = [], validity, txType } = input;
43
+ const conds = [];
44
+ if (sender && receiver) if (direction === "MUTUAL") conds.push(kysely.sql`((tx.sender = ${sender} and tx.receiver = ${receiver}) or (tx.sender = ${receiver} and tx.receiver = ${sender}))`);
45
+ else if (direction === "ONE_WAY") conds.push(kysely.sql`tx.sender = ${sender}`, kysely.sql`tx.receiver = ${receiver}`);
46
+ else conds.push(kysely.sql`(tx.sender = ${sender} or tx.receiver = ${receiver})`);
47
+ else if (sender) conds.push(kysely.sql`tx.sender = ${sender}`);
48
+ else if (receiver) conds.push(kysely.sql`tx.receiver = ${receiver}`);
49
+ if (gasPayer) conds.push(kysely.sql`tx.gasPayer = ${gasPayer}`);
50
+ if (types.length && !txType) conds.push(kysely.sql`tx.type in (${kysely.sql.join(types)})`);
51
+ if (txs.length) conds.push(kysely.sql`tx.hash in (${kysely.sql.join(txs)})`);
52
+ if (validity === "VALID") conds.push(kysely.sql`tx.valid = 1`);
53
+ else if (validity === "INVALID") conds.push(kysely.sql`tx.valid = 0`);
54
+ return conds;
55
+ }
56
+ function timeConditions(alias, start, end) {
57
+ const col = kysely.sql.ref(`${alias}.time`);
58
+ const conds = [];
59
+ if (start) conds.push(kysely.sql`${col} > ${start}`);
60
+ if (end) conds.push(kysely.sql`${col} <= ${end}`);
61
+ return conds;
62
+ }
63
+ /** Pick the filter that drives the scan: a single-valued one avoids the dedupe step. */
64
+ function pickDriver(refFilters) {
65
+ const single = refFilters.findIndex(([, values]) => values.length === 1);
66
+ return single >= 0 ? single : 0;
67
+ }
68
+ function buildTxRefDrivenQuery(input) {
69
+ const { refFilters, start, end, order, limit, offset, types = [], txType } = input;
70
+ if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
71
+ const driverIndex = pickDriver(refFilters);
72
+ const [driverType, driverValues] = refFilters[driverIndex];
73
+ const dir = kysely.sql.raw(order === "desc" ? "desc" : "asc");
74
+ const typeOnRef = !!txType && types.length > 0;
75
+ const txConds = txConditions(input);
76
+ const countWithoutTx = typeOnRef && txConds.length === 0;
77
+ let from;
78
+ let countFrom;
79
+ const driverWhere = [];
80
+ const pageTypeWhere = [];
81
+ const countTypeWhere = [];
82
+ if (driverValues.length === 1) {
83
+ from = kysely.sql`tx_ref r cross join tx`;
84
+ countFrom = countWithoutTx ? kysely.sql`tx_ref r` : from;
85
+ driverWhere.push(kysely.sql`r.type = ${driverType}`, kysely.sql`r.value = ${driverValues[0]}`, ...timeConditions("r", start, end));
86
+ if (typeOnRef) {
87
+ pageTypeWhere.push(kysely.sql`+r.tx_type in (${kysely.sql.join(types)})`);
88
+ countTypeWhere.push(kysely.sql`r.tx_type in (${kysely.sql.join(types)})`);
89
+ }
90
+ } else {
91
+ const innerOf = (typeCond) => and([
92
+ kysely.sql`type = ${driverType}`,
93
+ kysely.sql`value in (${kysely.sql.join(driverValues)})`,
94
+ ...typeCond,
95
+ ...timeConditions("tx_ref", start, end)
96
+ ]);
97
+ const pageInner = innerOf(typeOnRef ? [kysely.sql`+tx_type in (${kysely.sql.join(types)})`] : []);
98
+ const countInner = innerOf(typeOnRef ? [kysely.sql`tx_type in (${kysely.sql.join(types)})`] : []);
99
+ from = kysely.sql`(${kysely.sql`select distinct hash, time from tx_ref where ${pageInner} order by time ${dir}, hash limit -1`}) r cross join tx`;
100
+ const countSub = kysely.sql`(select distinct hash, time from tx_ref where ${countInner}) r`;
101
+ countFrom = countWithoutTx ? countSub : kysely.sql`${countSub} cross join tx`;
102
+ }
103
+ const joinWhere = [kysely.sql`tx.hash = r.hash`, ...txConds];
104
+ const existsWhere = [];
105
+ refFilters.forEach(([refType, values], i) => {
106
+ if (i === driverIndex) return;
107
+ existsWhere.push(kysely.sql`exists (select 1 from tx_ref x where x.hash = r.hash and x.type = ${refType} and x.value in (${kysely.sql.join(values)}))`);
108
+ });
109
+ const orderBy = driverValues.length === 1 ? kysely.sql`order by r.time ${dir}` : kysely.sql``;
110
+ const pageWhere = and([
111
+ ...driverWhere,
112
+ ...pageTypeWhere,
113
+ ...joinWhere,
114
+ ...existsWhere
115
+ ]);
116
+ const countParts = [
117
+ ...driverWhere,
118
+ ...countTypeWhere,
119
+ ...countWithoutTx ? [] : joinWhere,
120
+ ...existsWhere
121
+ ];
122
+ const countWhere = countParts.length ? kysely.sql`where ${and(countParts)}` : kysely.sql``;
123
+ return {
124
+ page: kysely.sql`select tx.* from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
125
+ count: kysely.sql`select count(*) as count from ${countFrom} ${countWhere}`
126
+ };
127
+ }
128
+
129
+ //#endregion
130
+ exports.buildTxRefDrivenQuery = buildTxRefDrivenQuery;
@@ -0,0 +1,35 @@
1
+ import { RawBuilder } from "kysely";
2
+
3
+ //#region src/db/tx-ref-query.d.ts
4
+
5
+ interface TxRefDrivenInput {
6
+ /** [tx_ref.type, values] pairs; at least one. */
7
+ refFilters: [string, string[]][];
8
+ sender?: string;
9
+ receiver?: string;
10
+ gasPayer?: string;
11
+ direction?: string;
12
+ types?: string[];
13
+ txs?: string[];
14
+ validity?: string;
15
+ /** tx_ref.tx_type is back-filled and indexed (offline migrateTxRefTxType); false/absent = the 1.31.7 SQL */
16
+ txType?: boolean;
17
+ /** exclusive lower bound on time (ISO string) */
18
+ start?: string;
19
+ /** inclusive upper bound on time (ISO string) */
20
+ end?: string;
21
+ order: 'asc' | 'desc';
22
+ limit: number;
23
+ offset: number;
24
+ }
25
+ interface TxRefDrivenQuery {
26
+ /** `select tx.* ...` ordered, offset/limit applied */
27
+ page: RawBuilder<Record<string, unknown>>;
28
+ /** `select count(*) as count ...` */
29
+ count: RawBuilder<{
30
+ count: number;
31
+ }>;
32
+ }
33
+ declare function buildTxRefDrivenQuery(input: TxRefDrivenInput): TxRefDrivenQuery;
34
+ //#endregion
35
+ export { TxRefDrivenInput, TxRefDrivenQuery, buildTxRefDrivenQuery };