Revert constraint migration

This commit is contained in:
Stefan Kostic
2022-03-08 18:38:53 +01:00
parent e834d41c0c
commit f68ca7ac6e

View File

@@ -34,7 +34,6 @@ func init() {
DECLARE DECLARE
sum BIGINT; sum BIGINT;
debit_account_type VARCHAR; debit_account_type VARCHAR;
credit_account_type VARCHAR;
BEGIN BEGIN
-- LOCK the account if the transaction is not from an incoming account -- LOCK the account if the transaction is not from an incoming account
@@ -49,18 +48,8 @@ func init() {
-- This can happen when two transactions try to access the same account -- This can happen when two transactions try to access the same account
FOR UPDATE NOWAIT; FOR UPDATE NOWAIT;
-- check if credit_account type is fees, if it's fees we don't check for negative balance constraint -- If it is an incoming account return; otherwise check the balance
SELECT INTO credit_account_type type IF debit_account_type IS NULL
FROM accounts
WHERE id = NEW.credit_account_id AND type <> 'fees'
-- IMPORTANT: lock rows but do not wait for another lock to be released.
-- Waiting would result in a deadlock because two parallel transactions could try to lock the same rows
-- NOWAIT reports an error rather than waiting for the lock to be released
-- This can happen when two transactions try to access the same account
FOR UPDATE NOWAIT;
-- If it is an debit incoming account or fees credit account return; otherwise check the balance
IF debit_account_type IS NULL OR credit_account_type IS NULL
THEN THEN
RETURN NEW; RETURN NEW;
END IF; END IF;
@@ -71,7 +60,7 @@ func init() {
WHERE account_ledgers.account_id = NEW.debit_account_id; WHERE account_ledgers.account_id = NEW.debit_account_id;
-- IF the account would go negative raise an exception -- IF the account would go negative raise an exception
IF sum < 0 IF sum < 0 AND debit_account_type != 'incoming'
THEN THEN
RAISE EXCEPTION 'invalid balance [user_id:%] [debit_account_id:%] balance [%]', RAISE EXCEPTION 'invalid balance [user_id:%] [debit_account_id:%] balance [%]',
NEW.user_id, NEW.user_id,