4thdoctor_scarf

Get the column metadata

Nov 28th, 2017
3,233
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. SELECT
  2.     col.attname as column_name,
  3.     (
  4.         SELECT
  5.             pg_catalog.pg_get_expr(def.adbin, def.adrelid)
  6.         FROM
  7.             pg_catalog.pg_attrdef def
  8.         WHERE
  9.                 def.adrelid = col.attrelid
  10.             AND def.adnum = col.attnum
  11.             AND col.atthasdef
  12.     ) as column_default,
  13.     col.attnum as ordinal_position,
  14.     CASE
  15.         WHEN typ.typcategory ='E'
  16.         THEN
  17.             'enum'
  18.         WHEN typ.typcategory='C'
  19.         THEN
  20.             'composite'
  21.        
  22.     ELSE
  23.         pg_catalog.format_type(col.atttypid, col.atttypmod)
  24.     END
  25.     AS type_format,
  26.     (
  27.         SELECT
  28.             pg_get_serial_sequence(format('%I.%I',tabsch.nspname,tab.relname), col.attname) IS NOT NULL
  29.         FROM
  30.             pg_catalog.pg_class tab
  31.             INNER JOIN pg_catalog.pg_namespace tabsch
  32.             ON  tab.relnamespace=tabsch.oid
  33.         WHERE
  34.             tab.oid=col.attrelid
  35.     ) as col_serial,
  36.    
  37.  
  38.    
  39.     typ.typcategory as type_category,
  40.     CASE
  41.         WHEN typ.typcategory='E'
  42.         THEN
  43.         (
  44.             SELECT
  45.                 string_agg(quote_literal(enumlabel),',')
  46.             FROM
  47.                 pg_catalog.pg_enum enm
  48.             WHERE enm.enumtypid=typ.oid
  49.         )
  50.         WHEN typ.typcategory='C'
  51.         THEN
  52.         (
  53.             SELECT
  54.                 string_agg(
  55.                     format('%I %s',
  56.                         attname,
  57.                         pg_catalog.format_type(atttypid, atttypmod)
  58.                     )
  59.                 ,
  60.                 ','
  61.                 )    
  62.             FROM
  63.                 pg_catalog.pg_attribute
  64.             WHERE
  65.                 attrelid=format(
  66.                     '%I.%I',
  67.                     sch.nspname,
  68.                     typ.typname)::regclass
  69.                 )
  70.     END AS typ_elements,
  71.     col.attnotnull as not_null
  72. FROM
  73.     pg_catalog.pg_attribute col
  74.     INNER JOIN pg_catalog.pg_type typ
  75.         ON  col.atttypid=typ.oid
  76.     INNER JOIN pg_catalog.pg_namespace sch
  77.         ON typ.typnamespace=sch.oid
  78. WHERE
  79.         col.attrelid = 'foo.bar'::regclass  --this is used to filter the table's name
  80.     AND NOT col.attisdropped
  81.     AND col.attnum>0
  82. ORDER BY
  83.     col.attnum
  84. ;
Advertisement