@ocap/indexdb-sqlite 1.31.7 → 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,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
@@ -39,6 +39,7 @@ function buildPagingResult(total, pagination, itemCount) {
39
39
  var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
40
40
  constructor(..._args) {
41
41
  super(..._args);
42
+ this.txRefTxTypeReady = false;
42
43
  this.txCountCache = null;
43
44
  }
44
45
  /**
@@ -196,6 +197,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
196
197
  types,
197
198
  txs,
198
199
  validity,
200
+ txType: this.txRefTxTypeReady,
199
201
  start: parsedStart || void 0,
200
202
  end: parsedEnd || void 0,
201
203
  order: pagination.order.type === "desc" ? "desc" : "asc",
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
  *
@@ -23,10 +23,23 @@ let kysely = require("kysely");
23
23
  * subquery over tx_ref only (index-only, no `tx` lookups), ordered by `(time, hash)`; `tx` rows are looked up
24
24
  * lazily, only until offset+limit rows pass the remaining filters.
25
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.
26
38
  */
27
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). */
28
41
  function txConditions(input) {
29
- const { sender, receiver, gasPayer, direction, types = [], txs = [], validity } = input;
42
+ const { sender, receiver, gasPayer, direction, types = [], txs = [], validity, txType } = input;
30
43
  const conds = [];
31
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}))`);
32
45
  else if (direction === "ONE_WAY") conds.push(kysely.sql`tx.sender = ${sender}`, kysely.sql`tx.receiver = ${receiver}`);
@@ -34,7 +47,7 @@ function txConditions(input) {
34
47
  else if (sender) conds.push(kysely.sql`tx.sender = ${sender}`);
35
48
  else if (receiver) conds.push(kysely.sql`tx.receiver = ${receiver}`);
36
49
  if (gasPayer) conds.push(kysely.sql`tx.gasPayer = ${gasPayer}`);
37
- if (types.length) conds.push(kysely.sql`tx.type in (${kysely.sql.join(types)})`);
50
+ if (types.length && !txType) conds.push(kysely.sql`tx.type in (${kysely.sql.join(types)})`);
38
51
  if (txs.length) conds.push(kysely.sql`tx.hash in (${kysely.sql.join(txs)})`);
39
52
  if (validity === "VALID") conds.push(kysely.sql`tx.valid = 1`);
40
53
  else if (validity === "INVALID") conds.push(kysely.sql`tx.valid = 0`);
@@ -53,38 +66,63 @@ function pickDriver(refFilters) {
53
66
  return single >= 0 ? single : 0;
54
67
  }
55
68
  function buildTxRefDrivenQuery(input) {
56
- const { refFilters, start, end, order, limit, offset } = input;
69
+ const { refFilters, start, end, order, limit, offset, types = [], txType } = input;
57
70
  if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
58
71
  const driverIndex = pickDriver(refFilters);
59
72
  const [driverType, driverValues] = refFilters[driverIndex];
60
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;
61
77
  let from;
62
78
  let countFrom;
63
- const where = [];
79
+ const driverWhere = [];
80
+ const pageTypeWhere = [];
81
+ const countTypeWhere = [];
64
82
  if (driverValues.length === 1) {
65
83
  from = kysely.sql`tx_ref r cross join tx`;
66
- countFrom = from;
67
- where.push(kysely.sql`r.type = ${driverType}`, kysely.sql`r.value = ${driverValues[0]}`, ...timeConditions("r", start, end));
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
+ }
68
90
  } else {
69
- const inner = and([
91
+ const innerOf = (typeCond) => and([
70
92
  kysely.sql`type = ${driverType}`,
71
93
  kysely.sql`value in (${kysely.sql.join(driverValues)})`,
94
+ ...typeCond,
72
95
  ...timeConditions("tx_ref", start, end)
73
96
  ]);
74
- from = kysely.sql`(${kysely.sql`select distinct hash, time from tx_ref where ${inner} order by time ${dir}, hash limit -1`}) r cross join tx`;
75
- countFrom = kysely.sql`(select distinct hash, time from tx_ref where ${inner}) r cross join tx`;
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`;
76
102
  }
77
- where.push(kysely.sql`tx.hash = r.hash`);
78
- where.push(...txConditions(input));
103
+ const joinWhere = [kysely.sql`tx.hash = r.hash`, ...txConds];
104
+ const existsWhere = [];
79
105
  refFilters.forEach(([refType, values], i) => {
80
106
  if (i === driverIndex) return;
81
- where.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)}))`);
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)}))`);
82
108
  });
