In the DB, I have a type and a table that one of it's rows is that type, such as this:
CREATE TYPE state (last_active timestamp, ...)
CREATE TABLE devices ( state state, ... )
For any interaction from the device, I want to update last_active field in the state. I added following BEFORE UPDATE trigger:
create or replace function update_last_active_on_position_update_hook()
returns trigger
language plpgsql
as $$
declare
new_state state;
begin
if new.state IS NOT NULL then
new.state.last_active := now();
end if;
RETURN new;
end
$$;
When I do that, I get the following error:
[42601] ERROR: "new.state.last_active" is not a known variable
But if I declare a variable with type state, copy new.state to that variable, update the field and copy back; it works. Working version:
create or replace function update_last_active_on_position_update_hook()
returns trigger
language plpgsql
as $$
declare
new_state state;
begin
if new.state IS NOT NULL then
new_state := new.state;
new_state.last_active := now();
new.state := new_state;
end if;
RETURN new;
end
$$;
But I don't like to do copy-update-copy. Is there another solution?
I tried to get new.state in parens as (new.state).last_active but it gives me a syntax error near "("
(new.state).last_active.