-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
46 lines (38 loc) · 1004 Bytes
/
app.rb
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
require 'sequel'
$stdout.sync = true
puts "Waiting for pg"
sleep 2 # hack to wait for pg container
DB = Sequel.connect('postgres://postgres:postgres@postgres:5432/postgres') # requires pg
DB.drop_table?(:items)
DB.create_table :items do
primary_key :id
String :name
Float :price
end
DB.execute("
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$
DECLARE
record RECORD;
payload JSON;
BEGIN
IF (TG_OP = 'DELETE') THEN
record = OLD;
ELSE
record = NEW;
END IF;
payload = json_build_object('table', TG_TABLE_NAME,
'action', TG_OP,
'data', row_to_json(record));
PERFORM pg_notify('events', payload::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
")
DB.execute("
CREATE TRIGGER notify_order_event
AFTER INSERT OR UPDATE OR DELETE ON items
FOR EACH ROW EXECUTE PROCEDURE notify_event();
")
DB.listen(:events, loop: true) do |_channel, _pid, payload|
puts payload
end