【问题标题】:Change Autoincrement values in migration (PostgreSQL and SQLite3)在迁移中更改自动增量值(PostgreSQL 和 SQLite3)
【发布时间】:2011-07-23 08:40:53
【问题描述】:

我有一个托管在 Heroku 上的项目,并且想更改表的自动增量起始值。我在本地使用 SQLite3 而 Heroku 使用 PostgreSQL 这就是我在迁移中所拥有的:

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

迁移在本地运行,但 SQLite 似乎只是忽略了更改,但它适用于 Heroku。我做错了什么?

【问题讨论】:

  • 有点过时了,但您确实应该在本地设置 PostgreSQL,在一个数据库上开发并在另一个数据库上部署是在 02:00 时令人沮丧和恐慌的电话的秘诀。

标签: sql ruby-on-rails-3 sqlite postgresql auto-increment


【解决方案1】:

老实说,这听起来不属于迁移。不过,您可以将以下内容添加到初始化程序中,以创建一个方便的 Base 类方法作为任务的一部分调用:

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

然后只需将以下作为任务的一部分运行或直接在控制台中运行:

Mytable.reset_autoincrement(:to => 1000)

请务必查看这个方便的答案,了解 sqlite 可能无法正常工作的原因。

SQLite Reset Primary Key Field

【讨论】:

  • 谢谢,这是一个更好的方法。因为我希望这个过程是自动化的,所以我会为它做一个 rake 任务。出于某种原因,尽管 SQLite 在我将查询更改为self.connection.execute "UPDATE sqlite_sequence SET seq=#{options[:to]} WHERE name='#{self.table_name}';" 之前无法工作。可能与%Q 有关?
  • 另外,PostgreSQL 行应该是... SEQUENCE #{self.table_name}_id_seq ...
  • 很好,感谢您的更正;我已将它们添加到帖子中。
猜你喜欢
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 2011-09-17
  • 2016-04-13
  • 2013-02-19
  • 2014-09-30
相关资源
最近更新 更多