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
|
# File 'lib/temporal_tables/connection_adapters/postgresql_adapter.rb', line 10
def create_temporal_triggers(table_name)
column_names = columns(table_name).map(&:name)
execute %{
create or replace function #{table_name}_ai() returns trigger as $#{table_name}_ai$
declare
cur_time timestamp without time zone;
begin
cur_time := localtimestamp;
insert into #{temporal_name(table_name)} (#{column_list(column_names)}, eff_from)
values (#{column_names.collect {|c| "new.#{c}"}.join(', ')}, cur_time);
return null;
end
$#{table_name}_ai$ language plpgsql;
drop trigger if exists #{table_name}_ai on #{table_name};
create trigger #{table_name}_ai after insert on #{table_name}
for each row execute procedure #{table_name}_ai();
}
execute %{
create or replace function #{table_name}_au() returns trigger as $#{table_name}_au$
declare
cur_time timestamp without time zone;
begin
cur_time := localtimestamp;
update #{temporal_name(table_name)} set eff_to = cur_time
where id = new.id
and eff_to = '9999-12-31';
insert into #{temporal_name(table_name)} (#{column_list(column_names)}, eff_from)
values (#{column_names.collect {|c| "new.#{c}"}.join(', ')}, cur_time);
return null;
end
$#{table_name}_au$ language plpgsql;
drop trigger if exists #{table_name}_au on #{table_name};
create trigger #{table_name}_au after update on #{table_name}
for each row execute procedure #{table_name}_au();
}
execute %{
create or replace function #{table_name}_ad() returns trigger as $#{table_name}_ad$
declare
cur_time timestamp without time zone;
begin
cur_time := localtimestamp;
update #{temporal_name(table_name)} set eff_to = cur_time
where id = old.id
and eff_to = '9999-12-31';
return null;
end
$#{table_name}_ad$ language plpgsql;
drop trigger if exists #{table_name}_ad on #{table_name};
create trigger #{table_name}_ad after delete on #{table_name}
for each row execute procedure #{table_name}_ad();
}
end
|