0

When I create a table with a Sqitch migration I want to initialize its starting SERIAL PRIMARY KEY with something other than 1. However, for some reason the ALTER SEQUENCE command does not seem to have any effect.

My deploy migration looks something like this:

BEGIN;

  CREATE TABLE "user" (
    "id" SERIAL PRIMARY KEY,

    ... more columns ...
  );

  ALTER SEQUENCE "user_id_seq" RESTART WITH 12345;

COMMIT;

When the above migration has successfully run, the id column of first row I insert into my user table with have the value 1.

However, if I execute the ALTER SEQUENCE "user_id_seq" RESTART WITH 12345; statement manually (after the migrations have run), the next row I insert, the id column has the value 12345.

I have tried to move the ALTER SEQUENCE... statement into its own migration but this does not seem to have any positive effect.

How can I successfully execute the ALTER SEQUENCE... statement within a Sqitch migration?

Luke
  • 20,878
  • 35
  • 119
  • 178

1 Answers1

0

Did you try this:

SELECT setval("user_id_seq", 12345, false);

https://www.postgresql.org/docs/current/functions-sequence.html

UPDATED:

what about this? just tested it works fine

BEGIN;

CREATE SEQUENCE user_id_seq START 12345;

CREATE TABLE "user" (
  "id" integer NOT NULL DEFAULT nextval('user_id_seq'),
  --- rest fields
);

ALTER SEQUENCE user_id_seq OWNED BY user.id;

COMMIT;
alex2007v
  • 1,230
  • 8
  • 12
  • I actually tried that, forgot to mention. Doesn't work either although it outputs the `SELECT` value when the migration runs. – Luke Jan 15 '20 at 04:49
  • Actually you case works too for me with one changing `ALTER SEQUENCE test_user_id_seq RESTART WITH 12345;` I have removed singlequote. – alex2007v Jan 15 '20 at 05:23
  • Yes, that is correct. It works me for too when I run the query directly on the db. But it doesn't work within the context of a Sqitch migration. – Luke Jan 15 '20 at 05:25
  • @Luke I assume you have mistake in your deploy file, because when I tested your case and my case both followed me to expected result, when `user.id` is `12345`. I mean testing with sqitch – alex2007v Jan 15 '20 at 06:35
  • OK. I think I found the issue. The migration and `ALTER TABLE...` as I have it in my question works fine. However, when I run my fixtures (dev data) and integration tests, I perform a `TRUNCATE` on the table to clear it out. I suspect that the `TRUNCATE` is resetting the `SEQUENCE` but I will never use `TRUNCATE` in prod anyway. So, this is just a local dev/test phenomenon. Thanks for your help! – Luke Jan 15 '20 at 23:41