简体   繁体   English

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

[英]In Postgres 12, how to change PK columns into IDENTITY using dynamic SQL?

So I migrated my database from SQLite to Postgres 12 using pgloader 3.4.1, and for some reason the PK columns across all tables aren't sequential/auto-increment.因此,我使用 pgloader 3.4.1 将我的数据库从 SQLite 迁移到 Postgres 12,并且由于某种原因,所有表中的 PK 列都不是顺序/自动递增的。 They're indexed as NOT NULL (correct) and bigint or int (correct), but they don't contain a default value, so I need to manually change them to IDENTITY type.它们的索引为 NOT NULL(正确)和 bigint 或 int(正确),但它们不包含默认值,因此我需要手动将它们更改为 IDENTITY 类型。

However, I need to leave alone some varchar PK columns.但是,我需要留下一些 varchar PK 列。

So far, I've tried this in psql:到目前为止,我已经在 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;  
$$
;

It spit out "DO," so I assume it must have worked, but when I use \d table_name to view the schema, it still doesn't have a default value.它吐出“DO”,所以我认为它一定有效,但是当我使用\d table_name查看架构时,它仍然没有默认值。

Help please?请帮忙?

The error lies in this line:错误在于这一行:

is_generated = 'NO'

is_generated only takes "ALWAYS" or "NEVER" as values. is_generated 仅将“ALWAYS”或“NEVER”作为值。

I was lucky enough to catch that in the Postgres documentation.我很幸运在 Postgres 文档中发现了这一点。

Hope this helps someone else!希望这对其他人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM