Guest User

Untitled

a guest
Dec 13th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. --
  2. -- Setup - Add plpgsql, create a parent table, create an initial child table,
  3. -- create the trigger and the initial trigger function.
  4. --
  5.  
  6. -- We'll need plpgsql, so create it in your db if it's not already available.
  7. CREATE LANGUAGE plpgsql;
  8.  
  9. -- Create a table to act as parent with the appropriate columns for your data.
  10. CREATE TABLE my_schema.my_data (name varchar(24), create_date timestamp);
  11.  
  12. -- Create an initial child table so that you can create the function/trigger without errors
  13. CREATE TABLE my_schema.my_data_201001
  14. (CHECK (create_date >= '2010-01-01' AND create_date < '2010-02-01'))
  15. INHERITS (my_schema.my_data);
  16. -- Add an index to your child tables.
  17. CREATE INDEX idx_my_data_201001 ON my_schema.my_data_201001 (create_date);
  18.  
  19. -- Create the initial function to handle inserting to child tables
  20. CREATE OR REPLACE FUNCTION my_schema.my_data_insert_trigger_function()
  21. RETURNS TRIGGER AS $$
  22. BEGIN
  23. IF ( NEW.create_date >= '2010-01-01' AND NEW.create_date < '2010-02-01' ) THEN
  24. INSERT INTO my_schema.my_data_201001 VALUES (NEW.*);
  25. ELSE
  26. RAISE EXCEPTION 'Date out of range. Fix parent_insert_trigger_function()!';
  27. END IF;
  28. RETURN NULL;
  29. END;
  30. $$
  31. LANGUAGE plpgsql;
  32.  
  33. -- Create a trigger to call the function before insert.
  34. CREATE TRIGGER my_data_insert_trigger
  35. BEFORE INSERT ON my_schema.my_data
  36. FOR EACH ROW EXECUTE PROCEDURE my_schema.my_data_insert_trigger_function();
  37.  
  38.  
  39. --
  40. -- Notice that: INSERT INTO my_schema.my_data VALUES ('somename','2010-01-10');
  41. -- inserts into the my_data_201001 table.
  42. -- Notice that: INSERT INTO my_schema.my_data VALUES ('somename','2010-02-10');
  43. -- raises an error, and does not insert anything.
  44. -- Notice that: SELECT * FROM my_schema.my_data;
  45. -- returns records from the child tables.
  46. --
Add Comment
Please, Sign In to add comment