json - Test datatype on postgresql update trigger -
i use trigger detect if @ least 1 value has changed when update performed on table.
the function :
create or replace function update_version_column() returns trigger $body$ begin if row(new.*) distinct row(old.*) new.version = now(); return new; else return old; end if; end; $body$ language plpgsql volatile cost 100; alter function update_version_column() owner gamesplateform;
the problem is, when column type "json", "is distinct" failed (standard comportement, explained in documentation).
i search way perform same thing, if column in "json" type, want force "jsonb" cast accept comparison operator.
is there way ?
thanks !
found way :
create or replace function update_version_column() returns trigger $body$ declare updated boolean := false; column_data record; begin column_data in select column_name::varchar, data_type::varchar information_schema.columns c table_name = tg_table_name loop if column_data.data_type = 'json' execute format('select case when ($1).' || column_data.column_name || '::text <> ($2).' || column_data.column_name || '::text true else false end') using new, old updated; else execute format('select case when ($1).' || column_data.column_name || ' <> ($2).' || column_data.column_name || ' true else false end') using new, old updated; end if; if updated = true new.version := now(); return new; end if; end loop; return old; end; $body$ language plpgsql volatile cost 100; alter function update_version_column() owner gamesplateform;
i cast "json" in "text" because have fail "jsonb" (type not exist). seems specific configuration, trigger answers great :)
thanks @julien bossart !
Comments
Post a Comment