ein*_*bst 3 postgresql activerecord ruby-on-rails primary-key
如何在postgres中将现有表的主键列类型从serial(int)更改为bigserial(bigint)?
该数据库由Rails应用程序使用.我是否需要对应用进行任何更改?
小智 9
我相信接受的答案只是故事的一半。您还必须修改您的序列。
特别是,仅更改 id 列的类型后,您仍然拥有:
# \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
Run Code Online (Sandbox Code Playgroud)
然后你需要运行 alter sequence mytable_id_seq as bigint;
结果是:
# \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
Run Code Online (Sandbox Code Playgroud)
创建迁移:
bundle exec rails generate migration ChangeSerialToBigserial
Run Code Online (Sandbox Code Playgroud)
编辑迁移文件:
def up
execute "ALTER TABLE my_table ALTER COLUMN id SET DATA TYPE bigint"
end
Run Code Online (Sandbox Code Playgroud)
登录到rails dbconsole(只有psql控制台才能为您的应用选择一个数据库):
bundle exec rails dbconsole
Run Code Online (Sandbox Code Playgroud)
检查表:
# \d my_table
Table "public.my_table"
Column | Type | Modifiers
------------------------+-----------------------------+----------------------------------------------------
id | bigint | not null default nextval('my_table_id_seq'::regclass)
Run Code Online (Sandbox Code Playgroud)
sql您可以直接从psql以下位置运行的迁移文件中的相同查询:
my_database=# ALTER TABLE my_table ALTER COLUMN id SET DATA TYPE bigint;
Run Code Online (Sandbox Code Playgroud)
作为@Mike Sherrill 'Cat Recall'建议引用my_table.id将不得不改变,也任何列.这意味着,如果你有Post模型,my_table_id它也应该改变.
| 归档时间: |
|
| 查看次数: |
5178 次 |
| 最近记录: |