复制主键,无法访问psql控制台

时间:2012-09-09 04:20:38

标签: postgresql activerecord heroku ruby-on-rails-3.2 cedar

在postgres数据库中创建新记录时出现问题。使用Heroku Cedar堆栈和Rails 3.2。

中调用创建结果
ActiveRecord::RecordNotUnique (PG::Error: ERROR:  duplicate key value violates unique constraint "answer_selections_pkey"

这是我的问题表的架构(它应该使用隐式自动增量id列):

  create_table "answer_selections", :force => true do |t|                                                              
    t.integer "individual_id"
    t.integer "answer_choice_id"
    t.boolean "still_true",       :default => false
  end

这是调用create时的错误。

2012-09-07T14:46:44+00:00 app[web.1]: ActiveRecord::RecordNotUnique (PG::Error: ERROR:  duplicate key value violates unique constraint "answer_selections_pkey"
2012-09-07T14:46:44+00:00 app[web.1]: : INSERT INTO "answer_selections" ("answer_choice_id", "individual_id", "still_true") VALUES ($1, $2, $3) RETURNING "id"):
2012-09-07T14:46:44+00:00 app[web.1]:   app/controllers/answer_selections_controller.rb:10:in `create'

同样,我在另一张桌子上看到同样的错误:

2012-09-09T04:10:34+00:00 app[web.2]: ActiveRecord::RecordNotUnique (PG::Error: ERROR:  duplicate key value violates unique constraint "trips_pkey"
2012-09-09T04:10:34+00:00 app[web.2]: : INSERT INTO "trips" ("booked", "created_at", "destination_id", "end_date", "individual_id", "n_travelers", "name", "start_date", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"):

由于连接超时,无法直接访问postgres数据库:

$ heroku pg:psql
psql: could not connect to server: Connection timed out

我该如何修复它,以后如何避免它?我已经读过运行VACCUUM和ANALYZE会解决它,但正如我所说我无法访问psql。

编辑以添加请求的信息(上面包含的示例模式,我们使用的是ActiveRecord):

@record.create(params) # How these records are created

1 个答案:

答案 0 :(得分:3)

我不确定您的数据发生了什么,但不知何故,提供id值的序列与表的id值不同步;如果您在INSERT中提供明确的id值,就会发生这种情况:

insert into t (id, col) values (11, 'pancakes')

也许你已经加载了一些批量数据,但没有让你的序列恢复正常。

在任何情况下,简单的迁移都可以解决您的问题:

class KickAnswerSelectionSequence < ActiveRecord::Migration
    def up
        connection.execute(%q{
            select setval('answer_selections_id_seq', max(id))
            from answer_selections
        })
    end
    def down
        raise ActiveRecord::IrreversibleMigration
    end
end

你想对所有给你问题的表重复这一点,为了安全起见,为你所有的表做这个可能是个好主意。

如果需要,您可以阅读有关序列操作功能的更多信息:

  

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

关于heroku pg:psql的问题,你必须和Heroku讨论这件事。