Re: update sequence conversion script - Mailing list pgsql-general

From Richard Huxton
Subject Re: update sequence conversion script
Date
Msg-id 416A5236.4020306@archonet.com
Whole thread Raw
In response to update sequence conversion script  (Sim Zacks <sim@compulab.co.il>)
Responses Re: update sequence conversion script  (Terry Lee Tucker <terry@esc1.com>)
Re: update sequence conversion script  (Michael Fuhr <mike@fuhr.org>)
List pgsql-general
Sim Zacks wrote:
> I am in the process of converting an existing database to PostGreSQL
> and wrote a generic script to update all of the sequences as they default at 1.
> I thought it would be useful to other people who are converting their
> databases.

Very nice.

> create or replace function UpdateSequences() returns varchar(50) as
> $$

For those that are puzzled, 8.0 allows you to use "dollar quoting" so
you can avoid \'\'\' in your plpgsql functions.

> declare
>         seqrecord record;
>         tblname varchar(50);
>         fieldname varchar(50);
>         maxrecord record;
>         maxvalue integer;
> begin
>         for seqrecord in select relname from pg_statio_user_sequences Loop
>                 tblname:=split_part(seqrecord.relname,'_',1);
>                 fieldname:=split_part(seqrecord.relname,'_',2);
>                 for maxrecord in execute 'select max(' || fieldname || ') as f1 from ' || tblname LOOP
>                         maxvalue:=maxrecord.f1;
>                 end loop;
>                 execute 'alter sequence ' || seqrecord.relname || ' restart with ' || coalesce(maxvalue,0)+1 ;

One thing you might want to test is what happens when you manually
create a sequence separate from a table, i.e. no such table-name exists.

Also, you can have more than one table relying on a single sequence (and
I have in one of my systems). Not sure there's anything useful you can
do in such a case, or how you'd detect such a situation.

--
   Richard Huxton
   Archonet Ltd

pgsql-general by date:

Previous
From: "Armen Rizal"
Date:
Subject: Reusable pl/pgsql samples ?
Next
From: Terry Lee Tucker
Date:
Subject: Re: update sequence conversion script