Advertisement
Guest User

Untitled

a guest
Jul 28th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION for_all_schemas(raw_query text) RETURNS integer AS $$
  2. DECLARE
  3. final_statement text;
  4. all_schema_query text;
  5. schema RECORD;
  6. schema_names text[];
  7. name text;
  8. temptable_select text;
  9. temptable_selects text[];
  10.  
  11. BEGIN
  12. -- kill temp tables
  13. DISCARD TEMP;
  14.  
  15. -- get all the schemas
  16. FOR schema IN SELECT DISTINCT subdomain AS tenant FROM public.tenants
  17. LOOP
  18. schema_names := array_append(schema_names, CAST(schema.tenant AS text));
  19. final_statement := 'CREATE TEMPORARY TABLE ' || schema.tenant || '_temptable AS '
  20. || 'SELECT '
  21. || 'CAST(''' || schema.tenant || ''' AS text) AS schema_name, '
  22. || 'q.* FROM ('
  23. || raw_query|| ') AS q';
  24. EXECUTE 'SET search_path = ' || schema.tenant || ', public';
  25. EXECUTE final_statement;
  26. END LOOP;
  27.  
  28. FOREACH name IN ARRAY schema_names
  29. LOOP
  30. temptable_select := 'SELECT * FROM ' || name || '_temptable';
  31. temptable_selects := array_append(temptable_selects, temptable_select);
  32. END LOOP;
  33. final_statement := 'CREATE TEMPORARY TABLE temptable AS ' || array_to_string(temptable_selects, ' UNION ALL ')
  34. || ' ORDER BY schema_name';
  35. EXECUTE final_statement;
  36. RETURN 0;
  37. END;$$ LANGUAGE plpgsql;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement