Skip to content

Instantly share code, notes, and snippets.

@vincentdesmares
Created May 11, 2017 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentdesmares/41633ca5f096f5bf8eef6c968d968e22 to your computer and use it in GitHub Desktop.
Save vincentdesmares/41633ca5f096f5bf8eef6c968d968e22 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION run_on_partitions(TEXT, TEXT)
RETURNS INTEGER AS $$ DECLARE partition RECORD;
tablename TEXT = $1;
sql TEXT = $2;
sqlReplaced TEXT;
BEGIN tablename := tablename || '%p';
FOR partition IN SELECT relname :: TEXT AS rel
FROM pg_class
WHERE relname :: TEXT LIKE tablename AND relkind = 't'
ORDER BY relname LOOP sqlReplaced := replace(sql, '', partition.rel);
RAISE NOTICE 'Executing: %', sqlReplaced;
EXECUTE sqlReplaced;
END LOOP;
RETURN 1;
END; $$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment