16

I am using dblink to move certain data between databases. Everything is save and sound but I am wondering if there is a more convenient way to define the column definition list of a dblink query result. I can do something like this:

SELECT *
FROM dblink('dbname=remote', 'select * from test')
AS t1(id integer, data text); 

The tables I'm interacting with have the same schema definition in both databases (remote & local). I was thinking of something like:

SELECT *
FROM dblink('dbname=remote', 'select * from test')
AS t1 LIKE public.test; 

Or:

SELECT *
FROM dblink('dbname=remote', 'select * from test')
AS t1::public.test;

The column definition list tends to become quite long. Is there something I may have overlooked?

EDIT:

As this has been a problem for me before I created a small function as a work-around.

CREATE OR REPLACE FUNCTION dblink_star_func(_conn text, _schema_name text, _table_name text)
RETURNS text
LANGUAGE PLPGSQL
VOLATILE STRICT
AS $function$
    DECLARE       
        _dblink_schema text;
        _cols          text; 
        _q             text;
        _func_name     text := format('star_%s', $3);
        _func          text;        
    BEGIN
        SELECT nspname INTO _dblink_schema
        FROM pg_namespace n, pg_extension e
        WHERE e.extname = 'dblink' AND e.extnamespace = n.oid;

        SELECT array_to_string(array_agg(column_name || ' ' || udt_name), ', ') INTO _cols
        FROM information_schema.columns
        WHERE table_schema = $2 AND table_name = $3;

        _q := format('SELECT * FROM %I.dblink(%L, %L) AS remote (%s)',
            _dblink_schema,
            _conn,
            format('SELECT * FROM %I.%I', $2, $3),
            _cols
        );

        _func := $_func$
            CREATE OR REPLACE FUNCTION %s()
            RETURNS SETOF %I.%I
            LANGUAGE SQL
            VOLATILE STRICT
            AS $$ %s; $$
        $_func$;

        EXECUTE format(_func, _func_name, $2, $3, _q);

        RETURN _func_name;
    END;
$function$;

This function creates and yields a function that wraps the dblink call. It's certainly not meant for heavy lifting but convenience.It would be nice if it turns out it's not necessary at all.

> select dblink_star_func('dbname=ben', 'public', 'test');
┌──────────────────┐
│ dblink_star_func │
├──────────────────┤
│ star_test        │
└──────────────────┘
(1 row)

> select * from star_test() where data = 'success';
┌────┬─────────┐
│ id │  data   │
├────┼─────────┤
│  1 │ success │
└────┴─────────┘
(1 row)
2
  • I need your help. I'm trying to do what you initially asked but I'm can't find my way... Sep 4, 2014 at 16:04
  • I'm strugling to make a version of your awesome code without intermediary function (dblink_star_func), to being able to query select * from select_remote('dbname=ben', 'public', 'test') where data = 'success'; straight away. Could you have a look at my question there: stackoverflow.com/questions/25691511/… ? Thanks Sep 5, 2014 at 18:06

3 Answers 3

17

Try something like this :

select (rec).* from dblink('dbname=...','select myalias from foreign_table
  myalias') t1 (rec local_type)

Example (get tables stats from other database) :

select (rec).* from dblink('dbname=foreignDb','select t1 from
  pg_stat_all_tables t1') t2 (rec pg_stat_all_tables)
3

You might need to make sure that your types are always in sync but this should work:

SELECT (t1::test).* 
  FROM dblink('dbname=remote', 'select * from test') AS t1;

The key is that often you need parentheses to ensure that the parser knows you are dealing with tuples.

For example this works for me:

 CREATE TABLE test (id int, test bool);
 select (t1::test).* from (select 1, true) t1;

But this throws a syntax error:

 select t1::test.* from (select 1, true) t1;
3
  • 7
    It doesn't work in dblink (Postgres 9.1). Throws the error a column definition list is required for functions returning "record"
    – ADTC
    Apr 15, 2014 at 6:45
  • @ADTC Funny thing I came here because change from dblink function to dblink_connect and now isnt working. Jul 15, 2016 at 20:38
  • See the solution of @Rémy Baron below. That works in Postgres 9.6.
    – kirikaza
    Sep 22, 2017 at 11:01
1
--You can make column names of table as a string and then apply it in your dblink.

Do $do$

Declare column_list text;

Begin

column_list := (Select array_to_string(Array(Select concat(column_name,' ',data_type) from information_schema.columns where table_name='type_a1'),','));

Execute format ($$ Insert into type_a1 Select * from dblink('host=localhost user=postgres password=1234 dbname=Test','Select * from type_b1')as linktable(%s);$$,column_list);

end;

$do$
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jul 12, 2022 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.