因此,我目前正在创建一些SQL来阅读postgres(9.1)目录以构建表定义。但是,我遇到了SERIAL / BIGSERIAL数据类型的问题。
例:
CREATE TABLE cruft.temp ( id BIGSERIAL PRIMARY KEY );
SELECT * FROM information_schema.columns WHERE table_schema='cruft' AND table_name='temp';
"db","cruft","temp","id",1,"nextval('cruft.temp_id_seq'::regclass)","NO","bigint",,,64,2,0,,,,,,,,,,,,,"db","pg_catalog","int8",,,,,"1","NO","NO",,,,,,,"NEVER",,"YES"
它提供了数据库名称(db),模式名称(cruft),表名称(temp),列名称(id),默认值(nextval(...))和数据类型(bigint和int8 .. NOT bigserial)。 ...我意识到我可以检查默认值是否为序列-但我不认为这是100%准确的,因为我可以手动创建一个序列并创建一个默认值是那个顺序。
有人对我如何做到这一点有建议吗?除了检查nextval(* _ seq)的默认值之外,没有其他功能吗?
针对TL; DR或不熟悉pg_catalog的新用户在此处添加的SQL解决方案进行了编辑:
with sequences as (
select oid, relname as sequencename from pg_class where relkind = 'S'
) select
sch.nspname as schemaname, tab.relname as tablename, col.attname as columnname, col.attnum as columnnumber, seqs.sequencename
from pg_attribute col
join pg_class tab on col.attrelid = tab.oid
join pg_namespace sch on tab.relnamespace = sch.oid
left join pg_attrdef def on tab.oid = def.adrelid and col.attnum = def.adnum
left join pg_depend deps on def.oid = deps.objid and deps.deptype = 'n'
left join sequences seqs on deps.refobjid = seqs.oid
where sch.nspname != 'information_schema' and sch.nspname not like 'pg_%' -- won't work if you have user schemas matching pg_
and col.attnum > 0
and seqs.sequencename is not null -- TO ONLY VIEW SERIAL/BIGSERIAL COLUMNS
order by sch.nspname, tab.relname, col.attnum;