Re: FW: Creating database links

From: Stephen Frost <sfrost(at)snowman(dot)net>
To: "Ferrell, Denise CTR NSWCDD, Z11" <denise(dot)ferrell(dot)ctr(at)navy(dot)mil>
Cc: "pgsql-admin(at)postgresql(dot)org" <pgsql-admin(at)postgresql(dot)org>
Subject: Re: FW: Creating database links
Date: 2014-10-03 18:01:28
Message-ID: 20141003180128.GO28859@tamriel.snowman.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

Denise,

* Ferrell, Denise CTR NSWCDD, Z11 (denise(dot)ferrell(dot)ctr(at)navy(dot)mil) wrote:
> What would be the syntax for extracting all columns from a database table using dblink? Could this be used if you are unsure of the structure of the table you're extracting from?

To grab all columns from a remote table, you could use:

select row_to_json(apples) from apples;

This would return a json blob, but unfortunately you can't trivially
convert that into a record at this time. You could turn it into a set
of key/value pairs though:

select
b.*
from (select row_to_json(data.*) from data) as a,
lateral json_each(a.row_to_json) as b;

You could write a PL/pgsql procedure to query the remote catalog and
determine what the columns are and create the view using dblink
accordingly too.

To get the columns for a database table, you can query pg_attribute,
with pg_class, like so:

-- Get the column names for the 'apples' table
-- attnum > 0 avoids internal PG columns
select
attname
from
pg_attribute
join pg_class on (attrelid = oid)
where relname = 'apples'
and attnum > 0;

You would need to include pg_namespace if you might have an 'apples'
table in multiple schemas.

What would probably be interesting to you also is the new IMPORT FOREIGN
SCHEMA capability which was recently added to PG and will be in
PostgreSQL 9.5:

http://www.postgresql.org/docs/devel/static/sql-importforeignschema.html

Or, perhaps, just using the postgres_fdw and foreign data tables instead
of using dblink at all might work.

Thanks!

Stephen

In response to

Browse pgsql-admin by date

  From Date Subject
Next Message Stephen Frost 2014-10-03 18:10:59 Re: PostgreSQL Tool
Previous Message Scott Ribe 2014-10-03 17:15:13 Re: Backup error