📜 ⬆️ ⬇️

An interesting feature of calculating logical expressions in plpgsql

There was a task to build a full-text index. The fts field of type ts_vector was created in the indexed table. When inserting and updating the trigger, if necessary, should update the fts field. To prevent the full-text index from being updated when updating fields not associated with it, the following condition was set:

 IF (TG_OP = 'UPDATE') AND (NEW."name" = OLD."name") THEN RETURN NEW; END IF; 
IF (TG_OP = 'UPDATE') AND (NEW."name" = OLD."name") THEN RETURN NEW; END IF;
Those. if the name is not updated, we don’t touch anything and just complete the execution of the trigger. But when updating this trigger fell with the error “record„ old “is not assigned yet”. However, errors do not occur with this design:

 IF (TG_OP = 'UPDATE') THEN IF (NEW."name" = OLD."name") THEN RETURN NEW; END IF; END IF; 
IF (TG_OP = 'UPDATE') THEN IF (NEW."name" = OLD."name") THEN RETURN NEW; END IF; END IF;
Therefore, when calculating a logical expression, each of its components is calculated. And even if TG_OP! = 'UPDATE' (which means INSERT is executed), the second condition is checked where OLD is not defined. Hence the error.

')

Source: https://habr.com/ru/post/44416/


All Articles