I want to have a column user.substitute_user_id
where users can appoint someone being in charge instead of them.
If they are still are in charge, it should point to themself, so that you can always look into that field and see the correct user id of the user being in charge.
create table public.user (
id bigserial primary key,
is_superuser boolean not null,
substitute_user_id bigint,
foreign key (substitute_user_id) references public.user (id)
match simple on update no action on delete no action
);
create index user_substitute_user_id_d012d5b2 on user using btree (substitute_user_id);
Now I can update the substitute_user_id
to point to a row itself like the following:
UPDATE "user" SET "substitute_user_id" = "user"."id"
How can I put a default which does the same?
Can be a trigger too, updating the value if it is still set to null on insert,
however I couldn’t find a way to do it.
Requirements:
- must work on insert, setting the inserted
row.substitute_user_id := row.id
automatically - must be possible to be changed to another
user.id
via UPDATE.
2
Answers
With
currval
being the missing part (thanks @Zegarek) in my earlier tries it is now possible to create two triggers, one for insert and one for update.INSERT
one will useNEW.substitute_user_id := currval(…)
, as the.id
is not yet availableUPDATE
one will useNEW.substitute_user_id := NEW.id
, as thecurrval(…)
might now point to some later added row.Here's the full fun:
The same way you generate
id
, except you take thecurrval()
which will be equal to whatid
column just got fromnextval()
. You don’t need to know the name of the sequence if you let postgres look it up withpg_get_serial_sequence()
.:demo at db<>fiddle
In case that DDL was because you used
serial
– don’t useserial
.