Skip to content

Commit

Permalink
Delete old states and create a UNIQUE index on states.contract_tx_id #21
Browse files Browse the repository at this point in the history
  • Loading branch information
janekolszak committed Jan 30, 2023
1 parent bf340e2 commit d96a66c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
58 changes: 58 additions & 0 deletions src/db/00001_unique_contract_tx_id.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
BEGIN;

-- Remove temp tables in case previous run failed
DROP TABLE IF EXISTS to_delete_states;

DROP TABLE IF EXISTS max_states;

-- Max sort keys in contracts that have multiple entries
CREATE TEMP TABLE max_states AS
SELECT
contract_tx_id,
MAX(sort_key) as max_sort_key
FROM
states
GROUP BY
contract_tx_id
HAVING
COUNT(*) > 1;

-- States that get removed. PK is contract_tx_id + sort_key
CREATE TEMP TABLE to_delete_states AS
SELECT
max_states.contract_tx_id,
states.sort_key
FROM
states
JOIN max_states ON states.contract_tx_id = max_states.contract_tx_id
WHERE
states.sort_key < max_states.max_sort_key;

-- Remove states
DELETE FROM
states
WHERE
EXISTS (
SELECT
*
FROM
to_delete_states
WHERE
to_delete_states.contract_tx_id = states.contract_tx_id
AND to_delete_states.sort_key = states.sort_key
);

-- There's one entry per contract_tx_id, so we can create a unique index
CREATE UNIQUE INDEX IF NOT EXISTS states_contract_tx_id_unique ON states(contract_tx_id);

-- Remove the old index
DROP INDEX IF EXISTS states_contract_tx_id_index;

-- Cleanup
DROP TABLE to_delete_states;

DROP TABLE max_states;

COMMIT;

VACUUM;
4 changes: 2 additions & 2 deletions src/db/nodeDb.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ module.exports = {
const hasStatesTable = await knex.schema.hasTable('states');
if (!hasStatesTable) {
await knex.schema.createTable('states', function (t) {
t.string('contract_tx_id').index();
t.string('contract_tx_id').unique();
t.jsonb('manifest').notNullable();
t.string('bundle_tx_id');
t.string('sort_key').index();
Expand All @@ -60,7 +60,7 @@ module.exports = {
// Trigger for ensuring only the newest state is stored
await knex.raw(`
CREATE TRIGGER IF NOT EXISTS reject_outdated_state
BEFORE INSERT
BEFORE UPDATE
ON states
BEGIN
SELECT CASE
Expand Down

0 comments on commit d96a66c

Please sign in to comment.