@ocap/indexdb-sqlite 1.31.8 → 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 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
@@ -49,7 +60,7 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
49
60
  /**
50
61
  * List transactions with filtering and pagination
51
62
  */
52
- listTransactions(params?: Partial<TRequestListTransactions>): Promise<IListTransactionsResult>;
63
+ listTransactions(params?: Partial<TRequestListTransactions> & IListTransactionsColumns): Promise<IListTransactionsResult>;
53
64
  /**
54
65
  * Get related addresses for account migration tracking
55
66
  */
@@ -102,4 +113,4 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
102
113
  search(keyword: string): Promise<TSearchResult[]>;
103
114
  }
104
115
  //#endregion
105
- 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}`);
@@ -84,7 +131,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
84
131
  * List transactions with filtering and pagination
85
132
  */
86
133
  async listTransactions(params = {}) {
87
- 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;
88
135
  const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
89
136
  const { types = [] } = typeFilter;
90
137
  const { factories = [] } = factoryFilter;
@@ -124,7 +171,13 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
124
171
  delegations,
125
172
  includeItxData
126
173
  });
127
- 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();
128
181
  const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
129
182
  const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
130
183
  if (sender && receiver) if (direction === "MUTUAL") {
@@ -194,6 +247,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
194
247
  txs,
195
248
  validity,
196
249
  txType: this.txRefTxTypeReady,
250
+ columns: selected ?? void 0,
197
251
  start: parsedStart || void 0,
198
252
  end: parsedEnd || void 0,
199
253
  order: pagination.order.type === "desc" ? "desc" : "asc",
@@ -226,15 +280,15 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
226
280
  const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
227
281
  let rawResults;
228
282
  if (isMutual) {
229
- const q1 = this.db.selectFrom("tx").selectAll().where("sender", "=", sender).where("receiver", "=", receiver);
230
- 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);
231
285
  rawResults = await q1.unionAll(q2).orderBy(pagination.order.field, orderDir).limit(pagination.size).offset(pagination.cursor).execute();
232
286
  } else if (isUnionOnly) {
233
287
  const topN = pagination.cursor + pagination.size;
234
288
  const dirRaw = sql.raw(orderDir === "desc" ? "DESC" : "ASC");
235
289
  const colRef = sql.ref(pagination.order.field);
236
290
  rawResults = (await sql`
