ดังนั้นตอนนี้ฉันกำลังสร้าง 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), ชื่อ schema (cruft), ชื่อตาราง (temp), ชื่อคอลัมน์ (id), ค่าเริ่มต้น (nextval (... )), และชนิดข้อมูล (bigint และ int8 .. ไม่ใหญ่มาก) ... ฉันรู้ว่าฉันสามารถตรวจสอบเพื่อดูว่าค่าเริ่มต้นเป็นลำดับ - แต่ฉันไม่เชื่อว่าจะถูกต้อง 100% เนื่องจากฉันสามารถสร้างลำดับด้วยตนเองและสร้างคอลัมน์อนุกรมที่ไม่ใช่ค่าเริ่มต้น ลำดับนั้น
ใครบ้างมีข้อเสนอแนะสำหรับวิธีฉันอาจบรรลุนี้ มีอะไรนอกเหนือจากการตรวจสอบค่าเริ่มต้นสำหรับ nextval (* _ seq) หรือไม่
แก้ไขสำหรับโซลูชัน SQL ที่เพิ่มที่นี่ในกรณีของ TL; DR หรือผู้ใช้ใหม่ที่ไม่คุ้นเคยกับ pg_catalog:
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;