@ocap/indexdb-sqlite 1.31.0 → 1.31.2
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 +18 -0
- package/esm/db/base.mjs +69 -11
- package/esm/db/index.mjs +4 -0
- package/esm/interfaces.d.mts +2 -0
- package/esm/migrations/001-genesis.mjs +2 -1
- package/esm/migrations/003-delegation-extensions.mjs +9 -2
- package/esm/migrations/005-rollup-missing-columns.mjs +5 -1
- package/esm/migrations/009-tx-gas-payer.d.mts +17 -0
- package/esm/migrations/009-tx-gas-payer.mjs +28 -0
- package/esm/migrations/010-tx-evidences.d.mts +16 -0
- package/esm/migrations/010-tx-evidences.mjs +26 -0
- package/esm/migrations/index.mjs +23 -7
- package/esm/table/base.d.mts +5 -0
- package/esm/table/base.mjs +25 -9
- package/esm/table/transaction.mjs +2 -1
- package/lib/db/base.cjs +69 -11
- package/lib/db/base.d.cts +18 -0
- package/lib/db/index.cjs +4 -0
- package/lib/interfaces.d.cts +2 -0
- package/lib/migrations/001-genesis.cjs +2 -1
- package/lib/migrations/003-delegation-extensions.cjs +9 -2
- package/lib/migrations/005-rollup-missing-columns.cjs +5 -1
- package/lib/migrations/009-tx-gas-payer.cjs +35 -0
- package/lib/migrations/009-tx-gas-payer.d.cts +17 -0
- package/lib/migrations/010-tx-evidences.cjs +33 -0
- package/lib/migrations/010-tx-evidences.d.cts +16 -0
- package/lib/migrations/index.cjs +23 -7
- package/lib/table/base.cjs +25 -9
- package/lib/table/base.d.cts +5 -0
- package/lib/table/transaction.cjs +2 -1
- package/package.json +6 -6
package/esm/db/base.d.mts
CHANGED
|
@@ -23,6 +23,24 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
|
|
|
23
23
|
rollupValidator: IIndexTable<IndexTableTypeMap['rollupValidator']>;
|
|
24
24
|
tokenDistribution: IIndexTable<IndexTableTypeMap['tokenDistribution']>;
|
|
25
25
|
tokenFactory: IIndexTable<IndexTableTypeMap['tokenFactory']>;
|
|
26
|
+
protected txCountCache: {
|
|
27
|
+
total: number;
|
|
28
|
+
invalid: number;
|
|
29
|
+
totalChanges: number;
|
|
30
|
+
dataVersion: number;
|
|
31
|
+
maxRowId: number;
|
|
32
|
+
} | null;
|
|
33
|
+
/**
|
|
34
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
35
|
+
*
|
|
36
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
37
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
38
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
39
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
40
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
41
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
42
|
+
*/
|
|
43
|
+
private getExactTxCounts;
|
|
26
44
|
/**
|
|
27
45
|
* List transactions with filtering and pagination
|
|
28
46
|
*/
|
package/esm/db/base.mjs
CHANGED
|
@@ -32,18 +32,65 @@ function buildPagingResult(total, pagination, itemCount) {
|
|
|
32
32
|
* Contains all the list methods with SQL-based filtering
|
|
33
33
|
*/
|
|
34
34
|
var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
35
|
+
constructor(..._args) {
|
|
36
|
+
super(..._args);
|
|
37
|
+
this.txCountCache = null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
41
|
+
*
|
|
42
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
43
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
44
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
45
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
46
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
47
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
48
|
+
*/
|
|
49
|
+
async getExactTxCounts() {
|
|
50
|
+
const probeRow = (await sql`
|
|
51
|
+
SELECT
|
|
52
|
+
total_changes() as tc,
|
|
53
|
+
(SELECT data_version FROM pragma_data_version) as dv,
|
|
54
|
+
COALESCE((SELECT max(rowid) FROM tx), 0) as maxRowId
|
|
55
|
+
`.execute(this.db)).rows[0];
|
|
56
|
+
const tc = Number(probeRow?.tc ?? -1);
|
|
57
|
+
const dv = Number(probeRow?.dv ?? -1);
|
|
58
|
+
const maxRowId = Number(probeRow?.maxRowId ?? 0);
|
|
59
|
+
const cached = this.txCountCache;
|
|
60
|
+
if (cached && tc >= 0 && dv >= 0 && cached.totalChanges === tc && cached.dataVersion === dv && cached.maxRowId === maxRowId) return {
|
|
61
|
+
total: cached.total,
|
|
62
|
+
valid: Math.max(0, cached.total - cached.invalid),
|
|
63
|
+
invalid: cached.invalid
|
|
64
|
+
};
|
|
65
|
+
const [allCount, invalidCount] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
|
|
66
|
+
const total = Number(allCount?.count ?? 0);
|
|
67
|
+
const invalid = Number(invalidCount?.count ?? 0);
|
|
68
|
+
this.txCountCache = {
|
|
69
|
+
total,
|
|
70
|
+
invalid,
|
|
71
|
+
totalChanges: tc,
|
|
72
|
+
dataVersion: dv,
|
|
73
|
+
maxRowId
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
total,
|
|
77
|
+
valid: Math.max(0, total - invalid),
|
|
78
|
+
invalid
|
|
79
|
+
};
|
|
80
|
+
}
|
|
35
81
|
/**
|
|
36
82
|
* List transactions with filtering and pagination
|
|
37
83
|
*/
|
|
38
84
|
async listTransactions(params = {}) {
|
|
39
85
|
const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
|
|
40
|
-
const { sender, receiver, direction = "UNION" } = addressFilter;
|
|
86
|
+
const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
|
|
41
87
|
const { types = [] } = typeFilter;
|
|
42
88
|
const { factories = [] } = factoryFilter;
|
|
43
89
|
const { assets = [] } = assetFilter;
|
|
44
90
|
const { tokens = [] } = tokenFilter;
|
|
45
91
|
const { accounts = [] } = accountFilter;
|
|
46
|
-
const { txs = [] } = txFilter;
|
|
92
|
+
const { txs = [], gasPayer: txGasPayer, evidences = [] } = txFilter;
|
|
93
|
+
const gasPayer = addressGasPayer || txGasPayer || "";
|
|
47
94
|
const { rollups = [] } = rollupFilter;
|
|
48
95
|
const { stakes = [] } = stakeFilter;
|
|
49
96
|
const { delegations = [] } = delegationFilter;
|
|
@@ -56,12 +103,14 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
56
103
|
"renaissanceTime",
|
|
57
104
|
"time",
|
|
58
105
|
"sender",
|
|
59
|
-
"receiver"
|
|
106
|
+
"receiver",
|
|
107
|
+
"gasPayer"
|
|
60
108
|
]
|
|
61
109
|
});
|
|
62
110
|
debug("listTransactions", {
|
|
63
111
|
sender,
|
|
64
112
|
receiver,
|
|
113
|
+
gasPayer,
|
|
65
114
|
pagination,
|
|
66
115
|
types,
|
|
67
116
|
factories,
|
|
@@ -74,12 +123,15 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
74
123
|
includeItxData
|
|
75
124
|
});
|
|
76
125
|
let qb = this.db.selectFrom("tx").selectAll();
|
|
77
|
-
const isMutual = !!(sender && receiver && direction === "MUTUAL");
|
|
126
|
+
const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
|
|
78
127
|
const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
|
|
79
|
-
if (sender && receiver) if (direction === "MUTUAL") {
|
|
128
|
+
if (sender && receiver) if (direction === "MUTUAL") {
|
|
129
|
+
if (!isMutual) qb = qb.where((eb) => eb.or([eb.and([eb("sender", "=", sender), eb("receiver", "=", receiver)]), eb.and([eb("sender", "=", receiver), eb("receiver", "=", sender)])]));
|
|
130
|
+
} else if (direction === "ONE_WAY") qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
|
|
80
131
|
else qb = qb.where((eb) => eb.or([eb("sender", "=", sender), eb("receiver", "=", receiver)]));
|
|
81
132
|
else if (sender) qb = qb.where("sender", "=", sender);
|
|
82
133
|
else if (receiver) qb = qb.where("receiver", "=", receiver);
|
|
134
|
+
if (gasPayer) qb = qb.where("gasPayer", "=", gasPayer);
|
|
83
135
|
if (types.length) qb = qb.where("type", "in", types);
|
|
84
136
|
if (txs.length) qb = qb.where("hash", "in", txs);
|
|
85
137
|
const { startDateTime, endDateTime } = timeFilter;
|
|
@@ -99,7 +151,8 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
99
151
|
rollups: "rollup",
|
|
100
152
|
stakes: "stake",
|
|
101
153
|
delegations: "delegation",
|
|
102
|
-
tokenFactories: "tokenFactory"
|
|
154
|
+
tokenFactories: "tokenFactory",
|
|
155
|
+
evidences: "evidence"
|
|
103
156
|
};
|
|
104
157
|
const applyJsonArrayFilter = (column, values) => {
|
|
105
158
|
const refType = txRefTypeMap[column];
|
|
@@ -113,6 +166,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
113
166
|
if (stakes.length) applyJsonArrayFilter("stakes", stakes);
|
|
114
167
|
if (delegations.length) applyJsonArrayFilter("delegations", delegations);
|
|
115
168
|
if (tokenFactories.length) applyJsonArrayFilter("tokenFactories", tokenFactories);
|
|
169
|
+
if (evidences.length) applyJsonArrayFilter("evidences", evidences);
|
|
116
170
|
let total;
|
|
117
171
|
const activeJsonFilters = [];
|
|
118
172
|
if (factories.length) activeJsonFilters.push(["factory", factories]);
|
|
@@ -123,9 +177,10 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
123
177
|
if (stakes.length) activeJsonFilters.push(["stake", stakes]);
|
|
124
178
|
if (delegations.length) activeJsonFilters.push(["delegation", delegations]);
|
|
125
179
|
if (tokenFactories.length) activeJsonFilters.push(["tokenFactory", tokenFactories]);
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
const
|
|
180
|
+
if (evidences.length) activeJsonFilters.push(["evidence", evidences]);
|
|
181
|
+
const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
182
|
+
const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
183
|
+
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
129
184
|
if (isMutual) {
|
|
130
185
|
const [c1, c2] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).where("receiver", "=", receiver).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", receiver).where("receiver", "=", sender).executeTakeFirst()]);
|
|
131
186
|
total = (c1?.count ?? 0) + (c2?.count ?? 0);
|
|
@@ -140,8 +195,10 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
140
195
|
]);
|
|
141
196
|
total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
|
|
142
197
|
} else if (isMultiTypeOnly) total = (await Promise.all(types.map((t) => this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("type", "=", t).executeTakeFirst()))).reduce((sum, c) => sum + (c?.count ?? 0), 0);
|
|
143
|
-
else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0)
|
|
144
|
-
|
|
198
|
+
else if ((validity === "VALID" || validity === "INVALID") && !sender && !receiver && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
|
|
199
|
+
const counts = await this.getExactTxCounts();
|
|
200
|
+
total = validity === "VALID" ? counts.valid : counts.invalid;
|
|
201
|
+
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.getExactTxCounts()).total;
|
|
145
202
|
else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
|
|
146
203
|
const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
|
|
147
204
|
let rawResults;
|
|
@@ -197,6 +254,7 @@ var SqliteBaseIndexDB = class extends BaseIndexDB {
|
|
|
197
254
|
"stakes",
|
|
198
255
|
"delegations",
|
|
199
256
|
"tokenFactories",
|
|
257
|
+
"evidences",
|
|
200
258
|
"data"
|
|
201
259
|
].forEach((field) => {
|
|
202
260
|
if (typeof tx[field] === "string") try {
|
package/esm/db/index.mjs
CHANGED
|
@@ -60,6 +60,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
60
60
|
"stakes",
|
|
61
61
|
"delegations",
|
|
62
62
|
"tokenFactories",
|
|
63
|
+
"evidences",
|
|
63
64
|
"data"
|
|
64
65
|
],
|
|
65
66
|
booleanFields: [
|
|
@@ -77,6 +78,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
77
78
|
"receiptsVerified",
|
|
78
79
|
"receiver",
|
|
79
80
|
"sender",
|
|
81
|
+
"gasPayer",
|
|
80
82
|
"time",
|
|
81
83
|
"tx",
|
|
82
84
|
"type",
|
|
@@ -91,6 +93,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
91
93
|
"stakes",
|
|
92
94
|
"delegations",
|
|
93
95
|
"tokenFactories",
|
|
96
|
+
"evidences",
|
|
94
97
|
"genesisTime",
|
|
95
98
|
"renaissanceTime",
|
|
96
99
|
"data"
|
|
@@ -544,6 +547,7 @@ var SqliteIndexDB = class extends base_default$1 {
|
|
|
544
547
|
* Reset all tables (for testing)
|
|
545
548
|
*/
|
|
546
549
|
async reset() {
|
|
550
|
+
this.txCountCache = null;
|
|
547
551
|
for (const table of [
|
|
548
552
|
"tx",
|
|
549
553
|
"account",
|
package/esm/interfaces.d.mts
CHANGED
|
@@ -35,6 +35,7 @@ interface TxTable {
|
|
|
35
35
|
receiptsVerified: number | null;
|
|
36
36
|
receiver: string | null;
|
|
37
37
|
sender: string | null;
|
|
38
|
+
gasPayer: string | null;
|
|
38
39
|
time: string | null;
|
|
39
40
|
tx: string | null;
|
|
40
41
|
type: string | null;
|
|
@@ -49,6 +50,7 @@ interface TxTable {
|
|
|
49
50
|
stakes: string | null;
|
|
50
51
|
delegations: string | null;
|
|
51
52
|
tokenFactories: string | null;
|
|
53
|
+
evidences: string | null;
|
|
52
54
|
genesisTime: string | null;
|
|
53
55
|
renaissanceTime: string | null;
|
|
54
56
|
data: string | null;
|
|
@@ -10,9 +10,10 @@ var _001_genesis_exports = /* @__PURE__ */ __exportAll({
|
|
|
10
10
|
* Genesis migration - creates all IndexDB tables
|
|
11
11
|
*/
|
|
12
12
|
async function up(db) {
|
|
13
|
-
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
13
|
+
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("gasPayer", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
14
14
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_sender ON tx(sender)`.execute(db);
|
|
15
15
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_receiver ON tx(receiver)`.execute(db);
|
|
16
|
+
await sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
16
17
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_type ON tx(type)`.execute(db);
|
|
17
18
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_time ON tx(time)`.execute(db);
|
|
18
19
|
await sql`CREATE INDEX IF NOT EXISTS idx_tx_height ON tx(height)`.execute(db);
|
|
@@ -6,9 +6,16 @@ var _003_delegation_extensions_exports = /* @__PURE__ */ __exportAll({
|
|
|
6
6
|
down: () => down,
|
|
7
7
|
up: () => up
|
|
8
8
|
});
|
|
9
|
+
async function addColumnIfNotExists(db, ddl) {
|
|
10
|
+
try {
|
|
11
|
+
await ddl.execute(db);
|
|
12
|
+
} catch (err) {
|
|
13
|
+
if (!(err instanceof Error ? err.message : String(err ?? "")).toLowerCase().includes("duplicate column name")) throw err;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
9
16
|
async function up(db) {
|
|
10
|
-
await sql`ALTER TABLE delegation ADD COLUMN deny TEXT
|
|
11
|
-
await sql`ALTER TABLE delegation ADD COLUMN validUntil INTEGER DEFAULT 0
|
|
17
|
+
await addColumnIfNotExists(db, sql`ALTER TABLE delegation ADD COLUMN deny TEXT`);
|
|
18
|
+
await addColumnIfNotExists(db, sql`ALTER TABLE delegation ADD COLUMN validUntil INTEGER DEFAULT 0`);
|
|
12
19
|
}
|
|
13
20
|
async function down(_db) {}
|
|
14
21
|
|
|
@@ -41,7 +41,11 @@ const MISSING_COLUMNS = [
|
|
|
41
41
|
}
|
|
42
42
|
];
|
|
43
43
|
async function up(db) {
|
|
44
|
-
for (const col of MISSING_COLUMNS)
|
|
44
|
+
for (const col of MISSING_COLUMNS) try {
|
|
45
|
+
await sql.raw(`ALTER TABLE rollup ADD COLUMN ${col.name} ${col.type}`).execute(db);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
if (!(err instanceof Error ? err.message : String(err ?? "")).toLowerCase().includes("duplicate column name")) throw err;
|
|
48
|
+
}
|
|
45
49
|
await sql.raw(`UPDATE rollup SET
|
|
46
50
|
minDepositFee = json_extract(data, '$.minDepositFee'),
|
|
47
51
|
maxDepositFee = json_extract(data, '$.maxDepositFee'),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/009-tx-gas-payer.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
7
|
+
*
|
|
8
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
9
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
10
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
11
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
12
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
13
|
+
*/
|
|
14
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { down, up };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { __exportAll } from "../_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/009-tx-gas-payer.ts
|
|
5
|
+
var _009_tx_gas_payer_exports = /* @__PURE__ */ __exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
11
|
+
*
|
|
12
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
13
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
14
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
15
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
16
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
17
|
+
*/
|
|
18
|
+
async function up(db) {
|
|
19
|
+
const columnsResult = await sql`PRAGMA table_info('tx')`.execute(db);
|
|
20
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("gasPayer")) await sql`ALTER TABLE tx ADD COLUMN gasPayer TEXT`.execute(db);
|
|
21
|
+
await sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
22
|
+
}
|
|
23
|
+
async function down(db) {
|
|
24
|
+
await sql`DROP INDEX IF EXISTS idx_tx_gasPayer`.execute(db);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { _009_tx_gas_payer_exports, down, up };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/010-tx-evidences.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 010 - Add evidences column on tx (#1479)
|
|
7
|
+
*
|
|
8
|
+
* `evidences` is a JSON array of bridge release evidence keys (`<kind>:<evidence>:<ordinal>`), written for
|
|
9
|
+
* `release_bridge_token` txs. Lookups go through the existing tx_ref junction table (type = 'evidence'),
|
|
10
|
+
* which already has the (type, value) index, so no new index is needed. Schema only: no historical rows
|
|
11
|
+
* carry a release tx.
|
|
12
|
+
*/
|
|
13
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
14
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { down, up };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { __exportAll } from "../_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/010-tx-evidences.ts
|
|
5
|
+
var _010_tx_evidences_exports = /* @__PURE__ */ __exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 010 - Add evidences column on tx (#1479)
|
|
11
|
+
*
|
|
12
|
+
* `evidences` is a JSON array of bridge release evidence keys (`<kind>:<evidence>:<ordinal>`), written for
|
|
13
|
+
* `release_bridge_token` txs. Lookups go through the existing tx_ref junction table (type = 'evidence'),
|
|
14
|
+
* which already has the (type, value) index, so no new index is needed. Schema only: no historical rows
|
|
15
|
+
* carry a release tx.
|
|
16
|
+
*/
|
|
17
|
+
async function up(db) {
|
|
18
|
+
const columnsResult = await sql`PRAGMA table_info('tx')`.execute(db);
|
|
19
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("evidences")) await sql`ALTER TABLE tx ADD COLUMN evidences TEXT`.execute(db);
|
|
20
|
+
}
|
|
21
|
+
async function down(db) {
|
|
22
|
+
await sql`ALTER TABLE tx DROP COLUMN evidences`.execute(db);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
export { _010_tx_evidences_exports, down, up };
|
package/esm/migrations/index.mjs
CHANGED
|
@@ -6,6 +6,8 @@ import { _005_rollup_missing_columns_exports } from "./005-rollup-missing-column
|
|
|
6
6
|
import { _006_rollup_block_height_integer_exports } from "./006-rollup-block-height-integer.mjs";
|
|
7
7
|
import { _007_token_factory_feerate_integer_exports } from "./007-token-factory-feerate-integer.mjs";
|
|
8
8
|
import { _008_index_failure_exports } from "./008-index-failure.mjs";
|
|
9
|
+
import { _009_tx_gas_payer_exports } from "./009-tx-gas-payer.mjs";
|
|
10
|
+
import { _010_tx_evidences_exports } from "./010-tx-evidences.mjs";
|
|
9
11
|
import { Migrator } from "kysely";
|
|
10
12
|
|
|
11
13
|
//#region src/migrations/index.ts
|
|
@@ -23,21 +25,35 @@ var InMemoryMigrationProvider = class {
|
|
|
23
25
|
"005-rollup-missing-columns": _005_rollup_missing_columns_exports,
|
|
24
26
|
"006-rollup-block-height-integer": _006_rollup_block_height_integer_exports,
|
|
25
27
|
"007-token-factory-feerate-integer": _007_token_factory_feerate_integer_exports,
|
|
26
|
-
"008-index-failure": _008_index_failure_exports
|
|
28
|
+
"008-index-failure": _008_index_failure_exports,
|
|
29
|
+
"009-tx-gas-payer": _009_tx_gas_payer_exports,
|
|
30
|
+
"010-tx-evidences": _010_tx_evidences_exports
|
|
27
31
|
};
|
|
28
32
|
}
|
|
29
33
|
};
|
|
34
|
+
function isRetryableMigrationError(error) {
|
|
35
|
+
const code = error?.code;
|
|
36
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" || code === 5 || code === 6) return true;
|
|
37
|
+
const msg = (error instanceof Error ? error.message : String(error ?? "")).toLowerCase();
|
|
38
|
+
return msg.includes("database is locked") || msg.includes("sqlite_busy") || msg.includes("sqlite_locked") || msg.includes("already exists") || msg.includes("duplicate column name") || msg.includes("unique constraint failed: kysely_migration") || msg.includes("kysely_migration_lock");
|
|
39
|
+
}
|
|
30
40
|
/**
|
|
31
41
|
* Run all pending migrations
|
|
32
42
|
* @param db - Kysely instance
|
|
33
43
|
*/
|
|
34
44
|
async function runMigrations(db) {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
for (let attempt = 0;; attempt++) {
|
|
46
|
+
const { error, results } = await new Migrator({
|
|
47
|
+
db,
|
|
48
|
+
provider: new InMemoryMigrationProvider()
|
|
49
|
+
}).migrateToLatest();
|
|
50
|
+
if (!error) {
|
|
51
|
+
for (const result of results ?? []) if (result.status === "Error") throw new Error(`Migration "${result.migrationName}" failed`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (!isRetryableMigrationError(error) || attempt >= 8) throw error;
|
|
55
|
+
await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
|
|
56
|
+
}
|
|
41
57
|
}
|
|
42
58
|
/**
|
|
43
59
|
* Rollback all migrations
|
package/esm/table/base.d.mts
CHANGED
|
@@ -47,6 +47,11 @@ declare class SqliteTable<T = unknown> extends BaseIndex<T> implements IIndexTab
|
|
|
47
47
|
* Handles both simple string keys and composite keys
|
|
48
48
|
*/
|
|
49
49
|
generatePrimaryKey(doc: string | Record<string, unknown>): string;
|
|
50
|
+
/**
|
|
51
|
+
* Check that a primary-key column value is a non-empty string or finite number.
|
|
52
|
+
* Prevents `undefined`/`null`/`''` key fields from silently dropping SQL WHERE clauses (#1438).
|
|
53
|
+
*/
|
|
54
|
+
protected isValidPrimaryKeyValue(v: unknown): boolean;
|
|
50
55
|
/**
|
|
51
56
|
* Map column name for reserved keywords
|
|
52
57
|
*/
|
package/esm/table/base.mjs
CHANGED
|
@@ -27,12 +27,21 @@ var SqliteTable = class extends BaseIndex {
|
|
|
27
27
|
generatePrimaryKey(doc) {
|
|
28
28
|
if (typeof doc === "string") return doc;
|
|
29
29
|
if (Array.isArray(this.uniqIndex)) {
|
|
30
|
-
const key = this.uniqIndex.map((id) => doc[id]).map((item) => typeof item === "object" ? JSON.stringify(item) : item).join("-");
|
|
30
|
+
const key = this.uniqIndex.map((id) => doc[id]).map((item) => typeof item === "object" ? JSON.stringify(item) : String(item ?? "")).map((item) => item.replace(/\\/g, "\\\\").replace(/-/g, "\\-")).join("-");
|
|
31
31
|
return crypto.createHash("md5").update(key).digest("hex");
|
|
32
32
|
}
|
|
33
33
|
return doc[this.uniqIndex];
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
|
+
* Check that a primary-key column value is a non-empty string or finite number.
|
|
37
|
+
* Prevents `undefined`/`null`/`''` key fields from silently dropping SQL WHERE clauses (#1438).
|
|
38
|
+
*/
|
|
39
|
+
isValidPrimaryKeyValue(v) {
|
|
40
|
+
if (typeof v === "string") return v.length > 0;
|
|
41
|
+
if (typeof v === "number") return Number.isFinite(v);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
36
45
|
* Map column name for reserved keywords
|
|
37
46
|
*/
|
|
38
47
|
mapColumnName(name) {
|
|
@@ -189,11 +198,10 @@ var SqliteTable = class extends BaseIndex {
|
|
|
189
198
|
const id = typeof key === "string" ? key : key[this.primaryKey];
|
|
190
199
|
query = { [this.mapColumnName(this.primaryKey)]: id };
|
|
191
200
|
}
|
|
201
|
+
const queryEntries = Object.entries(query);
|
|
202
|
+
if (queryEntries.length === 0 || queryEntries.some(([, v]) => !this.isValidPrimaryKeyValue(v))) return null;
|
|
192
203
|
let qb = this.getExecutor(context).selectFrom(this.name).selectAll();
|
|
193
|
-
for (const [k, v] of
|
|
194
|
-
if (v === void 0) continue;
|
|
195
|
-
qb = qb.where(k, "=", v);
|
|
196
|
-
}
|
|
204
|
+
for (const [k, v] of queryEntries) qb = qb.where(k, "=", v);
|
|
197
205
|
const result = await qb.executeTakeFirst();
|
|
198
206
|
return this.deserializeFromDb(result);
|
|
199
207
|
}
|
|
@@ -210,6 +218,15 @@ var SqliteTable = class extends BaseIndex {
|
|
|
210
218
|
* Internal update implementation - called by BaseIndex.update() via hooks
|
|
211
219
|
*/
|
|
212
220
|
async _update(key, updates, context) {
|
|
221
|
+
if (!key || typeof key === "object" && key === null) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
222
|
+
if (Array.isArray(this.uniqIndex)) {
|
|
223
|
+
if (typeof key !== "object") throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
224
|
+
const keyObj = key;
|
|
225
|
+
for (const k of this.uniqIndex) if (!this.isValidPrimaryKeyValue(keyObj[k])) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
226
|
+
} else if (typeof key === "object") {
|
|
227
|
+
const id = key[this.primaryKey];
|
|
228
|
+
if (!this.isValidPrimaryKeyValue(id)) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
229
|
+
} else if (!this.isValidPrimaryKeyValue(key)) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
213
230
|
const existing = await this._get(key, context);
|
|
214
231
|
if (!existing) throw new Error(`${this.name} does not exist: ${JSON.stringify(key)}`);
|
|
215
232
|
let query;
|
|
@@ -220,16 +237,15 @@ var SqliteTable = class extends BaseIndex {
|
|
|
220
237
|
const id = typeof key === "string" ? key : key[this.primaryKey];
|
|
221
238
|
query = { [this.mapColumnName(this.primaryKey)]: id };
|
|
222
239
|
}
|
|
240
|
+
const queryEntries = Object.entries(query);
|
|
241
|
+
if (queryEntries.length === 0 || queryEntries.some(([, v]) => !this.isValidPrimaryKeyValue(v))) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
223
242
|
const updateAttrs = { ...updates };
|
|
224
243
|
if (Array.isArray(this.uniqIndex)) for (const k of this.uniqIndex) delete updateAttrs[k];
|
|
225
244
|
else delete updateAttrs[this.primaryKey];
|
|
226
245
|
if (Object.keys(updateAttrs).length > 0) {
|
|
227
246
|
const serialized = this.serializeForDbUpdate(updateAttrs, existing);
|
|
228
247
|
let qb = this.getExecutor(context).updateTable(this.name).set(serialized);
|
|
229
|
-
for (const [k, v] of
|
|
230
|
-
if (v === void 0) continue;
|
|
231
|
-
qb = qb.where(k, "=", v);
|
|
232
|
-
}
|
|
248
|
+
for (const [k, v] of queryEntries) qb = qb.where(k, "=", v);
|
|
233
249
|
await qb.execute();
|
|
234
250
|
}
|
|
235
251
|
return {
|
|
@@ -11,7 +11,8 @@ const TX_REF_TYPES = [
|
|
|
11
11
|
["rollup", "rollups"],
|
|
12
12
|
["stake", "stakes"],
|
|
13
13
|
["delegation", "delegations"],
|
|
14
|
-
["tokenFactory", "tokenFactories"]
|
|
14
|
+
["tokenFactory", "tokenFactories"],
|
|
15
|
+
["evidence", "evidences"]
|
|
15
16
|
];
|
|
16
17
|
/**
|
|
17
18
|
* Transaction table for SQLite IndexDB
|
package/lib/db/base.cjs
CHANGED
|
@@ -36,18 +36,65 @@ function buildPagingResult(total, pagination, itemCount) {
|
|
|
36
36
|
* Contains all the list methods with SQL-based filtering
|
|
37
37
|
*/
|
|
38
38
|
var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
39
|
+
constructor(..._args) {
|
|
40
|
+
super(..._args);
|
|
41
|
+
this.txCountCache = null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
45
|
+
*
|
|
46
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
47
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
48
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
49
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
50
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
51
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
52
|
+
*/
|
|
53
|
+
async getExactTxCounts() {
|
|
54
|
+
const probeRow = (await kysely.sql`
|
|
55
|
+
SELECT
|
|
56
|
+
total_changes() as tc,
|
|
57
|
+
(SELECT data_version FROM pragma_data_version) as dv,
|
|
58
|
+
COALESCE((SELECT max(rowid) FROM tx), 0) as maxRowId
|
|
59
|
+
`.execute(this.db)).rows[0];
|
|
60
|
+
const tc = Number(probeRow?.tc ?? -1);
|
|
61
|
+
const dv = Number(probeRow?.dv ?? -1);
|
|
62
|
+
const maxRowId = Number(probeRow?.maxRowId ?? 0);
|
|
63
|
+
const cached = this.txCountCache;
|
|
64
|
+
if (cached && tc >= 0 && dv >= 0 && cached.totalChanges === tc && cached.dataVersion === dv && cached.maxRowId === maxRowId) return {
|
|
65
|
+
total: cached.total,
|
|
66
|
+
valid: Math.max(0, cached.total - cached.invalid),
|
|
67
|
+
invalid: cached.invalid
|
|
68
|
+
};
|
|
69
|
+
const [allCount, invalidCount] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("valid", "=", 0).executeTakeFirst()]);
|
|
70
|
+
const total = Number(allCount?.count ?? 0);
|
|
71
|
+
const invalid = Number(invalidCount?.count ?? 0);
|
|
72
|
+
this.txCountCache = {
|
|
73
|
+
total,
|
|
74
|
+
invalid,
|
|
75
|
+
totalChanges: tc,
|
|
76
|
+
dataVersion: dv,
|
|
77
|
+
maxRowId
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
total,
|
|
81
|
+
valid: Math.max(0, total - invalid),
|
|
82
|
+
invalid
|
|
83
|
+
};
|
|
84
|
+
}
|
|
39
85
|
/**
|
|
40
86
|
* List transactions with filtering and pagination
|
|
41
87
|
*/
|
|
42
88
|
async listTransactions(params = {}) {
|
|
43
89
|
const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
|
|
44
|
-
const { sender, receiver, direction = "UNION" } = addressFilter;
|
|
90
|
+
const { sender, receiver, gasPayer: addressGasPayer, direction = "UNION" } = addressFilter;
|
|
45
91
|
const { types = [] } = typeFilter;
|
|
46
92
|
const { factories = [] } = factoryFilter;
|
|
47
93
|
const { assets = [] } = assetFilter;
|
|
48
94
|
const { tokens = [] } = tokenFilter;
|
|
49
95
|
const { accounts = [] } = accountFilter;
|
|
50
|
-
const { txs = [] } = txFilter;
|
|
96
|
+
const { txs = [], gasPayer: txGasPayer, evidences = [] } = txFilter;
|
|
97
|
+
const gasPayer = addressGasPayer || txGasPayer || "";
|
|
51
98
|
const { rollups = [] } = rollupFilter;
|
|
52
99
|
const { stakes = [] } = stakeFilter;
|
|
53
100
|
const { delegations = [] } = delegationFilter;
|
|
@@ -60,12 +107,14 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
60
107
|
"renaissanceTime",
|
|
61
108
|
"time",
|
|
62
109
|
"sender",
|
|
63
|
-
"receiver"
|
|
110
|
+
"receiver",
|
|
111
|
+
"gasPayer"
|
|
64
112
|
]
|
|
65
113
|
});
|
|
66
114
|
debug$1("listTransactions", {
|
|
67
115
|
sender,
|
|
68
116
|
receiver,
|
|
117
|
+
gasPayer,
|
|
69
118
|
pagination,
|
|
70
119
|
types,
|
|
71
120
|
factories,
|
|
@@ -78,12 +127,15 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
78
127
|
includeItxData
|
|
79
128
|
});
|
|
80
129
|
let qb = this.db.selectFrom("tx").selectAll();
|
|
81
|
-
const isMutual = !!(sender && receiver && direction === "MUTUAL");
|
|
130
|
+
const isMutual = !!(sender && receiver && direction === "MUTUAL" && !gasPayer);
|
|
82
131
|
const isUnion = !!(sender && receiver && direction !== "MUTUAL" && direction !== "ONE_WAY");
|
|
83
|
-
if (sender && receiver) if (direction === "MUTUAL") {
|
|
132
|
+
if (sender && receiver) if (direction === "MUTUAL") {
|
|
133
|
+
if (!isMutual) qb = qb.where((eb) => eb.or([eb.and([eb("sender", "=", sender), eb("receiver", "=", receiver)]), eb.and([eb("sender", "=", receiver), eb("receiver", "=", sender)])]));
|
|
134
|
+
} else if (direction === "ONE_WAY") qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
|
|
84
135
|
else qb = qb.where((eb) => eb.or([eb("sender", "=", sender), eb("receiver", "=", receiver)]));
|
|
85
136
|
else if (sender) qb = qb.where("sender", "=", sender);
|
|
86
137
|
else if (receiver) qb = qb.where("receiver", "=", receiver);
|
|
138
|
+
if (gasPayer) qb = qb.where("gasPayer", "=", gasPayer);
|
|
87
139
|
if (types.length) qb = qb.where("type", "in", types);
|
|
88
140
|
if (txs.length) qb = qb.where("hash", "in", txs);
|
|
89
141
|
const { startDateTime, endDateTime } = timeFilter;
|
|
@@ -103,7 +155,8 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
103
155
|
rollups: "rollup",
|
|
104
156
|
stakes: "stake",
|
|
105
157
|
delegations: "delegation",
|
|
106
|
-
tokenFactories: "tokenFactory"
|
|
158
|
+
tokenFactories: "tokenFactory",
|
|
159
|
+
evidences: "evidence"
|
|
107
160
|
};
|
|
108
161
|
const applyJsonArrayFilter = (column, values) => {
|
|
109
162
|
const refType = txRefTypeMap[column];
|
|
@@ -117,6 +170,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
117
170
|
if (stakes.length) applyJsonArrayFilter("stakes", stakes);
|
|
118
171
|
if (delegations.length) applyJsonArrayFilter("delegations", delegations);
|
|
119
172
|
if (tokenFactories.length) applyJsonArrayFilter("tokenFactories", tokenFactories);
|
|
173
|
+
if (evidences.length) applyJsonArrayFilter("evidences", evidences);
|
|
120
174
|
let total;
|
|
121
175
|
const activeJsonFilters = [];
|
|
122
176
|
if (factories.length) activeJsonFilters.push(["factory", factories]);
|
|
@@ -127,9 +181,10 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
127
181
|
if (stakes.length) activeJsonFilters.push(["stake", stakes]);
|
|
128
182
|
if (delegations.length) activeJsonFilters.push(["delegation", delegations]);
|
|
129
183
|
if (tokenFactories.length) activeJsonFilters.push(["tokenFactory", tokenFactories]);
|
|
130
|
-
|
|
131
|
-
const
|
|
132
|
-
const
|
|
184
|
+
if (evidences.length) activeJsonFilters.push(["evidence", evidences]);
|
|
185
|
+
const hasNonJsonFilters = !!(sender || receiver || gasPayer || types.length || txs.length || parsedStart || parsedEnd || validity);
|
|
186
|
+
const isUnionOnly = isUnion && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
187
|
+
const isMultiTypeOnly = types.length > 1 && !sender && !receiver && !gasPayer && !txs.length && !parsedStart && !parsedEnd && !validity && activeJsonFilters.length === 0;
|
|
133
188
|
if (isMutual) {
|
|
134
189
|
const [c1, c2] = await Promise.all([this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", sender).where("receiver", "=", receiver).executeTakeFirst(), this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("sender", "=", receiver).where("receiver", "=", sender).executeTakeFirst()]);
|
|
135
190
|
total = (c1?.count ?? 0) + (c2?.count ?? 0);
|
|
@@ -144,8 +199,10 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
144
199
|
]);
|
|
145
200
|
total = (senderCount?.count ?? 0) + (receiverCount?.count ?? 0) - (overlapCount?.count ?? 0);
|
|
146
201
|
} else if (isMultiTypeOnly) total = (await Promise.all(types.map((t) => this.db.selectFrom("tx").select(this.db.fn.countAll().as("count")).where("type", "=", t).executeTakeFirst()))).reduce((sum, c) => sum + (c?.count ?? 0), 0);
|
|
147
|
-
else if (validity === "VALID" && !sender && !receiver && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0)
|
|
148
|
-
|
|
202
|
+
else if ((validity === "VALID" || validity === "INVALID") && !sender && !receiver && !gasPayer && !types.length && !txs.length && !parsedStart && !parsedEnd && activeJsonFilters.length === 0) {
|
|
203
|
+
const counts = await this.getExactTxCounts();
|
|
204
|
+
total = validity === "VALID" ? counts.valid : counts.invalid;
|
|
205
|
+
} else if (!hasNonJsonFilters && activeJsonFilters.length === 0) total = (await this.getExactTxCounts()).total;
|
|
149
206
|
else total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
|
|
150
207
|
const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
|
|
151
208
|
let rawResults;
|
|
@@ -201,6 +258,7 @@ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
|
|
|
201
258
|
"stakes",
|
|
202
259
|
"delegations",
|
|
203
260
|
"tokenFactories",
|
|
261
|
+
"evidences",
|
|
204
262
|
"data"
|
|
205
263
|
].forEach((field) => {
|
|
206
264
|
if (typeof tx[field] === "string") try {
|
package/lib/db/base.d.cts
CHANGED
|
@@ -23,6 +23,24 @@ declare class SqliteBaseIndexDB extends BaseIndexDB implements IIndexDB {
|
|
|
23
23
|
rollupValidator: IIndexTable<IndexTableTypeMap['rollupValidator']>;
|
|
24
24
|
tokenDistribution: IIndexTable<IndexTableTypeMap['tokenDistribution']>;
|
|
25
25
|
tokenFactory: IIndexTable<IndexTableTypeMap['tokenFactory']>;
|
|
26
|
+
protected txCountCache: {
|
|
27
|
+
total: number;
|
|
28
|
+
invalid: number;
|
|
29
|
+
totalChanges: number;
|
|
30
|
+
dataVersion: number;
|
|
31
|
+
maxRowId: number;
|
|
32
|
+
} | null;
|
|
33
|
+
/**
|
|
34
|
+
* Return exact total, valid, and invalid transaction counts.
|
|
35
|
+
*
|
|
36
|
+
* - On cache hit (verified via O(1) `total_changes()`, `pragma_data_version`, and `max(rowid)`),
|
|
37
|
+
* returns in ~0.002 ms without scanning `idx_tx_valid`.
|
|
38
|
+
* - On cache miss, computes `total = COUNT(*)` (SQLite B-tree count optimization on covering index)
|
|
39
|
+
* and `invalid = COUNT(*) WHERE valid = 0` (scans only the <0.5% invalid tail) in parallel,
|
|
40
|
+
* then derives `valid = total - invalid`. This avoids scanning the 99.5% `valid = 1` slice
|
|
41
|
+
* while remaining 100% exact even after row deletions (`max(rowid) != COUNT(*)`).
|
|
42
|
+
*/
|
|
43
|
+
private getExactTxCounts;
|
|
26
44
|
/**
|
|
27
45
|
* List transactions with filtering and pagination
|
|
28
46
|
*/
|
package/lib/db/index.cjs
CHANGED
|
@@ -61,6 +61,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
61
61
|
"stakes",
|
|
62
62
|
"delegations",
|
|
63
63
|
"tokenFactories",
|
|
64
|
+
"evidences",
|
|
64
65
|
"data"
|
|
65
66
|
],
|
|
66
67
|
booleanFields: [
|
|
@@ -78,6 +79,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
78
79
|
"receiptsVerified",
|
|
79
80
|
"receiver",
|
|
80
81
|
"sender",
|
|
82
|
+
"gasPayer",
|
|
81
83
|
"time",
|
|
82
84
|
"tx",
|
|
83
85
|
"type",
|
|
@@ -92,6 +94,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
92
94
|
"stakes",
|
|
93
95
|
"delegations",
|
|
94
96
|
"tokenFactories",
|
|
97
|
+
"evidences",
|
|
95
98
|
"genesisTime",
|
|
96
99
|
"renaissanceTime",
|
|
97
100
|
"data"
|
|
@@ -545,6 +548,7 @@ var SqliteIndexDB = class extends require_db_base.default {
|
|
|
545
548
|
* Reset all tables (for testing)
|
|
546
549
|
*/
|
|
547
550
|
async reset() {
|
|
551
|
+
this.txCountCache = null;
|
|
548
552
|
for (const table of [
|
|
549
553
|
"tx",
|
|
550
554
|
"account",
|
package/lib/interfaces.d.cts
CHANGED
|
@@ -35,6 +35,7 @@ interface TxTable {
|
|
|
35
35
|
receiptsVerified: number | null;
|
|
36
36
|
receiver: string | null;
|
|
37
37
|
sender: string | null;
|
|
38
|
+
gasPayer: string | null;
|
|
38
39
|
time: string | null;
|
|
39
40
|
tx: string | null;
|
|
40
41
|
type: string | null;
|
|
@@ -49,6 +50,7 @@ interface TxTable {
|
|
|
49
50
|
stakes: string | null;
|
|
50
51
|
delegations: string | null;
|
|
51
52
|
tokenFactories: string | null;
|
|
53
|
+
evidences: string | null;
|
|
52
54
|
genesisTime: string | null;
|
|
53
55
|
renaissanceTime: string | null;
|
|
54
56
|
data: string | null;
|
|
@@ -10,9 +10,10 @@ var _001_genesis_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll(
|
|
|
10
10
|
* Genesis migration - creates all IndexDB tables
|
|
11
11
|
*/
|
|
12
12
|
async function up(db) {
|
|
13
|
-
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
13
|
+
await db.schema.createTable("tx").ifNotExists().addColumn("hash", "text", (col) => col.primaryKey()).addColumn("code", "text").addColumn("height", "integer").addColumn("index_", "integer").addColumn("receipts", "text").addColumn("receiptsVerified", "integer").addColumn("receiver", "text").addColumn("sender", "text").addColumn("gasPayer", "text").addColumn("time", "text").addColumn("tx", "text").addColumn("type", "text").addColumn("finalized", "integer").addColumn("valid", "integer").addColumn("accounts", "text").addColumn("assets", "text").addColumn("tokens", "text").addColumn("tokenSymbols", "text").addColumn("factories", "text").addColumn("rollups", "text").addColumn("stakes", "text").addColumn("delegations", "text").addColumn("tokenFactories", "text").addColumn("genesisTime", "text").addColumn("renaissanceTime", "text").addColumn("data", "text").execute();
|
|
14
14
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_sender ON tx(sender)`.execute(db);
|
|
15
15
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_receiver ON tx(receiver)`.execute(db);
|
|
16
|
+
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
16
17
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_type ON tx(type)`.execute(db);
|
|
17
18
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_time ON tx(time)`.execute(db);
|
|
18
19
|
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_height ON tx(height)`.execute(db);
|
|
@@ -6,9 +6,16 @@ var _003_delegation_extensions_exports = /* @__PURE__ */ require_rolldown_runtim
|
|
|
6
6
|
down: () => down,
|
|
7
7
|
up: () => up
|
|
8
8
|
});
|
|
9
|
+
async function addColumnIfNotExists(db, ddl) {
|
|
10
|
+
try {
|
|
11
|
+
await ddl.execute(db);
|
|
12
|
+
} catch (err) {
|
|
13
|
+
if (!(err instanceof Error ? err.message : String(err ?? "")).toLowerCase().includes("duplicate column name")) throw err;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
9
16
|
async function up(db) {
|
|
10
|
-
await kysely.sql`ALTER TABLE delegation ADD COLUMN deny TEXT
|
|
11
|
-
await kysely.sql`ALTER TABLE delegation ADD COLUMN validUntil INTEGER DEFAULT 0
|
|
17
|
+
await addColumnIfNotExists(db, kysely.sql`ALTER TABLE delegation ADD COLUMN deny TEXT`);
|
|
18
|
+
await addColumnIfNotExists(db, kysely.sql`ALTER TABLE delegation ADD COLUMN validUntil INTEGER DEFAULT 0`);
|
|
12
19
|
}
|
|
13
20
|
async function down(_db) {}
|
|
14
21
|
|
|
@@ -41,7 +41,11 @@ const MISSING_COLUMNS = [
|
|
|
41
41
|
}
|
|
42
42
|
];
|
|
43
43
|
async function up(db) {
|
|
44
|
-
for (const col of MISSING_COLUMNS)
|
|
44
|
+
for (const col of MISSING_COLUMNS) try {
|
|
45
|
+
await kysely.sql.raw(`ALTER TABLE rollup ADD COLUMN ${col.name} ${col.type}`).execute(db);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
if (!(err instanceof Error ? err.message : String(err ?? "")).toLowerCase().includes("duplicate column name")) throw err;
|
|
48
|
+
}
|
|
45
49
|
await kysely.sql.raw(`UPDATE rollup SET
|
|
46
50
|
minDepositFee = json_extract(data, '$.minDepositFee'),
|
|
47
51
|
maxDepositFee = json_extract(data, '$.maxDepositFee'),
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let kysely = require("kysely");
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/009-tx-gas-payer.ts
|
|
5
|
+
var _009_tx_gas_payer_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
11
|
+
*
|
|
12
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
13
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
14
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
15
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
16
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
17
|
+
*/
|
|
18
|
+
async function up(db) {
|
|
19
|
+
const columnsResult = await kysely.sql`PRAGMA table_info('tx')`.execute(db);
|
|
20
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("gasPayer")) await kysely.sql`ALTER TABLE tx ADD COLUMN gasPayer TEXT`.execute(db);
|
|
21
|
+
await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)`.execute(db);
|
|
22
|
+
}
|
|
23
|
+
async function down(db) {
|
|
24
|
+
await kysely.sql`DROP INDEX IF EXISTS idx_tx_gasPayer`.execute(db);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
Object.defineProperty(exports, '_009_tx_gas_payer_exports', {
|
|
29
|
+
enumerable: true,
|
|
30
|
+
get: function () {
|
|
31
|
+
return _009_tx_gas_payer_exports;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
exports.down = down;
|
|
35
|
+
exports.up = up;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/009-tx-gas-payer.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 009 - Add gasPayer column + index on tx (#1362)
|
|
7
|
+
*
|
|
8
|
+
* Schema only. Historical rows are NOT rewritten here: on main the tx table holds ~710k rows / ~4 GB,
|
|
9
|
+
* ~60% with an empty sender, and two full-table json_extract UPDATEs at startup block boot for minutes
|
|
10
|
+
* and grow the WAL by roughly the table size. Back-fill `sender` / `gasPayer` offline with the
|
|
11
|
+
* digest-guarded tool instead: `bun scripts/backfill-tx-index-1362.ts --index-db <path>` (plan), then
|
|
12
|
+
* `--apply --expected-digest <sha256>`. New rows get both fields at index time.
|
|
13
|
+
*/
|
|
14
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { down, up };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let kysely = require("kysely");
|
|
3
|
+
|
|
4
|
+
//#region src/migrations/010-tx-evidences.ts
|
|
5
|
+
var _010_tx_evidences_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
6
|
+
down: () => down,
|
|
7
|
+
up: () => up
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Migration 010 - Add evidences column on tx (#1479)
|
|
11
|
+
*
|
|
12
|
+
* `evidences` is a JSON array of bridge release evidence keys (`<kind>:<evidence>:<ordinal>`), written for
|
|
13
|
+
* `release_bridge_token` txs. Lookups go through the existing tx_ref junction table (type = 'evidence'),
|
|
14
|
+
* which already has the (type, value) index, so no new index is needed. Schema only: no historical rows
|
|
15
|
+
* carry a release tx.
|
|
16
|
+
*/
|
|
17
|
+
async function up(db) {
|
|
18
|
+
const columnsResult = await kysely.sql`PRAGMA table_info('tx')`.execute(db);
|
|
19
|
+
if (!new Set((columnsResult.rows || []).map((r) => r.name)).has("evidences")) await kysely.sql`ALTER TABLE tx ADD COLUMN evidences TEXT`.execute(db);
|
|
20
|
+
}
|
|
21
|
+
async function down(db) {
|
|
22
|
+
await kysely.sql`ALTER TABLE tx DROP COLUMN evidences`.execute(db);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
Object.defineProperty(exports, '_010_tx_evidences_exports', {
|
|
27
|
+
enumerable: true,
|
|
28
|
+
get: function () {
|
|
29
|
+
return _010_tx_evidences_exports;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
exports.down = down;
|
|
33
|
+
exports.up = up;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/010-tx-evidences.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Migration 010 - Add evidences column on tx (#1479)
|
|
7
|
+
*
|
|
8
|
+
* `evidences` is a JSON array of bridge release evidence keys (`<kind>:<evidence>:<ordinal>`), written for
|
|
9
|
+
* `release_bridge_token` txs. Lookups go through the existing tx_ref junction table (type = 'evidence'),
|
|
10
|
+
* which already has the (type, value) index, so no new index is needed. Schema only: no historical rows
|
|
11
|
+
* carry a release tx.
|
|
12
|
+
*/
|
|
13
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
14
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { down, up };
|
package/lib/migrations/index.cjs
CHANGED
|
@@ -7,6 +7,8 @@ const require_migrations_005_rollup_missing_columns = require('./005-rollup-miss
|
|
|
7
7
|
const require_migrations_006_rollup_block_height_integer = require('./006-rollup-block-height-integer.cjs');
|
|
8
8
|
const require_migrations_007_token_factory_feerate_integer = require('./007-token-factory-feerate-integer.cjs');
|
|
9
9
|
const require_migrations_008_index_failure = require('./008-index-failure.cjs');
|
|
10
|
+
const require_migrations_009_tx_gas_payer = require('./009-tx-gas-payer.cjs');
|
|
11
|
+
const require_migrations_010_tx_evidences = require('./010-tx-evidences.cjs');
|
|
10
12
|
let kysely = require("kysely");
|
|
11
13
|
|
|
12
14
|
//#region src/migrations/index.ts
|
|
@@ -24,21 +26,35 @@ var InMemoryMigrationProvider = class {
|
|
|
24
26
|
"005-rollup-missing-columns": require_migrations_005_rollup_missing_columns._005_rollup_missing_columns_exports,
|
|
25
27
|
"006-rollup-block-height-integer": require_migrations_006_rollup_block_height_integer._006_rollup_block_height_integer_exports,
|
|
26
28
|
"007-token-factory-feerate-integer": require_migrations_007_token_factory_feerate_integer._007_token_factory_feerate_integer_exports,
|
|
27
|
-
"008-index-failure": require_migrations_008_index_failure._008_index_failure_exports
|
|
29
|
+
"008-index-failure": require_migrations_008_index_failure._008_index_failure_exports,
|
|
30
|
+
"009-tx-gas-payer": require_migrations_009_tx_gas_payer._009_tx_gas_payer_exports,
|
|
31
|
+
"010-tx-evidences": require_migrations_010_tx_evidences._010_tx_evidences_exports
|
|
28
32
|
};
|
|
29
33
|
}
|
|
30
34
|
};
|
|
35
|
+
function isRetryableMigrationError(error) {
|
|
36
|
+
const code = error?.code;
|
|
37
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" || code === 5 || code === 6) return true;
|
|
38
|
+
const msg = (error instanceof Error ? error.message : String(error ?? "")).toLowerCase();
|
|
39
|
+
return msg.includes("database is locked") || msg.includes("sqlite_busy") || msg.includes("sqlite_locked") || msg.includes("already exists") || msg.includes("duplicate column name") || msg.includes("unique constraint failed: kysely_migration") || msg.includes("kysely_migration_lock");
|
|
40
|
+
}
|
|
31
41
|
/**
|
|
32
42
|
* Run all pending migrations
|
|
33
43
|
* @param db - Kysely instance
|
|
34
44
|
*/
|
|
35
45
|
async function runMigrations(db) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
46
|
+
for (let attempt = 0;; attempt++) {
|
|
47
|
+
const { error, results } = await new kysely.Migrator({
|
|
48
|
+
db,
|
|
49
|
+
provider: new InMemoryMigrationProvider()
|
|
50
|
+
}).migrateToLatest();
|
|
51
|
+
if (!error) {
|
|
52
|
+
for (const result of results ?? []) if (result.status === "Error") throw new Error(`Migration "${result.migrationName}" failed`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (!isRetryableMigrationError(error) || attempt >= 8) throw error;
|
|
56
|
+
await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
|
|
57
|
+
}
|
|
42
58
|
}
|
|
43
59
|
/**
|
|
44
60
|
* Rollback all migrations
|
package/lib/table/base.cjs
CHANGED
|
@@ -30,12 +30,21 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
|
|
|
30
30
|
generatePrimaryKey(doc) {
|
|
31
31
|
if (typeof doc === "string") return doc;
|
|
32
32
|
if (Array.isArray(this.uniqIndex)) {
|
|
33
|
-
const key = this.uniqIndex.map((id) => doc[id]).map((item) => typeof item === "object" ? JSON.stringify(item) : item).join("-");
|
|
33
|
+
const key = this.uniqIndex.map((id) => doc[id]).map((item) => typeof item === "object" ? JSON.stringify(item) : String(item ?? "")).map((item) => item.replace(/\\/g, "\\\\").replace(/-/g, "\\-")).join("-");
|
|
34
34
|
return node_crypto.default.createHash("md5").update(key).digest("hex");
|
|
35
35
|
}
|
|
36
36
|
return doc[this.uniqIndex];
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
+
* Check that a primary-key column value is a non-empty string or finite number.
|
|
40
|
+
* Prevents `undefined`/`null`/`''` key fields from silently dropping SQL WHERE clauses (#1438).
|
|
41
|
+
*/
|
|
42
|
+
isValidPrimaryKeyValue(v) {
|
|
43
|
+
if (typeof v === "string") return v.length > 0;
|
|
44
|
+
if (typeof v === "number") return Number.isFinite(v);
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
39
48
|
* Map column name for reserved keywords
|
|
40
49
|
*/
|
|
41
50
|
mapColumnName(name) {
|
|
@@ -192,11 +201,10 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
|
|
|
192
201
|
const id = typeof key === "string" ? key : key[this.primaryKey];
|
|
193
202
|
query = { [this.mapColumnName(this.primaryKey)]: id };
|
|
194
203
|
}
|
|
204
|
+
const queryEntries = Object.entries(query);
|
|
205
|
+
if (queryEntries.length === 0 || queryEntries.some(([, v]) => !this.isValidPrimaryKeyValue(v))) return null;
|
|
195
206
|
let qb = this.getExecutor(context).selectFrom(this.name).selectAll();
|
|
196
|
-
for (const [k, v] of
|
|
197
|
-
if (v === void 0) continue;
|
|
198
|
-
qb = qb.where(k, "=", v);
|
|
199
|
-
}
|
|
207
|
+
for (const [k, v] of queryEntries) qb = qb.where(k, "=", v);
|
|
200
208
|
const result = await qb.executeTakeFirst();
|
|
201
209
|
return this.deserializeFromDb(result);
|
|
202
210
|
}
|
|
@@ -213,6 +221,15 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
|
|
|
213
221
|
* Internal update implementation - called by BaseIndex.update() via hooks
|
|
214
222
|
*/
|
|
215
223
|
async _update(key, updates, context) {
|
|
224
|
+
if (!key || typeof key === "object" && key === null) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
225
|
+
if (Array.isArray(this.uniqIndex)) {
|
|
226
|
+
if (typeof key !== "object") throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
227
|
+
const keyObj = key;
|
|
228
|
+
for (const k of this.uniqIndex) if (!this.isValidPrimaryKeyValue(keyObj[k])) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
229
|
+
} else if (typeof key === "object") {
|
|
230
|
+
const id = key[this.primaryKey];
|
|
231
|
+
if (!this.isValidPrimaryKeyValue(id)) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
232
|
+
} else if (!this.isValidPrimaryKeyValue(key)) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
216
233
|
const existing = await this._get(key, context);
|
|
217
234
|
if (!existing) throw new Error(`${this.name} does not exist: ${JSON.stringify(key)}`);
|
|
218
235
|
let query;
|
|
@@ -223,16 +240,15 @@ var SqliteTable = class extends _ocap_indexdb.BaseIndex {
|
|
|
223
240
|
const id = typeof key === "string" ? key : key[this.primaryKey];
|
|
224
241
|
query = { [this.mapColumnName(this.primaryKey)]: id };
|
|
225
242
|
}
|
|
243
|
+
const queryEntries = Object.entries(query);
|
|
244
|
+
if (queryEntries.length === 0 || queryEntries.some(([, v]) => !this.isValidPrimaryKeyValue(v))) throw new Error(`Invalid or incomplete primary key for ${this.name} update: ${JSON.stringify(key)}`);
|
|
226
245
|
const updateAttrs = { ...updates };
|
|
227
246
|
if (Array.isArray(this.uniqIndex)) for (const k of this.uniqIndex) delete updateAttrs[k];
|
|
228
247
|
else delete updateAttrs[this.primaryKey];
|
|
229
248
|
if (Object.keys(updateAttrs).length > 0) {
|
|
230
249
|
const serialized = this.serializeForDbUpdate(updateAttrs, existing);
|
|
231
250
|
let qb = this.getExecutor(context).updateTable(this.name).set(serialized);
|
|
232
|
-
for (const [k, v] of
|
|
233
|
-
if (v === void 0) continue;
|
|
234
|
-
qb = qb.where(k, "=", v);
|
|
235
|
-
}
|
|
251
|
+
for (const [k, v] of queryEntries) qb = qb.where(k, "=", v);
|
|
236
252
|
await qb.execute();
|
|
237
253
|
}
|
|
238
254
|
return {
|
package/lib/table/base.d.cts
CHANGED
|
@@ -47,6 +47,11 @@ declare class SqliteTable<T = unknown> extends BaseIndex<T> implements IIndexTab
|
|
|
47
47
|
* Handles both simple string keys and composite keys
|
|
48
48
|
*/
|
|
49
49
|
generatePrimaryKey(doc: string | Record<string, unknown>): string;
|
|
50
|
+
/**
|
|
51
|
+
* Check that a primary-key column value is a non-empty string or finite number.
|
|
52
|
+
* Prevents `undefined`/`null`/`''` key fields from silently dropping SQL WHERE clauses (#1438).
|
|
53
|
+
*/
|
|
54
|
+
protected isValidPrimaryKeyValue(v: unknown): boolean;
|
|
50
55
|
/**
|
|
51
56
|
* Map column name for reserved keywords
|
|
52
57
|
*/
|
|
@@ -13,7 +13,8 @@ const TX_REF_TYPES = [
|
|
|
13
13
|
["rollup", "rollups"],
|
|
14
14
|
["stake", "stakes"],
|
|
15
15
|
["delegation", "delegations"],
|
|
16
|
-
["tokenFactory", "tokenFactories"]
|
|
16
|
+
["tokenFactory", "tokenFactories"],
|
|
17
|
+
["evidence", "evidences"]
|
|
17
18
|
];
|
|
18
19
|
/**
|
|
19
20
|
* Transaction table for SQLite IndexDB
|
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.
|
|
4
|
+
"version": "1.31.2",
|
|
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.
|
|
17
|
+
"@ocap/indexdb-test": "1.31.2"
|
|
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.
|
|
67
|
-
"@ocap/indexdb": "1.31.
|
|
68
|
-
"@ocap/types": "1.31.
|
|
69
|
-
"@ocap/util": "1.31.
|
|
66
|
+
"@arcblock/did": "1.31.2",
|
|
67
|
+
"@ocap/indexdb": "1.31.2",
|
|
68
|
+
"@ocap/types": "1.31.2",
|
|
69
|
+
"@ocap/util": "1.31.2",
|
|
70
70
|
"debug": "^4.4.3",
|
|
71
71
|
"better-sqlite3": "^11.8.1",
|
|
72
72
|
"kysely": "^0.28.14",
|