Instead Of Trigger Makes View Writable

A filtered view is read-only until an INSTEAD OF trigger routes inserts into the base table, stamping the hidden column the view never exposes.

SqlData Integrity

Code

snippet
CREATE TABLE authors (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name      text NOT NULL,
    published boolean NOT NULL DEFAULT false
);

CREATE VIEW published_authors AS
SELECT id, name FROM authors WHERE published;

-- plain views reject writes; an INSTEAD OF trigger makes the filtered view
-- writable by handing each row to a routing function
CREATE OR REPLACE FUNCTION publish_author()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    INSERT INTO authors (name, published)
    VALUES (NEW.name, true)
    RETURNING id INTO NEW.id;
    RETURN NEW;
END;
$$;

CREATE TRIGGER published_authors_insert
INSTEAD OF INSERT ON published_authors
FOR EACH ROW EXECUTE FUNCTION publish_author();

-- the write lands in the base table with published forced to true
INSERT INTO published_authors (name) VALUES ('Ada Lovelace');

SELECT id, name, published FROM authors;
SELECT id, name FROM published_authors;

How the pieces connect — Instead Of Trigger Makes View Writable

What runs here is SELECT / INSERT / CREATE — authors, new.id and published_authors are the objects involved.

The pieces that do the work: a WHERE clause constraining which rows the statement operates on; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

The authors table is the working surface here.

Core lines

CREATE VIEW published_authors AS
SELECT id, name FROM authors WHERE published;
CREATE OR REPLACE FUNCTION publish_author()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    INSERT INTO authors (name, published)
    VALUES (NEW.name, true)
    RETURNING id INTO NEW.id;
    RETURN NEW;
END;
$$;
CREATE TRIGGER published_authors_insert
INSTEAD OF INSERT ON published_authors
FOR EACH ROW EXECUTE FUNCTION publish_author();

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`authors`, `new.id`, `published_authors`.