Sub topic 12
INSTEAD OF triggers on views
This chapter assumes you can write a PL/pgSQL trigger function and attach it with CREATE TRIGGER. It also assumes you know the difference between row-level and statement-level triggers, and what NEW and OLD hold. Here you will use INSTEAD OF triggers to make views writable when PostgreSQL cannot do it on its own.
Why views need INSTEAD OF triggers
A view is a stored query. PostgreSQL can update some views directly. These are called automatically updatable views. A view qualifies when it reads from a single table or view and has no DISTINCT, GROUP BY, aggregates, window functions, LIMIT, set operations, or similar constructs.
Many useful views do not qualify. A view that joins two tables, hides columns that need defaults, or computes values has no obvious mapping back to the base tables. An INSERT against such a view fails with an error like "cannot insert into view".
An INSTEAD OF trigger fixes this. It runs in place of the operation on the view. Your function decides which base tables to change.
The rules for INSTEAD OF triggers
- They can be defined only on views, not on tables.
- They must be
FOR EACH ROW. Statement-level INSTEAD OF triggers do not exist. - They cannot have a
WHENcondition on a column list (UPDATE OF col). AWHENclause is allowed in recent PostgreSQL versions, butUPDATE OFis not. - BEFORE and AFTER row triggers cannot be defined on a view. Only statement-level BEFORE and AFTER triggers can.
- The view itself is never changed by the operation. Only what your function does takes effect.
A first example
The view account_emails exposes two columns of accounts. Assume the accounts table from the earlier chapters.
CREATE VIEW account_emails AS
SELECT id, email FROM accounts;
CREATE FUNCTION account_emails_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts (email) VALUES (NEW.email)
RETURNING id INTO NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER account_emails_ins
INSTEAD OF INSERT ON account_emails
FOR EACH ROW
EXECUTE FUNCTION account_emails_insert();The function inserts into accounts and copies the generated id back into NEW. It then returns NEW.
Try it:
INSERT INTO account_emails (email) VALUES ('[email protected]')
RETURNING id, email;The RETURNING clause on the view reports the row you returned from the trigger. Because the function set NEW.id, the caller sees the real identity value.
What the return value means
For INSTEAD OF row triggers, the return value tells PostgreSQL whether you handled the row.
| Return value | Effect |
|---|---|
| A non-null row (usually `NEW`, or `OLD` for DELETE) | The operation counts as done. The row is included in the affected-row count and in `RETURNING`. |
| `NULL` | The operation is treated as skipped for this row. The count stays at zero and `RETURNING` gives nothing. |
The row you return is what RETURNING shows. For DELETE, return OLD, since NEW is not defined there. A frequent mistake is returning NULL at the end of the function out of habit from AFTER triggers. Your data change still happens, but the client sees "0 rows affected" and may treat the statement as a failure.
A view over a join
The more common case is a joined view. Suppose customers and their addresses live in separate tables.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE addresses (
customer_id bigint PRIMARY KEY REFERENCES customers (id),
city text NOT NULL
);
CREATE VIEW customer_directory AS
SELECT c.id, c.name, a.city
FROM customers c
JOIN addresses a ON a.customer_id = c.id;
CREATE FUNCTION customer_directory_write() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO customers (name) VALUES (NEW.name)
RETURNING id INTO NEW.id;
INSERT INTO addresses (customer_id, city) VALUES (NEW.id, NEW.city);
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
UPDATE customers SET name = NEW.name WHERE id = OLD.id;
UPDATE addresses SET city = NEW.city WHERE customer_id = OLD.id;
RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
DELETE FROM addresses WHERE customer_id = OLD.id;
DELETE FROM customers WHERE id = OLD.id;
RETURN OLD;
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER customer_directory_trg
INSTEAD OF INSERT OR UPDATE OR DELETE ON customer_directory
FOR EACH ROW
EXECUTE FUNCTION customer_directory_write();One function handles all three events by branching on TG_OP. Both base-table writes run inside the caller's transaction. If the second statement fails, the first one rolls back with it.
Gotchas
- Stale
NEWvalues on update. In theUPDATEbranch above, every column of the view is written, even when the user changed only one. This is fine for simple cases. For wide views, compareOLDandNEWand write only what changed. - Changing the key. If a user updates
idthrough the view,WHERE id = OLD.idstill targets the right row, but the newidis ignored. Decide whether to reject key changes withRAISE EXCEPTION. - Row counts on UPDATE and DELETE. The view's query selects the rows first. The trigger then fires once for each selected row. A
WHEREclause on the view therefore works as usual, with no extra code in your function. - Other triggers on base tables still fire. Writes made by your function are normal writes. Audit triggers or
updated_attriggers oncustomersrun as expected. - Permissions. The function runs with the privileges of the caller unless you declare it
SECURITY DEFINER. Users need rights on the view, and on the base tables unless the function isSECURITY DEFINER. If you useSECURITY DEFINER, set a safesearch_pathon the function. - Automatic updatability. If a simple view is already automatically updatable, adding an INSTEAD OF trigger overrides that behavior for the events it covers. Leave the simple case alone unless you need custom logic.
Alternatives
Rules (CREATE RULE ... DO INSTEAD) can also make views writable, but they rewrite queries and behave in surprising ways with multi-row statements. INSTEAD OF triggers are the recommended choice. Another option is to expose functions or stored procedures for writes and leave the view read-only. That is clearer when a write needs many parameters or a multi-step workflow.
Exercise
You create an INSTEAD OF INSERT trigger on a view. Its function inserts the row into the base table, then ends with RETURN NULL. The base table gains the row, but psql reports "INSERT 0 0". Why, and what is the fix?
Show answer
For an INSTEAD OF row trigger, returning NULL tells PostgreSQL the row was not handled, so the affected-row count is 0 and RETURNING yields nothing, even though the function itself wrote to the base table. Change the final statement to RETURN NEW (with NEW.id filled in from the base-table insert if the view exposes a generated key). Then psql reports "INSERT 0 1".
Exercise
Why can you not create an INSTEAD OF trigger with FOR EACH STATEMENT, and what timing options are allowed on a view for statement-level triggers?
Show answer
INSTEAD OF triggers replace the operation for a particular row of the view, so they exist only as FOR EACH ROW triggers. A view can still have statement-level BEFORE and AFTER triggers, which fire once per statement and do not see individual rows.