views:

302

answers:

2

I am deploying a rails app to heroku which uses PostgreSQL as its back-end. In my database migration I normally set the ID field for things likes reports etc to at least 1000, most clients don't seem to like starting at 1.

Normally I use mysql and I simply add an sql specific after my table creation:

def self.up
    create_table :reports do |t|
       t.references :something
       ...
    end
    execute("ALTER TABLE reports AUTO_INCREMENT = 1000;")
end

Does anybody know how I can acheive the same for PostgreSQL, ideally I would like the migration to build the table itself so that's not DB specific.

I guess a silly way of achieving my goal would be to create and delete 999 records in a loop, ouch.

+2  A: 

Have no idea about rubies and railroads part, but query you're talking about is

ALTER SEQUENCE reports_something_seq RESTART 1000;

You will have to look up your table for the sequence name and postgresql documentation for general education regarding the matter ;-)

Michael Krelin - hacker
Thanks both for the update, I've just pulled down a dump of the db, looks like this is the one:CREATE SEQUENCE reports_id_seq INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1;
tsdbrown
Yes, you can set start at `CREATE SEQUENCE` time, in which case you just add `START 1000` to the statement. But to change it later on you need `ALTER`, not `CREATE` command.
Michael Krelin - hacker
Haha thanks, I wasn't trying to use the CREATE command, just highlighting what 'had' been used to generate the sequence, that's the SQL generated from the migration file.I used the ALTER and RESTART as you mentioned and its worked a charm. If I'm going to be using Postgres in a production based app I'll be sure to read up on it.
tsdbrown
glad that it worked for you ;-)
Michael Krelin - hacker
+1  A: 

In postgres, like in many other databases, auto increment feature is done via Sequences. For every Serial and the likes fields sequences are created automatically by Postres for you and named something like TABLENAME _ COLUMNNAME _ seq.

So, you have to just alter the corresponding sequence, like this:

ALTER SEQUENCE example_id_seq START 1000
maksymko
hah, I made the same mistake, but corrected after looking up `\h alter sequence` just in case ;-) It's `RESTART`, not `START`. `START` is for `CREATE SEQUENCE`.
Michael Krelin - hacker