-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathenum.sql.jinja2
111 lines (95 loc) · 2.33 KB
/
enum.sql.jinja2
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
{% import 'util.jinja2' as util %}
-- ENUM
CREATE TABLE IF NOT EXISTS "{{table}}" (
id {{id_type}} primary key
);
CREATE TABLE IF NOT EXISTS "{{table}}__valid" (
metadata integer not null
,id {{id_type}} primary key
,EXCLUDE USING gist (
id with =,
transaction_time with &&,
valid_time with &&
)
) INHERITS (transaction_valid_{{enum.valid_type}});
{%- if enum.coded %}
create table if not exists "{{table}}_code" (
metadata integer not null
,id {{id_type}} not null references "{{table}}"(id)
,code varchar not null
,EXCLUDE USING gist (
code with =
,transaction_time with &&
,valid_time with &&
)
) INHERITS (transaction_valid_{{enum.valid_type}});
{%- endif %}
{%- if enum.localized %}
create table if not exists "{{table}}_name" (
metadata integer not null
,id {{id_type}} not null references "{{table}}"(id)
,language_code char(2) not null references language_iso639
,name varchar not null
,EXCLUDE USING gist (
id with =
,language_code with =
,transaction_time with &&
,valid_time with &&
)
) INHERITS (transaction_valid_{{enum.valid_type}});
{%- endif %}
CREATE OR REPLACE VIEW "l_{{table}}" AS
SELECT
metadata
,"{{table}}__valid".valid_time
,"{{table}}".id as id
FROM "{{table}}"
JOIN "{{table}}__valid" USING (id)
WHERE {{v_current_time}} <@ "{{table}}__valid".valid_time
AND {{t_current_time}} <@ "{{table}}__valid".transaction_time
;
CREATE OR REPLACE FUNCTION "delete_l_{{table}}"()
RETURNS TRIGGER AS $$
BEGIN
-- TODO
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION "update_l_{{table}}"()
RETURNS TRIGGER AS $$
BEGIN
-- TODO
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION "insert_l_{{table}}"()
RETURNS TRIGGER
AS $$
DECLARE
-- Primary key or id variables. Mainly for auto-filling serials and such (for now).
__id "{{table}}".id%TYPE; -- TODO
BEGIN
-- For now, allow empty metadata:
IF NEW.metadata IS NULL THEN
NEW.metadata := 0;
END IF;
IF NEW.id IS NULL THEN
INSERT INTO "{{table}}" (
metadata
) VALUES (
NEW.metadata
)
RETURNING id into __id;
ELSE
INSERT INTO "{{table}}" (
metadata, id
) VALUES (
NEW.metadata, NEW.id
)
RETURNING id into __id;
END IF;
NEW.id := __id;
-- TODO: coded, localized columns.
RETURN NEW; END;
$$ LANGUAGE plpgsql;
{{util.create_trigger_references(table, 'l_')}}