handling inherited sequence ids

此生再无相见时 提交于 2020-01-25 06:42:03

问题


I had the following tables: supernode (id bigint, name text) and subnode(id bigint, parent bigint references supernode(id), name text). (massive simplification to illustrate the issue, obviously)

But I want a subnode to be able to have either a supernode or another subnode as parent. In order to do this I create another table node(id bigint) and have them both inherit id from that node.

So from scratch it'd be:

create table node(id generated always as identity);
create table supernode (name text) inherits(node);
create table subnode (name text, parent bigint references node(id), name text)`

This worked, but when I tried to make id generate sequentially it did it sequentially for each separate table. So when I created 3 supernodes they had id 1, 2, 3 and when I created 3 subnodes they also had id 1,2,3.

So when I select * from node I'd see the ids 1,2,3,1,2,3. This happened even if I set the constraint of making id unique.

My original thought was that I should make the id into a uuid instead of a bigint. But when I tried:

alter table node alter column id type uuid;

I got: ERROR: identity column type must be smallint, integer, or bigint.

One idea I had to solve this is that since it's a bigint I can have supernode start counting at 100,000,000,000,000 and have subnode start counting at 500,000,000,000,000. This seems safe as long as I have less than 400 trillion records, which seems likely.

The other way I can think to do this is to create a sequence, say id_sequence, and have the node column generate from sequence. Since it's one sequence, supernode and subnode will be generating from the same series. But when I tried to do:

create sequence id_sequence;
alter table node alter column id  set default nextval('id_sequence');

I got the error:

ERROR:  column "id" of relation "node" is an identity column

What is the best way to create inherited unique ids?

来源:https://stackoverflow.com/questions/58905798/handling-inherited-sequence-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!