我想将Redshift表转换为JSON,以便可以从此JSON自动生成sql查询。为此我需要数据类型,列名distkey和sortkey,它们在系统表中以某种或其他格式提供。我无法找到的一件事是如何提取红移列的默认值。
有人可以帮我吗?
答案 0 :(得分:0)
Redshift与postgresql几乎相同。使用它,您可以从表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
答案 1 :(得分:0)
这应该回答您的问题: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
;