-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathqueries.go
65 lines (62 loc) · 1.96 KB
/
queries.go
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
package pqstream
var (
sqlQueryTables = `
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE'
`
sqlTriggerFunction = `
CREATE OR REPLACE FUNCTION pqstream_notify() RETURNS TRIGGER AS $$
DECLARE
payload json;
previous json;
notification json;
BEGIN
IF (TG_OP = 'DELETE') THEN
payload = row_to_json(OLD);
ELSE
payload = row_to_json(NEW);
END IF;
IF (TG_OP = 'UPDATE') THEN
previous = row_to_json(OLD);
END IF;
notification = json_build_object(
'schema', TG_TABLE_SCHEMA,
'table', TG_TABLE_NAME,
'op', TG_OP,
'id', json_extract_path(payload, 'id')::text,
'payload', payload,
'previous', previous);
IF (length(notification::text) >= 8000) THEN
notification = json_build_object(
'schema', TG_TABLE_SCHEMA,
'table', TG_TABLE_NAME,
'op', TG_OP,
'id', json_extract_path(payload, 'id')::text,
'payload', payload);
END IF;
IF (length(notification::text) >= 8000) THEN
notification = json_build_object(
'schema', TG_TABLE_SCHEMA,
'table', TG_TABLE_NAME,
'op', TG_OP,
'id', json_extract_path(payload, 'id')::text);
END IF;
PERFORM pg_notify('pqstream_notify', notification::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
`
sqlRemoveTrigger = `
DROP TRIGGER IF EXISTS pqstream_notify ON %s
`
sqlInstallTrigger = `
CREATE TRIGGER pqstream_notify
AFTER INSERT OR UPDATE OR DELETE ON %s
FOR EACH ROW EXECUTE PROCEDURE pqstream_notify();
`
sqlFetchRowByID = `
SELECT row_to_json(r)::text from (select * from %s where id = $1::%s) r;
`
)