I'm trying to write a dynamic after trigger function that does an update based on the TG_TABLE_NAME, but it seems that plpgsql's CASE cannot do "LIKE". Is it called differently in plpgsql, or impossible?
If not possible, my second idea would be to do a SUBSTR, or are there better ways?
CREATE OR REPLACE FUNCTION upd_sys_table()
RETURNS TRIGGER AS $$
DECLARE
lm BIGINT := (EXTRACT(epoch FROM timezone('UTC', now()))*1000)::bigint;
BEGIN
CASE TG_TABLE_NAME
WHEN LIKE 'candy\_%' THEN
BEGIN
UPDATE sys_table SET last_modified = lm, modified_by = NEW.modified_by WHERE sys_table_name = 'xvw_candy';
END;
WHEN LIKE 'fruit\_%' THEN
BEGIN
UPDATE sys_table SET last_modified = lm, modified_by = NEW.modified_by WHERE sys_table_name = 'xvw_fruit';
END;
ELSE
RAISE NOTICE 'No match';
END CASE;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
This simply updates a record in a table called sys_table, which keeps track of a last-modified date for a group of tables. The group of tables are prefixed with either candy_ and fruit_ (yes, I made that up).
timestamptzandbigintare both 8-byte integer quantities internally, with the same storage characteristics and basically the same performance characteristics. Thebigintrepresentation is meaningless to the human eye and lacks helpful sanity checks on input. Typically you store the result ofnow()and friends, which is cheaper without cast tobigint. And for all other date/time operations you need to cast totimestamp(tz) anyway. Typically, there is no good reason to use the inappropriate data typebigint. – Erwin Brandstetter Mar 07 '21 at 18:06