简体   繁体   中英

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. 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.

However, I need to leave alone some varchar PK columns.

So far, I've tried this in 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.

Help please?

The error lies in this line:

is_generated = 'NO'

is_generated only takes "ALWAYS" or "NEVER" as values.

I was lucky enough to catch that in the Postgres documentation.

Hope this helps someone else!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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