问题
I use this to create auto-incremented id columns:
id BIGSERIAL -- psql
id BIGINT GENERATED BY DEFAULT AS IDENTITY -- hsql
Now in unit tests i'd like to reset those sequences between tests.
Is this possible? I target PostgreSQL and HSQLDB
回答1:
TRUNCATE table RESTART IDENTITY;
http://www.postgresql.org/docs/9.2/static/sql-truncate.html
http://hsqldb.org/doc/guide/dataaccess-chapt.html#dac_truncate_statement
回答2:
For PostgreSQL, you can use the pg_get_serial_sequence
function to discover the name of the underlying sequence used to maintain the auto-increment, and the setval
function to then manipulate it, e.g. to make the sequence match the highest value in the table after manually inserting or deleting rows:
Select setval(
pg_get_serial_sequence('table_name', 'column_name'),
(Select Max(column_name) From table_name),
TRUE
);
The "true" is optional (default behaviour); it tells the sequence the value provided has been used, and to increment before providing the next value. See the Postgres documentation
On an empty table, you want the next value to be 1, but 0 is out of range, so you would pass FALSE:
Select setval(pg_get_serial_sequence('table_name', 'column_name'), 1, FALSE);
来源:https://stackoverflow.com/questions/15898772/alter-auto-generated-sequence