迁移postgres数据库的时候,有时候会出现序列与数据库值不匹配的现象.参考了https://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync之后,
改写了一下脚本,执行后可正常使用了.
1 do --check seq not in sync 2 $$ 3 declare 4 _r record; 5 _i bigint; 6 _m bigint; 7 begin 8 for _r in ( 9 Select 10 DISTINCT(constraint_column_usage.table_name) as tablename, 11 constraint_column_usage.column_name as idname, 12 replace(replace(columns.column_default,‘‘‘::regclass)‘,‘‘),‘nextval(‘‘‘,‘‘) as seqname, 13 columns.table_schema as schamename 14 from information_schema.constraint_column_usage, information_schema.columns 15 where constraint_column_usage.table_schema =‘public‘ AND 16 columns.table_schema = ‘public‘ AND columns.table_name=constraint_column_usage.table_name 17 AND constraint_column_usage.column_name = columns.column_name 18 AND columns.column_default is not null 19 ) loop 20 execute format(‘select last_value from %I.%s‘,_r.schamename,_r.seqname) into _i; 21 execute format(‘select max(%I) from %I.%I‘,_r.idname,_r.schamename,_r.tablename) into _m; 22 if coalesce(_m,0) > _i then 23 raise info ‘%‘,concat(‘changed: ‘,_r.tablename||‘_Id_seq‘,‘ from:‘,_i,‘ to:‘,_m); 24 execute format(‘alter sequence %I.%I restart with %s‘,_r.schamename,_r.seqname,_m); 25 end if; 26 end loop; 27 28 end; 29 $$ 30 ;
使用的时候根据实际情况修改一下 schema的值就好
原文地址:https://www.cnblogs.com/Raspberry-zx/p/12702310.html
时间: 2024-10-28 19:54:57