@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.
Files changed (41) hide show
  1. package/esm/db/base.d.mts +19 -3
  2. package/esm/db/base.mjs +66 -43
  3. package/esm/db/index.d.mts +16 -0
  4. package/esm/db/index.mjs +31 -0
  5. package/esm/db/tx-ref-query.d.mts +5 -1
  6. package/esm/db/tx-ref-query.mjs +53 -15
  7. package/esm/db/tx-rows.d.mts +11 -0
  8. package/esm/db/tx-rows.mjs +71 -0
  9. package/esm/index.d.mts +2 -1
  10. package/esm/index.mjs +2 -1
  11. package/esm/interfaces.d.mts +2 -0
  12. package/esm/kysely.d.mts +23 -1
  13. package/esm/kysely.mjs +49 -11
  14. package/esm/migrations/011-tx-ref-tx-type.d.mts +17 -0
  15. package/esm/migrations/011-tx-ref-tx-type.mjs +21 -0
  16. package/esm/migrations/index.mjs +3 -1
  17. package/esm/table/transaction.d.mts +7 -0
  18. package/esm/table/transaction.mjs +12 -1
  19. package/esm/tx-ref-tx-type.d.mts +131 -0
  20. package/esm/tx-ref-tx-type.mjs +211 -0
  21. package/lib/db/base.cjs +68 -44
  22. package/lib/db/base.d.cts +19 -3
  23. package/lib/db/index.cjs +31 -0
  24. package/lib/db/index.d.cts +16 -0
  25. package/lib/db/tx-ref-query.cjs +53 -15
  26. package/lib/db/tx-ref-query.d.cts +5 -1
  27. package/lib/db/tx-rows.cjs +74 -0
  28. package/lib/db/tx-rows.d.cts +11 -0
  29. package/lib/index.cjs +12 -1
  30. package/lib/index.d.cts +2 -1
  31. package/lib/interfaces.d.cts +2 -0
  32. package/lib/kysely.cjs +52 -10
  33. package/lib/kysely.d.cts +23 -1
  34. package/lib/migrations/011-tx-ref-tx-type.cjs +28 -0
  35. package/lib/migrations/011-tx-ref-tx-type.d.cts +17 -0
  36. package/lib/migrations/index.cjs +3 -1
  37. package/lib/table/transaction.cjs +12 -1
  38. package/lib/table/transaction.d.cts +7 -0
  39. package/lib/tx-ref-tx-type.cjs +222 -0
  40. package/lib/tx-ref-tx-type.d.cts +131 -0
  41. package/package.json +6 -6
package/esm/db/base.d.mts CHANGED
@@ -4,7 +4,18 @@ import { BaseIndexDB } from "@ocap/indexdb";
4
4
  import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDelegationsResult, IListFactoriesResult, IListRollupBlocksResult, IListRollupValidatorsResult, IListRollupsResult, IListStakesResult, IListTokenFactoriesResult, IListTokensResult, IListTransactionsResult, IndexTableTypeMap, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TSearchResult } from "@ocap/types";
5
5
 
6
6
  //#region src/db/base.d.ts
