=== Applying patches on top of PostgreSQL commit ID 48938780c3577835dda3dd17db4f8c968bb1e166 === /etc/rc.d/jail: WARNING: Per-jail configuration via jail_* variables is obsolete. Please consider migrating to /etc/jail.conf. Fri Nov 13 02:05:30 UTC 2026 On branch cf/6825 nothing to commit, working tree clean === using 'git am' to apply patch ./v11-REL_14_STABLE-0001-Don-t-free-a-cached-RI-plan-that-m.patch === Applying: Don't free a cached RI plan that may be in use Using index info to reconstruct a base tree... M src/backend/access/transam/xact.c M src/backend/utils/adt/ri_triggers.c M src/include/commands/trigger.h M src/test/regress/expected/foreign_key.out M src/test/regress/sql/foreign_key.sql Falling back to patching base and 3-way merge... Auto-merging src/test/regress/sql/foreign_key.sql CONFLICT (content): Merge conflict in src/test/regress/sql/foreign_key.sql Auto-merging src/test/regress/expected/foreign_key.out CONFLICT (content): Merge conflict in src/test/regress/expected/foreign_key.out Auto-merging src/include/commands/trigger.h Auto-merging src/backend/utils/adt/ri_triggers.c CONFLICT (content): Merge conflict in src/backend/utils/adt/ri_triggers.c Auto-merging src/backend/access/transam/xact.c error: Failed to merge in the changes. hint: Use 'git am --show-current-patch=diff' to see the failed patch Patch failed at 0001 Don't free a cached RI plan that may be in use When you have resolved this problem, run "git am --continue". If you prefer to skip this patch, run "git am --skip" instead. To restore the original branch and stop patching, run "git am --abort". === using patch(1) to apply patch ./v11-REL_14_STABLE-0001-Don-t-free-a-cached-RI-plan-that-m.patch === patching file src/backend/access/transam/xact.c Hunk #1 FAILED at 2301. Hunk #2 FAILED at 2589. Hunk #3 FAILED at 2802. 3 out of 3 hunks FAILED -- saving rejects to file src/backend/access/transam/xact.c.rej patching file src/backend/utils/adt/ri_triggers.c Hunk #1 succeeded at 333 with fuzz 2 (offset 171 lines). Hunk #2 FAILED at 223. Hunk #3 FAILED at 2271. Hunk #4 FAILED at 2356. Hunk #5 FAILED at 2690. Hunk #6 succeeded at 2609 with fuzz 1 (offset -120 lines). Hunk #7 succeeded at 4311 with fuzz 2 (offset 1257 lines). 4 out of 7 hunks FAILED -- saving rejects to file src/backend/utils/adt/ri_triggers.c.rej patching file src/include/commands/trigger.h Hunk #1 succeeded at 281 with fuzz 2 (offset 8 lines). patching file src/test/regress/expected/foreign_key.out Hunk #1 FAILED at 2800. 1 out of 1 hunk FAILED -- saving rejects to file src/test/regress/expected/foreign_key.out.rej patching file src/test/regress/sql/foreign_key.sql Hunk #1 FAILED at 1986. 1 out of 1 hunk FAILED -- saving rejects to file src/test/regress/sql/foreign_key.sql.rej Unstaged changes after reset: M src/backend/utils/adt/ri_triggers.c M src/include/commands/trigger.h Removing src/backend/access/transam/xact.c.rej Removing src/backend/utils/adt/ri_triggers.c.rej Removing src/test/regress/expected/foreign_key.out.rej Removing src/test/regress/sql/foreign_key.sql.rej === using 'git apply' to apply patch ./v11-REL_14_STABLE-0001-Don-t-free-a-cached-RI-plan-that-m.patch === Applied patch to 'src/backend/access/transam/xact.c' cleanly. Applied patch to 'src/backend/utils/adt/ri_triggers.c' with conflicts. Applied patch to 'src/include/commands/trigger.h' cleanly. Applied patch to 'src/test/regress/expected/foreign_key.out' with conflicts. Applied patch to 'src/test/regress/sql/foreign_key.sql' with conflicts. U src/backend/utils/adt/ri_triggers.c U src/test/regress/expected/foreign_key.out U src/test/regress/sql/foreign_key.sql diff --cc src/backend/utils/adt/ri_triggers.c index ab3419d6148,611111f2ce1..00000000000 --- a/src/backend/utils/adt/ri_triggers.c +++ b/src/backend/utils/adt/ri_triggers.c @@@ -215,6 -162,27 +215,30 @@@ typedef struct RI_CompareHashEntr FmgrInfo cast_func_finfo; /* in case we must coerce input */ } RI_CompareHashEntry; ++<<<<<<< ours ++======= + /* + * Stack of the plans being executed by ri_PerformCheck() calls currently + * running, i.e. RI queries whose SPI_execute_snapshot() has not returned. + * Innermost of those appears last in the array. A plan that + * ri_FetchPreparedPlan() finds invalid cannot be freed while it is on this + * stack. It instead goes on ri_plan_dead_list and is freed by + * ri_FreeDeadPlans() once it is no longer on the stack, which is checked + * whenever a check finishes normally, or by AtEOXact_RI() at the latest. + * Both live in TopMemoryContext. + * + * ri_PerformCheck() pops its plan whether the query returns or an error + * is thrown, by restoring the depth it saw at push time, so the stack is + * exact at all times. A plan on the stack is never freed until the stack + * is cut back past it, so no entry can dangle. + */ + static SPIPlanPtr *ri_executing_plans = NULL; + static int ri_executing_depth = 0; + static int ri_executing_maxdepth = 0; + static List *ri_plan_dead_list = NIL; + + ++>>>>>>> theirs /* * Local data */ @@@ -2740,10 -2363,6 +2764,13 @@@ ri_PerformCheck(const RI_ConstraintInf /* * Finally we can run the query. * ++<<<<<<< ours + * Set fire_triggers to false to ensure that AFTER triggers are queued in + * the outer query's after-trigger context and fire after all RI updates + * on the same row are complete, rather than immediately. + * ++======= ++>>>>>>> theirs * The plan is on the stack of executing plans while the query runs, so * that a nested check finding it invalid does not free it; see * ri_FetchPreparedPlan(). Pop it even if the query throws an error, so @@@ -3799,92 -2782,91 +3826,176 @@@ ri_HashPreparedPlan(RI_QueryKey *key, S entry->plan = plan; } + /* + * ri_PushExecutingPlan - + * + * Record that ri_PerformCheck() is about to execute plan. Returns the depth + * of the stack before the push; the caller pops by setting + * ri_executing_depth back to it when SPI_execute_snapshot() returns or + * throws an error. + */ + static int + ri_PushExecutingPlan(SPIPlanPtr plan) + { + int depth = ri_executing_depth; + + if (ri_executing_depth >= ri_executing_maxdepth) + { + int newmax = Max(8, ri_executing_maxdepth * 2); + + if (ri_executing_plans == NULL) + ri_executing_plans = (SPIPlanPtr *) + MemoryContextAlloc(TopMemoryContext, + newmax * sizeof(SPIPlanPtr)); + else + ri_executing_plans = (SPIPlanPtr *) + repalloc(ri_executing_plans, newmax * sizeof(SPIPlanPtr)); + ri_executing_maxdepth = newmax; + } + ri_executing_plans[ri_executing_depth++] = plan; + + return depth; + } + + /* + * ri_PlanIsExecuting - + * + * Is plan being executed by an ri_PerformCheck() call in progress? The + * stack is as deep as RI checks nest, so a linear scan is fine. + */ + static bool + ri_PlanIsExecuting(SPIPlanPtr plan) + { + for (int i = 0; i < ri_executing_depth; i++) + { + if (ri_executing_plans[i] == plan) + return true; + } + return false; + } + + /* + * ri_FreeDeadPlans - + * + * Free the plans queued on ri_plan_dead_list that no RI check is executing + * any more, keeping the others queued. With the stack empty, that is all of + * them. + */ + static void + ri_FreeDeadPlans(void) + { + List *plans = ri_plan_dead_list; + ListCell *lc; + + /* + * Detach the list from the static before freeing, so that an error while + * freeing a plan does not leave a dangling pointer to a half-freed plan + * in it. Not expected, but we may be called from the abort path, where + * no further cleanup pass would come to fix that up. + */ + ri_plan_dead_list = NIL; + + foreach(lc, plans) + { + SPIPlanPtr plan = (SPIPlanPtr) lfirst(lc); + + if (ri_PlanIsExecuting(plan)) + continue; + SPI_freeplan(plan); + plans = foreach_delete_current(plans, lc); + } + + /* Put back whatever is still executing, if any. */ + Assert(plans == NIL || ri_executing_depth > 0); + ri_plan_dead_list = plans; + } + +/* + * ri_PushExecutingPlan - + * + * Record that ri_PerformCheck() is about to execute plan. Returns the depth + * of the stack before the push; the caller pops by setting + * ri_executing_depth back to it when SPI_execute_snapshot() returns or + * throws an error. + */ +static int +ri_PushExecutingPlan(SPIPlanPtr plan) +{ + int depth = ri_executing_depth; + + if (ri_executing_depth >= ri_executing_maxdepth) + { + int newmax = Max(8, ri_executing_maxdepth * 2); + + if (ri_executing_plans == NULL) + ri_executing_plans = (SPIPlanPtr *) + MemoryContextAlloc(TopMemoryContext, + newmax * sizeof(SPIPlanPtr)); + else + ri_executing_plans = (SPIPlanPtr *) + repalloc(ri_executing_plans, newmax * sizeof(SPIPlanPtr)); + ri_executing_maxdepth = newmax; + } + ri_executing_plans[ri_executing_depth++] = plan; + + return depth; +} + +/* + * ri_PlanIsExecuting - + * + * Is plan being executed by an ri_PerformCheck() call in progress? The + * stack is as deep as RI checks nest, so a linear scan is fine. + */ +static bool +ri_PlanIsExecuting(SPIPlanPtr plan) +{ + for (int i = 0; i < ri_executing_depth; i++) + { + if (ri_executing_plans[i] == plan) + return true; + } + return false; +} + +/* + * ri_FreeDeadPlans - + * + * Free the plans queued on ri_plan_dead_list that no RI check is executing + * any more, keeping the others queued. With the stack empty, that is all of + * them. + */ +static void +ri_FreeDeadPlans(void) +{ + List *plans = ri_plan_dead_list; + ListCell *lc; + + /* + * Detach the list from the static before freeing, so that an error while + * freeing a plan does not leave a dangling pointer to a half-freed plan + * in it. Not expected, but we may be called from the abort path, where + * no further cleanup pass would come to fix that up. + */ + ri_plan_dead_list = NIL; + + foreach(lc, plans) + { + SPIPlanPtr plan = (SPIPlanPtr) lfirst(lc); + + if (ri_PlanIsExecuting(plan)) + continue; + SPI_freeplan(plan); + plans = foreach_delete_current(plans, lc); + } + + /* Put back whatever is still executing, if any. */ + Assert(plans == NIL || ri_executing_depth > 0); + ri_plan_dead_list = plans; +} + + /* * ri_KeysEqual - * @@@ -4162,40 -3112,24 +4273,58 @@@ RI_FKey_trigger_type(Oid tgfoid * AtEOXact_RI * End-of-transaction cleanup for referential integrity. * ++<<<<<<< ours + * This releases objects that were detached from the RI caches during the + * transaction but could not be freed on the spot, because an RI check + * further up the stack might still have been using them: + * + * - fast-path metadata detached by InvalidateConstraintCacheCallBack(), + * queued on ri_fpmeta_dead_list; + * + * - SPI plans found invalid by ri_FetchPreparedPlan() while a check was + * executing them, queued on ri_plan_dead_list. These are normally freed + * as soon as the check executing them finishes; we only see them here if + * an error interrupted that check and no later check finished normally in + * the transaction. + * + * Here no RI check can be in progress, so both can be released. The + * release is the same on the commit and the abort path; isCommit only + * decides whether we can assert that the stack of executing plans is empty. + * + * There is no AtEOSubXact_RI() counterpart. Nothing here is scoped to a + * subtransaction: a detached object stays reachable from its dead list + * whichever subtransaction detached it, and a check using one may be ++======= + * Release the SPI plans that ri_FetchPreparedPlan() found invalid while a + * check was executing them and queued on ri_plan_dead_list. These are + * normally freed as soon as the check executing them finishes; we only see + * them here if an error interrupted that check and no later check finished + * normally in the transaction. Here no RI check can be in progress, so they + * can be released. The release is the same on the commit and the abort + * path; isCommit only decides whether we can assert that the stack of + * executing plans is empty. + * + * There is no AtEOSubXact_RI() counterpart. Nothing here is scoped to a + * subtransaction: a detached plan stays reachable from the dead list + * whichever subtransaction detached it, and a check executing it may be ++>>>>>>> theirs * running at an outer level, so releasing at subtransaction end would be * unsafe as well as unnecessary. */ void AtEOXact_RI(bool isCommit) { ++<<<<<<< ours + while (ri_fpmeta_dead_list != NULL) + { + FastPathMeta *dead = ri_fpmeta_dead_list; + + ri_fpmeta_dead_list = dead->next_dead; + pfree(dead); + } + ++======= ++>>>>>>> theirs /* * No RI check can be in progress here, so clear the stack. On commit it * must be empty already, since ri_PerformCheck() pops its plan whether diff --cc src/test/regress/expected/foreign_key.out index 95a0531f3a0,96c3cc91035..00000000000 --- a/src/test/regress/expected/foreign_key.out +++ b/src/test/regress/expected/foreign_key.out @@@ -3648,436 -2800,12 +3648,443 @@@ SET client_min_messages TO warning DROP SCHEMA fkpart12 CASCADE; RESET client_min_messages; RESET search_path; ++<<<<<<< ours +-- Exercise the column mapping code with foreign keys. In this test we'll +-- create a partitioned table which has a partition with a dropped column and +-- check to ensure that an UPDATE cascades the changes correctly to the +-- partitioned table. +CREATE SCHEMA fkpart13; +SET search_path TO fkpart13; +CREATE TABLE fkpart13_t1 (a int PRIMARY KEY); +CREATE TABLE fkpart13_t2 ( + part_id int PRIMARY KEY, + column_to_drop int, + FOREIGN KEY (part_id) REFERENCES fkpart13_t1 ON UPDATE CASCADE ON DELETE CASCADE +) PARTITION BY LIST (part_id); +CREATE TABLE fkpart13_t2_p1 PARTITION OF fkpart13_t2 FOR VALUES IN (1); +-- drop the column +ALTER TABLE fkpart13_t2 DROP COLUMN column_to_drop; +-- create a new partition without the dropped column +CREATE TABLE fkpart13_t2_p2 PARTITION OF fkpart13_t2 FOR VALUES IN (2); +CREATE TABLE fkpart13_t3 ( + a int NOT NULL, + FOREIGN KEY (a) + REFERENCES fkpart13_t2 + ON UPDATE CASCADE ON DELETE CASCADE +); +INSERT INTO fkpart13_t1 (a) VALUES (1); +INSERT INTO fkpart13_t2 (part_id) VALUES (1); +INSERT INTO fkpart13_t3 (a) VALUES (1); +-- Test that a cascading update works correctly with the dropped column +UPDATE fkpart13_t1 SET a = 2 WHERE a = 1; +SELECT tableoid::regclass,* FROM fkpart13_t2; + tableoid | part_id +----------------+--------- + fkpart13_t2_p2 | 2 +(1 row) + +SELECT tableoid::regclass,* FROM fkpart13_t3; + tableoid | a +-------------+--- + fkpart13_t3 | 2 +(1 row) + +-- Exercise code in ExecGetTriggerResultRel() as there's been previous issues +-- with ResultRelInfos being returned with the incorrect ri_RootResultRelInfo +WITH cte AS ( + UPDATE fkpart13_t2_p1 SET part_id = part_id +) UPDATE fkpart13_t1 SET a = 2 WHERE a = 1; +DROP SCHEMA fkpart13 CASCADE; +NOTICE: drop cascades to 3 other objects +DETAIL: drop cascades to table fkpart13_t1 +drop cascades to table fkpart13_t2 +drop cascades to table fkpart13_t3 +RESET search_path; +-- Test the fast-path ALTER TABLE validation path. RLS on the referenced +-- table makes RI_Initial_Check() decline the set-based check, so validation +-- invokes the RI trigger once per referencing row. +CREATE ROLE regress_fk_fastpath_role; +CREATE TABLE fp_pk_alter (a int PRIMARY KEY); +INSERT INTO fp_pk_alter SELECT generate_series(1, 100); +ALTER TABLE fp_pk_alter ENABLE ROW LEVEL SECURITY; +CREATE POLICY fp_pk_alter_all ON fp_pk_alter + FOR ALL USING (true) WITH CHECK (true); +GRANT REFERENCES, SELECT ON fp_pk_alter TO regress_fk_fastpath_role; +CREATE TABLE fp_fk_alter (a int); +INSERT INTO fp_fk_alter SELECT generate_series(1, 100); +ALTER TABLE fp_fk_alter OWNER TO regress_fk_fastpath_role; +-- Validation path: should succeed +SET ROLE regress_fk_fastpath_role; +ALTER TABLE fp_fk_alter ADD FOREIGN KEY (a) REFERENCES fp_pk_alter; +INSERT INTO fp_fk_alter VALUES (101); -- should fail (constraint active) +ERROR: insert or update on table "fp_fk_alter" violates foreign key constraint "fp_fk_alter_a_fkey" +DETAIL: Key (a)=(101) is not present in table "fp_pk_alter". +RESET ROLE; +DROP TABLE fp_fk_alter, fp_pk_alter; +-- Separate test: validation catches existing violation +CREATE TABLE fp_pk_alter2 (a int PRIMARY KEY); +INSERT INTO fp_pk_alter2 VALUES (1); +ALTER TABLE fp_pk_alter2 ENABLE ROW LEVEL SECURITY; +CREATE POLICY fp_pk_alter2_all ON fp_pk_alter2 + FOR ALL USING (true) WITH CHECK (true); +GRANT REFERENCES, SELECT ON fp_pk_alter2 TO regress_fk_fastpath_role; +CREATE TABLE fp_fk_alter2 (a int); +INSERT INTO fp_fk_alter2 VALUES (1), (200); -- 200 has no PK match +ALTER TABLE fp_fk_alter2 OWNER TO regress_fk_fastpath_role; +SET ROLE regress_fk_fastpath_role; +ALTER TABLE fp_fk_alter2 ADD FOREIGN KEY (a) REFERENCES fp_pk_alter2; -- should fail +ERROR: insert or update on table "fp_fk_alter2" violates foreign key constraint "fp_fk_alter2_a_fkey" +DETAIL: Key (a)=(200) is not present in table "fp_pk_alter2". +RESET ROLE; +DROP TABLE fp_fk_alter2, fp_pk_alter2; +DROP ROLE regress_fk_fastpath_role; +-- Tests that the fast-path handles multiple constraints +CREATE TABLE fp_pk1 (a int PRIMARY KEY); +CREATE TABLE fp_pk2 (b int PRIMARY KEY); +INSERT INTO fp_pk1 VALUES (1); +INSERT INTO fp_pk2 VALUES (1); +CREATE TABLE fp_multi_fk ( + a int REFERENCES fp_pk1, + b int REFERENCES fp_pk2 +); +INSERT INTO fp_multi_fk VALUES (1, 1); -- two constraints +INSERT INTO fp_multi_fk VALUES (1, 2); -- second constraint fails +ERROR: insert or update on table "fp_multi_fk" violates foreign key constraint "fp_multi_fk_b_fkey" +DETAIL: Key (b)=(2) is not present in table "fp_pk2". +DROP TABLE fp_multi_fk, fp_pk1, fp_pk2; +-- Test that fast-path handles deferred constraints and SET CONSTRAINTS IMMEDIATE +CREATE TABLE fp_pk_defer (a int PRIMARY KEY); +CREATE TABLE fp_fk_defer (a int REFERENCES fp_pk_defer DEFERRABLE INITIALLY DEFERRED); +INSERT INTO fp_pk_defer VALUES (1), (2); +BEGIN; +INSERT INTO fp_fk_defer VALUES (1); +INSERT INTO fp_fk_defer VALUES (2); +SET CONSTRAINTS ALL IMMEDIATE; -- fires deferred checks here +INSERT INTO fp_fk_defer VALUES (3); -- should fail +ERROR: insert or update on table "fp_fk_defer" violates foreign key constraint "fp_fk_defer_a_fkey" +DETAIL: Key (a)=(3) is not present in table "fp_pk_defer". +COMMIT; +DROP TABLE fp_pk_defer, fp_fk_defer; +-- A deferred FK check queued while firing deferred triggers at commit must +-- not be lost. An RI check runs during the deferred firing loop and can run +-- user cast code whose DML queues a further deferred check; that check must +-- still fire. fk_defer_main's deferred check runs a cast whose function +-- inserts a violating row into fk_defer_t2, queueing fk_defer_t2's own +-- deferred check, which must still be reported. +CREATE TABLE fk_defer_t2_pk (id int PRIMARY KEY); +CREATE TABLE fk_defer_t2 (a int REFERENCES fk_defer_t2_pk(id) + DEFERRABLE INITIALLY DEFERRED); +CREATE TYPE fk_defer_vch AS (v int); +CREATE FUNCTION fk_defer_cast(fk_defer_vch) RETURNS int + LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO fk_defer_t2 VALUES (999); -- 999 absent, queues deferred check + RETURN $1.v; +END$$; +CREATE CAST (fk_defer_vch AS int) WITH FUNCTION fk_defer_cast(fk_defer_vch) + AS IMPLICIT; +CREATE TABLE fk_defer_main_pk (id int PRIMARY KEY); +INSERT INTO fk_defer_main_pk VALUES (1); +CREATE TABLE fk_defer_main (a fk_defer_vch REFERENCES fk_defer_main_pk(id) + DEFERRABLE INITIALLY DEFERRED); +-- At COMMIT the queued fk_defer_t2 check must fire and report the violation +BEGIN; +INSERT INTO fk_defer_main VALUES (row(1)::fk_defer_vch); +COMMIT; -- expected: ERROR on fk_defer_t2_a_fkey +ERROR: insert or update on table "fk_defer_t2" violates foreign key constraint "fk_defer_t2_a_fkey" +DETAIL: Key (a)=(999) is not present in table "fk_defer_t2_pk". +-- The queued check must fire at transaction end, not early: making the +-- referenced row present in the same transaction lets the commit succeed. +INSERT INTO fk_defer_t2_pk VALUES (999); +BEGIN; +INSERT INTO fk_defer_main VALUES (row(1)::fk_defer_vch); +COMMIT; -- expected: success +DROP TABLE fk_defer_main, fk_defer_main_pk, fk_defer_t2, fk_defer_t2_pk; +DROP CAST (fk_defer_vch AS int); +DROP FUNCTION fk_defer_cast(fk_defer_vch); +DROP TYPE fk_defer_vch; +-- FK check must see PK rows inserted by earlier AFTER triggers +-- firing on the same statement +CREATE TABLE fp_pk_cci (a int PRIMARY KEY); +CREATE TABLE fp_fk_cci (a int REFERENCES fp_pk_cci); +CREATE FUNCTION fp_auto_pk() RETURNS trigger AS $$ +BEGIN + RAISE NOTICE 'fp_auto_pk called'; + INSERT INTO fp_pk_cci VALUES (NEW.a); + RETURN NEW; +END $$ LANGUAGE plpgsql; +-- Name sorts before the RI trigger, so fires first per row +CREATE TRIGGER "AAA_auto" AFTER INSERT ON fp_fk_cci + FOR EACH ROW EXECUTE FUNCTION fp_auto_pk(); +-- Should succeed: AAA_auto provisions the PK row before RI check +INSERT INTO fp_fk_cci VALUES (1), (2), (3); +NOTICE: fp_auto_pk called +NOTICE: fp_auto_pk called +NOTICE: fp_auto_pk called +DROP TABLE fp_fk_cci, fp_pk_cci; +DROP FUNCTION fp_auto_pk; +-- An FK check must check EXECUTE, as the referenced table's owner, on the +-- functions it applies to the FK values: the equality operator's function +-- and, for an FK needing an implicit cast function, the cast. Validation of +-- a new constraint by a role that cannot use the bulk check (RLS is enabled +-- on the referenced table) runs per-row checks, through the fast path for +-- the operator case and through SPI for the cast case, since FK values that +-- need a cast function are not checked by the fast path. +-- +-- Wrapped with BEGIN...ROLLBACK to ensure opclasses used here don't interfere +-- with nearby tests. +BEGIN; +CREATE ROLE regress_ri_pkowner; +CREATE ROLE regress_ri_fkowner; +-- A private btree opclass whose equality function we can revoke without +-- affecting anything else. +CREATE FUNCTION regress_ri_int4eq(int4, int4) RETURNS bool + AS 'int4eq' LANGUAGE internal IMMUTABLE STRICT; +CREATE OPERATOR === (LEFTARG = int4, RIGHTARG = int4, + FUNCTION = regress_ri_int4eq, COMMUTATOR = ===, + RESTRICT = eqsel, JOIN = eqjoinsel); +CREATE OPERATOR CLASS regress_ri_int4_ops FOR TYPE int4 USING btree AS + OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 ===, OPERATOR 4 >=, OPERATOR 5 >, + FUNCTION 1 btint4cmp(int4, int4); +REVOKE EXECUTE ON FUNCTION regress_ri_int4eq(int4, int4) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION regress_ri_int4eq(int4, int4) TO regress_ri_fkowner; +-- An FK column type needing a user-defined implicit cast to the PK type. +CREATE TYPE fkenum AS ENUM ('one'); +CREATE FUNCTION fkenum_to_int4(fkenum) RETURNS int4 + AS 'SELECT 1' LANGUAGE sql IMMUTABLE STRICT; +CREATE CAST (fkenum AS int4) WITH FUNCTION fkenum_to_int4(fkenum) AS IMPLICIT; +REVOKE EXECUTE ON FUNCTION fkenum_to_int4(fkenum) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION fkenum_to_int4(fkenum) TO regress_ri_fkowner; +CREATE TABLE pktable_acl_op (a int4); +CREATE UNIQUE INDEX ON pktable_acl_op (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_cast (a int4 PRIMARY KEY); +CREATE TABLE pktable_acl_op_part (a int4) PARTITION BY LIST (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_op_part1 PARTITION OF pktable_acl_op_part DEFAULT; +CREATE UNIQUE INDEX ON pktable_acl_op_part (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_cast_part (a int4 PRIMARY KEY) PARTITION BY LIST (a); +INSERT INTO pktable_acl_op VALUES (1); +INSERT INTO pktable_acl_cast VALUES (1); +ALTER TABLE pktable_acl_op OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_cast OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_op_part OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_cast_part OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_op ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_cast ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_op_part ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_cast_part ENABLE ROW LEVEL SECURITY; +GRANT REFERENCES ON pktable_acl_op, pktable_acl_cast, pktable_acl_op_part, pktable_acl_cast_part TO regress_ri_fkowner; +CREATE TABLE fktable_acl_op (a int4); +CREATE TABLE fktable_acl_cast (a fkenum); +INSERT INTO fktable_acl_op VALUES (1); +INSERT INTO fktable_acl_cast VALUES ('one'); +ALTER TABLE fktable_acl_op OWNER TO regress_ri_fkowner; +ALTER TABLE fktable_acl_cast OWNER TO regress_ri_fkowner; +-- The FK owner holds EXECUTE on both functions; the PK owner does not, and +-- it is the PK owner whose privileges apply. +SET ROLE regress_ri_fkowner; +SAVEPOINT s; +ALTER TABLE fktable_acl_op + ADD FOREIGN KEY (a) REFERENCES pktable_acl_op (a); -- fails +ERROR: permission denied for function regress_ri_int4eq +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_cast + ADD FOREIGN KEY (a) REFERENCES pktable_acl_cast (a); -- fails (SPI path message) +ERROR: permission denied for function fkenum_to_int4 +CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."pktable_acl_cast" x WHERE "a" OPERATOR(pg_catalog.=) $1::pg_catalog.int4 FOR KEY SHARE OF x" +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_op + ADD FOREIGN KEY (a) REFERENCES pktable_acl_op_part (a); -- fails (SPI path message) +ERROR: permission denied for function regress_ri_int4eq +CONTEXT: SQL statement "SELECT 1 FROM "public"."pktable_acl_op_part" x WHERE "a" OPERATOR(public.===) $1 FOR KEY SHARE OF x" +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_cast + ADD FOREIGN KEY (a) REFERENCES pktable_acl_cast_part (a); -- fails (SPI path message) +ERROR: permission denied for function fkenum_to_int4 +CONTEXT: SQL statement "SELECT 1 FROM "public"."pktable_acl_cast_part" x WHERE "a" OPERATOR(pg_catalog.=) $1::pg_catalog.int4 FOR KEY SHARE OF x" +ROLLBACK TO SAVEPOINT s; +RESET ROLE; +ROLLBACK; +-- A STABLE equality function used by an FK check must see changes made by +-- earlier AFTER triggers, using the check's snapshot rather than the outer +-- query's snapshot. Compare the fast path (pk_fast) with a partitioned-parent +-- SPI check (pk_spi). The equality function of the referenced index's +-- opclass is the user code that runs during a fast-path check. +BEGIN; +CREATE SCHEMA ri_snapshot; +SET LOCAL search_path = ri_snapshot, pg_catalog; +CREATE TABLE lookup_rows (v int); +-- Considers two values equal only if a lookup row exists for them. +CREATE FUNCTION lookup_eq(a int, b int) RETURNS bool +LANGUAGE plpgsql STABLE AS $$ +BEGIN + RETURN a = b AND EXISTS (SELECT 1 FROM lookup_rows AS r WHERE r.v = a); +END; +$$; +CREATE OPERATOR === (LEFTARG = int, RIGHTARG = int, FUNCTION = lookup_eq); +CREATE OPERATOR CLASS lookup_ops FOR TYPE int USING btree AS + OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 ===, OPERATOR 4 >=, OPERATOR 5 >, + FUNCTION 1 btint4cmp(int, int); +CREATE TABLE pk_fast (v int); +CREATE UNIQUE INDEX ON pk_fast (v lookup_ops); +CREATE TABLE pk_spi (v int) PARTITION BY RANGE (v lookup_ops); +CREATE TABLE pk_spi_p PARTITION OF pk_spi + FOR VALUES FROM (MINVALUE) TO (MAXVALUE); +CREATE UNIQUE INDEX ON pk_spi (v lookup_ops); +INSERT INTO pk_fast VALUES (1); +INSERT INTO pk_spi VALUES (1); +CREATE TABLE fk_fast (k int REFERENCES pk_fast(v)); +CREATE TABLE fk_spi (k int REFERENCES pk_spi(v)); +CREATE FUNCTION add_lookup_row() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO lookup_rows VALUES (NEW.k); + RETURN NEW; +END; +$$; +-- Sort before the RI trigger, so the lookup row is inserted first. +CREATE TRIGGER "AAA_lookup" AFTER INSERT ON fk_fast + FOR EACH ROW EXECUTE FUNCTION add_lookup_row(); +CREATE TRIGGER "AAA_lookup" AFTER INSERT ON fk_spi + FOR EACH ROW EXECUTE FUNCTION add_lookup_row(); +-- Both checks must succeed. Without the check's snapshot active, the +-- STABLE equality function misses the lookup row, so no PK row matches. +INSERT INTO fk_fast VALUES (1); +SELECT count(*) FROM fk_fast; + count +------- + 1 +(1 row) + +DELETE FROM lookup_rows; +INSERT INTO fk_spi VALUES (1); +SELECT count(*) FROM fk_spi; + count +------- + 1 +(1 row) + +ROLLBACK; +-- Multi-column FK: exercises direct per-row probing with composite keys +CREATE TABLE fp_pk_multi (a int, b int, PRIMARY KEY (a, b)); +INSERT INTO fp_pk_multi SELECT i, i FROM generate_series(1, 100) i; +CREATE TABLE fp_fk_multi (x int, a int, b int, + FOREIGN KEY (a, b) REFERENCES fp_pk_multi); +INSERT INTO fp_fk_multi SELECT i, i, i FROM generate_series(1, 100) i; +INSERT INTO fp_fk_multi VALUES (1, 999, 999); +ERROR: insert or update on table "fp_fk_multi" violates foreign key constraint "fp_fk_multi_a_b_fkey" +DETAIL: Key (a, b)=(999, 999) is not present in table "fp_pk_multi". +DROP TABLE fp_fk_multi, fp_pk_multi; +-- Multi-column FK with columns in different order than PK index. +-- The FK references columns in a different order than they appear in the +-- PK's primary key, which requires mapping constraint key positions to +-- index column positions when building scan keys. +CREATE TABLE fp_pk_order (a int, b text, c int, PRIMARY KEY (a, b, c)); +INSERT INTO fp_pk_order VALUES (1, 'one', 10), (2, 'two', 20); +CREATE TABLE fp_fk_order ( + x int, + c int, + b text, + a int, + FOREIGN KEY (a, c, b) REFERENCES fp_pk_order (a, c, b) -- c and b swapped +); +INSERT INTO fp_fk_order VALUES (1, 10, 'one', 1); -- should succeed +INSERT INTO fp_fk_order VALUES (2, 20, 'two', 2); -- should succeed +INSERT INTO fp_fk_order VALUES (3, 99, 'none', 9); -- should fail +ERROR: insert or update on table "fp_fk_order" violates foreign key constraint "fp_fk_order_a_c_b_fkey" +DETAIL: Key (a, c, b)=(9, 99, none) is not present in table "fp_pk_order". +DROP TABLE fp_fk_order, fp_pk_order; +-- Same-type columns in different order: +CREATE TABLE fp_pk_same (c1 int, c2 int, PRIMARY KEY (c1, c2)); +INSERT INTO fp_pk_same VALUES (1, 2); +CREATE TABLE fp_fk_same (c1 int, c2 int, + FOREIGN KEY (c2, c1) REFERENCES fp_pk_same (c2, c1)); +INSERT INTO fp_fk_same VALUES (1, 2); -- should succeed +INSERT INTO fp_fk_same VALUES (9, 9); -- should fail +ERROR: insert or update on table "fp_fk_same" violates foreign key constraint "fp_fk_same_c2_c1_fkey" +DETAIL: Key (c2, c1)=(9, 9) is not present in table "fp_pk_same". +DROP TABLE fp_fk_same, fp_pk_same; +-- Deferred constraint: deferred check fired at COMMIT, not at statement end +CREATE TABLE fp_pk_commit (a int PRIMARY KEY); +CREATE TABLE fp_fk_commit (a int REFERENCES fp_pk_commit + DEFERRABLE INITIALLY DEFERRED); +INSERT INTO fp_pk_commit VALUES (1); +BEGIN; +INSERT INTO fp_fk_commit VALUES (1); +INSERT INTO fp_fk_commit VALUES (1); +INSERT INTO fp_fk_commit VALUES (999); +COMMIT; +ERROR: insert or update on table "fp_fk_commit" violates foreign key constraint "fp_fk_commit_a_fkey" +DETAIL: Key (a)=(999) is not present in table "fp_pk_commit". +DROP TABLE fp_fk_commit, fp_pk_commit; +-- Cross-type FK with bulk insert: int8 FK referencing int4 PK, +-- values cast during array construction +CREATE TABLE fp_pk_cross (a int4 PRIMARY KEY); +INSERT INTO fp_pk_cross SELECT generate_series(1, 200); +CREATE TABLE fp_fk_cross (a int8 REFERENCES fp_pk_cross); +INSERT INTO fp_fk_cross SELECT generate_series(1, 200); +INSERT INTO fp_fk_cross VALUES (999); +ERROR: insert or update on table "fp_fk_cross" violates foreign key constraint "fp_fk_cross_a_fkey" +DETAIL: Key (a)=(999) is not present in table "fp_pk_cross". +DROP TABLE fp_fk_cross, fp_pk_cross; +-- Domain-typed FK column whose base type differs from the PK type: the +-- fast path must look through the domain to its base type when deciding +-- whether the cross-type comparison needs a cast. Otherwise valid rows +-- were wrongly rejected with "no conversion function from ... to ...". +CREATE DOMAIN fp_int8dom AS int8; +CREATE TABLE fp_pk_dom (a int4 PRIMARY KEY); +INSERT INTO fp_pk_dom SELECT generate_series(1, 200); +CREATE TABLE fp_fk_dom (a fp_int8dom REFERENCES fp_pk_dom); +INSERT INTO fp_fk_dom SELECT generate_series(1, 200); +INSERT INTO fp_fk_dom VALUES (999); +ERROR: insert or update on table "fp_fk_dom" violates foreign key constraint "fp_fk_dom_a_fkey" +DETAIL: Key (a)=(999) is not present in table "fp_pk_dom". +INSERT INTO fp_fk_dom VALUES (NULL); +DROP TABLE fp_fk_dom, fp_pk_dom; +DROP DOMAIN fp_int8dom; +-- Re-entrant FK check: DML on the same FK table from a cast function +CREATE TABLE fp_reentry_pk (id int PRIMARY KEY); +INSERT INTO fp_reentry_pk VALUES (1), (2); +CREATE TYPE fp_vch AS (v int); +CREATE FUNCTION fp_vcast(fp_vch) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF $1.v = 1 THEN + INSERT INTO fp_reentry_fk VALUES (row(2)::fp_vch); + END IF; + RETURN $1.v; +END$$; +CREATE CAST (fp_vch AS int) WITH FUNCTION fp_vcast(fp_vch) AS IMPLICIT; +CREATE TABLE fp_reentry_fk (a fp_vch + REFERENCES fp_reentry_pk (id)); +-- The cast re-enters with DML on the same FK, so the inner check looks up +-- the same cached SPI plan while the outer check is still executing it. +-- If the plan has been invalidated meanwhile (as CLOBBER_CACHE_ALWAYS makes +-- certain), the inner check must not free it out from under the outer one. +INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2); +SELECT a, count(*) FROM fp_reentry_fk GROUP BY a ORDER BY a; + a | count +-----+------- + (1) | 2 + (2) | 2 +(2 rows) + +DROP TABLE fp_reentry_fk, fp_reentry_pk; +DROP CAST (fp_vch AS int); +DROP FUNCTION fp_vcast(fp_vch); +DROP TYPE fp_vch; ++======= ++>>>>>>> theirs -- Re-entrant ON DELETE CASCADE whose trigger invalidates the cached RI plan. -- The cascade for id = 2 runs a BEFORE DELETE trigger that does GRANT/REVOKE -- on the table, invalidating the cached plan the cascade is executing, and -- then deletes more rows, whose own cascade fetches that plan again. The -- inner fetch must not free the plan out from under the outer cascade. ++<<<<<<< ours +-- Unlike the case above, this reproduces the crash without cache clobbering. ++======= + -- This reproduces the crash without cache clobbering. ++>>>>>>> theirs CREATE TABLE fk_self_ref ( id int PRIMARY KEY, parent_id int REFERENCES fk_self_ref (id) ON DELETE CASCADE @@@ -4228,222 -2956,3 +4235,225 @@@ DROP CAST (fk_err_vch AS int) DROP FUNCTION fk_err_vcast(fk_err_vch); DROP TYPE fk_err_vch; DROP ROLE regress_fk_err_role; ++<<<<<<< ours +-- +-- Cache invalidation arriving during a fast-path check. +-- +-- The equality function of the referenced index's opclass runs while the +-- fast path scans the index. One that performs DDL raises an invalidation +-- there, detaching the constraint's fast-path metadata while the check is +-- still using it. This is done in a transaction that is rolled back, so that +-- other tests never see the operator class. +-- +BEGIN; +-- Renames the constraint the first time it is called, and so raises an +-- invalidation partway through the check. Guarded on the catalog so the +-- second and later calls are no-ops. +CREATE FUNCTION fp_inval_eq(int4, int4) RETURNS bool AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_constraint + WHERE conrelid = 'fktable_inval'::regclass + AND conname = 'fktable_inval_fk') THEN + EXECUTE 'ALTER TABLE fktable_inval' + ' RENAME CONSTRAINT fktable_inval_fk TO fktable_inval_fk2'; + END IF; + RETURN $1 OPERATOR(pg_catalog.=) $2; +END $$ LANGUAGE plpgsql; +CREATE OPERATOR =@= (LEFTARG = int4, RIGHTARG = int4, FUNCTION = fp_inval_eq); +CREATE OPERATOR CLASS fp_inval_ops FOR TYPE int4 USING btree AS + OPERATOR 1 pg_catalog.<, OPERATOR 2 pg_catalog.<=, OPERATOR 3 =@=, + OPERATOR 4 pg_catalog.>=, OPERATOR 5 pg_catalog.>, + FUNCTION 1 btint4cmp(int4, int4); +CREATE TABLE pktable_inval (a int4, b int4); +CREATE UNIQUE INDEX pktable_inval_a_b ON pktable_inval (a fp_inval_ops, b); +INSERT INTO pktable_inval VALUES (1, 1), (2, 2); +CREATE TABLE fktable_inval (a int4, b int4, + CONSTRAINT fktable_inval_fk FOREIGN KEY (a, b) + REFERENCES pktable_inval (a, b)); +-- The first row invalidates the metadata; the second check must repopulate +-- and use it safely. +INSERT INTO fktable_inval VALUES (1, 1), (2, 2); +-- Confirms the equality function actually ran and raised the invalidation. +-- Without this the insert above could pass merely by not exercising the path +-- at all. +SELECT conname FROM pg_constraint + WHERE conrelid = 'fktable_inval'::regclass AND contype = 'f'; + conname +------------------- + fktable_inval_fk2 +(1 row) + +SELECT count(*) FROM fktable_inval; + count +------- + 2 +(1 row) + +ROLLBACK; +-- An FK check locks the referenced row, which a read-only transaction does +-- not allow unless the referenced table is temporary. +CREATE TABLE fp_pk_ro (a int PRIMARY KEY); +INSERT INTO fp_pk_ro VALUES (1); +CREATE TABLE fp_fk_ro (a int REFERENCES fp_pk_ro DEFERRABLE INITIALLY DEFERRED); +BEGIN; +INSERT INTO fp_fk_ro VALUES (1); +SET TRANSACTION READ ONLY; +COMMIT; -- fails +ERROR: cannot execute SELECT FOR KEY SHARE in a read-only transaction +CREATE TEMP TABLE fp_pk_ro_tmp (a int PRIMARY KEY); +INSERT INTO fp_pk_ro_tmp VALUES (1); +CREATE TEMP TABLE fp_fk_ro_tmp (a int REFERENCES fp_pk_ro_tmp + DEFERRABLE INITIALLY DEFERRED); +BEGIN; +INSERT INTO fp_fk_ro_tmp VALUES (1); +SET TRANSACTION READ ONLY; +COMMIT; -- succeeds +SELECT count(*) FROM fp_fk_ro; + count +------- + 0 +(1 row) + +SELECT count(*) FROM fp_fk_ro_tmp; + count +------- + 1 +(1 row) + +DROP TABLE fp_fk_ro, fp_pk_ro, fp_fk_ro_tmp, fp_pk_ro_tmp; +-- The row lock must use the command ID the check's snapshot was taken +-- with. An equality function that updates the referenced row advances the +-- command counter before the lock; the row must then count as updated by +-- the check's own command, so that the check reports a violation, as the +-- SPI path does, rather than failing to lock an "invisible" tuple. The +-- equality function runs while the scan holds the index page locked; its +-- UPDATE is a HOT update, since v isn't indexed, so it doesn't touch the +-- index. This is done in a transaction that is rolled back, so that other +-- tests never see the operator class. +BEGIN; +CREATE TABLE fp_pk_cid (id int, v int DEFAULT 0); +CREATE FUNCTION fp_cid_eq(int, int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + UPDATE fp_pk_cid SET v = v + 1 WHERE id OPERATOR(pg_catalog.=) $1; + RETURN $1 OPERATOR(pg_catalog.=) $2; +END$$; +CREATE OPERATOR =~= (LEFTARG = int, RIGHTARG = int, FUNCTION = fp_cid_eq); +CREATE OPERATOR CLASS fp_cid_ops FOR TYPE int USING btree AS + OPERATOR 1 pg_catalog.<, OPERATOR 2 pg_catalog.<=, OPERATOR 3 =~=, + OPERATOR 4 pg_catalog.>=, OPERATOR 5 pg_catalog.>, + FUNCTION 1 btint4cmp(int, int); +CREATE UNIQUE INDEX fp_pk_cid_id ON fp_pk_cid (id fp_cid_ops); +INSERT INTO fp_pk_cid VALUES (1); +CREATE TABLE fp_fk_cid (a int REFERENCES fp_pk_cid (id)); +SAVEPOINT fp_cid; +INSERT INTO fp_fk_cid VALUES (1); -- fails, as a violation +ERROR: insert or update on table "fp_fk_cid" violates foreign key constraint "fp_fk_cid_a_fkey" +DETAIL: Key (a)=(1) is not present in table "fp_pk_cid". +ROLLBACK TO SAVEPOINT fp_cid; +ROLLBACK; +-- +-- FK values that need a coercion to reach the equality operator's input type +-- are checked through SPI, which applies the coercion as part of the query. +-- The fast path used to call the cast function directly. +-- +BEGIN; +CREATE SCHEMA ri_cast; +SET LOCAL search_path = ri_cast, pg_catalog; +-- A cast that returns NULL for a non-NULL key: an FK violation, as for any +-- other key without a match, not an internal error. +CREATE TYPE ri_word AS ENUM ('one', 'none'); +CREATE FUNCTION ri_word_to_int4(ri_word) RETURNS int4 + LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN $1::text = 'one' THEN 1 END $$; +CREATE CAST (ri_word AS int4) WITH FUNCTION ri_word_to_int4(ri_word) AS IMPLICIT; +CREATE TABLE ri_pk (id int4 PRIMARY KEY); +INSERT INTO ri_pk VALUES (1); +CREATE TABLE ri_fk (a ri_word REFERENCES ri_pk); +INSERT INTO ri_fk VALUES ('one'); +SAVEPOINT s; +INSERT INTO ri_fk VALUES ('none'); -- fails +ERROR: insert or update on table "ri_fk" violates foreign key constraint "ri_fk_a_fkey" +DETAIL: Key (a)=(none) is not present in table "ri_pk". +ROLLBACK TO SAVEPOINT s; +-- Replacing the cast and dropping its old function must not leave a later +-- check in this session calling the dropped function. +CREATE FUNCTION ri_word_to_int4_v2(ri_word) RETURNS int4 + LANGUAGE sql IMMUTABLE AS $$ SELECT 1 $$; +DROP CAST (ri_word AS int4); +CREATE CAST (ri_word AS int4) WITH FUNCTION ri_word_to_int4_v2(ri_word) AS IMPLICIT; +DROP FUNCTION ri_word_to_int4(ri_word); +INSERT INTO ri_fk VALUES ('none'); -- succeeds through the new cast +-- A collation-sensitive cast from a collatable type gets the input +-- collation an expression would give it. +CREATE TYPE ri_ctext; +CREATE FUNCTION ri_ctext_in(cstring) RETURNS ri_ctext + AS 'textin' LANGUAGE internal IMMUTABLE STRICT; +NOTICE: return type ri_ctext is only a shell +CREATE FUNCTION ri_ctext_out(ri_ctext) RETURNS cstring + AS 'textout' LANGUAGE internal IMMUTABLE STRICT; +NOTICE: argument type ri_ctext is only a shell +LINE 1: CREATE FUNCTION ri_ctext_out(ri_ctext) RETURNS cstring + ^ +CREATE TYPE ri_ctext (INPUT = ri_ctext_in, OUTPUT = ri_ctext_out, + LIKE = text, COLLATABLE = true); +CREATE FUNCTION ri_ctext_lower(ri_ctext) RETURNS text + AS 'lower' LANGUAGE internal IMMUTABLE STRICT; +CREATE CAST (ri_ctext AS text) WITH FUNCTION ri_ctext_lower(ri_ctext) AS IMPLICIT; +CREATE TABLE ri_pk_text (k text PRIMARY KEY); +INSERT INTO ri_pk_text VALUES ('abc'); +CREATE TABLE ri_fk_text (a ri_ctext REFERENCES ri_pk_text); +INSERT INTO ri_fk_text VALUES ('ABC'); -- succeeds; the cast lowercases +-- An array coercion (int2[] to int4[], allowed with an opclass declared for +-- int4[]) has no single cast function to call. +CREATE FUNCTION ri_i4a_lt(int4[], int4[]) RETURNS bool + AS 'array_lt' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_le(int4[], int4[]) RETURNS bool + AS 'array_le' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_eq(int4[], int4[]) RETURNS bool + AS 'array_eq' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_ge(int4[], int4[]) RETURNS bool + AS 'array_ge' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_gt(int4[], int4[]) RETURNS bool + AS 'array_gt' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_cmp(int4[], int4[]) RETURNS int4 + AS 'btarraycmp' LANGUAGE internal IMMUTABLE STRICT; +CREATE OPERATOR ri_cast.<<< (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_lt); +CREATE OPERATOR ri_cast.<<= (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_le); +CREATE OPERATOR ri_cast.=== (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_eq); +CREATE OPERATOR ri_cast.>>= (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_ge); +CREATE OPERATOR ri_cast.>>> (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_gt); +CREATE OPERATOR CLASS ri_i4a_ops FOR TYPE int4[] USING btree AS + OPERATOR 1 ri_cast.<<<, OPERATOR 2 ri_cast.<<=, OPERATOR 3 ri_cast.===, + OPERATOR 4 ri_cast.>>=, OPERATOR 5 ri_cast.>>>, + FUNCTION 1 ri_i4a_cmp(int4[], int4[]); +CREATE TABLE ri_pk_arr (k int4[]); +CREATE UNIQUE INDEX ON ri_pk_arr (k ri_i4a_ops); +INSERT INTO ri_pk_arr VALUES ('{1,2}'); +CREATE TABLE ri_fk_arr (a int2[] REFERENCES ri_pk_arr (k)); +INSERT INTO ri_fk_arr VALUES ('{1,2}'); -- succeeds +SAVEPOINT s; +INSERT INTO ri_fk_arr VALUES ('{3}'); -- fails +ERROR: insert or update on table "ri_fk_arr" violates foreign key constraint "ri_fk_arr_a_fkey" +DETAIL: Key (a)=({3}) is not present in table "ri_pk_arr". +ROLLBACK TO SAVEPOINT s; +-- A coercion via I/O has no cast function to call either. +CREATE TYPE ri_ioint; +CREATE FUNCTION ri_ioint_in(cstring) RETURNS ri_ioint + AS 'int4in' LANGUAGE internal IMMUTABLE STRICT; +NOTICE: return type ri_ioint is only a shell +CREATE FUNCTION ri_ioint_out(ri_ioint) RETURNS cstring + AS 'int4out' LANGUAGE internal IMMUTABLE STRICT; +NOTICE: argument type ri_ioint is only a shell +LINE 1: CREATE FUNCTION ri_ioint_out(ri_ioint) RETURNS cstring + ^ +CREATE TYPE ri_ioint (INPUT = ri_ioint_in, OUTPUT = ri_ioint_out, LIKE = int4); +CREATE CAST (ri_ioint AS int4) WITH INOUT AS IMPLICIT; +CREATE TABLE ri_fk_io (a ri_ioint REFERENCES ri_pk); +INSERT INTO ri_fk_io VALUES ('1'); -- succeeds +SAVEPOINT s; +INSERT INTO ri_fk_io VALUES ('2'); -- fails +ERROR: insert or update on table "ri_fk_io" violates foreign key constraint "ri_fk_io_a_fkey" +DETAIL: Key (a)=(2) is not present in table "ri_pk". +ROLLBACK TO SAVEPOINT s; +ROLLBACK; ++======= ++>>>>>>> theirs diff --cc src/test/regress/sql/foreign_key.sql index 65b68f46325,3a03251dc50..00000000000 --- a/src/test/regress/sql/foreign_key.sql +++ b/src/test/regress/sql/foreign_key.sql @@@ -2624,414 -1987,12 +2624,421 @@@ DROP SCHEMA fkpart12 CASCADE RESET client_min_messages; RESET search_path; ++<<<<<<< ours +-- Exercise the column mapping code with foreign keys. In this test we'll +-- create a partitioned table which has a partition with a dropped column and +-- check to ensure that an UPDATE cascades the changes correctly to the +-- partitioned table. +CREATE SCHEMA fkpart13; +SET search_path TO fkpart13; + +CREATE TABLE fkpart13_t1 (a int PRIMARY KEY); + +CREATE TABLE fkpart13_t2 ( + part_id int PRIMARY KEY, + column_to_drop int, + FOREIGN KEY (part_id) REFERENCES fkpart13_t1 ON UPDATE CASCADE ON DELETE CASCADE +) PARTITION BY LIST (part_id); + +CREATE TABLE fkpart13_t2_p1 PARTITION OF fkpart13_t2 FOR VALUES IN (1); + +-- drop the column +ALTER TABLE fkpart13_t2 DROP COLUMN column_to_drop; + +-- create a new partition without the dropped column +CREATE TABLE fkpart13_t2_p2 PARTITION OF fkpart13_t2 FOR VALUES IN (2); + +CREATE TABLE fkpart13_t3 ( + a int NOT NULL, + FOREIGN KEY (a) + REFERENCES fkpart13_t2 + ON UPDATE CASCADE ON DELETE CASCADE +); + +INSERT INTO fkpart13_t1 (a) VALUES (1); +INSERT INTO fkpart13_t2 (part_id) VALUES (1); +INSERT INTO fkpart13_t3 (a) VALUES (1); + +-- Test that a cascading update works correctly with the dropped column +UPDATE fkpart13_t1 SET a = 2 WHERE a = 1; +SELECT tableoid::regclass,* FROM fkpart13_t2; +SELECT tableoid::regclass,* FROM fkpart13_t3; + +-- Exercise code in ExecGetTriggerResultRel() as there's been previous issues +-- with ResultRelInfos being returned with the incorrect ri_RootResultRelInfo +WITH cte AS ( + UPDATE fkpart13_t2_p1 SET part_id = part_id +) UPDATE fkpart13_t1 SET a = 2 WHERE a = 1; + +DROP SCHEMA fkpart13 CASCADE; +RESET search_path; + +-- Test the fast-path ALTER TABLE validation path. RLS on the referenced +-- table makes RI_Initial_Check() decline the set-based check, so validation +-- invokes the RI trigger once per referencing row. +CREATE ROLE regress_fk_fastpath_role; +CREATE TABLE fp_pk_alter (a int PRIMARY KEY); +INSERT INTO fp_pk_alter SELECT generate_series(1, 100); +ALTER TABLE fp_pk_alter ENABLE ROW LEVEL SECURITY; +CREATE POLICY fp_pk_alter_all ON fp_pk_alter + FOR ALL USING (true) WITH CHECK (true); +GRANT REFERENCES, SELECT ON fp_pk_alter TO regress_fk_fastpath_role; +CREATE TABLE fp_fk_alter (a int); +INSERT INTO fp_fk_alter SELECT generate_series(1, 100); +ALTER TABLE fp_fk_alter OWNER TO regress_fk_fastpath_role; +-- Validation path: should succeed +SET ROLE regress_fk_fastpath_role; +ALTER TABLE fp_fk_alter ADD FOREIGN KEY (a) REFERENCES fp_pk_alter; +INSERT INTO fp_fk_alter VALUES (101); -- should fail (constraint active) +RESET ROLE; +DROP TABLE fp_fk_alter, fp_pk_alter; + +-- Separate test: validation catches existing violation +CREATE TABLE fp_pk_alter2 (a int PRIMARY KEY); +INSERT INTO fp_pk_alter2 VALUES (1); +ALTER TABLE fp_pk_alter2 ENABLE ROW LEVEL SECURITY; +CREATE POLICY fp_pk_alter2_all ON fp_pk_alter2 + FOR ALL USING (true) WITH CHECK (true); +GRANT REFERENCES, SELECT ON fp_pk_alter2 TO regress_fk_fastpath_role; +CREATE TABLE fp_fk_alter2 (a int); +INSERT INTO fp_fk_alter2 VALUES (1), (200); -- 200 has no PK match +ALTER TABLE fp_fk_alter2 OWNER TO regress_fk_fastpath_role; +SET ROLE regress_fk_fastpath_role; +ALTER TABLE fp_fk_alter2 ADD FOREIGN KEY (a) REFERENCES fp_pk_alter2; -- should fail +RESET ROLE; +DROP TABLE fp_fk_alter2, fp_pk_alter2; +DROP ROLE regress_fk_fastpath_role; + +-- Tests that the fast-path handles multiple constraints +CREATE TABLE fp_pk1 (a int PRIMARY KEY); +CREATE TABLE fp_pk2 (b int PRIMARY KEY); +INSERT INTO fp_pk1 VALUES (1); +INSERT INTO fp_pk2 VALUES (1); +CREATE TABLE fp_multi_fk ( + a int REFERENCES fp_pk1, + b int REFERENCES fp_pk2 +); +INSERT INTO fp_multi_fk VALUES (1, 1); -- two constraints +INSERT INTO fp_multi_fk VALUES (1, 2); -- second constraint fails +DROP TABLE fp_multi_fk, fp_pk1, fp_pk2; + +-- Test that fast-path handles deferred constraints and SET CONSTRAINTS IMMEDIATE +CREATE TABLE fp_pk_defer (a int PRIMARY KEY); +CREATE TABLE fp_fk_defer (a int REFERENCES fp_pk_defer DEFERRABLE INITIALLY DEFERRED); +INSERT INTO fp_pk_defer VALUES (1), (2); + +BEGIN; +INSERT INTO fp_fk_defer VALUES (1); +INSERT INTO fp_fk_defer VALUES (2); +SET CONSTRAINTS ALL IMMEDIATE; -- fires deferred checks here +INSERT INTO fp_fk_defer VALUES (3); -- should fail +COMMIT; +DROP TABLE fp_pk_defer, fp_fk_defer; + +-- A deferred FK check queued while firing deferred triggers at commit must +-- not be lost. An RI check runs during the deferred firing loop and can run +-- user cast code whose DML queues a further deferred check; that check must +-- still fire. fk_defer_main's deferred check runs a cast whose function +-- inserts a violating row into fk_defer_t2, queueing fk_defer_t2's own +-- deferred check, which must still be reported. +CREATE TABLE fk_defer_t2_pk (id int PRIMARY KEY); +CREATE TABLE fk_defer_t2 (a int REFERENCES fk_defer_t2_pk(id) + DEFERRABLE INITIALLY DEFERRED); +CREATE TYPE fk_defer_vch AS (v int); +CREATE FUNCTION fk_defer_cast(fk_defer_vch) RETURNS int + LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO fk_defer_t2 VALUES (999); -- 999 absent, queues deferred check + RETURN $1.v; +END$$; +CREATE CAST (fk_defer_vch AS int) WITH FUNCTION fk_defer_cast(fk_defer_vch) + AS IMPLICIT; +CREATE TABLE fk_defer_main_pk (id int PRIMARY KEY); +INSERT INTO fk_defer_main_pk VALUES (1); +CREATE TABLE fk_defer_main (a fk_defer_vch REFERENCES fk_defer_main_pk(id) + DEFERRABLE INITIALLY DEFERRED); +-- At COMMIT the queued fk_defer_t2 check must fire and report the violation +BEGIN; +INSERT INTO fk_defer_main VALUES (row(1)::fk_defer_vch); +COMMIT; -- expected: ERROR on fk_defer_t2_a_fkey +-- The queued check must fire at transaction end, not early: making the +-- referenced row present in the same transaction lets the commit succeed. +INSERT INTO fk_defer_t2_pk VALUES (999); +BEGIN; +INSERT INTO fk_defer_main VALUES (row(1)::fk_defer_vch); +COMMIT; -- expected: success +DROP TABLE fk_defer_main, fk_defer_main_pk, fk_defer_t2, fk_defer_t2_pk; +DROP CAST (fk_defer_vch AS int); +DROP FUNCTION fk_defer_cast(fk_defer_vch); +DROP TYPE fk_defer_vch; + +-- FK check must see PK rows inserted by earlier AFTER triggers +-- firing on the same statement +CREATE TABLE fp_pk_cci (a int PRIMARY KEY); +CREATE TABLE fp_fk_cci (a int REFERENCES fp_pk_cci); + +CREATE FUNCTION fp_auto_pk() RETURNS trigger AS $$ +BEGIN + RAISE NOTICE 'fp_auto_pk called'; + INSERT INTO fp_pk_cci VALUES (NEW.a); + RETURN NEW; +END $$ LANGUAGE plpgsql; + +-- Name sorts before the RI trigger, so fires first per row +CREATE TRIGGER "AAA_auto" AFTER INSERT ON fp_fk_cci + FOR EACH ROW EXECUTE FUNCTION fp_auto_pk(); + +-- Should succeed: AAA_auto provisions the PK row before RI check +INSERT INTO fp_fk_cci VALUES (1), (2), (3); + +DROP TABLE fp_fk_cci, fp_pk_cci; +DROP FUNCTION fp_auto_pk; + +-- An FK check must check EXECUTE, as the referenced table's owner, on the +-- functions it applies to the FK values: the equality operator's function +-- and, for an FK needing an implicit cast function, the cast. Validation of +-- a new constraint by a role that cannot use the bulk check (RLS is enabled +-- on the referenced table) runs per-row checks, through the fast path for +-- the operator case and through SPI for the cast case, since FK values that +-- need a cast function are not checked by the fast path. +-- +-- Wrapped with BEGIN...ROLLBACK to ensure opclasses used here don't interfere +-- with nearby tests. +BEGIN; +CREATE ROLE regress_ri_pkowner; +CREATE ROLE regress_ri_fkowner; + +-- A private btree opclass whose equality function we can revoke without +-- affecting anything else. +CREATE FUNCTION regress_ri_int4eq(int4, int4) RETURNS bool + AS 'int4eq' LANGUAGE internal IMMUTABLE STRICT; +CREATE OPERATOR === (LEFTARG = int4, RIGHTARG = int4, + FUNCTION = regress_ri_int4eq, COMMUTATOR = ===, + RESTRICT = eqsel, JOIN = eqjoinsel); +CREATE OPERATOR CLASS regress_ri_int4_ops FOR TYPE int4 USING btree AS + OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 ===, OPERATOR 4 >=, OPERATOR 5 >, + FUNCTION 1 btint4cmp(int4, int4); +REVOKE EXECUTE ON FUNCTION regress_ri_int4eq(int4, int4) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION regress_ri_int4eq(int4, int4) TO regress_ri_fkowner; + +-- An FK column type needing a user-defined implicit cast to the PK type. +CREATE TYPE fkenum AS ENUM ('one'); +CREATE FUNCTION fkenum_to_int4(fkenum) RETURNS int4 + AS 'SELECT 1' LANGUAGE sql IMMUTABLE STRICT; +CREATE CAST (fkenum AS int4) WITH FUNCTION fkenum_to_int4(fkenum) AS IMPLICIT; +REVOKE EXECUTE ON FUNCTION fkenum_to_int4(fkenum) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION fkenum_to_int4(fkenum) TO regress_ri_fkowner; + +CREATE TABLE pktable_acl_op (a int4); +CREATE UNIQUE INDEX ON pktable_acl_op (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_cast (a int4 PRIMARY KEY); +CREATE TABLE pktable_acl_op_part (a int4) PARTITION BY LIST (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_op_part1 PARTITION OF pktable_acl_op_part DEFAULT; +CREATE UNIQUE INDEX ON pktable_acl_op_part (a regress_ri_int4_ops); +CREATE TABLE pktable_acl_cast_part (a int4 PRIMARY KEY) PARTITION BY LIST (a); +INSERT INTO pktable_acl_op VALUES (1); +INSERT INTO pktable_acl_cast VALUES (1); +ALTER TABLE pktable_acl_op OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_cast OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_op_part OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_cast_part OWNER TO regress_ri_pkowner; +ALTER TABLE pktable_acl_op ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_cast ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_op_part ENABLE ROW LEVEL SECURITY; +ALTER TABLE pktable_acl_cast_part ENABLE ROW LEVEL SECURITY; +GRANT REFERENCES ON pktable_acl_op, pktable_acl_cast, pktable_acl_op_part, pktable_acl_cast_part TO regress_ri_fkowner; + +CREATE TABLE fktable_acl_op (a int4); +CREATE TABLE fktable_acl_cast (a fkenum); +INSERT INTO fktable_acl_op VALUES (1); +INSERT INTO fktable_acl_cast VALUES ('one'); +ALTER TABLE fktable_acl_op OWNER TO regress_ri_fkowner; +ALTER TABLE fktable_acl_cast OWNER TO regress_ri_fkowner; + +-- The FK owner holds EXECUTE on both functions; the PK owner does not, and +-- it is the PK owner whose privileges apply. +SET ROLE regress_ri_fkowner; +SAVEPOINT s; +ALTER TABLE fktable_acl_op + ADD FOREIGN KEY (a) REFERENCES pktable_acl_op (a); -- fails +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_cast + ADD FOREIGN KEY (a) REFERENCES pktable_acl_cast (a); -- fails (SPI path message) +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_op + ADD FOREIGN KEY (a) REFERENCES pktable_acl_op_part (a); -- fails (SPI path message) +ROLLBACK TO SAVEPOINT s; +SAVEPOINT s; +ALTER TABLE fktable_acl_cast + ADD FOREIGN KEY (a) REFERENCES pktable_acl_cast_part (a); -- fails (SPI path message) +ROLLBACK TO SAVEPOINT s; +RESET ROLE; +ROLLBACK; + +-- A STABLE equality function used by an FK check must see changes made by +-- earlier AFTER triggers, using the check's snapshot rather than the outer +-- query's snapshot. Compare the fast path (pk_fast) with a partitioned-parent +-- SPI check (pk_spi). The equality function of the referenced index's +-- opclass is the user code that runs during a fast-path check. +BEGIN; +CREATE SCHEMA ri_snapshot; +SET LOCAL search_path = ri_snapshot, pg_catalog; + +CREATE TABLE lookup_rows (v int); +-- Considers two values equal only if a lookup row exists for them. +CREATE FUNCTION lookup_eq(a int, b int) RETURNS bool +LANGUAGE plpgsql STABLE AS $$ +BEGIN + RETURN a = b AND EXISTS (SELECT 1 FROM lookup_rows AS r WHERE r.v = a); +END; +$$; +CREATE OPERATOR === (LEFTARG = int, RIGHTARG = int, FUNCTION = lookup_eq); +CREATE OPERATOR CLASS lookup_ops FOR TYPE int USING btree AS + OPERATOR 1 <, OPERATOR 2 <=, OPERATOR 3 ===, OPERATOR 4 >=, OPERATOR 5 >, + FUNCTION 1 btint4cmp(int, int); + +CREATE TABLE pk_fast (v int); +CREATE UNIQUE INDEX ON pk_fast (v lookup_ops); +CREATE TABLE pk_spi (v int) PARTITION BY RANGE (v lookup_ops); +CREATE TABLE pk_spi_p PARTITION OF pk_spi + FOR VALUES FROM (MINVALUE) TO (MAXVALUE); +CREATE UNIQUE INDEX ON pk_spi (v lookup_ops); +INSERT INTO pk_fast VALUES (1); +INSERT INTO pk_spi VALUES (1); +CREATE TABLE fk_fast (k int REFERENCES pk_fast(v)); +CREATE TABLE fk_spi (k int REFERENCES pk_spi(v)); + +CREATE FUNCTION add_lookup_row() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO lookup_rows VALUES (NEW.k); + RETURN NEW; +END; +$$; +-- Sort before the RI trigger, so the lookup row is inserted first. +CREATE TRIGGER "AAA_lookup" AFTER INSERT ON fk_fast + FOR EACH ROW EXECUTE FUNCTION add_lookup_row(); +CREATE TRIGGER "AAA_lookup" AFTER INSERT ON fk_spi + FOR EACH ROW EXECUTE FUNCTION add_lookup_row(); + +-- Both checks must succeed. Without the check's snapshot active, the +-- STABLE equality function misses the lookup row, so no PK row matches. +INSERT INTO fk_fast VALUES (1); +SELECT count(*) FROM fk_fast; +DELETE FROM lookup_rows; +INSERT INTO fk_spi VALUES (1); +SELECT count(*) FROM fk_spi; +ROLLBACK; + +-- Multi-column FK: exercises direct per-row probing with composite keys +CREATE TABLE fp_pk_multi (a int, b int, PRIMARY KEY (a, b)); +INSERT INTO fp_pk_multi SELECT i, i FROM generate_series(1, 100) i; +CREATE TABLE fp_fk_multi (x int, a int, b int, + FOREIGN KEY (a, b) REFERENCES fp_pk_multi); +INSERT INTO fp_fk_multi SELECT i, i, i FROM generate_series(1, 100) i; +INSERT INTO fp_fk_multi VALUES (1, 999, 999); +DROP TABLE fp_fk_multi, fp_pk_multi; + +-- Multi-column FK with columns in different order than PK index. +-- The FK references columns in a different order than they appear in the +-- PK's primary key, which requires mapping constraint key positions to +-- index column positions when building scan keys. +CREATE TABLE fp_pk_order (a int, b text, c int, PRIMARY KEY (a, b, c)); +INSERT INTO fp_pk_order VALUES (1, 'one', 10), (2, 'two', 20); +CREATE TABLE fp_fk_order ( + x int, + c int, + b text, + a int, + FOREIGN KEY (a, c, b) REFERENCES fp_pk_order (a, c, b) -- c and b swapped +); +INSERT INTO fp_fk_order VALUES (1, 10, 'one', 1); -- should succeed +INSERT INTO fp_fk_order VALUES (2, 20, 'two', 2); -- should succeed +INSERT INTO fp_fk_order VALUES (3, 99, 'none', 9); -- should fail +DROP TABLE fp_fk_order, fp_pk_order; + +-- Same-type columns in different order: +CREATE TABLE fp_pk_same (c1 int, c2 int, PRIMARY KEY (c1, c2)); +INSERT INTO fp_pk_same VALUES (1, 2); +CREATE TABLE fp_fk_same (c1 int, c2 int, + FOREIGN KEY (c2, c1) REFERENCES fp_pk_same (c2, c1)); +INSERT INTO fp_fk_same VALUES (1, 2); -- should succeed +INSERT INTO fp_fk_same VALUES (9, 9); -- should fail +DROP TABLE fp_fk_same, fp_pk_same; + +-- Deferred constraint: deferred check fired at COMMIT, not at statement end +CREATE TABLE fp_pk_commit (a int PRIMARY KEY); +CREATE TABLE fp_fk_commit (a int REFERENCES fp_pk_commit + DEFERRABLE INITIALLY DEFERRED); +INSERT INTO fp_pk_commit VALUES (1); +BEGIN; +INSERT INTO fp_fk_commit VALUES (1); +INSERT INTO fp_fk_commit VALUES (1); +INSERT INTO fp_fk_commit VALUES (999); +COMMIT; +DROP TABLE fp_fk_commit, fp_pk_commit; + +-- Cross-type FK with bulk insert: int8 FK referencing int4 PK, +-- values cast during array construction +CREATE TABLE fp_pk_cross (a int4 PRIMARY KEY); +INSERT INTO fp_pk_cross SELECT generate_series(1, 200); +CREATE TABLE fp_fk_cross (a int8 REFERENCES fp_pk_cross); +INSERT INTO fp_fk_cross SELECT generate_series(1, 200); +INSERT INTO fp_fk_cross VALUES (999); +DROP TABLE fp_fk_cross, fp_pk_cross; + +-- Domain-typed FK column whose base type differs from the PK type: the +-- fast path must look through the domain to its base type when deciding +-- whether the cross-type comparison needs a cast. Otherwise valid rows +-- were wrongly rejected with "no conversion function from ... to ...". +CREATE DOMAIN fp_int8dom AS int8; +CREATE TABLE fp_pk_dom (a int4 PRIMARY KEY); +INSERT INTO fp_pk_dom SELECT generate_series(1, 200); +CREATE TABLE fp_fk_dom (a fp_int8dom REFERENCES fp_pk_dom); +INSERT INTO fp_fk_dom SELECT generate_series(1, 200); +INSERT INTO fp_fk_dom VALUES (999); +INSERT INTO fp_fk_dom VALUES (NULL); +DROP TABLE fp_fk_dom, fp_pk_dom; +DROP DOMAIN fp_int8dom; + +-- Re-entrant FK check: DML on the same FK table from a cast function +CREATE TABLE fp_reentry_pk (id int PRIMARY KEY); +INSERT INTO fp_reentry_pk VALUES (1), (2); +CREATE TYPE fp_vch AS (v int); +CREATE FUNCTION fp_vcast(fp_vch) RETURNS int LANGUAGE plpgsql AS $$ +BEGIN + IF $1.v = 1 THEN + INSERT INTO fp_reentry_fk VALUES (row(2)::fp_vch); + END IF; + RETURN $1.v; +END$$; +CREATE CAST (fp_vch AS int) WITH FUNCTION fp_vcast(fp_vch) AS IMPLICIT; +CREATE TABLE fp_reentry_fk (a fp_vch + REFERENCES fp_reentry_pk (id)); +-- The cast re-enters with DML on the same FK, so the inner check looks up +-- the same cached SPI plan while the outer check is still executing it. +-- If the plan has been invalidated meanwhile (as CLOBBER_CACHE_ALWAYS makes +-- certain), the inner check must not free it out from under the outer one. +INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2); +SELECT a, count(*) FROM fp_reentry_fk GROUP BY a ORDER BY a; +DROP TABLE fp_reentry_fk, fp_reentry_pk; +DROP CAST (fp_vch AS int); +DROP FUNCTION fp_vcast(fp_vch); +DROP TYPE fp_vch; + ++======= ++>>>>>>> theirs -- Re-entrant ON DELETE CASCADE whose trigger invalidates the cached RI plan. -- The cascade for id = 2 runs a BEFORE DELETE trigger that does GRANT/REVOKE -- on the table, invalidating the cached plan the cascade is executing, and -- then deletes more rows, whose own cascade fetches that plan again. The -- inner fetch must not free the plan out from under the outer cascade. ++<<<<<<< ours +-- Unlike the case above, this reproduces the crash without cache clobbering. ++======= + -- This reproduces the crash without cache clobbering. ++>>>>>>> theirs CREATE TABLE fk_self_ref ( id int PRIMARY KEY, parent_id int REFERENCES fk_self_ref (id) ON DELETE CASCADE @@@ -3150,198 -2111,3 +3157,201 @@@ DROP CAST (fk_err_vch AS int) DROP FUNCTION fk_err_vcast(fk_err_vch); DROP TYPE fk_err_vch; DROP ROLE regress_fk_err_role; ++<<<<<<< ours + +-- +-- Cache invalidation arriving during a fast-path check. +-- +-- The equality function of the referenced index's opclass runs while the +-- fast path scans the index. One that performs DDL raises an invalidation +-- there, detaching the constraint's fast-path metadata while the check is +-- still using it. This is done in a transaction that is rolled back, so that +-- other tests never see the operator class. +-- +BEGIN; +-- Renames the constraint the first time it is called, and so raises an +-- invalidation partway through the check. Guarded on the catalog so the +-- second and later calls are no-ops. +CREATE FUNCTION fp_inval_eq(int4, int4) RETURNS bool AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_constraint + WHERE conrelid = 'fktable_inval'::regclass + AND conname = 'fktable_inval_fk') THEN + EXECUTE 'ALTER TABLE fktable_inval' + ' RENAME CONSTRAINT fktable_inval_fk TO fktable_inval_fk2'; + END IF; + RETURN $1 OPERATOR(pg_catalog.=) $2; +END $$ LANGUAGE plpgsql; +CREATE OPERATOR =@= (LEFTARG = int4, RIGHTARG = int4, FUNCTION = fp_inval_eq); +CREATE OPERATOR CLASS fp_inval_ops FOR TYPE int4 USING btree AS + OPERATOR 1 pg_catalog.<, OPERATOR 2 pg_catalog.<=, OPERATOR 3 =@=, + OPERATOR 4 pg_catalog.>=, OPERATOR 5 pg_catalog.>, + FUNCTION 1 btint4cmp(int4, int4); + +CREATE TABLE pktable_inval (a int4, b int4); +CREATE UNIQUE INDEX pktable_inval_a_b ON pktable_inval (a fp_inval_ops, b); +INSERT INTO pktable_inval VALUES (1, 1), (2, 2); +CREATE TABLE fktable_inval (a int4, b int4, + CONSTRAINT fktable_inval_fk FOREIGN KEY (a, b) + REFERENCES pktable_inval (a, b)); + +-- The first row invalidates the metadata; the second check must repopulate +-- and use it safely. +INSERT INTO fktable_inval VALUES (1, 1), (2, 2); + +-- Confirms the equality function actually ran and raised the invalidation. +-- Without this the insert above could pass merely by not exercising the path +-- at all. +SELECT conname FROM pg_constraint + WHERE conrelid = 'fktable_inval'::regclass AND contype = 'f'; + +SELECT count(*) FROM fktable_inval; +ROLLBACK; + +-- An FK check locks the referenced row, which a read-only transaction does +-- not allow unless the referenced table is temporary. +CREATE TABLE fp_pk_ro (a int PRIMARY KEY); +INSERT INTO fp_pk_ro VALUES (1); +CREATE TABLE fp_fk_ro (a int REFERENCES fp_pk_ro DEFERRABLE INITIALLY DEFERRED); +BEGIN; +INSERT INTO fp_fk_ro VALUES (1); +SET TRANSACTION READ ONLY; +COMMIT; -- fails +CREATE TEMP TABLE fp_pk_ro_tmp (a int PRIMARY KEY); +INSERT INTO fp_pk_ro_tmp VALUES (1); +CREATE TEMP TABLE fp_fk_ro_tmp (a int REFERENCES fp_pk_ro_tmp + DEFERRABLE INITIALLY DEFERRED); +BEGIN; +INSERT INTO fp_fk_ro_tmp VALUES (1); +SET TRANSACTION READ ONLY; +COMMIT; -- succeeds +SELECT count(*) FROM fp_fk_ro; +SELECT count(*) FROM fp_fk_ro_tmp; +DROP TABLE fp_fk_ro, fp_pk_ro, fp_fk_ro_tmp, fp_pk_ro_tmp; + +-- The row lock must use the command ID the check's snapshot was taken +-- with. An equality function that updates the referenced row advances the +-- command counter before the lock; the row must then count as updated by +-- the check's own command, so that the check reports a violation, as the +-- SPI path does, rather than failing to lock an "invisible" tuple. The +-- equality function runs while the scan holds the index page locked; its +-- UPDATE is a HOT update, since v isn't indexed, so it doesn't touch the +-- index. This is done in a transaction that is rolled back, so that other +-- tests never see the operator class. +BEGIN; +CREATE TABLE fp_pk_cid (id int, v int DEFAULT 0); +CREATE FUNCTION fp_cid_eq(int, int) RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + UPDATE fp_pk_cid SET v = v + 1 WHERE id OPERATOR(pg_catalog.=) $1; + RETURN $1 OPERATOR(pg_catalog.=) $2; +END$$; +CREATE OPERATOR =~= (LEFTARG = int, RIGHTARG = int, FUNCTION = fp_cid_eq); +CREATE OPERATOR CLASS fp_cid_ops FOR TYPE int USING btree AS + OPERATOR 1 pg_catalog.<, OPERATOR 2 pg_catalog.<=, OPERATOR 3 =~=, + OPERATOR 4 pg_catalog.>=, OPERATOR 5 pg_catalog.>, + FUNCTION 1 btint4cmp(int, int); +CREATE UNIQUE INDEX fp_pk_cid_id ON fp_pk_cid (id fp_cid_ops); +INSERT INTO fp_pk_cid VALUES (1); +CREATE TABLE fp_fk_cid (a int REFERENCES fp_pk_cid (id)); +SAVEPOINT fp_cid; +INSERT INTO fp_fk_cid VALUES (1); -- fails, as a violation +ROLLBACK TO SAVEPOINT fp_cid; +ROLLBACK; + +-- +-- FK values that need a coercion to reach the equality operator's input type +-- are checked through SPI, which applies the coercion as part of the query. +-- The fast path used to call the cast function directly. +-- +BEGIN; +CREATE SCHEMA ri_cast; +SET LOCAL search_path = ri_cast, pg_catalog; + +-- A cast that returns NULL for a non-NULL key: an FK violation, as for any +-- other key without a match, not an internal error. +CREATE TYPE ri_word AS ENUM ('one', 'none'); +CREATE FUNCTION ri_word_to_int4(ri_word) RETURNS int4 + LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN $1::text = 'one' THEN 1 END $$; +CREATE CAST (ri_word AS int4) WITH FUNCTION ri_word_to_int4(ri_word) AS IMPLICIT; +CREATE TABLE ri_pk (id int4 PRIMARY KEY); +INSERT INTO ri_pk VALUES (1); +CREATE TABLE ri_fk (a ri_word REFERENCES ri_pk); +INSERT INTO ri_fk VALUES ('one'); +SAVEPOINT s; +INSERT INTO ri_fk VALUES ('none'); -- fails +ROLLBACK TO SAVEPOINT s; + +-- Replacing the cast and dropping its old function must not leave a later +-- check in this session calling the dropped function. +CREATE FUNCTION ri_word_to_int4_v2(ri_word) RETURNS int4 + LANGUAGE sql IMMUTABLE AS $$ SELECT 1 $$; +DROP CAST (ri_word AS int4); +CREATE CAST (ri_word AS int4) WITH FUNCTION ri_word_to_int4_v2(ri_word) AS IMPLICIT; +DROP FUNCTION ri_word_to_int4(ri_word); +INSERT INTO ri_fk VALUES ('none'); -- succeeds through the new cast + +-- A collation-sensitive cast from a collatable type gets the input +-- collation an expression would give it. +CREATE TYPE ri_ctext; +CREATE FUNCTION ri_ctext_in(cstring) RETURNS ri_ctext + AS 'textin' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_ctext_out(ri_ctext) RETURNS cstring + AS 'textout' LANGUAGE internal IMMUTABLE STRICT; +CREATE TYPE ri_ctext (INPUT = ri_ctext_in, OUTPUT = ri_ctext_out, + LIKE = text, COLLATABLE = true); +CREATE FUNCTION ri_ctext_lower(ri_ctext) RETURNS text + AS 'lower' LANGUAGE internal IMMUTABLE STRICT; +CREATE CAST (ri_ctext AS text) WITH FUNCTION ri_ctext_lower(ri_ctext) AS IMPLICIT; +CREATE TABLE ri_pk_text (k text PRIMARY KEY); +INSERT INTO ri_pk_text VALUES ('abc'); +CREATE TABLE ri_fk_text (a ri_ctext REFERENCES ri_pk_text); +INSERT INTO ri_fk_text VALUES ('ABC'); -- succeeds; the cast lowercases + +-- An array coercion (int2[] to int4[], allowed with an opclass declared for +-- int4[]) has no single cast function to call. +CREATE FUNCTION ri_i4a_lt(int4[], int4[]) RETURNS bool + AS 'array_lt' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_le(int4[], int4[]) RETURNS bool + AS 'array_le' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_eq(int4[], int4[]) RETURNS bool + AS 'array_eq' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_ge(int4[], int4[]) RETURNS bool + AS 'array_ge' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_gt(int4[], int4[]) RETURNS bool + AS 'array_gt' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_i4a_cmp(int4[], int4[]) RETURNS int4 + AS 'btarraycmp' LANGUAGE internal IMMUTABLE STRICT; +CREATE OPERATOR ri_cast.<<< (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_lt); +CREATE OPERATOR ri_cast.<<= (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_le); +CREATE OPERATOR ri_cast.=== (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_eq); +CREATE OPERATOR ri_cast.>>= (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_ge); +CREATE OPERATOR ri_cast.>>> (LEFTARG = int4[], RIGHTARG = int4[], FUNCTION = ri_i4a_gt); +CREATE OPERATOR CLASS ri_i4a_ops FOR TYPE int4[] USING btree AS + OPERATOR 1 ri_cast.<<<, OPERATOR 2 ri_cast.<<=, OPERATOR 3 ri_cast.===, + OPERATOR 4 ri_cast.>>=, OPERATOR 5 ri_cast.>>>, + FUNCTION 1 ri_i4a_cmp(int4[], int4[]); +CREATE TABLE ri_pk_arr (k int4[]); +CREATE UNIQUE INDEX ON ri_pk_arr (k ri_i4a_ops); +INSERT INTO ri_pk_arr VALUES ('{1,2}'); +CREATE TABLE ri_fk_arr (a int2[] REFERENCES ri_pk_arr (k)); +INSERT INTO ri_fk_arr VALUES ('{1,2}'); -- succeeds +SAVEPOINT s; +INSERT INTO ri_fk_arr VALUES ('{3}'); -- fails +ROLLBACK TO SAVEPOINT s; + +-- A coercion via I/O has no cast function to call either. +CREATE TYPE ri_ioint; +CREATE FUNCTION ri_ioint_in(cstring) RETURNS ri_ioint + AS 'int4in' LANGUAGE internal IMMUTABLE STRICT; +CREATE FUNCTION ri_ioint_out(ri_ioint) RETURNS cstring + AS 'int4out' LANGUAGE internal IMMUTABLE STRICT; +CREATE TYPE ri_ioint (INPUT = ri_ioint_in, OUTPUT = ri_ioint_out, LIKE = int4); +CREATE CAST (ri_ioint AS int4) WITH INOUT AS IMPLICIT; +CREATE TABLE ri_fk_io (a ri_ioint REFERENCES ri_pk); +INSERT INTO ri_fk_io VALUES ('1'); -- succeeds +SAVEPOINT s; +INSERT INTO ri_fk_io VALUES ('2'); -- fails +ROLLBACK TO SAVEPOINT s; +ROLLBACK; ++======= ++>>>>>>> theirs