File tree Expand file tree Collapse file tree 2 files changed +60
-2
lines changed Expand file tree Collapse file tree 2 files changed +60
-2
lines changed Original file line number Diff line number Diff line change
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;
Original file line number Diff line number Diff line change @@ -43,7 +43,7 @@ module.exports = {
43
43
const hasStatesTable = await knex . schema . hasTable ( 'states' ) ;
44
44
if ( ! hasStatesTable ) {
45
45
await knex . schema . createTable ( 'states' , function ( t ) {
46
- t . string ( 'contract_tx_id' ) . index ( ) ;
46
+ t . string ( 'contract_tx_id' ) . unique ( ) ;
47
47
t . jsonb ( 'manifest' ) . notNullable ( ) ;
48
48
t . string ( 'bundle_tx_id' ) ;
49
49
t . string ( 'sort_key' ) . index ( ) ;
@@ -60,7 +60,7 @@ module.exports = {
60
60
// Trigger for ensuring only the newest state is stored
61
61
await knex . raw ( `
62
62
CREATE TRIGGER IF NOT EXISTS reject_outdated_state
63
- BEFORE INSERT
63
+ BEFORE UPDATE
64
64
ON states
65
65
BEGIN
66
66
SELECT CASE
You can’t perform that action at this time.
0 commit comments