7
-
7
+ /** Every column of the `tx` table (any order: older databases have `gasPayer` / `evidences` appended). */
8
+ declare const TX_TABLE_COLUMNS: readonly string[];
9
+ /**
10
+ * Internal (non-GraphQL) option of listTransactions (#1872): read only these `tx` columns. Rows then only carry
11
+ * these keys (in this order); `hash` and the sort column are always added because pagination needs them.
12
+ * Omitted / empty = every column, the historical behaviour.
13
+ */
14
+ interface IListTransactionsColumns {
15
+ columns?: readonly string[];
16
+ }
17
+ /** Validated projection, or `null` for `select *`. Unknown column names are a programming error. */
18
+ declare function resolveTxColumns(columns: unknown, orderField: string): string[] | null;
8
19
  /**
9
20
  * Base SQLite IndexDB implementation
10
21
  * Contains all the list methods with SQL-based filtering
@@ -23,6 +34,11 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
23
34
  rollupValidator: IIndexTable<IndexTableTypeMap['rollupValidator']>;
24
35
  tokenDistribution: IIndexTable<IndexTableTypeMap['tokenDistribution']>;
25
36
  tokenFactory: IIndexTable<IndexTableTypeMap['tokenFactory']>;
37
+ /**
38
+ * tx_ref.tx_type is back-filled and indexed (offline migrateTxRefTxType, #1870/#1885). Detected once by initialize();
39
+ * false keeps listTransactions on the 1.31.7 SQL.
40
+ */
41
+ protected txRefTxTypeReady: boolean;
26
42
  protected txCountCache: {
27
43
  total: number;
28
44
  invalid: number;
@@ -44,7 +60,7 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
44
60
  /**
45
61
  * List transactions with filtering and pagination
46
62
  */
47
- listTransactions(params?: Partial<TRequestListTransactions>): Promise<IListTransactionsResult>;
63
+ listTransactions(params?: Partial<TRequestListTransactions> & IListTransactionsColumns): Promise<IListTransactionsResult>;
48
64
  /**
49
65
  * Get related addresses for account migration tracking
50
66
  */
@@ -97,4 +113,4 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
97
113
  search(keyword: string): Promise<TSearchResult[]>;
98
114
  }
99
115
  //#endregion
100
- export { SqliteBaseIndexDB as default };
116
+ export { IListTransactionsColumns, TX_TABLE_COLUMNS, SqliteBaseIndexDB as default, resolveTxColumns };
package/esm/db/base.mjs CHANGED
@@ -1,15 +1,62 @@
1
1
  import { buildTxRefDrivenQuery } from "./tx-ref-query.mjs";
2
+ import { formatTxRows } from "./tx-rows.mjs";
2
3
  import { sql } from "kysely";
3
4
  import { BaseIndexDB, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, parseDateTime } from "@ocap/indexdb";
4
5
  import { toChecksumAddress } from "@arcblock/did/lib/type";
5
6
  import { DEFAULT_TOKEN_DECIMAL } from "@ocap/util/lib/constant";
6
7
  import debugFactory from "debug";
7
- import omit from "lodash/omit.js";
8
8
 
9
9
  //#region src/db/base.ts
10
10
  const debug = debugFactory("@ocap/indexdb-sqlite");
11
11
  const MAX_REQUEST_FACTORY_ADDRESS_SIZE = 100;
12
12
  const SEARCH_LIMIT_PER_TABLE = 5;
13
+ /** Every column of the `tx` table (any order: older databases have `gasPayer` / `evidences` appended). */
14
+ const TX_TABLE_COLUMNS = [
15
+ "hash",
16
+ "code",
17
+ "height",
18
+ "index_",
19
+ "receipts",
20
+ "receiptsVerified",
21
+ "receiver",
22
+ "sender",
23
+ "gasPayer",
24
+ "time",
25
+ "tx",
26
+ "type",
27
+ "finalized",
28
+ "valid",
29
+ "accounts",
30
+ "assets",
31
+ "tokens",
32
+ "tokenSymbols",
33
+ "factories",
34
+ "rollups",
35
+ "stakes",
36
+ "delegations",
37
+ "tokenFactories",
38
+ "genesisTime",
39
+ "renaissanceTime",
40
+ "data",
41
+ "evidences"
42
+ ];
43
+ const TX_TABLE_COLUMN_SET = new Set(TX_TABLE_COLUMNS);
44
+ /** Validated projection, or `null` for `select *`. Unknown column names are a programming error. */
45
+ function resolveTxColumns(columns, orderField) {
46
+ if (columns === void 0 || columns === null) return null;
47
+ if (!Array.isArray(columns)) throw new Error("listTransactions: columns must be an array of tx column names");
48
+ if (columns.length === 0) return null;
49
+ const out = [];
50
+ for (const c of [
51
+ "hash",
52
+ ...columns,
53
+ orderField
54
+ ]) {
55
+ if (typeof c !== "string" || !TX_TABLE_COLUMN_SET.has(c)) throw new Error(`listTransactions: unknown tx column ${JSON.stringify(c)}`);
56
+ if (!out.includes(c)) out.push(c);
57
+ }
58
+ return out;
59
+ }
13
60
  /** Escape SQL LIKE special characters */
