如何通过 Rails 迁移在 Postgres 中设置主键 (ID) 列的起点
我正在将一个 Rails 应用程序部署到 Heroku,它使用 PostgreSQL 作为后端。在我的数据库迁移中,我通常将报告等内容的 ID 字段设置为至少 1000,大多数客户端似乎不喜欢从 1 开始。
我使用 mysql,我只需在创建表后添加特定的 sql:
def self.up
create_table :reports do |t|
t.references :something
...
end
execute("ALTER TABLE reports AUTO_INCREMENT = 1000;")
end
通常 知道如何为 PostgreSQL 实现相同的目标,理想情况下,我希望迁移能够构建表本身,这样就不是特定于数据库的。
我想实现我的目标的一个愚蠢的方法是循环创建和删除 999 条记录,哎呀。
I am deploying a rails app to heroku which uses PostgreSQL as its back-end. In my database migration I normally set the ID field for things likes reports etc to at least 1000, most clients don't seem to like starting at 1.
Normally I use mysql and I simply add an sql specific after my table creation:
def self.up
create_table :reports do |t|
t.references :something
...
end
execute("ALTER TABLE reports AUTO_INCREMENT = 1000;")
end
Does anybody know how I can acheive the same for PostgreSQL, ideally I would like the migration to build the table itself so that's not DB specific.
I guess a silly way of achieving my goal would be to create and delete 999 records in a loop, ouch.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不知道红宝石和铁路部分,但您正在谈论的查询是
您必须查找表中的序列名称和 postgresql 文档,以了解有关此事的普通教育;-)
Have no idea about rubies and railroads part, but query you're talking about is
You will have to look up your table for the sequence name and postgresql documentation for general education regarding the matter ;-)
在 postgres 中,与许多其他数据库一样,自动增量功能是通过序列完成的。对于每个 Serial 和 Likes 字段,Postres 会自动为您创建序列,并命名为 TABLENAME _ COLUMNNAME _ seq 之类的名称。
因此,您只需更改相应的顺序,如下所示:
In postgres, like in many other databases, auto increment feature is done via Sequences. For every Serial and the likes fields sequences are created automatically by Postres for you and named something like TABLENAME _ COLUMNNAME _ seq.
So, you have to just alter the corresponding sequence, like this: