--
-- This file is part of TALER
-- Copyright (C) 2026 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--

BEGIN;

SELECT _v.register_patch('donau-0003', NULL, NULL);
SET search_path TO donau;

-- The `history' table is documented as holding "the yearly donation amount
-- for each charity", but its primary key was `charity_id' alone, so it could
-- hold at most ONE year per charity: the second year was a unique violation.
-- The key must include the year.
ALTER TABLE history
  DROP CONSTRAINT history_pkey;
ALTER TABLE history
  ADD CONSTRAINT history_pkey PRIMARY KEY (charity_id, donation_year);

COMMENT ON COLUMN history.donation_year
  IS 'Year the final_amount was accumulated in; part of the primary key.';

-- receipts_issued.receipt_id was GENERATED BY DEFAULT AS IDENTITY, which
-- permits explicit inserts (bulk load, partial restore, ad-hoc migration)
-- and thus permits leaving the identity sequence behind the largest stored
-- value.  Every subsequent insert then fails with a unique violation on
-- receipts_issued_receipt_id_key -- which donau-httpd cannot distinguish
-- from "this receipt_hash already exists".  The value is never supplied by
-- the daemon, so make it unforgeable from the outside.
ALTER TABLE receipts_issued
  ALTER COLUMN receipt_id SET GENERATED ALWAYS;

-- receipts_issued.receipt_hash is the idempotence key of POST /batch-issue:
-- it is what stops a charity from having the same blinded UDIs signed twice.
-- With ON DELETE CASCADE that guarantee lasted only as long as the charity
-- row: deleting and re-registering a charity freed every one of its receipt
-- hashes for replay, and destroyed the record of what had been issued.
ALTER TABLE receipts_issued
  DROP CONSTRAINT receipts_issued_charity_id_fkey;
ALTER TABLE receipts_issued
  ADD CONSTRAINT receipts_issued_charity_id_fkey
  FOREIGN KEY (charity_id)
  REFERENCES charities (charity_id)
  ON DELETE RESTRICT;

COMMIT;