237
- SELECT * FROM (
291
+ SELECT ${colsSql} FROM (
238
292
  SELECT * FROM (SELECT * FROM tx WHERE sender = ${sender} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
239
293
  UNION
240
294
  SELECT * FROM (SELECT * FROM tx WHERE receiver = ${receiver} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
@@ -248,14 +302,14 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
248
302
  let unionQuery = sql`SELECT * FROM (SELECT * FROM tx WHERE type = ${types[0]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
249
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})`;
250
304
  rawResults = (await sql`
251
- SELECT * FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
305
+ SELECT ${colsSql} FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
252
306
  LIMIT ${pagination.size} OFFSET ${pagination.cursor}
253
307
  `.execute(this.db)).rows;
254
308
  } else if (!hasNonJsonFilters && activeJsonFilters.length === 1 && pagination.order.field === "time") {
255
309
  const [refType, values] = activeJsonFilters[0];
256
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);
257
311
  if (hashes.length > 0) {
258
- const dataRows = await this.db.selectFrom("tx").selectAll().where("hash", "in", hashes).execute();
312
+ const dataRows = await selectTx().where("hash", "in", hashes).execute();
259
313
  const hashOrder = new Map(hashes.map((h, i) => [h, i]));
260
314
  rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
261
315
  } else rawResults = [];
@@ -266,40 +320,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
266
320
  qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
267
321
  rawResults = await qb.execute();
268
322
  }
269
- let transactions = rawResults.map((row) => {
270
- const tx = { ...row };
271
- [
272
- "receipts",
273
- "tx",
274
- "accounts",
275
- "assets",
276
- "tokens",
277
- "tokenSymbols",
278
- "factories",
279
- "rollups",
280
- "stakes",
281
- "delegations",
282
- "tokenFactories",
283
- "evidences",
284
- "data"
285
- ].forEach((field) => {
286
- if (typeof tx[field] === "string") try {
287
- tx[field] = JSON.parse(tx[field]);
288
- } catch {}
289
- });
290
- return tx;
291
- });
292
- if (!includeItxData) transactions = transactions.map((tx) => {
293
- const row = tx;
294
- if (row.tx && row.tx?.itxJson) return {
295
- ...tx,
296
- tx: {
297
- ...row.tx,
298
- itxJson: omit(row.tx.itxJson, ["data"])
299
- }
300
- };
301
- return tx;
302
- });
323
+ const transactions = formatTxRows(rawResults, !!includeItxData);
303
324
  return {
304
325
  transactions,
305
326
  paging: buildPagingResult(total, pagination, transactions.length)
@@ -980,4 +1001,4 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
980
1001
  var base_default = SqliteBaseIndexDB;
981
1002
 
982
1003
  //#endregion
983
- export { base_default as default };
1004
+ export { TX_TABLE_COLUMNS, base_default as default, resolveTxColumns };
@@ -21,9 +21,11 @@ interface TxRefDrivenInput {
21
21
  order: 'asc' | 'desc';
22
22
  limit: number;
23
23
  offset: number;
24
+ /** page query: select only these `tx` columns (validated by the caller); absent = `tx.*` */
25
+ columns?: readonly string[];
24
26
  }
25
27
  interface TxRefDrivenQuery {
26
- /** `select tx.* ...` ordered, offset/limit applied */
28
+ /** `select tx.* ...` (or the `columns` projection) ordered, offset/limit applied */
27
29
  page: RawBuilder<Record<string, unknown>>;
28
30
  /** `select count(*) as count ...` */
29
31
  count: RawBuilder<{
@@ -65,7 +65,7 @@ function pickDriver(refFilters) {
65
65
  return single >= 0 ? single : 0;
66
66
  }
67
67
  function buildTxRefDrivenQuery(input) {
68
- const { refFilters, start, end, order, limit, offset, types = [], txType } = input;
68
+ const { refFilters, start, end, order, limit, offset, types = [], txType, columns } = input;
69
69
  if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
70
70
  const driverIndex = pickDriver(refFilters);
71
71
  const [driverType, driverValues] = refFilters[driverIndex];
@@ -120,7 +120,7 @@ function buildTxRefDrivenQuery(input) {
120
120
  ];
121
121
  const countWhere = countParts.length ? sql`where ${and(countParts)}` : sql``;
122
122
  return {
123
- page: sql`select tx.* from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
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
124
  count: sql`select count(*) as count from ${countFrom} ${countWhere}`
125
125
  };
126
126
  }
@@ -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/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;
@@ -1576,9 +1580,15 @@ function createKysely(config) {
1576
1580
  sqlite.exec("PRAGMA foreign_keys = ON");
1577
1581
  sqlite.exec("PRAGMA busy_timeout = 5000");
1578
1582
  sqlite.exec(`PRAGMA mmap_size = ${resolveMmapSize(config)}`);
1579
- return new Kysely({ dialect: new BunSqliteDialect({ database: sqlite }) });
1580
- }
1581
- return new Kysely({ dialect: new SqliteDialect({ database: openBetterSqlite3(__require("better-sqlite3"), filename, 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
+ }) });
1582
1592
  }
1583
1593
  /**
1584
1594
  * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
package/lib/db/base.cjs CHANGED
@@ -1,19 +1,65 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_db_tx_ref_query = require('./tx-ref-query.cjs');
4
+ const require_db_tx_rows = require('./tx-rows.cjs');
4
5
  let kysely = require("kysely");
5
6
  let _ocap_indexdb = require("@ocap/indexdb");
6
7
  let _arcblock_did_lib_type = require("@arcblock/did/lib/type");
7
8
  let _ocap_util_lib_constant = require("@ocap/util/lib/constant");
8
9
  let debug = require("debug");
9
10
  debug = require_rolldown_runtime.__toESM(debug);
10
- let lodash_omit = require("lodash/omit");
11
- lodash_omit = require_rolldown_runtime.__toESM(lodash_omit);
12
11
 
13
12
  //#region src/db/base.ts
14
13
  const debug$1 = (0, debug.default)("@ocap/indexdb-sqlite");
15
14
  const MAX_REQUEST_FACTORY_ADDRESS_SIZE = 100;
16
15
  const SEARCH_LIMIT_PER_TABLE = 5;
16
+ /** Every column of the `tx` table (any order: older databases have `gasPayer` / `evidences` appended). */
17
+ const TX_TABLE_COLUMNS = [
18
+ "hash",
19
+ "code",
20
+ "height",
21
+ "index_",
22
+ "receipts",
23
+ "receiptsVerified",
24
+ "receiver",
25
+ "sender",
26
+ "gasPayer",
27
+ "time",
28
+ "tx",
29
+ "type",
30
+ "finalized",
31
+ "valid",
32
+ "accounts",
33
+ "assets",
34
+ "tokens",
35
+ "tokenSymbols",
36
+ "factories",
37
+ "rollups",
38
+ "stakes",
39
+ "delegations",
40
+ "tokenFactories",
41
+ "genesisTime",
42
+ "renaissanceTime",
43
+ "data",
44
+ "evidences"
45
+ ];
46
+ const TX_TABLE_COLUMN_SET = new Set(TX_TABLE_COLUMNS);
47
+ /** Validated projection, or `null` for `select *`. Unknown column names are a programming error. */
48
+ function resolveTxColumns(columns, orderField) {
49
+ if (columns === void 0 || columns === null) return null;
50
+ if (!Array.isArray(columns)) throw new Error("listTransactions: columns must be an array of tx column names");
51
+ if (columns.length === 0) return null;
52
+ const out = [];
53
+ for (const c of [
54
+ "hash",
55
+ ...columns,
56
+ orderField
57
+ ]) {
58
+ if (typeof c !== "string" || !TX_TABLE_COLUMN_SET.has(c)) throw new Error(`listTransactions: unknown tx column ${JSON.stringify(c)}`);
59
+ if (!out.includes(c)) out.push(c);
60
+ }
61
+ return out;
62
+ }
17
63
  /** Escape SQL LIKE special characters */
18
64
  function escapeLikePattern(s) {
19
65
  return s.replace(/[%_\\]/g, (c) => `\\${c}`);
@@ -88,7 +134,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
88
134
  * List transactions with filtering and pagination
89
135
  */
90
136
  async listTransactions(params = {}) {
91
- const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
137
+ const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false, columns } = params;
92
138
  const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
93
139
  const { types = [] } = typeFilter;
94
140
  const { factories = [] } = factoryFilter;
@@ -128,7 +174,13 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
128
174
  delegations,
129
175
  includeItxData
130
176
  });
131
- let qb = this.db.selectFrom("tx").selectAll();
177
+ const selected = resolveTxColumns(columns, pagination.order.field);
178
+ const selectTx = () => {
179
+ const q = this.db.selectFrom("tx").selectAll();
180
+ return selected ? q.clearSelect().select(selected) : q;
181
+ };
182
+ const colsSql = selected ? kysely.sql.join(selected.map((c) => kysely.sql.ref(c))) : kysely.sql`*`;
183
+ let qb = selectTx();
132
184
  const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
133
185
  const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
134
186
  if (sender && receiver) if (direction === "MUTUAL") {
@@ -198,6 +250,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
198
250
  txs,
199
251
  validity,
200
252
  txType: this.txRefTxTypeReady,
253
+ columns: selected ?? void 0,
201
254
  start: parsedStart || void 0,
202
255
  end: parsedEnd || void 0,
203
256
  order: pagination.order.type === "desc" ? "desc" : "asc",
@@ -230,15 +283,15 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
230
283
  const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
231
284
  let rawResults;
232
285
  if (isMutual) {
233
- const q1 = this.db.selectFrom("tx").selectAll().where("sender", "=", sender).where("receiver", "=", receiver);
234
- const q2 = this.db.selectFrom("tx").selectAll().where("sender", "=", receiver).where("receiver", "=", sender);
286
+ const q1 = selectTx().where("sender", "=", sender).where("receiver", "=", receiver);
287
+ const q2 = selectTx().where("sender", "=", receiver).where("receiver", "=", sender);
235
288
  rawResults = await q1.unionAll(q2).orderBy(pagination.order.field, orderDir).limit(pagination.size).offset(pagination.cursor).execute();
236
289
  } else if (isUnionOnly) {
237
290
  const topN = pagination.cursor + pagination.size;
238
291
  const dirRaw = kysely.sql.raw(orderDir === "desc" ? "DESC" : "ASC");
239
292
  const colRef = kysely.sql.ref(pagination.order.field);
240
293
  rawResults = (await kysely.sql`
241
- SELECT * FROM (
294
+ SELECT ${colsSql} FROM (
242
295
  SELECT * FROM (SELECT * FROM tx WHERE sender = ${sender} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
243
296
  UNION
244
297
  SELECT * FROM (SELECT * FROM tx WHERE receiver = ${receiver} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
@@ -252,14 +305,14 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
252
305
  let unionQuery = kysely.sql`SELECT * FROM (SELECT * FROM tx WHERE type = ${types[0]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
253
306
  for (let i = 1; i < types.length; i++) unionQuery = kysely.sql`${unionQuery} UNION ALL SELECT * FROM (SELECT * FROM tx WHERE type = ${types[i]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
254
307
  rawResults = (await kysely.sql`
255
- SELECT * FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
308
+ SELECT ${colsSql} FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
256
309
  LIMIT ${pagination.size} OFFSET ${pagination.cursor}
257
310
  `.execute(this.db)).rows;
258
311
  } else if (!hasNonJsonFilters && activeJsonFilters.length === 1 && pagination.order.field === "time") {
259
312
  const [refType, values] = activeJsonFilters[0];
260
313
  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);
261
314
  if (hashes.length > 0) {
262
- const dataRows = await this.db.selectFrom("tx").selectAll().where("hash", "in", hashes).execute();
315
+ const dataRows = await selectTx().where("hash", "in", hashes).execute();
263
316
  const hashOrder = new Map(hashes.map((h, i) => [h, i]));
264
317
  rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
265
318
  } else rawResults = [];
@@ -270,40 +323,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
270
323
  qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
271
324
  rawResults = await qb.execute();
272
325
  }
273
- let transactions = rawResults.map((row) => {
274
- const tx = { ...row };
275
- [
276
- "receipts",
277
- "tx",
278
- "accounts",
279
- "assets",
280
- "tokens",
281
- "tokenSymbols",
282
- "factories",
283
- "rollups",
284
- "stakes",
285
- "delegations",
286
- "tokenFactories",
287
- "evidences",
288
- "data"
289
- ].forEach((field) => {
290
- if (typeof tx[field] === "string") try {
291
- tx[field] = JSON.parse(tx[field]);
292
- } catch {}
293
- });
294
- return tx;
295
- });
296
- if (!includeItxData) transactions = transactions.map((tx) => {
297
- const row = tx;
298
- if (row.tx && row.tx?.itxJson) return {
299
- ...tx,
300
- tx: {
301
- ...row.tx,
302
- itxJson: (0, lodash_omit.default)(row.tx.itxJson, ["data"])
303
- }
304
- };
305
- return tx;
306
- });
326
+ const transactions = require_db_tx_rows.formatTxRows(rawResults, !!includeItxData);
307
327
  return {
308
328
  transactions,
309
329
  paging: buildPagingResult(total, pagination, transactions.length)
@@ -984,4 +1004,6 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
984
1004
  var base_default = SqliteBaseIndexDB;
985
1005
 
986
1006
  //#endregion
987
- exports.default = base_default;
1007
+ exports.TX_TABLE_COLUMNS = TX_TABLE_COLUMNS;
1008
+ exports.default = base_default;
1009
+ exports.resolveTxColumns = resolveTxColumns;
package/lib/db/base.d.cts CHANGED
@@ -4,7 +4,18 @@ import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDel
4
4
  import { Kysely } from "kysely";
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
@@ -49,7 +60,7 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
49
60
  /**
50
61
  * List transactions with filtering and pagination
51
62
  */
52
- listTransactions(params?: Partial<TRequestListTransactions>): Promise<IListTransactionsResult>;
63
+ listTransactions(params?: Partial<TRequestListTransactions> & IListTransactionsColumns): Promise<IListTransactionsResult>;
53
64
  /**
54
65
  * Get related addresses for account migration tracking
55
66
  */
@@ -102,4 +113,4 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
102
113
  search(keyword: string): Promise<TSearchResult[]>;
103
114
  }
104
115
  //#endregion
105
- export { SqliteBaseIndexDB as default };
116
+ export { IListTransactionsColumns, TX_TABLE_COLUMNS, SqliteBaseIndexDB as default, resolveTxColumns };
@@ -66,7 +66,7 @@ function pickDriver(refFilters) {
66
66
  return single >= 0 ? single : 0;
67
67
  }
68
68
  function buildTxRefDrivenQuery(input) {
69
- const { refFilters, start, end, order, limit, offset, types = [], txType } = input;
69
+ const { refFilters, start, end, order, limit, offset, types = [], txType, columns } = input;
70
70
  if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
71
71
  const driverIndex = pickDriver(refFilters);
72
72
  const [driverType, driverValues] = refFilters[driverIndex];
@@ -121,7 +121,7 @@ function buildTxRefDrivenQuery(input) {
121
121
  ];
122
122
  const countWhere = countParts.length ? kysely.sql`where ${and(countParts)}` : kysely.sql``;
123
123
  return {
124
- page: kysely.sql`select tx.* from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
124
+ page: kysely.sql`select ${columns?.length ? kysely.sql.join(columns.map((c) => kysely.sql.ref(`tx.${c}`))) : kysely.sql`tx.*`} from ${from} where ${pageWhere} ${orderBy} limit ${limit} offset ${offset}`,
125
125
  count: kysely.sql`select count(*) as count from ${countFrom} ${countWhere}`
126
126
  };
127
127
  }
@@ -21,9 +21,11 @@ interface TxRefDrivenInput {
21
21
  order: 'asc' | 'desc';
22
22
  limit: number;
23
23
  offset: number;
24
+ /** page query: select only these `tx` columns (validated by the caller); absent = `tx.*` */
25
+ columns?: readonly string[];
24
26
  }
25
27
  interface TxRefDrivenQuery {
26
- /** `select tx.* ...` ordered, offset/limit applied */
28
+ /** `select tx.* ...` (or the `columns` projection) ordered, offset/limit applied */
27
29
  page: RawBuilder<Record<string, unknown>>;
28
30
  /** `select count(*) as count ...` */
29
31
  count: RawBuilder<{
@@ -0,0 +1,74 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ let lodash_omit = require("lodash/omit");
3
+ lodash_omit = require_rolldown_runtime.__toESM(lodash_omit);
4
+
5
+ //#region src/db/tx-rows.ts
6
+ /**
7
+ * Post-processing of raw `tx` rows for `listTransactions` (#1872 phase 2).
8
+ *
9
+ * Output is identical to the original
10
+ * rows.map((row) => { const tx = { ...row }; <JSON.parse each JSON column>; return tx; })
11
+ * .map((tx) => tx.tx && tx.tx.itxJson ? { ...tx, tx: { ...tx.tx, itxJson: omit(tx.tx.itxJson, ['data']) } } : tx)
12
+ * but without the three per-row object copies and the lodash `omit` copy: a row object returned by the driver
13
+ * (better-sqlite3, bun:sqlite, Durable Object `cursor.toArray()`) is a fresh plain object owned by this call,
14
+ * and the parsed `tx` / `itxJson` objects are created here, so mutating them in place is unobservable.
15
+ *
16
+ * Exactness guards (fall back to the copying code):
17
+ * - a row whose prototype is not `Object.prototype` is copied first (the spread produced a plain object);
18
+ * - an `itxJson` that is not a plain object (string, number, array, ...) goes through `omit` as before
19
+ * (`omit` turns e.g. an array or a string into an index-keyed object; `delete` would not).
20
+ */
21
+ /** JSON-encoded columns of the `tx` table, parsed when they hold a string (kept as-is if not valid JSON). */
22
+ const TX_JSON_COLUMNS = [
23
+ "receipts",
24
+ "tx",
25
+ "accounts",
26
+ "assets",
27
+ "tokens",
28
+ "tokenSymbols",
29
+ "factories",
30
+ "rollups",
31
+ "stakes",
32
+ "delegations",
33
+ "tokenFactories",
34
+ "evidences",
35
+ "data"
36
+ ];
37
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
38
+ /**
39
+ * Parse the JSON columns of `rows` and, unless `includeItxData`, drop `tx.itxJson.data`.
40
+ * Returns a new array; row objects are reused when that is unobservable (see header).
41
+ */
42
+ function formatTxRows(rows, includeItxData) {
43
+ const out = new Array(rows.length);
44
+ for (let i = 0; i < rows.length; i++) {
45
+ const tx = Object.getPrototypeOf(rows[i]) === Object.prototype ? rows[i] : { ...rows[i] };
46
+ for (const field of TX_JSON_COLUMNS) {
47
+ const value = tx[field];
48
+ if (typeof value === "string") try {
49
+ tx[field] = JSON.parse(value);
50
+ } catch {}
51
+ }
52
+ if (!includeItxData) {
53
+ const inner = tx.tx;
54
+ const itxJson = inner?.itxJson;
55
+ if (inner && itxJson) if (isPlainObject(inner) && isPlainObject(itxJson)) delete itxJson.data;
56
+ else {
57
+ out[i] = {
58
+ ...tx,
59
+ tx: {
60
+ ...inner,
61
+ itxJson: (0, lodash_omit.default)(itxJson, ["data"])
62
+ }
63
+ };
64
+ continue;
65
+ }
66
+ }
67
+ out[i] = tx;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ //#endregion
73
+ exports.TX_JSON_COLUMNS = TX_JSON_COLUMNS;
74
+ exports.formatTxRows = formatTxRows;
@@ -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 };
package/lib/kysely.cjs CHANGED
@@ -1,7 +1,11 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util_lib_sql_timing = require("@ocap/util/lib/sql-timing");
2
3
  let kysely = require("kysely");
3
4
 
4
5
  //#region src/kysely.ts
6
+ const timeConnection = async (connection) => {
7
+ (0, _ocap_util_lib_sql_timing.instrumentSqlTiming)(connection);
8
+ };
5
9
  var ConnectionMutex = class {
6
10
  async lock() {
7
11
  while (this.promise) await this.promise;
@@ -1576,9 +1580,15 @@ function createKysely(config) {
1576
1580
  sqlite.exec("PRAGMA foreign_keys = ON");
1577
1581
  sqlite.exec("PRAGMA busy_timeout = 5000");
1578
1582
  sqlite.exec(`PRAGMA mmap_size = ${resolveMmapSize(config)}`);
1579
- return new kysely.Kysely({ dialect: new BunSqliteDialect({ database: sqlite }) });
1580
- }
1581
- return new kysely.Kysely({ dialect: new kysely.SqliteDialect({ database: openBetterSqlite3(require("better-sqlite3"), filename, config) }) });
1583
+ return new kysely.Kysely({ dialect: new BunSqliteDialect({
1584
+ database: sqlite,
1585
+ onCreateConnection: timeConnection
1586
+ }) });
1587
+ }
1588
+ return new kysely.Kysely({ dialect: new kysely.SqliteDialect({
1589
+ database: openBetterSqlite3(require("better-sqlite3"), filename, config),
1590
+ onCreateConnection: timeConnection
1591
+ }) });
1582
1592
  }
1583
1593
  /**
1584
1594
  * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ocap/indexdb-sqlite",
3
3
  "description": "OCAP indexdb adapter that uses SQLite as backend",
4
- "version": "1.31.8",
4
+ "version": "1.31.9",
5
5
  "author": "wangshijun <shijun@arcblock.io> (https://www.arcblock.io)",
6
6
  "bugs": {
7
7
  "url": "https://github.com/ArcBlock/blockchain/issues",
@@ -14,7 +14,7 @@
14
14
  "wangshijun <shijun@arcblock.io> (https://www.arcblock.io)"
15
15
  ],
16
16
  "devDependencies": {
17
- "@ocap/indexdb-test": "1.31.8"
17
+ "@ocap/indexdb-test": "1.31.9"
18
18
  },
19
19
  "homepage": "https://github.com/ArcBlock/blockchain/tree/master/indexdb/sqlite",
20
20
  "keywords": [
@@ -63,10 +63,10 @@
63
63
  "clean": "rm -rf lib esm"
64
64
  },
65
65
  "dependencies": {
66
- "@arcblock/did": "1.31.8",
67
- "@ocap/indexdb": "1.31.8",
68
- "@ocap/types": "1.31.8",
69
- "@ocap/util": "1.31.8",
66
+ "@arcblock/did": "1.31.9",
67
+ "@ocap/indexdb": "1.31.9",
68
+ "@ocap/types": "1.31.9",
69
+ "@ocap/util": "1.31.9",
70
70
  "debug": "^4.4.3",
71
71
  "better-sqlite3": "^11.8.1",
72
72
  "kysely": "^0.28.14",