PostgreSQL Source Code git master
Loading...
Searching...
No Matches
ri_triggers.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * ri_triggers.c
4 *
5 * Generic trigger procedures for referential integrity constraint
6 * checks.
7 *
8 * Note about memory management: the private hashtables kept here live
9 * across query and transaction boundaries, in fact they live as long as
10 * the backend does. This works because the hashtable structures
11 * themselves are allocated by dynahash.c in its permanent DynaHashCxt,
12 * and the SPI plans they point to are saved using SPI_keepplan().
13 * There is not currently any provision for throwing away a no-longer-needed
14 * plan --- consider improving this someday.
15 *
16 *
17 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
18 *
19 * src/backend/utils/adt/ri_triggers.c
20 *
21 *-------------------------------------------------------------------------
22 */
23
24#include "postgres.h"
25
26#include "access/amapi.h"
27#include "access/genam.h"
28#include "access/htup_details.h"
29#include "access/skey.h"
30#include "access/sysattr.h"
31#include "access/table.h"
32#include "access/tableam.h"
33#include "access/xact.h"
34#include "catalog/index.h"
38#include "commands/trigger.h"
39#include "executor/executor.h"
40#include "executor/spi.h"
41#include "lib/ilist.h"
42#include "miscadmin.h"
43#include "parser/parse_coerce.h"
45#include "utils/acl.h"
46#include "utils/builtins.h"
47#include "utils/datum.h"
48#include "utils/fmgroids.h"
49#include "utils/guc.h"
50#include "utils/hsearch.h"
51#include "utils/inval.h"
52#include "utils/lsyscache.h"
53#include "utils/memutils.h"
54#include "utils/rel.h"
55#include "utils/rls.h"
56#include "utils/ruleutils.h"
57#include "utils/snapmgr.h"
58#include "utils/syscache.h"
59
60/*
61 * Local definitions
62 */
63
64#define RI_MAX_NUMKEYS INDEX_MAX_KEYS
65
66#define RI_INIT_CONSTRAINTHASHSIZE 64
67#define RI_INIT_QUERYHASHSIZE (RI_INIT_CONSTRAINTHASHSIZE * 4)
68
69#define RI_KEYS_ALL_NULL 0
70#define RI_KEYS_SOME_NULL 1
71#define RI_KEYS_NONE_NULL 2
72
73/* RI query type codes */
74/* these queries are executed against the PK (referenced) table: */
75#define RI_PLAN_CHECK_LOOKUPPK 1
76#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK 2
77#define RI_PLAN_LAST_ON_PK RI_PLAN_CHECK_LOOKUPPK_FROM_PK
78/* these queries are executed against the FK (referencing) table: */
79#define RI_PLAN_CASCADE_ONDELETE 3
80#define RI_PLAN_CASCADE_ONUPDATE 4
81#define RI_PLAN_NO_ACTION 5
82/* For RESTRICT, the same plan can be used for both ON DELETE and ON UPDATE triggers. */
83#define RI_PLAN_RESTRICT 6
84#define RI_PLAN_SETNULL_ONDELETE 7
85#define RI_PLAN_SETNULL_ONUPDATE 8
86#define RI_PLAN_SETDEFAULT_ONDELETE 9
87#define RI_PLAN_SETDEFAULT_ONUPDATE 10
88
89#define MAX_QUOTED_NAME_LEN (NAMEDATALEN*2+3)
90#define MAX_QUOTED_REL_NAME_LEN (MAX_QUOTED_NAME_LEN*2)
91
92#define RIAttName(rel, attnum) NameStr(*attnumAttName(rel, attnum))
93#define RIAttType(rel, attnum) attnumTypeId(rel, attnum)
94#define RIAttCollation(rel, attnum) attnumCollationId(rel, attnum)
95
96#define RI_TRIGTYPE_INSERT 1
97#define RI_TRIGTYPE_UPDATE 2
98#define RI_TRIGTYPE_DELETE 3
99
101
102/*
103 * RI_ConstraintInfo
104 *
105 * Information extracted from an FK pg_constraint entry. This is cached in
106 * ri_constraint_cache.
107 *
108 * Note that pf/pp/ff_eq_oprs may hold the overlaps operator instead of equals
109 * for the PERIOD part of a temporal foreign key.
110 */
111typedef struct RI_ConstraintInfo
112{
113 Oid constraint_id; /* OID of pg_constraint entry (hash key) */
114 bool valid; /* successfully initialized? */
115 Oid constraint_root_id; /* OID of topmost ancestor constraint;
116 * same as constraint_id if not inherited */
117 uint32 oidHashValue; /* hash value of constraint_id */
118 uint32 rootHashValue; /* hash value of constraint_root_id */
119 NameData conname; /* name of the FK constraint */
120 Oid pk_relid; /* referenced relation */
121 Oid fk_relid; /* referencing relation */
122 char confupdtype; /* foreign key's ON UPDATE action */
123 char confdeltype; /* foreign key's ON DELETE action */
124 int ndelsetcols; /* number of columns referenced in ON DELETE
125 * SET clause */
126 int16 confdelsetcols[RI_MAX_NUMKEYS]; /* attnums of cols to set on
127 * delete */
128 char confmatchtype; /* foreign key's match type */
129 bool hasperiod; /* if the foreign key uses PERIOD */
130 int nkeys; /* number of key columns */
131 int16 pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
132 int16 fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
133 Oid pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
134 Oid pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
135 Oid ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
136 Oid period_contained_by_oper; /* anyrange <@ anyrange (or
137 * multiranges) */
138 Oid agged_period_contained_by_oper; /* fkattr <@ range_agg(pkattr) */
139 Oid period_intersect_oper; /* anyrange * anyrange (or
140 * multiranges) */
141 dlist_node valid_link; /* Link in list of valid entries */
142
145
148
150
151/* Fast-path metadata for RI checks on foreign key referencing tables */
161
162/*
163 * RI_QueryKey
164 *
165 * The key identifying a prepared SPI plan in our query hashtable
166 */
167typedef struct RI_QueryKey
168{
169 Oid constr_id; /* OID of pg_constraint entry */
170 int32 constr_queryno; /* query type ID, see RI_PLAN_XXX above */
172
173/*
174 * RI_QueryHashEntry
175 */
181
182/*
183 * RI_CompareKey
184 *
185 * The key identifying an entry showing how to compare two values
186 */
187typedef struct RI_CompareKey
188{
189 Oid eq_opr; /* the equality operator to apply */
190 Oid typeid; /* the data type to apply it to */
192
193/*
194 * RI_CompareHashEntry
195 */
197{
199 bool valid; /* successfully initialized? */
200 FmgrInfo eq_opr_finfo; /* call info for equality fn */
201 FmgrInfo cast_func_finfo; /* in case we must coerce input */
203
204/*
205 * Maximum number of FK rows buffered before flushing.
206 *
207 * Larger batches amortize per-flush overhead and let the SK_SEARCHARRAY
208 * path walk more leaf pages in a single sorted traversal. But each
209 * buffered row is a materialized HeapTuple in flush_cxt, and the matched[]
210 * scan in ri_FastPathFlushArray() is O(batch_size) per index match.
211 * Benchmarking showed little difference between 16 and 64, with 256
212 * consistently slower. 64 is a reasonable default.
213 */
214#define RI_FASTPATH_BATCH_SIZE 64
215
216/*
217 * RI_FastPathEntry
218 * Per-constraint cache of resources needed by ri_FastPathBatchFlush().
219 *
220 * One entry per constraint, keyed by pg_constraint OID. Created lazily
221 * by ri_FastPathGetEntry() on first use within a trigger-firing batch
222 * and torn down by ri_FastPathTeardown() at batch end.
223 *
224 * FK tuples are buffered in batch[] across trigger invocations and
225 * flushed when the buffer fills or the batch ends.
226 *
227 * RI_FastPathEntry is not subject to cache invalidation. The cached
228 * relations are held open with locks for the transaction duration, preventing
229 * relcache invalidation. The entry itself is torn down at batch end by
230 * ri_FastPathEndBatch(); on abort, ResourceOwner releases the cached
231 * relations and AtEOXact_RI() NULLs the static cache pointer to prevent
232 * any subsequent access.
233 */
234typedef struct RI_FastPathEntry
235{
236 Oid conoid; /* hash key: pg_constraint OID */
237 Oid fk_relid; /* for ri_FastPathEndBatch() */
242 MemoryContext flush_cxt; /* short-lived context for per-flush work */
243
244 /*
245 * TODO: batch[] is HeapTuple[] because the AFTER trigger machinery
246 * currently passes tuples as HeapTuples. Once trigger infrastructure is
247 * slotified, this should use a slot array or whatever batched tuple
248 * storage abstraction exists at that point to be TAM-agnostic.
249 */
252
253 /*
254 * true while this entry's batch is being flushed; guards against
255 * re-entrant ri_FastPathBatchAdd from user code run during the flush.
256 */
259
260/*
261 * Local data
262 */
267
270static bool ri_fastpath_flushing = false;
271
272/*
273 * Local function prototypes
274 */
275static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
278static Datum ri_restrict(TriggerData *trigdata, bool is_no_action);
279static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind);
280static void quoteOneName(char *buffer, const char *name);
281static void quoteRelationName(char *buffer, Relation rel);
282static void ri_GenerateQual(StringInfo buf,
283 const char *sep,
284 const char *leftop, Oid leftoptype,
285 Oid opoid,
286 const char *rightop, Oid rightoptype);
287static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
288static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot,
289 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
290static void ri_BuildQueryKey(RI_QueryKey *key,
292 int32 constr_queryno);
294 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
295static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
296 Datum lhs, Datum rhs);
297
298static void ri_InitHashTables(void);
300 uint32 hashvalue);
303static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
304
305static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
306 int tgkind);
311static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, const Oid *argtypes,
313static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo,
315 Relation fk_rel, Relation pk_rel,
317 bool is_restrict,
318 bool detectNewRows, int expect_OK);
327 Snapshot snapshot, IndexScanDesc scandesc);
330 Snapshot snapshot, IndexScanDesc scandesc);
331static bool ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel,
332 IndexScanDesc scandesc, TupleTableSlot *slot,
333 Snapshot snapshot, const RI_ConstraintInfo *riinfo,
334 ScanKeyData *skey, int nkeys);
335static bool ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap,
340 int nkeys, TupleTableSlot *new_slot);
342 Relation idx_rel, Datum *pk_vals,
343 char *pk_nulls, ScanKey skeys);
345 Relation fk_rel, Relation idx_rel);
346static void ri_ExtractValues(Relation rel, TupleTableSlot *slot,
348 Datum *vals, char *nulls);
350 Relation pk_rel, Relation fk_rel,
352 int queryno, bool is_restrict, bool partgone);
355static void ri_FastPathEndBatch(void *arg);
356static void ri_FastPathTeardown(void);
357
358
359/*
360 * RI_FKey_check -
361 *
362 * Check foreign key existence (combined for INSERT and UPDATE).
363 */
364static Datum
366{
369 Relation pk_rel;
373
375 trigdata->tg_relation, false);
376
377 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
378 newslot = trigdata->tg_newslot;
379 else
380 newslot = trigdata->tg_trigslot;
381
382 /*
383 * We should not even consider checking the row if it is no longer valid,
384 * since it was either deleted (so the deferred check should be skipped)
385 * or updated (in which case only the latest version of the row should be
386 * checked). Test its liveness according to SnapshotSelf. We need pin
387 * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
388 * should be holding pin, but not lock.
389 */
391 return PointerGetDatum(NULL);
392
393 fk_rel = trigdata->tg_relation;
394
396 {
397 case RI_KEYS_ALL_NULL:
398
399 /*
400 * No further check needed - an all-NULL key passes every type of
401 * foreign key constraint.
402 */
403 return PointerGetDatum(NULL);
404
406
407 /*
408 * This is the only case that differs between the three kinds of
409 * MATCH.
410 */
411 switch (riinfo->confmatchtype)
412 {
414
415 /*
416 * Not allowed - MATCH FULL says either all or none of the
417 * attributes can be NULLs
418 */
421 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
423 NameStr(riinfo->conname)),
424 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
426 NameStr(riinfo->conname))));
427 return PointerGetDatum(NULL);
428
430
431 /*
432 * MATCH SIMPLE - if ANY column is null, the key passes
433 * the constraint.
434 */
435 return PointerGetDatum(NULL);
436
437#ifdef NOT_USED
439
440 /*
441 * MATCH PARTIAL - all non-null columns must match. (not
442 * implemented, can be done by modifying the query below
443 * to only include non-null columns, or by writing a
444 * special version here)
445 */
446 break;
447#endif
448 }
449
451
452 /*
453 * Have a full qualified key - continue below for all three kinds
454 * of MATCH.
455 */
456 break;
457 }
458
459 /*
460 * Fast path: probe the PK unique index directly, bypassing SPI.
461 *
462 * For non-partitioned, non-temporal FKs, we can skip the SPI machinery
463 * (plan cache, executor setup, etc.) and do a direct index scan + tuple
464 * lock. This is semantically equivalent to the SPI path below but avoids
465 * the per-row executor overhead.
466 *
467 * ri_FastPathBatchAdd() and ri_FastPathCheck() report the violation
468 * themselves if no matching PK row is found, so they only return on
469 * success.
470 */
472 {
473 if (AfterTriggerIsActive() &&
476 {
477 /* Batched path: buffer and probe in groups */
479 }
480 else
481 {
482 /*
483 * Per-row path, used when batching is not safe or not applicable:
484 *
485 * - ALTER TABLE validation, where no after-trigger firing is
486 * active;
487 *
488 * - any FK check inside a subtransaction, since the batch cache
489 * is confined to the top transaction level (it cannot be cleanly
490 * unwound on subxact abort);
491 *
492 * - a re-entrant check from user cast/operator code running
493 * during a batch flush, since adding a cache entry while
494 * ri_FastPathEndBatch is iterating the cache could leave it
495 * unflushed.
496 */
498 }
499 return PointerGetDatum(NULL);
500 }
501
502 SPI_connect();
503
504 /*
505 * pk_rel is opened in RowShareLock mode since that's what our eventual
506 * SELECT FOR KEY SHARE will get on it.
507 */
508 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
509
510 /* Fetch or prepare a saved plan for the real check */
512
513 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
514 {
518 char paramname[16];
519 const char *querysep;
521 const char *pk_only;
522
523 /* ----------
524 * The query string built is
525 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
526 * FOR KEY SHARE OF x
527 * The type id's for the $ parameters are those of the
528 * corresponding FK attributes.
529 *
530 * But for temporal FKs we need to make sure
531 * the FK's range is completely covered.
532 * So we use this query instead:
533 * SELECT 1
534 * FROM (
535 * SELECT pkperiodatt AS r
536 * FROM [ONLY] pktable x
537 * WHERE pkatt1 = $1 [AND ...]
538 * AND pkperiodatt && $n
539 * FOR KEY SHARE OF x
540 * ) x1
541 * HAVING $n <@ range_agg(x1.r)
542 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
543 * we can make this a bit simpler.
544 * ----------
545 */
547 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
548 "" : "ONLY ";
550 if (riinfo->hasperiod)
551 {
553 RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
554
556 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
558 }
559 else
560 {
561 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
563 }
564 querysep = "WHERE";
565 for (int i = 0; i < riinfo->nkeys; i++)
566 {
567 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
568 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
569
571 RIAttName(pk_rel, riinfo->pk_attnums[i]));
572 sprintf(paramname, "$%d", i + 1);
575 riinfo->pf_eq_oprs[i],
577 querysep = "AND";
579 }
580 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
581 if (riinfo->hasperiod)
582 {
583 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
584
585 appendStringInfoString(&querybuf, ") x1 HAVING ");
586 sprintf(paramname, "$%d", riinfo->nkeys);
589 riinfo->agged_period_contained_by_oper,
590 "pg_catalog.range_agg", ANYMULTIRANGEOID);
592 }
593
594 /* Prepare and save the plan */
596 &qkey, fk_rel, pk_rel);
597 }
598
599 /*
600 * Now check that foreign key exists in PK table
601 *
602 * XXX detectNewRows must be true when a partitioned table is on the
603 * referenced side. The reason is that our snapshot must be fresh in
604 * order for the hack in find_inheritance_children() to work.
605 */
607 fk_rel, pk_rel,
608 NULL, newslot,
609 false,
610 pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
612
613 if (SPI_finish() != SPI_OK_FINISH)
614 elog(ERROR, "SPI_finish failed");
615
616 table_close(pk_rel, RowShareLock);
617
618 return PointerGetDatum(NULL);
619}
620
621
622/*
623 * RI_FKey_check_ins -
624 *
625 * Check foreign key existence at insert event on FK table.
626 */
627Datum
629{
630 /* Check that this is a valid trigger call on the right time and event. */
631 ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
632
633 /* Share code with UPDATE case. */
634 return RI_FKey_check((TriggerData *) fcinfo->context);
635}
636
637
638/*
639 * RI_FKey_check_upd -
640 *
641 * Check foreign key existence at update event on FK table.
642 */
643Datum
645{
646 /* Check that this is a valid trigger call on the right time and event. */
647 ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
648
649 /* Share code with INSERT case. */
650 return RI_FKey_check((TriggerData *) fcinfo->context);
651}
652
653
654/*
655 * ri_Check_Pk_Match
656 *
657 * Check to see if another PK row has been created that provides the same
658 * key values as the "oldslot" that's been modified or deleted in our trigger
659 * event. Returns true if a match is found in the PK table.
660 *
661 * We assume the caller checked that the oldslot contains no NULL key values,
662 * since otherwise a match is impossible.
663 */
664static bool
668{
671 bool result;
672
673 /* Only called for non-null rows */
675
676 SPI_connect();
677
678 /*
679 * Fetch or prepare a saved plan for checking PK table with values coming
680 * from a PK row
681 */
683
684 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
685 {
689 char paramname[16];
690 const char *querysep;
691 const char *pk_only;
693
694 /* ----------
695 * The query string built is
696 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
697 * FOR KEY SHARE OF x
698 * The type id's for the $ parameters are those of the
699 * PK attributes themselves.
700 *
701 * But for temporal FKs we need to make sure
702 * the old PK's range is completely covered.
703 * So we use this query instead:
704 * SELECT 1
705 * FROM (
706 * SELECT pkperiodatt AS r
707 * FROM [ONLY] pktable x
708 * WHERE pkatt1 = $1 [AND ...]
709 * AND pkperiodatt && $n
710 * FOR KEY SHARE OF x
711 * ) x1
712 * HAVING $n <@ range_agg(x1.r)
713 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
714 * we can make this a bit simpler.
715 * ----------
716 */
718 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
719 "" : "ONLY ";
721 if (riinfo->hasperiod)
722 {
723 quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
724
726 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
728 }
729 else
730 {
731 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
733 }
734 querysep = "WHERE";
735 for (int i = 0; i < riinfo->nkeys; i++)
736 {
737 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
738
740 RIAttName(pk_rel, riinfo->pk_attnums[i]));
741 sprintf(paramname, "$%d", i + 1);
744 riinfo->pp_eq_oprs[i],
746 querysep = "AND";
748 }
749 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
750 if (riinfo->hasperiod)
751 {
752 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
753
754 appendStringInfoString(&querybuf, ") x1 HAVING ");
755 sprintf(paramname, "$%d", riinfo->nkeys);
758 riinfo->agged_period_contained_by_oper,
759 "pg_catalog.range_agg", ANYMULTIRANGEOID);
761 }
762
763 /* Prepare and save the plan */
765 &qkey, fk_rel, pk_rel);
766 }
767
768 /*
769 * We have a plan now. Run it.
770 */
772 fk_rel, pk_rel,
773 oldslot, NULL,
774 false,
775 true, /* treat like update */
777
778 if (SPI_finish() != SPI_OK_FINISH)
779 elog(ERROR, "SPI_finish failed");
780
781 return result;
782}
783
784
785/*
786 * RI_FKey_noaction_del -
787 *
788 * Give an error and roll back the current transaction if the
789 * delete has resulted in a violation of the given referential
790 * integrity constraint.
791 */
792Datum
794{
795 /* Check that this is a valid trigger call on the right time and event. */
796 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
797
798 /* Share code with RESTRICT/UPDATE cases. */
799 return ri_restrict((TriggerData *) fcinfo->context, true);
800}
801
802/*
803 * RI_FKey_restrict_del -
804 *
805 * Restrict delete from PK table to rows unreferenced by foreign key.
806 *
807 * The SQL standard intends that this referential action occur exactly when
808 * the delete is performed, rather than after. This appears to be
809 * the only difference between "NO ACTION" and "RESTRICT". In Postgres
810 * we still implement this as an AFTER trigger, but it's non-deferrable.
811 */
812Datum
814{
815 /* Check that this is a valid trigger call on the right time and event. */
816 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
817
818 /* Share code with NO ACTION/UPDATE cases. */
819 return ri_restrict((TriggerData *) fcinfo->context, false);
820}
821
822/*
823 * RI_FKey_noaction_upd -
824 *
825 * Give an error and roll back the current transaction if the
826 * update has resulted in a violation of the given referential
827 * integrity constraint.
828 */
829Datum
831{
832 /* Check that this is a valid trigger call on the right time and event. */
833 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
834
835 /* Share code with RESTRICT/DELETE cases. */
836 return ri_restrict((TriggerData *) fcinfo->context, true);
837}
838
839/*
840 * RI_FKey_restrict_upd -
841 *
842 * Restrict update of PK to rows unreferenced by foreign key.
843 *
844 * The SQL standard intends that this referential action occur exactly when
845 * the update is performed, rather than after. This appears to be
846 * the only difference between "NO ACTION" and "RESTRICT". In Postgres
847 * we still implement this as an AFTER trigger, but it's non-deferrable.
848 */
849Datum
851{
852 /* Check that this is a valid trigger call on the right time and event. */
853 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
854
855 /* Share code with NO ACTION/DELETE cases. */
856 return ri_restrict((TriggerData *) fcinfo->context, false);
857}
858
859/*
860 * ri_restrict -
861 *
862 * Common code for ON DELETE RESTRICT, ON DELETE NO ACTION,
863 * ON UPDATE RESTRICT, and ON UPDATE NO ACTION.
864 */
865static Datum
867{
870 Relation pk_rel;
874
876 trigdata->tg_relation, true);
877
878 /*
879 * Get the relation descriptors of the FK and PK tables and the old tuple.
880 *
881 * fk_rel is opened in RowShareLock mode since that's what our eventual
882 * SELECT FOR KEY SHARE will get on it.
883 */
884 fk_rel = table_open(riinfo->fk_relid, RowShareLock);
885 pk_rel = trigdata->tg_relation;
886 oldslot = trigdata->tg_trigslot;
887
888 /*
889 * If another PK row now exists providing the old key values, we should
890 * not do anything. However, this check should only be made in the NO
891 * ACTION case; in RESTRICT cases we don't wish to allow another row to be
892 * substituted.
893 *
894 * If the foreign key has PERIOD, we incorporate looking for replacement
895 * rows in the main SQL query below, so we needn't do it here.
896 */
897 if (is_no_action && !riinfo->hasperiod &&
899 {
901 return PointerGetDatum(NULL);
902 }
903
904 SPI_connect();
905
906 /*
907 * Fetch or prepare a saved plan for the restrict lookup (it's the same
908 * query for delete and update cases)
909 */
911
912 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
913 {
919 char paramname[16];
920 const char *querysep;
922 const char *fk_only;
923
924 /* ----------
925 * The query string built is
926 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
927 * FOR KEY SHARE OF x
928 * The type id's for the $ parameters are those of the
929 * corresponding PK attributes.
930 * ----------
931 */
933 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
934 "" : "ONLY ";
936 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
938 querysep = "WHERE";
939 for (int i = 0; i < riinfo->nkeys; i++)
940 {
941 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
942 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
943
945 RIAttName(fk_rel, riinfo->fk_attnums[i]));
946 sprintf(paramname, "$%d", i + 1);
949 riinfo->pf_eq_oprs[i],
951 querysep = "AND";
953 }
954
955 /*----------
956 * For temporal foreign keys, a reference could still be valid if the
957 * referenced range didn't change too much. Also if a referencing
958 * range extends past the current PK row, we don't want to check that
959 * part: some other PK row should fulfill it. We only want to check
960 * the part matching the PK record we've changed. Therefore to find
961 * invalid records we do this:
962 *
963 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
964 * -- begin temporal
965 * AND $n && x.fkperiod
966 * AND NOT coalesce((x.fkperiod * $n) <@
967 * (SELECT range_agg(r)
968 * FROM (SELECT y.pkperiod r
969 * FROM [ONLY] <pktable> y
970 * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
971 * FOR KEY SHARE OF y) y2), false)
972 * -- end temporal
973 * FOR KEY SHARE OF x
974 *
975 * We need the coalesce in case the first subquery returns no rows.
976 * We need the second subquery because FOR KEY SHARE doesn't support
977 * aggregate queries.
978 */
979 if (riinfo->hasperiod && is_no_action)
980 {
981 Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
982 Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
985 char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
986 "" : "ONLY ";
987
988 quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
989 sprintf(paramname, "$%d", riinfo->nkeys);
990
991 appendStringInfoString(&querybuf, " AND NOT coalesce(");
992
993 /* Intersect the fk with the old pk range */
998 riinfo->period_intersect_oper,
1001
1002 /* Find the remaining history */
1004 appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
1005
1006 quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
1008 appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
1010
1011 /* Restrict pk rows to what matches */
1012 querysep = "WHERE";
1013 for (int i = 0; i < riinfo->nkeys; i++)
1014 {
1015 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1016
1018 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1019 sprintf(paramname, "$%d", i + 1);
1022 riinfo->pp_eq_oprs[i],
1023 attname, pk_type);
1024 querysep = "AND";
1025 queryoids[i] = pk_type;
1026 }
1027 appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
1028
1031 riinfo->agged_period_contained_by_oper,
1033 /* end of coalesce: */
1034 appendStringInfoString(&querybuf, ", false)");
1035 }
1036
1037 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
1038
1039 /* Prepare and save the plan */
1040 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1041 &qkey, fk_rel, pk_rel);
1042 }
1043
1044 /*
1045 * We have a plan now. Run it to check for existing references.
1046 */
1048 fk_rel, pk_rel,
1049 oldslot, NULL,
1050 !is_no_action,
1051 true, /* must detect new rows */
1053
1054 if (SPI_finish() != SPI_OK_FINISH)
1055 elog(ERROR, "SPI_finish failed");
1056
1058
1059 return PointerGetDatum(NULL);
1060}
1061
1062
1063/*
1064 * RI_FKey_cascade_del -
1065 *
1066 * Cascaded delete foreign key references at delete event on PK table.
1067 */
1068Datum
1070{
1071 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1074 Relation pk_rel;
1078
1079 /* Check that this is a valid trigger call on the right time and event. */
1080 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
1081
1083 trigdata->tg_relation, true);
1084
1085 /*
1086 * Get the relation descriptors of the FK and PK tables and the old tuple.
1087 *
1088 * fk_rel is opened in RowExclusiveLock mode since that's what our
1089 * eventual DELETE will get on it.
1090 */
1092 pk_rel = trigdata->tg_relation;
1093 oldslot = trigdata->tg_trigslot;
1094
1095 SPI_connect();
1096
1097 /* Fetch or prepare a saved plan for the cascaded delete */
1099
1100 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1101 {
1105 char paramname[16];
1106 const char *querysep;
1108 const char *fk_only;
1109
1110 /* ----------
1111 * The query string built is
1112 * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
1113 * The type id's for the $ parameters are those of the
1114 * corresponding PK attributes.
1115 * ----------
1116 */
1118 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1119 "" : "ONLY ";
1121 appendStringInfo(&querybuf, "DELETE FROM %s%s",
1123 querysep = "WHERE";
1124 for (int i = 0; i < riinfo->nkeys; i++)
1125 {
1126 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1127 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1128
1130 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1131 sprintf(paramname, "$%d", i + 1);
1134 riinfo->pf_eq_oprs[i],
1135 attname, fk_type);
1136 querysep = "AND";
1137 queryoids[i] = pk_type;
1138 }
1139
1140 /* Prepare and save the plan */
1141 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1142 &qkey, fk_rel, pk_rel);
1143 }
1144
1145 /*
1146 * We have a plan now. Build up the arguments from the key values in the
1147 * deleted PK tuple and delete the referencing rows
1148 */
1150 fk_rel, pk_rel,
1151 oldslot, NULL,
1152 false,
1153 true, /* must detect new rows */
1155
1156 if (SPI_finish() != SPI_OK_FINISH)
1157 elog(ERROR, "SPI_finish failed");
1158
1160
1161 return PointerGetDatum(NULL);
1162}
1163
1164
1165/*
1166 * RI_FKey_cascade_upd -
1167 *
1168 * Cascaded update foreign key references at update event on PK table.
1169 */
1170Datum
1172{
1173 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1176 Relation pk_rel;
1181
1182 /* Check that this is a valid trigger call on the right time and event. */
1183 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1184
1186 trigdata->tg_relation, true);
1187
1188 /*
1189 * Get the relation descriptors of the FK and PK tables and the new and
1190 * old tuple.
1191 *
1192 * fk_rel is opened in RowExclusiveLock mode since that's what our
1193 * eventual UPDATE will get on it.
1194 */
1196 pk_rel = trigdata->tg_relation;
1197 newslot = trigdata->tg_newslot;
1198 oldslot = trigdata->tg_trigslot;
1199
1200 SPI_connect();
1201
1202 /* Fetch or prepare a saved plan for the cascaded update */
1204
1205 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1206 {
1211 char paramname[16];
1212 const char *querysep;
1213 const char *qualsep;
1215 const char *fk_only;
1216
1217 /* ----------
1218 * The query string built is
1219 * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1220 * WHERE $n = fkatt1 [AND ...]
1221 * The type id's for the $ parameters are those of the
1222 * corresponding PK attributes. Note that we are assuming
1223 * there is an assignment cast from the PK to the FK type;
1224 * else the parser will fail.
1225 * ----------
1226 */
1229 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1230 "" : "ONLY ";
1232 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1234 querysep = "";
1235 qualsep = "WHERE";
1236 for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1237 {
1238 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1239 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1240
1242 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1244 "%s %s = $%d",
1245 querysep, attname, i + 1);
1246 sprintf(paramname, "$%d", j + 1);
1249 riinfo->pf_eq_oprs[i],
1250 attname, fk_type);
1251 querysep = ",";
1252 qualsep = "AND";
1253 queryoids[i] = pk_type;
1254 queryoids[j] = pk_type;
1255 }
1257
1258 /* Prepare and save the plan */
1259 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1260 &qkey, fk_rel, pk_rel);
1261 }
1262
1263 /*
1264 * We have a plan now. Run it to update the existing references.
1265 */
1267 fk_rel, pk_rel,
1269 false,
1270 true, /* must detect new rows */
1272
1273 if (SPI_finish() != SPI_OK_FINISH)
1274 elog(ERROR, "SPI_finish failed");
1275
1277
1278 return PointerGetDatum(NULL);
1279}
1280
1281
1282/*
1283 * RI_FKey_setnull_del -
1284 *
1285 * Set foreign key references to NULL values at delete event on PK table.
1286 */
1287Datum
1289{
1290 /* Check that this is a valid trigger call on the right time and event. */
1291 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1292
1293 /* Share code with UPDATE case */
1294 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1295}
1296
1297/*
1298 * RI_FKey_setnull_upd -
1299 *
1300 * Set foreign key references to NULL at update event on PK table.
1301 */
1302Datum
1304{
1305 /* Check that this is a valid trigger call on the right time and event. */
1306 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1307
1308 /* Share code with DELETE case */
1309 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1310}
1311
1312/*
1313 * RI_FKey_setdefault_del -
1314 *
1315 * Set foreign key references to defaults at delete event on PK table.
1316 */
1317Datum
1319{
1320 /* Check that this is a valid trigger call on the right time and event. */
1321 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1322
1323 /* Share code with UPDATE case */
1324 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1325}
1326
1327/*
1328 * RI_FKey_setdefault_upd -
1329 *
1330 * Set foreign key references to defaults at update event on PK table.
1331 */
1332Datum
1334{
1335 /* Check that this is a valid trigger call on the right time and event. */
1336 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1337
1338 /* Share code with DELETE case */
1339 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1340}
1341
1342/*
1343 * ri_set -
1344 *
1345 * Common code for ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE SET
1346 * NULL, and ON UPDATE SET DEFAULT.
1347 */
1348static Datum
1350{
1353 Relation pk_rel;
1357 int32 queryno;
1358
1360 trigdata->tg_relation, true);
1361
1362 /*
1363 * Get the relation descriptors of the FK and PK tables and the old tuple.
1364 *
1365 * fk_rel is opened in RowExclusiveLock mode since that's what our
1366 * eventual UPDATE will get on it.
1367 */
1369 pk_rel = trigdata->tg_relation;
1370 oldslot = trigdata->tg_trigslot;
1371
1372 SPI_connect();
1373
1374 /*
1375 * Fetch or prepare a saved plan for the trigger.
1376 */
1377 switch (tgkind)
1378 {
1379 case RI_TRIGTYPE_UPDATE:
1383 break;
1384 case RI_TRIGTYPE_DELETE:
1388 break;
1389 default:
1390 elog(ERROR, "invalid tgkind passed to ri_set");
1391 }
1392
1394
1395 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1396 {
1400 char paramname[16];
1401 const char *querysep;
1402 const char *qualsep;
1404 const char *fk_only;
1405 int num_cols_to_set;
1406 const int16 *set_cols;
1407
1408 switch (tgkind)
1409 {
1410 case RI_TRIGTYPE_UPDATE:
1411 num_cols_to_set = riinfo->nkeys;
1412 set_cols = riinfo->fk_attnums;
1413 break;
1414 case RI_TRIGTYPE_DELETE:
1415
1416 /*
1417 * If confdelsetcols are present, then we only update the
1418 * columns specified in that array, otherwise we update all
1419 * the referencing columns.
1420 */
1421 if (riinfo->ndelsetcols != 0)
1422 {
1423 num_cols_to_set = riinfo->ndelsetcols;
1424 set_cols = riinfo->confdelsetcols;
1425 }
1426 else
1427 {
1428 num_cols_to_set = riinfo->nkeys;
1429 set_cols = riinfo->fk_attnums;
1430 }
1431 break;
1432 default:
1433 elog(ERROR, "invalid tgkind passed to ri_set");
1434 }
1435
1436 /* ----------
1437 * The query string built is
1438 * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1439 * WHERE $1 = fkatt1 [AND ...]
1440 * The type id's for the $ parameters are those of the
1441 * corresponding PK attributes.
1442 * ----------
1443 */
1445 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1446 "" : "ONLY ";
1448 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1450
1451 /*
1452 * Add assignment clauses
1453 */
1454 querysep = "";
1455 for (int i = 0; i < num_cols_to_set; i++)
1456 {
1459 "%s %s = %s",
1461 is_set_null ? "NULL" : "DEFAULT");
1462 querysep = ",";
1463 }
1464
1465 /*
1466 * Add WHERE clause
1467 */
1468 qualsep = "WHERE";
1469 for (int i = 0; i < riinfo->nkeys; i++)
1470 {
1471 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1472 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1473
1475 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1476
1477 sprintf(paramname, "$%d", i + 1);
1480 riinfo->pf_eq_oprs[i],
1481 attname, fk_type);
1482 qualsep = "AND";
1483 queryoids[i] = pk_type;
1484 }
1485
1486 /* Prepare and save the plan */
1487 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1488 &qkey, fk_rel, pk_rel);
1489 }
1490
1491 /*
1492 * We have a plan now. Run it to update the existing references.
1493 */
1495 fk_rel, pk_rel,
1496 oldslot, NULL,
1497 false,
1498 true, /* must detect new rows */
1500
1501 if (SPI_finish() != SPI_OK_FINISH)
1502 elog(ERROR, "SPI_finish failed");
1503
1505
1506 if (is_set_null)
1507 return PointerGetDatum(NULL);
1508 else
1509 {
1510 /*
1511 * If we just deleted or updated the PK row whose key was equal to the
1512 * FK columns' default values, and a referencing row exists in the FK
1513 * table, we would have updated that row to the same values it already
1514 * had --- and RI_FKey_fk_upd_check_required would hence believe no
1515 * check is necessary. So we need to do another lookup now and in
1516 * case a reference still exists, abort the operation. That is
1517 * already implemented in the NO ACTION trigger, so just run it. (This
1518 * recheck is only needed in the SET DEFAULT case, since CASCADE would
1519 * remove such rows in case of a DELETE operation or would change the
1520 * FK key values in case of an UPDATE, while SET NULL is certain to
1521 * result in rows that satisfy the FK constraint.)
1522 */
1523 return ri_restrict(trigdata, true);
1524 }
1525}
1526
1527
1528/*
1529 * RI_FKey_pk_upd_check_required -
1530 *
1531 * Check if we really need to fire the RI trigger for an update or delete to a PK
1532 * relation. This is called by the AFTER trigger queue manager to see if
1533 * it can skip queuing an instance of an RI trigger. Returns true if the
1534 * trigger must be fired, false if we can prove the constraint will still
1535 * be satisfied.
1536 *
1537 * newslot will be NULL if this is called for a delete.
1538 */
1539bool
1542{
1544
1545 riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1546
1547 /*
1548 * If any old key value is NULL, the row could not have been referenced by
1549 * an FK row, so no check is needed.
1550 */
1552 return false;
1553
1554 /* If all old and new key values are equal, no check is needed */
1555 if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1556 return false;
1557
1558 /* Else we need to fire the trigger. */
1559 return true;
1560}
1561
1562/*
1563 * RI_FKey_fk_upd_check_required -
1564 *
1565 * Check if we really need to fire the RI trigger for an update to an FK
1566 * relation. This is called by the AFTER trigger queue manager to see if
1567 * it can skip queuing an instance of an RI trigger. Returns true if the
1568 * trigger must be fired, false if we can prove the constraint will still
1569 * be satisfied.
1570 */
1571bool
1574{
1576 int ri_nullcheck;
1577
1578 /*
1579 * AfterTriggerSaveEvent() handles things such that this function is never
1580 * called for partitioned tables.
1581 */
1582 Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1583
1585
1587
1588 /*
1589 * If all new key values are NULL, the row satisfies the constraint, so no
1590 * check is needed.
1591 */
1593 return false;
1594
1595 /*
1596 * If some new key values are NULL, the behavior depends on the match
1597 * type.
1598 */
1599 else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1600 {
1601 switch (riinfo->confmatchtype)
1602 {
1604
1605 /*
1606 * If any new key value is NULL, the row must satisfy the
1607 * constraint, so no check is needed.
1608 */
1609 return false;
1610
1612
1613 /*
1614 * Don't know, must run full check.
1615 */
1616 break;
1617
1619
1620 /*
1621 * If some new key values are NULL, the row fails the
1622 * constraint. We must not throw error here, because the row
1623 * might get invalidated before the constraint is to be
1624 * checked, but we should queue the event to apply the check
1625 * later.
1626 */
1627 return true;
1628 }
1629 }
1630
1631 /*
1632 * Continues here for no new key values are NULL, or we couldn't decide
1633 * yet.
1634 */
1635
1636 /*
1637 * If the original row was inserted by our own transaction, we must fire
1638 * the trigger whether or not the keys are equal. This is because our
1639 * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1640 * not do anything; so we had better do the UPDATE check. (We could skip
1641 * this if we knew the INSERT trigger already fired, but there is no easy
1642 * way to know that.)
1643 */
1645 return true;
1646
1647 /* If all old and new key values are equal, no check is needed */
1648 if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1649 return false;
1650
1651 /* Else we need to fire the trigger. */
1652 return true;
1653}
1654
1655/*
1656 * RI_Initial_Check -
1657 *
1658 * Check an entire table for non-matching values using a single query.
1659 * This is not a trigger procedure, but is called during ALTER TABLE
1660 * ADD FOREIGN KEY to validate the initial table contents.
1661 *
1662 * We expect that the caller has made provision to prevent any problems
1663 * caused by concurrent actions. This could be either by locking rel and
1664 * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
1665 * that triggers implementing the checks are already active.
1666 * Hence, we do not need to lock individual rows for the check.
1667 *
1668 * If the check fails because the current user doesn't have permissions
1669 * to read both tables, return false to let our caller know that they will
1670 * need to do something else to check the constraint.
1671 */
1672bool
1674{
1684 List *rtes = NIL;
1685 List *perminfos = NIL;
1686 const char *sep;
1687 const char *fk_only;
1688 const char *pk_only;
1689 int save_nestlevel;
1690 char workmembuf[32];
1691 int spi_result;
1693
1695
1696 /*
1697 * Check to make sure current user has enough permissions to do the test
1698 * query. (If not, caller can fall back to the trigger method, which
1699 * works because it changes user IDs on the fly.)
1700 *
1701 * XXX are there any other show-stopper conditions to check?
1702 */
1704 pk_perminfo->relid = RelationGetRelid(pk_rel);
1705 pk_perminfo->requiredPerms = ACL_SELECT;
1708 rte->rtekind = RTE_RELATION;
1709 rte->relid = RelationGetRelid(pk_rel);
1710 rte->relkind = pk_rel->rd_rel->relkind;
1711 rte->rellockmode = AccessShareLock;
1712 rte->perminfoindex = list_length(perminfos);
1713 rtes = lappend(rtes, rte);
1714
1717 fk_perminfo->requiredPerms = ACL_SELECT;
1720 rte->rtekind = RTE_RELATION;
1721 rte->relid = RelationGetRelid(fk_rel);
1722 rte->relkind = fk_rel->rd_rel->relkind;
1723 rte->rellockmode = AccessShareLock;
1724 rte->perminfoindex = list_length(perminfos);
1725 rtes = lappend(rtes, rte);
1726
1727 for (int i = 0; i < riinfo->nkeys; i++)
1728 {
1729 int attno;
1730
1731 attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1732 pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1733
1734 attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1735 fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1736 }
1737
1738 if (!ExecCheckPermissions(rtes, perminfos, false))
1739 return false;
1740
1741 /*
1742 * Also punt if RLS is enabled on either table unless this role has the
1743 * bypassrls right or is the table owner of the table(s) involved which
1744 * have RLS enabled.
1745 */
1747 ((pk_rel->rd_rel->relrowsecurity &&
1749 GetUserId())) ||
1750 (fk_rel->rd_rel->relrowsecurity &&
1752 GetUserId()))))
1753 return false;
1754
1755 /*----------
1756 * The query string built is:
1757 * SELECT fk.keycols FROM [ONLY] relname fk
1758 * LEFT OUTER JOIN [ONLY] pkrelname pk
1759 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1760 * WHERE pk.pkkeycol1 IS NULL AND
1761 * For MATCH SIMPLE:
1762 * (fk.keycol1 IS NOT NULL [AND ...])
1763 * For MATCH FULL:
1764 * (fk.keycol1 IS NOT NULL [OR ...])
1765 *
1766 * We attach COLLATE clauses to the operators when comparing columns
1767 * that have different collations.
1768 *----------
1769 */
1771 appendStringInfoString(&querybuf, "SELECT ");
1772 sep = "";
1773 for (int i = 0; i < riinfo->nkeys; i++)
1774 {
1776 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1777 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1778 sep = ", ";
1779 }
1780
1783 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1784 "" : "ONLY ";
1785 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1786 "" : "ONLY ";
1788 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1790
1791 strcpy(pkattname, "pk.");
1792 strcpy(fkattname, "fk.");
1793 sep = "(";
1794 for (int i = 0; i < riinfo->nkeys; i++)
1795 {
1796 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1797 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1798 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1799 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1800
1802 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1804 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1807 riinfo->pf_eq_oprs[i],
1809 if (pk_coll != fk_coll)
1811 sep = "AND";
1812 }
1813
1814 /*
1815 * It's sufficient to test any one pk attribute for null to detect a join
1816 * failure.
1817 */
1818 quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1819 appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1820
1821 sep = "";
1822 for (int i = 0; i < riinfo->nkeys; i++)
1823 {
1824 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1826 "%sfk.%s IS NOT NULL",
1827 sep, fkattname);
1828 switch (riinfo->confmatchtype)
1829 {
1831 sep = " AND ";
1832 break;
1834 sep = " OR ";
1835 break;
1836 }
1837 }
1839
1840 /*
1841 * Temporarily increase work_mem so that the check query can be executed
1842 * more efficiently. It seems okay to do this because the query is simple
1843 * enough to not use a multiple of work_mem, and one typically would not
1844 * have many large foreign-key validations happening concurrently. So
1845 * this seems to meet the criteria for being considered a "maintenance"
1846 * operation, and accordingly we use maintenance_work_mem. However, we
1847 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1848 * let that get applied to the maintenance_work_mem value.
1849 *
1850 * We use the equivalent of a function SET option to allow the setting to
1851 * persist for exactly the duration of the check query. guc.c also takes
1852 * care of undoing the setting on error.
1853 */
1854 save_nestlevel = NewGUCNestLevel();
1855
1857 (void) set_config_option("work_mem", workmembuf,
1859 GUC_ACTION_SAVE, true, 0, false);
1860 (void) set_config_option("hash_mem_multiplier", "1",
1862 GUC_ACTION_SAVE, true, 0, false);
1863
1864 SPI_connect();
1865
1866 /*
1867 * Generate the plan. We don't need to cache it, and there are no
1868 * arguments to the plan.
1869 */
1870 qplan = SPI_prepare(querybuf.data, 0, NULL);
1871
1872 if (qplan == NULL)
1873 elog(ERROR, "SPI_prepare returned %s for %s",
1875
1876 /*
1877 * Run the plan. For safety we force a current snapshot to be used. (In
1878 * transaction-snapshot mode, this arguably violates transaction isolation
1879 * rules, but we really haven't got much choice.) We don't need to
1880 * register the snapshot, because SPI_execute_snapshot will see to it. We
1881 * need at most one tuple returned, so pass limit = 1.
1882 */
1884 NULL, NULL,
1887 true, false, 1);
1888
1889 /* Check result */
1891 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1892
1893 /* Did we find a tuple violating the constraint? */
1894 if (SPI_processed > 0)
1895 {
1896 TupleTableSlot *slot;
1897 HeapTuple tuple = SPI_tuptable->vals[0];
1898 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1900
1901 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1902
1903 heap_deform_tuple(tuple, tupdesc,
1904 slot->tts_values, slot->tts_isnull);
1906
1907 /*
1908 * The columns to look at in the result tuple are 1..N, not whatever
1909 * they are in the fk_rel. Hack up riinfo so that the subroutines
1910 * called here will behave properly.
1911 *
1912 * In addition to this, we have to pass the correct tupdesc to
1913 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1914 * or fk_rel's tupdesc.
1915 */
1917 for (int i = 0; i < fake_riinfo.nkeys; i++)
1918 fake_riinfo.fk_attnums[i] = i + 1;
1919
1920 /*
1921 * If it's MATCH FULL, and there are any nulls in the FK keys,
1922 * complain about that rather than the lack of a match. MATCH FULL
1923 * disallows partially-null FK rows.
1924 */
1925 if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1926 ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1927 ereport(ERROR,
1929 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1931 NameStr(fake_riinfo.conname)),
1932 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1934 NameStr(fake_riinfo.conname))));
1935
1936 /*
1937 * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1938 * query, which isn't true, but will cause it to use
1939 * fake_riinfo.fk_attnums as we need.
1940 */
1942 pk_rel, fk_rel,
1943 slot, tupdesc,
1944 RI_PLAN_CHECK_LOOKUPPK, false, false);
1945
1947 }
1948
1949 if (SPI_finish() != SPI_OK_FINISH)
1950 elog(ERROR, "SPI_finish failed");
1951
1952 /*
1953 * Restore work_mem and hash_mem_multiplier.
1954 */
1955 AtEOXact_GUC(true, save_nestlevel);
1956
1957 return true;
1958}
1959
1960/*
1961 * RI_PartitionRemove_Check -
1962 *
1963 * Verify no referencing values exist, when a partition is detached on
1964 * the referenced side of a foreign key constraint.
1965 */
1966void
1968{
1971 char *constraintDef;
1976 const char *sep;
1977 const char *fk_only;
1978 int save_nestlevel;
1979 char workmembuf[32];
1980 int spi_result;
1982 int i;
1983
1985
1986 /*
1987 * We don't check permissions before displaying the error message, on the
1988 * assumption that the user detaching the partition must have enough
1989 * privileges to examine the table contents anyhow.
1990 */
1991
1992 /*----------
1993 * The query string built is:
1994 * SELECT fk.keycols FROM [ONLY] relname fk
1995 * JOIN pkrelname pk
1996 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1997 * WHERE (<partition constraint>) AND
1998 * For MATCH SIMPLE:
1999 * (fk.keycol1 IS NOT NULL [AND ...])
2000 * For MATCH FULL:
2001 * (fk.keycol1 IS NOT NULL [OR ...])
2002 *
2003 * We attach COLLATE clauses to the operators when comparing columns
2004 * that have different collations.
2005 *----------
2006 */
2008 appendStringInfoString(&querybuf, "SELECT ");
2009 sep = "";
2010 for (i = 0; i < riinfo->nkeys; i++)
2011 {
2013 RIAttName(fk_rel, riinfo->fk_attnums[i]));
2014 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
2015 sep = ", ";
2016 }
2017
2020 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
2021 "" : "ONLY ";
2023 " FROM %s%s fk JOIN %s pk ON",
2025 strcpy(pkattname, "pk.");
2026 strcpy(fkattname, "fk.");
2027 sep = "(";
2028 for (i = 0; i < riinfo->nkeys; i++)
2029 {
2030 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
2031 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
2032 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
2033 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
2034
2036 RIAttName(pk_rel, riinfo->pk_attnums[i]));
2038 RIAttName(fk_rel, riinfo->fk_attnums[i]));
2041 riinfo->pf_eq_oprs[i],
2043 if (pk_coll != fk_coll)
2045 sep = "AND";
2046 }
2047
2048 /*
2049 * Start the WHERE clause with the partition constraint (except if this is
2050 * the default partition and there's no other partition, because the
2051 * partition constraint is the empty string in that case.)
2052 */
2054 if (constraintDef && constraintDef[0] != '\0')
2055 appendStringInfo(&querybuf, ") WHERE %s AND (",
2057 else
2058 appendStringInfoString(&querybuf, ") WHERE (");
2059
2060 sep = "";
2061 for (i = 0; i < riinfo->nkeys; i++)
2062 {
2063 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
2065 "%sfk.%s IS NOT NULL",
2066 sep, fkattname);
2067 switch (riinfo->confmatchtype)
2068 {
2070 sep = " AND ";
2071 break;
2073 sep = " OR ";
2074 break;
2075 }
2076 }
2078
2079 /*
2080 * Temporarily increase work_mem so that the check query can be executed
2081 * more efficiently. It seems okay to do this because the query is simple
2082 * enough to not use a multiple of work_mem, and one typically would not
2083 * have many large foreign-key validations happening concurrently. So
2084 * this seems to meet the criteria for being considered a "maintenance"
2085 * operation, and accordingly we use maintenance_work_mem. However, we
2086 * must also set hash_mem_multiplier to 1, since it is surely not okay to
2087 * let that get applied to the maintenance_work_mem value.
2088 *
2089 * We use the equivalent of a function SET option to allow the setting to
2090 * persist for exactly the duration of the check query. guc.c also takes
2091 * care of undoing the setting on error.
2092 */
2093 save_nestlevel = NewGUCNestLevel();
2094
2096 (void) set_config_option("work_mem", workmembuf,
2098 GUC_ACTION_SAVE, true, 0, false);
2099 (void) set_config_option("hash_mem_multiplier", "1",
2101 GUC_ACTION_SAVE, true, 0, false);
2102
2103 SPI_connect();
2104
2105 /*
2106 * Generate the plan. We don't need to cache it, and there are no
2107 * arguments to the plan.
2108 */
2109 qplan = SPI_prepare(querybuf.data, 0, NULL);
2110
2111 if (qplan == NULL)
2112 elog(ERROR, "SPI_prepare returned %s for %s",
2114
2115 /*
2116 * Run the plan. For safety we force a current snapshot to be used. (In
2117 * transaction-snapshot mode, this arguably violates transaction isolation
2118 * rules, but we really haven't got much choice.) We don't need to
2119 * register the snapshot, because SPI_execute_snapshot will see to it. We
2120 * need at most one tuple returned, so pass limit = 1.
2121 */
2123 NULL, NULL,
2126 true, false, 1);
2127
2128 /* Check result */
2130 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2131
2132 /* Did we find a tuple that would violate the constraint? */
2133 if (SPI_processed > 0)
2134 {
2135 TupleTableSlot *slot;
2136 HeapTuple tuple = SPI_tuptable->vals[0];
2137 TupleDesc tupdesc = SPI_tuptable->tupdesc;
2139
2140 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
2141
2142 heap_deform_tuple(tuple, tupdesc,
2143 slot->tts_values, slot->tts_isnull);
2145
2146 /*
2147 * The columns to look at in the result tuple are 1..N, not whatever
2148 * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
2149 * will behave properly.
2150 *
2151 * In addition to this, we have to pass the correct tupdesc to
2152 * ri_ReportViolation, overriding its normal habit of using the pk_rel
2153 * or fk_rel's tupdesc.
2154 */
2156 for (i = 0; i < fake_riinfo.nkeys; i++)
2157 fake_riinfo.pk_attnums[i] = i + 1;
2158
2160 slot, tupdesc, 0, false, true);
2161 }
2162
2163 if (SPI_finish() != SPI_OK_FINISH)
2164 elog(ERROR, "SPI_finish failed");
2165
2166 /*
2167 * Restore work_mem and hash_mem_multiplier.
2168 */
2169 AtEOXact_GUC(true, save_nestlevel);
2170}
2171
2172
2173/* ----------
2174 * Local functions below
2175 * ----------
2176 */
2177
2178
2179/*
2180 * quoteOneName --- safely quote a single SQL name
2181 *
2182 * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
2183 */
2184static void
2185quoteOneName(char *buffer, const char *name)
2186{
2187 /* Rather than trying to be smart, just always quote it. */
2188 *buffer++ = '"';
2189 while (*name)
2190 {
2191 if (*name == '"')
2192 *buffer++ = '"';
2193 *buffer++ = *name++;
2194 }
2195 *buffer++ = '"';
2196 *buffer = '\0';
2197}
2198
2199/*
2200 * quoteRelationName --- safely quote a fully qualified relation name
2201 *
2202 * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
2203 */
2204static void
2205quoteRelationName(char *buffer, Relation rel)
2206{
2208 buffer += strlen(buffer);
2209 *buffer++ = '.';
2211}
2212
2213/*
2214 * ri_GenerateQual --- generate a WHERE clause equating two variables
2215 *
2216 * This basically appends " sep leftop op rightop" to buf, adding casts
2217 * and schema qualification as needed to ensure that the parser will select
2218 * the operator we specify. leftop and rightop should be parenthesized
2219 * if they aren't variables or parameters.
2220 */
2221static void
2223 const char *sep,
2224 const char *leftop, Oid leftoptype,
2225 Oid opoid,
2226 const char *rightop, Oid rightoptype)
2227{
2228 appendStringInfo(buf, " %s ", sep);
2231}
2232
2233/*
2234 * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
2235 *
2236 * We only have to use this function when directly comparing the referencing
2237 * and referenced columns, if they are of different collations; else the
2238 * parser will fail to resolve the collation to use. We don't need to use
2239 * this function for RI queries that compare a variable to a $n parameter.
2240 * Since parameter symbols always have default collation, the effect will be
2241 * to use the variable's collation.
2242 *
2243 * Note that we require that the collations of the referencing and the
2244 * referenced column have the same notion of equality: Either they have to
2245 * both be deterministic or else they both have to be the same. (See also
2246 * ATAddForeignKeyConstraint().)
2247 */
2248static void
2250{
2251 HeapTuple tp;
2253 char *collname;
2255
2256 /* Nothing to do if it's a noncollatable data type */
2257 if (!OidIsValid(collation))
2258 return;
2259
2260 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2261 if (!HeapTupleIsValid(tp))
2262 elog(ERROR, "cache lookup failed for collation %u", collation);
2264 collname = NameStr(colltup->collname);
2265
2266 /*
2267 * We qualify the name always, for simplicity and to ensure the query is
2268 * not search-path-dependent.
2269 */
2271 appendStringInfo(buf, " COLLATE %s", onename);
2272 quoteOneName(onename, collname);
2273 appendStringInfo(buf, ".%s", onename);
2274
2275 ReleaseSysCache(tp);
2276}
2277
2278/* ----------
2279 * ri_BuildQueryKey -
2280 *
2281 * Construct a hashtable key for a prepared SPI plan of an FK constraint.
2282 *
2283 * key: output argument, *key is filled in based on the other arguments
2284 * riinfo: info derived from pg_constraint entry
2285 * constr_queryno: an internal number identifying the query type
2286 * (see RI_PLAN_XXX constants at head of file)
2287 * ----------
2288 */
2289static void
2291 int32 constr_queryno)
2292{
2293 /*
2294 * Inherited constraints with a common ancestor can share ri_query_cache
2295 * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2296 * Except in that case, the query processes the other table involved in
2297 * the FK constraint (i.e., not the table on which the trigger has been
2298 * fired), and so it will be the same for all members of the inheritance
2299 * tree. So we may use the root constraint's OID in the hash key, rather
2300 * than the constraint's own OID. This avoids creating duplicate SPI
2301 * plans, saving lots of work and memory when there are many partitions
2302 * with similar FK constraints.
2303 *
2304 * (Note that we must still have a separate RI_ConstraintInfo for each
2305 * constraint, because partitions can have different column orders,
2306 * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2307 *
2308 * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2309 * to use memset to clear them.
2310 */
2311 if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2312 key->constr_id = riinfo->constraint_root_id;
2313 else
2314 key->constr_id = riinfo->constraint_id;
2315 key->constr_queryno = constr_queryno;
2316}
2317
2318/*
2319 * Check that RI trigger function was called in expected context
2320 */
2321static void
2323{
2324 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2325
2326 if (!CALLED_AS_TRIGGER(fcinfo))
2327 ereport(ERROR,
2329 errmsg("function \"%s\" was not called by trigger manager", funcname)));
2330
2331 /*
2332 * Check proper event
2333 */
2334 if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2335 !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2336 ereport(ERROR,
2338 errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2339
2340 switch (tgkind)
2341 {
2342 case RI_TRIGTYPE_INSERT:
2343 if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2344 ereport(ERROR,
2346 errmsg("function \"%s\" must be fired for INSERT", funcname)));
2347 break;
2348 case RI_TRIGTYPE_UPDATE:
2349 if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2350 ereport(ERROR,
2352 errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2353 break;
2354 case RI_TRIGTYPE_DELETE:
2355 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2356 ereport(ERROR,
2358 errmsg("function \"%s\" must be fired for DELETE", funcname)));
2359 break;
2360 }
2361}
2362
2363
2364/*
2365 * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
2366 */
2367static RI_ConstraintInfo *
2369{
2370 Oid constraintOid = trigger->tgconstraint;
2372
2373 /*
2374 * Check that the FK constraint's OID is available; it might not be if
2375 * we've been invoked via an ordinary trigger or an old-style "constraint
2376 * trigger".
2377 */
2379 ereport(ERROR,
2381 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2383 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2384
2385 /* Find or create a hashtable entry for the constraint */
2387
2388 /* Do some easy cross-checks against the trigger call data */
2389 if (rel_is_pk)
2390 {
2391 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2392 riinfo->pk_relid != RelationGetRelid(trig_rel))
2393 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2395 }
2396 else
2397 {
2398 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2399 riinfo->pk_relid != trigger->tgconstrrelid)
2400 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2402 }
2403
2404 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2405 riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
2406 riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
2407 elog(ERROR, "unrecognized confmatchtype: %d",
2408 riinfo->confmatchtype);
2409
2410 if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2411 ereport(ERROR,
2413 errmsg("MATCH PARTIAL not yet implemented")));
2414
2415 return riinfo;
2416}
2417
2418/*
2419 * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
2420 */
2421static RI_ConstraintInfo *
2423{
2425 bool found;
2426 HeapTuple tup;
2428
2429 /*
2430 * On the first call initialize the hashtable
2431 */
2434
2435 /*
2436 * Find or create a hash entry. If we find a valid one, just return it.
2437 */
2440 HASH_ENTER, &found);
2441 if (!found)
2442 riinfo->valid = false;
2443 else if (riinfo->valid)
2444 return riinfo;
2445
2446 /*
2447 * Fetch the pg_constraint row so we can fill in the entry.
2448 */
2450 if (!HeapTupleIsValid(tup)) /* should not happen */
2451 elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2453
2454 if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2455 elog(ERROR, "constraint %u is not a foreign key constraint",
2457
2458 /* And extract data */
2459 Assert(riinfo->constraint_id == constraintOid);
2460 if (OidIsValid(conForm->conparentid))
2461 riinfo->constraint_root_id =
2462 get_ri_constraint_root(conForm->conparentid);
2463 else
2464 riinfo->constraint_root_id = constraintOid;
2465 riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2467 riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2468 ObjectIdGetDatum(riinfo->constraint_root_id));
2469 memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2470 riinfo->pk_relid = conForm->confrelid;
2471 riinfo->fk_relid = conForm->conrelid;
2472 riinfo->confupdtype = conForm->confupdtype;
2473 riinfo->confdeltype = conForm->confdeltype;
2474 riinfo->confmatchtype = conForm->confmatchtype;
2475 riinfo->hasperiod = conForm->conperiod;
2476
2478 &riinfo->nkeys,
2479 riinfo->fk_attnums,
2480 riinfo->pk_attnums,
2481 riinfo->pf_eq_oprs,
2482 riinfo->pp_eq_oprs,
2483 riinfo->ff_eq_oprs,
2484 &riinfo->ndelsetcols,
2485 riinfo->confdelsetcols);
2486
2487 /*
2488 * For temporal FKs, get the operators and functions we need. We ask the
2489 * opclass of the PK element for these. This all gets cached (as does the
2490 * generated plan), so there's no performance issue.
2491 */
2492 if (riinfo->hasperiod)
2493 {
2494 Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2495
2496 FindFKPeriodOpers(opclass,
2497 &riinfo->period_contained_by_oper,
2498 &riinfo->agged_period_contained_by_oper,
2499 &riinfo->period_intersect_oper);
2500 }
2501
2502 /* Metadata used by fast path. */
2503 riinfo->conindid = conForm->conindid;
2504 riinfo->pk_is_partitioned =
2506
2508
2509 /*
2510 * For efficient processing of invalidation messages below, we keep a
2511 * doubly-linked count list of all currently valid entries.
2512 */
2514
2515 riinfo->valid = true;
2516
2517 riinfo->fpmeta = NULL;
2518
2519 return riinfo;
2520}
2521
2522/*
2523 * get_ri_constraint_root
2524 * Returns the OID of the constraint's root parent
2525 */
2526static Oid
2528{
2529 for (;;)
2530 {
2531 HeapTuple tuple;
2533
2535 if (!HeapTupleIsValid(tuple))
2536 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2538 ReleaseSysCache(tuple);
2540 break; /* we reached the root constraint */
2542 }
2543 return constrOid;
2544}
2545
2546/*
2547 * Callback for pg_constraint inval events
2548 *
2549 * While most syscache callbacks just flush all their entries, pg_constraint
2550 * gets enough update traffic that it's probably worth being smarter.
2551 * Invalidate any ri_constraint_cache entry associated with the syscache
2552 * entry with the specified hash value, or all entries if hashvalue == 0.
2553 *
2554 * Note: at the time a cache invalidation message is processed there may be
2555 * active references to the cache. Because of this we never remove entries
2556 * from the cache, but only mark them invalid, which is harmless to active
2557 * uses. (Any query using an entry should hold a lock sufficient to keep that
2558 * data from changing under it --- but we may get cache flushes anyway.)
2559 */
2560static void
2562 uint32 hashvalue)
2563{
2564 dlist_mutable_iter iter;
2565
2567
2568 /*
2569 * If the list of currently valid entries gets excessively large, we mark
2570 * them all invalid so we can empty the list. This arrangement avoids
2571 * O(N^2) behavior in situations where a session touches many foreign keys
2572 * and also does many ALTER TABLEs, such as a restore from pg_dump.
2573 */
2575 hashvalue = 0; /* pretend it's a cache reset */
2576
2578 {
2580 valid_link, iter.cur);
2581
2582 /*
2583 * We must invalidate not only entries directly matching the given
2584 * hash value, but also child entries, in case the invalidation
2585 * affects a root constraint.
2586 */
2587 if (hashvalue == 0 ||
2588 riinfo->oidHashValue == hashvalue ||
2589 riinfo->rootHashValue == hashvalue)
2590 {
2591 riinfo->valid = false;
2592 if (riinfo->fpmeta)
2593 {
2594 pfree(riinfo->fpmeta);
2595 riinfo->fpmeta = NULL;
2596 }
2597 /* Remove invalidated entries from the list, too */
2599 }
2600 }
2601}
2602
2603
2604/*
2605 * Prepare execution plan for a query to enforce an RI restriction
2606 */
2607static SPIPlanPtr
2608ri_PlanCheck(const char *querystr, int nargs, const Oid *argtypes,
2610{
2613 Oid save_userid;
2614 int save_sec_context;
2615
2616 /*
2617 * Use the query type code to determine whether the query is run against
2618 * the PK or FK table; we'll do the check as that table's owner
2619 */
2620 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2621 query_rel = pk_rel;
2622 else
2623 query_rel = fk_rel;
2624
2625 /* Switch to proper UID to perform check as */
2626 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2628 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2630
2631 /* Create the plan */
2632 qplan = SPI_prepare(querystr, nargs, argtypes);
2633
2634 if (qplan == NULL)
2635 elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2636
2637 /* Restore UID and security context */
2638 SetUserIdAndSecContext(save_userid, save_sec_context);
2639
2640 /* Save the plan */
2643
2644 return qplan;
2645}
2646
2647/*
2648 * Perform a query to enforce an RI restriction
2649 */
2650static bool
2653 Relation fk_rel, Relation pk_rel,
2655 bool is_restrict,
2656 bool detectNewRows, int expect_OK)
2657{
2659 source_rel;
2660 bool source_is_pk;
2662 Snapshot crosscheck_snapshot;
2663 int limit;
2664 int spi_result;
2665 Oid save_userid;
2666 int save_sec_context;
2667 Datum vals[RI_MAX_NUMKEYS * 2];
2668 char nulls[RI_MAX_NUMKEYS * 2];
2669
2670 /*
2671 * Use the query type code to determine whether the query is run against
2672 * the PK or FK table; we'll do the check as that table's owner
2673 */
2674 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2675 query_rel = pk_rel;
2676 else
2677 query_rel = fk_rel;
2678
2679 /*
2680 * The values for the query are taken from the table on which the trigger
2681 * is called - it is normally the other one with respect to query_rel. An
2682 * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2683 * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2684 * need some less klugy way to determine this.
2685 */
2686 if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
2687 {
2689 source_is_pk = false;
2690 }
2691 else
2692 {
2693 source_rel = pk_rel;
2694 source_is_pk = true;
2695 }
2696
2697 /* Extract the parameters to be passed into the query */
2698 if (newslot)
2699 {
2701 vals, nulls);
2702 if (oldslot)
2704 vals + riinfo->nkeys, nulls + riinfo->nkeys);
2705 }
2706 else
2707 {
2709 vals, nulls);
2710 }
2711
2712 /*
2713 * In READ COMMITTED mode, we just need to use an up-to-date regular
2714 * snapshot, and we will see all rows that could be interesting. But in
2715 * transaction-snapshot mode, we can't change the transaction snapshot. If
2716 * the caller passes detectNewRows == false then it's okay to do the query
2717 * with the transaction snapshot; otherwise we use a current snapshot, and
2718 * tell the executor to error out if it finds any rows under the current
2719 * snapshot that wouldn't be visible per the transaction snapshot. Note
2720 * that SPI_execute_snapshot will register the snapshots, so we don't need
2721 * to bother here.
2722 */
2724 {
2725 CommandCounterIncrement(); /* be sure all my own work is visible */
2727 crosscheck_snapshot = GetTransactionSnapshot();
2728 }
2729 else
2730 {
2731 /* the default SPI behavior is okay */
2733 crosscheck_snapshot = InvalidSnapshot;
2734 }
2735
2736 /*
2737 * If this is a select query (e.g., for a 'no action' or 'restrict'
2738 * trigger), we only need to see if there is a single row in the table,
2739 * matching the key. Otherwise, limit = 0 - because we want the query to
2740 * affect ALL the matching rows.
2741 */
2742 limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2743
2744 /* Switch to proper UID to perform check as */
2745 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2747 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2749
2750 /*
2751 * Finally we can run the query.
2752 *
2753 * Set fire_triggers to false to ensure that AFTER triggers are queued in
2754 * the outer query's after-trigger context and fire after all RI updates
2755 * on the same row are complete, rather than immediately.
2756 */
2758 vals, nulls,
2759 test_snapshot, crosscheck_snapshot,
2760 false, false, limit);
2761
2762 /* Restore UID and security context */
2763 SetUserIdAndSecContext(save_userid, save_sec_context);
2764
2765 /* Check result */
2766 if (spi_result < 0)
2767 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2768
2769 if (expect_OK >= 0 && spi_result != expect_OK)
2770 ereport(ERROR,
2772 errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2774 NameStr(riinfo->conname),
2776 errhint("This is most likely due to a rule having rewritten the query.")));
2777
2778 /* XXX wouldn't it be clearer to do this part at the caller? */
2779 if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
2781 (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
2783 pk_rel, fk_rel,
2785 NULL,
2786 qkey->constr_queryno, is_restrict, false);
2787
2788 return SPI_processed != 0;
2789}
2790
2791/*
2792 * ri_FastPathCheck
2793 * Perform per row FK existence check via direct index probe,
2794 * bypassing SPI.
2795 *
2796 * If no matching PK row exists, report the violation via ri_ReportViolation(),
2797 * otherwise, the function returns normally.
2798 *
2799 * Note: This is only used by the ALTER TABLE validation path. Other paths use
2800 * ri_FastPathBatchAdd().
2801 */
2802static void
2805{
2806 Relation pk_rel;
2807 Relation idx_rel;
2808 IndexScanDesc scandesc;
2809 TupleTableSlot *slot;
2813 bool found = false;
2816 Snapshot snapshot;
2817
2818 /*
2819 * Advance the command counter so the snapshot sees the effects of prior
2820 * triggers in this statement. Mirrors what the SPI path does in
2821 * ri_PerformCheck().
2822 */
2825
2826 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
2827 idx_rel = index_open(riinfo->conindid, AccessShareLock);
2828
2829 slot = table_slot_create(pk_rel, NULL);
2830 scandesc = index_beginscan(pk_rel, idx_rel,
2831 snapshot, NULL,
2832 riinfo->nkeys, 0,
2833 SO_NONE);
2834
2840 ri_CheckPermissions(pk_rel);
2841
2842 if (riinfo->fpmeta == NULL)
2843 {
2844 /* Reload to ensure it's valid. */
2845 riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2847 }
2848 Assert(riinfo->fpmeta);
2851 found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, slot,
2852 snapshot, riinfo, skey, riinfo->nkeys);
2854 index_endscan(scandesc);
2856 UnregisterSnapshot(snapshot);
2857
2858 if (!found)
2860 newslot, NULL,
2861 RI_PLAN_CHECK_LOOKUPPK, false, false);
2862
2863 index_close(idx_rel, NoLock);
2864 table_close(pk_rel, NoLock);
2865}
2866
2867/*
2868 * ri_FastPathBatchAdd
2869 * Buffer a FK row for batched probing.
2870 *
2871 * Adds the row to the batch buffer. When the buffer is full, flushes all
2872 * buffered rows by probing the PK index. Any violation is reported
2873 * immediately during the flush via ri_ReportViolation (which does not return).
2874 *
2875 * Uses the per-batch cache (RI_FastPathEntry) to avoid per-row relation
2876 * open/close, slot creation, etc.
2877 *
2878 * The batch is also flushed at end of trigger-firing cycle via
2879 * ri_FastPathEndBatch().
2880 */
2881static void
2884{
2886
2887 /*
2888 * If this entry is already being flushed, a cast function or an operator
2889 * invoked during the flush has re-entered with DML on the same FK. Fall
2890 * back to the per-row path rather than touching the batch array, which is
2891 * mid-flush.
2892 */
2893 if (unlikely(fpentry->flushing))
2894 {
2896 return;
2897 }
2898
2899 /*
2900 * Buffer the row. A full batch is flushed below and re-entry is handled
2901 * above, so there is always room here; the bounds check just guards the
2902 * array write.
2903 */
2904 if (fpentry->batch_count < RI_FASTPATH_BATCH_SIZE)
2905 {
2907
2908 fpentry->batch[fpentry->batch_count] =
2910 fpentry->batch_count++;
2912 }
2913 else
2914 elog(ERROR, "RI fast-path batch unexpectedly full");
2915
2916 /* Flush as soon as the batch is full. */
2917 if (fpentry->batch_count == RI_FASTPATH_BATCH_SIZE)
2919}
2920
2921/*
2922 * ri_FastPathBatchFlush
2923 * Flush all buffered FK rows by probing the PK index.
2924 *
2925 * Dispatches to ri_FastPathFlushArray() for single-column FKs
2926 * (using SK_SEARCHARRAY) or ri_FastPathFlushLoop() for multi-column
2927 * FKs (per-row probing). Violations are reported immediately via
2928 * ri_ReportViolation(), which does not return.
2929 */
2930static void
2933{
2934 Relation pk_rel = fpentry->pk_rel;
2935 Relation idx_rel = fpentry->idx_rel;
2936 TupleTableSlot *fk_slot = fpentry->fk_slot;
2937 Snapshot snapshot;
2938 IndexScanDesc scandesc;
2942 int violation_index;
2943
2944 if (fpentry->batch_count == 0)
2945 return;
2946
2947 /*
2948 * CCI and security context switch are done once for the entire batch.
2949 * Per-row CCI is unnecessary because by the time a flush runs, all AFTER
2950 * triggers for the buffered rows have already fired (trigger invocations
2951 * strictly alternate per row), so a single CCI advances past all their
2952 * effects. Per-row security context switch is unnecessary because each
2953 * row's probe runs entirely as the PK table owner, same as the SPI path
2954 * -- the only difference is that the SPI path sets and restores the
2955 * context per row whereas we do it once around the whole batch.
2956 */
2959
2960 /*
2961 * build_index_scankeys() may palloc cast results for cross-type FKs. Use
2962 * the entry's short-lived flush context so these don't accumulate across
2963 * batches.
2964 */
2965 oldcxt = MemoryContextSwitchTo(fpentry->flush_cxt);
2966
2967 scandesc = index_beginscan(pk_rel, idx_rel, snapshot, NULL,
2968 riinfo->nkeys, 0, SO_NONE);
2969
2975
2976 /*
2977 * Check that the current user has permission to access pk_rel. Done here
2978 * rather than at entry creation so that permission changes between
2979 * flushes are respected, matching the per-row behavior of the SPI path,
2980 * albeit checked once per flush rather than once per row, like in
2981 * ri_FastPathCheck().
2982 */
2983 ri_CheckPermissions(pk_rel);
2984
2985 if (riinfo->fpmeta == NULL)
2986 {
2987 /* Reload to ensure it's valid. */
2988 riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2990 }
2991 Assert(riinfo->fpmeta);
2992
2993 /*
2994 * The probe runs user-defined cast and equality functions. Set the
2995 * flushing flag around it so a re-entrant ri_FastPathBatchAdd on this
2996 * entry takes the per-row path, and clear it even on error so the entry
2997 * is reusable if the error is caught by a savepoint.
2998 */
2999 Assert(!fpentry->flushing);
3000 fpentry->flushing = true;
3001 PG_TRY();
3002 {
3003 /* Skip array overhead for single-row batches. */
3004 if (riinfo->nkeys == 1 && fpentry->batch_count > 1)
3006 fk_rel, snapshot, scandesc);
3007 else
3009 fk_rel, snapshot, scandesc);
3010 }
3011 PG_FINALLY();
3012 {
3013 fpentry->flushing = false;
3014 fpentry->batch_count = 0;
3015 }
3016 PG_END_TRY();
3017
3019 UnregisterSnapshot(snapshot);
3020 index_endscan(scandesc);
3021
3022 if (violation_index >= 0)
3023 {
3024 ExecStoreHeapTuple(fpentry->batch[violation_index], fk_slot, false);
3026 fk_slot, NULL,
3027 RI_PLAN_CHECK_LOOKUPPK, false, false);
3028 }
3029
3030 MemoryContextReset(fpentry->flush_cxt);
3032}
3033
3034/*
3035 * ri_FastPathFlushLoop
3036 * Multi-column fallback: probe the index once per buffered row.
3037 *
3038 * Used for composite foreign keys where SK_SEARCHARRAY does not
3039 * apply, and also for single-row batches of single-column FKs where
3040 * the array overhead is not worth it.
3041 *
3042 * Returns the index of the first violating row in the batch array, or -1 if
3043 * all rows are valid.
3044 */
3045static int
3048 Snapshot snapshot, IndexScanDesc scandesc)
3049{
3050 Relation pk_rel = fpentry->pk_rel;
3051 Relation idx_rel = fpentry->idx_rel;
3052 TupleTableSlot *pk_slot = fpentry->pk_slot;
3056 bool found = true;
3057
3058 for (int i = 0; i < fpentry->batch_count; i++)
3059 {
3060 ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
3061 ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
3063
3064 found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, pk_slot,
3065 snapshot, riinfo, skey, riinfo->nkeys);
3066
3067 /* Report first unmatched row */
3068 if (!found)
3069 return i;
3070 }
3071
3072 /* All pass. */
3073 return -1;
3074}
3075
3076/*
3077 * ri_FastPathFlushArray
3078 * Single-column fast path using SK_SEARCHARRAY.
3079 *
3080 * Builds an array of FK values and does one index scan with
3081 * SK_SEARCHARRAY. The index AM sorts and deduplicates the array
3082 * internally, then walks matching leaf pages in order. Each
3083 * matched PK tuple is locked and rechecked as before; a matched[]
3084 * bitmap tracks which batch items were satisfied.
3085 *
3086 * Returns the index of the first violating row in the batch array, or -1 if
3087 * all rows are valid.
3088 */
3089static int
3092 Snapshot snapshot, IndexScanDesc scandesc)
3093{
3094 FastPathMeta *fpmeta = riinfo->fpmeta;
3095 Relation pk_rel = fpentry->pk_rel;
3096 Relation idx_rel = fpentry->idx_rel;
3097 TupleTableSlot *pk_slot = fpentry->pk_slot;
3099 bool matched[RI_FASTPATH_BATCH_SIZE];
3100 int nvals = fpentry->batch_count;
3103 ScanKeyData skey[1];
3104 FmgrInfo *cast_func_finfo;
3105 FmgrInfo *eq_opr_finfo;
3106 Oid elem_type;
3108 bool elem_byval;
3109 char elem_align;
3110 ArrayType *arr;
3111
3112 Assert(fpmeta);
3113
3114 memset(matched, 0, nvals * sizeof(bool));
3115
3116 /*
3117 * Extract FK values, casting to the operator's expected input type if
3118 * needed (e.g. int8 FK -> int4 for int48eq).
3119 */
3120 cast_func_finfo = &fpmeta->cast_func_finfo[0];
3121 eq_opr_finfo = &fpmeta->eq_opr_finfo[0];
3122 for (int i = 0; i < nvals; i++)
3123 {
3124 ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
3125 ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
3126
3127 /* Cast if needed (e.g. int8 FK -> numeric PK) */
3128 if (OidIsValid(cast_func_finfo->fn_oid))
3129 search_vals[i] = FunctionCall3(cast_func_finfo,
3130 pk_vals[0],
3131 Int32GetDatum(-1),
3132 BoolGetDatum(false));
3133 else
3134 search_vals[i] = pk_vals[0];
3135 }
3136
3137 /*
3138 * Array element type must match the operator's right-hand input type,
3139 * which is what the index comparison expects on the search side.
3140 * ri_populate_fastpath_metadata() stores exactly this via
3141 * get_op_opfamily_properties(), which returns the operator's right-hand
3142 * type as the subtype for cross-type operators (e.g. int8 for int48eq)
3143 * and the common type for same-type operators.
3144 */
3145 elem_type = fpmeta->subtypes[0];
3148
3151
3152 /*
3153 * Build scan key with SK_SEARCHARRAY. The index AM code will internally
3154 * sort and deduplicate, then walk leaf pages in order.
3155 *
3156 * PK indexes are always btree, which supports SK_SEARCHARRAY.
3157 *
3158 * This path handles single-column FKs only, so index_attnos[0] == 1.
3159 */
3160 Assert(idx_rel->rd_indam->amsearcharray);
3161 Assert(fpmeta->index_attnos[0] == 1);
3164 fpmeta->index_attnos[0],
3165 fpmeta->strats[0],
3166 fpmeta->subtypes[0],
3167 idx_rel->rd_indcollation[fpmeta->index_attnos[0] - 1],
3168 fpmeta->regops[0],
3169 PointerGetDatum(arr));
3170
3171 index_rescan(scandesc, skey, 1, NULL, 0);
3172
3173 /*
3174 * Walk all matches. The index AM returns them in index order. For each
3175 * match, find which batch item(s) it satisfies.
3176 */
3177 while (index_getnext_slot(scandesc, ForwardScanDirection, pk_slot))
3178 {
3180 bool found_null;
3183
3184 if (!ri_LockPKTuple(pk_rel, pk_slot, snapshot, &concurrently_updated))
3185 continue;
3186
3187 /* Extract the PK value from the matched and locked tuple */
3188 found_val = slot_getattr(pk_slot, riinfo->pk_attnums[0], &found_null);
3190
3192 {
3193 /*
3194 * Build a single-key scankey for recheck. We need the actual PK
3195 * value that was found, not the FK search value.
3196 */
3198 fpmeta->strats[0],
3199 fpmeta->subtypes[0],
3200 idx_rel->rd_indcollation[0],
3201 fpmeta->regops[0],
3202 found_val);
3203 if (!recheck_matched_pk_tuple(idx_rel, recheck_skey, 1, pk_slot))
3204 continue;
3205 }
3206
3207 /*
3208 * Linear scan to mark all batch items matching this PK value.
3209 * O(batch_size) per match, O(batch_size^2) worst case -- fine for the
3210 * current batch size of 64.
3211 */
3212 for (int i = 0; i < nvals; i++)
3213 {
3214 if (!matched[i] &&
3215 DatumGetBool(FunctionCall2Coll(eq_opr_finfo,
3216 idx_rel->rd_indcollation[0],
3217 found_val,
3218 search_vals[i])))
3219 matched[i] = true;
3220 }
3221 }
3222
3223 /* Report first unmatched row */
3224 for (int i = 0; i < nvals; i++)
3225 if (!matched[i])
3226 return i;
3227
3228 /* All pass. */
3229 return -1;
3230}
3231
3232/*
3233 * ri_FastPathProbeOne
3234 * Probe the PK index for one set of scan keys, lock the matching
3235 * tuple
3236 *
3237 * Returns true if a matching PK row was found, locked, and (if
3238 * applicable) visible to the transaction snapshot.
3239 */
3240static bool
3242 IndexScanDesc scandesc, TupleTableSlot *slot,
3243 Snapshot snapshot, const RI_ConstraintInfo *riinfo,
3244 ScanKeyData *skey, int nkeys)
3245{
3246 bool found = false;
3247
3248 index_rescan(scandesc, skey, nkeys, NULL, 0);
3249
3250 if (index_getnext_slot(scandesc, ForwardScanDirection, slot))
3251 {
3253
3254 if (ri_LockPKTuple(pk_rel, slot, snapshot,
3256 {
3258 found = recheck_matched_pk_tuple(idx_rel, skey, nkeys, slot);
3259 else
3260 found = true;
3261 }
3262 }
3263
3264 return found;
3265}
3266
3267/*
3268 * ri_LockPKTuple
3269 * Lock a PK tuple found by the fast-path index scan.
3270 *
3271 * Calls table_tuple_lock() directly with handling specific to RI checks.
3272 * Returns true if the tuple was successfully locked.
3273 *
3274 * Sets *concurrently_updated to true if the locked tuple was reached
3275 * by following an update chain (tmfd.traversed), indicating the caller
3276 * should recheck the key.
3277 */
3278static bool
3281{
3282 TM_FailureData tmfd;
3285
3286 *concurrently_updated = false;
3287
3290
3291 result = table_tuple_lock(pk_rel, &slot->tts_tid, snap,
3292 slot, GetCurrentCommandId(false),
3294 lockflags, &tmfd);
3295
3296 switch (result)
3297 {
3298 case TM_Ok:
3299 if (tmfd.traversed)
3300 *concurrently_updated = true;
3301 return true;
3302
3303 case TM_Deleted:
3305 ereport(ERROR,
3307 errmsg("could not serialize access due to concurrent delete")));
3308 return false;
3309
3310 case TM_Updated:
3312 ereport(ERROR,
3314 errmsg("could not serialize access due to concurrent update")));
3315
3316 /*
3317 * In READ COMMITTED, FIND_LAST_VERSION should have chased the
3318 * chain and returned TM_Ok. Getting here means something
3319 * unexpected -- fall through to error.
3320 */
3321 elog(ERROR, "unexpected table_tuple_lock status: %u", result);
3322 break;
3323
3324 case TM_SelfModified:
3325
3326 /*
3327 * The current command or a later command in this transaction
3328 * modified the PK row. This shouldn't normally happen during an
3329 * FK check (we're not modifying pk_rel), but handle it safely by
3330 * treating the tuple as not found.
3331 */
3332 return false;
3333
3334 case TM_Invisible:
3335 elog(ERROR, "attempted to lock invisible tuple");
3336 break;
3337
3338 default:
3339 elog(ERROR, "unrecognized table_tuple_lock status: %u", result);
3340 break;
3341 }
3342
3343 return false; /* keep compiler quiet */
3344}
3345
3346static bool
3348{
3349 /*
3350 * Partitioned referenced tables are skipped for simplicity, since they
3351 * require routing the probe through the correct partition using
3352 * PartitionDirectory.
3353 */
3354 if (riinfo->pk_is_partitioned)
3355 return false;
3356
3357 /*
3358 * Temporal foreign keys use range overlap and containment semantics (&&,
3359 * <@, range_agg()) that inherently involve aggregation and multiple-row
3360 * reasoning, so they stay on the SPI path.
3361 */
3362 if (riinfo->hasperiod)
3363 return false;
3364
3365 return true;
3366}
3367
3368/*
3369 * ri_CheckPermissions
3370 * Check that the current user has permissions to look into the schema of
3371 * and SELECT from 'query_rel'
3372 */
3373static void
3393
3394/*
3395 * recheck_matched_pk_tuple
3396 * After following an update chain (tmfd.traversed), verify that
3397 * the locked PK tuple still matches the original search keys.
3398 *
3399 * A non-key update (e.g. changing a non-PK column) creates a new tuple version
3400 * that we've now locked, but the key is unchanged -- that's fine. A key
3401 * update means the value we were looking for is gone, so we should treat it as
3402 * not found.
3403 */
3404static bool
3406 TupleTableSlot *new_slot)
3407{
3408 /*
3409 * TODO: BuildIndexInfo does a syscache lookup + palloc on every call.
3410 * This only fires on the concurrent-update path (tmfd.traversed), which
3411 * should be rare, so the cost is acceptable for now. If profiling shows
3412 * otherwise, cache the IndexInfo in FastPathMeta.
3413 */
3414 IndexInfo *indexInfo = BuildIndexInfo(idxrel);
3416 bool isnull[INDEX_MAX_KEYS];
3417 bool matched = true;
3418
3419 /* PK indexes never have these. */
3420 Assert(indexInfo->ii_Expressions == NIL &&
3421 indexInfo->ii_ExclusionOps == NULL);
3422
3423 /* Form the index values and isnull flags given the table tuple. */
3424 Assert(nkeys == indexInfo->ii_NumIndexKeyAttrs);
3425 FormIndexDatum(indexInfo, new_slot, NULL, values, isnull);
3426 for (int i = 0; i < nkeys; i++)
3427 {
3428 ScanKeyData *skey = &skeys[i];
3429
3430 /* A PK column can never be set to NULL. */
3431 Assert(!isnull[i]);
3432 if (!DatumGetBool(FunctionCall2Coll(&skey->sk_func,
3433 skey->sk_collation,
3434 values[i],
3435 skey->sk_argument)))
3436 {
3437 matched = false;
3438 break;
3439 }
3440 }
3441
3442 return matched;
3443}
3444
3445/*
3446 * build_index_scankeys
3447 * Build ScanKeys for a direct index probe of the PK's unique index.
3448 *
3449 * Uses cached compare entries, operator procedures, and strategy numbers
3450 * from ri_populate_fastpath_metadata() rather than looking them up on
3451 * each invocation. Casts FK values to the operator's expected input
3452 * type if needed.
3453 */
3454static void
3456 Relation idx_rel, Datum *pk_vals,
3457 char *pk_nulls, ScanKey skeys)
3458{
3459 FastPathMeta *fpmeta = riinfo->fpmeta;
3460
3461 Assert(fpmeta);
3462
3463 /*
3464 * May need to cast each of the individual values of the foreign key to
3465 * the corresponding PK column's type if the equality operator demands it.
3466 */
3467 for (int i = 0; i < riinfo->nkeys; i++)
3468 {
3469 if (pk_nulls[i] != 'n' &&
3472 pk_vals[i],
3473 Int32GetDatum(-1), /* typmod */
3474 BoolGetDatum(false)); /* implicit coercion */
3475 }
3476
3477 /*
3478 * Set up ScanKeys for the index scan. This is essentially how
3479 * ExecIndexBuildScanKeys() sets them up. Use the cached index_attnos and
3480 * the corresponding collation since FK columns may be in a different
3481 * order than PK index columns. Place each scan key at the array position
3482 * corresponding to its index column, since btree requires keys to be
3483 * ordered by attribute number.
3484 */
3485 for (int i = 0; i < riinfo->nkeys; i++)
3486 {
3487 AttrNumber pkattrno = fpmeta->index_attnos[i];
3488 int skey_pos = pkattrno - 1; /* 0-based array position */
3489
3491 fpmeta->strats[i], fpmeta->subtypes[i],
3492 idx_rel->rd_indcollation[skey_pos], fpmeta->regops[i],
3493 pk_vals[i]);
3494 }
3495}
3496
3497/*
3498 * ri_populate_fastpath_metadata
3499 * Cache per-key metadata needed by build_index_scankeys().
3500 *
3501 * Looks up the compare hash entry, operator procedure OID, and index
3502 * strategy/subtype for each key column. Called lazily on first use
3503 * and persists for the lifetime of the RI_ConstraintInfo entry.
3504 */
3505static void
3507 Relation fk_rel, Relation idx_rel)
3508{
3509 FastPathMeta *fpmeta;
3511
3512 Assert(riinfo != NULL && riinfo->valid);
3513
3514 fpmeta = palloc_object(FastPathMeta);
3515 for (int i = 0; i < riinfo->nkeys; i++)
3516 {
3517 Oid eq_opr = riinfo->pf_eq_oprs[i];
3518 Oid typeid = RIAttType(fk_rel, riinfo->fk_attnums[i]);
3519 Oid lefttype;
3520 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3521 int idx_col;
3522
3523 /*
3524 * Find the index column position for this constraint key. The FK
3525 * constraint may reference columns in a different order than they
3526 * appear in the PK index, so we must map pk_attnums[i] to the
3527 * corresponding index column position.
3528 */
3529 for (idx_col = 0; idx_col < riinfo->nkeys; idx_col++)
3530 {
3531 if (idx_rel->rd_index->indkey.values[idx_col] == riinfo->pk_attnums[i])
3532 break;
3533 }
3535
3536 /* 1-based attribute number */
3537 fpmeta->index_attnos[i] = idx_col + 1;
3538
3541 fmgr_info_copy(&fpmeta->eq_opr_finfo[i], &entry->eq_opr_finfo,
3543 fpmeta->regops[i] = get_opcode(eq_opr);
3544
3546 idx_rel->rd_opfamily[idx_col],
3547 false,
3548 &fpmeta->strats[i],
3549 &lefttype,
3550 &fpmeta->subtypes[i]);
3551 }
3552
3553 riinfo->fpmeta = fpmeta;
3555}
3556
3557/*
3558 * Extract fields from a tuple into Datum/nulls arrays
3559 */
3560static void
3562 const RI_ConstraintInfo *riinfo, bool rel_is_pk,
3563 Datum *vals, char *nulls)
3564{
3565 const int16 *attnums;
3566 bool isnull;
3567
3568 if (rel_is_pk)
3569 attnums = riinfo->pk_attnums;
3570 else
3571 attnums = riinfo->fk_attnums;
3572
3573 for (int i = 0; i < riinfo->nkeys; i++)
3574 {
3575 vals[i] = slot_getattr(slot, attnums[i], &isnull);
3576 nulls[i] = isnull ? 'n' : ' ';
3577 }
3578}
3579
3580/*
3581 * Produce an error report
3582 *
3583 * If the failed constraint was on insert/update to the FK table,
3584 * we want the key names and values extracted from there, and the error
3585 * message to look like 'key blah is not present in PK'.
3586 * Otherwise, the attr names and values come from the PK table and the
3587 * message looks like 'key blah is still referenced from FK'.
3588 */
3589static void
3591 Relation pk_rel, Relation fk_rel,
3593 int queryno, bool is_restrict, bool partgone)
3594{
3597 bool onfk;
3598 const int16 *attnums;
3599 Oid rel_oid;
3601 bool has_perm = true;
3602
3603 /*
3604 * Determine which relation to complain about. If tupdesc wasn't passed
3605 * by caller, assume the violator tuple came from there.
3606 */
3608 if (onfk)
3609 {
3610 attnums = riinfo->fk_attnums;
3611 rel_oid = fk_rel->rd_id;
3612 if (tupdesc == NULL)
3613 tupdesc = fk_rel->rd_att;
3614 }
3615 else
3616 {
3617 attnums = riinfo->pk_attnums;
3618 rel_oid = pk_rel->rd_id;
3619 if (tupdesc == NULL)
3620 tupdesc = pk_rel->rd_att;
3621 }
3622
3623 /*
3624 * Check permissions- if the user does not have access to view the data in
3625 * any of the key columns then we don't include the errdetail() below.
3626 *
3627 * Check if RLS is enabled on the relation first. If so, we don't return
3628 * any specifics to avoid leaking data.
3629 *
3630 * Check table-level permissions next and, failing that, column-level
3631 * privileges.
3632 *
3633 * When a partition at the referenced side is being detached/dropped, we
3634 * needn't check, since the user must be the table owner anyway.
3635 */
3636 if (partgone)
3637 has_perm = true;
3638 else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
3639 {
3641 if (aclresult != ACLCHECK_OK)
3642 {
3643 /* Try for column-level permissions */
3644 for (int idx = 0; idx < riinfo->nkeys; idx++)
3645 {
3647 GetUserId(),
3648 ACL_SELECT);
3649
3650 /* No access to the key */
3651 if (aclresult != ACLCHECK_OK)
3652 {
3653 has_perm = false;
3654 break;
3655 }
3656 }
3657 }
3658 }
3659 else
3660 has_perm = false;
3661
3662 if (has_perm)
3663 {
3664 /* Get printable versions of the keys involved */
3667 for (int idx = 0; idx < riinfo->nkeys; idx++)
3668 {
3669 int fnum = attnums[idx];
3670 Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
3671 char *name,
3672 *val;
3673 Datum datum;
3674 bool isnull;
3675
3676 name = NameStr(att->attname);
3677
3678 datum = slot_getattr(violatorslot, fnum, &isnull);
3679 if (!isnull)
3680 {
3681 Oid foutoid;
3682 bool typisvarlena;
3683
3684 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
3686 }
3687 else
3688 val = "null";
3689
3690 if (idx > 0)
3691 {
3694 }
3697 }
3698 }
3699
3700 if (partgone)
3701 ereport(ERROR,
3703 errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
3705 NameStr(riinfo->conname)),
3706 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3707 key_names.data, key_values.data,
3710 else if (onfk)
3711 ereport(ERROR,
3713 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
3715 NameStr(riinfo->conname)),
3716 has_perm ?
3717 errdetail("Key (%s)=(%s) is not present in table \"%s\".",
3718 key_names.data, key_values.data,
3719 RelationGetRelationName(pk_rel)) :
3720 errdetail("Key is not present in table \"%s\".",
3721 RelationGetRelationName(pk_rel)),
3723 else if (is_restrict)
3724 ereport(ERROR,
3726 errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
3728 NameStr(riinfo->conname),
3730 has_perm ?
3731 errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
3732 key_names.data, key_values.data,
3734 errdetail("Key is referenced from table \"%s\".",
3737 else
3738 ereport(ERROR,
3740 errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
3742 NameStr(riinfo->conname),
3744 has_perm ?
3745 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3746 key_names.data, key_values.data,
3748 errdetail("Key is still referenced from table \"%s\".",
3751}
3752
3753
3754/*
3755 * ri_NullCheck -
3756 *
3757 * Determine the NULL state of all key values in a tuple
3758 *
3759 * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
3760 */
3761static int
3763 TupleTableSlot *slot,
3764 const RI_ConstraintInfo *riinfo, bool rel_is_pk)
3765{
3766 const int16 *attnums;
3767 bool allnull = true;
3768 bool nonenull = true;
3769
3770 if (rel_is_pk)
3771 attnums = riinfo->pk_attnums;
3772 else
3773 attnums = riinfo->fk_attnums;
3774
3775 for (int i = 0; i < riinfo->nkeys; i++)
3776 {
3777 if (slot_attisnull(slot, attnums[i]))
3778 nonenull = false;
3779 else
3780 allnull = false;
3781 }
3782
3783 if (allnull)
3784 return RI_KEYS_ALL_NULL;
3785
3786 if (nonenull)
3787 return RI_KEYS_NONE_NULL;
3788
3789 return RI_KEYS_SOME_NULL;
3790}
3791
3792
3793/*
3794 * ri_InitHashTables -
3795 *
3796 * Initialize our internal hash tables.
3797 */
3798static void
3800{
3801 HASHCTL ctl;
3802
3803 ctl.keysize = sizeof(Oid);
3804 ctl.entrysize = sizeof(RI_ConstraintInfo);
3805 ri_constraint_cache = hash_create("RI constraint cache",
3808
3809 /* Arrange to flush cache on pg_constraint changes */
3812 (Datum) 0);
3813
3814 ctl.keysize = sizeof(RI_QueryKey);
3815 ctl.entrysize = sizeof(RI_QueryHashEntry);
3816 ri_query_cache = hash_create("RI query cache",
3819
3820 ctl.keysize = sizeof(RI_CompareKey);
3821 ctl.entrysize = sizeof(RI_CompareHashEntry);
3822 ri_compare_cache = hash_create("RI compare cache",
3825}
3826
3827
3828/*
3829 * ri_FetchPreparedPlan -
3830 *
3831 * Lookup for a query key in our private hash table of prepared
3832 * and saved SPI execution plans. Return the plan if found or NULL.
3833 */
3834static SPIPlanPtr
3836{
3837 RI_QueryHashEntry *entry;
3839
3840 /*
3841 * On the first call initialize the hashtable
3842 */
3843 if (!ri_query_cache)
3845
3846 /*
3847 * Lookup for the key
3848 */
3850 key,
3851 HASH_FIND, NULL);
3852 if (entry == NULL)
3853 return NULL;
3854
3855 /*
3856 * Check whether the plan is still valid. If it isn't, we don't want to
3857 * simply rely on plancache.c to regenerate it; rather we should start
3858 * from scratch and rebuild the query text too. This is to cover cases
3859 * such as table/column renames. We depend on the plancache machinery to
3860 * detect possible invalidations, though.
3861 *
3862 * CAUTION: this check is only trustworthy if the caller has already
3863 * locked both FK and PK rels.
3864 */
3865 plan = entry->plan;
3866 if (plan && SPI_plan_is_valid(plan))
3867 return plan;
3868
3869 /*
3870 * Otherwise we might as well flush the cached plan now, to free a little
3871 * memory space before we make a new one.
3872 */
3873 entry->plan = NULL;
3874 if (plan)
3876
3877 return NULL;
3878}
3879
3880
3881/*
3882 * ri_HashPreparedPlan -
3883 *
3884 * Add another plan to our private SPI query plan hashtable.
3885 */
3886static void
3888{
3889 RI_QueryHashEntry *entry;
3890 bool found;
3891
3892 /*
3893 * On the first call initialize the hashtable
3894 */
3895 if (!ri_query_cache)
3897
3898 /*
3899 * Add the new plan. We might be overwriting an entry previously found
3900 * invalid by ri_FetchPreparedPlan.
3901 */
3903 key,
3904 HASH_ENTER, &found);
3905 Assert(!found || entry->plan == NULL);
3906 entry->plan = plan;
3907}
3908
3909
3910/*
3911 * ri_KeysEqual -
3912 *
3913 * Check if all key values in OLD and NEW are "equivalent":
3914 * For normal FKs we check for equality.
3915 * For temporal FKs we check that the PK side is a superset of its old value,
3916 * or the FK side is a subset of its old value.
3917 *
3918 * Note: at some point we might wish to redefine this as checking for
3919 * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
3920 * considered equal. Currently there is no need since all callers have
3921 * previously found at least one of the rows to contain no nulls.
3922 */
3923static bool
3925 const RI_ConstraintInfo *riinfo, bool rel_is_pk)
3926{
3927 const int16 *attnums;
3928
3929 if (rel_is_pk)
3930 attnums = riinfo->pk_attnums;
3931 else
3932 attnums = riinfo->fk_attnums;
3933
3934 /* XXX: could be worthwhile to fetch all necessary attrs at once */
3935 for (int i = 0; i < riinfo->nkeys; i++)
3936 {
3939 bool isnull;
3940
3941 /*
3942 * Get one attribute's oldvalue. If it is NULL - they're not equal.
3943 */
3944 oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3945 if (isnull)
3946 return false;
3947
3948 /*
3949 * Get one attribute's newvalue. If it is NULL - they're not equal.
3950 */
3951 newvalue = slot_getattr(newslot, attnums[i], &isnull);
3952 if (isnull)
3953 return false;
3954
3955 if (rel_is_pk)
3956 {
3957 /*
3958 * If we are looking at the PK table, then do a bytewise
3959 * comparison. We must propagate PK changes if the value is
3960 * changed to one that "looks" different but would compare as
3961 * equal using the equality operator. This only makes a
3962 * difference for ON UPDATE CASCADE, but for consistency we treat
3963 * all changes to the PK the same.
3964 */
3965 CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3966
3967 if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3968 return false;
3969 }
3970 else
3971 {
3972 Oid eq_opr;
3973
3974 /*
3975 * When comparing the PERIOD columns we can skip the check
3976 * whenever the referencing column stayed equal or shrank, so test
3977 * with the contained-by operator instead.
3978 */
3979 if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3980 eq_opr = riinfo->period_contained_by_oper;
3981 else
3982 eq_opr = riinfo->ff_eq_oprs[i];
3983
3984 /*
3985 * For the FK table, compare with the appropriate equality
3986 * operator. Changes that compare equal will still satisfy the
3987 * constraint after the update.
3988 */
3989 if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3991 return false;
3992 }
3993 }
3994
3995 return true;
3996}
3997
3998
3999/*
4000 * ri_CompareWithCast -
4001 *
4002 * Call the appropriate comparison operator for two values.
4003 * Normally this is equality, but for the PERIOD part of foreign keys
4004 * it is ContainedBy, so the order of lhs vs rhs is significant.
4005 * See below for how the collation is applied.
4006 *
4007 * NB: we have already checked that neither value is null.
4008 */
4009static bool
4011 Datum lhs, Datum rhs)
4012{
4013 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
4014
4015 /* Do we need to cast the values? */
4016 if (OidIsValid(entry->cast_func_finfo.fn_oid))
4017 {
4019 lhs,
4020 Int32GetDatum(-1), /* typmod */
4021 BoolGetDatum(false)); /* implicit coercion */
4023 rhs,
4024 Int32GetDatum(-1), /* typmod */
4025 BoolGetDatum(false)); /* implicit coercion */
4026 }
4027
4028 /*
4029 * Apply the comparison operator.
4030 *
4031 * Note: This function is part of a call stack that determines whether an
4032 * update to a row is significant enough that it needs checking or action
4033 * on the other side of a foreign-key constraint. Therefore, the
4034 * comparison here would need to be done with the collation of the *other*
4035 * table. For simplicity (e.g., we might not even have the other table
4036 * open), we'll use our own collation. This is fine because we require
4037 * that both collations have the same notion of equality (either they are
4038 * both deterministic or else they are both the same).
4039 *
4040 * With range/multirangetypes, the collation of the base type is stored as
4041 * part of the rangetype (pg_range.rngcollation), and always used, so
4042 * there is no danger of inconsistency even using a non-equals operator.
4043 * But if we support arbitrary types with PERIOD, we should perhaps just
4044 * always force a re-check.
4045 */
4047}
4048
4049/*
4050 * ri_HashCompareOp -
4051 *
4052 * Look up or create a cache entry for the given equality operator and
4053 * the caller's value type (typeid). The entry holds the operator's
4054 * FmgrInfo and, if typeid doesn't match what the operator expects as
4055 * its right-hand input, a cast function to coerce the value before
4056 * comparison.
4057 */
4058static RI_CompareHashEntry *
4059ri_HashCompareOp(Oid eq_opr, Oid typeid)
4060{
4061 RI_CompareKey key;
4062 RI_CompareHashEntry *entry;
4063 bool found;
4064
4065 /*
4066 * On the first call initialize the hashtable
4067 */
4068 if (!ri_compare_cache)
4070
4071 /*
4072 * Find or create a hash entry. Note we're assuming RI_CompareKey
4073 * contains no struct padding.
4074 */
4075 key.eq_opr = eq_opr;
4076 key.typeid = typeid;
4078 &key,
4079 HASH_ENTER, &found);
4080 if (!found)
4081 entry->valid = false;
4082
4083 /*
4084 * If not already initialized, do so. Since we'll keep this hash entry
4085 * for the life of the backend, put any subsidiary info for the function
4086 * cache structs into TopMemoryContext.
4087 */
4088 if (!entry->valid)
4089 {
4090 Oid lefttype,
4091 righttype,
4092 castfunc;
4093 CoercionPathType pathtype;
4094
4095 /* We always need to know how to call the equality operator */
4096 fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
4098
4099 /*
4100 * If we chose to use a cast from FK to PK type, we may have to apply
4101 * the cast function to get to the operator's input type.
4102 *
4103 * XXX eventually it would be good to support array-coercion cases
4104 * here and in ri_CompareWithCast(). At the moment there is no point
4105 * because cases involving nonidentical array types will be rejected
4106 * at constraint creation time.
4107 *
4108 * XXX perhaps also consider supporting CoerceViaIO? No need at the
4109 * moment since that will never be generated for implicit coercions.
4110 */
4111 op_input_types(eq_opr, &lefttype, &righttype);
4112
4113 /*
4114 * pf_eq_oprs (used by the fast path) can be cross-type when the FK
4115 * and PK columns differ in type, e.g. int48eq for int4 PK / int8 FK.
4116 * If the FK column's type, or the base type of a domain over it,
4117 * already matches what the operator expects as its right-hand input,
4118 * no cast is needed.
4119 */
4120 if (getBaseType(typeid) == righttype)
4121 castfunc = InvalidOid; /* simplest case */
4122 else
4123 {
4124 pathtype = find_coercion_pathway(lefttype, typeid,
4126 &castfunc);
4127 if (pathtype != COERCION_PATH_FUNC &&
4128 pathtype != COERCION_PATH_RELABELTYPE)
4129 {
4130 /*
4131 * The declared input type of the eq_opr might be a
4132 * polymorphic type such as ANYARRAY or ANYENUM, or other
4133 * special cases such as RECORD; find_coercion_pathway
4134 * currently doesn't subsume these special cases.
4135 */
4136 if (!IsBinaryCoercible(typeid, lefttype))
4137 elog(ERROR, "no conversion function from %s to %s",
4138 format_type_be(typeid),
4139 format_type_be(lefttype));
4140 }
4141 }
4142 if (OidIsValid(castfunc))
4143 fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
4145 else
4147 entry->valid = true;
4148 }
4149
4150 return entry;
4151}
4152
4153
4154/*
4155 * Given a trigger function OID, determine whether it is an RI trigger,
4156 * and if so whether it is attached to PK or FK relation.
4157 */
4158int
4160{
4161 switch (tgfoid)
4162 {
4173 return RI_TRIGGER_PK;
4174
4177 return RI_TRIGGER_FK;
4178 }
4179
4180 return RI_TRIGGER_NONE;
4181}
4182
4183/*
4184 * ri_FastPathEndBatch
4185 * Flush remaining rows and tear down cached state.
4186 *
4187 * Registered as an AfterTriggerBatchCallback. Note: the flush can
4188 * do real work (CCI, security context switch, index probes) and can
4189 * throw ERROR on a constraint violation. If that happens,
4190 * ri_FastPathTeardown never runs; ResourceOwner releases the cached
4191 * relations and AtEOXact_RI() resets the static state on the abort path.
4192 */
4193static void
4195{
4196 HASH_SEQ_STATUS status;
4197 RI_FastPathEntry *entry;
4198
4199 if (ri_fastpath_cache == NULL)
4200 return;
4201
4202 /*
4203 * Set a flag for the duration of the scan so that any FK check triggered
4204 * by user cast or operator code during a flush takes the per-row path
4205 * instead of adding a new entry to the cache we are iterating. A new
4206 * entry could land in an already-scanned bucket and then be torn down
4207 * unflushed below.
4208 *
4209 * The flush can throw ERROR (a reported constraint violation, or an error
4210 * from the user code it runs). In that case ri_FastPathTeardown below is
4211 * skipped; the ResourceOwner and the transaction-end callback handle
4212 * resource cleanup on the abort path. The PG_FINALLY only resets the
4213 * flag and deliberately does not attempt teardown.
4214 */
4216 ri_fastpath_flushing = true;
4217 PG_TRY();
4218 {
4220 while ((entry = hash_seq_search(&status)) != NULL)
4221 {
4222 if (entry->batch_count > 0)
4223 {
4226
4229 }
4230 }
4231 }
4232 PG_FINALLY();
4233 {
4234 ri_fastpath_flushing = false;
4235 }
4236 PG_END_TRY();
4237
4239}
4240
4241/*
4242 * ri_FastPathTeardown
4243 * Tear down all cached fast-path state.
4244 *
4245 * Called from ri_FastPathEndBatch() after flushing any remaining rows.
4246 */
4247static void
4249{
4250 HASH_SEQ_STATUS status;
4251 RI_FastPathEntry *entry;
4252
4253 if (ri_fastpath_cache == NULL)
4254 return;
4255
4257 while ((entry = hash_seq_search(&status)) != NULL)
4258 {
4259 if (entry->idx_rel)
4260 index_close(entry->idx_rel, NoLock);
4261 if (entry->pk_rel)
4262 table_close(entry->pk_rel, NoLock);
4263 if (entry->pk_slot)
4265 if (entry->fk_slot)
4267 if (entry->flush_cxt)
4269 }
4270
4274}
4275
4276/*
4277 * AtEOXact_RI
4278 * Reset fast-path batching state at end of transaction.
4279 *
4280 * Called from CommitTransaction() and PrepareTransaction() with isCommit
4281 * true, and from AbortTransaction() with isCommit false.
4282 *
4283 * By the time we get here on a clean commit or prepare, the fast-path cache
4284 * has already been flushed and torn down by ri_FastPathEndBatch() (an
4285 * AfterTriggerBatchCallback fired from AfterTriggerFireDeferred(), well before
4286 * this point), so the static pointers are already clear and the reset below is
4287 * a no-op. A surviving cache at commit means a trigger batch was never
4288 * flushed, which would have silently skipped FK checks, so we complain.
4289 *
4290 * On abort, ri_FastPathEndBatch()/ri_FastPathTeardown() may not have run (a
4291 * flush can error out partway): the ResourceOwner releases the cached
4292 * relations and the TopTransactionContext reset frees the cache memory, but
4293 * the process-local static pointers below would dangle into the next
4294 * transaction. This resets them so they don't.
4295 *
4296 * The reset touches only backend-local static state (no relations, locks,
4297 * buffers or catalog access), so it has no ordering dependency on the
4298 * surrounding ResourceOwnerRelease() / AtEOXact_* steps.
4299 */
4300void
4302{
4303 /*
4304 * The cache must be empty on a clean commit or prepare; a survivor means
4305 * a trigger batch went unflushed. Assert for assert-enabled builds and,
4306 * since the transaction is already committed by now and FK checks may
4307 * have been skipped, also warn in production builds.
4308 */
4311 elog(WARNING, "RI fast-path cache not flushed at end of transaction");
4312
4313 /*
4314 * Clear the static pointers/flags. The cache memory lives in
4315 * TopTransactionContext and is freed by the end-of-transaction
4316 * memory-context reset; here we only drop the references to it.
4317 */
4320
4321 /*
4322 * Also clear the in-flush flag. ri_FastPathEndBatch() already clears it
4323 * via PG_FINALLY, so this is just defensive: it keeps a stale flag from
4324 * surviving into the next transaction should any future path leave it
4325 * set.
4326 */
4327 ri_fastpath_flushing = false;
4328}
4329
4330/*
4331 * ri_FastPathGetEntry
4332 * Look up or create a per-batch cache entry for the given constraint.
4333 *
4334 * On first call for a constraint within a batch: opens pk_rel and the index,
4335 * allocates slots for both FK row and the looked up PK row, and registers the
4336 * cleanup callback.
4337 *
4338 * On subsequent calls: returns the existing entry.
4339 */
4340static RI_FastPathEntry *
4342{
4343 RI_FastPathEntry *entry;
4344 bool found;
4345
4346 /* Create hash table on first use in this batch */
4347 if (ri_fastpath_cache == NULL)
4348 {
4349 HASHCTL ctl;
4350
4351 ctl.keysize = sizeof(Oid);
4352 ctl.entrysize = sizeof(RI_FastPathEntry);
4354 ri_fastpath_cache = hash_create("RI fast-path cache",
4355 16,
4356 &ctl,
4358 }
4359
4360 entry = hash_search(ri_fastpath_cache, &riinfo->constraint_id,
4361 HASH_ENTER, &found);
4362
4363 if (!found)
4364 {
4366
4367 /*
4368 * Zero out non-key fields so ri_FastPathTeardown is safe if we error
4369 * out during partial initialization below.
4370 */
4371 memset(((char *) entry) + offsetof(RI_FastPathEntry, pk_rel), 0,
4372 sizeof(RI_FastPathEntry) - offsetof(RI_FastPathEntry, pk_rel));
4373
4375
4376 entry->fk_relid = RelationGetRelid(fk_rel);
4377
4378 /*
4379 * Open PK table and its unique index.
4380 *
4381 * RowShareLock on pk_rel matches what the SPI path's SELECT ... FOR
4382 * KEY SHARE would acquire as a relation-level lock. AccessShareLock
4383 * on the index is standard for index scans.
4384 *
4385 * We don't release these locks until end of transaction, matching SPI
4386 * behavior.
4387 */
4388 entry->pk_rel = table_open(riinfo->pk_relid, RowShareLock);
4389 entry->idx_rel = index_open(riinfo->conindid, AccessShareLock);
4390 entry->pk_slot = table_slot_create(entry->pk_rel, NULL);
4391
4392 /*
4393 * Must be TTSOpsHeapTuple because ExecStoreHeapTuple() is used to
4394 * load entries from batch[] into this slot for value extraction.
4395 */
4398
4400 "RI fast path flush temporary context",
4403
4404 /* Ensure cleanup at end of this trigger-firing batch */
4406 {
4409 }
4410
4411 entry->flushing = false;
4412 entry->batch_count = 0;
4413 }
4414
4415 return entry;
4416}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
bool has_bypassrls_privilege(Oid roleid)
Definition aclchk.c:4232
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition aclchk.c:3912
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3880
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4134
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4083
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
int16 AttrNumber
Definition attnum.h:21
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define NameStr(name)
Definition c.h:891
#define pg_noreturn
Definition c.h:246
#define Assert(condition)
Definition c.h:999
int16_t int16
Definition c.h:675
regproc RegProcedure
Definition c.h:790
int32_t int32
Definition c.h:676
#define unlikely(x)
Definition c.h:494
uint32_t uint32
Definition c.h:680
#define OidIsValid(objectId)
Definition c.h:914
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
Oid collid
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition datum.c:271
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
Datum arg
Definition elog.c:1323
int errcode(int sqlerrcode)
Definition elog.c:875
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define PG_END_TRY(...)
Definition elog.h:399
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define PG_FINALLY(...)
Definition elog.h:391
#define ereport(elevel,...)
Definition elog.h:152
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition execMain.c:593
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
const TupleTableSlotOps TTSOpsHeapTuple
Definition execTuples.c:85
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
#define palloc_object(type)
Definition fe_memutils.h:89
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:1151
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition fmgr.c:1764
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition fmgr.c:139
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition fmgr.c:582
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition fmgr.h:710
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
char * format_type_be(Oid type_oid)
int maintenance_work_mem
Definition globals.c:135
int NewGUCNestLevel(void)
Definition guc.c:2142
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition guc.c:3248
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_USERSET
Definition guc.h:79
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition heaptuple.c:1254
@ HASH_FIND
Definition hsearch.h:108
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define dclist_container(type, membername, ptr)
Definition ilist.h:947
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition ilist.h:709
static uint32 dclist_count(const dclist_head *head)
Definition ilist.h:932
static void dclist_delete_from(dclist_head *head, dlist_node *node)
Definition ilist.h:763
#define dclist_foreach_modify(iter, lhead)
Definition ilist.h:973
#define funcname
IndexInfo * BuildIndexInfo(Relation index)
Definition index.c:2446
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition index.c:2748
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition indexam.c:698
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, IndexScanInstrumentation *instrument, int nkeys, int norderbys, uint32 flags)
Definition indexam.c:257
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
void index_endscan(IndexScanDesc scan)
Definition indexam.c:394
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition indexam.c:368
long val
Definition informix.c:689
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1813
int j
Definition isn.c:78
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
#define NoLock
Definition lockdefs.h:34
#define AccessShareLock
Definition lockdefs.h:36
#define RowShareLock
Definition lockdefs.h:37
#define RowExclusiveLock
Definition lockdefs.h:38
@ LockWaitBlock
Definition lockoptions.h:40
@ LockTupleKeyShare
Definition lockoptions.h:53
void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op, int *strategy, Oid *lefttype, Oid *righttype)
Definition lsyscache.c:140
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3215
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2577
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2309
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1577
Oid get_index_column_opclass(Oid index_oid, int attno)
Definition lsyscache.c:3865
Oid getBaseType(Oid typid)
Definition lsyscache.c:2829
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3674
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition lsyscache.c:1650
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
MemoryContext TopTransactionContext
Definition mcxt.c:172
void pfree(void *pointer)
Definition mcxt.c:1619
MemoryContext TopMemoryContext
Definition mcxt.c:167
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition memutils.h:170
#define SECURITY_NOFORCE_RLS
Definition miscadmin.h:323
#define SECURITY_LOCAL_USERID_CHANGE
Definition miscadmin.h:321
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:613
Oid GetUserId(void)
Definition miscinit.c:470
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:620
#define makeNode(_type_)
Definition nodes.h:159
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
@ COERCION_PATH_FUNC
@ COERCION_PATH_RELABELTYPE
#define ACL_USAGE
Definition parsenodes.h:84
#define FKCONSTR_MATCH_SIMPLE
@ RTE_RELATION
#define FKCONSTR_MATCH_PARTIAL
@ OBJECT_SCHEMA
@ OBJECT_TABLE
#define ACL_SELECT
Definition parsenodes.h:77
#define FKCONSTR_MATCH_FULL
NameData attname
FormData_pg_attribute * Form_pg_attribute
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation
#define INDEX_MAX_KEYS
void FindFKPeriodOpers(Oid opclass, Oid *containedbyoperoid, Oid *aggedcontainedbyoperoid, Oid *intersectoperoid)
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define plan(x)
Definition pg_regress.c:164
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition pgbench.c:77
#define sprintf
Definition port.h:263
#define snprintf
Definition port.h:261
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
static int fb(int x)
@ COERCION_IMPLICIT
Definition primnodes.h:737
tree ctl
Definition radixtree.h:1838
#define RelationGetForm(relation)
Definition rel.h:510
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetDescr(relation)
Definition rel.h:542
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationGetNamespace(relation)
Definition rel.h:557
int errtableconstraint(Relation rel, const char *conname)
Definition relcache.c:6136
static void ri_FastPathEndBatch(void *arg)
static bool recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys, int nkeys, TupleTableSlot *new_slot)
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool is_restrict, bool detectNewRows, int expect_OK)
#define RI_TRIGTYPE_INSERT
Definition ri_triggers.c:96
static Datum RI_FKey_check(TriggerData *trigdata)
#define RI_PLAN_SETNULL_ONUPDATE
Definition ri_triggers.c:85
#define RI_PLAN_CASCADE_ONUPDATE
Definition ri_triggers.c:80
#define RI_TRIGTYPE_DELETE
Definition ri_triggers.c:98
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, const Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Datum RI_FKey_setnull_del(PG_FUNCTION_ARGS)
static bool ri_fastpath_callback_registered
static pg_noreturn void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
static void quoteOneName(char *buffer, const char *name)
bool RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
#define RI_PLAN_LAST_ON_PK
Definition ri_triggers.c:77
#define RIAttType(rel, attnum)
Definition ri_triggers.c:93
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Datum RI_FKey_cascade_del(PG_FUNCTION_ARGS)
#define RI_KEYS_SOME_NULL
Definition ri_triggers.c:70
Datum RI_FKey_check_upd(PG_FUNCTION_ARGS)
static HTAB * ri_query_cache
#define MAX_QUOTED_REL_NAME_LEN
Definition ri_triggers.c:90
Datum RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
static int ri_FastPathFlushLoop(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Datum RI_FKey_restrict_del(PG_FUNCTION_ARGS)
#define RI_PLAN_RESTRICT
Definition ri_triggers.c:83
Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS)
static void ri_FastPathCheck(RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
static void quoteRelationName(char *buffer, Relation rel)
static void ri_FastPathBatchAdd(RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
static void build_index_scankeys(const RI_ConstraintInfo *riinfo, Relation idx_rel, Datum *pk_vals, char *pk_nulls, ScanKey skeys)
static bool ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap, bool *concurrently_updated)
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static HTAB * ri_fastpath_cache
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition ri_triggers.c:76
#define RIAttCollation(rel, attnum)
Definition ri_triggers.c:94
static dclist_head ri_constraint_cache_valid_list
static Oid get_ri_constraint_root(Oid constrOid)
Datum RI_FKey_check_ins(PG_FUNCTION_ARGS)
#define RI_KEYS_ALL_NULL
Definition ri_triggers.c:69
static HTAB * ri_compare_cache
static void ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo, Relation fk_rel, Relation idx_rel)
#define RI_KEYS_NONE_NULL
Definition ri_triggers.c:71
#define RI_FASTPATH_BATCH_SIZE
#define RI_INIT_QUERYHASHSIZE
Definition ri_triggers.c:67
static void ri_FastPathBatchFlush(RI_FastPathEntry *fpentry, Relation fk_rel, RI_ConstraintInfo *riinfo)
static bool ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel, IndexScanDesc scandesc, TupleTableSlot *slot, Snapshot snapshot, const RI_ConstraintInfo *riinfo, ScanKeyData *skey, int nkeys)
void AtEOXact_RI(bool isCommit)
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
#define RI_PLAN_CASCADE_ONDELETE
Definition ri_triggers.c:79
Datum RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
static RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition ri_triggers.c:86
Datum RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition ri_triggers.c:87
#define RI_PLAN_CHECK_LOOKUPPK
Definition ri_triggers.c:75
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
static int ri_FastPathFlushArray(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
#define RI_PLAN_SETNULL_ONDELETE
Definition ri_triggers.c:84
#define RI_INIT_CONSTRAINTHASHSIZE
Definition ri_triggers.c:66
static void ri_CheckPermissions(Relation query_rel)
bool RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
static RI_FastPathEntry * ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo, Relation fk_rel)
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
static void ri_FastPathTeardown(void)
#define MAX_QUOTED_NAME_LEN
Definition ri_triggers.c:89
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
static bool ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo)
#define RI_TRIGTYPE_UPDATE
Definition ri_triggers.c:97
static bool ri_fastpath_flushing
bool RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
int RI_FKey_trigger_type(Oid tgfoid)
Datum RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
Datum RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
static void ri_InitHashTables(void)
static void InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
static RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
#define RIAttName(rel, attnum)
Definition ri_triggers.c:92
#define RI_MAX_NUMKEYS
Definition ri_triggers.c:64
static HTAB * ri_constraint_cache
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Datum RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
#define RI_PLAN_NO_ACTION
Definition ri_triggers.c:81
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition rls.c:52
@ RLS_ENABLED
Definition rls.h:45
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition ruleutils.c:2486
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition scankey.c:32
@ ForwardScanDirection
Definition sdir.h:28
#define SK_SEARCHARRAY
Definition skey.h:120
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
#define SnapshotSelf
Definition snapmgr.h:32
#define InvalidSnapshot
Definition snapshot.h:119
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition spi.c:1949
uint64 SPI_processed
Definition spi.c:45
int SPI_freeplan(SPIPlanPtr plan)
Definition spi.c:1026
const char * SPI_result_code_string(int code)
Definition spi.c:1973
SPITupleTable * SPI_tuptable
Definition spi.c:46
int SPI_connect(void)
Definition spi.c:95
int SPI_result
Definition spi.c:47
int SPI_finish(void)
Definition spi.c:183
int SPI_execute_snapshot(SPIPlanPtr plan, const Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition spi.c:774
int SPI_keepplan(SPIPlanPtr plan)
Definition spi.c:977
SPIPlanPtr SPI_prepare(const char *src, int nargs, const Oid *argtypes)
Definition spi.c:861
#define SPI_OK_UPDATE
Definition spi.h:90
#define SPI_OK_DELETE
Definition spi.h:89
#define SPI_OK_FINISH
Definition spi.h:83
#define SPI_OK_SELECT
Definition spi.h:86
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
FmgrInfo eq_opr_finfo[RI_MAX_NUMKEYS]
AttrNumber index_attnos[RI_MAX_NUMKEYS]
RegProcedure regops[RI_MAX_NUMKEYS]
int strats[RI_MAX_NUMKEYS]
Oid subtypes[RI_MAX_NUMKEYS]
FmgrInfo cast_func_finfo[RI_MAX_NUMKEYS]
Oid fn_oid
Definition fmgr.h:59
Size keysize
Definition hsearch.h:69
bool amsearcharray
Definition amapi.h:265
Oid * ii_ExclusionOps
Definition execnodes.h:202
int ii_NumIndexKeyAttrs
Definition execnodes.h:183
List * ii_Expressions
Definition execnodes.h:192
Definition pg_list.h:54
RI_CompareKey key
dlist_node valid_link
int16 pk_attnums[RI_MAX_NUMKEYS]
Oid agged_period_contained_by_oper
int16 fk_attnums[RI_MAX_NUMKEYS]
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
int16 confdelsetcols[RI_MAX_NUMKEYS]
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
FastPathMeta * fpmeta
TupleTableSlot * fk_slot
TupleTableSlot * pk_slot
MemoryContext flush_cxt
HeapTuple batch[RI_FASTPATH_BATCH_SIZE]
RI_QueryKey key
int32 constr_queryno
const struct IndexAmRoutine * rd_indam
Definition rel.h:206
TupleDesc rd_att
Definition rel.h:112
Form_pg_index rd_index
Definition rel.h:192
Oid rd_id
Definition rel.h:113
Oid * rd_opfamily
Definition rel.h:207
Oid * rd_indcollation
Definition rel.h:217
Form_pg_class rd_rel
Definition rel.h:111
TupleDesc tupdesc
Definition spi.h:25
HeapTuple * vals
Definition spi.h:26
Relation tg_relation
Definition trigger.h:35
TriggerEvent tg_event
Definition trigger.h:34
TupleTableSlot * tg_trigslot
Definition trigger.h:39
TupleTableSlot * tg_newslot
Definition trigger.h:40
Trigger * tg_trigger
Definition trigger.h:38
bool * tts_isnull
Definition tuptable.h:133
ItemPointerData tts_tid
Definition tuptable.h:142
Datum * tts_values
Definition tuptable.h:131
dlist_node * cur
Definition ilist.h:200
Definition c.h:886
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition tableam.c:92
@ SO_NONE
Definition tableam.h:49
TM_Result
Definition tableam.h:95
@ TM_Ok
Definition tableam.h:100
@ TM_Deleted
Definition tableam.h:115
@ TM_Updated
Definition tableam.h:112
@ TM_SelfModified
Definition tableam.h:106
@ TM_Invisible
Definition tableam.h:103
static TM_Result table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, uint8 flags, TM_FailureData *tmfd)
Definition tableam.h:1646
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition tableam.h:299
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition tableam.h:1391
#define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS
Definition tableam.h:297
void RegisterAfterTriggerBatchCallback(AfterTriggerBatchCallback callback, void *arg)
Definition trigger.c:6838
bool AfterTriggerIsActive(void)
Definition trigger.c:6903
#define RI_TRIGGER_FK
Definition trigger.h:287
#define TRIGGER_FIRED_BY_DELETE(event)
Definition trigger.h:115
#define CALLED_AS_TRIGGER(fcinfo)
Definition trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition trigger.h:124
#define RI_TRIGGER_NONE
Definition trigger.h:288
#define TRIGGER_FIRED_AFTER(event)
Definition trigger.h:133
#define TRIGGER_FIRED_BY_INSERT(event)
Definition trigger.h:112
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition trigger.h:118
#define RI_TRIGGER_PK
Definition trigger.h:286
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition tuptable.h:504
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition tuptable.h:417
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition tuptable.h:467
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:403
const char * name
int GetCurrentTransactionNestLevel(void)
Definition xact.c:931
void CommandCounterIncrement(void)
Definition xact.c:1130
CommandId GetCurrentCommandId(bool used)
Definition xact.c:831
#define IsolationUsesXactSnapshot()
Definition xact.h:52