-- Init CREATE VIEW seattle_employees_v AS SELECT FROM employees depar

 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
-- Init
CREATE VIEW seattle_employees_v AS SELECT e.* FROM employees e, departments d, locations l, countries c WHERE e.department_id=d.department_id AND l.location_id=d.location_id AND l.country_id=c.country_id AND c.country_name='United States of America' AND l.city='Seattle';
CREATE TABLE seattle_employees AS
SELECT * from seattle_employees_v;
ALTER TABLE seattle_employees
ADD PRIMARY KEY(employee_id);
CREATE INDEX se_salary ON seattle_employees
(salary);
CREATE INDEX se_last_name ON seattle_employees
(last_name);
CREATE TABLE seattle_employees_log ( employee_id int );
ALTER TABLE seattle_employees_log
ADD PRIMARY KEY(employee_id);
-- refresh_seattle_employees
CREATE OR REPLACE FUNCTION refresh_seattle_employees (id INTEGER) RETURNS
VOID SECURITY DEFINER
AS $$
DELETE FROM seattle_employees WHERE employee_id=$1;
INSERT INTO seattle_employees SELECT * FROM seattle_employees_v WHERE employee_id=$1;
$$ LANGUAGE SQL;
-- Method
CREATE OR REPLACE synchronizeSeattleView() RETURNS VOID AS $$
DECLARE
emp RECORD;
BEGIN
-- Get ids from log
FOR emp IN (select employee_id from seattle_employees_log) LOOP
PERFORM refresh_seattle_employees(emp.employee_id);
END LOOP;
-- Clear log
TRUNCATE TABLE seattle_employees_log;
END;
$$ LANGUAGE PLPGSQL;
-- Insert Trigger
CREATE OR REPLACE FUNCTION mv_se_ins ()
RETURNS TRIGGER
AS $$
begin
insert into seattle_employees_log values(new.employee_id);
RETURN null;
end;
$$ LANGUAGE PLPGSQL;
CREATE TRIGGER mv_se_employees_ins AFTER
INSERT ON employees FOR EACH ROW EXECUTE
PROCEDURE mv_se_ins();
-- Update Trigger
CREATE OR REPLACE FUNCTION mv_se_upd ()
RETURNS TRIGGER
AS $$
begin
if old.employee_id=new.employee_id then
insert into seattle_employees_log values(new.employee_id);
else
insert into seattle_employees_log values(old.employee_id);
insert into seattle_employees_log values(new.employee_id);
end if;
RETURN null;
end;
$$ LANGUAGE PLPGSQL;
CREATE TRIGGER mv_se_employees_upd AFTER
UPDATE ON employees FOR EACH ROW EXECUTE
PROCEDURE mv_se_upd();
-- Delete Trigger
CREATE OR REPLACE FUNCTION mv_se_del ()
RETURNS TRIGGER
AS $$
begin
insert into seattle_employees_log values(old.employee_id);
RETURN null;
end;
$$ LANGUAGE PLPGSQL;
CREATE TRIGGER mv_se_employees_del AFTER
DELETE ON employees FOR EACH ROW EXECUTE
PROCEDURE mv_se_del();