pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Dan Lyke <danlyke@flutterby.com>
To: pgsql-sql@postgresql.org
Subject: reinitialize a sequence?
Date: Mon, 4 Dec 2000 15:51:35 -0800 (PST)
Message-ID: <14892.11783.659931.212551@wynand.flutterby.com> (raw)
In-Reply-To: <20001205003034.D31987@erm1.u-strasbg.fr>
References: <20001205003034.D31987@erm1.u-strasbg.fr>

Bruno Boettcher writes:
> is there a simple way to tell all sequences to take the max value +1 of
> their respective tables? (a bit like the vacuum command?)

This is completely gross, but what I've done:


#!/usr/bin/perl -w
use strict;
use DBI;
my ($dbh);
sub BEGIN
{
    $dbh = DBI->connect('DBI:Pg:dbname=xxxx',
			'zzzzzzz',
			'zzzzz')
	or die $DBI::errstr;
}
sub END
{
    $dbh->disconnect;
}


sub UpdateSequenceFor($)
{
    my ($table) = @_;
    my ($sql,$sth,$id,$row);

    $sql = "SELECT max(id) FROM $table";
    $sth = $dbh->prepare($sql) or die $dbh->errstr."\n$sql\n";
    $sth->execute or die $sth->errstr."\n$sql\n";
    if ($id = $sth->fetchrow_arrayref)
    {
	$id = $id->[0];
	$sql = "SELECT nextval('".$table."_id_seq')";
	$sth = $dbh->prepare($sql) or die $dbh->errstr."\n$sql\n";
	$sth->execute or die $sth->errstr."\n$sql\n";
	while (($row = $sth->fetchrow_arrayref) && ($row->[0] < $id))
	{
	    $sth = $dbh->prepare($sql) or die $dbh->errstr."\n$sql\n";
	    $sth->execute or die $sth->errstr."\n$sql\n";
	}
    }
}

# update the sequence for each table:
foreach ('users','blogentries','blogcomments','blogcommenthistory')
{
    UpdateSequenceFor($_);
}



view thread (5+ messages)  latest in thread

Message-ID: <14892.11783.659931.212551@wynand.flutterby.com>
Permalink:  ../14892.11783.659931.212551@wynand.flutterby.com/
Also on:    postgresql.org/message-id/14892.11783.659931.212551@wynand.flutterby.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: danlyke@flutterby.com
  Subject: Re: reinitialize a sequence?
  In-Reply-To: <14892.11783.659931.212551@wynand.flutterby.com>
  References: <20001205003034.D31987@erm1.u-strasbg.fr> <14892.11783.659931.212551@wynand.flutterby.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox