diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql index 587eb641..ff0b5cf6 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql @@ -27,6 +27,31 @@ create table if not exists hs_office_coopassetstransaction reverseEntryUuid uuid references hs_office_coopassetstransaction (uuid) deferrable , comment varchar(512) ); + +alter table hs_office_coopassetstransaction + add constraint hs_office_coopassetstransaction_reverse_entry_missing + check ( transactionType != 'ADJUSTMENT' or reverseEntryUuid is not null); + +CREATE OR REPLACE FUNCTION hs_office_coopassetstransaction_reverse_entry_is_reciprocal_tf() + RETURNS TRIGGER + LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.reverseEntryUuid IS NULL + OR NEW.uuid IN (SELECT other.reverseEntryUuid + FROM hs_office_coopassetstransaction other + WHERE other.uuid = NEW.reverseEntryUuid + AND NEW.membershipUuid = other.membershipUuid) + THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'reverseEntryUuid must refer to a row that has a reference back to this row and belongs to the same membership'; +END; $$; + +-- FIXME: why does this not work? +-- CREATE TRIGGER hs_office_coopassetstransaction_reverse_entry_is_reciprocal_tg +-- AFTER INSERT OR UPDATE ON hs_office_coopassetstransaction +-- FOR EACH ROW EXECUTE FUNCTION hs_office_coopassetstransaction_reverse_entry_is_reciprocal_tf(); --// -- ============================================================================