@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/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}`);
|
|
@@ -39,6 +85,7 @@ function buildPagingResult(total, pagination, itemCount) {
|
|
|
39
85
|
var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
40
86
|
constructor(..._args) {
|
|
41
87
|
super(..._args);
|
|
88
|
+
this.txRefTxTypeReady = false;
|
|
42
89
|
this.txCountCache = null;
|
|
43
90
|
}
|
|
44
91
|
/**
|
|
@@ -87,7 +134,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
87
134
|
* List transactions with filtering and pagination
|
|
88
135
|
*/
|
|
89
136
|
async listTransactions(params = {}) {
|
|
90
|
-
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;
|
|
91
138
|
const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
|
|
92
139
|
const { types = [] } = typeFilter;
|
|
93
140
|
const { factories = [] } = factoryFilter;
|
|
@@ -127,7 +174,13 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
127
174
|
delegations,
|
|
128
175
|
includeItxData
|
|
129
176
|
});
|
|
130
|
-
|
|
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();
|
|
131
184
|
const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
|
|
132
185
|
const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
|
|
133
186
|
if (sender && receiver) if (direction === "MUTUAL") {
|
|
@@ -196,6 +249,8 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
196
249
|
types,
|
|
197
250
|
txs,
|
|
198
251
|
validity,
|
|
252
|
+
txType: this.txRefTxTypeReady,
|
|
253
|
+
columns: selected ?? void 0,
|
|
199
254
|
start: parsedStart || void 0,
|
|
200
255
|
end: parsedEnd || void 0,
|
|
201
256
|
order: pagination.order.type === "desc" ? "desc" : "asc",
|
|
@@ -228,15 +283,15 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
228
283
|
const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
|
|
229
284
|
let rawResults;
|
|
230
285
|
if (isMutual) {
|
|
231
|
-
const q1 =
|
|
232
|
-
const q2 =
|
|
286
|
+
const q1 = selectTx().where("sender", "=", sender).where("receiver", "=", receiver);
|
|
287
|
+
const q2 = selectTx().where("sender", "=", receiver).where("receiver", "=", sender);
|
|
233
288
|
rawResults = await q1.unionAll(q2).orderBy(pagination.order.field, orderDir).limit(pagination.size).offset(pagination.cursor).execute();
|
|
234
289
|
} else if (isUnionOnly) {
|
|
235
290
|
const topN = pagination.cursor + pagination.size;
|
|
236
291
|
const dirRaw = kysely.sql.raw(orderDir === "desc" ? "DESC" : "ASC");
|
|
237
292
|
const colRef = kysely.sql.ref(pagination.order.field);
|
|
238
293
|
rawResults = (await kysely.sql`
|
|
239
|
-
SELECT
|
|
294
|
+
SELECT ${colsSql} FROM (
|
|
240
295
|
SELECT * FROM (SELECT * FROM tx WHERE sender = ${sender} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
|
|
241
296
|
UNION
|
|
242
297
|
SELECT * FROM (SELECT * FROM tx WHERE receiver = ${receiver} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})
|
|
@@ -250,14 +305,14 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
250
305
|
let unionQuery = kysely.sql`SELECT * FROM (SELECT * FROM tx WHERE type = ${types[0]} ORDER BY ${colRef} ${dirRaw} LIMIT ${topN})`;
|
|
251
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})`;
|
|
252
307
|
rawResults = (await kysely.sql`
|
|
253
|
-
SELECT
|
|
308
|
+
SELECT ${colsSql} FROM (${unionQuery}) ORDER BY ${colRef} ${dirRaw}
|
|
254
309
|
LIMIT ${pagination.size} OFFSET ${pagination.cursor}
|
|
255
310
|
`.execute(this.db)).rows;
|
|
256
311
|
} else if (!hasNonJsonFilters && activeJsonFilters.length === 1 && pagination.order.field === "time") {
|
|
257
312
|
const [refType, values] = activeJsonFilters[0];
|
|
258
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);
|
|
259
314
|
if (hashes.length > 0) {
|
|
260
|
-
const dataRows = await
|
|
315
|
+
const dataRows = await selectTx().where("hash", "in", hashes).execute();
|
|
261
316
|
const hashOrder = new Map(hashes.map((h, i) => [h, i]));
|
|
262
317
|
rawResults = [...dataRows].sort((a, b) => (hashOrder.get(a.hash) ?? 0) - (hashOrder.get(b.hash) ?? 0));
|
|
263
318
|
} else rawResults = [];
|
|
@@ -268,40 +323,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
268
323
|
qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
|
|
269
324
|
rawResults = await qb.execute();
|
|
270
325
|
}
|
|
271
|
-
|
|
272
|
-
const tx = { ...row };
|
|
273
|
-
[
|
|
274
|
-
"receipts",
|
|
275
|
-
"tx",
|
|
276
|
-
"accounts",
|
|
277
|
-
"assets",
|
|
278
|
-
"tokens",
|
|
279
|
-
"tokenSymbols",
|
|
280
|
-
"factories",
|
|
281
|
-
"rollups",
|
|
282
|
-
"stakes",
|
|
283
|
-
"delegations",
|
|
284
|
-
"tokenFactories",
|
|
285
|
-
"evidences",
|
|
286
|
-
"data"
|
|
287
|
-
].forEach((field) => {
|
|
288
|
-
if (typeof tx[field] === "string") try {
|
|
289
|
-
tx[field] = JSON.parse(tx[field]);
|
|
290
|
-
} catch {}
|
|
291
|
-
});
|
|
292
|
-
return tx;
|
|
293
|
-
});
|
|
294
|
-
if (!includeItxData) transactions = transactions.map((tx) => {
|
|
295
|
-
const row = tx;
|
|
296
|
-
if (row.tx && row.tx?.itxJson) return {
|
|
297
|
-
...tx,
|
|
298
|
-
tx: {
|
|
299
|
-
...row.tx,
|
|
300
|
-
itxJson: (0, lodash_omit.default)(row.tx.itxJson, ["data"])
|
|
301
|
-
}
|
|
302
|
-
};
|
|
303
|
-
return tx;
|
|
304
|
-
});
|
|
326
|
+
const transactions = require_db_tx_rows.formatTxRows(rawResults, !!includeItxData);
|
|
305
327
|
return {
|
|
306
328
|
transactions,
|
|
307
329
|
paging: buildPagingResult(total, pagination, transactions.length)
|
|
@@ -982,4 +1004,6 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
982
1004
|
var base_default = SqliteBaseIndexDB;
|
|
983
1005
|
|
|
984
1006
|
//#endregion
|
|
985
|
-
exports.
|
|
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
|
|
@@ -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/lib/db/index.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_kysely = require('../kysely.cjs');
|
|
|
3
3
|
const require_migrations_index = require('../migrations/index.cjs');
|
|
4
4
|
const require_table_base = require('../table/base.cjs');
|
|
5
5
|
const require_table_account = require('../table/account.cjs');
|
|
6
|
+
const require_tx_ref_tx_type = require('../tx-ref-tx-type.cjs');
|
|
6
7
|
const require_table_transaction = require('../table/transaction.cjs');
|
|
7
8
|
const require_db_base = require('./base.cjs');
|
|
8
9
|
const require_package = require('../package.cjs');
|
|
@@ -533,9 +534,39 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
533
534
|
async initialize() {
|
|
534
535
|
if (this.initialized) return;
|
|
535
536
|
await require_migrations_index.runMigrations(this.db);
|
|
537
|
+
await this.detectTxRefTxType();
|
|
536
538
|
this.initialized = true;
|
|
537
539
|
}
|
|
538
540
|
/**
|
|
541
|
+
* Detect the tx_ref.tx_type state once (#1885). Read-only: startup never adds the column, back-fills or builds
|
|
542
|
+
* the index; that is migrateTxRefTxType, run offline.
|
|
543
|
+
*/
|
|
544
|
+
async detectTxRefTxType() {
|
|
545
|
+
const k = this.db;
|
|
546
|
+
this.tx.setTxRefTxTypeColumn(await require_tx_ref_tx_type.hasTxRefTxTypeColumn(k));
|
|
547
|
+
this.txRefTxTypeReady = await require_tx_ref_tx_type.isTxRefTxTypeReady(k);
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Run the offline tx_ref.tx_type migration on this database (#1870, #1885), then switch this instance's write
|
|
551
|
+
* and query paths to the result. Only for scripts/ops/indexdb-migrate.mjs and tests, with the chain stopped;
|
|
552
|
+
* never part of initialize().
|
|
553
|
+
*
|
|
554
|
+
* This instance must be the only SqliteIndexDB (in any process) with the file open: other instances keep their
|
|
555
|
+
* cached "tx_ref has tx_type" flag (TransactionTable#txRefHasTxType) and their later writes leave tx_type NULL.
|
|
556
|
+
* In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
|
|
557
|
+
*/
|
|
558
|
+
async migrateTxRefTxType(options) {
|
|
559
|
+
const k = this.db;
|
|
560
|
+
const columnAdded = await require_tx_ref_tx_type.addTxRefTxTypeColumn(k);
|
|
561
|
+
this.tx.setTxRefTxTypeColumn(true);
|
|
562
|
+
const result = await require_tx_ref_tx_type.migrateTxRefTxType(k, options);
|
|
563
|
+
await this.detectTxRefTxType();
|
|
564
|
+
return {
|
|
565
|
+
...result,
|
|
566
|
+
columnAdded
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
539
570
|
* Execute multiple operations within a database transaction
|
|
540
571
|
*
|
|
541
572
|
* @param fn - Function receiving Kysely transaction object
|
package/lib/db/index.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Database } from "../interfaces.cjs";
|
|
2
2
|
import SqliteBaseIndexDB from "./base.cjs";
|
|
3
3
|
import { SqliteConfig } from "../kysely.cjs";
|
|
4
|
+
import { TxRefTxTypeBackfillOptions, TxRefTxTypeMigrationResult } from "../tx-ref-tx-type.cjs";
|
|
4
5
|
import { IIndexDB, IIndexTable, IndexTableTypeMap } from "@ocap/types";
|
|
5
6
|
import { Kysely, Transaction } from "kysely";
|
|
6
7
|
|
|
@@ -57,6 +58,21 @@ declare class SqliteIndexDB extends SqliteBaseIndexDB implements IIndexDB {
|
|
|
57
58
|
* Call this after constructor to ensure database schema is ready
|
|
58
59
|
*/
|
|
59
60
|
initialize(): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Detect the tx_ref.tx_type state once (#1885). Read-only: startup never adds the column, back-fills or builds
|
|
63
|
+
* the index; that is migrateTxRefTxType, run offline.
|
|
64
|
+
*/
|
|
65
|
+
private detectTxRefTxType;
|
|
66
|
+
/**
|
|
67
|
+
* Run the offline tx_ref.tx_type migration on this database (#1870, #1885), then switch this instance's write
|
|
68
|
+
* and query paths to the result. Only for scripts/ops/indexdb-migrate.mjs and tests, with the chain stopped;
|
|
69
|
+
* never part of initialize().
|
|
70
|
+
*
|
|
71
|
+
* This instance must be the only SqliteIndexDB (in any process) with the file open: other instances keep their
|
|
72
|
+
* cached "tx_ref has tx_type" flag (TransactionTable#txRefHasTxType) and their later writes leave tx_type NULL.
|
|
73
|
+
* In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
|
|
74
|
+
*/
|
|
75
|
+
migrateTxRefTxType(options?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeMigrationResult>;
|
|
60
76
|
/**
|
|
61
77
|
* Execute multiple operations within a database transaction
|
|
62
78
|
*
|
package/lib/db/tx-ref-query.cjs
CHANGED
|
@@ -23,10 +23,23 @@ let kysely = require("kysely");
|
|
|
23
23
|
* subquery over tx_ref only (index-only, no `tx` lookups), ordered by `(time, hash)`; `tx` rows are looked up
|
|
24
24
|
* lazily, only until offset+limit rows pass the remaining filters.
|
|
25
25
|
* - Additional JSON filters are `exists (select 1 from tx_ref x where x.hash = r.hash ...)` probes on idx_tx_ref_pk.
|
|
26
|
+
*
|
|
27
|
+
* tx_type (#1870, `txType: true` once the offline migrateTxRefTxType (#1885) has back-filled tx_ref.tx_type and built
|
|
28
|
+
* idx_tx_ref_type_value_txtype_time):
|
|
29
|
+
* - The type filter moves from `tx.type in (...)` to `r.tx_type in (...)` (into the deduping subquery for a
|
|
30
|
+
* multi-value driver), so rows of other types are dropped before `tx` is probed.
|
|
31
|
+
* - In the page query it is written `+r.tx_type`: the unary plus keeps the planner on the time index
|
|
32
|
+
* (no sort; the page stops after offset+limit rows) instead of seeking the new index per type and sorting.
|
|
33
|
+
* - If the type filter (plus time / other tx_ref filters) is all there is, the count does not join `tx` at all:
|
|
34
|
+
* `SEARCH r USING COVERING INDEX idx_tx_ref_type_value_txtype_time (type=? AND value=? AND tx_type=?)`.
|
|
35
|
+
* Same result as the join: a non-NULL tx_type is only ever written from an existing tx row (and tx rows are
|
|
36
|
+
* never deleted without their tx_ref rows), and a NULL one cannot match `in (...)`. Counts without a type
|
|
37
|
+
* filter keep the join, so orphan tx_ref rows (if any) are still excluded there.
|
|
26
38
|
*/
|
|
27
39
|
const and = (parts) => kysely.sql.join(parts, kysely.sql` and `);
|
|
40
|
+
/** Conditions that need the `tx` row (the type filter is not one of them when tx_type is ready). */
|
|
28
41
|
function txConditions(input) {
|
|
29
|
-
const { sender, receiver, gasPayer, direction, types = [], txs = [], validity } = input;
|
|
42
|
+
const { sender, receiver, gasPayer, direction, types = [], txs = [], validity, txType } = input;
|
|
30
43
|
const conds = [];
|
|
31
44
|
if (sender && receiver) if (direction === "MUTUAL") conds.push(kysely.sql`((tx.sender = ${sender} and tx.receiver = ${receiver}) or (tx.sender = ${receiver} and tx.receiver = ${sender}))`);
|
|
32
45
|
else if (direction === "ONE_WAY") conds.push(kysely.sql`tx.sender = ${sender}`, kysely.sql`tx.receiver = ${receiver}`);
|
|
@@ -34,7 +47,7 @@ function txConditions(input) {
|
|
|
34
47
|
else if (sender) conds.push(kysely.sql`tx.sender = ${sender}`);
|
|
35
48
|
else if (receiver) conds.push(kysely.sql`tx.receiver = ${receiver}`);
|
|
36
49
|
if (gasPayer) conds.push(kysely.sql`tx.gasPayer = ${gasPayer}`);
|
|
37
|
-
if (types.length) conds.push(kysely.sql`tx.type in (${kysely.sql.join(types)})`);
|
|
50
|
+
if (types.length && !txType) conds.push(kysely.sql`tx.type in (${kysely.sql.join(types)})`);
|
|
38
51
|
if (txs.length) conds.push(kysely.sql`tx.hash in (${kysely.sql.join(txs)})`);
|
|
39
52
|
if (validity === "VALID") conds.push(kysely.sql`tx.valid = 1`);
|
|
40
53
|
else if (validity === "INVALID") conds.push(kysely.sql`tx.valid = 0`);
|
|
@@ -53,38 +66,63 @@ function pickDriver(refFilters) {
|
|
|
53
66
|
return single >= 0 ? single : 0;
|
|
54
67
|
}
|
|
55
68
|
function buildTxRefDrivenQuery(input) {
|
|
56
|
-
const { refFilters, start, end, order, limit, offset } = input;
|
|
69
|
+
const { refFilters, start, end, order, limit, offset, types = [], txType, columns } = input;
|
|
57
70
|
if (!refFilters.length) throw new Error("buildTxRefDrivenQuery requires at least one tx_ref filter");
|
|
58
71
|
const driverIndex = pickDriver(refFilters);
|
|
59
72
|
const [driverType, driverValues] = refFilters[driverIndex];
|
|
60
73
|
const dir = kysely.sql.raw(order === "desc" ? "desc" : "asc");
|
|
74
|
+
const typeOnRef = !!txType && types.length > 0;
|
|
75
|
+
const txConds = txConditions(input);
|
|
76
|
+
const countWithoutTx = typeOnRef && txConds.length === 0;
|
|
61
77
|
let from;
|
|
62
78
|
let countFrom;
|
|
63
|
-
const
|
|
79
|
+
const driverWhere = [];
|
|
80
|
+
const pageTypeWhere = [];
|
|
81
|
+
const countTypeWhere = [];
|
|
64
82
|
if (driverValues.length === 1) {
|
|
65
83
|
from = kysely.sql`tx_ref r cross join tx`;
|
|
66
|
-
countFrom = from;
|
|
67
|
-
|
|
84
|
+
countFrom = countWithoutTx ? kysely.sql`tx_ref r` : from;
|
|
85
|
+
driverWhere.push(kysely.sql`r.type = ${driverType}`, kysely.sql`r.value = ${driverValues[0]}`, ...timeConditions("r", start, end));
|
|
86
|
+
if (typeOnRef) {
|
|
87
|
+
pageTypeWhere.push(kysely.sql`+r.tx_type in (${kysely.sql.join(types)})`);
|
|
88
|
+
countTypeWhere.push(kysely.sql`r.tx_type in (${kysely.sql.join(types)})`);
|
|
89
|
+
}
|
|
68
90
|
} else {
|
|
69
|
-
const
|
|
91
|
+
const innerOf = (typeCond) => and([
|
|
70
92
|
kysely.sql`type = ${driverType}`,
|
|
71
93
|
kysely.sql`value in (${kysely.sql.join(driverValues)})`,
|
|
94
|
+
...typeCond,
|
|
72
95
|
...timeConditions("tx_ref", start, end)
|
|
73
96
|
]);
|
|
74
|
-
|
|
75
|
-
|
|
97
|
+
const pageInner = innerOf(typeOnRef ? [kysely.sql`+tx_type in (${kysely.sql.join(types)})`] : []);
|
|
98
|
+
const countInner = innerOf(typeOnRef ? [kysely.sql`tx_type in (${kysely.sql.join(types)})`] : []);
|
|
99
|
+
from = kysely.sql`(${kysely.sql`select distinct hash, time from tx_ref where ${pageInner} order by time ${dir}, hash limit -1`}) r cross join tx`;
|
|
100
|
+
const countSub = kysely.sql`(select distinct hash, time from tx_ref where ${countInner}) r`;
|
|
101
|
+
countFrom = countWithoutTx ? countSub : kysely.sql`${countSub} cross join tx`;
|
|
76
102
|
}
|
|
77
|
-
|
|
78
|
-
|
|
103
|
+
const joinWhere = [kysely.sql`tx.hash = r.hash`, ...txConds];
|
|
104
|
+
const existsWhere = [];
|
|
79
105
|
refFilters.forEach(([refType, values], i) => {
|
|
80
106
|
if (i === driverIndex) return;
|
|
81
|
-
|
|
107
|
+
existsWhere.push(kysely.sql`exists (select 1 from tx_ref x where x.hash = r.hash and x.type = ${refType} and x.value in (${kysely.sql.join(values)}))`);
|
|
82
108
|
});
|
|
83
|
-
const whereSql = and(where);
|
|
84
109
|
const orderBy = driverValues.length === 1 ? kysely.sql`order by r.time ${dir}` : kysely.sql``;
|
|
110
|
+
const pageWhere = and([
|
|
111
|
+
...driverWhere,
|
|
112
|
+
...pageTypeWhere,
|
|
113
|
+
...joinWhere,
|
|
114
|
+
...existsWhere
|
|
115
|
+
]);
|
|
116
|
+
const countParts = [
|
|
117
|
+
...driverWhere,
|
|
118
|
+
...countTypeWhere,
|
|
119
|
+
...countWithoutTx ? [] : joinWhere,
|
|
120
|
+
...existsWhere
|
|
121
|
+
];
|
|
122
|
+
const countWhere = countParts.length ? kysely.sql`where ${and(countParts)}` : kysely.sql``;
|
|
85
123
|
return {
|
|
86
|
-
page: kysely.sql`select tx
|
|
87
|
-
count: kysely.sql`select count(*) as count from ${countFrom}
|
|
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
|
+
count: kysely.sql`select count(*) as count from ${countFrom} ${countWhere}`
|
|
88
126
|
};
|
|
89
127
|
}
|
|
90
128
|
|
|
@@ -12,6 +12,8 @@ interface TxRefDrivenInput {
|
|
|
12
12
|
types?: string[];
|
|
13
13
|
txs?: string[];
|
|
14
14
|
validity?: string;
|
|
15
|
+
/** tx_ref.tx_type is back-filled and indexed (offline migrateTxRefTxType); false/absent = the 1.31.7 SQL */
|
|
16
|
+
txType?: boolean;
|
|
15
17
|
/** exclusive lower bound on time (ISO string) */
|
|
16
18
|
start?: string;
|
|
17
19
|
/** inclusive upper bound on time (ISO string) */
|
|
@@ -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<{
|
|
@@ -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/index.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_kysely = require('./kysely.cjs');
|
|
3
|
+
const require_tx_ref_tx_type = require('./tx-ref-tx-type.cjs');
|
|
3
4
|
const require_db_base = require('./db/base.cjs');
|
|
4
5
|
const require_db_index = require('./db/index.cjs');
|
|
5
6
|
|
|
@@ -9,5 +10,15 @@ var src_default = require_db_index.default;
|
|
|
9
10
|
//#endregion
|
|
10
11
|
exports.DurableObjectSqliteDialect = require_kysely.DurableObjectSqliteDialect;
|
|
11
12
|
exports.SqliteBaseIndexDB = require_db_base.default;
|
|
13
|
+
exports.TX_REF_TX_TYPE_INDEX = require_tx_ref_tx_type.TX_REF_TX_TYPE_INDEX;
|
|
14
|
+
exports.TX_REF_TX_TYPE_PROGRESS_TABLE = require_tx_ref_tx_type.TX_REF_TX_TYPE_PROGRESS_TABLE;
|
|
15
|
+
exports.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = require_tx_ref_tx_type.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE;
|
|
16
|
+
exports.addTxRefTxTypeColumn = require_tx_ref_tx_type.addTxRefTxTypeColumn;
|
|
17
|
+
exports.backfillTxRefTxType = require_tx_ref_tx_type.backfillTxRefTxType;
|
|
12
18
|
exports.default = src_default;
|
|
13
|
-
exports.
|
|
19
|
+
exports.dropTxRefTxType = require_tx_ref_tx_type.dropTxRefTxType;
|
|
20
|
+
exports.getRawDatabase = require_kysely.getRawDatabase;
|
|
21
|
+
exports.hasTxRefTxTypeColumn = require_tx_ref_tx_type.hasTxRefTxTypeColumn;
|
|
22
|
+
exports.isTxRefTxTypeReady = require_tx_ref_tx_type.isTxRefTxTypeReady;
|
|
23
|
+
exports.migrateTxRefTxType = require_tx_ref_tx_type.migrateTxRefTxType;
|
|
24
|
+
exports.sweepTxRefTxTypeNulls = require_tx_ref_tx_type.sweepTxRefTxTypeNulls;
|
package/lib/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import SqliteBaseIndexDB from "./db/base.cjs";
|
|
2
2
|
import { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, getRawDatabase } from "./kysely.cjs";
|
|
3
|
+
import { TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, TxRefTxTypeBackfillOptions, TxRefTxTypeBackfillStats, TxRefTxTypeBatch, TxRefTxTypeMigrationResult, TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, dropTxRefTxType, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls } from "./tx-ref-tx-type.cjs";
|
|
3
4
|
import SqliteIndexDB from "./db/index.cjs";
|
|
4
|
-
export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, SqliteIndexDB as default, getRawDatabase };
|
|
5
|
+
export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, type TxRefTxTypeBackfillOptions, type TxRefTxTypeBackfillStats, type TxRefTxTypeBatch, type TxRefTxTypeMigrationResult, type TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, SqliteIndexDB as default, dropTxRefTxType, getRawDatabase, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };
|
package/lib/interfaces.d.cts
CHANGED
|
@@ -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).
|