83
- const whereSql = and(where);
84
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``;
85
123
  return {
86
- page: kysely.sql`select tx.* from ${from} where ${whereSql} ${orderBy} limit ${limit} offset ${offset}`,
87
- count: kysely.sql`select count(*) as count from ${countFrom} where ${whereSql}`
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}`
88
126
  };
89
127
  }
90
128
 
@@ -12,6 +12,8 @@ interface TxRefDrivenInput {
12
12
  types?: string[];
13
13
  txs?: string[];
14
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;
15
17
  /** exclusive lower bound on time (ISO string) */
16
18
  start?: string;
17
19
  /** inclusive upper bound on time (ISO string) */
package/lib/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_kysely = require('./kysely.cjs');
3
+ const require_tx_ref_tx_type = require('./tx-ref-tx-type.cjs');
3
4
  const require_db_base = require('./db/base.cjs');
4
5
  const require_db_index = require('./db/index.cjs');
5
6
 
@@ -9,5 +10,15 @@ var src_default = require_db_index.default;
9
10
  //#endregion
10
11
  exports.DurableObjectSqliteDialect = require_kysely.DurableObjectSqliteDialect;
11
12
  exports.SqliteBaseIndexDB = require_db_base.default;
13
+ exports.TX_REF_TX_TYPE_INDEX = require_tx_ref_tx_type.TX_REF_TX_TYPE_INDEX;
14
+ exports.TX_REF_TX_TYPE_PROGRESS_TABLE = require_tx_ref_tx_type.TX_REF_TX_TYPE_PROGRESS_TABLE;
15
+ exports.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = require_tx_ref_tx_type.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE;
16
+ exports.addTxRefTxTypeColumn = require_tx_ref_tx_type.addTxRefTxTypeColumn;
17
+ exports.backfillTxRefTxType = require_tx_ref_tx_type.backfillTxRefTxType;
12
18
  exports.default = src_default;
13
- exports.getRawDatabase = require_kysely.getRawDatabase;
19
+ exports.dropTxRefTxType = require_tx_ref_tx_type.dropTxRefTxType;
20
+ exports.getRawDatabase = require_kysely.getRawDatabase;
21
+ exports.hasTxRefTxTypeColumn = require_tx_ref_tx_type.hasTxRefTxTypeColumn;
22
+ exports.isTxRefTxTypeReady = require_tx_ref_tx_type.isTxRefTxTypeReady;
23
+ exports.migrateTxRefTxType = require_tx_ref_tx_type.migrateTxRefTxType;
24
+ exports.sweepTxRefTxTypeNulls = require_tx_ref_tx_type.sweepTxRefTxTypeNulls;
package/lib/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import SqliteBaseIndexDB from "./db/base.cjs";
2
2
  import { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, getRawDatabase } from "./kysely.cjs";
3
+ import { 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 } from "./tx-ref-tx-type.cjs";
3
4
  import SqliteIndexDB from "./db/index.cjs";
4
- export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, SqliteIndexDB as default, getRawDatabase };
5
+ export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, type TxRefTxTypeBackfillOptions, type TxRefTxTypeBackfillStats, type TxRefTxTypeBatch, type TxRefTxTypeMigrationResult, type TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, SqliteIndexDB as default, dropTxRefTxType, getRawDatabase, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };
@@ -333,6 +333,8 @@ interface TxRefTable {
333
333
  type: string;
334
334
  value: string;
335
335
  time: string | null;
336
+ /** copy of tx.type (#1870); NULL only for rows not yet back-filled, orphans, or a NULL tx.type */
337
+ tx_type: string | null;
336
338
  }
337
339
  /**
338
340
  * IndexFailure table: durable log of failed indexdb writes from connectIndexDB() (see #67).
package/lib/kysely.cjs CHANGED
@@ -1515,6 +1515,25 @@ function resolveWalCheckpointIntervalMs(config) {
1515
1515
  const v = config.walCheckpointIntervalMs ?? fromEnv;
1516
1516
  return Number.isFinite(v) && v > 0 ? Math.floor(v) : void 0;
1517
1517
  }
1518
+ /** Default `PRAGMA mmap_size` (8 GiB). */
1519
+ const DEFAULT_MMAP_SIZE = 8 * 1024 * 1024 * 1024;
1520
+ /** Env var overriding the default `PRAGMA mmap_size` (bytes, `0` disables). */
1521
+ const MMAP_SIZE_ENV = "SQLITE_INDEXDB_MMAP_SIZE";
1522
+ function parseMmapSize(value, source) {
1523
+ if (value === void 0) return void 0;
1524
+ let n;
1525
+ if (typeof value === "number") n = value;
1526
+ else if (typeof value === "string" && /^\d+$/.test(value.trim())) n = Number(value.trim());
1527
+ if (n !== void 0 && Number.isSafeInteger(n) && n >= 0) return n;
1528
+ console.warn(`[sqlite] ignoring invalid mmap_size from ${source}: ${JSON.stringify(String(value))}`);
1529
+ }
1530
+ /**
1531
+ * Resolve `PRAGMA mmap_size`: valid `config.mmapSize` wins, then a valid `SQLITE_INDEXDB_MMAP_SIZE`, then
1532
+ * `DEFAULT_MMAP_SIZE`. Invalid input never becomes `0` (an empty env var is not "disable").
1533
+ */
1534
+ function resolveMmapSize(config, env = process.env) {
1535
+ return parseMmapSize(config.mmapSize, "config.mmapSize") ?? parseMmapSize(env[MMAP_SIZE_ENV], MMAP_SIZE_ENV) ?? DEFAULT_MMAP_SIZE;
1536
+ }
1518
1537
  /**
1519
1538
  * Create a Kysely instance with SQLite dialect
1520
1539
  * Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
@@ -1544,21 +1563,29 @@ function createKysely(config) {
1544
1563
  const bunReq = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : typeof require === "function" ? require : {}.require;
1545
1564
  const { BunSqliteDialect } = bunReq("kysely-bun-sqlite");
1546
1565
  const { Database: BunDatabase } = bunReq("bun:sqlite");
1547
- const sqlite$1 = new BunDatabase(filename, {
1566
+ const sqlite = new BunDatabase(filename, {
1548
1567
  create: config.create !== false,
1549
1568
  readonly: config.readonly === true
1550
1569
  });
1551
1570
  if (config.walMode !== false && !config.readonly && filename !== ":memory:") {
1552
- sqlite$1.exec("PRAGMA journal_mode = WAL");
1553
- sqlite$1.exec("PRAGMA synchronous = NORMAL");
1571
+ sqlite.exec("PRAGMA journal_mode = WAL");
1572
+ sqlite.exec("PRAGMA synchronous = NORMAL");
1554
1573
  const walCp = resolveWalAutoCheckpoint(config);
1555
- if (walCp !== void 0) sqlite$1.exec(`PRAGMA wal_autocheckpoint = ${walCp}`);
1574
+ if (walCp !== void 0) sqlite.exec(`PRAGMA wal_autocheckpoint = ${walCp}`);
1556
1575
  }
1557
- sqlite$1.exec("PRAGMA foreign_keys = ON");
1558
- sqlite$1.exec("PRAGMA busy_timeout = 5000");
1559
- return new kysely.Kysely({ dialect: new BunSqliteDialect({ database: sqlite$1 }) });
1576
+ sqlite.exec("PRAGMA foreign_keys = ON");
1577
+ sqlite.exec("PRAGMA busy_timeout = 5000");
1578
+ sqlite.exec(`PRAGMA mmap_size = ${resolveMmapSize(config)}`);
1579
+ return new kysely.Kysely({ dialect: new BunSqliteDialect({ database: sqlite }) });
1560
1580
  }
1561
- const sqlite = new (require("better-sqlite3"))(filename, {
1581
+ return new kysely.Kysely({ dialect: new kysely.SqliteDialect({ database: openBetterSqlite3(require("better-sqlite3"), filename, config) }) });
1582
+ }
1583
+ /**
1584
+ * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
1585
+ * Exported so tests running under bun can exercise this path with a fake driver.
1586
+ */
1587
+ function openBetterSqlite3(BetterSqlite3, filename, config) {
1588
+ const sqlite = new BetterSqlite3(filename, {
1562
1589
  readonly: config.readonly === true,
1563
1590
  fileMustExist: config.create === false
1564
1591
  });
@@ -1570,7 +1597,8 @@ function createKysely(config) {
1570
1597
  }
1571
1598
  sqlite.pragma("foreign_keys = ON");
1572
1599
  sqlite.pragma("busy_timeout = 5000");
1573
- return new kysely.Kysely({ dialect: new kysely.SqliteDialect({ database: sqlite }) });
1600
+ sqlite.pragma(`mmap_size = ${resolveMmapSize(config)}`);
1601
+ return sqlite;
1574
1602
  }
1575
1603
  /**
1576
1604
  * Get the underlying SQLite database instance from Kysely
@@ -1583,8 +1611,12 @@ function getRawDatabase(db) {
1583
1611
  }
1584
1612
 
1585
1613
  //#endregion
1614
+ exports.DEFAULT_MMAP_SIZE = DEFAULT_MMAP_SIZE;
1586
1615
  exports.DurableObjectSqliteDialect = DurableObjectSqliteDialect;
1616
+ exports.MMAP_SIZE_ENV = MMAP_SIZE_ENV;
1587
1617
  exports.createKysely = createKysely;
1588
1618
  exports.getDoStorageWriteEpoch = getDoStorageWriteEpoch;
1589
1619
  exports.getRawDatabase = getRawDatabase;
1620
+ exports.openBetterSqlite3 = openBetterSqlite3;
1621
+ exports.resolveMmapSize = resolveMmapSize;
1590
1622
  exports.resolveWalCheckpointIntervalMs = resolveWalCheckpointIntervalMs;
package/lib/kysely.d.cts CHANGED
@@ -87,8 +87,25 @@ interface SqliteConfig {
87
87
  * Disabled by default (0 / undefined).
88
88
  */
89
89
  walCheckpointIntervalMs?: number;
90
+ /**
91
+ * `PRAGMA mmap_size` in bytes, applied to every better-sqlite3 / bun:sqlite connection (readonly included).
92
+ * Memory-mapped reads skip the pread syscall + copy into the small page cache on large databases.
93
+ * SQLite clamps the value to its compile-time `SQLITE_MAX_MMAP_SIZE` (better-sqlite3 11.x: 2147418112).
94
+ * `0` disables. Falls back to the `SQLITE_INDEXDB_MMAP_SIZE` env var, then 8 GiB.
95
+ * Invalid values (negative, fractional, non-numeric) are ignored with a warning.
96
+ */
97
+ mmapSize?: number;
90
98
  }
91
99
  declare function resolveWalCheckpointIntervalMs(config: SqliteConfig): number | undefined;
100
+ /** Default `PRAGMA mmap_size` (8 GiB). */
101
+ declare const DEFAULT_MMAP_SIZE: number;
102
+ /** Env var overriding the default `PRAGMA mmap_size` (bytes, `0` disables). */
103
+ declare const MMAP_SIZE_ENV = "SQLITE_INDEXDB_MMAP_SIZE";
104
+ /**
105
+ * Resolve `PRAGMA mmap_size`: valid `config.mmapSize` wins, then a valid `SQLITE_INDEXDB_MMAP_SIZE`, then
106
+ * `DEFAULT_MMAP_SIZE`. Invalid input never becomes `0` (an empty env var is not "disable").
107
+ */
108
+ declare function resolveMmapSize(config: SqliteConfig, env?: Record<string, string | undefined>): number;
92
109
  /**
93
110
  * Create a Kysely instance with SQLite dialect
94
111
  * Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
@@ -107,6 +124,11 @@ declare function resolveWalCheckpointIntervalMs(config: SqliteConfig): number |
107
124
  * ```
