I am using the following trigger to check that the referenced table has the type that I want.
I can use check_constraint(changeset, field, opts \\ [])
, but it is not possible to put a constraint with a foreign table,
CREATE OR REPLACE FUNCTION type_check() RETURNS trigger AS $$
DECLARE
required_type TEXT;
inserted_type TEXT;
inserted_id bigint;
BEGIN
EXECUTE 'SELECT $1.' || tg_argv[0] INTO inserted_id USING NEW;
required_type = tg_argv[1];
inserted_type = (SELECT TYPE FROM items WHERE ID = inserted_id);
IF inserted_type IS NULL OR required_type != inserted_type THEN
RAISE EXCEPTION 'Type mismatch: required: % and got %', required_type, inserted_type;
ELSE
RETURN NEW;
END IF;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER dummy_check BEFORE INSERT OR UPDATE ON dummy FOR EACH ROW EXECUTE FUNCTION type_check(item_id, cat);