Postgresql trigger set empty string to NULL
I have a table with field "mac" of type MACADDR. Now I would like to treat a situation (probably with trigger?) when some开发者_JS百科body inserts empty string instead of mac address. I would like to turn this empty string to NULL, so postgresql will not complain: invalid input syntax for type macaddr: ""
What I have now in trigger function is this:
IF CHAR_LENGTH(NEW.mac) = 0 THEN
NEW.mac := NULL;
END IF;
But it does not seem to work. What would you do, if you want to treat this on DB level?
Thank you very much. -Jan
PS: I am a postgresql newbie. But a fascinated one :)
You can't do what you want with a trigger. Your incoming empty string will be parsed and converted to a macaddr
(or at least the parsing will be attempted) before the trigger is executed. However, you could write a simple function to convert empty strings to NULL and use that in your INSERT:
create function macaddr_ify(m varchar) returns macaddr as $$
begin
if m is null or length(m) = 0 then
return null;
end if;
return cast(m as macaddr);
end;
$$ language plpgsql;
And then:
insert into t (addr) values (macaddr_ify(str));
I'd recommend that your client application properly convert empty MAC address strings to NULLs itself though.
精彩评论