Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Autoincrement values in migration (PostgreSQL and SQLite3)

I have a project hosted on Heroku and would like to change a table's autoincrement start value. I'm using SQLite3 locally and Heroku uses PostgreSQL This is what I have in the migration:

class CreateMytable < ActiveRecord::Migration

  def self.up
    create_table :mytable do |t|
      t.text :mytext
    end

    case ActiveRecord::Base.connection.adapter_name 
      when 'PostgreSQL'
        execute 'ALTER SEQUENCE mytable_id_seq RESTART WITH 1000;'
      when 'SQLite'
        execute 'update sqlite_sequence set seq = 1000 where name = "mytable";'
      else
    end 
  end

  def self.down
    drop_table :mytable
  end
end

Locally the migration runs but SQLite seems to just ignore the change, it works on Heroku though. What am I doing wrong?

like image 724
David Avatar asked Mar 26 '11 04:03

David


People also ask

Does SQLite have Autoincrement?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.

Does PostgreSQL have auto increment?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .

Does primary key auto increment SQLite?

In SQLite, an AUTOINCREMENT column is one that uses an automatically incremented value for each row that's inserted into the table. There are a couple of ways you can create an AUTOINCREMENT column: You can create it implicitly when you define the column as INTEGER PRIMARY KEY .


1 Answers

Honestly, it doesn't sound like this belongs in a migration. You could add the following to an initializer to make a handy Base class method to call as part of a task, though:

ActiveRecord::Base.class_eval do
  def self.reset_autoincrement(options={})
    options[:to] ||= 1
    case self.connection.adapter_name
      when 'MySQL'
        self.connection.execute "ALTER TABLE #{self.table_name} AUTO_INCREMENT=#{options[:to]}"
      when 'PostgreSQL'
        self.connection.execute "ALTER SEQUENCE #{self.table_name}_id_seq RESTART WITH #{options[:to]};"
      when 'SQLite'
        self.connection.execute "UPDATE sqlite_sequence SET seq=#{options[:to]} WHERE name='#{self.table_name}';"
      else
    end
  end
end

Then just run the following as part of a task or right in the console:

Mytable.reset_autoincrement(:to => 1000)

Make sure to check this handy answer as to why the sqlite may not be working.

SQLite Reset Primary Key Field

like image 178
20man Avatar answered Nov 02 '22 23:11

20man