且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 3 迁移:(非主键)列上的自动增量?

更新时间:2023-11-24 12:56:28

通常使用数据库序列实现自动递增列.使用序列比计算下一个增量的优势在于从序列中获取下一个值是原子的.因此,如果您有多个流程创建新元素,则该序列将确保您的数字确实是唯一的.

Normally auto-incrementing columns are implemented using database sequences. The advantage of using a sequence over calculating the next increment, is that getting the next value from a sequence is atomic. So if you have multiple processes creating new elements, the sequence will make sure your numbers are really unique.

序列可用于 postgresql、oracle、mysql、...

Sequences can be used in postgresql, oracle, mysql, ...

如何实现这一点,例如,如果您使用的是 postgres:

How to implement this, if you are using postgres for instance:

  • 从序列中选择下一个值:

  • select the next value from the sequence:

Integer(Operator.connection.select_value("SELECT nextval('#{sequence_name}')"))

创建一个序列:

Operator.connection.execute("CREATE sequence #{sequence_name}")

设置序列的起始值:

Operator.connection.execute("SELECT setval('#{sequence_name}', #{new_start_serial})")

希望这会有所帮助.