Re: all serial type was changed to 1

From: Max Wang <mwang(at)1080agile(dot)com>
To: David Rowley <david(dot)rowley(at)2ndquadrant(dot)com>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: all serial type was changed to 1
Date: 2017-05-01 23:07:45
Message-ID: ME1PR01MB13948CFE3CEDC3EC627B58F0A8140@ME1PR01MB1394.ausprd01.prod.outlook.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi David,

Thanks for suggestion. We use PostgreSQL 9.5. And we did not import or bulk loaded data to these tables.

Regards,
Max

-----Original Message-----
From: David Rowley [mailto:david(dot)rowley(at)2ndquadrant(dot)com]
Sent: Monday, 1 May 2017 11:05 PM
To: Max Wang <mwang(at)1080agile(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: [GENERAL] all serial type was changed to 1

On 1 May 2017 at 17:51, Max Wang <mwang(at)1080agile(dot)com> wrote:
> We have a PostgreSQL database. There are 26 tables and we use serial
> type as primary key. We had a insert error as “duplicate key value
> violates unique constraint, DETAIL: Key (id)=(1) already exists.” one
> weeks ago. I checked and found all tables’ id were reset to 1.

Sounds like something that might happen if you'd just bulk loaded the data and didn't set the sequences.

If you really did use serial types then you could set all these to the max value of the column which they belong to.

The following will give you a list of commands to execute:

SELECT 'select setval(''' || c.relname || ''', max(' ||
quote_ident(a.attname) || ')) from ' || d.refobjid::regclass || ';'
FROM pg_depend d
INNER JOIN pg_class c ON d.objid = c.oid INNER JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid WHERE c.relkind = 'S' AND d.refclassid = 1259;

You may like to check that returns 26 rows as you expect and verify that all those sequences do need reset before running the command.

If you're running Postgres 9.6 and using psql, you can execute the above then execute \gexec which will execute the previous result set as commands.

--
David Rowley http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Max Wang 2017-05-01 23:08:30 Re: all serial type was changed to 1
Previous Message John R Pierce 2017-05-01 22:33:43 Re: Compatibility of libpg