]> begriffs open source - ai-pg/blob - full-docs/txt/event-trigger-table-rewrite-example.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / event-trigger-table-rewrite-example.txt
1
2 38.4. A Table Rewrite Event Trigger Example #
3
4    Thanks to the table_rewrite event, it is possible to implement a table
5    rewriting policy only allowing the rewrite in maintenance windows.
6
7    Here's an example implementing such a policy.
8 CREATE OR REPLACE FUNCTION no_rewrite()
9  RETURNS event_trigger
10  LANGUAGE plpgsql AS
11 $$
12 ---
13 --- Implement local Table Rewriting policy:
14 ---   public.foo is not allowed rewriting, ever
15 ---   other tables are only allowed rewriting between 1am and 6am
16 ---   unless they have more than 100 blocks
17 ---
18 DECLARE
19   table_oid oid := pg_event_trigger_table_rewrite_oid();
20   current_hour integer := extract('hour' from current_time);
21   pages integer;
22   max_pages integer := 100;
23 BEGIN
24   IF pg_event_trigger_table_rewrite_oid() = 'public.foo'::regclass
25   THEN
26         RAISE EXCEPTION 'you''re not allowed to rewrite the table %',
27                         table_oid::regclass;
28   END IF;
29
30   SELECT INTO pages relpages FROM pg_class WHERE oid = table_oid;
31   IF pages > max_pages
32   THEN
33         RAISE EXCEPTION 'rewrites only allowed for table with less than % pages'
34 ,
35                         max_pages;
36   END IF;
37
38   IF current_hour NOT BETWEEN 1 AND 6
39   THEN
40         RAISE EXCEPTION 'rewrites only allowed between 1am and 6am';
41   END IF;
42 END;
43 $$;
44
45 CREATE EVENT TRIGGER no_rewrite_allowed
46                   ON table_rewrite
47    EXECUTE FUNCTION no_rewrite();