@ocap/indexdb-sqlite 1.31.7 → 1.31.9
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 +19 -3
- package/esm/db/base.mjs +66 -43
- package/esm/db/index.d.mts +16 -0
- package/esm/db/index.mjs +31 -0
- package/esm/db/tx-ref-query.d.mts +5 -1
- package/esm/db/tx-ref-query.mjs +53 -15
- package/esm/db/tx-rows.d.mts +11 -0
- package/esm/db/tx-rows.mjs +71 -0
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/esm/interfaces.d.mts +2 -0
- package/esm/kysely.d.mts +23 -1
- package/esm/kysely.mjs +49 -11
- package/esm/migrations/011-tx-ref-tx-type.d.mts +17 -0
- package/esm/migrations/011-tx-ref-tx-type.mjs +21 -0
- package/esm/migrations/index.mjs +3 -1
- package/esm/table/transaction.d.mts +7 -0
- package/esm/table/transaction.mjs +12 -1
- package/esm/tx-ref-tx-type.d.mts +131 -0
- package/esm/tx-ref-tx-type.mjs +211 -0
- package/lib/db/base.cjs +68 -44
- package/lib/db/base.d.cts +19 -3
- package/lib/db/index.cjs +31 -0
- package/lib/db/index.d.cts +16 -0
- package/lib/db/tx-ref-query.cjs +53 -15
- package/lib/db/tx-ref-query.d.cts +5 -1
- package/lib/db/tx-rows.cjs +74 -0
- package/lib/db/tx-rows.d.cts +11 -0
- package/lib/index.cjs +12 -1
- package/lib/index.d.cts +2 -1
- package/lib/interfaces.d.cts +2 -0
- package/lib/kysely.cjs +52 -10
- package/lib/kysely.d.cts +23 -1
- package/lib/migrations/011-tx-ref-tx-type.cjs +28 -0
- package/lib/migrations/011-tx-ref-tx-type.d.cts +17 -0
- package/lib/migrations/index.cjs +3 -1
- package/lib/table/transaction.cjs +12 -1
- package/lib/table/transaction.d.cts +7 -0
- package/lib/tx-ref-tx-type.cjs +222 -0
- package/lib/tx-ref-tx-type.d.cts +131 -0
- package/package.json +6 -6
package/esm/kysely.mjs
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { __require } from "./_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { instrumentSqlTiming } from "@ocap/util/lib/sql-timing";
|
|
2
3
|
import { Kysely, SqliteAdapter, SqliteDialect, SqliteIntrospector, SqliteQueryCompiler } from "kysely";
|
|
3
4
|
|
|
4
5
|
//#region src/kysely.ts
|
|
6
|
+
const timeConnection = async (connection) => {
|
|
7
|
+
instrumentSqlTiming(connection);
|
|
8
|
+
};
|
|
5
9
|
var ConnectionMutex = class {
|
|
6
10
|
async lock() {
|
|
7
11
|
while (this.promise) await this.promise;
|
|
@@ -1515,6 +1519,25 @@ function resolveWalCheckpointIntervalMs(config) {
|
|
|
1515
1519
|
const v = config.walCheckpointIntervalMs ?? fromEnv;
|
|
1516
1520
|
return Number.isFinite(v) && v > 0 ? Math.floor(v) : void 0;
|
|
1517
1521
|
}
|
|
1522
|
+
/** Default `PRAGMA mmap_size` (8 GiB). */
|
|
1523
|
+
const DEFAULT_MMAP_SIZE = 8 * 1024 * 1024 * 1024;
|
|
1524
|
+
/** Env var overriding the default `PRAGMA mmap_size` (bytes, `0` disables). */
|
|
1525
|
+
const MMAP_SIZE_ENV = "SQLITE_INDEXDB_MMAP_SIZE";
|
|
1526
|
+
function parseMmapSize(value, source) {
|
|
1527
|
+
if (value === void 0) return void 0;
|
|
1528
|
+
let n;
|
|
1529
|
+
if (typeof value === "number") n = value;
|
|
1530
|
+
else if (typeof value === "string" && /^\d+$/.test(value.trim())) n = Number(value.trim());
|
|
1531
|
+
if (n !== void 0 && Number.isSafeInteger(n) && n >= 0) return n;
|
|
1532
|
+
console.warn(`[sqlite] ignoring invalid mmap_size from ${source}: ${JSON.stringify(String(value))}`);
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Resolve `PRAGMA mmap_size`: valid `config.mmapSize` wins, then a valid `SQLITE_INDEXDB_MMAP_SIZE`, then
|
|
1536
|
+
* `DEFAULT_MMAP_SIZE`. Invalid input never becomes `0` (an empty env var is not "disable").
|
|
1537
|
+
*/
|
|
1538
|
+
function resolveMmapSize(config, env = process.env) {
|
|
1539
|
+
return parseMmapSize(config.mmapSize, "config.mmapSize") ?? parseMmapSize(env[MMAP_SIZE_ENV], MMAP_SIZE_ENV) ?? DEFAULT_MMAP_SIZE;
|
|
1540
|
+
}
|
|
1518
1541
|
/**
|
|
1519
1542
|
* Create a Kysely instance with SQLite dialect
|
|
1520
1543
|
* Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
|
|
@@ -1544,21 +1567,35 @@ function createKysely(config) {
|
|
|
1544
1567
|
const bunReq = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : typeof __require === "function" ? __require : import.meta.require;
|
|
1545
1568
|
const { BunSqliteDialect } = bunReq("kysely-bun-sqlite");
|
|
1546
1569
|
const { Database: BunDatabase } = bunReq("bun:sqlite");
|
|
1547
|
-
const sqlite
|
|
1570
|
+
const sqlite = new BunDatabase(filename, {
|
|
1548
1571
|
create: config.create !== false,
|
|
1549
1572
|
readonly: config.readonly === true
|
|
1550
1573
|
});
|
|
1551
1574
|
if (config.walMode !== false && !config.readonly && filename !== ":memory:") {
|
|
1552
|
-
sqlite
|
|
1553
|
-
sqlite
|
|
1575
|
+
sqlite.exec("PRAGMA journal_mode = WAL");
|
|
1576
|
+
sqlite.exec("PRAGMA synchronous = NORMAL");
|
|
1554
1577
|
const walCp = resolveWalAutoCheckpoint(config);
|
|
1555
|
-
if (walCp !== void 0) sqlite
|
|
1578
|
+
if (walCp !== void 0) sqlite.exec(`PRAGMA wal_autocheckpoint = ${walCp}`);
|
|
1556
1579
|
}
|
|
1557
|
-
sqlite
|
|
1558
|
-
sqlite
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1580
|
+
sqlite.exec("PRAGMA foreign_keys = ON");
|
|
1581
|
+
sqlite.exec("PRAGMA busy_timeout = 5000");
|
|
1582
|
+
sqlite.exec(`PRAGMA mmap_size = ${resolveMmapSize(config)}`);
|
|
1583
|
+
return new Kysely({ dialect: new BunSqliteDialect({
|
|
1584
|
+
database: sqlite,
|
|
1585
|
+
onCreateConnection: timeConnection
|
|
1586
|
+
}) });
|
|
1587
|
+
}
|
|
1588
|
+
return new Kysely({ dialect: new SqliteDialect({
|
|
1589
|
+
database: openBetterSqlite3(__require("better-sqlite3"), filename, config),
|
|
1590
|
+
onCreateConnection: timeConnection
|
|
1591
|
+
}) });
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
|
|
1595
|
+
* Exported so tests running under bun can exercise this path with a fake driver.
|
|
1596
|
+
*/
|
|
1597
|
+
function openBetterSqlite3(BetterSqlite3, filename, config) {
|
|
1598
|
+
const sqlite = new BetterSqlite3(filename, {
|
|
1562
1599
|
readonly: config.readonly === true,
|
|
1563
1600
|
fileMustExist: config.create === false
|
|
1564
1601
|
});
|
|
@@ -1570,7 +1607,8 @@ function createKysely(config) {
|
|
|
1570
1607
|
}
|
|
1571
1608
|
sqlite.pragma("foreign_keys = ON");
|
|
1572
1609
|
sqlite.pragma("busy_timeout = 5000");
|
|
1573
|
-
|
|
1610
|
+
sqlite.pragma(`mmap_size = ${resolveMmapSize(config)}`);
|
|
1611
|
+
return sqlite;
|
|
1574
1612
|
}
|
|
1575
1613
|
/**
|
|
1576
1614
|
* Get the underlying SQLite database instance from Kysely
|
|
@@ -1583,4 +1621,4 @@ function getRawDatabase(db) {
|
|
|
1583
1621
|
}
|
|
1584
1622
|
|
|
1585
1623
|
//#endregion
|
|
1586
|
-
export { DurableObjectSqliteDialect, createKysely, getDoStorageWriteEpoch, getRawDatabase, resolveWalCheckpointIntervalMs };
|
|
1624
|
+
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 };
|
package/esm/migrations/index.mjs
CHANGED
|
@@ -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
|
/**
|
|
@@ -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 };
|