2017-01-22 21:20:17 +01:00
|
|
|
CREATE TRIGGER linkTransferTightly
|
|
|
|
AFTER INSERT ON Transfer
|
2017-01-19 21:44:22 +01:00
|
|
|
BEGIN
|
|
|
|
|
|
|
|
SELECT RAISE(FAIL, "It is not the debtor who is set to pay")
|
|
|
|
WHERE (SELECT debtor FROM Debit WHERE billId=NEW.billId)
|
|
|
|
!= (SELECT account FROM Credit WHERE credId=NEW.credId)
|
|
|
|
;
|
|
|
|
|
|
|
|
SELECT RAISE(FAIL, "Target of a debit cannot be an incoming payment")
|
|
|
|
FROM Credit c
|
|
|
|
JOIN Debit d ON c.credId = d.targetCredit
|
|
|
|
WHERE c.credId = NEW.credId
|
|
|
|
AND c.value > 0
|
|
|
|
GROUP BY c.credId
|
|
|
|
HAVING count(d.billId) == 0
|
|
|
|
;
|
|
|
|
|
2017-01-22 21:20:17 +01:00
|
|
|
INSERT INTO __INTERNAL_TRIGGER_STACK
|
|
|
|
SELECT NEW.ROWID,
|
|
|
|
CASE remainingDebt WHEN 0 THEN RAISE(FAIL, "Debt settled") ELSE NEW.billId END,
|
|
|
|
CASE remainingCredit WHEN 0 THEN RAISE(FAIL, "Credit spent") ELSE NEW.credId END,
|
|
|
|
min(remainingDebt, remainingCredit)
|
|
|
|
FROM (SELECT
|
|
|
|
(SELECT value - paid FROM Debit WHERE billId=NEW.billId) AS remainingDebt,
|
|
|
|
(SELECT value - spent FROM Credit WHERE credId=NEW.credId) AS remainingCredit
|
|
|
|
)
|
2017-01-19 21:44:22 +01:00
|
|
|
;
|
|
|
|
|
2017-01-22 21:20:17 +01:00
|
|
|
END;
|
|
|
|
|
|
|
|
CREATE TRIGGER reflectTransfer
|
|
|
|
AFTER INSERT ON __INTERNAL_TRIGGER_STACK
|
|
|
|
WHEN NEW.id > 0
|
|
|
|
BEGIN
|
|
|
|
|
2017-01-19 21:44:22 +01:00
|
|
|
UPDATE Debit
|
2017-01-22 21:20:17 +01:00
|
|
|
SET paid = paid + NEW.m
|
|
|
|
WHERE billId = NEW.d;
|
2017-01-19 21:44:22 +01:00
|
|
|
|
|
|
|
UPDATE Credit
|
2017-01-22 21:20:17 +01:00
|
|
|
SET spent = spent + NEW.m
|
|
|
|
WHERE credId = NEW.c;
|
2017-01-19 21:44:22 +01:00
|
|
|
|
|
|
|
UPDATE Transfer
|
2017-01-22 21:20:17 +01:00
|
|
|
SET amount = ifnull(amount,0) + NEW.m
|
|
|
|
WHERE ROWID = NEW.id;
|
2017-01-19 21:44:22 +01:00
|
|
|
|
|
|
|
UPDATE Credit
|
2017-01-22 21:20:17 +01:00
|
|
|
SET value = value + NEW.m
|
2017-01-19 21:44:22 +01:00
|
|
|
WHERE credId = (
|
|
|
|
SELECT targetCredit
|
|
|
|
FROM Debit
|
2017-01-22 21:20:17 +01:00
|
|
|
WHERE billId = NEW.d
|
2017-01-19 21:44:22 +01:00
|
|
|
);
|
|
|
|
|
2017-01-22 21:20:17 +01:00
|
|
|
DELETE FROM __INTERNAL_TRIGGER_STACK WHERE id=NEW.id;
|
|
|
|
|
|
|
|
END;
|
|
|
|
|
|
|
|
CREATE TRIGGER refreshTransfer
|
|
|
|
AFTER UPDATE OF amount ON Transfer
|
|
|
|
BEGIN
|
|
|
|
|
|
|
|
DELETE FROM Transfer
|
|
|
|
WHERE ROWID = NEW.ROWID AND amount = 0;
|
|
|
|
|
|
|
|
UPDATE Transfer
|
|
|
|
SET timestamp=CURRENT_TIMESTAMP
|
|
|
|
WHERE ROWID=NEW.ROWID;
|
2017-01-19 21:44:22 +01:00
|
|
|
|
|
|
|
END;
|
|
|
|
|