'Postgres: Join data returned from a postgresql function, where the tables to be joined are updated in the function?
I am creating a postgresql function which updates a history and status table, where the history is the log of all changes, and the status is the current state.
The function returns the most recent history entry.
I'd like to use the result of the function to JOIN on the status table ... (In reality, this is a little more complicated, but the example is dumbed down for clarity)
This function is being called by Hasura, which is attempting to use the returned id from the new entry table to join on the status table to get actual status. Here is some sample code which shows the problem.
create sequence thing_seq;
create table thing_history (id int not null default nextval('thing_seq'), thing int, status int);
create table thing_status (id int, status int);
-- initial status for 'thing-0'
insert into thing_status values (0,0);
-- this works
--insert into thing_history (thing, status) values (0,1);
--insert into thing_status values (0,1);
--select * from thing_history h left join thing_status s on h.thing = s.id;
-- this works too
--insert into thing_history (thing, status) values (0,2);
--update thing_status set status=2 where id = 0;
--select * from thing_history h left join thing_status s on h.thing = s.id ;
-- this doesn't work
create or replace function new_thing (thing_id int)
returns setof thing_history AS $$
DECLARE
l_status int;
l_inserted_id bigint;
BEGIN
-- get the current state, increment by 1. Simplificiation.
SELECT status into l_status from thing_status where id = thing_id;
l_status = l_status+1;
update thing_status SET status = l_status where id = thing_id;
insert into thing_history (thing, status) values (thing_id, l_status) returning id into l_inserted_id;
return query select * from thing_history where id = l_inserted_id;
return;
END $$
LANGUAGE plpgsql;
-- thing_status records are "old"
select * from new_thing(0) th left join thing_status ts on ts.id = th.thing;
-- thing_status records are "old"
select (new_thing(0)).* nt, * from thing_status ts
When the "new_thing" is status "1" based upon return from history, the joined status is "0".
Is this possible to expect the join to provide data that is "post" update from the function?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
