Is there any shortcut for using dblink in Postgres?

后端 未结 2 683
孤城傲影
孤城傲影 2021-01-03 02:22

In Postgres, you can link to your other databases using dblink, but the syntax is very verbose. For example you can do:

SELECT *
FROM dblink (
         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 03:09

    You can wrap connection parameters in a FOREIGN SERVER object like @Peter explains, but you'd still have to spell out the rest.

    You can encapsulate everything in a view or function, so you type it only once. Example with a function - Run as superuser:

    CREATE OR REPLACE FUNCTION f_lnk_tbl()
      RETURNS TABLE(tbl_id int, col1 text, log_ts timestamp) AS
    $BODY$
    
    SELECT *
      FROM dblink(
      'SELECT tbl_id, col1, log_ts
       FROM   tbl
       ORDER  BY tbl_id'::text) AS b(
     tbl_id int
    ,col1   text
    ,log_ts timestamp);
    
    $BODY$ LANGUAGE sql STABLE SECURITY DEFINER;
    REVOKE ALL ON FUNCTION f_lnk_tbl() FROM public;
    
    
    CREATE OR REPLACE FUNCTION f_sync()
      RETURNS text AS
    $BODY$
    
    SELECT dblink_connect('hostaddr=123.123.123.123 port=5432 dbname=mydb
                           user=postgres password=*secret*');
    
    INSERT INTO my_local_tbl SELECT * FROM f_lnk_tbl();
    -- more tables?
    
    SELECT dblink_disconnect();
    
    $BODY$
      LANGUAGE sql VOLATILE SECURITY DEFINER;
    REVOKE ALL ON FUNCTION blob.f_dbsync() FROM public;
    -- GRANT ....;
    

提交回复
热议问题