在 Postgres 中重命名 nextval('...')

Rename nextval('...') in Postgres

我有一个名为 pivot_device_user 的 table 并且在 ID 上有一个序列为 not null default nextval('pivot_device_user_id_seq'::regclass)

然后我决定将我的 table 重命名为 pivot_box_user,但 nextval(...) 仍然是 nextval('pivot_device_user_id_seq'::regclass)

我想将其更改为 nextval('pivot_box_user_id_seq'::regclass)。我该怎么做?

首先你必须明白什么是serial

  • Safely and cleanly rename tables that use serial primary key columns in Postgres?
  • Auto increment SQL function

列默认值实际上并未存储为文本文字。您看到的只是人类可读的文本表示:nextval('pivot_device_user_id_seq'::regclass)

'pivot_device_user_id_seq'::regclass 在内部解析为 OID (regclass to be precise) - the OID of the underlying sequence - and that's what's actually stored (early binding). If you rename the sequence, its OID remains unchanged. So all you need to do is rename the sequence:

ALTER SEQUENCE pivot_device_user_id_seq RENAME TO pivot_box_user_id_seq;

检查是否成功:

SELECT pg_get_serial_sequence('pivot_box_user', 'id');

相关:

  • Activerecord-import & serial column in PostgreSQL