I have 2 views:
CREATE VIEW v_foo AS
SELECT
foo.id AS id,
foo.name AS name,
foo.userId AS userId
FROM foo;
and
CREATE VIEW v_bar AS
SELECT
bar.id AS id,
bar.name AS name,
bar.fooId AS fooId,
foo.userId AS userId
FROM bar
JOIN foo ON foo.id = bar.fooId;
I'm trying to build an INSERT rule
CREATE OR REPLACE RULE v_bar_INSERT AS ON INSERT TO v_bar
DO INSTEAD(
INSERT INTO bar (name, fooId) VALUES (NEW.id, NEW.fooId)
RETURNING bar.id, bar.name, bar.fooId, NULL::integer
--we don't care about return values for userId
);
My issue is I need to check if a record exists on foo WHERE id=NEW.fooId AND userId=NEW.userId
, and fail the insert if it does not. Essentially, v_bar needs to inherit the userId through its relationship to foo, and ensure that when inserting a new record into bar, the id and userId exist as a pair in foo.
We're retooling a schema to work with an existing application layer, which is why the apparent silliness.