PostgreSQL - 获取物化视图列元数据

时间:2016-08-27 08:50:36

标签: postgresql

这与Column data types for materialized views?类似,但我需要更多数据(不仅仅是数据类型)。我想对表/视图进行相同类型的查询,但是对于物化视图。

SELECT column_name, data_type, character_maximum_length,
      character_octet_length, numeric_precision, numeric_precision_radix,
     numeric_scale, datetime_precision, interval_type, interval_precision
     FROM information_schema.columns
    WHERE table_schema = '{}'
    AND table_name   = '{}'
    order by ordinal_position

有没有人有类似的东西? pg_attribute中的列名非常神秘。

2 个答案:

答案 0 :(得分:12)

使用psql(" echo hidden queries")选项运行-E时,可以轻松检索此类问题的查询。

以下查询应该执行您想要的操作:

SELECT a.attname,
       pg_catalog.format_type(a.atttypid, a.atttypmod),
       a.attnotnull
FROM pg_attribute a
  JOIN pg_class t on a.attrelid = t.oid
  JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0 
  AND NOT a.attisdropped
  AND t.relname = 'mv_name' --<< replace with the name of the MV 
  AND s.nspname = 'public' --<< change to the schema your MV is in 
ORDER BY a.attnum;

答案 1 :(得分:0)

我今天花了一些时间-正在构建一个元数据视图,该视图显示数据库中的所有架构,表和列。

我需要做一些挖掘工作,以使实现实例化视图的元数据与表或常规视图一样可用(因为information_schema中未包含实现视图),但是到了这里:

SELECT pg_namespace.nspname AS table_schema
    , pg_class.relname AS table_name
    , 'materialized view'::TEXT AS table_type
    , pg_attribute.attname AS column_name
    , pg_attribute.attnum AS ordinal_position
FROM pg_catalog.pg_class
    INNER JOIN pg_catalog.pg_namespace
        ON pg_class.relnamespace = pg_namespace.oid
    INNER JOIN pg_catalog.pg_attribute
        ON pg_class.oid = pg_attribute.attrelid
-- Keeps only materialized views, and non-db/catalog/index columns 
WHERE pg_class.relkind = 'm'
    AND pg_attribute.attnum >= 1
ORDER BY table_schema
    , table_name
    , column_name