How to change primary key type in postgreSQL to bigserial using Rails/ActiveRecord
I believe the accepted answer is only half the story. You must also modify your sequence.
In particular, after only change the type of the id column, you still have:
# \d my_table_id_seq
Sequence "public.my_table_id_seq"
Type | Start | Minimum | Maximum | Increment | Cycles? | Cache
---------+-------+---------+------------+-----------+---------+-------
integer | 1 | 1 | 2147483647 | 1 | no | 1
You then need to run alter sequence mytable_id_seq as bigint;
The result is:
# \d my_table_id_seq
Sequence "public.my_table_id_seq"
Type | Start | Minimum | Maximum | Increment | Cycles? | Cache
--------+-------+---------+---------------------+-----------+---------+-------
bigint | 1 | 1 | 9223372036854775807 | 1 | no | 1
Create a migration:
bundle exec rails generate migration ChangeSerialToBigserial
Edit migration file:
def up
execute "ALTER TABLE my_table ALTER COLUMN id SET DATA TYPE bigint"
end
Login to the rails dbconsole
(it is just psql
console only with chosen a database for your app):
bundle exec rails dbconsole
Check table:
# \d my_table
Table "public.my_table"
Column | Type | Modifiers
------------------------+-----------------------------+----------------------------------------------------
id | bigint | not null default nextval('my_table_id_seq'::regclass)
The same sql
query like in a migration file you can run directly from psql
:
my_database=# ALTER TABLE my_table ALTER COLUMN id SET DATA TYPE bigint;
As @Mike Sherrill 'Cat Recall'
suggest Any column that references my_table.id will have to be changed, too. Thats mean if you have the Post
model with my_table_id
it should be changed too.