]> git.nbdom.net Git - nb.git/commitdiff
create file
authorNicolas Boisselier <nicolas.boisselier@gmail.com>
Sat, 27 Feb 2016 23:52:14 +0000 (23:52 +0000)
committerNicolas Boisselier <nicolas.boisselier@gmail.com>
Sat, 27 Feb 2016 23:52:14 +0000 (23:52 +0000)
lib/postgres/show_create_table.sql [new file with mode: 0644]

diff --git a/lib/postgres/show_create_table.sql b/lib/postgres/show_create_table.sql
new file mode 100644 (file)
index 0000000..5ac0546
--- /dev/null
@@ -0,0 +1,51 @@
+--
+--
+-- 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
+;