Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created March 30, 2012 23:37
Show Gist options
  • Save maxjustus/2257922 to your computer and use it in GitHub Desktop.
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.
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;
@maxjustus
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment