-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.sql
61 lines (54 loc) · 1.72 KB
/
database.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
CREATE EXTENSION postgis;
CREATE TABLE IF NOT EXISTS flags (
id serial,
flagged_by text DEFAULT current_user,
flagged_at timestamp without time zone DEFAULT now(),
tree character(64) NOT NULL REFERENCES trees(ssm_key),
flag character(16) NOT NULL,
reason character varying(1024),
PRIMARY KEY (tree, flag)
);
CREATE TABLE IF NOT EXISTS trees (
ssm_key character(64) NOT NULL,
description character varying(1024),
img character varying(255),
type character(32),
added_by character varying(128),
added_at timestamp without time zone DEFAULT now(),
point geometry(Point) NOT NULL
);
ALTER TABLE ONLY trees ADD CONSTRAINT trees_pkey PRIMARY KEY (ssm_key);
ALTER TABLE ONLY trees ADD CONSTRAINT trees_ssm_key_key UNIQUE (ssm_key);
CREATE TABLE IF NOT EXISTS history (
id serial,
by text DEFAULT current_user,
at timestamp without time zone DEFAULT now(),
tab text,
op text,
old_json json,
new_json json
);
DROP TRIGGER IF EXISTS trees_history ON trees;
CREATE OR REPLACE FUNCTION history_trigger()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
AS $function$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO history (tab, op, new_json)
VALUES (TG_RELNAME, TG_OP, row_to_json(NEW));
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO history (tab, op, old_json, new_json)
VALUES (TG_RELNAME, TG_OP, row_to_json(OLD), row_to_json(NEW));
RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO history (tab, op, old_json)
VALUES (TG_RELNAME, TG_OP, row_to_json(OLD));
RETURN OLD;
END IF;
END;
$function$;
CREATE TRIGGER trees_history BEFORE INSERT OR UPDATE OR DELETE ON trees
FOR EACH ROW EXECUTE PROCEDURE history_trigger();