Skip to content

Commit 2acbe34

Browse files
committed
schema: Add migration 0002_schema.up.sql
`0002_schema.up.sql` changes the PRIMARY KEY of `block` table from `(height, hash)` to `height` only, in order to prevent multiple rows from contending for the same height. **NOTE** this operation is potentially destructive. If two or more rows existed at the same height, they'll now be missing from the database since we can't reliably determine which block hash is the correct one. Additionally, the anchor `block_hash` column previously had the type INTEGER, and this was a mistake in the schema, since block hashes are typically represented as a hex string. Thus we change the type of the `block_hash` column to TEXT.
1 parent 4a393b5 commit 2acbe34

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

migrations/0002_schema.up.sql

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
-- 0002_schema_up.sql
2+
3+
-- ******************************************** --
4+
-- Change primary key of block table to height. --
5+
-- ******************************************** --
6+
7+
-- Create new table
8+
CREATE TABLE IF NOT EXISTS block_new(
9+
height INTEGER PRIMARY KEY NOT NULL,
10+
hash TEXT NOT NULL
11+
);
12+
-- Copy only unique rows
13+
INSERT INTO block_new(height, hash)
14+
SELECT height, hash
15+
FROM block
16+
WHERE height IN(
17+
SELECT height
18+
FROM block
19+
GROUP BY height
20+
HAVING COUNT(*) = 1
21+
);
22+
-- Drop old table
23+
DROP TABLE block;
24+
-- Rename new table to old
25+
ALTER TABLE block_new RENAME TO block;
26+
27+
-- ************************************************ --
28+
-- Change type of anchor block_hash column to TEXT. --
29+
-- ************************************************ --
30+
31+
-- Create new table
32+
CREATE TABLE IF NOT EXISTS anchor_new(
33+
block_height INTEGER NOT NULL,
34+
block_hash TEXT NOT NULL,
35+
txid TEXT NOT NULL,
36+
confirmation_time INTEGER NOT NULL,
37+
PRIMARY KEY(block_height, block_hash, txid)
38+
);
39+
-- Copy old data
40+
INSERT INTO anchor_new(block_height, block_hash, txid, confirmation_time)
41+
SELECT block_height, block_hash, txid, confirmation_time
42+
FROM anchor;
43+
-- Delete old table
44+
DROP TABLE anchor;
45+
-- Rename new table to old table
46+
ALTER TABLE anchor_new RENAME TO anchor;

0 commit comments

Comments
 (0)