Wednesday, October 2, 2013

PostgreSQL : Move your stuff out of the public schema

Using the default public schema is not recommended. If you have created a bunch of tables and functions in the public schema, you can use the following scripts to move them to a different schema:

Move tables:
  DO$$   
  DECLARE   
   row record;   
  BEGIN   
   FOR row IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'   
   LOOP   
    EXECUTE 'ALTER TABLE public.' || quote_ident(row.tablename) || ' SET SCHEMA [new_schema];';   
   END LOOP;   
  END;$$;  

Move functions:
  DO  
 $do$  
 DECLARE  
   sql text;  
 BEGIN  
   SELECT INTO sql  
      string_agg(format('ALTER FUNCTION public.%I(%s) SET SCHEMA new_schema;'  
           ,p.proname, pg_get_function_identity_arguments(p.oid)), E'\n')  
   FROM  pg_proc p  
   JOIN  pg_namespace n ON n.oid = p.pronamespace  
   WHERE nspname = 'public';  
    -- and other conditions, if needed  
   RAISE NOTICE '%', sql; -- for viewing the sql before executing it  
   -- EXECUTE sql; -- for executing the sql  
 END  
 $do$  

No comments:

Post a Comment