简体   繁体   中英

Postgresql user-defined type and trigger

I have user defined type in Postgresql and table with this type:

CREATE TYPE public.hour_integer AS
(
    q_1 integer,
    q_2 integer,
    q_3 integer,
    q_4 integer
);

CREATE TABLE IF NOT EXISTS device_hours_data
(
    device_hours_data_id serial,
    date date,
    h01 hour_integer ,
    h02 hour_integer ,
    h03 hour_integer ,
...
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

Now I need to create a trigger before insert with rule: if h01.q_1 is null then h01.q_1 = 0. How can I use correct syntax please?

CREATE OR REPLACE FUNCTION public.device_hours_data_trigger()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
    v_hour character varying;
BEGIN
    IF (NEW).h01.q_1 = null THEN
      NEW.h01.q_1 = 0;
    END IF;

    ...

    RETURN NEW;
END;
$BODY$;

I am using something like:

 NEW.h01.q_1 = 0; - syntax error,
(NEW).h01.q_1 = 0; - syntax error,
(NEW.h01).q_1 = 0; - syntax error....

Could you please help me? Thanks

The only way I could get it to work is as suggested by @a_horse_with_no_name, something like:

CREATE OR REPLACE FUNCTION public.device_hours_data_trigger()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
    v_hour character varying;
    new_hour hour_integer;
BEGIN
    new_hour = NEW.h01;
    IF new_hour.q_1 = null THEN
      new_hour.q_1 = 0;
    END IF;

    ...
    NEW.h01 = new_hour;
    RETURN NEW;
END;
$BODY$;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM