Postgres metadata: get a list of all MATERIALIZED VIEW columns, with data type, INCLUDING array columns

All we need is an easy explanation of the problem, so here it is.

I need to get metadata about all MATERIALIZED VIEW columns, including their data type. I can do this with this query:

SELECT 

trim(leading '_' from pg_type.typname) as data_type,
pg_namespace.nspname as schema_name, 
pg_namespace.nspname as udt_name, 
attnum AS ordinal_position,
pg_attribute.attname as column_name,
pg_class.relname as matview_name, 
'-------' AS spacer,
*


from pg_catalog.pg_attribute
join pg_catalog.pg_class ON pg_class.oid = pg_attribute.attrelid
join pg_catalog.pg_namespace ON pg_namespace.oid = pg_class.relnamespace
join pg_catalog.pg_type ON pg_type.typelem = pg_attribute.atttypid
where 
    pg_class.relkind = 'm' AND
    not pg_attribute.attisdropped and 
    cast(pg_type.typanalyze as text) = 'array_typanalyze' and 
    pg_attribute.attnum > 0
order by 
    pg_attribute.attnum

However it doesn’t list any array columns, due to them not existing in the pg_catalog.pg_type table (which is the table I’m getting the data types from).

How can I also get metadata (including type) for array columns too?

I’m using postgres 13.3.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can make your life easier using the format_type() function:

SELECT format_type(att.atttypid, att.atttypmod) as data_type, 
       nsp.nspname as schema_name, 
       att.attnum AS ordinal_position,
       att.attname as column_name,
       mv.relname as matview_name
from pg_catalog.pg_attribute att
  join pg_catalog.pg_class mv ON mv.oid = att.attrelid
  join pg_catalog.pg_namespace nsp ON nsp.oid = mv.relnamespace
where mv.relkind = 'm' 
  AND not att.attisdropped 
  and att.attnum > 0
order by att.attnum

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply