How to drop a primary key?

2019-08-06 05:05发布

So, I'd like to drop the current primary key on my users table.. I think it's on the email column.

And add a primary key to the uid column instead to get my omniauth working.

schema.rb snippit

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "admin"
    t.string   "provider"
    t.string   "uid"
    t.string   "username"
  end

I've tried adding a primary key to uid with:

class ChangeUidToPrimaryKey < ActiveRecord::Migration
  def change
    execute 'ALTER TABLE users ADD PRIMARY KEY (uid)'
  end
end

and got the following error (snippit):

PG::Error: ERROR:  multiple primary keys for table "users" are not allowed
: ALTER TABLE users ADD PRIMARY KEY (uid)/usr/local/rvm/gems/ruby-2.0.0-p195/gems/act

So how can I get this workin' ?

leap2_stage_development=# select * from information_schema.table_constraints where table_name='users';
   constraint_catalog    | constraint_schema |    constraint_name    |      table_catalog      | table_schema | table_name | constraint_type | is_deferrable | initially_deferred 
-------------------------+-------------------+-----------------------+-------------------------+--------------+------------+-----------------+---------------+--------------------
 leap2_stage_development | public            | users_pkey            | leap2_stage_development | public       | users      | PRIMARY KEY     | NO            | NO
 leap2_stage_development | public            | 2200_33435_1_not_null | leap2_stage_development | public       | users      | CHECK           | NO            | NO
 leap2_stage_development | public            | 2200_33435_2_not_null | leap2_stage_development | public       | users      | CHECK           | NO            | NO
 leap2_stage_development | public            | 2200_33435_3_not_null | leap2_stage_development | public       | users      | CHECK           | NO            | NO
(4 rows)

1条回答
女痞
2楼-- · 2019-08-06 05:26

You have to drop the existing primary key first, something along the lines of:

ALTER TABLE "users" DROP CONSTRAINT "users_pkey".

You can add that statement as another execute before your current one in the migration.

Edit: You can check the current constrains on a table with the following:

select * from information_schema.table_constraints where table_name='myTable';

Source: PostgreSQL documentation

查看更多
登录 后发表回答