Is this possible? I’m interested in finding out which columns were specified in the UPDATE request regardless of the fact that the new value that is being sent may or may not be what is stored in the database already.
The reason I want to do this is because we have a table that can receive updates from multiple sources. Previously, we weren’t recording which source the update originated from. Now the table stores which source has performed the most recent update. We can change some of the sources to send an identifier, but that isn’t an option for everything. So I’d like to be able to recognize when an UPDATE request doesn’t have an identifier so I can substitute in a default value.
If a "source" doesn’t "send an identifier", the column will be unchanged. Then you cannot detect whether the current
UPDATEwas done by the same source as the last one or by a source that did not change the column at all. In other words: this does not work properly.If the "source" is identifiable by any session information function, you can work with that. Like:
Unconditionally for every update.
General Solution
I found a way to solve the original problem.
Set the column to a default value if it’s not targeted in an
UPDATE(not in theSETlist). Key element is a per-column trigger introduced with PostgreSQL 9.0 – a column-specific trigger using theUPDATE OFcolumn_nameclause. The manual:That’s the only simple way I found to distinguish whether a column was updated with a new value identical to the old, versus not updated at all.
One could also parse the text returned by
current_query(). But that seems cumbersome, tricky and unreliable.Trigger functions
I assume a column
sourcedefinedNOT NULL.Step 1: Set
sourcetoNULLif unchanged:Step 2: Revert to old value. Trigger will only be fired if the value was actually updated (see below):
Step 3: Now we can identify the lacking update and set a default value instead:
Triggers
The trigger for Step 2 is fired per column!
db<>fiddle here
Trigger names are relevant, because they are fired in alphabetical order (all being
BEFORE UPDATE)!The procedure could be simplified with something like "per-not-column triggers" or any other way to check the target-list of an
UPDATEin a trigger. But I see no handle for this, currently (unchanged as of Postgres 16).If
sourcecan beNULL, use any other "impossible" intermediate value and check forNULLadditionally in trigger function 1:Adapt the rest accordingly.