如何反省物化视图

时间:2013-10-01 23:15:24

标签: postgresql materialized-views information-schema postgresql-9.3

我有一个实用程序,它使用:

来内省表的列
select column_name, data_type from information_schema.columns
        where table_name=%s

如何将此扩展到物化视图的内省列?

2 个答案:

答案 0 :(得分:11)

您的查询存在一些缺点/改进空间:

  • 数据库中的表名是不唯一,您必须缩小到特定架构,否则可能会出现令人惊讶/误导/完全错误的结果。
    将(可选)模式限定的表名转换为regclass更有效/方便...见下文。

  • 转换为regtype会为您提供通用类型名称而不是内部名称。但那仍然只是基本类型 请使用the system catalog information functions format_type()来获取包含修饰符的确切类型名称。

  • 通过上述改进,您无需加入其他表。只需pg_attribute

  • 删除的列驻留在目录中,直到表被抽真空(完全)。你需要排除这些。

SELECT attname, atttypid::regtype AS base_type
              , format_type(atttypid, atttypmod) AS full_type
FROM   pg_attribute
WHERE  attrelid = 'myschema.mytable'::regclass
AND    attnum > 0
AND    NOT attisdropped;  -- no dead columns

暂且不说:information schema中的观点仅适用于标准合规性和可移植性(无论如何都很少有效)。如果您不打算切换RDBMS,请坚持使用快速 的目录表 - 并且显然更完整。

答案 1 :(得分:3)

似乎postgres 9.3已将物化视图从information_schema中删除。 (请参阅http://postgresql.1045698.n5.nabble.com/Re-Materialized-views-WIP-patch-td5740513i40.html进行讨论。)

以下内容适用于内省:

select attname, typname 
from pg_attribute a 
join pg_class c on a.attrelid = c.oid 
join pg_type t on a.atttypid = t.oid
where relname = %s and attnum >= 1;

子句attnum >= 1抑制系统列。我猜这种类型的名称是pg_specific,但对我的目的来说足够好了。