pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Thomas Kellerer <shammat@gmx.net>
To: pgsql-general@lists.postgresql.org
Subject: Re: checking existence of a table before updating its SERIAL
Date: Mon, 8 Jun 2020 10:18:41 +0200
Message-ID: <3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net> (raw)
In-Reply-To: <20200608075358.GA17471@sh4-5.1blu.de>
References: <20200608075358.GA17471@sh4-5.1blu.de>

Matthias Apitz schrieb am 08.06.2020 um 09:53:
> We're updating the SERIAL of a bunch of tables with a SQL script which
> does for any table:
>
> /* table: idm_tasktab */
> DO $$
> DECLARE
>   max_id int;
> BEGIN
>   SELECT INTO max_id GREATEST(COALESCE(max(taskid), 0),0) + 1 FROM idm_tasktab;
>   RAISE NOTICE '% % %', 'idm_tasktab', 'taskid', max_id ;
>   EXECUTE 'ALTER SEQUENCE idm_tasktab_taskid_seq RESTART ' || max_id::text;
> END $$ LANGUAGE plpgsql;
>
> Can some kind soul help me with doing a test for the existence of the
> table to avoid the error message about non existing relation?


I think the easiest way is to use to_regclass():

DO $$
DECLARE
  max_id int;
BEGIN
  if to_regclass('idm_tasktab') is not null then
    SELECT INTO max_id GREATEST(COALESCE(max(taskid), 0),0) + 1 FROM idm_tasktab;
    RAISE NOTICE '% % %', 'idm_tasktab', 'taskid', max_id ;
    EXECUTE 'ALTER SEQUENCE idm_tasktab_taskid_seq RESTART ' || max_id::text;
  end if;
END $$ LANGUAGE plpgsql;

Note that you don't really need dynamic SQL for this, you can simplify this to:

  select setval('idm_tasktab_taskid_seq', GREATEST(COALESCE(max(taskid), 0),0))
  from idm_tasktab;


I also don't think greatest() is necessary.

Thomas





view thread (3+ messages)

Message-ID: <3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net>
Permalink:  ../3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net/
Also on:    postgresql.org/message-id/3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net

 · 

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-general@postgresql.org
  Cc: shammat@gmx.net
  Subject: Re: checking existence of a table before updating its SERIAL
  In-Reply-To: <3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net>
  References: <20200608075358.GA17471@sh4-5.1blu.de> <3be8b9bc-70ce-ed6b-c47b-0544e42be925@gmx.net>

* 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