February 27, 2016
Problem solved ! Here is a pure sql solution, how to get all sql from all tables in Postgres:
--
--
-- NB 27.02.16
-- List sql tables
-- show_create_table()
--
--
SELECT
'CREATE TABLE '||sql.table||'('
||array_to_string(array_agg(sql),', ')
||')' as sql
FROM (
(
SELECT -- FIELDS
c.oid AS id
,c.relname as table
,9 as prio
,''
|| f.attname
|| ' ' || pg_catalog.format_type(f.atttypid,f.atttypmod)
||CASE WHEN f.attnotnull THEN ' NOT NULL' ELSE '' END
||CASE WHEN f.atthasdef = 't' AND d.adsrc !=''THEN ' DEFAULT '||d.adsrc ELSE '' END
AS sql
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
WHERE c.relkind = 'r'::char
AND f.attnum > 0
ORDER BY f.attnum
) UNION (
SELECT -- CONSTRAINTS
c.oid as id
,c.relname as table
,0 as prio
,CASE
WHEN p.contype = 'p' THEN 'PRIMARY KEY'
WHEN p.contype = 'u' THEN 'UNIQ'
ELSE '' END
||'('||array_to_string(array_agg(f.attname),', ')||')' AS sql
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
WHERE c.relkind = 'r'::char
AND f.attnum > 0
AND p.contype IN ('u','p')
GROUP BY c.oid,p.contype,f.attrelid,c.relname
ORDER BY c.oid,f.attrelid
)
ORDER BY prio DESC) sql
GROUP BY sql.id,sql.table
;