[英]In Postgres 12, how to change PK columns into IDENTITY using dynamic SQL?
因此,我使用 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
查看架構時,它仍然沒有默認值。
請幫忙?
錯誤在於這一行:
is_generated = 'NO'
is_generated 僅將“ALWAYS”或“NEVER”作為值。
我很幸運在 Postgres 文檔中發現了這一點。
希望這對其他人有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.