14
61
  function escapeLikePattern(s) {
15
62
  return s.replace(/[%_\\]/g, (c) => `\\${c}`);
@@ -35,6 +82,7 @@ function buildPagingResult(total, pagination, itemCount) {
35
82
  var SqliteBaseIndexDB = class extends BaseIndexDB {
36
83
  constructor(..._args) {
37
84
  super(..._args);
85
+ this.txRefTxTypeReady = false;
38
86
  this.txCountCache = null;
39
87
  }
40
88
  /**
@@ -83,7 +131,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
83
131
  * List transactions with filtering and pagination
84
132
  */
85
133
  async listTransactions(params = {}) {
86
- const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
134
+ const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false, columns } = params;
87
135
  const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
88
136
  const { types = [] } = typeFilter;
89
137
  const { factories = [] } = factoryFilter;
@@ -123,7 +171,13 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
123
171
  delegations,
124
172
  includeItxData
125
173
  });
126
- let qb = this.db.selectFrom("tx").selectAll();
174
+ const selected = resolveTxColumns(columns, pagination.order.field);
175
+ const selectTx = () => {
176
+ const q = this.db.selectFrom("tx").selectAll();
177
+ return selected ? q.clearSelect().select(selected) : q;
178
+ };
179
+ const colsSql = selected ? sql.join(selected.map((c) => sql.ref(c))) : sql`*`;
180
+ let qb = selectTx();
127
181
  const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
128
182
  const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
129
183
  if (sender && receiver) if (direction === "MUTUAL") {
@@ -192,6 +246,8 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
192
246
  types,
193
247
  txs,
194
248
  validity,
249
+ txType: this.txRefTxTypeReady,
250
+ columns: selected ?? void 0,
195
251
  start: parsedStart || void 0,
196
252
  end: parsedEnd || void 0,
197
253
  order: pagination.order.type === "desc" ? "desc" : "asc",
@@ -224,15 +280,15 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
224
280
  const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
225
281
  let rawResults;
226
282
  if (isMutual) {
227
- const q1 = this.db.selectFrom("tx").selectAll().where("sender", "=", sender).where("receiver", "=", receiver);
228
- const q2 = this.db.selectFrom("tx").selectAll().where("sender", "=", receiver).where("receiver", "=", sender);
283
+ const q1 = selectTx().where("sender", "=", sender).where("receiver", "=", receiver);
284
+ const q2 = selectTx().where("sender", "=", receiver).where("receiver", "=", sender);
229
285
  rawResults = await q1.unionAll(q2).orderBy(pagination.order.field, orderDir).limit(pagination.size).offset(pagination.cursor).execute();
230
286
  } else if (isUnionOnly) {
231
287
  const topN = pagination.cursor + pagination.size;
232
288
  const dirRaw = sql.raw(orderDir === "desc" ? "DESC" : "ASC");
233
289
  const colRef = sql.ref(pagination.order.field);
234
290
  rawResults = (await sql`
235
- SELECT * FROM (
291
+ SELECT ${colsSql} FROM (
236
292
  SELECT * FROM (SELECT * FROM tx WHERE sender = ${sender} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
237
293
  UNION
238
294
  SELECT * FROM (SELECT * FROM tx WHERE receiver = ${receiver} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
@@ -246,14 +302,14 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
246
302
  let unionQuery = sql`SELECT * FROM (SELECT * FROM tx WHERE type = ${types[0]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
247
303
  for (let i = 1; i < types.length; i++) unionQuery = sql`${unionQuery} UNION ALL SELECT * FROM (SELECT * FROM tx WHERE type = ${types[i]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
248
304
  rawResults = (await sql`
249
- SELECT * FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
305
+ SELECT ${colsSql} FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
250
306
  LIMIT ${pagination.size} OFFSET ${pagination.cursor}
251
307
  `.execute(this.db)).rows;
252
308
  } else if (!hasNonJsonFilters && activeJsonFilters.length === 1 && pagination.order.field === "time") {
253
309
  const [refType, values] = activeJsonFilters[0];
254
310
  const hashes = (await this.db.selectFrom("tx_ref").select("hash").where("type", "=", refType).where("value", "in", values).orderBy("time", orderDir).limit(pagination.size).offset(pagination.cursor).execute()).map((r) => r.hash);
255
311
  if (hashes.length > 0) {
256
- const dataRows = await this.db.selectFrom("tx").selectAll().where("hash", "in", hashes).execute();
312
+ const dataRows = await selectTx().where("hash", "in", hashes).execute();
257
313
  const hashOrder = new Map(hashes.map((h, i) => [h, i]));
258
314
  rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
259
315
  } else rawResults = [];
@@ -264,40 +320,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
264
320
  qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
265
321
  rawResults = await qb.execute();
266
322
  }
267
- let transactions = rawResults.map((row) => {
268
- const tx = { ...row };
269
- [
270
- "receipts",
271
- "tx",
272
- "accounts",
273
- "assets",
274
- "tokens",
275
- "tokenSymbols",
276
- "factories",
277
- "rollups",
278
- "stakes",
279
- "delegations",
280
- "tokenFactories",
281
- "evidences",
282
- "data"
283
- ].forEach((field) => {
284
- if (typeof tx[field] === "string") try {
285
- tx[field] = JSON.parse(tx[field]);
286
- } catch {}
287
- });
288
- return tx;
289
- });
290
- if (!includeItxData) transactions = transactions.map((tx) => {
291
- const row = tx;
292
- if (row.tx && row.tx?.itxJson) return {
293
- ...tx,
294
- tx: {
295
- ...row.tx,
296
- itxJson: omit(row.tx.itxJson, ["data"])
297
- }
298
- };
299
- return tx;
300
- });
323
+ const transactions = formatTxRows(rawResults, !!includeItxData);
301
324
  return {
302
325
  transactions,
303
326
  paging: buildPagingResult(total, pagination, transactions.length)
@@ -978,4 +1001,4 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
978
1001
  var base_default = SqliteBaseIndexDB;
979
1002
 
980
1003
  //#endregion
981
- export { base_default as default };
1004
+ export { TX_TABLE_COLUMNS, base_default as default, resolveTxColumns };
@@ -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
@@ -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) */
@@ -19,9 +21,11 @@ interface TxRefDrivenInput {
19
21
  order: 'asc' | 'desc';
20
22
  limit: number;
21
23
  offset: number;
24
+ /** page query: select only these `tx` columns (validated by the caller); absent = `tx.*` */
25
+ columns?: readonly string[];
22
26
  }
23
27
  interface TxRefDrivenQuery {
24
- /** `select tx.* ...` ordered, offset/limit applied */
28
+ /** `select tx.* ...` (or the `columns` projection) ordered, offset/limit applied */
25
29
  page: RawBuilder<Record<string, unknown>>;
26
30
  /** `select count(*) as count ...` */
27
31
  count: RawBuilder<{
@@ -22,10 +22,23 @@ import { sql } from "kysely";
22
22
  * subquery over tx_ref only (index-only, no `tx` lookups), ordered by `(time, hash)`; `tx` rows are looked up
23
23
  * lazily, only until offset+limit rows pass the remaining filters.
24
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.
25
37
  */
26
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). */
27
40
  function txConditions(input) {
28
- const { sender, receiver, gasPayer, direction, types = [], txs = [], validity } = input;
41
+ const { sender, receiver, gasPayer, direction, types = [], txs = [], validity, txType } = input;
29
42
  const conds = [];
30
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}))`);
31
44
  else if (direction === "ONE_WAY") conds.push(sql`tx.sender = ${sender}`, sql`tx.receiver = ${receiver}`);
@@ -33,7 +46,7 @@ function txConditions(input) {
33
46
  else if (sender) conds.push(sql`tx.sender = ${sender}`);
34
47
  else if (receiver) conds.push(sql`tx.receiver = ${receiver}`);
35
48
  if (gasPayer) conds.push(sql`tx.gasPayer = ${gasPayer}`);
36
- if (types.length) conds.push(sql`tx.type in (${sql.join(types)})`);
49
+ if (types.length && !txType) conds.push(sql`tx.type in (${sql.join(types)})`);
37
50
  if (txs.length) conds.push(sql`tx.hash in (${sql.join(txs)})`);
38
51
  if (validity === "VALID") conds.push(sql`tx.valid = 1`);
39
52
  else if (validity === "INVALID") conds.push(sql`tx.valid = 0`);
@@ -52,38 +65,63 @@ function pickDriver(refFilters) {
52
65
  return single >= 0 ? single : 0;
53
66
  }
54
67
  function buildTxRefDrivenQuery(input) {
55
- const { refFilters, start, end, order, limit, offset } = input;
68
+ const { refFilters, start, end, order, limit, offset, types = [], txType, columns } = input;
56
69
  if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
57
70
  const driverIndex = pickDriver(refFilters);
58
71
  const [driverType, driverValues] = refFilters[driverIndex];
59
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;
60
76
  let from;
61
77
  let countFrom;
62
- const where = [];
78
+ const driverWhere = [];
79
+ const pageTypeWhere = [];
80
+ const countTypeWhere = [];
63
81
  if (driverValues.length === 1) {
64
82
  from = sql`tx_ref r cross join tx`;
65
- countFrom = from;
66
- where.push(sql`r.type = ${driverType}`, sql`r.value = ${driverValues[0]}`, ...timeConditions("r", start, end));
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
+ }
67
89
  } else {
68
- const inner = and([
90
+ const innerOf = (typeCond) => and([
69
91
  sql`type = ${driverType}`,
70
92
  sql`value in (${sql.join(driverValues)})`,
93
+ ...typeCond,
71
94
  ...timeConditions("tx_ref", start, end)
72
95
  ]);
73
- from = sql`(${sql`select distinct hash, time from tx_ref where ${inner} order by time ${dir}, hash limit -1`}) r cross join tx`;
74
- countFrom = sql`(select distinct hash, time from tx_ref where ${inner}) r cross join tx`;
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`;
75
101
  }
76
- where.push(sql`tx.hash = r.hash`);
77
- where.push(...txConditions(input));
102
+ const joinWhere = [sql`tx.hash = r.hash`, ...txConds];
103
+ const existsWhere = [];
78
104
  refFilters.forEach(([refType, values], i) => {
79
105
  if (i === driverIndex) return;
80
- where.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)}))`);
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)}))`);
81
107
  });
82
- const whereSql = and(where);
83
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``;
84
122
  return {
85
- page: sql`select tx.* from ${from} where ${whereSql} ${orderBy} limit ${limit} offset ${offset}`,
86
- count: sql`select count(*) as count from ${countFrom} where ${whereSql}`
123
+ page: sql`select ${columns?.length ? sql.join(columns.map((c) => sql.ref(`tx.${c}`))) : sql`tx.*`} from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
124
+ count: sql`select count(*) as count from ${countFrom} ${countWhere}`
87
125
  };
88
126
  }
89
127
 
@@ -0,0 +1,11 @@
1
+ //#region src/db/tx-rows.d.ts
2
+ type Row = Record<string, unknown>;
3
+ /** JSON-encoded columns of the `tx` table, parsed when they hold a string (kept as-is if not valid JSON). */
4
+ declare const TX_JSON_COLUMNS: readonly ["receipts", "tx", "accounts", "assets", "tokens", "tokenSymbols", "factories", "rollups", "stakes", "delegations", "tokenFactories", "evidences", "data"];
5
+ /**
6
+ * Parse the JSON columns of `rows` and, unless `includeItxData`, drop `tx.itxJson.data`.
7
+ * Returns a new array; row objects are reused when that is unobservable (see header).
8
+ */
9
+ declare function formatTxRows<T = Row>(rows: readonly Row[], includeItxData: boolean): T[];
10
+ //#endregion
11
+ export { TX_JSON_COLUMNS, formatTxRows };
@@ -0,0 +1,71 @@
1
+ import omit from "lodash/omit.js";
2
+
3
+ //#region src/db/tx-rows.ts
4
+ /**
5
+ * Post-processing of raw `tx` rows for `listTransactions` (#1872 phase 2).
6
+ *
7
+ * Output is identical to the original
8
+ * rows.map((row) => { const tx = { ...row }; <JSON.parse each JSON column>; return tx; })
9
+ * .map((tx) => tx.tx && tx.tx.itxJson ? { ...tx, tx: { ...tx.tx, itxJson: omit(tx.tx.itxJson, ['data']) } } : tx)
10
+ * but without the three per-row object copies and the lodash `omit` copy: a row object returned by the driver
11
+ * (better-sqlite3, bun:sqlite, Durable Object `cursor.toArray()`) is a fresh plain object owned by this call,
12
+ * and the parsed `tx` / `itxJson` objects are created here, so mutating them in place is unobservable.
13
+ *
14
+ * Exactness guards (fall back to the copying code):
15
+ * - a row whose prototype is not `Object.prototype` is copied first (the spread produced a plain object);
16
+ * - an `itxJson` that is not a plain object (string, number, array, ...) goes through `omit` as before
17
+ * (`omit` turns e.g. an array or a string into an index-keyed object; `delete` would not).
18
+ */
19
+ /** JSON-encoded columns of the `tx` table, parsed when they hold a string (kept as-is if not valid JSON). */
20
+ const TX_JSON_COLUMNS = [
21
+ "receipts",
22
+ "tx",
23
+ "accounts",
24
+ "assets",
25
+ "tokens",
26
+ "tokenSymbols",
27
+ "factories",
28
+ "rollups",
29
+ "stakes",
30
+ "delegations",
31
+ "tokenFactories",
32
+ "evidences",
33
+ "data"
34
+ ];
35
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
36
+ /**
37
+ * Parse the JSON columns of `rows` and, unless `includeItxData`, drop `tx.itxJson.data`.
38
+ * Returns a new array; row objects are reused when that is unobservable (see header).
39
+ */
40
+ function formatTxRows(rows, includeItxData) {
41
+ const out = new Array(rows.length);
42
+ for (let i = 0; i < rows.length; i++) {
43
+ const tx = Object.getPrototypeOf(rows[i]) === Object.prototype ? rows[i] : { ...rows[i] };
44
+ for (const field of TX_JSON_COLUMNS) {
45
+ const value = tx[field];
46
+ if (typeof value === "string") try {
47
+ tx[field] = JSON.parse(value);
48
+ } catch {}
49
+ }
50
+ if (!includeItxData) {
51
+ const inner = tx.tx;
52
+ const itxJson = inner?.itxJson;
53
+ if (inner && itxJson) if (isPlainObject(inner) && isPlainObject(itxJson)) delete itxJson.data;
54
+ else {
55
+ out[i] = {
56
+ ...tx,
57
+ tx: {
58
+ ...inner,
59
+ itxJson: omit(itxJson, ["data"])
60
+ }
61
+ };
62
+ continue;
63
+ }
64
+ }
65
+ out[i] = tx;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ //#endregion
71
+ export { TX_JSON_COLUMNS, formatTxRows };
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 };