108
125
  */
109
126
  declare function createKysely(config: SqliteConfig): Kysely<Database>;
127
+ /**
128
+ * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
129
+ * Exported so tests running under bun can exercise this path with a fake driver.
130
+ */
131
+ declare function openBetterSqlite3(BetterSqlite3: new (filename: string, options: Record<string, unknown>) => any, filename: string, config: SqliteConfig): any;
110
132
  /**
111
133
  * Get the underlying SQLite database instance from Kysely
112
134
  * Useful for executing raw SQL or pragmas
@@ -114,4 +136,4 @@ declare function createKysely(config: SqliteConfig): Kysely<Database>;
114
136
  */
115
137
  declare function getRawDatabase(db: Kysely<Database>): any;
116
138
  //#endregion
117
- export { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, createKysely, getDoStorageWriteEpoch, getRawDatabase, resolveWalCheckpointIntervalMs };
139
+ export { DEFAULT_MMAP_SIZE, DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, MMAP_SIZE_ENV, SqliteConfig, createKysely, getDoStorageWriteEpoch, getRawDatabase, openBetterSqlite3, resolveMmapSize, resolveWalCheckpointIntervalMs };
@@ -0,0 +1,28 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+
3
+ //#region src/migrations/011-tx-ref-tx-type.ts
4
+ var _011_tx_ref_tx_type_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
5
+ down: () => down,
6
+ up: () => up
7
+ });
8
+ /**
9
+ * Migration 011 - intentionally a no-op (#1885).
10
+ *
11
+ * #1884 shipped 011 as the tx_ref.tx_type back-fill + index, run at startup. That work now runs only offline
12
+ * (`scripts/ops/indexdb-migrate.mjs` -> `migrateTxRefTxType` in ../tx-ref-tx-type), never while a node starts.
13
+ * The entry stays in the chain because databases created from master after #1884 have `011-tx-ref-tx-type`
14
+ * recorded in kysely_migration, and Kysely refuses to run when a recorded migration is missing from the provider.
15
+ * Keeping the name also keeps 012+ ordered after it.
16
+ */
17
+ async function up(_db) {}
18
+ async function down(_db) {}
19
+
20
+ //#endregion
21
+ Object.defineProperty(exports, '_011_tx_ref_tx_type_exports', {
22
+ enumerable: true,
23
+ get: function () {
24
+ return _011_tx_ref_tx_type_exports;
25
+ }
26
+ });
27
+ exports.down = down;
28
+ exports.up = up;