-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.sql
69 lines (54 loc) · 1.98 KB
/
script.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
CREATE TABLE IF NOT EXISTS transactions (
transaction_id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255),
timestamp TIMESTAMP,
amount DECIMAL,
currency VARCHAR(255),
city VARCHAR(255),
country VARCHAR(255),
merchant_name VARCHAR(255),
payment_method VARCHAR(255),
ip_address VARCHAR(255),
voucher_code VARCHAR(255),
affiliateId VARCHAR(255)
);
-- add columns
ALTER TABLE transactions add column modified_by TEXT;
ALTER TABLE transactions add column modified_at TIMESTAMP;
CREATE OR REPLACE FUNCTION record_change_user()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified_by := current_user;
NEW.modified_at := CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger for UPDATE
CREATE TRIGGER trigger_record_user_update
BEFORE UPDATE ON transactions
FOR EACH ROW EXECUTE FUNCTION record_change_user();
-- capture before records on debezium
ALTER TABLE transactions REPLICA IDENTITY FULL;
--change information column
ALTER TABLE transactions ADD COLUMN change_info JSONB;
-- capture the changes to specific columns into json object
CREATE OR REPLACE FUNCTION record_changed_columns()
RETURNS TRIGGER AS $$
DECLARE
change_details JSONB;
BEGIN
change_details := '{}'::JSONB; -- Initialize an empty JSONB object
-- Check each column for changes and record as necessary
IF NEW.amount IS DISTINCT FROM OLD.amount THEN
change_details := jsonb_insert(change_details, '{amount}', jsonb_build_object('old', OLD.amount, 'new', NEW.amount));
END IF;
-- Add user and timestamp
change_details := change_details || jsonb_build_object('modified_by', current_user, 'modified_at', now());
-- Update the change_info column
NEW.change_info := change_details;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_record_amount_info
BEFORE UPDATE ON transactions
FOR EACH ROW EXECUTE FUNCTION record_changed_columns();