如何通过 Rails 迁移在 Postgres 中设置主键 (ID) 列的起点

发布于 2024-08-04 23:47:58 字数 444 浏览 1 评论 0原文

我正在将一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

_畞蕅 2024-08-11 23:47:59

不知道红宝石和铁路部分,但您正在谈论的查询是

ALTER SEQUENCE reports_something_seq RESTART 1000;

您必须查找表中的序列名称和 postgresql 文档,以了解有关此事的普通教育;-)

Have no idea about rubies and railroads part, but query you're talking about is

ALTER SEQUENCE reports_something_seq RESTART 1000;

You will have to look up your table for the sequence name and postgresql documentation for general education regarding the matter ;-)

晨与橙与城 2024-08-11 23:47:59

在 postgres 中,与许多其他数据库一样,自动增量功能是通过序列完成的。对于每个 Serial 和 Likes 字段,Postres 会自动为您创建序列,并命名为 TABLENAME _ COLUMNNAME _ seq 之类的名称。

因此,您只需更改相应的顺序,如下所示:

ALTER SEQUENCE example_id_seq RESTART 1000 -- corrected from START

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:

ALTER SEQUENCE example_id_seq RESTART 1000 -- corrected from START
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文