From 240b3444466fb458b517d84c83bd6a782a21934e Mon Sep 17 00:00:00 2001 From: Stephen Paul Weber Date: Tue, 21 Dec 2021 19:50:40 -0500 Subject: [PATCH] NOTIFY on low balance This will be picked up by the LISTEN in sgx-jmp to auto-top-up or notify the customer of low balance. --- deploy/notify_low_balance.sql | 25 +++++++++++++++++++++++++ revert/notify_low_balance.sql | 8 ++++++++ sqitch.plan | 1 + verify/notify_low_balance.sql | 7 +++++++ 4 files changed, 41 insertions(+) create mode 100644 deploy/notify_low_balance.sql create mode 100644 revert/notify_low_balance.sql create mode 100644 verify/notify_low_balance.sql diff --git a/deploy/notify_low_balance.sql b/deploy/notify_low_balance.sql new file mode 100644 index 0000000..c80e6e9 --- /dev/null +++ b/deploy/notify_low_balance.sql @@ -0,0 +1,25 @@ +-- Deploy jmp:notify_low_balance to pg +-- requires: transactions +-- requires: balances + +BEGIN; + +CREATE OR REPLACE FUNCTION check_and_notify_low_balance() RETURNS TRIGGER AS $$ + DECLARE + bal NUMERIC; + BEGIN + SELECT balance INTO bal FROM balances WHERE customer_id = NEW.customer_id; + IF bal < 5 THEN + SELECT pg_notify('low_balance', NEW.customer_id); + END IF; + RETURN NEW; + END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER notify_low_balance + AFTER INSERT ON transactions + FOR EACH ROW + WHEN (NEW.amount < 0) + EXECUTE PROCEDURE check_and_notify_low_balance(); + +COMMIT; diff --git a/revert/notify_low_balance.sql b/revert/notify_low_balance.sql new file mode 100644 index 0000000..2c6e2c0 --- /dev/null +++ b/revert/notify_low_balance.sql @@ -0,0 +1,8 @@ +-- Revert jmp:notify_low_balance from pg + +BEGIN; + +DROP TRIGGER notify_low_balance ON transactions; +DROP FUNCTION check_and_notify_low_balance; + +COMMIT; diff --git a/sqitch.plan b/sqitch.plan index b201af6..659e917 100644 --- a/sqitch.plan +++ b/sqitch.plan @@ -21,3 +21,4 @@ plans 2021-11-17T18:06:30Z Stephen Paul Weber,,, # customers 2021-11-30T16:36:48Z Stephen Paul Weber,,, # Get customers from Redis\n\nRequires a redis_server to be configured on the postgres instance. cdr_charge [customer_plans plans cdr_with_charge] 2021-11-17T18:09:49Z Stephen Paul Weber,,, # Get the amount to charge a customer for a given CDR insert_charge_for_cdr [cdr_charge cdr_with_charge transactions] 2021-11-23T14:41:15Z Stephen Paul Weber,,, # Trigger to insert a transaction for the charge for this CDR +notify_low_balance [transactions balances] 2021-12-22T00:36:03Z Stephen Paul Weber,,, # NOTIFY when balance dips low diff --git a/verify/notify_low_balance.sql b/verify/notify_low_balance.sql new file mode 100644 index 0000000..293255e --- /dev/null +++ b/verify/notify_low_balance.sql @@ -0,0 +1,7 @@ +-- Verify jmp:notify_low_balance on pg + +BEGIN; + +-- Cannot LISTEN from inside DB + +ROLLBACK; -- 2.34.2