From a4425d3c0bc702f4066446751ec28331d5121dbe Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 24 Jun 2021 08:47:13 +1000 Subject: [PATCH] db: Fix uniqueness constraint on CollateralTxIn table The uniqueness constraints used to be on `txOutId` and `txOutIndex` but that is not correct because collateral inputs that are not consumed can be reused. Instead we put the uniqueness constraint on the `txInId`. Closes: https://github.com/input-output-hk/cardano-db-sync/issues/664 --- cardano-db/src/Cardano/Db/Schema.hs | 2 +- schema/migration-2-0008-20210623.sql | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 schema/migration-2-0008-20210623.sql diff --git a/cardano-db/src/Cardano/Db/Schema.hs b/cardano-db/src/Cardano/Db/Schema.hs index 7f9f4d917..e6b043070 100644 --- a/cardano-db/src/Cardano/Db/Schema.hs +++ b/cardano-db/src/Cardano/Db/Schema.hs @@ -136,7 +136,7 @@ share txInId TxId OnDeleteCascade -- The transaction where this is used as an input. txOutId TxId OnDeleteCascade -- The transaction where this was created as an output. txOutIndex Word16 sqltype=txindex - UniqueColTxin txOutId txOutIndex + UniqueColTxin txInId -- A table containing metadata about the chain. There will probably only ever be one -- row in this table. diff --git a/schema/migration-2-0008-20210623.sql b/schema/migration-2-0008-20210623.sql new file mode 100644 index 000000000..b5fc2c5a2 --- /dev/null +++ b/schema/migration-2-0008-20210623.sql @@ -0,0 +1,20 @@ +-- Persistent generated migration. + +CREATE FUNCTION migrate() RETURNS void AS $$ +DECLARE + next_version int ; +BEGIN + SELECT stage_two + 1 INTO next_version FROM schema_version ; + IF next_version = 8 THEN + EXECUTE 'ALTER TABLE "collateral_tx_in" DROP CONSTRAINT "unique_col_txin"' ; + EXECUTE 'ALTER TABLE "collateral_tx_in" ADD CONSTRAINT "unique_col_txin" UNIQUE("tx_in_id")' ; + -- Hand written SQL statements can be added here. + UPDATE schema_version SET stage_two = next_version ; + RAISE NOTICE 'DB has been migrated to stage_two version %', next_version ; + END IF ; +END ; +$$ LANGUAGE plpgsql ; + +SELECT migrate() ; + +DROP FUNCTION migrate() ;