amazon redshift 中存储的特定行的默认值在哪里?

Where are default values for a particular row stored in amazon redshift?

我想将 Redshift table 转换为 JSON,以便 sql 查询可以从这个 JSON 自动生成。为此,我需要数据类型、列名 distkey 和 sortkey,它们在系统 tables 中以某种或其他格式提供。我找不到的一件事是如何提取红移列的默认值。

谁能帮我解决这个问题?

Redshift 与 postgresql 几乎相同。使用它,您可以从 table INFORMATION_SCHEMA.COLUMNS.

中获取列的默认值

我在postgre里查过了:

create table test_tbl (n int DEFAULT 100500);

select table_name, column_name, column_default from INFORMATION_SCHEMA.COLUMNS where table_name = 'test_tbl';

 table_name | column_name | column_default 
------------+-------------+----------------
 test_tbl   | n           | 100500

这应该可以回答您的问题:Get the default values of table columns in Postgres?

总结:

如果您只有一个模式,

INFORMATION_SCHEMA.COLUMNS 效果很好。如果您有多个跨模式同名的表,它会变得更加棘手。

这适用于所有情况:

SELECT d.adsrc AS default_value
FROM   pg_catalog.pg_attribute a
LEFT   JOIN pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum)
                                     = (d.adrelid,  d.adnum)
WHERE  NOT a.attisdropped   -- no dropped (dead) columns
AND    a.attnum > 0         -- no system columns
AND    a.attrelid = 'myschema.mytable'::regclass
AND    a.attname = 'mycolumn';

我在生产中使用了一个稍微不同的版本来获取类型(以及每列适当的长度):

SELECT
            pg_namespace.nspname AS schema_name,
            pg_class.relname AS table_name,
            pg_attribute.attname AS column_name,
            pg_type.typname AS type,
            pg_attribute.atttypmod AS column_len,
            pg_attrdef.adsrc AS column_default
FROM
            pg_class
INNER JOIN
            pg_namespace
            ON pg_class.relnamespace = pg_namespace.oid
INNER JOIN
            pg_attribute
            ON pg_class.oid = pg_attribute.attrelid
INNER JOIN
            pg_type
            ON pg_attribute.atttypid = pg_type.oid
LEFT JOIN 
            pg_attrdef  
            ON pg_attribute.attrelid = pg_attrdef.adrelid
            AND pg_attribute.attnum = pg_attrdef.adnum
WHERE
            pg_class.relname = 'table_name'
            AND pg_namespace.nspname = 'schema_name'
            AND pg_type.typname NOT IN ('oid','xid','tid','cid')
            AND pg_attribute.attnum >= 0
ORDER BY
            pg_attribute.attnum ASC
;