Skip to content

Commit d96a66c

Browse files
committed
Delete old states and create a UNIQUE index on states.contract_tx_id #21
1 parent bf340e2 commit d96a66c

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
BEGIN;
2+
3+
-- Remove temp tables in case previous run failed
4+
DROP TABLE IF EXISTS to_delete_states;
5+
6+
DROP TABLE IF EXISTS max_states;
7+
8+
-- Max sort keys in contracts that have multiple entries
9+
CREATE TEMP TABLE max_states AS
10+
SELECT
11+
contract_tx_id,
12+
MAX(sort_key) as max_sort_key
13+
FROM
14+
states
15+
GROUP BY
16+
contract_tx_id
17+
HAVING
18+
COUNT(*) > 1;
19+
20+
-- States that get removed. PK is contract_tx_id + sort_key
21+
CREATE TEMP TABLE to_delete_states AS
22+
SELECT
23+
max_states.contract_tx_id,
24+
states.sort_key
25+
FROM
26+
states
27+
JOIN max_states ON states.contract_tx_id = max_states.contract_tx_id
28+
WHERE
29+
states.sort_key < max_states.max_sort_key;
30+
31+
-- Remove states
32+
DELETE FROM
33+
states
34+
WHERE
35+
EXISTS (
36+
SELECT
37+
*
38+
FROM
39+
to_delete_states
40+
WHERE
41+
to_delete_states.contract_tx_id = states.contract_tx_id
42+
AND to_delete_states.sort_key = states.sort_key
43+
);
44+
45+
-- There's one entry per contract_tx_id, so we can create a unique index
46+
CREATE UNIQUE INDEX IF NOT EXISTS states_contract_tx_id_unique ON states(contract_tx_id);
47+
48+
-- Remove the old index
49+
DROP INDEX IF EXISTS states_contract_tx_id_index;
50+
51+
-- Cleanup
52+
DROP TABLE to_delete_states;
53+
54+
DROP TABLE max_states;
55+
56+
COMMIT;
57+
58+
VACUUM;

src/db/nodeDb.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ module.exports = {
4343
const hasStatesTable = await knex.schema.hasTable('states');
4444
if (!hasStatesTable) {
4545
await knex.schema.createTable('states', function (t) {
46-
t.string('contract_tx_id').index();
46+
t.string('contract_tx_id').unique();
4747
t.jsonb('manifest').notNullable();
4848
t.string('bundle_tx_id');
4949
t.string('sort_key').index();
@@ -60,7 +60,7 @@ module.exports = {
6060
// Trigger for ensuring only the newest state is stored
6161
await knex.raw(`
6262
CREATE TRIGGER IF NOT EXISTS reject_outdated_state
63-
BEFORE INSERT
63+
BEFORE UPDATE
6464
ON states
6565
BEGIN
6666
SELECT CASE

0 commit comments

Comments
 (0)