简体   繁体   中英

PostgreSQL before insert trigger for blocking 0000-00-00 00:00:00

I have created the following trigger in my PostgreSQL environment to block the inserts of 0000-00-00 00:00:00 in my timestamp datatype field, since it's not supported.

create function my_trigger_func() returns trigger as $$
begin
    if NEW.t_date = '0000-00-00 00:00:00' then
        NEW.t_date := '0001-01-01 00:00:00';
    end if;
    return new;
end
$$ language plpgsql;

CREATE TRIGGER my_trigger
BEFORE INSERT ON timezone.test
FOR EACH ROW
EXECUTE PROCEDURE my_trigger_func()

The above trigger function gets created successfully. But after that, when I execute the below insert command:

Insert into timezone.test (t_id,t_date) values ('3','0001-01-01 01:10:01');

I am getting the following error:

ERROR:  date/time field value out of range: "0000-00-00 00:00:00"
LINE 1: SELECT NEW.t_date = '0000-00-00 00:00:00'
                            ^
QUERY:  SELECT NEW.t_date = '0000-00-00 00:00:00'
CONTEXT:  PL/pgSQL function my_trigger_func() line 3 at IF
********** Error **********

ERROR: date/time field value out of range: "0000-00-00 00:00:00"
SQL state: 22008
Context: PL/pgSQL function my_trigger_func() line 3 at IF

Kindly let me know where am I going wrong.

Kindly let me know where am I going wrong.

Simple, you try to compare:

IF NEW.t_date          = '0000-00-00 00:00:00' THEN
   (type timestamp)      literal -> conversion to Timestamp 

'0000-00-00 00:00:00' -> Invalid timestamp

And because of this trigger you cannot insert even correct values. I would suggest correcting it in application and insert proper values.

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