Created
March 30, 2012 23:37
-
-
Save maxjustus/2257922 to your computer and use it in GitHub Desktop.
Insert to correct Postgres partition dynamically using trigger, create partition automatically if not found.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create or replace function insert_herp_to_derp() | |
returns trigger as $body$ | |
declare | |
name text := 'derp_' || NEW.derp_id || '_herps'; | |
s text; | |
begin | |
-- check that the needed table exists on the database | |
perform 1 | |
from pg_class, pg_namespace | |
where relnamespace = pg_namespace.oid | |
and relkind = 'r'::"char" | |
and relname = name; | |
IF NOT FOUND THEN | |
BEGIN | |
s := 'CREATE TABLE ' || name || ' ( | |
CHECK ( derp_id = ' || NEW.derp_id || ' ) | |
) INHERITS ( herps )'; | |
raise notice 'creating table as [%]', s; | |
EXECUTE s; | |
END; | |
END IF; | |
EXECUTE 'INSERT INTO ' || quote_ident(name) || ' SELECT ($1).*' using NEW; | |
return null; | |
end; | |
$body$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This would be better if I attempted an insert and then rescued the exception if the table doesn't exist, creating it only then. Not sure whether that's possible though.