added recursing triggers to enable indirect payments and revocations.

This commit is contained in:
Florian "flowdy" Heß 2016-06-25 17:02:27 +02:00
parent d915d32e3b
commit 769dcebc92

View File

@ -141,7 +141,7 @@ CREATE TRIGGER enforceImmutableTransfer
BEFORE UPDATE ON Transfer BEFORE UPDATE ON Transfer
WHEN OLD.amount IS NOT NULL WHEN OLD.amount IS NOT NULL
BEGIN BEGIN
SELECT RAISE(FAIL, "Transfer cannot be updated, but needs to be revoked and re-inserted to run triggers"); SELECT RAISE(FAIL, "Transfer cannot be updated, but needs to be replaced to make triggers run");
END; END;
CREATE TRIGGER enforceiZeroPaidAtStart CREATE TRIGGER enforceiZeroPaidAtStart
@ -161,6 +161,66 @@ BEGIN
WHERE (NEW.paid + IFNULL((SELECT m FROM _temp WHERE c IS NULL AND d IS NULL),0) ) <> OLD.paid; WHERE (NEW.paid + IFNULL((SELECT m FROM _temp WHERE c IS NULL AND d IS NULL),0) ) <> OLD.paid;
END; END;
-- When a transfer is revoked, the targetCredit of the associated bill is reduced. Hence we must
-- check if we can still have paid the debts linked to this transfer in an "is paid from" relation,
-- otherwise we have to revoke these transfers as well.
CREATE TRIGGER rebalanceReducedCredit
AFTER UPDATE OF value ON Credit
WHEN NEW.value < OLD.spent
BEGIN
REPLACE INTO _temp (d, m)
SELECT
'from_' || NEW.Id,
billId
FROM Transfer
WHERE fromCredit = NEW.Id
ORDER BY date DESC
LIMIT 1
;
DELETE
FROM Transfer
WHERE fromCredit = NEW.Id
AND billId IN (
SELECT billId
FROM _temp
WHERE c = 'from_' || NEW.Id
)
;
INSERT INTO Transfer (fromCredit, billId)
SELECT NEW.Id, m
FROM _temp
WHERE d = 'from_' || NEW.Id
AND NEW.value > (
SELECT spent
FROM Credit
WHERE Id = NEW.Id
)
;
DELETE FROM _temp WHERE d = 'from_' || NEW.Id;
END;
-- When we enter a transfer, the targetCredit of the associated bill might already be the fromCredit
-- of a transfer for other dues itself. We can update (replace) the transfer for an unfullfilled one.
-- That way, a transfer may issue recursively chained transfers.
CREATE TRIGGER rebalanceIncreasedCredit
AFTER UPDATE OF value ON Credit
WHEN NEW.value > OLD.spent
BEGIN
REPLACE INTO Transfer
SELECT OLD.Id AS fromCredit,
billId
FROM Transfer t
JOIN CurrentDebts cd ON t.billId = cd.billId
;
END;
CREATE TRIGGER enforceFixedDebits CREATE TRIGGER enforceFixedDebits
BEFORE UPDATE OF value ON Debit BEFORE UPDATE OF value ON Debit
WHEN EXISTS (SELECT * FROM Transfer WHERE billId=NEW.billId) WHEN EXISTS (SELECT * FROM Transfer WHERE billId=NEW.billId)
@ -206,7 +266,8 @@ BEGIN
END; END;
CREATE VIEW CurrentDebts AS CREATE VIEW CurrentDebts AS
SELECT debtor, SELECT billId,
debtor,
targetCredit, targetCredit,
purpose, purpose,
date, date,