Advertisement
Guest User

Untitled

a guest
Jan 10th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION remote_db(_table anyelement)
  2. RETURNS SETOF anyelement
  3. AS $func$
  4. DECLARE
  5. _host text := 'ngrok.com'
  6. _port text := '53813'
  7. _user text := 'postgres'
  8. _password text := 'postgres'
  9. _db_name text := 'backup-28-08'
  10. _server text := format('host=%s port=%s user=%s password=%s dbname=%s', _host, _port, _user, _password, _db_name);
  11. _table_name text := pg_typeof(_table);
  12. _dblink_schema text;
  13. _cols_names text;
  14. _remote_schema_query text;
  15. _information_schema text;
  16.  
  17. BEGIN
  18. -- Still unclear about what this does, what a schema is etc.
  19. SELECT nspname INTO _dblink_schema
  20. FROM pg_namespace n, pg_extension e
  21. WHERE e.extname = 'dblink' AND e.extnamespace = n.oid;
  22.  
  23. -- Fetch the remote table information_schema to get column names and types
  24. EXECUTE format(
  25. 'SELECT array_to_string(array_agg(remote_cols.column_name || '' '' || remote_cols.udt_name), '', '')
  26. FROM %I.dblink(%L, %L) AS remote_cols (column_name text, udt_name text)',
  27. _dblink_schema,
  28. _server,
  29. format('SELECT column_name, udt_name FROM information_schema.columns WHERE table_name = ''%s'' ORDER BY ordinal_position', _table_name)
  30. ) INTO _cols2;
  31.  
  32. -- Execute the query itself and returns it
  33. RETURN QUERY EXECUTE format('SELECT (remote::%I).* FROM %I.dblink(%L, %L) AS remote (%s)',
  34. _table_name,
  35. _dblink_schema,
  36. _server,
  37. format('SELECT * FROM %I', _table_name),
  38. _cols_names
  39. );
  40.  
  41.  
  42. END;
  43. $func$ LANGUAGE plpgsql;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement