After importing data in PostgreSQL, duplicate key value violates unique constraint

后端 未结 4 957
忘了有多久
忘了有多久 2021-02-02 17:51

I recently migrated my rails app to PostgreSQL in order to take advantage of fulltext search.

Since the migration coincided with moving to a new webhost, the steps for m

4条回答
  •  时光取名叫无心
    2021-02-02 18:00

    You can automate wildplasser's solution so that all sequences are synchronized with the current maximum value of their associated column:

    do
    $block$
    declare 
      r        record;
      stmt     text;
      max_id   integer;
    begin
      for r in (
                  select *
                  from (
                    select table_schema, 
                           table_name, 
                           column_name, 
                           pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence
                    from information_schema.columns
                    where table_schema not in ('pg_catalog', 'information_schema')
                  ) t
                  where col_sequence is not null
            ) 
      loop
        stmt := 'select coalesce(max('||r.column_name||'), 0) + 1 from '||r.table_schema||'.'||r.table_name;
        execute stmt into max_id;
        raise notice 'Next ID for %.%.% is %', r.table_schema, r.table_name, r.column_name, max_id;
        perform setval(r.col_sequence, max_id); 
      end loop;
    end;
    $block$
    

    Note that this will only work if the columns have been defined as serial, bigserial or have been made the "owner" of a sequence.

提交回复
热议问题