如何匹配ID字段与其序列?

时间:2017-05-30 17:27:33

标签: database postgresql metadata

我有一些PK表来自专用序列。不幸的是,我认为其中一个序列被用于两个不同的表两次(以生成ID)。是否可以编写一个返回所有字段的查询(字段名称始终为ID),并使用的序列为这些字段生成默认值?

1 个答案:

答案 0 :(得分:2)

查询列出了与表的id列关联的表名和序列:

select 
    nspname as schema, 
    relname as table,
    trim(substring(pg_get_expr(adbin, adrelid), e'\'.*\''), '''') as sequence
from pg_attribute a
join pg_attrdef d on adrelid = attrelid and adnum = attnum 
join pg_class c on c.oid = attrelid
join pg_namespace n on n.oid = relnamespace
where attname = 'id' and atthasdef
and left(pg_get_expr(adbin, adrelid), 7) = 'nextval';

 schema |    table     |      sequence       
--------+--------------+---------------------
 public | test_table   | test_table_id_seq
 public | log          | log_id_seq
 public | master       | master_id_seq
 public | details      | details_id_seq
 ...

您可以跳过条件attname = 'id'。查询查找具有函数nextval()作为默认表达式的列,例如:

select 
    nspname as schema, 
    relname as table,
    attname as column,
    trim(substring(pg_get_expr(adbin, adrelid), e'\'.*\''), '''') as sequence
from pg_attribute a
join pg_attrdef d on adrelid = attrelid and adnum = attnum 
join pg_class c on c.oid = attrelid
join pg_namespace n on n.oid = relnamespace
where atthasdef
and left(pg_get_expr(adbin, adrelid), 7) = 'nextval';

 schema |    table     |  column   |       sequence        
--------+--------------+-----------+-----------------------
 public | test_table   | id        | test_table_id_seq
 public | log          | id        | log_id_seq
 public | wallets      | wallet_id | wallets_wallet_id_seq
 public | master       | id        | master_id_seq
 public | details      | id        | details_id_seq
 ...