在Postgres 12中,如何使用动态SQL将PK列更改为IDENTITY?

时间:2020-07-11 04:50:04

标签: sql postgresql postgresql-12

因此,我使用pgloader 3.4.1将数据库从SQLite迁移到Postgres 12,由于某种原因,所有表中的PK列都不是连续的/自动递增的。它们被索引为NOT NULL(正确)和bigint或int(正确),但是它们不包含默认值,因此我需要手动将它们更改为IDENTITY类型。

但是,我需要留下一些varchar PK列。

到目前为止,我已经在psql中尝试过此操作:

do
$$
declare
  l_rec record;
  l_sql text;
  l_table text;
begin
  for l_rec in select table_schema, table_name, column_name, data_type, is_nullable
               from information_schema.columns
               where data_type in ('bigint', 'integer')
                 and is_nullable = 'NO' 
                 and is_generated = 'NO'
                 and is_identity = 'NO'
  loop
    l_sql := format('alter table %I.%I alter %I add generated always as identity', 
                     l_rec.table_schema, 
                     l_rec.table_name, 
                     l_rec.column_name);                 
    execute l_sql;
    l_table := concat(quote_ident(l_rec.table_schema), '.', quote_ident(l_rec.table_name));
    l_sql := format('select setval(pg_get_serial_sequence(%L, %L), max(%I)) from %I.%I', 
                    l_table, 
                    quote_ident(l_rec.column_name), 
                    l_rec.column_name, 
                    l_rec.table_schema, 
                    l_rec.table_name);
    execute l_sql;
  end loop;
end;  
$$
;

它吐出了“ DO”,所以我认为它一定可行,但是当我使用\d table_name查看架构时,它仍然没有默认值。

请帮助?

1 个答案:

答案 0 :(得分:0)

错误在于此行:

is_generated = 'NO'

is_generated仅将“ ALWAYS”或“ NEVER”作为值。

我很幸运地在Postgres文档中发现了这一点。

希望这对其他人有帮助!