我有一个数据库,我想将其转换为使用 UUID 作为 postgresql 中的主键。
我有大约 30 个具有深度多级关联的表。是否有一种“简单”的方法可以将所有当前 ID 转换为 UUID?
从这里: https://coderwall.com/p/n_0awq,我可以看到我可以在迁移中更改表。我在想这样的事情:
for client in Client.all
# Retrieve children
underwritings = client.underwritings
# Change primary key
execute 'ALTER TABLE clients ALTER COLUMN id TYPE uuid;'
execute 'ALTER TABLE clients ALTER COLUMN id SET DEFAULT uuid_generate_v1();'
# Get new id - is this already generated?
client_id = client.id
for underwriting in underwritings
locations = underwriting.locations
other_record = underwriting.other_records...
execute 'ALTER TABLE underwritings ALTER COLUMN id TYPE uuid;'
execute 'ALTER TABLE underwritings ALTER COLUMN id SET DEFAULT uuid_generate_v1();'
underwriting.client_id = client_id
underwriting.saved
underwriting_id = underwriting.id
for location in locations
buildings = location.buildings
execute 'ALTER TABLE locations ALTER COLUMN id TYPE uuid;'
execute 'ALTER TABLE locations ALTER COLUMN id SET DEFAULT uuid_generate_v1();'
location.undewriting_id = underwriting_id
location.save
location_id = location.id
for building in buildings
...
end
end
for other_record in other_records
...
end
...
...
end
end
问题:
- 这行得通吗?
- 有没有更简单的方法来做到这一点?
- 只要在更改主键之前检索子记录,是否会正确检索子记录?
- 一旦调用了alter table,是否已经生成了新的主键?
非常感谢您提供的任何帮助或提示。