DROP FUNCTION IF EXISTS account_transfert;

CREATE FUNCTION account_transfert(v_name_from text, v_name_to text, v_amount integer) RETURNS integer AS
$$
DECLARE v_balance integer;
BEGIN
    
    SELECT balance FROM account WHERE name = v_name_from INTO v_balance;
    -- /!\ race condition si modification du solde de v_name_from à cet endroit
    IF v_balance >= v_amount THEN
        UPDATE account SET balance = balance - v_amount
        WHERE name = v_name_from;

        UPDATE account SET balance = balance + v_amount
        WHERE name = v_name_to;

        RAISE NOTICE '%''s transférés de % vers %', v_amount, v_name_from, v_name_to;

        RETURN v_amount;
    ELSE
        RAISE WARNING '% ne dispose que de %€ : transfert de % annulé', v_name_from, v_balance, v_amount;

        RETURN NULL;
    END IF;
    

END$$ LANGUAGE plpgsql;

-- a exécuter dans un SELECT, comme suit :
-- SELECT account_transfert('alice', 'bob', 10);
