@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.
package/esm/db/base.d.mts 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/esm/db/base.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { buildTxRefDrivenQuery } from "./tx-ref-query.mjs";
1
2
  import { sql } from "kysely";
2
3
  import { BaseIndexDB, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, parseDateTime } from "@ocap/indexdb";
3
4
  import { toChecksumAddress } from "@arcblock/did/lib/type";
@@ -34,6 +35,7 @@ function buildPagingResult(total, pagination, itemCount) {
34
35
  var SqliteBaseIndexDB = class extends BaseIndexDB {
35
36
  constructor(..._args) {
36
37
  super(..._args);
38
+ this.txRefTxTypeReady = false;
37
39
  this.txCountCache = null;
38
40
  }
39
41
  /**
@@ -181,12 +183,33 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
181
183
  const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
182
184
  const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
183
185
  const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
186
+ const txRefDriven = !isMutual && activeJsonFilters.length >= 1 && (hasNonJsonFilters || activeJsonFilters.length > 1);
187
+ const txRefDrivenInput = (limit, offset) => ({
188
+ refFilters: activeJsonFilters,
189
+ sender,
190
+ receiver,
191
+ gasPayer,
192
+ direction,
193
+ types,
194
+ txs,
195
+ validity,
196
+ txType: this.txRefTxTypeReady,
197
+ start: parsedStart || void 0,
198
+ end: parsedEnd || void 0,
199
+ order: pagination.order.type === "desc" ? "desc" : "asc",
200
+ limit,
201
+ offset
202
+ });
184
203
  if (isMutual) {
185
204
  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()]);
186
205
  total = (c1?.count ?? 0) + (c2?.count ?? 0);
187
206
  } else if (!hasNonJsonFilters && activeJsonFilters.length === 1) {
188
207
  const [refType, values] = activeJsonFilters[0];
189
208
  total = (await this.db.selectFrom("tx_ref").select(this.db.fn.countAll().as("count")).where("type", "=", refType).where("value", "in", values).executeTakeFirst())?.count ?? 0;
209
+ } else if (txRefDriven) {
210
+ const { count } = buildTxRefDrivenQuery(txRefDrivenInput(0, 0));
211
+ const countRows = await count.execute(this.db);
212
+ total = Number(countRows.rows[0]?.count ?? 0);
190
213
  } else if (isUnionOnly) {
191
214
  const [senderCount, receiverCount, overlapCount] = await Promise.all([
192
215
  this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).executeTakeFirst(),
@@ -236,6 +259,9 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
236
259
  const hashOrder = new Map(hashes.map((h, i) => [h, i]));
237
260
  rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
238
261
  } else rawResults = [];
262
+ } else if (txRefDriven && pagination.order.field === "time") {
263
+ const { page } = buildTxRefDrivenQuery(txRefDrivenInput(pagination.size, pagination.cursor));
264
+ rawResults = (await page.execute(this.db)).rows;
239
265
  } else {
240
266
  qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
241
267
  rawResults = await qb.execute();
@@ -1,6 +1,7 @@
1
1
  import { Database } from "../interfaces.mjs";
2
2
  import SqliteBaseIndexDB from "./base.mjs";
3
3
  import { SqliteConfig } from "../kysely.mjs";
4
+ import { TxRefTxTypeBackfillOptions, TxRefTxTypeMigrationResult } from "../tx-ref-tx-type.mjs";
4
5
  import { Kysely, Transaction } from "kysely";
5
6
  import { IIndexDB, IIndexTable, IndexTableTypeMap } from "@ocap/types";
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
  *
package/esm/db/index.mjs CHANGED
@@ -2,6 +2,7 @@ import { createKysely } from "../kysely.mjs";
2
2
  import { runMigrations } from "../migrations/index.mjs";
3
3
  import base_default from "../table/base.mjs";
4
4
  import account_default from "../table/account.mjs";
5
+ import { addTxRefTxTypeColumn, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType } from "../tx-ref-tx-type.mjs";
5
6
  import transaction_default from "../table/transaction.mjs";
6
7
  import base_default$1 from "./base.mjs";
7
8
  import package_default from "../package.mjs";
@@ -532,9 +533,39 @@ var SqliteIndexDB = class extends base_default$1 {
532
533
  async initialize() {
533
534
  if (this.initialized) return;
534
535
  await runMigrations(this.db);
536
+ await this.detectTxRefTxType();
535
537
  this.initialized = true;
536
538
  }
537
539
  /**
540
+ * Detect the tx_ref.tx_type state once (#1885). Read-only: startup never adds the column, back-fills or builds
541
+ * the index; that is migrateTxRefTxType, run offline.
542
+ */
543
+ async detectTxRefTxType() {
544
+ const k = this.db;
545
+ this.tx.setTxRefTxTypeColumn(await hasTxRefTxTypeColumn(k));
546
+ this.txRefTxTypeReady = await isTxRefTxTypeReady(k);
547
+ }
548
+ /**
549
+ * Run the offline tx_ref.tx_type migration on this database (#1870, #1885), then switch this instance's write
550
+ * and query paths to the result. Only for scripts/ops/indexdb-migrate.mjs and tests, with the chain stopped;
551
+ * never part of initialize().
552
+ *
553
+ * This instance must be the only SqliteIndexDB (in any process) with the file open: other instances keep their
554
+ * cached "tx_ref has tx_type" flag (TransactionTable#txRefHasTxType) and their later writes leave tx_type NULL.
555
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
556
+ */
557
+ async migrateTxRefTxType(options) {
558
+ const k = this.db;
559
+ const columnAdded = await addTxRefTxTypeColumn(k);
560
+ this.tx.setTxRefTxTypeColumn(true);
561
+ const result = await migrateTxRefTxType(k, options);
562
+ await this.detectTxRefTxType();
563
+ return {
564
+ ...result,
565
+ columnAdded
566
+ };
567
+ }
568
+ /**
538
569
  * Execute multiple operations within a database transaction
539
570
  *
540
571
  * @param fn - Function receiving Kysely transaction object
@@ -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 };
@@ -0,0 +1,129 @@
1
+ import { sql } from "kysely";
2
+
3
+ //#region src/db/tx-ref-query.ts
4
+ /**
5
+ * tx_ref-driven SQL for `listTransactions` (issue #1861).
6
+ *
7
+ * The generic path (`select * from tx where <conds> and hash in (select hash from tx_ref ...) order by time`)
8
+ * makes SQLite walk every tx_ref row of the account, look up every full `tx` row, filter, sort in a temp
9
+ * b-tree and only then apply offset/limit: cost is O(total history of the account), twice (count + page).
10
+ *
11
+ * Here tx_ref is the OUTER loop (`cross join` pins the join order), ordered by `idx_tx_ref_time_lookup
12
+ * (type, value, time DESC)`. `tx` is probed by primary key (`hash = ?`) only for rows that are actually
13
+ * needed, and time filters are pushed down to `tx_ref.time` so they become index range bounds.
14
+ *
15
+ * Correctness notes:
16
+ * - `tx_ref.time` is copied from `tx.time` on insert and rewritten on every update (TransactionTable.syncTxRefs),
17
+ * so ordering/filtering on `r.time` equals ordering/filtering on `tx.time`.
18
+ * Only difference: an empty-string `tx.time` is stored as NULL in tx_ref (never produced by the chain).
19
+ * - Single-value driver: `(hash, type, value)` is unique, so no duplicates are possible; ties on `time` come out
20
+ * in tx_ref index order (same as the pre-existing single-filter fast path).
21
+ * - Multi-value driver (`value in (a, b)`): a tx can match twice. The driver is a `select distinct hash, time`
22
+ * subquery over tx_ref only (index-only, no `tx` lookups), ordered by `(time, hash)`; `tx` rows are looked up
23
+ * lazily, only until offset+limit rows pass the remaining filters.
24
+ * - Additional JSON filters are `exists (select 1 from tx_ref x where x.hash = r.hash ...)` probes on idx_tx_ref_pk.
25
+ *
26
+ * tx_type (#1870, `txType: true` once the offline migrateTxRefTxType (#1885) has back-filled tx_ref.tx_type and built
27
+ * idx_tx_ref_type_value_txtype_time):
28
+ * - The type filter moves from `tx.type in (...)` to `r.tx_type in (...)` (into the deduping subquery for a
29
+ * multi-value driver), so rows of other types are dropped before `tx` is probed.
30
+ * - In the page query it is written `+r.tx_type`: the unary plus keeps the planner on the time index
31
+ * (no sort; the page stops after offset+limit rows) instead of seeking the new index per type and sorting.
32
+ * - If the type filter (plus time / other tx_ref filters) is all there is, the count does not join `tx` at all:
33
+ * `SEARCH r USING COVERING INDEX idx_tx_ref_type_value_txtype_time (type=? AND value=? AND tx_type=?)`.
34
+ * Same result as the join: a non-NULL tx_type is only ever written from an existing tx row (and tx rows are
35
+ * never deleted without their tx_ref rows), and a NULL one cannot match `in (...)`. Counts without a type
36
+ * filter keep the join, so orphan tx_ref rows (if any) are still excluded there.
37
+ */
38
+ const and = (parts) => sql.join(parts, sql` and `);
39
+ /** Conditions that need the `tx` row (the type filter is not one of them when tx_type is ready). */
40
+ function txConditions(input) {
41
+ const { sender, receiver, gasPayer, direction, types = [], txs = [], validity, txType } = input;
42
+ const conds = [];
43
+ if (sender && receiver) if (direction === "MUTUAL") conds.push(sql`((tx.sender = ${sender} and tx.receiver = ${receiver}) or (tx.sender = ${receiver} and tx.receiver = ${sender}))`);
44
+ else if (direction === "ONE_WAY") conds.push(sql`tx.sender = ${sender}`, sql`tx.receiver = ${receiver}`);
45
+ else conds.push(sql`(tx.sender = ${sender} or tx.receiver = ${receiver})`);
46
+ else if (sender) conds.push(sql`tx.sender = ${sender}`);
47
+ else if (receiver) conds.push(sql`tx.receiver = ${receiver}`);
48
+ if (gasPayer) conds.push(sql`tx.gasPayer = ${gasPayer}`);
49
+ if (types.length && !txType) conds.push(sql`tx.type in (${sql.join(types)})`);
50
+ if (txs.length) conds.push(sql`tx.hash in (${sql.join(txs)})`);
51
+ if (validity === "VALID") conds.push(sql`tx.valid = 1`);
52
+ else if (validity === "INVALID") conds.push(sql`tx.valid = 0`);
53
+ return conds;
54
+ }
55
+ function timeConditions(alias, start, end) {
56
+ const col = sql.ref(`${alias}.time`);
57
+ const conds = [];
58
+ if (start) conds.push(sql`${col} > ${start}`);
59
+ if (end) conds.push(sql`${col} <= ${end}`);
60
+ return conds;
61
+ }
62
+ /** Pick the filter that drives the scan: a single-valued one avoids the dedupe step. */
63
+ function pickDriver(refFilters) {
64
+ const single = refFilters.findIndex(([, values]) => values.length === 1);
65
+ return single >= 0 ? single : 0;
66
+ }
67
+ function buildTxRefDrivenQuery(input) {
68
+ const { refFilters, start, end, order, limit, offset, types = [], txType } = input;
69
+ if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
70
+ const driverIndex = pickDriver(refFilters);
71
+ const [driverType, driverValues] = refFilters[driverIndex];
72
+ const dir = sql.raw(order === "desc" ? "desc" : "asc");
73
+ const typeOnRef = !!txType && types.length > 0;
74
+ const txConds = txConditions(input);
75
+ const countWithoutTx = typeOnRef && txConds.length === 0;
76
+ let from;
77
+ let countFrom;
78
+ const driverWhere = [];
79
+ const pageTypeWhere = [];
80
+ const countTypeWhere = [];
81
+ if (driverValues.length === 1) {
82
+ from = sql`tx_ref r cross join tx`;
83
+ countFrom = countWithoutTx ? sql`tx_ref r` : from;
84
+ driverWhere.push(sql`r.type = ${driverType}`, sql`r.value = ${driverValues[0]}`, ...timeConditions("r", start, end));
85
+ if (typeOnRef) {
86
+ pageTypeWhere.push(sql`+r.tx_type in (${sql.join(types)})`);
87
+ countTypeWhere.push(sql`r.tx_type in (${sql.join(types)})`);
88
+ }
89
+ } else {
90
+ const innerOf = (typeCond) => and([
91
+ sql`type = ${driverType}`,
92
+ sql`value in (${sql.join(driverValues)})`,
93
+ ...typeCond,
94
+ ...timeConditions("tx_ref", start, end)
95
+ ]);
96
+ const pageInner = innerOf(typeOnRef ? [sql`+tx_type in (${sql.join(types)})`] : []);
97
+ const countInner = innerOf(typeOnRef ? [sql`tx_type in (${sql.join(types)})`] : []);
98
+ from = sql`(${sql`select distinct hash, time from tx_ref where ${pageInner} order by time ${dir}, hash limit -1`}) r cross join tx`;
99
+ const countSub = sql`(select distinct hash, time from tx_ref where ${countInner}) r`;
100
+ countFrom = countWithoutTx ? countSub : sql`${countSub} cross join tx`;
101
+ }
102
+ const joinWhere = [sql`tx.hash = r.hash`, ...txConds];
103
+ const existsWhere = [];
104
+ refFilters.forEach(([refType, values], i) => {
105
+ if (i === driverIndex) return;
106
+ existsWhere.push(sql`exists (select 1 from tx_ref x where x.hash = r.hash and x.type = ${refType} and x.value in (${sql.join(values)}))`);
107
+ });
108
+ const orderBy = driverValues.length === 1 ? sql`order by r.time ${dir}` : sql``;
109
+ const pageWhere = and([
110
+ ...driverWhere,
111
+ ...pageTypeWhere,
112
+ ...joinWhere,
113
+ ...existsWhere
114
+ ]);
115
+ const countParts = [
116
+ ...driverWhere,
117
+ ...countTypeWhere,
118
+ ...countWithoutTx ? [] : joinWhere,
119
+ ...existsWhere
120
+ ];
121
+ const countWhere = countParts.length ? sql`where ${and(countParts)}` : sql``;
122
+ return {
123
+ page: sql`select tx.* from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
124
+ count: sql`select count(*) as count from ${countFrom} ${countWhere}`
125
+ };
126
+ }
127
+
128
+ //#endregion
129
+ export { buildTxRefDrivenQuery };
package/esm/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import SqliteBaseIndexDB from "./db/base.mjs";
2
2
  import { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, getRawDatabase } from "./kysely.mjs";
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.mjs";
3
4
  import SqliteIndexDB from "./db/index.mjs";
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 };
package/esm/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DurableObjectSqliteDialect, getRawDatabase } from "./kysely.mjs";
2
+ import { 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 } from "./tx-ref-tx-type.mjs";
2
3
  import base_default from "./db/base.mjs";
3
4
  import db_default from "./db/index.mjs";
4
5
 
@@ -6,4 +7,4 @@ import db_default from "./db/index.mjs";
6
7
  var src_default = db_default;
7
8
 
8
9
  //#endregion
9
- export { DurableObjectSqliteDialect, base_default as SqliteBaseIndexDB, src_default as default, getRawDatabase };
10
+ export { DurableObjectSqliteDialect, base_default as SqliteBaseIndexDB, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, addTxRefTxTypeColumn, backfillTxRefTxType, src_default 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/esm/kysely.d.mts 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 };
package/esm/kysely.mjs 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 : import.meta.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({ 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({ dialect: new BunSqliteDialect({ database: sqlite }) });
1560
1580
  }
1561
- const sqlite = new (__require("better-sqlite3"))(filename, {
1581
+ return new Kysely({ dialect: new 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({ dialect: new 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,4 +1611,4 @@ function getRawDatabase(db) {
1583
1611
  }
1584
1612
 
1585
1613
  //#endregion
1586
- export { DurableObjectSqliteDialect, createKysely, getDoStorageWriteEpoch, getRawDatabase, resolveWalCheckpointIntervalMs };
1614
+ export { DEFAULT_MMAP_SIZE, DurableObjectSqliteDialect, MMAP_SIZE_ENV, createKysely, getDoStorageWriteEpoch, getRawDatabase, openBetterSqlite3, resolveMmapSize, resolveWalCheckpointIntervalMs };
@@ -0,0 +1,17 @@
1
+ import { Kysely } from "kysely";
2
+
3
+ //#region src/migrations/011-tx-ref-tx-type.d.ts
4
+
5
+ /**
6
+ * Migration 011 - intentionally a no-op (#1885).
7
+ *
8
+ * #1884 shipped 011 as the tx_ref.tx_type back-fill + index, run at startup. That work now runs only offline
9
+ * (`scripts/ops/indexdb-migrate.mjs` -> `migrateTxRefTxType` in ../tx-ref-tx-type), never while a node starts.
10
+ * The entry stays in the chain because databases created from master after #1884 have `011-tx-ref-tx-type`
11
+ * recorded in kysely_migration, and Kysely refuses to run when a recorded migration is missing from the provider.
12
+ * Keeping the name also keeps 012+ ordered after it.
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,21 @@
1
+ import { __exportAll } from "../_virtual/rolldown_runtime.mjs";
2
+
3
+ //#region src/migrations/011-tx-ref-tx-type.ts
4
+ var _011_tx_ref_tx_type_exports = /* @__PURE__ */ __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
+ export { _011_tx_ref_tx_type_exports, down, up };
@@ -8,6 +8,7 @@ import { _007_token_factory_feerate_integer_exports } from "./007-token-factory-
8
8
  import { _008_index_failure_exports } from "./008-index-failure.mjs";
9
9
  import { _009_tx_gas_payer_exports } from "./009-tx-gas-payer.mjs";
10
10
  import { _010_tx_evidences_exports } from "./010-tx-evidences.mjs";
11
+ import { _011_tx_ref_tx_type_exports } from "./011-tx-ref-tx-type.mjs";
11
12
  import { Migrator } from "kysely";
12
13
 
13
14
  //#region src/migrations/index.ts
@@ -27,7 +28,8 @@ var InMemoryMigrationProvider = class {
27
28
  "007-token-factory-feerate-integer": _007_token_factory_feerate_integer_exports,
28
29
  "008-index-failure": _008_index_failure_exports,
29
30
  "009-tx-gas-payer": _009_tx_gas_payer_exports,
30
- "010-tx-evidences": _010_tx_evidences_exports
31
+ "010-tx-evidences": _010_tx_evidences_exports,
32
+ "011-tx-ref-tx-type": _011_tx_ref_tx_type_exports
31
33
  };
32
34
  }
33
35
  };
@@ -10,6 +10,13 @@ import { TIndexedTransaction } from "@ocap/types";
10
10
  * and maintain the tx_ref junction table for fast JSON array lookups
11
11
  */
12
12
  declare class TransactionTable extends SqliteTable<TIndexedTransaction> {
13
+ /**
14
+ * Whether tx_ref has the tx_type column. Set by SqliteIndexDB.initialize() (and after migrateTxRefTxType);
15
+ * detected lazily on the first write otherwise. The schema only changes offline, so it is never re-read.
16
+ */
17
+ private txRefHasTxType;
18
+ setTxRefTxTypeColumn(present: boolean | undefined): void;
19
+ private writesTxRefTxType;
13
20
  /**
14
21
  * Override _insert to format transaction before inserting
15
22
  * This populates assets, tokens, factories, etc. from itxJson,
@@ -1,4 +1,5 @@
1
1
  import base_default from "./base.mjs";
2
+ import { hasTxRefTxTypeColumn } from "../tx-ref-tx-type.mjs";
2
3
  import { sql } from "kysely";
3
4
  import { formatTxBeforeInsert } from "@ocap/indexdb";
4
5
 
@@ -20,6 +21,13 @@ const TX_REF_TYPES = [
20
21
  * and maintain the tx_ref junction table for fast JSON array lookups
21
22
  */
22
23
  var TransactionTable = class extends base_default {
24
+ setTxRefTxTypeColumn(present) {
25
+ this.txRefHasTxType = present;
26
+ }
27
+ async writesTxRefTxType(executor) {
28
+ if (this.txRefHasTxType === void 0) this.txRefHasTxType = await hasTxRefTxTypeColumn(executor);
29
+ return this.txRefHasTxType;
30
+ }
23
31
  /**
24
32
  * Override _insert to format transaction before inserting
25
33
  * This populates assets, tokens, factories, etc. from itxJson,
@@ -59,6 +67,8 @@ var TransactionTable = class extends base_default {
59
67
  const executor = this.getExecutor(context);
60
68
  if (replaceExisting) await sql`DELETE FROM tx_ref WHERE hash = ${hash}`.execute(executor);
61
69
  const time = data.time || null;
70
+ const withTxType = await this.writesTxRefTxType(executor);
71
+ const txType = typeof data.type === "string" ? data.type : null;
62
72
  for (const [type, field] of TX_REF_TYPES) {
63
73
  let values = data[field];
64
74
  if (typeof values === "string") try {
@@ -67,7 +77,8 @@ var TransactionTable = class extends base_default {
67
77
  continue;
68
78
  }
69
79
  if (!Array.isArray(values) || values.length === 0) continue;
70
- 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);
80
+ for (const v of values) if (typeof v === "string" && v) if (withTxType) await sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time, tx_type) VALUES (${hash}, ${type}, ${v}, ${time}, ${txType})`.execute(executor);
81
+ else await sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(executor);
71
82
  }
72
83
  }
73
84
  /**