LCOV - code coverage report
Current view: top level - src/backend/utils/adt - ri_triggers.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 92.6 % 1170 1083
Test Date: 2026-05-09 09:16:28 Functions: 100.0 % 59 59
Legend: Lines:     hit not hit

            Line data    Source code
       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"
      35              : #include "catalog/pg_collation.h"
      36              : #include "catalog/pg_constraint.h"
      37              : #include "catalog/pg_namespace.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"
      44              : #include "parser/parse_relation.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              : 
     100              : typedef struct FastPathMeta FastPathMeta;
     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              :  */
     111              : typedef 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              : 
     143              :     Oid         conindid;
     144              :     bool        pk_is_partitioned;
     145              : 
     146              :     FastPathMeta *fpmeta;
     147              : } RI_ConstraintInfo;
     148              : 
     149              : typedef struct RI_CompareHashEntry RI_CompareHashEntry;
     150              : 
     151              : /* Fast-path metadata for RI checks on foreign key referencing tables */
     152              : typedef struct FastPathMeta
     153              : {
     154              :     FmgrInfo    eq_opr_finfo[RI_MAX_NUMKEYS];
     155              :     FmgrInfo    cast_func_finfo[RI_MAX_NUMKEYS];
     156              :     RegProcedure regops[RI_MAX_NUMKEYS];
     157              :     Oid         subtypes[RI_MAX_NUMKEYS];
     158              :     int         strats[RI_MAX_NUMKEYS];
     159              :     AttrNumber  index_attnos[RI_MAX_NUMKEYS];   /* index column positions */
     160              : } FastPathMeta;
     161              : 
     162              : /*
     163              :  * RI_QueryKey
     164              :  *
     165              :  * The key identifying a prepared SPI plan in our query hashtable
     166              :  */
     167              : typedef 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 */
     171              : } RI_QueryKey;
     172              : 
     173              : /*
     174              :  * RI_QueryHashEntry
     175              :  */
     176              : typedef struct RI_QueryHashEntry
     177              : {
     178              :     RI_QueryKey key;
     179              :     SPIPlanPtr  plan;
     180              : } RI_QueryHashEntry;
     181              : 
     182              : /*
     183              :  * RI_CompareKey
     184              :  *
     185              :  * The key identifying an entry showing how to compare two values
     186              :  */
     187              : typedef struct RI_CompareKey
     188              : {
     189              :     Oid         eq_opr;         /* the equality operator to apply */
     190              :     Oid         typeid;         /* the data type to apply it to */
     191              : } RI_CompareKey;
     192              : 
     193              : /*
     194              :  * RI_CompareHashEntry
     195              :  */
     196              : typedef struct RI_CompareHashEntry
     197              : {
     198              :     RI_CompareKey key;
     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 */
     202              : } RI_CompareHashEntry;
     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 the XactCallback/SubXactCallback NULL the static cache pointer
     232              :  * to prevent any subsequent access.
     233              :  */
     234              : typedef struct RI_FastPathEntry
     235              : {
     236              :     Oid         conoid;         /* hash key: pg_constraint OID */
     237              :     Oid         fk_relid;       /* for ri_FastPathEndBatch() */
     238              :     Relation    pk_rel;
     239              :     Relation    idx_rel;
     240              :     TupleTableSlot *pk_slot;
     241              :     TupleTableSlot *fk_slot;
     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              :      */
     250              :     HeapTuple   batch[RI_FASTPATH_BATCH_SIZE];
     251              :     int         batch_count;
     252              : } RI_FastPathEntry;
     253              : 
     254              : /*
     255              :  * Local data
     256              :  */
     257              : static HTAB *ri_constraint_cache = NULL;
     258              : static HTAB *ri_query_cache = NULL;
     259              : static HTAB *ri_compare_cache = NULL;
     260              : static dclist_head ri_constraint_cache_valid_list;
     261              : 
     262              : static HTAB *ri_fastpath_cache = NULL;
     263              : static bool ri_fastpath_callback_registered = false;
     264              : 
     265              : /*
     266              :  * Local function prototypes
     267              :  */
     268              : static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
     269              :                               TupleTableSlot *oldslot,
     270              :                               const RI_ConstraintInfo *riinfo);
     271              : static Datum ri_restrict(TriggerData *trigdata, bool is_no_action);
     272              : static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind);
     273              : static void quoteOneName(char *buffer, const char *name);
     274              : static void quoteRelationName(char *buffer, Relation rel);
     275              : static void ri_GenerateQual(StringInfo buf,
     276              :                             const char *sep,
     277              :                             const char *leftop, Oid leftoptype,
     278              :                             Oid opoid,
     279              :                             const char *rightop, Oid rightoptype);
     280              : static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
     281              : static int  ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot,
     282              :                          const RI_ConstraintInfo *riinfo, bool rel_is_pk);
     283              : static void ri_BuildQueryKey(RI_QueryKey *key,
     284              :                              const RI_ConstraintInfo *riinfo,
     285              :                              int32 constr_queryno);
     286              : static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
     287              :                          const RI_ConstraintInfo *riinfo, bool rel_is_pk);
     288              : static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
     289              :                                Datum lhs, Datum rhs);
     290              : 
     291              : static void ri_InitHashTables(void);
     292              : static void InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid,
     293              :                                               uint32 hashvalue);
     294              : static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key);
     295              : static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan);
     296              : static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
     297              : 
     298              : static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
     299              :                             int tgkind);
     300              : static RI_ConstraintInfo *ri_FetchConstraintInfo(Trigger *trigger,
     301              :                                                  Relation trig_rel, bool rel_is_pk);
     302              : static RI_ConstraintInfo *ri_LoadConstraintInfo(Oid constraintOid);
     303              : static Oid  get_ri_constraint_root(Oid constrOid);
     304              : static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
     305              :                                RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel);
     306              : static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo,
     307              :                             RI_QueryKey *qkey, SPIPlanPtr qplan,
     308              :                             Relation fk_rel, Relation pk_rel,
     309              :                             TupleTableSlot *oldslot, TupleTableSlot *newslot,
     310              :                             bool is_restrict,
     311              :                             bool detectNewRows, int expect_OK);
     312              : static void ri_FastPathCheck(RI_ConstraintInfo *riinfo,
     313              :                              Relation fk_rel, TupleTableSlot *newslot);
     314              : static void ri_FastPathBatchAdd(RI_ConstraintInfo *riinfo,
     315              :                                 Relation fk_rel, TupleTableSlot *newslot);
     316              : static void ri_FastPathBatchFlush(RI_FastPathEntry *fpentry, Relation fk_rel,
     317              :                                   RI_ConstraintInfo *riinfo);
     318              : static int  ri_FastPathFlushArray(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot,
     319              :                                   const RI_ConstraintInfo *riinfo, Relation fk_rel,
     320              :                                   Snapshot snapshot, IndexScanDesc scandesc);
     321              : static int  ri_FastPathFlushLoop(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot,
     322              :                                  const RI_ConstraintInfo *riinfo, Relation fk_rel,
     323              :                                  Snapshot snapshot, IndexScanDesc scandesc);
     324              : static bool ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel,
     325              :                                 IndexScanDesc scandesc, TupleTableSlot *slot,
     326              :                                 Snapshot snapshot, const RI_ConstraintInfo *riinfo,
     327              :                                 ScanKeyData *skey, int nkeys);
     328              : static bool ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap,
     329              :                            bool *concurrently_updated);
     330              : static bool ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo);
     331              : static void ri_CheckPermissions(Relation query_rel);
     332              : static bool recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys,
     333              :                                      int nkeys, TupleTableSlot *new_slot);
     334              : static void build_index_scankeys(const RI_ConstraintInfo *riinfo,
     335              :                                  Relation idx_rel, Datum *pk_vals,
     336              :                                  char *pk_nulls, ScanKey skeys);
     337              : static void ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo,
     338              :                                           Relation fk_rel, Relation idx_rel);
     339              : static void ri_ExtractValues(Relation rel, TupleTableSlot *slot,
     340              :                              const RI_ConstraintInfo *riinfo, bool rel_is_pk,
     341              :                              Datum *vals, char *nulls);
     342              : pg_noreturn static void ri_ReportViolation(const RI_ConstraintInfo *riinfo,
     343              :                                            Relation pk_rel, Relation fk_rel,
     344              :                                            TupleTableSlot *violatorslot, TupleDesc tupdesc,
     345              :                                            int queryno, bool is_restrict, bool partgone);
     346              : static RI_FastPathEntry *ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo,
     347              :                                              Relation fk_rel);
     348              : static void ri_FastPathEndBatch(void *arg);
     349              : static void ri_FastPathTeardown(void);
     350              : 
     351              : 
     352              : /*
     353              :  * RI_FKey_check -
     354              :  *
     355              :  * Check foreign key existence (combined for INSERT and UPDATE).
     356              :  */
     357              : static Datum
     358       604727 : RI_FKey_check(TriggerData *trigdata)
     359              : {
     360              :     RI_ConstraintInfo *riinfo;
     361              :     Relation    fk_rel;
     362              :     Relation    pk_rel;
     363              :     TupleTableSlot *newslot;
     364              :     RI_QueryKey qkey;
     365              :     SPIPlanPtr  qplan;
     366              : 
     367       604727 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     368              :                                     trigdata->tg_relation, false);
     369              : 
     370       604727 :     if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
     371          294 :         newslot = trigdata->tg_newslot;
     372              :     else
     373       604433 :         newslot = trigdata->tg_trigslot;
     374              : 
     375              :     /*
     376              :      * We should not even consider checking the row if it is no longer valid,
     377              :      * since it was either deleted (so the deferred check should be skipped)
     378              :      * or updated (in which case only the latest version of the row should be
     379              :      * checked).  Test its liveness according to SnapshotSelf.  We need pin
     380              :      * and lock on the buffer to call HeapTupleSatisfiesVisibility.  Caller
     381              :      * should be holding pin, but not lock.
     382              :      */
     383       604727 :     if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
     384           40 :         return PointerGetDatum(NULL);
     385              : 
     386       604687 :     fk_rel = trigdata->tg_relation;
     387              : 
     388       604687 :     switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
     389              :     {
     390           98 :         case RI_KEYS_ALL_NULL:
     391              : 
     392              :             /*
     393              :              * No further check needed - an all-NULL key passes every type of
     394              :              * foreign key constraint.
     395              :              */
     396           98 :             return PointerGetDatum(NULL);
     397              : 
     398          104 :         case RI_KEYS_SOME_NULL:
     399              : 
     400              :             /*
     401              :              * This is the only case that differs between the three kinds of
     402              :              * MATCH.
     403              :              */
     404          104 :             switch (riinfo->confmatchtype)
     405              :             {
     406           24 :                 case FKCONSTR_MATCH_FULL:
     407              : 
     408              :                     /*
     409              :                      * Not allowed - MATCH FULL says either all or none of the
     410              :                      * attributes can be NULLs
     411              :                      */
     412           24 :                     ereport(ERROR,
     413              :                             (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
     414              :                              errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
     415              :                                     RelationGetRelationName(fk_rel),
     416              :                                     NameStr(riinfo->conname)),
     417              :                              errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
     418              :                              errtableconstraint(fk_rel,
     419              :                                                 NameStr(riinfo->conname))));
     420              :                     return PointerGetDatum(NULL);
     421              : 
     422           80 :                 case FKCONSTR_MATCH_SIMPLE:
     423              : 
     424              :                     /*
     425              :                      * MATCH SIMPLE - if ANY column is null, the key passes
     426              :                      * the constraint.
     427              :                      */
     428           80 :                     return PointerGetDatum(NULL);
     429              : 
     430              : #ifdef NOT_USED
     431              :                 case FKCONSTR_MATCH_PARTIAL:
     432              : 
     433              :                     /*
     434              :                      * MATCH PARTIAL - all non-null columns must match. (not
     435              :                      * implemented, can be done by modifying the query below
     436              :                      * to only include non-null columns, or by writing a
     437              :                      * special version here)
     438              :                      */
     439              :                     break;
     440              : #endif
     441              :             }
     442              : 
     443              :         case RI_KEYS_NONE_NULL:
     444              : 
     445              :             /*
     446              :              * Have a full qualified key - continue below for all three kinds
     447              :              * of MATCH.
     448              :              */
     449       604485 :             break;
     450              :     }
     451              : 
     452              :     /*
     453              :      * Fast path: probe the PK unique index directly, bypassing SPI.
     454              :      *
     455              :      * For non-partitioned, non-temporal FKs, we can skip the SPI machinery
     456              :      * (plan cache, executor setup, etc.) and do a direct index scan + tuple
     457              :      * lock.  This is semantically equivalent to the SPI path below but avoids
     458              :      * the per-row executor overhead.
     459              :      *
     460              :      * ri_FastPathBatchAdd() and ri_FastPathCheck() report the violation
     461              :      * themselves if no matching PK row is found, so they only return on
     462              :      * success.
     463              :      */
     464       604485 :     if (ri_fastpath_is_applicable(riinfo))
     465              :     {
     466       603695 :         if (AfterTriggerIsActive())
     467              :         {
     468              :             /* Batched path: buffer and probe in groups */
     469       603651 :             ri_FastPathBatchAdd(riinfo, fk_rel, newslot);
     470              :         }
     471              :         else
     472              :         {
     473              :             /* ALTER TABLE validation: per-row, no cache */
     474           44 :             ri_FastPathCheck(riinfo, fk_rel, newslot);
     475              :         }
     476       603691 :         return PointerGetDatum(NULL);
     477              :     }
     478              : 
     479          790 :     SPI_connect();
     480              : 
     481              :     /*
     482              :      * pk_rel is opened in RowShareLock mode since that's what our eventual
     483              :      * SELECT FOR KEY SHARE will get on it.
     484              :      */
     485          790 :     pk_rel = table_open(riinfo->pk_relid, RowShareLock);
     486              : 
     487              :     /* Fetch or prepare a saved plan for the real check */
     488          790 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK);
     489              : 
     490          790 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     491              :     {
     492              :         StringInfoData querybuf;
     493              :         char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
     494              :         char        attname[MAX_QUOTED_NAME_LEN];
     495              :         char        paramname[16];
     496              :         const char *querysep;
     497              :         Oid         queryoids[RI_MAX_NUMKEYS];
     498              :         const char *pk_only;
     499              : 
     500              :         /* ----------
     501              :          * The query string built is
     502              :          *  SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
     503              :          *         FOR KEY SHARE OF x
     504              :          * The type id's for the $ parameters are those of the
     505              :          * corresponding FK attributes.
     506              :          *
     507              :          * But for temporal FKs we need to make sure
     508              :          * the FK's range is completely covered.
     509              :          * So we use this query instead:
     510              :          *  SELECT 1
     511              :          *  FROM    (
     512              :          *      SELECT pkperiodatt AS r
     513              :          *      FROM   [ONLY] pktable x
     514              :          *      WHERE  pkatt1 = $1 [AND ...]
     515              :          *      AND    pkperiodatt && $n
     516              :          *      FOR KEY SHARE OF x
     517              :          *  ) x1
     518              :          *  HAVING $n <@ range_agg(x1.r)
     519              :          * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
     520              :          * we can make this a bit simpler.
     521              :          * ----------
     522              :          */
     523          366 :         initStringInfo(&querybuf);
     524          732 :         pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     525          366 :             "" : "ONLY ";
     526          366 :         quoteRelationName(pkrelname, pk_rel);
     527          366 :         if (riinfo->hasperiod)
     528              :         {
     529           67 :             quoteOneName(attname,
     530           67 :                          RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
     531              : 
     532           67 :             appendStringInfo(&querybuf,
     533              :                              "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
     534              :                              attname, pk_only, pkrelname);
     535              :         }
     536              :         else
     537              :         {
     538          299 :             appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     539              :                              pk_only, pkrelname);
     540              :         }
     541          366 :         querysep = "WHERE";
     542          815 :         for (int i = 0; i < riinfo->nkeys; i++)
     543              :         {
     544          449 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     545          449 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     546              : 
     547          449 :             quoteOneName(attname,
     548          449 :                          RIAttName(pk_rel, riinfo->pk_attnums[i]));
     549          449 :             sprintf(paramname, "$%d", i + 1);
     550          449 :             ri_GenerateQual(&querybuf, querysep,
     551              :                             attname, pk_type,
     552              :                             riinfo->pf_eq_oprs[i],
     553              :                             paramname, fk_type);
     554          449 :             querysep = "AND";
     555          449 :             queryoids[i] = fk_type;
     556              :         }
     557          366 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
     558          366 :         if (riinfo->hasperiod)
     559              :         {
     560           67 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
     561              : 
     562           67 :             appendStringInfoString(&querybuf, ") x1 HAVING ");
     563           67 :             sprintf(paramname, "$%d", riinfo->nkeys);
     564           67 :             ri_GenerateQual(&querybuf, "",
     565              :                             paramname, fk_type,
     566              :                             riinfo->agged_period_contained_by_oper,
     567              :                             "pg_catalog.range_agg", ANYMULTIRANGEOID);
     568           67 :             appendStringInfoString(&querybuf, "(x1.r)");
     569              :         }
     570              : 
     571              :         /* Prepare and save the plan */
     572          366 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     573              :                              &qkey, fk_rel, pk_rel);
     574              :     }
     575              : 
     576              :     /*
     577              :      * Now check that foreign key exists in PK table
     578              :      *
     579              :      * XXX detectNewRows must be true when a partitioned table is on the
     580              :      * referenced side.  The reason is that our snapshot must be fresh in
     581              :      * order for the hack in find_inheritance_children() to work.
     582              :      */
     583          790 :     ri_PerformCheck(riinfo, &qkey, qplan,
     584              :                     fk_rel, pk_rel,
     585              :                     NULL, newslot,
     586              :                     false,
     587          790 :                     pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
     588              :                     SPI_OK_SELECT);
     589              : 
     590          650 :     if (SPI_finish() != SPI_OK_FINISH)
     591            0 :         elog(ERROR, "SPI_finish failed");
     592              : 
     593          650 :     table_close(pk_rel, RowShareLock);
     594              : 
     595          650 :     return PointerGetDatum(NULL);
     596              : }
     597              : 
     598              : 
     599              : /*
     600              :  * RI_FKey_check_ins -
     601              :  *
     602              :  * Check foreign key existence at insert event on FK table.
     603              :  */
     604              : Datum
     605       604433 : RI_FKey_check_ins(PG_FUNCTION_ARGS)
     606              : {
     607              :     /* Check that this is a valid trigger call on the right time and event. */
     608       604433 :     ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
     609              : 
     610              :     /* Share code with UPDATE case. */
     611       604433 :     return RI_FKey_check((TriggerData *) fcinfo->context);
     612              : }
     613              : 
     614              : 
     615              : /*
     616              :  * RI_FKey_check_upd -
     617              :  *
     618              :  * Check foreign key existence at update event on FK table.
     619              :  */
     620              : Datum
     621          294 : RI_FKey_check_upd(PG_FUNCTION_ARGS)
     622              : {
     623              :     /* Check that this is a valid trigger call on the right time and event. */
     624          294 :     ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
     625              : 
     626              :     /* Share code with INSERT case. */
     627          294 :     return RI_FKey_check((TriggerData *) fcinfo->context);
     628              : }
     629              : 
     630              : 
     631              : /*
     632              :  * ri_Check_Pk_Match
     633              :  *
     634              :  * Check to see if another PK row has been created that provides the same
     635              :  * key values as the "oldslot" that's been modified or deleted in our trigger
     636              :  * event.  Returns true if a match is found in the PK table.
     637              :  *
     638              :  * We assume the caller checked that the oldslot contains no NULL key values,
     639              :  * since otherwise a match is impossible.
     640              :  */
     641              : static bool
     642          523 : ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
     643              :                   TupleTableSlot *oldslot,
     644              :                   const RI_ConstraintInfo *riinfo)
     645              : {
     646              :     SPIPlanPtr  qplan;
     647              :     RI_QueryKey qkey;
     648              :     bool        result;
     649              : 
     650              :     /* Only called for non-null rows */
     651              :     Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
     652              : 
     653          523 :     SPI_connect();
     654              : 
     655              :     /*
     656              :      * Fetch or prepare a saved plan for checking PK table with values coming
     657              :      * from a PK row
     658              :      */
     659          523 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK_FROM_PK);
     660              : 
     661          523 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     662              :     {
     663              :         StringInfoData querybuf;
     664              :         char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
     665              :         char        attname[MAX_QUOTED_NAME_LEN];
     666              :         char        paramname[16];
     667              :         const char *querysep;
     668              :         const char *pk_only;
     669              :         Oid         queryoids[RI_MAX_NUMKEYS];
     670              : 
     671              :         /* ----------
     672              :          * The query string built is
     673              :          *  SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
     674              :          *         FOR KEY SHARE OF x
     675              :          * The type id's for the $ parameters are those of the
     676              :          * PK attributes themselves.
     677              :          *
     678              :          * But for temporal FKs we need to make sure
     679              :          * the old PK's range is completely covered.
     680              :          * So we use this query instead:
     681              :          *  SELECT 1
     682              :          *  FROM    (
     683              :          *    SELECT pkperiodatt AS r
     684              :          *    FROM   [ONLY] pktable x
     685              :          *    WHERE  pkatt1 = $1 [AND ...]
     686              :          *    AND    pkperiodatt && $n
     687              :          *    FOR KEY SHARE OF x
     688              :          *  ) x1
     689              :          *  HAVING $n <@ range_agg(x1.r)
     690              :          * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
     691              :          * we can make this a bit simpler.
     692              :          * ----------
     693              :          */
     694          258 :         initStringInfo(&querybuf);
     695          516 :         pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     696          258 :             "" : "ONLY ";
     697          258 :         quoteRelationName(pkrelname, pk_rel);
     698          258 :         if (riinfo->hasperiod)
     699              :         {
     700            0 :             quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
     701              : 
     702            0 :             appendStringInfo(&querybuf,
     703              :                              "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
     704              :                              attname, pk_only, pkrelname);
     705              :         }
     706              :         else
     707              :         {
     708          258 :             appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     709              :                              pk_only, pkrelname);
     710              :         }
     711          258 :         querysep = "WHERE";
     712          600 :         for (int i = 0; i < riinfo->nkeys; i++)
     713              :         {
     714          342 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     715              : 
     716          342 :             quoteOneName(attname,
     717          342 :                          RIAttName(pk_rel, riinfo->pk_attnums[i]));
     718          342 :             sprintf(paramname, "$%d", i + 1);
     719          342 :             ri_GenerateQual(&querybuf, querysep,
     720              :                             attname, pk_type,
     721          342 :                             riinfo->pp_eq_oprs[i],
     722              :                             paramname, pk_type);
     723          342 :             querysep = "AND";
     724          342 :             queryoids[i] = pk_type;
     725              :         }
     726          258 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
     727          258 :         if (riinfo->hasperiod)
     728              :         {
     729            0 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
     730              : 
     731            0 :             appendStringInfoString(&querybuf, ") x1 HAVING ");
     732            0 :             sprintf(paramname, "$%d", riinfo->nkeys);
     733            0 :             ri_GenerateQual(&querybuf, "",
     734              :                             paramname, fk_type,
     735            0 :                             riinfo->agged_period_contained_by_oper,
     736              :                             "pg_catalog.range_agg", ANYMULTIRANGEOID);
     737            0 :             appendStringInfoString(&querybuf, "(x1.r)");
     738              :         }
     739              : 
     740              :         /* Prepare and save the plan */
     741          258 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     742              :                              &qkey, fk_rel, pk_rel);
     743              :     }
     744              : 
     745              :     /*
     746              :      * We have a plan now. Run it.
     747              :      */
     748          523 :     result = ri_PerformCheck(riinfo, &qkey, qplan,
     749              :                              fk_rel, pk_rel,
     750              :                              oldslot, NULL,
     751              :                              false,
     752              :                              true,  /* treat like update */
     753              :                              SPI_OK_SELECT);
     754              : 
     755          523 :     if (SPI_finish() != SPI_OK_FINISH)
     756            0 :         elog(ERROR, "SPI_finish failed");
     757              : 
     758          523 :     return result;
     759              : }
     760              : 
     761              : 
     762              : /*
     763              :  * RI_FKey_noaction_del -
     764              :  *
     765              :  * Give an error and roll back the current transaction if the
     766              :  * delete has resulted in a violation of the given referential
     767              :  * integrity constraint.
     768              :  */
     769              : Datum
     770          313 : RI_FKey_noaction_del(PG_FUNCTION_ARGS)
     771              : {
     772              :     /* Check that this is a valid trigger call on the right time and event. */
     773          313 :     ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
     774              : 
     775              :     /* Share code with RESTRICT/UPDATE cases. */
     776          313 :     return ri_restrict((TriggerData *) fcinfo->context, true);
     777              : }
     778              : 
     779              : /*
     780              :  * RI_FKey_restrict_del -
     781              :  *
     782              :  * Restrict delete from PK table to rows unreferenced by foreign key.
     783              :  *
     784              :  * The SQL standard intends that this referential action occur exactly when
     785              :  * the delete is performed, rather than after.  This appears to be
     786              :  * the only difference between "NO ACTION" and "RESTRICT".  In Postgres
     787              :  * we still implement this as an AFTER trigger, but it's non-deferrable.
     788              :  */
     789              : Datum
     790            8 : RI_FKey_restrict_del(PG_FUNCTION_ARGS)
     791              : {
     792              :     /* Check that this is a valid trigger call on the right time and event. */
     793            8 :     ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
     794              : 
     795              :     /* Share code with NO ACTION/UPDATE cases. */
     796            8 :     return ri_restrict((TriggerData *) fcinfo->context, false);
     797              : }
     798              : 
     799              : /*
     800              :  * RI_FKey_noaction_upd -
     801              :  *
     802              :  * Give an error and roll back the current transaction if the
     803              :  * update has resulted in a violation of the given referential
     804              :  * integrity constraint.
     805              :  */
     806              : Datum
     807          356 : RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
     808              : {
     809              :     /* Check that this is a valid trigger call on the right time and event. */
     810          356 :     ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
     811              : 
     812              :     /* Share code with RESTRICT/DELETE cases. */
     813          356 :     return ri_restrict((TriggerData *) fcinfo->context, true);
     814              : }
     815              : 
     816              : /*
     817              :  * RI_FKey_restrict_upd -
     818              :  *
     819              :  * Restrict update of PK to rows unreferenced by foreign key.
     820              :  *
     821              :  * The SQL standard intends that this referential action occur exactly when
     822              :  * the update is performed, rather than after.  This appears to be
     823              :  * the only difference between "NO ACTION" and "RESTRICT".  In Postgres
     824              :  * we still implement this as an AFTER trigger, but it's non-deferrable.
     825              :  */
     826              : Datum
     827           20 : RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
     828              : {
     829              :     /* Check that this is a valid trigger call on the right time and event. */
     830           20 :     ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
     831              : 
     832              :     /* Share code with NO ACTION/DELETE cases. */
     833           20 :     return ri_restrict((TriggerData *) fcinfo->context, false);
     834              : }
     835              : 
     836              : /*
     837              :  * ri_restrict -
     838              :  *
     839              :  * Common code for ON DELETE RESTRICT, ON DELETE NO ACTION,
     840              :  * ON UPDATE RESTRICT, and ON UPDATE NO ACTION.
     841              :  */
     842              : static Datum
     843          785 : ri_restrict(TriggerData *trigdata, bool is_no_action)
     844              : {
     845              :     const RI_ConstraintInfo *riinfo;
     846              :     Relation    fk_rel;
     847              :     Relation    pk_rel;
     848              :     TupleTableSlot *oldslot;
     849              :     RI_QueryKey qkey;
     850              :     SPIPlanPtr  qplan;
     851              : 
     852          785 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     853              :                                     trigdata->tg_relation, true);
     854              : 
     855              :     /*
     856              :      * Get the relation descriptors of the FK and PK tables and the old tuple.
     857              :      *
     858              :      * fk_rel is opened in RowShareLock mode since that's what our eventual
     859              :      * SELECT FOR KEY SHARE will get on it.
     860              :      */
     861          785 :     fk_rel = table_open(riinfo->fk_relid, RowShareLock);
     862          785 :     pk_rel = trigdata->tg_relation;
     863          785 :     oldslot = trigdata->tg_trigslot;
     864              : 
     865              :     /*
     866              :      * If another PK row now exists providing the old key values, we should
     867              :      * not do anything.  However, this check should only be made in the NO
     868              :      * ACTION case; in RESTRICT cases we don't wish to allow another row to be
     869              :      * substituted.
     870              :      *
     871              :      * If the foreign key has PERIOD, we incorporate looking for replacement
     872              :      * rows in the main SQL query below, so we needn't do it here.
     873              :      */
     874         1308 :     if (is_no_action && !riinfo->hasperiod &&
     875          523 :         ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
     876              :     {
     877           38 :         table_close(fk_rel, RowShareLock);
     878           38 :         return PointerGetDatum(NULL);
     879              :     }
     880              : 
     881          747 :     SPI_connect();
     882              : 
     883              :     /*
     884              :      * Fetch or prepare a saved plan for the restrict lookup (it's the same
     885              :      * query for delete and update cases)
     886              :      */
     887          747 :     ri_BuildQueryKey(&qkey, riinfo, is_no_action ? RI_PLAN_NO_ACTION : RI_PLAN_RESTRICT);
     888              : 
     889          747 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     890              :     {
     891              :         StringInfoData querybuf;
     892              :         char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
     893              :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
     894              :         char        attname[MAX_QUOTED_NAME_LEN];
     895              :         char        periodattname[MAX_QUOTED_NAME_LEN];
     896              :         char        paramname[16];
     897              :         const char *querysep;
     898              :         Oid         queryoids[RI_MAX_NUMKEYS];
     899              :         const char *fk_only;
     900              : 
     901              :         /* ----------
     902              :          * The query string built is
     903              :          *  SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
     904              :          *         FOR KEY SHARE OF x
     905              :          * The type id's for the $ parameters are those of the
     906              :          * corresponding PK attributes.
     907              :          * ----------
     908              :          */
     909          318 :         initStringInfo(&querybuf);
     910          636 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     911          318 :             "" : "ONLY ";
     912          318 :         quoteRelationName(fkrelname, fk_rel);
     913          318 :         appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     914              :                          fk_only, fkrelname);
     915          318 :         querysep = "WHERE";
     916          811 :         for (int i = 0; i < riinfo->nkeys; i++)
     917              :         {
     918          493 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     919          493 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     920              : 
     921          493 :             quoteOneName(attname,
     922          493 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
     923          493 :             sprintf(paramname, "$%d", i + 1);
     924          493 :             ri_GenerateQual(&querybuf, querysep,
     925              :                             paramname, pk_type,
     926          493 :                             riinfo->pf_eq_oprs[i],
     927              :                             attname, fk_type);
     928          493 :             querysep = "AND";
     929          493 :             queryoids[i] = pk_type;
     930              :         }
     931              : 
     932              :         /*----------
     933              :          * For temporal foreign keys, a reference could still be valid if the
     934              :          * referenced range didn't change too much.  Also if a referencing
     935              :          * range extends past the current PK row, we don't want to check that
     936              :          * part: some other PK row should fulfill it.  We only want to check
     937              :          * the part matching the PK record we've changed.  Therefore to find
     938              :          * invalid records we do this:
     939              :          *
     940              :          * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
     941              :          * -- begin temporal
     942              :          * AND $n && x.fkperiod
     943              :          * AND NOT coalesce((x.fkperiod * $n) <@
     944              :          *  (SELECT range_agg(r)
     945              :          *   FROM (SELECT y.pkperiod r
     946              :          *         FROM [ONLY] <pktable> y
     947              :          *         WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
     948              :          *         FOR KEY SHARE OF y) y2), false)
     949              :          * -- end temporal
     950              :          * FOR KEY SHARE OF x
     951              :          *
     952              :          * We need the coalesce in case the first subquery returns no rows.
     953              :          * We need the second subquery because FOR KEY SHARE doesn't support
     954              :          * aggregate queries.
     955              :          */
     956          318 :         if (riinfo->hasperiod && is_no_action)
     957              :         {
     958           91 :             Oid         pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
     959           91 :             Oid         fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
     960              :             StringInfoData intersectbuf;
     961              :             StringInfoData replacementsbuf;
     962          182 :             char       *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     963           91 :                 "" : "ONLY ";
     964              : 
     965           91 :             quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
     966           91 :             sprintf(paramname, "$%d", riinfo->nkeys);
     967              : 
     968           91 :             appendStringInfoString(&querybuf, " AND NOT coalesce(");
     969              : 
     970              :             /* Intersect the fk with the old pk range */
     971           91 :             initStringInfo(&intersectbuf);
     972           91 :             appendStringInfoChar(&intersectbuf, '(');
     973           91 :             ri_GenerateQual(&intersectbuf, "",
     974              :                             attname, fk_period_type,
     975           91 :                             riinfo->period_intersect_oper,
     976              :                             paramname, pk_period_type);
     977           91 :             appendStringInfoChar(&intersectbuf, ')');
     978              : 
     979              :             /* Find the remaining history */
     980           91 :             initStringInfo(&replacementsbuf);
     981           91 :             appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
     982              : 
     983           91 :             quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
     984           91 :             quoteRelationName(pkrelname, pk_rel);
     985           91 :             appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
     986              :                              periodattname, pk_only, pkrelname);
     987              : 
     988              :             /* Restrict pk rows to what matches */
     989           91 :             querysep = "WHERE";
     990          273 :             for (int i = 0; i < riinfo->nkeys; i++)
     991              :             {
     992          182 :                 Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     993              : 
     994          182 :                 quoteOneName(attname,
     995          182 :                              RIAttName(pk_rel, riinfo->pk_attnums[i]));
     996          182 :                 sprintf(paramname, "$%d", i + 1);
     997          182 :                 ri_GenerateQual(&replacementsbuf, querysep,
     998              :                                 paramname, pk_type,
     999          182 :                                 riinfo->pp_eq_oprs[i],
    1000              :                                 attname, pk_type);
    1001          182 :                 querysep = "AND";
    1002          182 :                 queryoids[i] = pk_type;
    1003              :             }
    1004           91 :             appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
    1005              : 
    1006           91 :             ri_GenerateQual(&querybuf, "",
    1007           91 :                             intersectbuf.data, fk_period_type,
    1008           91 :                             riinfo->agged_period_contained_by_oper,
    1009           91 :                             replacementsbuf.data, ANYMULTIRANGEOID);
    1010              :             /* end of coalesce: */
    1011           91 :             appendStringInfoString(&querybuf, ", false)");
    1012              :         }
    1013              : 
    1014          318 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
    1015              : 
    1016              :         /* Prepare and save the plan */
    1017          318 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
    1018              :                              &qkey, fk_rel, pk_rel);
    1019              :     }
    1020              : 
    1021              :     /*
    1022              :      * We have a plan now. Run it to check for existing references.
    1023              :      */
    1024          747 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1025              :                     fk_rel, pk_rel,
    1026              :                     oldslot, NULL,
    1027              :                     !is_no_action,
    1028              :                     true,       /* must detect new rows */
    1029          747 :                     SPI_OK_SELECT);
    1030              : 
    1031          417 :     if (SPI_finish() != SPI_OK_FINISH)
    1032            0 :         elog(ERROR, "SPI_finish failed");
    1033              : 
    1034          417 :     table_close(fk_rel, RowShareLock);
    1035              : 
    1036          417 :     return PointerGetDatum(NULL);
    1037              : }
    1038              : 
    1039              : 
    1040              : /*
    1041              :  * RI_FKey_cascade_del -
    1042              :  *
    1043              :  * Cascaded delete foreign key references at delete event on PK table.
    1044              :  */
    1045              : Datum
    1046           98 : RI_FKey_cascade_del(PG_FUNCTION_ARGS)
    1047              : {
    1048           98 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
    1049              :     const RI_ConstraintInfo *riinfo;
    1050              :     Relation    fk_rel;
    1051              :     Relation    pk_rel;
    1052              :     TupleTableSlot *oldslot;
    1053              :     RI_QueryKey qkey;
    1054              :     SPIPlanPtr  qplan;
    1055              : 
    1056              :     /* Check that this is a valid trigger call on the right time and event. */
    1057           98 :     ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
    1058              : 
    1059           98 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
    1060              :                                     trigdata->tg_relation, true);
    1061              : 
    1062              :     /*
    1063              :      * Get the relation descriptors of the FK and PK tables and the old tuple.
    1064              :      *
    1065              :      * fk_rel is opened in RowExclusiveLock mode since that's what our
    1066              :      * eventual DELETE will get on it.
    1067              :      */
    1068           98 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
    1069           98 :     pk_rel = trigdata->tg_relation;
    1070           98 :     oldslot = trigdata->tg_trigslot;
    1071              : 
    1072           98 :     SPI_connect();
    1073              : 
    1074              :     /* Fetch or prepare a saved plan for the cascaded delete */
    1075           98 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONDELETE);
    1076              : 
    1077           98 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
    1078              :     {
    1079              :         StringInfoData querybuf;
    1080              :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1081              :         char        attname[MAX_QUOTED_NAME_LEN];
    1082              :         char        paramname[16];
    1083              :         const char *querysep;
    1084              :         Oid         queryoids[RI_MAX_NUMKEYS];
    1085              :         const char *fk_only;
    1086              : 
    1087              :         /* ----------
    1088              :          * The query string built is
    1089              :          *  DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
    1090              :          * The type id's for the $ parameters are those of the
    1091              :          * corresponding PK attributes.
    1092              :          * ----------
    1093              :          */
    1094           58 :         initStringInfo(&querybuf);
    1095          116 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1096           58 :             "" : "ONLY ";
    1097           58 :         quoteRelationName(fkrelname, fk_rel);
    1098           58 :         appendStringInfo(&querybuf, "DELETE FROM %s%s",
    1099              :                          fk_only, fkrelname);
    1100           58 :         querysep = "WHERE";
    1101          128 :         for (int i = 0; i < riinfo->nkeys; i++)
    1102              :         {
    1103           70 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1104           70 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1105              : 
    1106           70 :             quoteOneName(attname,
    1107           70 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1108           70 :             sprintf(paramname, "$%d", i + 1);
    1109           70 :             ri_GenerateQual(&querybuf, querysep,
    1110              :                             paramname, pk_type,
    1111           70 :                             riinfo->pf_eq_oprs[i],
    1112              :                             attname, fk_type);
    1113           70 :             querysep = "AND";
    1114           70 :             queryoids[i] = pk_type;
    1115              :         }
    1116              : 
    1117              :         /* Prepare and save the plan */
    1118           58 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
    1119              :                              &qkey, fk_rel, pk_rel);
    1120              :     }
    1121              : 
    1122              :     /*
    1123              :      * We have a plan now. Build up the arguments from the key values in the
    1124              :      * deleted PK tuple and delete the referencing rows
    1125              :      */
    1126           98 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1127              :                     fk_rel, pk_rel,
    1128              :                     oldslot, NULL,
    1129              :                     false,
    1130              :                     true,       /* must detect new rows */
    1131              :                     SPI_OK_DELETE);
    1132              : 
    1133           97 :     if (SPI_finish() != SPI_OK_FINISH)
    1134            0 :         elog(ERROR, "SPI_finish failed");
    1135              : 
    1136           97 :     table_close(fk_rel, RowExclusiveLock);
    1137              : 
    1138           97 :     return PointerGetDatum(NULL);
    1139              : }
    1140              : 
    1141              : 
    1142              : /*
    1143              :  * RI_FKey_cascade_upd -
    1144              :  *
    1145              :  * Cascaded update foreign key references at update event on PK table.
    1146              :  */
    1147              : Datum
    1148          144 : RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
    1149              : {
    1150          144 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
    1151              :     const RI_ConstraintInfo *riinfo;
    1152              :     Relation    fk_rel;
    1153              :     Relation    pk_rel;
    1154              :     TupleTableSlot *newslot;
    1155              :     TupleTableSlot *oldslot;
    1156              :     RI_QueryKey qkey;
    1157              :     SPIPlanPtr  qplan;
    1158              : 
    1159              :     /* Check that this is a valid trigger call on the right time and event. */
    1160          144 :     ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
    1161              : 
    1162          144 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
    1163              :                                     trigdata->tg_relation, true);
    1164              : 
    1165              :     /*
    1166              :      * Get the relation descriptors of the FK and PK tables and the new and
    1167              :      * old tuple.
    1168              :      *
    1169              :      * fk_rel is opened in RowExclusiveLock mode since that's what our
    1170              :      * eventual UPDATE will get on it.
    1171              :      */
    1172          144 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
    1173          144 :     pk_rel = trigdata->tg_relation;
    1174          144 :     newslot = trigdata->tg_newslot;
    1175          144 :     oldslot = trigdata->tg_trigslot;
    1176              : 
    1177          144 :     SPI_connect();
    1178              : 
    1179              :     /* Fetch or prepare a saved plan for the cascaded update */
    1180          144 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONUPDATE);
    1181              : 
    1182          144 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
    1183              :     {
    1184              :         StringInfoData querybuf;
    1185              :         StringInfoData qualbuf;
    1186              :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1187              :         char        attname[MAX_QUOTED_NAME_LEN];
    1188              :         char        paramname[16];
    1189              :         const char *querysep;
    1190              :         const char *qualsep;
    1191              :         Oid         queryoids[RI_MAX_NUMKEYS * 2];
    1192              :         const char *fk_only;
    1193              : 
    1194              :         /* ----------
    1195              :          * The query string built is
    1196              :          *  UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
    1197              :          *          WHERE $n = fkatt1 [AND ...]
    1198              :          * The type id's for the $ parameters are those of the
    1199              :          * corresponding PK attributes.  Note that we are assuming
    1200              :          * there is an assignment cast from the PK to the FK type;
    1201              :          * else the parser will fail.
    1202              :          * ----------
    1203              :          */
    1204           85 :         initStringInfo(&querybuf);
    1205           85 :         initStringInfo(&qualbuf);
    1206          170 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1207           85 :             "" : "ONLY ";
    1208           85 :         quoteRelationName(fkrelname, fk_rel);
    1209           85 :         appendStringInfo(&querybuf, "UPDATE %s%s SET",
    1210              :                          fk_only, fkrelname);
    1211           85 :         querysep = "";
    1212           85 :         qualsep = "WHERE";
    1213          188 :         for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
    1214              :         {
    1215          103 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1216          103 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1217              : 
    1218          103 :             quoteOneName(attname,
    1219          103 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1220          103 :             appendStringInfo(&querybuf,
    1221              :                              "%s %s = $%d",
    1222              :                              querysep, attname, i + 1);
    1223          103 :             sprintf(paramname, "$%d", j + 1);
    1224          103 :             ri_GenerateQual(&qualbuf, qualsep,
    1225              :                             paramname, pk_type,
    1226          103 :                             riinfo->pf_eq_oprs[i],
    1227              :                             attname, fk_type);
    1228          103 :             querysep = ",";
    1229          103 :             qualsep = "AND";
    1230          103 :             queryoids[i] = pk_type;
    1231          103 :             queryoids[j] = pk_type;
    1232              :         }
    1233           85 :         appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
    1234              : 
    1235              :         /* Prepare and save the plan */
    1236           85 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
    1237              :                              &qkey, fk_rel, pk_rel);
    1238              :     }
    1239              : 
    1240              :     /*
    1241              :      * We have a plan now. Run it to update the existing references.
    1242              :      */
    1243          144 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1244              :                     fk_rel, pk_rel,
    1245              :                     oldslot, newslot,
    1246              :                     false,
    1247              :                     true,       /* must detect new rows */
    1248              :                     SPI_OK_UPDATE);
    1249              : 
    1250          144 :     if (SPI_finish() != SPI_OK_FINISH)
    1251            0 :         elog(ERROR, "SPI_finish failed");
    1252              : 
    1253          144 :     table_close(fk_rel, RowExclusiveLock);
    1254              : 
    1255          144 :     return PointerGetDatum(NULL);
    1256              : }
    1257              : 
    1258              : 
    1259              : /*
    1260              :  * RI_FKey_setnull_del -
    1261              :  *
    1262              :  * Set foreign key references to NULL values at delete event on PK table.
    1263              :  */
    1264              : Datum
    1265           65 : RI_FKey_setnull_del(PG_FUNCTION_ARGS)
    1266              : {
    1267              :     /* Check that this is a valid trigger call on the right time and event. */
    1268           65 :     ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
    1269              : 
    1270              :     /* Share code with UPDATE case */
    1271           65 :     return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
    1272              : }
    1273              : 
    1274              : /*
    1275              :  * RI_FKey_setnull_upd -
    1276              :  *
    1277              :  * Set foreign key references to NULL at update event on PK table.
    1278              :  */
    1279              : Datum
    1280           20 : RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
    1281              : {
    1282              :     /* Check that this is a valid trigger call on the right time and event. */
    1283           20 :     ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
    1284              : 
    1285              :     /* Share code with DELETE case */
    1286           20 :     return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
    1287              : }
    1288              : 
    1289              : /*
    1290              :  * RI_FKey_setdefault_del -
    1291              :  *
    1292              :  * Set foreign key references to defaults at delete event on PK table.
    1293              :  */
    1294              : Datum
    1295           56 : RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
    1296              : {
    1297              :     /* Check that this is a valid trigger call on the right time and event. */
    1298           56 :     ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
    1299              : 
    1300              :     /* Share code with UPDATE case */
    1301           56 :     return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
    1302              : }
    1303              : 
    1304              : /*
    1305              :  * RI_FKey_setdefault_upd -
    1306              :  *
    1307              :  * Set foreign key references to defaults at update event on PK table.
    1308              :  */
    1309              : Datum
    1310           32 : RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
    1311              : {
    1312              :     /* Check that this is a valid trigger call on the right time and event. */
    1313           32 :     ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
    1314              : 
    1315              :     /* Share code with DELETE case */
    1316           32 :     return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
    1317              : }
    1318              : 
    1319              : /*
    1320              :  * ri_set -
    1321              :  *
    1322              :  * Common code for ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE SET
    1323              :  * NULL, and ON UPDATE SET DEFAULT.
    1324              :  */
    1325              : static Datum
    1326          173 : ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
    1327              : {
    1328              :     const RI_ConstraintInfo *riinfo;
    1329              :     Relation    fk_rel;
    1330              :     Relation    pk_rel;
    1331              :     TupleTableSlot *oldslot;
    1332              :     RI_QueryKey qkey;
    1333              :     SPIPlanPtr  qplan;
    1334              :     int32       queryno;
    1335              : 
    1336          173 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
    1337              :                                     trigdata->tg_relation, true);
    1338              : 
    1339              :     /*
    1340              :      * Get the relation descriptors of the FK and PK tables and the old tuple.
    1341              :      *
    1342              :      * fk_rel is opened in RowExclusiveLock mode since that's what our
    1343              :      * eventual UPDATE will get on it.
    1344              :      */
    1345          173 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
    1346          173 :     pk_rel = trigdata->tg_relation;
    1347          173 :     oldslot = trigdata->tg_trigslot;
    1348              : 
    1349          173 :     SPI_connect();
    1350              : 
    1351              :     /*
    1352              :      * Fetch or prepare a saved plan for the trigger.
    1353              :      */
    1354          173 :     switch (tgkind)
    1355              :     {
    1356           52 :         case RI_TRIGTYPE_UPDATE:
    1357           52 :             queryno = is_set_null
    1358              :                 ? RI_PLAN_SETNULL_ONUPDATE
    1359           52 :                 : RI_PLAN_SETDEFAULT_ONUPDATE;
    1360           52 :             break;
    1361          121 :         case RI_TRIGTYPE_DELETE:
    1362          121 :             queryno = is_set_null
    1363              :                 ? RI_PLAN_SETNULL_ONDELETE
    1364          121 :                 : RI_PLAN_SETDEFAULT_ONDELETE;
    1365          121 :             break;
    1366            0 :         default:
    1367            0 :             elog(ERROR, "invalid tgkind passed to ri_set");
    1368              :     }
    1369              : 
    1370          173 :     ri_BuildQueryKey(&qkey, riinfo, queryno);
    1371              : 
    1372          173 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
    1373              :     {
    1374              :         StringInfoData querybuf;
    1375              :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1376              :         char        attname[MAX_QUOTED_NAME_LEN];
    1377              :         char        paramname[16];
    1378              :         const char *querysep;
    1379              :         const char *qualsep;
    1380              :         Oid         queryoids[RI_MAX_NUMKEYS];
    1381              :         const char *fk_only;
    1382              :         int         num_cols_to_set;
    1383              :         const int16 *set_cols;
    1384              : 
    1385          103 :         switch (tgkind)
    1386              :         {
    1387           32 :             case RI_TRIGTYPE_UPDATE:
    1388           32 :                 num_cols_to_set = riinfo->nkeys;
    1389           32 :                 set_cols = riinfo->fk_attnums;
    1390           32 :                 break;
    1391           71 :             case RI_TRIGTYPE_DELETE:
    1392              : 
    1393              :                 /*
    1394              :                  * If confdelsetcols are present, then we only update the
    1395              :                  * columns specified in that array, otherwise we update all
    1396              :                  * the referencing columns.
    1397              :                  */
    1398           71 :                 if (riinfo->ndelsetcols != 0)
    1399              :                 {
    1400           16 :                     num_cols_to_set = riinfo->ndelsetcols;
    1401           16 :                     set_cols = riinfo->confdelsetcols;
    1402              :                 }
    1403              :                 else
    1404              :                 {
    1405           55 :                     num_cols_to_set = riinfo->nkeys;
    1406           55 :                     set_cols = riinfo->fk_attnums;
    1407              :                 }
    1408           71 :                 break;
    1409            0 :             default:
    1410            0 :                 elog(ERROR, "invalid tgkind passed to ri_set");
    1411              :         }
    1412              : 
    1413              :         /* ----------
    1414              :          * The query string built is
    1415              :          *  UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
    1416              :          *          WHERE $1 = fkatt1 [AND ...]
    1417              :          * The type id's for the $ parameters are those of the
    1418              :          * corresponding PK attributes.
    1419              :          * ----------
    1420              :          */
    1421          103 :         initStringInfo(&querybuf);
    1422          206 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1423          103 :             "" : "ONLY ";
    1424          103 :         quoteRelationName(fkrelname, fk_rel);
    1425          103 :         appendStringInfo(&querybuf, "UPDATE %s%s SET",
    1426              :                          fk_only, fkrelname);
    1427              : 
    1428              :         /*
    1429              :          * Add assignment clauses
    1430              :          */
    1431          103 :         querysep = "";
    1432          273 :         for (int i = 0; i < num_cols_to_set; i++)
    1433              :         {
    1434          170 :             quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
    1435          170 :             appendStringInfo(&querybuf,
    1436              :                              "%s %s = %s",
    1437              :                              querysep, attname,
    1438              :                              is_set_null ? "NULL" : "DEFAULT");
    1439          170 :             querysep = ",";
    1440              :         }
    1441              : 
    1442              :         /*
    1443              :          * Add WHERE clause
    1444              :          */
    1445          103 :         qualsep = "WHERE";
    1446          289 :         for (int i = 0; i < riinfo->nkeys; i++)
    1447              :         {
    1448          186 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1449          186 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1450              : 
    1451          186 :             quoteOneName(attname,
    1452          186 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1453              : 
    1454          186 :             sprintf(paramname, "$%d", i + 1);
    1455          186 :             ri_GenerateQual(&querybuf, qualsep,
    1456              :                             paramname, pk_type,
    1457          186 :                             riinfo->pf_eq_oprs[i],
    1458              :                             attname, fk_type);
    1459          186 :             qualsep = "AND";
    1460          186 :             queryoids[i] = pk_type;
    1461              :         }
    1462              : 
    1463              :         /* Prepare and save the plan */
    1464          103 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
    1465              :                              &qkey, fk_rel, pk_rel);
    1466              :     }
    1467              : 
    1468              :     /*
    1469              :      * We have a plan now. Run it to update the existing references.
    1470              :      */
    1471          173 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1472              :                     fk_rel, pk_rel,
    1473              :                     oldslot, NULL,
    1474              :                     false,
    1475              :                     true,       /* must detect new rows */
    1476              :                     SPI_OK_UPDATE);
    1477              : 
    1478          172 :     if (SPI_finish() != SPI_OK_FINISH)
    1479            0 :         elog(ERROR, "SPI_finish failed");
    1480              : 
    1481          172 :     table_close(fk_rel, RowExclusiveLock);
    1482              : 
    1483          172 :     if (is_set_null)
    1484           84 :         return PointerGetDatum(NULL);
    1485              :     else
    1486              :     {
    1487              :         /*
    1488              :          * If we just deleted or updated the PK row whose key was equal to the
    1489              :          * FK columns' default values, and a referencing row exists in the FK
    1490              :          * table, we would have updated that row to the same values it already
    1491              :          * had --- and RI_FKey_fk_upd_check_required would hence believe no
    1492              :          * check is necessary.  So we need to do another lookup now and in
    1493              :          * case a reference still exists, abort the operation.  That is
    1494              :          * already implemented in the NO ACTION trigger, so just run it. (This
    1495              :          * recheck is only needed in the SET DEFAULT case, since CASCADE would
    1496              :          * remove such rows in case of a DELETE operation or would change the
    1497              :          * FK key values in case of an UPDATE, while SET NULL is certain to
    1498              :          * result in rows that satisfy the FK constraint.)
    1499              :          */
    1500           88 :         return ri_restrict(trigdata, true);
    1501              :     }
    1502              : }
    1503              : 
    1504              : 
    1505              : /*
    1506              :  * RI_FKey_pk_upd_check_required -
    1507              :  *
    1508              :  * Check if we really need to fire the RI trigger for an update or delete to a PK
    1509              :  * relation.  This is called by the AFTER trigger queue manager to see if
    1510              :  * it can skip queuing an instance of an RI trigger.  Returns true if the
    1511              :  * trigger must be fired, false if we can prove the constraint will still
    1512              :  * be satisfied.
    1513              :  *
    1514              :  * newslot will be NULL if this is called for a delete.
    1515              :  */
    1516              : bool
    1517         1533 : RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel,
    1518              :                               TupleTableSlot *oldslot, TupleTableSlot *newslot)
    1519              : {
    1520              :     const RI_ConstraintInfo *riinfo;
    1521              : 
    1522         1533 :     riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
    1523              : 
    1524              :     /*
    1525              :      * If any old key value is NULL, the row could not have been referenced by
    1526              :      * an FK row, so no check is needed.
    1527              :      */
    1528         1533 :     if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
    1529            4 :         return false;
    1530              : 
    1531              :     /* If all old and new key values are equal, no check is needed */
    1532         1529 :     if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
    1533          288 :         return false;
    1534              : 
    1535              :     /* Else we need to fire the trigger. */
    1536         1241 :     return true;
    1537              : }
    1538              : 
    1539              : /*
    1540              :  * RI_FKey_fk_upd_check_required -
    1541              :  *
    1542              :  * Check if we really need to fire the RI trigger for an update to an FK
    1543              :  * relation.  This is called by the AFTER trigger queue manager to see if
    1544              :  * it can skip queuing an instance of an RI trigger.  Returns true if the
    1545              :  * trigger must be fired, false if we can prove the constraint will still
    1546              :  * be satisfied.
    1547              :  */
    1548              : bool
    1549          668 : RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel,
    1550              :                               TupleTableSlot *oldslot, TupleTableSlot *newslot)
    1551              : {
    1552              :     const RI_ConstraintInfo *riinfo;
    1553              :     int         ri_nullcheck;
    1554              : 
    1555              :     /*
    1556              :      * AfterTriggerSaveEvent() handles things such that this function is never
    1557              :      * called for partitioned tables.
    1558              :      */
    1559              :     Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
    1560              : 
    1561          668 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1562              : 
    1563          668 :     ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
    1564              : 
    1565              :     /*
    1566              :      * If all new key values are NULL, the row satisfies the constraint, so no
    1567              :      * check is needed.
    1568              :      */
    1569          668 :     if (ri_nullcheck == RI_KEYS_ALL_NULL)
    1570           84 :         return false;
    1571              : 
    1572              :     /*
    1573              :      * If some new key values are NULL, the behavior depends on the match
    1574              :      * type.
    1575              :      */
    1576          584 :     else if (ri_nullcheck == RI_KEYS_SOME_NULL)
    1577              :     {
    1578           20 :         switch (riinfo->confmatchtype)
    1579              :         {
    1580           16 :             case FKCONSTR_MATCH_SIMPLE:
    1581              : 
    1582              :                 /*
    1583              :                  * If any new key value is NULL, the row must satisfy the
    1584              :                  * constraint, so no check is needed.
    1585              :                  */
    1586           16 :                 return false;
    1587              : 
    1588            0 :             case FKCONSTR_MATCH_PARTIAL:
    1589              : 
    1590              :                 /*
    1591              :                  * Don't know, must run full check.
    1592              :                  */
    1593            0 :                 break;
    1594              : 
    1595            4 :             case FKCONSTR_MATCH_FULL:
    1596              : 
    1597              :                 /*
    1598              :                  * If some new key values are NULL, the row fails the
    1599              :                  * constraint.  We must not throw error here, because the row
    1600              :                  * might get invalidated before the constraint is to be
    1601              :                  * checked, but we should queue the event to apply the check
    1602              :                  * later.
    1603              :                  */
    1604            4 :                 return true;
    1605              :         }
    1606              :     }
    1607              : 
    1608              :     /*
    1609              :      * Continues here for no new key values are NULL, or we couldn't decide
    1610              :      * yet.
    1611              :      */
    1612              : 
    1613              :     /*
    1614              :      * If the original row was inserted by our own transaction, we must fire
    1615              :      * the trigger whether or not the keys are equal.  This is because our
    1616              :      * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
    1617              :      * not do anything; so we had better do the UPDATE check.  (We could skip
    1618              :      * this if we knew the INSERT trigger already fired, but there is no easy
    1619              :      * way to know that.)
    1620              :      */
    1621          564 :     if (slot_is_current_xact_tuple(oldslot))
    1622           77 :         return true;
    1623              : 
    1624              :     /* If all old and new key values are equal, no check is needed */
    1625          487 :     if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
    1626          262 :         return false;
    1627              : 
    1628              :     /* Else we need to fire the trigger. */
    1629          225 :     return true;
    1630              : }
    1631              : 
    1632              : /*
    1633              :  * RI_Initial_Check -
    1634              :  *
    1635              :  * Check an entire table for non-matching values using a single query.
    1636              :  * This is not a trigger procedure, but is called during ALTER TABLE
    1637              :  * ADD FOREIGN KEY to validate the initial table contents.
    1638              :  *
    1639              :  * We expect that the caller has made provision to prevent any problems
    1640              :  * caused by concurrent actions. This could be either by locking rel and
    1641              :  * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
    1642              :  * that triggers implementing the checks are already active.
    1643              :  * Hence, we do not need to lock individual rows for the check.
    1644              :  *
    1645              :  * If the check fails because the current user doesn't have permissions
    1646              :  * to read both tables, return false to let our caller know that they will
    1647              :  * need to do something else to check the constraint.
    1648              :  */
    1649              : bool
    1650          765 : RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
    1651              : {
    1652              :     const RI_ConstraintInfo *riinfo;
    1653              :     StringInfoData querybuf;
    1654              :     char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
    1655              :     char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1656              :     char        pkattname[MAX_QUOTED_NAME_LEN + 3];
    1657              :     char        fkattname[MAX_QUOTED_NAME_LEN + 3];
    1658              :     RangeTblEntry *rte;
    1659              :     RTEPermissionInfo *pk_perminfo;
    1660              :     RTEPermissionInfo *fk_perminfo;
    1661          765 :     List       *rtes = NIL;
    1662          765 :     List       *perminfos = NIL;
    1663              :     const char *sep;
    1664              :     const char *fk_only;
    1665              :     const char *pk_only;
    1666              :     int         save_nestlevel;
    1667              :     char        workmembuf[32];
    1668              :     int         spi_result;
    1669              :     SPIPlanPtr  qplan;
    1670              : 
    1671          765 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1672              : 
    1673              :     /*
    1674              :      * Check to make sure current user has enough permissions to do the test
    1675              :      * query.  (If not, caller can fall back to the trigger method, which
    1676              :      * works because it changes user IDs on the fly.)
    1677              :      *
    1678              :      * XXX are there any other show-stopper conditions to check?
    1679              :      */
    1680          765 :     pk_perminfo = makeNode(RTEPermissionInfo);
    1681          765 :     pk_perminfo->relid = RelationGetRelid(pk_rel);
    1682          765 :     pk_perminfo->requiredPerms = ACL_SELECT;
    1683          765 :     perminfos = lappend(perminfos, pk_perminfo);
    1684          765 :     rte = makeNode(RangeTblEntry);
    1685          765 :     rte->rtekind = RTE_RELATION;
    1686          765 :     rte->relid = RelationGetRelid(pk_rel);
    1687          765 :     rte->relkind = pk_rel->rd_rel->relkind;
    1688          765 :     rte->rellockmode = AccessShareLock;
    1689          765 :     rte->perminfoindex = list_length(perminfos);
    1690          765 :     rtes = lappend(rtes, rte);
    1691              : 
    1692          765 :     fk_perminfo = makeNode(RTEPermissionInfo);
    1693          765 :     fk_perminfo->relid = RelationGetRelid(fk_rel);
    1694          765 :     fk_perminfo->requiredPerms = ACL_SELECT;
    1695          765 :     perminfos = lappend(perminfos, fk_perminfo);
    1696          765 :     rte = makeNode(RangeTblEntry);
    1697          765 :     rte->rtekind = RTE_RELATION;
    1698          765 :     rte->relid = RelationGetRelid(fk_rel);
    1699          765 :     rte->relkind = fk_rel->rd_rel->relkind;
    1700          765 :     rte->rellockmode = AccessShareLock;
    1701          765 :     rte->perminfoindex = list_length(perminfos);
    1702          765 :     rtes = lappend(rtes, rte);
    1703              : 
    1704         1799 :     for (int i = 0; i < riinfo->nkeys; i++)
    1705              :     {
    1706              :         int         attno;
    1707              : 
    1708         1034 :         attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
    1709         1034 :         pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
    1710              : 
    1711         1034 :         attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
    1712         1034 :         fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
    1713              :     }
    1714              : 
    1715          765 :     if (!ExecCheckPermissions(rtes, perminfos, false))
    1716            8 :         return false;
    1717              : 
    1718              :     /*
    1719              :      * Also punt if RLS is enabled on either table unless this role has the
    1720              :      * bypassrls right or is the table owner of the table(s) involved which
    1721              :      * have RLS enabled.
    1722              :      */
    1723          757 :     if (!has_bypassrls_privilege(GetUserId()) &&
    1724            0 :         ((pk_rel->rd_rel->relrowsecurity &&
    1725            0 :           !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
    1726            0 :                              GetUserId())) ||
    1727            0 :          (fk_rel->rd_rel->relrowsecurity &&
    1728            0 :           !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
    1729              :                              GetUserId()))))
    1730            0 :         return false;
    1731              : 
    1732              :     /*----------
    1733              :      * The query string built is:
    1734              :      *  SELECT fk.keycols FROM [ONLY] relname fk
    1735              :      *   LEFT OUTER JOIN [ONLY] pkrelname pk
    1736              :      *   ON (pk.pkkeycol1=fk.keycol1 [AND ...])
    1737              :      *   WHERE pk.pkkeycol1 IS NULL AND
    1738              :      * For MATCH SIMPLE:
    1739              :      *   (fk.keycol1 IS NOT NULL [AND ...])
    1740              :      * For MATCH FULL:
    1741              :      *   (fk.keycol1 IS NOT NULL [OR ...])
    1742              :      *
    1743              :      * We attach COLLATE clauses to the operators when comparing columns
    1744              :      * that have different collations.
    1745              :      *----------
    1746              :      */
    1747          757 :     initStringInfo(&querybuf);
    1748          757 :     appendStringInfoString(&querybuf, "SELECT ");
    1749          757 :     sep = "";
    1750         1775 :     for (int i = 0; i < riinfo->nkeys; i++)
    1751              :     {
    1752         1018 :         quoteOneName(fkattname,
    1753         1018 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1754         1018 :         appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
    1755         1018 :         sep = ", ";
    1756              :     }
    1757              : 
    1758          757 :     quoteRelationName(pkrelname, pk_rel);
    1759          757 :     quoteRelationName(fkrelname, fk_rel);
    1760         1514 :     fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1761          757 :         "" : "ONLY ";
    1762         1514 :     pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1763          757 :         "" : "ONLY ";
    1764          757 :     appendStringInfo(&querybuf,
    1765              :                      " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
    1766              :                      fk_only, fkrelname, pk_only, pkrelname);
    1767              : 
    1768          757 :     strcpy(pkattname, "pk.");
    1769          757 :     strcpy(fkattname, "fk.");
    1770          757 :     sep = "(";
    1771         1775 :     for (int i = 0; i < riinfo->nkeys; i++)
    1772              :     {
    1773         1018 :         Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1774         1018 :         Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1775         1018 :         Oid         pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
    1776         1018 :         Oid         fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
    1777              : 
    1778         1018 :         quoteOneName(pkattname + 3,
    1779         1018 :                      RIAttName(pk_rel, riinfo->pk_attnums[i]));
    1780         1018 :         quoteOneName(fkattname + 3,
    1781         1018 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1782         1018 :         ri_GenerateQual(&querybuf, sep,
    1783              :                         pkattname, pk_type,
    1784         1018 :                         riinfo->pf_eq_oprs[i],
    1785              :                         fkattname, fk_type);
    1786         1018 :         if (pk_coll != fk_coll)
    1787            8 :             ri_GenerateQualCollation(&querybuf, pk_coll);
    1788         1018 :         sep = "AND";
    1789              :     }
    1790              : 
    1791              :     /*
    1792              :      * It's sufficient to test any one pk attribute for null to detect a join
    1793              :      * failure.
    1794              :      */
    1795          757 :     quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
    1796          757 :     appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
    1797              : 
    1798          757 :     sep = "";
    1799         1775 :     for (int i = 0; i < riinfo->nkeys; i++)
    1800              :     {
    1801         1018 :         quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1802         1018 :         appendStringInfo(&querybuf,
    1803              :                          "%sfk.%s IS NOT NULL",
    1804              :                          sep, fkattname);
    1805         1018 :         switch (riinfo->confmatchtype)
    1806              :         {
    1807          944 :             case FKCONSTR_MATCH_SIMPLE:
    1808          944 :                 sep = " AND ";
    1809          944 :                 break;
    1810           74 :             case FKCONSTR_MATCH_FULL:
    1811           74 :                 sep = " OR ";
    1812           74 :                 break;
    1813              :         }
    1814              :     }
    1815          757 :     appendStringInfoChar(&querybuf, ')');
    1816              : 
    1817              :     /*
    1818              :      * Temporarily increase work_mem so that the check query can be executed
    1819              :      * more efficiently.  It seems okay to do this because the query is simple
    1820              :      * enough to not use a multiple of work_mem, and one typically would not
    1821              :      * have many large foreign-key validations happening concurrently.  So
    1822              :      * this seems to meet the criteria for being considered a "maintenance"
    1823              :      * operation, and accordingly we use maintenance_work_mem.  However, we
    1824              :      * must also set hash_mem_multiplier to 1, since it is surely not okay to
    1825              :      * let that get applied to the maintenance_work_mem value.
    1826              :      *
    1827              :      * We use the equivalent of a function SET option to allow the setting to
    1828              :      * persist for exactly the duration of the check query.  guc.c also takes
    1829              :      * care of undoing the setting on error.
    1830              :      */
    1831          757 :     save_nestlevel = NewGUCNestLevel();
    1832              : 
    1833          757 :     snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
    1834          757 :     (void) set_config_option("work_mem", workmembuf,
    1835              :                              PGC_USERSET, PGC_S_SESSION,
    1836              :                              GUC_ACTION_SAVE, true, 0, false);
    1837          757 :     (void) set_config_option("hash_mem_multiplier", "1",
    1838              :                              PGC_USERSET, PGC_S_SESSION,
    1839              :                              GUC_ACTION_SAVE, true, 0, false);
    1840              : 
    1841          757 :     SPI_connect();
    1842              : 
    1843              :     /*
    1844              :      * Generate the plan.  We don't need to cache it, and there are no
    1845              :      * arguments to the plan.
    1846              :      */
    1847          757 :     qplan = SPI_prepare(querybuf.data, 0, NULL);
    1848              : 
    1849          757 :     if (qplan == NULL)
    1850            0 :         elog(ERROR, "SPI_prepare returned %s for %s",
    1851              :              SPI_result_code_string(SPI_result), querybuf.data);
    1852              : 
    1853              :     /*
    1854              :      * Run the plan.  For safety we force a current snapshot to be used. (In
    1855              :      * transaction-snapshot mode, this arguably violates transaction isolation
    1856              :      * rules, but we really haven't got much choice.) We don't need to
    1857              :      * register the snapshot, because SPI_execute_snapshot will see to it. We
    1858              :      * need at most one tuple returned, so pass limit = 1.
    1859              :      */
    1860          757 :     spi_result = SPI_execute_snapshot(qplan,
    1861              :                                       NULL, NULL,
    1862              :                                       GetLatestSnapshot(),
    1863              :                                       InvalidSnapshot,
    1864              :                                       true, false, 1);
    1865              : 
    1866              :     /* Check result */
    1867          757 :     if (spi_result != SPI_OK_SELECT)
    1868            0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    1869              : 
    1870              :     /* Did we find a tuple violating the constraint? */
    1871          757 :     if (SPI_processed > 0)
    1872              :     {
    1873              :         TupleTableSlot *slot;
    1874           59 :         HeapTuple   tuple = SPI_tuptable->vals[0];
    1875           59 :         TupleDesc   tupdesc = SPI_tuptable->tupdesc;
    1876              :         RI_ConstraintInfo fake_riinfo;
    1877              : 
    1878           59 :         slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
    1879              : 
    1880           59 :         heap_deform_tuple(tuple, tupdesc,
    1881              :                           slot->tts_values, slot->tts_isnull);
    1882           59 :         ExecStoreVirtualTuple(slot);
    1883              : 
    1884              :         /*
    1885              :          * The columns to look at in the result tuple are 1..N, not whatever
    1886              :          * they are in the fk_rel.  Hack up riinfo so that the subroutines
    1887              :          * called here will behave properly.
    1888              :          *
    1889              :          * In addition to this, we have to pass the correct tupdesc to
    1890              :          * ri_ReportViolation, overriding its normal habit of using the pk_rel
    1891              :          * or fk_rel's tupdesc.
    1892              :          */
    1893           59 :         memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
    1894          134 :         for (int i = 0; i < fake_riinfo.nkeys; i++)
    1895           75 :             fake_riinfo.fk_attnums[i] = i + 1;
    1896              : 
    1897              :         /*
    1898              :          * If it's MATCH FULL, and there are any nulls in the FK keys,
    1899              :          * complain about that rather than the lack of a match.  MATCH FULL
    1900              :          * disallows partially-null FK rows.
    1901              :          */
    1902           79 :         if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
    1903           20 :             ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
    1904            8 :             ereport(ERROR,
    1905              :                     (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    1906              :                      errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
    1907              :                             RelationGetRelationName(fk_rel),
    1908              :                             NameStr(fake_riinfo.conname)),
    1909              :                      errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
    1910              :                      errtableconstraint(fk_rel,
    1911              :                                         NameStr(fake_riinfo.conname))));
    1912              : 
    1913              :         /*
    1914              :          * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
    1915              :          * query, which isn't true, but will cause it to use
    1916              :          * fake_riinfo.fk_attnums as we need.
    1917              :          */
    1918           51 :         ri_ReportViolation(&fake_riinfo,
    1919              :                            pk_rel, fk_rel,
    1920              :                            slot, tupdesc,
    1921              :                            RI_PLAN_CHECK_LOOKUPPK, false, false);
    1922              : 
    1923              :         ExecDropSingleTupleTableSlot(slot);
    1924              :     }
    1925              : 
    1926          698 :     if (SPI_finish() != SPI_OK_FINISH)
    1927            0 :         elog(ERROR, "SPI_finish failed");
    1928              : 
    1929              :     /*
    1930              :      * Restore work_mem and hash_mem_multiplier.
    1931              :      */
    1932          698 :     AtEOXact_GUC(true, save_nestlevel);
    1933              : 
    1934          698 :     return true;
    1935              : }
    1936              : 
    1937              : /*
    1938              :  * RI_PartitionRemove_Check -
    1939              :  *
    1940              :  * Verify no referencing values exist, when a partition is detached on
    1941              :  * the referenced side of a foreign key constraint.
    1942              :  */
    1943              : void
    1944           65 : RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
    1945              : {
    1946              :     const RI_ConstraintInfo *riinfo;
    1947              :     StringInfoData querybuf;
    1948              :     char       *constraintDef;
    1949              :     char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
    1950              :     char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1951              :     char        pkattname[MAX_QUOTED_NAME_LEN + 3];
    1952              :     char        fkattname[MAX_QUOTED_NAME_LEN + 3];
    1953              :     const char *sep;
    1954              :     const char *fk_only;
    1955              :     int         save_nestlevel;
    1956              :     char        workmembuf[32];
    1957              :     int         spi_result;
    1958              :     SPIPlanPtr  qplan;
    1959              :     int         i;
    1960              : 
    1961           65 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1962              : 
    1963              :     /*
    1964              :      * We don't check permissions before displaying the error message, on the
    1965              :      * assumption that the user detaching the partition must have enough
    1966              :      * privileges to examine the table contents anyhow.
    1967              :      */
    1968              : 
    1969              :     /*----------
    1970              :      * The query string built is:
    1971              :      *  SELECT fk.keycols FROM [ONLY] relname fk
    1972              :      *    JOIN pkrelname pk
    1973              :      *    ON (pk.pkkeycol1=fk.keycol1 [AND ...])
    1974              :      *    WHERE (<partition constraint>) AND
    1975              :      * For MATCH SIMPLE:
    1976              :      *   (fk.keycol1 IS NOT NULL [AND ...])
    1977              :      * For MATCH FULL:
    1978              :      *   (fk.keycol1 IS NOT NULL [OR ...])
    1979              :      *
    1980              :      * We attach COLLATE clauses to the operators when comparing columns
    1981              :      * that have different collations.
    1982              :      *----------
    1983              :      */
    1984           65 :     initStringInfo(&querybuf);
    1985           65 :     appendStringInfoString(&querybuf, "SELECT ");
    1986           65 :     sep = "";
    1987          130 :     for (i = 0; i < riinfo->nkeys; i++)
    1988              :     {
    1989           65 :         quoteOneName(fkattname,
    1990           65 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1991           65 :         appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
    1992           65 :         sep = ", ";
    1993              :     }
    1994              : 
    1995           65 :     quoteRelationName(pkrelname, pk_rel);
    1996           65 :     quoteRelationName(fkrelname, fk_rel);
    1997          130 :     fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1998           65 :         "" : "ONLY ";
    1999           65 :     appendStringInfo(&querybuf,
    2000              :                      " FROM %s%s fk JOIN %s pk ON",
    2001              :                      fk_only, fkrelname, pkrelname);
    2002           65 :     strcpy(pkattname, "pk.");
    2003           65 :     strcpy(fkattname, "fk.");
    2004           65 :     sep = "(";
    2005          130 :     for (i = 0; i < riinfo->nkeys; i++)
    2006              :     {
    2007           65 :         Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    2008           65 :         Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    2009           65 :         Oid         pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
    2010           65 :         Oid         fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
    2011              : 
    2012           65 :         quoteOneName(pkattname + 3,
    2013           65 :                      RIAttName(pk_rel, riinfo->pk_attnums[i]));
    2014           65 :         quoteOneName(fkattname + 3,
    2015           65 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    2016           65 :         ri_GenerateQual(&querybuf, sep,
    2017              :                         pkattname, pk_type,
    2018           65 :                         riinfo->pf_eq_oprs[i],
    2019              :                         fkattname, fk_type);
    2020           65 :         if (pk_coll != fk_coll)
    2021            0 :             ri_GenerateQualCollation(&querybuf, pk_coll);
    2022           65 :         sep = "AND";
    2023              :     }
    2024              : 
    2025              :     /*
    2026              :      * Start the WHERE clause with the partition constraint (except if this is
    2027              :      * the default partition and there's no other partition, because the
    2028              :      * partition constraint is the empty string in that case.)
    2029              :      */
    2030           65 :     constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
    2031           65 :     if (constraintDef && constraintDef[0] != '\0')
    2032           65 :         appendStringInfo(&querybuf, ") WHERE %s AND (",
    2033              :                          constraintDef);
    2034              :     else
    2035            0 :         appendStringInfoString(&querybuf, ") WHERE (");
    2036              : 
    2037           65 :     sep = "";
    2038          130 :     for (i = 0; i < riinfo->nkeys; i++)
    2039              :     {
    2040           65 :         quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
    2041           65 :         appendStringInfo(&querybuf,
    2042              :                          "%sfk.%s IS NOT NULL",
    2043              :                          sep, fkattname);
    2044           65 :         switch (riinfo->confmatchtype)
    2045              :         {
    2046           65 :             case FKCONSTR_MATCH_SIMPLE:
    2047           65 :                 sep = " AND ";
    2048           65 :                 break;
    2049            0 :             case FKCONSTR_MATCH_FULL:
    2050            0 :                 sep = " OR ";
    2051            0 :                 break;
    2052              :         }
    2053              :     }
    2054           65 :     appendStringInfoChar(&querybuf, ')');
    2055              : 
    2056              :     /*
    2057              :      * Temporarily increase work_mem so that the check query can be executed
    2058              :      * more efficiently.  It seems okay to do this because the query is simple
    2059              :      * enough to not use a multiple of work_mem, and one typically would not
    2060              :      * have many large foreign-key validations happening concurrently.  So
    2061              :      * this seems to meet the criteria for being considered a "maintenance"
    2062              :      * operation, and accordingly we use maintenance_work_mem.  However, we
    2063              :      * must also set hash_mem_multiplier to 1, since it is surely not okay to
    2064              :      * let that get applied to the maintenance_work_mem value.
    2065              :      *
    2066              :      * We use the equivalent of a function SET option to allow the setting to
    2067              :      * persist for exactly the duration of the check query.  guc.c also takes
    2068              :      * care of undoing the setting on error.
    2069              :      */
    2070           65 :     save_nestlevel = NewGUCNestLevel();
    2071              : 
    2072           65 :     snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
    2073           65 :     (void) set_config_option("work_mem", workmembuf,
    2074              :                              PGC_USERSET, PGC_S_SESSION,
    2075              :                              GUC_ACTION_SAVE, true, 0, false);
    2076           65 :     (void) set_config_option("hash_mem_multiplier", "1",
    2077              :                              PGC_USERSET, PGC_S_SESSION,
    2078              :                              GUC_ACTION_SAVE, true, 0, false);
    2079              : 
    2080           65 :     SPI_connect();
    2081              : 
    2082              :     /*
    2083              :      * Generate the plan.  We don't need to cache it, and there are no
    2084              :      * arguments to the plan.
    2085              :      */
    2086           65 :     qplan = SPI_prepare(querybuf.data, 0, NULL);
    2087              : 
    2088           65 :     if (qplan == NULL)
    2089            0 :         elog(ERROR, "SPI_prepare returned %s for %s",
    2090              :              SPI_result_code_string(SPI_result), querybuf.data);
    2091              : 
    2092              :     /*
    2093              :      * Run the plan.  For safety we force a current snapshot to be used. (In
    2094              :      * transaction-snapshot mode, this arguably violates transaction isolation
    2095              :      * rules, but we really haven't got much choice.) We don't need to
    2096              :      * register the snapshot, because SPI_execute_snapshot will see to it. We
    2097              :      * need at most one tuple returned, so pass limit = 1.
    2098              :      */
    2099           65 :     spi_result = SPI_execute_snapshot(qplan,
    2100              :                                       NULL, NULL,
    2101              :                                       GetLatestSnapshot(),
    2102              :                                       InvalidSnapshot,
    2103              :                                       true, false, 1);
    2104              : 
    2105              :     /* Check result */
    2106           65 :     if (spi_result != SPI_OK_SELECT)
    2107            0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    2108              : 
    2109              :     /* Did we find a tuple that would violate the constraint? */
    2110           65 :     if (SPI_processed > 0)
    2111              :     {
    2112              :         TupleTableSlot *slot;
    2113           22 :         HeapTuple   tuple = SPI_tuptable->vals[0];
    2114           22 :         TupleDesc   tupdesc = SPI_tuptable->tupdesc;
    2115              :         RI_ConstraintInfo fake_riinfo;
    2116              : 
    2117           22 :         slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
    2118              : 
    2119           22 :         heap_deform_tuple(tuple, tupdesc,
    2120              :                           slot->tts_values, slot->tts_isnull);
    2121           22 :         ExecStoreVirtualTuple(slot);
    2122              : 
    2123              :         /*
    2124              :          * The columns to look at in the result tuple are 1..N, not whatever
    2125              :          * they are in the fk_rel.  Hack up riinfo so that ri_ReportViolation
    2126              :          * will behave properly.
    2127              :          *
    2128              :          * In addition to this, we have to pass the correct tupdesc to
    2129              :          * ri_ReportViolation, overriding its normal habit of using the pk_rel
    2130              :          * or fk_rel's tupdesc.
    2131              :          */
    2132           22 :         memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
    2133           44 :         for (i = 0; i < fake_riinfo.nkeys; i++)
    2134           22 :             fake_riinfo.pk_attnums[i] = i + 1;
    2135              : 
    2136           22 :         ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
    2137              :                            slot, tupdesc, 0, false, true);
    2138              :     }
    2139              : 
    2140           43 :     if (SPI_finish() != SPI_OK_FINISH)
    2141            0 :         elog(ERROR, "SPI_finish failed");
    2142              : 
    2143              :     /*
    2144              :      * Restore work_mem and hash_mem_multiplier.
    2145              :      */
    2146           43 :     AtEOXact_GUC(true, save_nestlevel);
    2147           43 : }
    2148              : 
    2149              : 
    2150              : /* ----------
    2151              :  * Local functions below
    2152              :  * ----------
    2153              :  */
    2154              : 
    2155              : 
    2156              : /*
    2157              :  * quoteOneName --- safely quote a single SQL name
    2158              :  *
    2159              :  * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
    2160              :  */
    2161              : static void
    2162        13195 : quoteOneName(char *buffer, const char *name)
    2163              : {
    2164              :     /* Rather than trying to be smart, just always quote it. */
    2165        13195 :     *buffer++ = '"';
    2166        81509 :     while (*name)
    2167              :     {
    2168        68314 :         if (*name == '"')
    2169            0 :             *buffer++ = '"';
    2170        68314 :         *buffer++ = *name++;
    2171              :     }
    2172        13195 :     *buffer++ = '"';
    2173        13195 :     *buffer = '\0';
    2174        13195 : }
    2175              : 
    2176              : /*
    2177              :  * quoteRelationName --- safely quote a fully qualified relation name
    2178              :  *
    2179              :  * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
    2180              :  */
    2181              : static void
    2182         2923 : quoteRelationName(char *buffer, Relation rel)
    2183              : {
    2184         2923 :     quoteOneName(buffer, get_namespace_name(RelationGetNamespace(rel)));
    2185         2923 :     buffer += strlen(buffer);
    2186         2923 :     *buffer++ = '.';
    2187         2923 :     quoteOneName(buffer, RelationGetRelationName(rel));
    2188         2923 : }
    2189              : 
    2190              : /*
    2191              :  * ri_GenerateQual --- generate a WHERE clause equating two variables
    2192              :  *
    2193              :  * This basically appends " sep leftop op rightop" to buf, adding casts
    2194              :  * and schema qualification as needed to ensure that the parser will select
    2195              :  * the operator we specify.  leftop and rightop should be parenthesized
    2196              :  * if they aren't variables or parameters.
    2197              :  */
    2198              : static void
    2199         3157 : ri_GenerateQual(StringInfo buf,
    2200              :                 const char *sep,
    2201              :                 const char *leftop, Oid leftoptype,
    2202              :                 Oid opoid,
    2203              :                 const char *rightop, Oid rightoptype)
    2204              : {
    2205         3157 :     appendStringInfo(buf, " %s ", sep);
    2206         3157 :     generate_operator_clause(buf, leftop, leftoptype, opoid,
    2207              :                              rightop, rightoptype);
    2208         3157 : }
    2209              : 
    2210              : /*
    2211              :  * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
    2212              :  *
    2213              :  * We only have to use this function when directly comparing the referencing
    2214              :  * and referenced columns, if they are of different collations; else the
    2215              :  * parser will fail to resolve the collation to use.  We don't need to use
    2216              :  * this function for RI queries that compare a variable to a $n parameter.
    2217              :  * Since parameter symbols always have default collation, the effect will be
    2218              :  * to use the variable's collation.
    2219              :  *
    2220              :  * Note that we require that the collations of the referencing and the
    2221              :  * referenced column have the same notion of equality: Either they have to
    2222              :  * both be deterministic or else they both have to be the same.  (See also
    2223              :  * ATAddForeignKeyConstraint().)
    2224              :  */
    2225              : static void
    2226            8 : ri_GenerateQualCollation(StringInfo buf, Oid collation)
    2227              : {
    2228              :     HeapTuple   tp;
    2229              :     Form_pg_collation colltup;
    2230              :     char       *collname;
    2231              :     char        onename[MAX_QUOTED_NAME_LEN];
    2232              : 
    2233              :     /* Nothing to do if it's a noncollatable data type */
    2234            8 :     if (!OidIsValid(collation))
    2235            0 :         return;
    2236              : 
    2237            8 :     tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
    2238            8 :     if (!HeapTupleIsValid(tp))
    2239            0 :         elog(ERROR, "cache lookup failed for collation %u", collation);
    2240            8 :     colltup = (Form_pg_collation) GETSTRUCT(tp);
    2241            8 :     collname = NameStr(colltup->collname);
    2242              : 
    2243              :     /*
    2244              :      * We qualify the name always, for simplicity and to ensure the query is
    2245              :      * not search-path-dependent.
    2246              :      */
    2247            8 :     quoteOneName(onename, get_namespace_name(colltup->collnamespace));
    2248            8 :     appendStringInfo(buf, " COLLATE %s", onename);
    2249            8 :     quoteOneName(onename, collname);
    2250            8 :     appendStringInfo(buf, ".%s", onename);
    2251              : 
    2252            8 :     ReleaseSysCache(tp);
    2253              : }
    2254              : 
    2255              : /* ----------
    2256              :  * ri_BuildQueryKey -
    2257              :  *
    2258              :  *  Construct a hashtable key for a prepared SPI plan of an FK constraint.
    2259              :  *
    2260              :  *      key: output argument, *key is filled in based on the other arguments
    2261              :  *      riinfo: info derived from pg_constraint entry
    2262              :  *      constr_queryno: an internal number identifying the query type
    2263              :  *          (see RI_PLAN_XXX constants at head of file)
    2264              :  * ----------
    2265              :  */
    2266              : static void
    2267         2475 : ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo,
    2268              :                  int32 constr_queryno)
    2269              : {
    2270              :     /*
    2271              :      * Inherited constraints with a common ancestor can share ri_query_cache
    2272              :      * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
    2273              :      * Except in that case, the query processes the other table involved in
    2274              :      * the FK constraint (i.e., not the table on which the trigger has been
    2275              :      * fired), and so it will be the same for all members of the inheritance
    2276              :      * tree.  So we may use the root constraint's OID in the hash key, rather
    2277              :      * than the constraint's own OID.  This avoids creating duplicate SPI
    2278              :      * plans, saving lots of work and memory when there are many partitions
    2279              :      * with similar FK constraints.
    2280              :      *
    2281              :      * (Note that we must still have a separate RI_ConstraintInfo for each
    2282              :      * constraint, because partitions can have different column orders,
    2283              :      * resulting in different pk_attnums[] or fk_attnums[] array contents.)
    2284              :      *
    2285              :      * We assume struct RI_QueryKey contains no padding bytes, else we'd need
    2286              :      * to use memset to clear them.
    2287              :      */
    2288         2475 :     if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
    2289         1952 :         key->constr_id = riinfo->constraint_root_id;
    2290              :     else
    2291          523 :         key->constr_id = riinfo->constraint_id;
    2292         2475 :     key->constr_queryno = constr_queryno;
    2293         2475 : }
    2294              : 
    2295              : /*
    2296              :  * Check that RI trigger function was called in expected context
    2297              :  */
    2298              : static void
    2299       605839 : ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
    2300              : {
    2301       605839 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
    2302              : 
    2303       605839 :     if (!CALLED_AS_TRIGGER(fcinfo))
    2304            0 :         ereport(ERROR,
    2305              :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2306              :                  errmsg("function \"%s\" was not called by trigger manager", funcname)));
    2307              : 
    2308              :     /*
    2309              :      * Check proper event
    2310              :      */
    2311       605839 :     if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
    2312       605839 :         !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
    2313            0 :         ereport(ERROR,
    2314              :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2315              :                  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
    2316              : 
    2317       605839 :     switch (tgkind)
    2318              :     {
    2319       604433 :         case RI_TRIGTYPE_INSERT:
    2320       604433 :             if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    2321            0 :                 ereport(ERROR,
    2322              :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2323              :                          errmsg("function \"%s\" must be fired for INSERT", funcname)));
    2324       604433 :             break;
    2325          866 :         case RI_TRIGTYPE_UPDATE:
    2326          866 :             if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    2327            0 :                 ereport(ERROR,
    2328              :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2329              :                          errmsg("function \"%s\" must be fired for UPDATE", funcname)));
    2330          866 :             break;
    2331          540 :         case RI_TRIGTYPE_DELETE:
    2332          540 :             if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    2333            0 :                 ereport(ERROR,
    2334              :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2335              :                          errmsg("function \"%s\" must be fired for DELETE", funcname)));
    2336          540 :             break;
    2337              :     }
    2338       605839 : }
    2339              : 
    2340              : 
    2341              : /*
    2342              :  * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
    2343              :  */
    2344              : static RI_ConstraintInfo *
    2345       608958 : ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
    2346              : {
    2347       608958 :     Oid         constraintOid = trigger->tgconstraint;
    2348              :     RI_ConstraintInfo *riinfo;
    2349              : 
    2350              :     /*
    2351              :      * Check that the FK constraint's OID is available; it might not be if
    2352              :      * we've been invoked via an ordinary trigger or an old-style "constraint
    2353              :      * trigger".
    2354              :      */
    2355       608958 :     if (!OidIsValid(constraintOid))
    2356            0 :         ereport(ERROR,
    2357              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2358              :                  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2359              :                         trigger->tgname, RelationGetRelationName(trig_rel)),
    2360              :                  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
    2361              : 
    2362              :     /* Find or create a hashtable entry for the constraint */
    2363       608958 :     riinfo = ri_LoadConstraintInfo(constraintOid);
    2364              : 
    2365              :     /* Do some easy cross-checks against the trigger call data */
    2366       608958 :     if (rel_is_pk)
    2367              :     {
    2368         2733 :         if (riinfo->fk_relid != trigger->tgconstrrelid ||
    2369         2733 :             riinfo->pk_relid != RelationGetRelid(trig_rel))
    2370            0 :             elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2371              :                  trigger->tgname, RelationGetRelationName(trig_rel));
    2372              :     }
    2373              :     else
    2374              :     {
    2375       606225 :         if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
    2376       606225 :             riinfo->pk_relid != trigger->tgconstrrelid)
    2377            0 :             elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2378              :                  trigger->tgname, RelationGetRelationName(trig_rel));
    2379              :     }
    2380              : 
    2381       608958 :     if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
    2382       608645 :         riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
    2383       608645 :         riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
    2384            0 :         elog(ERROR, "unrecognized confmatchtype: %d",
    2385              :              riinfo->confmatchtype);
    2386              : 
    2387       608958 :     if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
    2388            0 :         ereport(ERROR,
    2389              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2390              :                  errmsg("MATCH PARTIAL not yet implemented")));
    2391              : 
    2392       608958 :     return riinfo;
    2393              : }
    2394              : 
    2395              : /*
    2396              :  * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
    2397              :  */
    2398              : static RI_ConstraintInfo *
    2399       611624 : ri_LoadConstraintInfo(Oid constraintOid)
    2400              : {
    2401              :     RI_ConstraintInfo *riinfo;
    2402              :     bool        found;
    2403              :     HeapTuple   tup;
    2404              :     Form_pg_constraint conForm;
    2405              : 
    2406              :     /*
    2407              :      * On the first call initialize the hashtable
    2408              :      */
    2409       611624 :     if (!ri_constraint_cache)
    2410          264 :         ri_InitHashTables();
    2411              : 
    2412              :     /*
    2413              :      * Find or create a hash entry.  If we find a valid one, just return it.
    2414              :      */
    2415       611624 :     riinfo = (RI_ConstraintInfo *) hash_search(ri_constraint_cache,
    2416              :                                                &constraintOid,
    2417              :                                                HASH_ENTER, &found);
    2418       611624 :     if (!found)
    2419         2482 :         riinfo->valid = false;
    2420       609142 :     else if (riinfo->valid)
    2421       608878 :         return riinfo;
    2422              : 
    2423              :     /*
    2424              :      * Fetch the pg_constraint row so we can fill in the entry.
    2425              :      */
    2426         2746 :     tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
    2427         2746 :     if (!HeapTupleIsValid(tup)) /* should not happen */
    2428            0 :         elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
    2429         2746 :     conForm = (Form_pg_constraint) GETSTRUCT(tup);
    2430              : 
    2431         2746 :     if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
    2432            0 :         elog(ERROR, "constraint %u is not a foreign key constraint",
    2433              :              constraintOid);
    2434              : 
    2435              :     /* And extract data */
    2436              :     Assert(riinfo->constraint_id == constraintOid);
    2437         2746 :     if (OidIsValid(conForm->conparentid))
    2438          964 :         riinfo->constraint_root_id =
    2439          964 :             get_ri_constraint_root(conForm->conparentid);
    2440              :     else
    2441         1782 :         riinfo->constraint_root_id = constraintOid;
    2442         2746 :     riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
    2443              :                                                  ObjectIdGetDatum(constraintOid));
    2444         2746 :     riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
    2445              :                                                   ObjectIdGetDatum(riinfo->constraint_root_id));
    2446         2746 :     memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
    2447         2746 :     riinfo->pk_relid = conForm->confrelid;
    2448         2746 :     riinfo->fk_relid = conForm->conrelid;
    2449         2746 :     riinfo->confupdtype = conForm->confupdtype;
    2450         2746 :     riinfo->confdeltype = conForm->confdeltype;
    2451         2746 :     riinfo->confmatchtype = conForm->confmatchtype;
    2452         2746 :     riinfo->hasperiod = conForm->conperiod;
    2453              : 
    2454         2746 :     DeconstructFkConstraintRow(tup,
    2455              :                                &riinfo->nkeys,
    2456         2746 :                                riinfo->fk_attnums,
    2457         2746 :                                riinfo->pk_attnums,
    2458         2746 :                                riinfo->pf_eq_oprs,
    2459         2746 :                                riinfo->pp_eq_oprs,
    2460         2746 :                                riinfo->ff_eq_oprs,
    2461              :                                &riinfo->ndelsetcols,
    2462         2746 :                                riinfo->confdelsetcols);
    2463              : 
    2464              :     /*
    2465              :      * For temporal FKs, get the operators and functions we need. We ask the
    2466              :      * opclass of the PK element for these. This all gets cached (as does the
    2467              :      * generated plan), so there's no performance issue.
    2468              :      */
    2469         2746 :     if (riinfo->hasperiod)
    2470              :     {
    2471          141 :         Oid         opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
    2472              : 
    2473          141 :         FindFKPeriodOpers(opclass,
    2474              :                           &riinfo->period_contained_by_oper,
    2475              :                           &riinfo->agged_period_contained_by_oper,
    2476              :                           &riinfo->period_intersect_oper);
    2477              :     }
    2478              : 
    2479              :     /* Metadata used by fast path. */
    2480         2746 :     riinfo->conindid = conForm->conindid;
    2481         2746 :     riinfo->pk_is_partitioned =
    2482         2746 :         (get_rel_relkind(riinfo->pk_relid) == RELKIND_PARTITIONED_TABLE);
    2483              : 
    2484         2746 :     ReleaseSysCache(tup);
    2485              : 
    2486              :     /*
    2487              :      * For efficient processing of invalidation messages below, we keep a
    2488              :      * doubly-linked count list of all currently valid entries.
    2489              :      */
    2490         2746 :     dclist_push_tail(&ri_constraint_cache_valid_list, &riinfo->valid_link);
    2491              : 
    2492         2746 :     riinfo->valid = true;
    2493              : 
    2494         2746 :     riinfo->fpmeta = NULL;
    2495              : 
    2496         2746 :     return riinfo;
    2497              : }
    2498              : 
    2499              : /*
    2500              :  * get_ri_constraint_root
    2501              :  *      Returns the OID of the constraint's root parent
    2502              :  */
    2503              : static Oid
    2504          964 : get_ri_constraint_root(Oid constrOid)
    2505              : {
    2506              :     for (;;)
    2507          232 :     {
    2508              :         HeapTuple   tuple;
    2509              :         Oid         constrParentOid;
    2510              : 
    2511         1196 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
    2512         1196 :         if (!HeapTupleIsValid(tuple))
    2513            0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
    2514         1196 :         constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
    2515         1196 :         ReleaseSysCache(tuple);
    2516         1196 :         if (!OidIsValid(constrParentOid))
    2517          964 :             break;              /* we reached the root constraint */
    2518          232 :         constrOid = constrParentOid;
    2519              :     }
    2520          964 :     return constrOid;
    2521              : }
    2522              : 
    2523              : /*
    2524              :  * Callback for pg_constraint inval events
    2525              :  *
    2526              :  * While most syscache callbacks just flush all their entries, pg_constraint
    2527              :  * gets enough update traffic that it's probably worth being smarter.
    2528              :  * Invalidate any ri_constraint_cache entry associated with the syscache
    2529              :  * entry with the specified hash value, or all entries if hashvalue == 0.
    2530              :  *
    2531              :  * Note: at the time a cache invalidation message is processed there may be
    2532              :  * active references to the cache.  Because of this we never remove entries
    2533              :  * from the cache, but only mark them invalid, which is harmless to active
    2534              :  * uses.  (Any query using an entry should hold a lock sufficient to keep that
    2535              :  * data from changing under it --- but we may get cache flushes anyway.)
    2536              :  */
    2537              : static void
    2538        57437 : InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid,
    2539              :                                   uint32 hashvalue)
    2540              : {
    2541              :     dlist_mutable_iter iter;
    2542              : 
    2543              :     Assert(ri_constraint_cache != NULL);
    2544              : 
    2545              :     /*
    2546              :      * If the list of currently valid entries gets excessively large, we mark
    2547              :      * them all invalid so we can empty the list.  This arrangement avoids
    2548              :      * O(N^2) behavior in situations where a session touches many foreign keys
    2549              :      * and also does many ALTER TABLEs, such as a restore from pg_dump.
    2550              :      */
    2551        57437 :     if (dclist_count(&ri_constraint_cache_valid_list) > 1000)
    2552            0 :         hashvalue = 0;          /* pretend it's a cache reset */
    2553              : 
    2554       243344 :     dclist_foreach_modify(iter, &ri_constraint_cache_valid_list)
    2555              :     {
    2556       185907 :         RI_ConstraintInfo *riinfo = dclist_container(RI_ConstraintInfo,
    2557              :                                                      valid_link, iter.cur);
    2558              : 
    2559              :         /*
    2560              :          * We must invalidate not only entries directly matching the given
    2561              :          * hash value, but also child entries, in case the invalidation
    2562              :          * affects a root constraint.
    2563              :          */
    2564       185907 :         if (hashvalue == 0 ||
    2565       185864 :             riinfo->oidHashValue == hashvalue ||
    2566       184134 :             riinfo->rootHashValue == hashvalue)
    2567              :         {
    2568         1989 :             riinfo->valid = false;
    2569         1989 :             if (riinfo->fpmeta)
    2570              :             {
    2571          648 :                 pfree(riinfo->fpmeta);
    2572          648 :                 riinfo->fpmeta = NULL;
    2573              :             }
    2574              :             /* Remove invalidated entries from the list, too */
    2575         1989 :             dclist_delete_from(&ri_constraint_cache_valid_list, iter.cur);
    2576              :         }
    2577              :     }
    2578        57437 : }
    2579              : 
    2580              : 
    2581              : /*
    2582              :  * Prepare execution plan for a query to enforce an RI restriction
    2583              :  */
    2584              : static SPIPlanPtr
    2585         1188 : ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
    2586              :              RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
    2587              : {
    2588              :     SPIPlanPtr  qplan;
    2589              :     Relation    query_rel;
    2590              :     Oid         save_userid;
    2591              :     int         save_sec_context;
    2592              : 
    2593              :     /*
    2594              :      * Use the query type code to determine whether the query is run against
    2595              :      * the PK or FK table; we'll do the check as that table's owner
    2596              :      */
    2597         1188 :     if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
    2598          624 :         query_rel = pk_rel;
    2599              :     else
    2600          564 :         query_rel = fk_rel;
    2601              : 
    2602              :     /* Switch to proper UID to perform check as */
    2603         1188 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2604         1188 :     SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
    2605              :                            save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
    2606              :                            SECURITY_NOFORCE_RLS);
    2607              : 
    2608              :     /* Create the plan */
    2609         1188 :     qplan = SPI_prepare(querystr, nargs, argtypes);
    2610              : 
    2611         1188 :     if (qplan == NULL)
    2612            0 :         elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
    2613              : 
    2614              :     /* Restore UID and security context */
    2615         1188 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2616              : 
    2617              :     /* Save the plan */
    2618         1188 :     SPI_keepplan(qplan);
    2619         1188 :     ri_HashPreparedPlan(qkey, qplan);
    2620              : 
    2621         1188 :     return qplan;
    2622              : }
    2623              : 
    2624              : /*
    2625              :  * Perform a query to enforce an RI restriction
    2626              :  */
    2627              : static bool
    2628         2475 : ri_PerformCheck(const RI_ConstraintInfo *riinfo,
    2629              :                 RI_QueryKey *qkey, SPIPlanPtr qplan,
    2630              :                 Relation fk_rel, Relation pk_rel,
    2631              :                 TupleTableSlot *oldslot, TupleTableSlot *newslot,
    2632              :                 bool is_restrict,
    2633              :                 bool detectNewRows, int expect_OK)
    2634              : {
    2635              :     Relation    query_rel,
    2636              :                 source_rel;
    2637              :     bool        source_is_pk;
    2638              :     Snapshot    test_snapshot;
    2639              :     Snapshot    crosscheck_snapshot;
    2640              :     int         limit;
    2641              :     int         spi_result;
    2642              :     Oid         save_userid;
    2643              :     int         save_sec_context;
    2644              :     Datum       vals[RI_MAX_NUMKEYS * 2];
    2645              :     char        nulls[RI_MAX_NUMKEYS * 2];
    2646              : 
    2647              :     /*
    2648              :      * Use the query type code to determine whether the query is run against
    2649              :      * the PK or FK table; we'll do the check as that table's owner
    2650              :      */
    2651         2475 :     if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
    2652         1313 :         query_rel = pk_rel;
    2653              :     else
    2654         1162 :         query_rel = fk_rel;
    2655              : 
    2656              :     /*
    2657              :      * The values for the query are taken from the table on which the trigger
    2658              :      * is called - it is normally the other one with respect to query_rel. An
    2659              :      * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
    2660              :      * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK).  We might eventually
    2661              :      * need some less klugy way to determine this.
    2662              :      */
    2663         2475 :     if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
    2664              :     {
    2665          790 :         source_rel = fk_rel;
    2666          790 :         source_is_pk = false;
    2667              :     }
    2668              :     else
    2669              :     {
    2670         1685 :         source_rel = pk_rel;
    2671         1685 :         source_is_pk = true;
    2672              :     }
    2673              : 
    2674              :     /* Extract the parameters to be passed into the query */
    2675         2475 :     if (newslot)
    2676              :     {
    2677          934 :         ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
    2678              :                          vals, nulls);
    2679          934 :         if (oldslot)
    2680          144 :             ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
    2681          144 :                              vals + riinfo->nkeys, nulls + riinfo->nkeys);
    2682              :     }
    2683              :     else
    2684              :     {
    2685         1541 :         ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
    2686              :                          vals, nulls);
    2687              :     }
    2688              : 
    2689              :     /*
    2690              :      * In READ COMMITTED mode, we just need to use an up-to-date regular
    2691              :      * snapshot, and we will see all rows that could be interesting. But in
    2692              :      * transaction-snapshot mode, we can't change the transaction snapshot. If
    2693              :      * the caller passes detectNewRows == false then it's okay to do the query
    2694              :      * with the transaction snapshot; otherwise we use a current snapshot, and
    2695              :      * tell the executor to error out if it finds any rows under the current
    2696              :      * snapshot that wouldn't be visible per the transaction snapshot.  Note
    2697              :      * that SPI_execute_snapshot will register the snapshots, so we don't need
    2698              :      * to bother here.
    2699              :      */
    2700         2475 :     if (IsolationUsesXactSnapshot() && detectNewRows)
    2701              :     {
    2702           36 :         CommandCounterIncrement();  /* be sure all my own work is visible */
    2703           36 :         test_snapshot = GetLatestSnapshot();
    2704           36 :         crosscheck_snapshot = GetTransactionSnapshot();
    2705              :     }
    2706              :     else
    2707              :     {
    2708              :         /* the default SPI behavior is okay */
    2709         2439 :         test_snapshot = InvalidSnapshot;
    2710         2439 :         crosscheck_snapshot = InvalidSnapshot;
    2711              :     }
    2712              : 
    2713              :     /*
    2714              :      * If this is a select query (e.g., for a 'no action' or 'restrict'
    2715              :      * trigger), we only need to see if there is a single row in the table,
    2716              :      * matching the key.  Otherwise, limit = 0 - because we want the query to
    2717              :      * affect ALL the matching rows.
    2718              :      */
    2719         2475 :     limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
    2720              : 
    2721              :     /* Switch to proper UID to perform check as */
    2722         2475 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2723         2475 :     SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
    2724              :                            save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
    2725              :                            SECURITY_NOFORCE_RLS);
    2726              : 
    2727              :     /*
    2728              :      * Finally we can run the query.
    2729              :      *
    2730              :      * Set fire_triggers to false to ensure that AFTER triggers are queued in
    2731              :      * the outer query's after-trigger context and fire after all RI updates
    2732              :      * on the same row are complete, rather than immediately.
    2733              :      */
    2734         2475 :     spi_result = SPI_execute_snapshot(qplan,
    2735              :                                       vals, nulls,
    2736              :                                       test_snapshot, crosscheck_snapshot,
    2737              :                                       false, false, limit);
    2738              : 
    2739              :     /* Restore UID and security context */
    2740         2465 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2741              : 
    2742              :     /* Check result */
    2743         2465 :     if (spi_result < 0)
    2744            0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    2745              : 
    2746         2465 :     if (expect_OK >= 0 && spi_result != expect_OK)
    2747            0 :         ereport(ERROR,
    2748              :                 (errcode(ERRCODE_INTERNAL_ERROR),
    2749              :                  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
    2750              :                         RelationGetRelationName(pk_rel),
    2751              :                         NameStr(riinfo->conname),
    2752              :                         RelationGetRelationName(fk_rel)),
    2753              :                  errhint("This is most likely due to a rule having rewritten the query.")));
    2754              : 
    2755              :     /* XXX wouldn't it be clearer to do this part at the caller? */
    2756         2465 :     if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
    2757         1529 :         expect_OK == SPI_OK_SELECT &&
    2758         1529 :         (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
    2759          462 :         ri_ReportViolation(riinfo,
    2760              :                            pk_rel, fk_rel,
    2761              :                            newslot ? newslot : oldslot,
    2762              :                            NULL,
    2763              :                            qkey->constr_queryno, is_restrict, false);
    2764              : 
    2765         2003 :     return SPI_processed != 0;
    2766              : }
    2767              : 
    2768              : /*
    2769              :  * ri_FastPathCheck
    2770              :  *      Perform per row FK existence check via direct index probe,
    2771              :  *      bypassing SPI.
    2772              :  *
    2773              :  * If no matching PK row exists, report the violation via ri_ReportViolation(),
    2774              :  * otherwise, the function returns normally.
    2775              :  *
    2776              :  * Note: This is only used by the ALTER TABLE validation path. Other paths use
    2777              :  * ri_FastPathBatchAdd().
    2778              :  */
    2779              : static void
    2780           44 : ri_FastPathCheck(RI_ConstraintInfo *riinfo,
    2781              :                  Relation fk_rel, TupleTableSlot *newslot)
    2782              : {
    2783              :     Relation    pk_rel;
    2784              :     Relation    idx_rel;
    2785              :     IndexScanDesc scandesc;
    2786              :     TupleTableSlot *slot;
    2787              :     Datum       pk_vals[INDEX_MAX_KEYS];
    2788              :     char        pk_nulls[INDEX_MAX_KEYS];
    2789              :     ScanKeyData skey[INDEX_MAX_KEYS];
    2790           44 :     bool        found = false;
    2791              :     Oid         saved_userid;
    2792              :     int         saved_sec_context;
    2793              :     Snapshot    snapshot;
    2794              : 
    2795              :     /*
    2796              :      * Advance the command counter so the snapshot sees the effects of prior
    2797              :      * triggers in this statement.  Mirrors what the SPI path does in
    2798              :      * ri_PerformCheck().
    2799              :      */
    2800           44 :     CommandCounterIncrement();
    2801           44 :     snapshot = RegisterSnapshot(GetTransactionSnapshot());
    2802              : 
    2803           44 :     pk_rel = table_open(riinfo->pk_relid, RowShareLock);
    2804           44 :     idx_rel = index_open(riinfo->conindid, AccessShareLock);
    2805              : 
    2806           44 :     slot = table_slot_create(pk_rel, NULL);
    2807           44 :     scandesc = index_beginscan(pk_rel, idx_rel,
    2808              :                                snapshot, NULL,
    2809              :                                riinfo->nkeys, 0,
    2810              :                                SO_NONE);
    2811              : 
    2812           44 :     GetUserIdAndSecContext(&saved_userid, &saved_sec_context);
    2813           44 :     SetUserIdAndSecContext(RelationGetForm(pk_rel)->relowner,
    2814              :                            saved_sec_context |
    2815              :                            SECURITY_LOCAL_USERID_CHANGE |
    2816              :                            SECURITY_NOFORCE_RLS);
    2817           44 :     ri_CheckPermissions(pk_rel);
    2818              : 
    2819           44 :     if (riinfo->fpmeta == NULL)
    2820              :     {
    2821              :         /* Reload to ensure it's valid. */
    2822            8 :         riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
    2823            8 :         ri_populate_fastpath_metadata(riinfo, fk_rel, idx_rel);
    2824              :     }
    2825              :     Assert(riinfo->fpmeta);
    2826           44 :     ri_ExtractValues(fk_rel, newslot, riinfo, false, pk_vals, pk_nulls);
    2827           44 :     build_index_scankeys(riinfo, idx_rel, pk_vals, pk_nulls, skey);
    2828           44 :     found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, slot,
    2829              :                                 snapshot, riinfo, skey, riinfo->nkeys);
    2830           44 :     SetUserIdAndSecContext(saved_userid, saved_sec_context);
    2831           44 :     index_endscan(scandesc);
    2832           44 :     ExecDropSingleTupleTableSlot(slot);
    2833           44 :     UnregisterSnapshot(snapshot);
    2834              : 
    2835           44 :     if (!found)
    2836            4 :         ri_ReportViolation(riinfo, pk_rel, fk_rel,
    2837              :                            newslot, NULL,
    2838              :                            RI_PLAN_CHECK_LOOKUPPK, false, false);
    2839              : 
    2840           40 :     index_close(idx_rel, NoLock);
    2841           40 :     table_close(pk_rel, NoLock);
    2842           40 : }
    2843              : 
    2844              : /*
    2845              :  * ri_FastPathBatchAdd
    2846              :  *      Buffer a FK row for batched probing.
    2847              :  *
    2848              :  * Adds the row to the batch buffer.  When the buffer is full, flushes all
    2849              :  * buffered rows by probing the PK index.  Any violation is reported
    2850              :  * immediately during the flush via ri_ReportViolation (which does not return).
    2851              :  *
    2852              :  * Uses the per-batch cache (RI_FastPathEntry) to avoid per-row relation
    2853              :  * open/close, slot creation, etc.
    2854              :  *
    2855              :  * The batch is also flushed at end of trigger-firing cycle via
    2856              :  * ri_FastPathEndBatch().
    2857              :  */
    2858              : static void
    2859       603651 : ri_FastPathBatchAdd(RI_ConstraintInfo *riinfo,
    2860              :                     Relation fk_rel, TupleTableSlot *newslot)
    2861              : {
    2862       603651 :     RI_FastPathEntry *fpentry = ri_FastPathGetEntry(riinfo, fk_rel);
    2863              :     MemoryContext oldcxt;
    2864              : 
    2865       603651 :     oldcxt = MemoryContextSwitchTo(fpentry->flush_cxt);
    2866      1207302 :     fpentry->batch[fpentry->batch_count] =
    2867       603651 :         ExecCopySlotHeapTuple(newslot);
    2868       603651 :     fpentry->batch_count++;
    2869       603651 :     MemoryContextSwitchTo(oldcxt);
    2870              : 
    2871       603651 :     if (fpentry->batch_count >= RI_FASTPATH_BATCH_SIZE)
    2872         9392 :         ri_FastPathBatchFlush(fpentry, fk_rel, riinfo);
    2873       603651 : }
    2874              : 
    2875              : /*
    2876              :  * ri_FastPathBatchFlush
    2877              :  *      Flush all buffered FK rows by probing the PK index.
    2878              :  *
    2879              :  * Dispatches to ri_FastPathFlushArray() for single-column FKs
    2880              :  * (using SK_SEARCHARRAY) or ri_FastPathFlushLoop() for multi-column
    2881              :  * FKs (per-row probing).  Violations are reported immediately via
    2882              :  * ri_ReportViolation(), which does not return.
    2883              :  */
    2884              : static void
    2885        11107 : ri_FastPathBatchFlush(RI_FastPathEntry *fpentry, Relation fk_rel,
    2886              :                       RI_ConstraintInfo *riinfo)
    2887              : {
    2888        11107 :     Relation    pk_rel = fpentry->pk_rel;
    2889        11107 :     Relation    idx_rel = fpentry->idx_rel;
    2890        11107 :     TupleTableSlot *fk_slot = fpentry->fk_slot;
    2891              :     Snapshot    snapshot;
    2892              :     IndexScanDesc scandesc;
    2893              :     Oid         saved_userid;
    2894              :     int         saved_sec_context;
    2895              :     MemoryContext oldcxt;
    2896              :     int         violation_index;
    2897              : 
    2898        11107 :     if (fpentry->batch_count == 0)
    2899            0 :         return;
    2900              : 
    2901              :     /*
    2902              :      * CCI and security context switch are done once for the entire batch.
    2903              :      * Per-row CCI is unnecessary because by the time a flush runs, all AFTER
    2904              :      * triggers for the buffered rows have already fired (trigger invocations
    2905              :      * strictly alternate per row), so a single CCI advances past all their
    2906              :      * effects.  Per-row security context switch is unnecessary because each
    2907              :      * row's probe runs entirely as the PK table owner, same as the SPI path
    2908              :      * -- the only difference is that the SPI path sets and restores the
    2909              :      * context per row whereas we do it once around the whole batch.
    2910              :      */
    2911        11107 :     CommandCounterIncrement();
    2912        11107 :     snapshot = RegisterSnapshot(GetTransactionSnapshot());
    2913              : 
    2914              :     /*
    2915              :      * build_index_scankeys() may palloc cast results for cross-type FKs. Use
    2916              :      * the entry's short-lived flush context so these don't accumulate across
    2917              :      * batches.
    2918              :      */
    2919        11107 :     oldcxt = MemoryContextSwitchTo(fpentry->flush_cxt);
    2920              : 
    2921        11107 :     scandesc = index_beginscan(pk_rel, idx_rel, snapshot, NULL,
    2922              :                                riinfo->nkeys, 0, SO_NONE);
    2923              : 
    2924        11107 :     GetUserIdAndSecContext(&saved_userid, &saved_sec_context);
    2925        11107 :     SetUserIdAndSecContext(RelationGetForm(pk_rel)->relowner,
    2926              :                            saved_sec_context |
    2927              :                            SECURITY_LOCAL_USERID_CHANGE |
    2928              :                            SECURITY_NOFORCE_RLS);
    2929              : 
    2930              :     /*
    2931              :      * Check that the current user has permission to access pk_rel. Done here
    2932              :      * rather than at entry creation so that permission changes between
    2933              :      * flushes are respected, matching the per-row behavior of the SPI path,
    2934              :      * albeit checked once per flush rather than once per row, like in
    2935              :      * ri_FastPathCheck().
    2936              :      */
    2937        11107 :     ri_CheckPermissions(pk_rel);
    2938              : 
    2939        11103 :     if (riinfo->fpmeta == NULL)
    2940              :     {
    2941              :         /* Reload to ensure it's valid. */
    2942          943 :         riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
    2943          943 :         ri_populate_fastpath_metadata(riinfo, fk_rel, idx_rel);
    2944              :     }
    2945              :     Assert(riinfo->fpmeta);
    2946              : 
    2947              :     /* Skip array overhead for single-row batches. */
    2948        11103 :     if (riinfo->nkeys == 1 && fpentry->batch_count > 1)
    2949         9533 :         violation_index = ri_FastPathFlushArray(fpentry, fk_slot, riinfo,
    2950              :                                                 fk_rel, snapshot, scandesc);
    2951              :     else
    2952         1570 :         violation_index = ri_FastPathFlushLoop(fpentry, fk_slot, riinfo,
    2953              :                                                fk_rel, snapshot, scandesc);
    2954              : 
    2955        11096 :     SetUserIdAndSecContext(saved_userid, saved_sec_context);
    2956        11096 :     UnregisterSnapshot(snapshot);
    2957        11096 :     index_endscan(scandesc);
    2958              : 
    2959        11096 :     if (violation_index >= 0)
    2960              :     {
    2961          282 :         ExecStoreHeapTuple(fpentry->batch[violation_index], fk_slot, false);
    2962          282 :         ri_ReportViolation(riinfo, pk_rel, fk_rel,
    2963              :                            fk_slot, NULL,
    2964              :                            RI_PLAN_CHECK_LOOKUPPK, false, false);
    2965              :     }
    2966              : 
    2967        10814 :     MemoryContextReset(fpentry->flush_cxt);
    2968        10814 :     MemoryContextSwitchTo(oldcxt);
    2969              : 
    2970              :     /* Reset. */
    2971        10814 :     fpentry->batch_count = 0;
    2972              : }
    2973              : 
    2974              : /*
    2975              :  * ri_FastPathFlushLoop
    2976              :  *      Multi-column fallback: probe the index once per buffered row.
    2977              :  *
    2978              :  * Used for composite foreign keys where SK_SEARCHARRAY does not
    2979              :  * apply, and also for single-row batches of single-column FKs where
    2980              :  * the array overhead is not worth it.
    2981              :  *
    2982              :  * Returns the index of the first violating row in the batch array, or -1 if
    2983              :  * all rows are valid.
    2984              :  */
    2985              : static int
    2986         1570 : ri_FastPathFlushLoop(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot,
    2987              :                      const RI_ConstraintInfo *riinfo, Relation fk_rel,
    2988              :                      Snapshot snapshot, IndexScanDesc scandesc)
    2989              : {
    2990         1570 :     Relation    pk_rel = fpentry->pk_rel;
    2991         1570 :     Relation    idx_rel = fpentry->idx_rel;
    2992         1570 :     TupleTableSlot *pk_slot = fpentry->pk_slot;
    2993              :     Datum       pk_vals[INDEX_MAX_KEYS];
    2994              :     char        pk_nulls[INDEX_MAX_KEYS];
    2995              :     ScanKeyData skey[INDEX_MAX_KEYS];
    2996         1570 :     bool        found = true;
    2997              : 
    2998         3247 :     for (int i = 0; i < fpentry->batch_count; i++)
    2999              :     {
    3000         1962 :         ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
    3001         1962 :         ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
    3002         1962 :         build_index_scankeys(riinfo, idx_rel, pk_vals, pk_nulls, skey);
    3003              : 
    3004         1962 :         found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, pk_slot,
    3005         1962 :                                     snapshot, riinfo, skey, riinfo->nkeys);
    3006              : 
    3007              :         /* Report first unmatched row */
    3008         1955 :         if (!found)
    3009          278 :             return i;
    3010              :     }
    3011              : 
    3012              :     /* All pass. */
    3013         1285 :     return -1;
    3014              : }
    3015              : 
    3016              : /*
    3017              :  * ri_FastPathFlushArray
    3018              :  *      Single-column fast path using SK_SEARCHARRAY.
    3019              :  *
    3020              :  * Builds an array of FK values and does one index scan with
    3021              :  * SK_SEARCHARRAY.  The index AM sorts and deduplicates the array
    3022              :  * internally, then walks matching leaf pages in order.  Each
    3023              :  * matched PK tuple is locked and rechecked as before; a matched[]
    3024              :  * bitmap tracks which batch items were satisfied.
    3025              :  *
    3026              :  * Returns the index of the first violating row in the batch array, or -1 if
    3027              :  * all rows are valid.
    3028              :  */
    3029              : static int
    3030         9533 : ri_FastPathFlushArray(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot,
    3031              :                       const RI_ConstraintInfo *riinfo, Relation fk_rel,
    3032              :                       Snapshot snapshot, IndexScanDesc scandesc)
    3033              : {
    3034         9533 :     FastPathMeta *fpmeta = riinfo->fpmeta;
    3035         9533 :     Relation    pk_rel = fpentry->pk_rel;
    3036         9533 :     Relation    idx_rel = fpentry->idx_rel;
    3037         9533 :     TupleTableSlot *pk_slot = fpentry->pk_slot;
    3038              :     Datum       search_vals[RI_FASTPATH_BATCH_SIZE];
    3039              :     bool        matched[RI_FASTPATH_BATCH_SIZE];
    3040         9533 :     int         nvals = fpentry->batch_count;
    3041              :     Datum       pk_vals[INDEX_MAX_KEYS];
    3042              :     char        pk_nulls[INDEX_MAX_KEYS];
    3043              :     ScanKeyData skey[1];
    3044              :     FmgrInfo   *cast_func_finfo;
    3045              :     FmgrInfo   *eq_opr_finfo;
    3046              :     Oid         elem_type;
    3047              :     int16       elem_len;
    3048              :     bool        elem_byval;
    3049              :     char        elem_align;
    3050              :     ArrayType  *arr;
    3051              : 
    3052              :     Assert(fpmeta);
    3053              : 
    3054         9533 :     memset(matched, 0, nvals * sizeof(bool));
    3055              : 
    3056              :     /*
    3057              :      * Extract FK values, casting to the operator's expected input type if
    3058              :      * needed (e.g. int8 FK -> int4 for int48eq).
    3059              :      */
    3060         9533 :     cast_func_finfo = &fpmeta->cast_func_finfo[0];
    3061         9533 :     eq_opr_finfo = &fpmeta->eq_opr_finfo[0];
    3062       611202 :     for (int i = 0; i < nvals; i++)
    3063              :     {
    3064       601669 :         ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
    3065       601669 :         ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
    3066              : 
    3067              :         /* Cast if needed (e.g. int8 FK -> numeric PK) */
    3068       601669 :         if (OidIsValid(cast_func_finfo->fn_oid))
    3069            0 :             search_vals[i] = FunctionCall3(cast_func_finfo,
    3070              :                                            pk_vals[0],
    3071              :                                            Int32GetDatum(-1),
    3072              :                                            BoolGetDatum(false));
    3073              :         else
    3074       601669 :             search_vals[i] = pk_vals[0];
    3075              :     }
    3076              : 
    3077              :     /*
    3078              :      * Array element type must match the operator's right-hand input type,
    3079              :      * which is what the index comparison expects on the search side.
    3080              :      * ri_populate_fastpath_metadata() stores exactly this via
    3081              :      * get_op_opfamily_properties(), which returns the operator's right-hand
    3082              :      * type as the subtype for cross-type operators (e.g. int8 for int48eq)
    3083              :      * and the common type for same-type operators.
    3084              :      */
    3085         9533 :     elem_type = fpmeta->subtypes[0];
    3086              :     Assert(OidIsValid(elem_type));
    3087         9533 :     get_typlenbyvalalign(elem_type, &elem_len, &elem_byval, &elem_align);
    3088              : 
    3089         9533 :     arr = construct_array(search_vals, nvals,
    3090              :                           elem_type, elem_len, elem_byval, elem_align);
    3091              : 
    3092              :     /*
    3093              :      * Build scan key with SK_SEARCHARRAY.  The index AM code will internally
    3094              :      * sort and deduplicate, then walk leaf pages in order.
    3095              :      *
    3096              :      * PK indexes are always btree, which supports SK_SEARCHARRAY.
    3097              :      *
    3098              :      * This path handles single-column FKs only, so index_attnos[0] == 1.
    3099              :      */
    3100              :     Assert(idx_rel->rd_indam->amsearcharray);
    3101              :     Assert(fpmeta->index_attnos[0] == 1);
    3102         9533 :     ScanKeyEntryInitialize(&skey[0],
    3103              :                            SK_SEARCHARRAY,
    3104         9533 :                            fpmeta->index_attnos[0],
    3105         9533 :                            fpmeta->strats[0],
    3106              :                            fpmeta->subtypes[0],
    3107         9533 :                            idx_rel->rd_indcollation[fpmeta->index_attnos[0] - 1],
    3108              :                            fpmeta->regops[0],
    3109              :                            PointerGetDatum(arr));
    3110              : 
    3111         9533 :     index_rescan(scandesc, skey, 1, NULL, 0);
    3112              : 
    3113              :     /*
    3114              :      * Walk all matches.  The index AM returns them in index order.  For each
    3115              :      * match, find which batch item(s) it satisfies.
    3116              :      */
    3117       420040 :     while (index_getnext_slot(scandesc, ForwardScanDirection, pk_slot))
    3118              :     {
    3119              :         Datum       found_val;
    3120              :         bool        found_null;
    3121              :         bool        concurrently_updated;
    3122              :         ScanKeyData recheck_skey[1];
    3123              : 
    3124       410507 :         if (!ri_LockPKTuple(pk_rel, pk_slot, snapshot, &concurrently_updated))
    3125            0 :             continue;
    3126              : 
    3127              :         /* Extract the PK value from the matched and locked tuple */
    3128       410507 :         found_val = slot_getattr(pk_slot, riinfo->pk_attnums[0], &found_null);
    3129              :         Assert(!found_null);
    3130              : 
    3131       410507 :         if (concurrently_updated)
    3132              :         {
    3133              :             /*
    3134              :              * Build a single-key scankey for recheck.  We need the actual PK
    3135              :              * value that was found, not the FK search value.
    3136              :              */
    3137            0 :             ScanKeyEntryInitialize(&recheck_skey[0], 0, 1,
    3138            0 :                                    fpmeta->strats[0],
    3139              :                                    fpmeta->subtypes[0],
    3140            0 :                                    idx_rel->rd_indcollation[0],
    3141              :                                    fpmeta->regops[0],
    3142              :                                    found_val);
    3143            0 :             if (!recheck_matched_pk_tuple(idx_rel, recheck_skey, 1, pk_slot))
    3144            0 :                 continue;
    3145              :         }
    3146              : 
    3147              :         /*
    3148              :          * Linear scan to mark all batch items matching this PK value.
    3149              :          * O(batch_size) per match, O(batch_size^2) worst case -- fine for the
    3150              :          * current batch size of 64.
    3151              :          */
    3152     26657840 :         for (int i = 0; i < nvals; i++)
    3153              :         {
    3154     39671800 :             if (!matched[i] &&
    3155     13424467 :                 DatumGetBool(FunctionCall2Coll(eq_opr_finfo,
    3156     13424467 :                                                idx_rel->rd_indcollation[0],
    3157              :                                                found_val,
    3158              :                                                search_vals[i])))
    3159       601665 :                 matched[i] = true;
    3160              :         }
    3161              :     }
    3162              : 
    3163              :     /* Report first unmatched row */
    3164       611198 :     for (int i = 0; i < nvals; i++)
    3165       601669 :         if (!matched[i])
    3166            4 :             return i;
    3167              : 
    3168              :     /* All pass. */
    3169         9529 :     return -1;
    3170              : }
    3171              : 
    3172              : /*
    3173              :  * ri_FastPathProbeOne
    3174              :  *      Probe the PK index for one set of scan keys, lock the matching
    3175              :  *      tuple
    3176              :  *
    3177              :  * Returns true if a matching PK row was found, locked, and (if
    3178              :  * applicable) visible to the transaction snapshot.
    3179              :  */
    3180              : static bool
    3181         2006 : ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel,
    3182              :                     IndexScanDesc scandesc, TupleTableSlot *slot,
    3183              :                     Snapshot snapshot, const RI_ConstraintInfo *riinfo,
    3184              :                     ScanKeyData *skey, int nkeys)
    3185              : {
    3186         2006 :     bool        found = false;
    3187              : 
    3188         2006 :     index_rescan(scandesc, skey, nkeys, NULL, 0);
    3189              : 
    3190         2006 :     if (index_getnext_slot(scandesc, ForwardScanDirection, slot))
    3191              :     {
    3192              :         bool        concurrently_updated;
    3193              : 
    3194         1726 :         if (ri_LockPKTuple(pk_rel, slot, snapshot,
    3195              :                            &concurrently_updated))
    3196              :         {
    3197         1718 :             if (concurrently_updated)
    3198            2 :                 found = recheck_matched_pk_tuple(idx_rel, skey, nkeys, slot);
    3199              :             else
    3200         1716 :                 found = true;
    3201              :         }
    3202              :     }
    3203              : 
    3204         1999 :     return found;
    3205              : }
    3206              : 
    3207              : /*
    3208              :  * ri_LockPKTuple
    3209              :  *      Lock a PK tuple found by the fast-path index scan.
    3210              :  *
    3211              :  * Calls table_tuple_lock() directly with handling specific to RI checks.
    3212              :  * Returns true if the tuple was successfully locked.
    3213              :  *
    3214              :  * Sets *concurrently_updated to true if the locked tuple was reached
    3215              :  * by following an update chain (tmfd.traversed), indicating the caller
    3216              :  * should recheck the key.
    3217              :  */
    3218              : static bool
    3219       412233 : ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap,
    3220              :                bool *concurrently_updated)
    3221              : {
    3222              :     TM_FailureData tmfd;
    3223              :     TM_Result   result;
    3224       412233 :     int         lockflags = TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS;
    3225              : 
    3226       412233 :     *concurrently_updated = false;
    3227              : 
    3228       412233 :     if (!IsolationUsesXactSnapshot())
    3229       412211 :         lockflags |= TUPLE_LOCK_FLAG_FIND_LAST_VERSION;
    3230              : 
    3231       412233 :     result = table_tuple_lock(pk_rel, &slot->tts_tid, snap,
    3232              :                               slot, GetCurrentCommandId(false),
    3233              :                               LockTupleKeyShare, LockWaitBlock,
    3234              :                               lockflags, &tmfd);
    3235              : 
    3236       412230 :     switch (result)
    3237              :     {
    3238       412225 :         case TM_Ok:
    3239       412225 :             if (tmfd.traversed)
    3240            2 :                 *concurrently_updated = true;
    3241       412225 :             return true;
    3242              : 
    3243            4 :         case TM_Deleted:
    3244            4 :             if (IsolationUsesXactSnapshot())
    3245            3 :                 ereport(ERROR,
    3246              :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3247              :                          errmsg("could not serialize access due to concurrent delete")));
    3248            1 :             return false;
    3249              : 
    3250            1 :         case TM_Updated:
    3251            1 :             if (IsolationUsesXactSnapshot())
    3252            1 :                 ereport(ERROR,
    3253              :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3254              :                          errmsg("could not serialize access due to concurrent update")));
    3255              : 
    3256              :             /*
    3257              :              * In READ COMMITTED, FIND_LAST_VERSION should have chased the
    3258              :              * chain and returned TM_Ok.  Getting here means something
    3259              :              * unexpected -- fall through to error.
    3260              :              */
    3261            0 :             elog(ERROR, "unexpected table_tuple_lock status: %u", result);
    3262              :             break;
    3263              : 
    3264            0 :         case TM_SelfModified:
    3265              : 
    3266              :             /*
    3267              :              * The current command or a later command in this transaction
    3268              :              * modified the PK row.  This shouldn't normally happen during an
    3269              :              * FK check (we're not modifying pk_rel), but handle it safely by
    3270              :              * treating the tuple as not found.
    3271              :              */
    3272            0 :             return false;
    3273              : 
    3274            0 :         case TM_Invisible:
    3275            0 :             elog(ERROR, "attempted to lock invisible tuple");
    3276              :             break;
    3277              : 
    3278            0 :         default:
    3279            0 :             elog(ERROR, "unrecognized table_tuple_lock status: %u", result);
    3280              :             break;
    3281              :     }
    3282              : 
    3283              :     return false;               /* keep compiler quiet */
    3284              : }
    3285              : 
    3286              : static bool
    3287       604485 : ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo)
    3288              : {
    3289              :     /*
    3290              :      * Partitioned referenced tables are skipped for simplicity, since they
    3291              :      * require routing the probe through the correct partition using
    3292              :      * PartitionDirectory.
    3293              :      */
    3294       604485 :     if (riinfo->pk_is_partitioned)
    3295          639 :         return false;
    3296              : 
    3297              :     /*
    3298              :      * Temporal foreign keys use range overlap and containment semantics (&&,
    3299              :      * <@, range_agg()) that inherently involve aggregation and multiple-row
    3300              :      * reasoning, so they stay on the SPI path.
    3301              :      */
    3302       603846 :     if (riinfo->hasperiod)
    3303          151 :         return false;
    3304              : 
    3305       603695 :     return true;
    3306              : }
    3307              : 
    3308              : /*
    3309              :  * ri_CheckPermissions
    3310              :  *   Check that the current user has permissions to look into the schema of
    3311              :  *   and SELECT from 'query_rel'
    3312              :  */
    3313              : static void
    3314        11151 : ri_CheckPermissions(Relation query_rel)
    3315              : {
    3316              :     AclResult   aclresult;
    3317              : 
    3318              :     /* USAGE on schema. */
    3319        11151 :     aclresult = object_aclcheck(NamespaceRelationId,
    3320        11151 :                                 RelationGetNamespace(query_rel),
    3321              :                                 GetUserId(), ACL_USAGE);
    3322        11151 :     if (aclresult != ACLCHECK_OK)
    3323            0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
    3324            0 :                        get_namespace_name(RelationGetNamespace(query_rel)));
    3325              : 
    3326              :     /* SELECT on relation. */
    3327        11151 :     aclresult = pg_class_aclcheck(RelationGetRelid(query_rel), GetUserId(),
    3328              :                                   ACL_SELECT);
    3329        11151 :     if (aclresult != ACLCHECK_OK)
    3330            4 :         aclcheck_error(aclresult, OBJECT_TABLE,
    3331            4 :                        RelationGetRelationName(query_rel));
    3332        11147 : }
    3333              : 
    3334              : /*
    3335              :  * recheck_matched_pk_tuple
    3336              :  *      After following an update chain (tmfd.traversed), verify that
    3337              :  *      the locked PK tuple still matches the original search keys.
    3338              :  *
    3339              :  * A non-key update (e.g. changing a non-PK column) creates a new tuple version
    3340              :  * that we've now locked, but the key is unchanged -- that's fine.  A key
    3341              :  * update means the value we were looking for is gone, so we should treat it as
    3342              :  * not found.
    3343              :  */
    3344              : static bool
    3345            2 : recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys, int nkeys,
    3346              :                          TupleTableSlot *new_slot)
    3347              : {
    3348              :     /*
    3349              :      * TODO: BuildIndexInfo does a syscache lookup + palloc on every call.
    3350              :      * This only fires on the concurrent-update path (tmfd.traversed), which
    3351              :      * should be rare, so the cost is acceptable for now.  If profiling shows
    3352              :      * otherwise, cache the IndexInfo in FastPathMeta.
    3353              :      */
    3354            2 :     IndexInfo  *indexInfo = BuildIndexInfo(idxrel);
    3355              :     Datum       values[INDEX_MAX_KEYS];
    3356              :     bool        isnull[INDEX_MAX_KEYS];
    3357            2 :     bool        matched = true;
    3358              : 
    3359              :     /* PK indexes never have these. */
    3360              :     Assert(indexInfo->ii_Expressions == NIL &&
    3361              :            indexInfo->ii_ExclusionOps == NULL);
    3362              : 
    3363              :     /* Form the index values and isnull flags given the table tuple. */
    3364              :     Assert(nkeys == indexInfo->ii_NumIndexKeyAttrs);
    3365            2 :     FormIndexDatum(indexInfo, new_slot, NULL, values, isnull);
    3366            3 :     for (int i = 0; i < nkeys; i++)
    3367              :     {
    3368            2 :         ScanKeyData *skey = &skeys[i];
    3369              : 
    3370              :         /* A PK column can never be set to NULL. */
    3371              :         Assert(!isnull[i]);
    3372            2 :         if (!DatumGetBool(FunctionCall2Coll(&skey->sk_func,
    3373              :                                             skey->sk_collation,
    3374              :                                             values[i],
    3375              :                                             skey->sk_argument)))
    3376              :         {
    3377            1 :             matched = false;
    3378            1 :             break;
    3379              :         }
    3380              :     }
    3381              : 
    3382            2 :     return matched;
    3383              : }
    3384              : 
    3385              : /*
    3386              :  * build_index_scankeys
    3387              :  *      Build ScanKeys for a direct index probe of the PK's unique index.
    3388              :  *
    3389              :  * Uses cached compare entries, operator procedures, and strategy numbers
    3390              :  * from ri_populate_fastpath_metadata() rather than looking them up on
    3391              :  * each invocation.  Casts FK values to the operator's expected input
    3392              :  * type if needed.
    3393              :  */
    3394              : static void
    3395         2006 : build_index_scankeys(const RI_ConstraintInfo *riinfo,
    3396              :                      Relation idx_rel, Datum *pk_vals,
    3397              :                      char *pk_nulls, ScanKey skeys)
    3398              : {
    3399         2006 :     FastPathMeta *fpmeta = riinfo->fpmeta;
    3400              : 
    3401              :     Assert(fpmeta);
    3402              : 
    3403              :     /*
    3404              :      * May need to cast each of the individual values of the foreign key to
    3405              :      * the corresponding PK column's type if the equality operator demands it.
    3406              :      */
    3407         4896 :     for (int i = 0; i < riinfo->nkeys; i++)
    3408              :     {
    3409         2890 :         if (pk_nulls[i] != 'n' &&
    3410         2890 :             OidIsValid(fpmeta->cast_func_finfo[i].fn_oid))
    3411           20 :             pk_vals[i] = FunctionCall3(&fpmeta->cast_func_finfo[i],
    3412              :                                        pk_vals[i],
    3413              :                                        Int32GetDatum(-1),   /* typmod */
    3414              :                                        BoolGetDatum(false));    /* implicit coercion */
    3415              :     }
    3416              : 
    3417              :     /*
    3418              :      * Set up ScanKeys for the index scan. This is essentially how
    3419              :      * ExecIndexBuildScanKeys() sets them up.  Use the cached index_attnos and
    3420              :      * the corresponding collation since FK columns may be in a different
    3421              :      * order than PK index columns.  Place each scan key at the array position
    3422              :      * corresponding to its index column, since btree requires keys to be
    3423              :      * ordered by attribute number.
    3424              :      */
    3425         4896 :     for (int i = 0; i < riinfo->nkeys; i++)
    3426              :     {
    3427         2890 :         AttrNumber  pkattrno = fpmeta->index_attnos[i];
    3428         2890 :         int         skey_pos = pkattrno - 1;    /* 0-based array position */
    3429              : 
    3430         2890 :         ScanKeyEntryInitialize(&skeys[skey_pos], 0, pkattrno,
    3431         2890 :                                fpmeta->strats[i], fpmeta->subtypes[i],
    3432         2890 :                                idx_rel->rd_indcollation[skey_pos], fpmeta->regops[i],
    3433         2890 :                                pk_vals[i]);
    3434              :     }
    3435         2006 : }
    3436              : 
    3437              : /*
    3438              :  * ri_populate_fastpath_metadata
    3439              :  *      Cache per-key metadata needed by build_index_scankeys().
    3440              :  *
    3441              :  * Looks up the compare hash entry, operator procedure OID, and index
    3442              :  * strategy/subtype for each key column.  Called lazily on first use
    3443              :  * and persists for the lifetime of the RI_ConstraintInfo entry.
    3444              :  */
    3445              : static void
    3446          951 : ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo,
    3447              :                               Relation fk_rel, Relation idx_rel)
    3448              : {
    3449              :     FastPathMeta *fpmeta;
    3450          951 :     MemoryContext oldcxt = MemoryContextSwitchTo(TopMemoryContext);
    3451              : 
    3452              :     Assert(riinfo != NULL && riinfo->valid);
    3453              : 
    3454          951 :     fpmeta = palloc_object(FastPathMeta);
    3455         2050 :     for (int i = 0; i < riinfo->nkeys; i++)
    3456              :     {
    3457         1099 :         Oid         eq_opr = riinfo->pf_eq_oprs[i];
    3458         1099 :         Oid         typeid = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    3459              :         Oid         lefttype;
    3460         1099 :         RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
    3461              :         int         idx_col;
    3462              : 
    3463              :         /*
    3464              :          * Find the index column position for this constraint key.  The FK
    3465              :          * constraint may reference columns in a different order than they
    3466              :          * appear in the PK index, so we must map pk_attnums[i] to the
    3467              :          * corresponding index column position.
    3468              :          */
    3469         1271 :         for (idx_col = 0; idx_col < riinfo->nkeys; idx_col++)
    3470              :         {
    3471         1271 :             if (idx_rel->rd_index->indkey.values[idx_col] == riinfo->pk_attnums[i])
    3472         1099 :                 break;
    3473              :         }
    3474              :         Assert(idx_col < riinfo->nkeys);
    3475              : 
    3476              :         /* 1-based attribute number */
    3477         1099 :         fpmeta->index_attnos[i] = idx_col + 1;
    3478              : 
    3479         1099 :         fmgr_info_copy(&fpmeta->cast_func_finfo[i], &entry->cast_func_finfo,
    3480              :                        CurrentMemoryContext);
    3481         1099 :         fmgr_info_copy(&fpmeta->eq_opr_finfo[i], &entry->eq_opr_finfo,
    3482              :                        CurrentMemoryContext);
    3483         1099 :         fpmeta->regops[i] = get_opcode(eq_opr);
    3484              : 
    3485         1099 :         get_op_opfamily_properties(eq_opr,
    3486         1099 :                                    idx_rel->rd_opfamily[idx_col],
    3487              :                                    false,
    3488              :                                    &fpmeta->strats[i],
    3489              :                                    &lefttype,
    3490              :                                    &fpmeta->subtypes[i]);
    3491              :     }
    3492              : 
    3493          951 :     riinfo->fpmeta = fpmeta;
    3494          951 :     MemoryContextSwitchTo(oldcxt);
    3495          951 : }
    3496              : 
    3497              : /*
    3498              :  * Extract fields from a tuple into Datum/nulls arrays
    3499              :  */
    3500              : static void
    3501       606294 : ri_ExtractValues(Relation rel, TupleTableSlot *slot,
    3502              :                  const RI_ConstraintInfo *riinfo, bool rel_is_pk,
    3503              :                  Datum *vals, char *nulls)
    3504              : {
    3505              :     const int16 *attnums;
    3506              :     bool        isnull;
    3507              : 
    3508       606294 :     if (rel_is_pk)
    3509         1829 :         attnums = riinfo->pk_attnums;
    3510              :     else
    3511       604465 :         attnums = riinfo->fk_attnums;
    3512              : 
    3513      1214605 :     for (int i = 0; i < riinfo->nkeys; i++)
    3514              :     {
    3515       608311 :         vals[i] = slot_getattr(slot, attnums[i], &isnull);
    3516       608311 :         nulls[i] = isnull ? 'n' : ' ';
    3517              :     }
    3518       606294 : }
    3519              : 
    3520              : /*
    3521              :  * Produce an error report
    3522              :  *
    3523              :  * If the failed constraint was on insert/update to the FK table,
    3524              :  * we want the key names and values extracted from there, and the error
    3525              :  * message to look like 'key blah is not present in PK'.
    3526              :  * Otherwise, the attr names and values come from the PK table and the
    3527              :  * message looks like 'key blah is still referenced from FK'.
    3528              :  */
    3529              : static void
    3530          821 : ri_ReportViolation(const RI_ConstraintInfo *riinfo,
    3531              :                    Relation pk_rel, Relation fk_rel,
    3532              :                    TupleTableSlot *violatorslot, TupleDesc tupdesc,
    3533              :                    int queryno, bool is_restrict, bool partgone)
    3534              : {
    3535              :     StringInfoData key_names;
    3536              :     StringInfoData key_values;
    3537              :     bool        onfk;
    3538              :     const int16 *attnums;
    3539              :     Oid         rel_oid;
    3540              :     AclResult   aclresult;
    3541          821 :     bool        has_perm = true;
    3542              : 
    3543              :     /*
    3544              :      * Determine which relation to complain about.  If tupdesc wasn't passed
    3545              :      * by caller, assume the violator tuple came from there.
    3546              :      */
    3547          821 :     onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
    3548          821 :     if (onfk)
    3549              :     {
    3550          469 :         attnums = riinfo->fk_attnums;
    3551          469 :         rel_oid = fk_rel->rd_id;
    3552          469 :         if (tupdesc == NULL)
    3553          418 :             tupdesc = fk_rel->rd_att;
    3554              :     }
    3555              :     else
    3556              :     {
    3557          352 :         attnums = riinfo->pk_attnums;
    3558          352 :         rel_oid = pk_rel->rd_id;
    3559          352 :         if (tupdesc == NULL)
    3560          330 :             tupdesc = pk_rel->rd_att;
    3561              :     }
    3562              : 
    3563              :     /*
    3564              :      * Check permissions- if the user does not have access to view the data in
    3565              :      * any of the key columns then we don't include the errdetail() below.
    3566              :      *
    3567              :      * Check if RLS is enabled on the relation first.  If so, we don't return
    3568              :      * any specifics to avoid leaking data.
    3569              :      *
    3570              :      * Check table-level permissions next and, failing that, column-level
    3571              :      * privileges.
    3572              :      *
    3573              :      * When a partition at the referenced side is being detached/dropped, we
    3574              :      * needn't check, since the user must be the table owner anyway.
    3575              :      */
    3576          821 :     if (partgone)
    3577           22 :         has_perm = true;
    3578          799 :     else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
    3579              :     {
    3580          795 :         aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
    3581          795 :         if (aclresult != ACLCHECK_OK)
    3582              :         {
    3583              :             /* Try for column-level permissions */
    3584            0 :             for (int idx = 0; idx < riinfo->nkeys; idx++)
    3585              :             {
    3586            0 :                 aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
    3587              :                                                   GetUserId(),
    3588              :                                                   ACL_SELECT);
    3589              : 
    3590              :                 /* No access to the key */
    3591            0 :                 if (aclresult != ACLCHECK_OK)
    3592              :                 {
    3593            0 :                     has_perm = false;
    3594            0 :                     break;
    3595              :                 }
    3596              :             }
    3597              :         }
    3598              :     }
    3599              :     else
    3600            4 :         has_perm = false;
    3601              : 
    3602          821 :     if (has_perm)
    3603              :     {
    3604              :         /* Get printable versions of the keys involved */
    3605          817 :         initStringInfo(&key_names);
    3606          817 :         initStringInfo(&key_values);
    3607         2021 :         for (int idx = 0; idx < riinfo->nkeys; idx++)
    3608              :         {
    3609         1204 :             int         fnum = attnums[idx];
    3610         1204 :             Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
    3611              :             char       *name,
    3612              :                        *val;
    3613              :             Datum       datum;
    3614              :             bool        isnull;
    3615              : 
    3616         1204 :             name = NameStr(att->attname);
    3617              : 
    3618         1204 :             datum = slot_getattr(violatorslot, fnum, &isnull);
    3619         1204 :             if (!isnull)
    3620              :             {
    3621              :                 Oid         foutoid;
    3622              :                 bool        typisvarlena;
    3623              : 
    3624         1204 :                 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
    3625         1204 :                 val = OidOutputFunctionCall(foutoid, datum);
    3626              :             }
    3627              :             else
    3628            0 :                 val = "null";
    3629              : 
    3630         1204 :             if (idx > 0)
    3631              :             {
    3632          387 :                 appendStringInfoString(&key_names, ", ");
    3633          387 :                 appendStringInfoString(&key_values, ", ");
    3634              :             }
    3635         1204 :             appendStringInfoString(&key_names, name);
    3636         1204 :             appendStringInfoString(&key_values, val);
    3637              :         }
    3638              :     }
    3639              : 
    3640          821 :     if (partgone)
    3641           22 :         ereport(ERROR,
    3642              :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    3643              :                  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
    3644              :                         RelationGetRelationName(pk_rel),
    3645              :                         NameStr(riinfo->conname)),
    3646              :                  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
    3647              :                            key_names.data, key_values.data,
    3648              :                            RelationGetRelationName(fk_rel)),
    3649              :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    3650          799 :     else if (onfk)
    3651          469 :         ereport(ERROR,
    3652              :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    3653              :                  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
    3654              :                         RelationGetRelationName(fk_rel),
    3655              :                         NameStr(riinfo->conname)),
    3656              :                  has_perm ?
    3657              :                  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
    3658              :                            key_names.data, key_values.data,
    3659              :                            RelationGetRelationName(pk_rel)) :
    3660              :                  errdetail("Key is not present in table \"%s\".",
    3661              :                            RelationGetRelationName(pk_rel)),
    3662              :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    3663          330 :     else if (is_restrict)
    3664           20 :         ereport(ERROR,
    3665              :                 (errcode(ERRCODE_RESTRICT_VIOLATION),
    3666              :                  errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
    3667              :                         RelationGetRelationName(pk_rel),
    3668              :                         NameStr(riinfo->conname),
    3669              :                         RelationGetRelationName(fk_rel)),
    3670              :                  has_perm ?
    3671              :                  errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
    3672              :                            key_names.data, key_values.data,
    3673              :                            RelationGetRelationName(fk_rel)) :
    3674              :                  errdetail("Key is referenced from table \"%s\".",
    3675              :                            RelationGetRelationName(fk_rel)),
    3676              :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    3677              :     else
    3678          310 :         ereport(ERROR,
    3679              :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    3680              :                  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
    3681              :                         RelationGetRelationName(pk_rel),
    3682              :                         NameStr(riinfo->conname),
    3683              :                         RelationGetRelationName(fk_rel)),
    3684              :                  has_perm ?
    3685              :                  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
    3686              :                            key_names.data, key_values.data,
    3687              :                            RelationGetRelationName(fk_rel)) :
    3688              :                  errdetail("Key is still referenced from table \"%s\".",
    3689              :                            RelationGetRelationName(fk_rel)),
    3690              :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    3691              : }
    3692              : 
    3693              : 
    3694              : /*
    3695              :  * ri_NullCheck -
    3696              :  *
    3697              :  * Determine the NULL state of all key values in a tuple
    3698              :  *
    3699              :  * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
    3700              :  */
    3701              : static int
    3702       606908 : ri_NullCheck(TupleDesc tupDesc,
    3703              :              TupleTableSlot *slot,
    3704              :              const RI_ConstraintInfo *riinfo, bool rel_is_pk)
    3705              : {
    3706              :     const int16 *attnums;
    3707       606908 :     bool        allnull = true;
    3708       606908 :     bool        nonenull = true;
    3709              : 
    3710       606908 :     if (rel_is_pk)
    3711         1533 :         attnums = riinfo->pk_attnums;
    3712              :     else
    3713       605375 :         attnums = riinfo->fk_attnums;
    3714              : 
    3715      1215937 :     for (int i = 0; i < riinfo->nkeys; i++)
    3716              :     {
    3717       609029 :         if (slot_attisnull(slot, attnums[i]))
    3718          366 :             nonenull = false;
    3719              :         else
    3720       608663 :             allnull = false;
    3721              :     }
    3722              : 
    3723       606908 :     if (allnull)
    3724          182 :         return RI_KEYS_ALL_NULL;
    3725              : 
    3726       606726 :     if (nonenull)
    3727       606590 :         return RI_KEYS_NONE_NULL;
    3728              : 
    3729          136 :     return RI_KEYS_SOME_NULL;
    3730              : }
    3731              : 
    3732              : 
    3733              : /*
    3734              :  * ri_InitHashTables -
    3735              :  *
    3736              :  * Initialize our internal hash tables.
    3737              :  */
    3738              : static void
    3739          264 : ri_InitHashTables(void)
    3740              : {
    3741              :     HASHCTL     ctl;
    3742              : 
    3743          264 :     ctl.keysize = sizeof(Oid);
    3744          264 :     ctl.entrysize = sizeof(RI_ConstraintInfo);
    3745          264 :     ri_constraint_cache = hash_create("RI constraint cache",
    3746              :                                       RI_INIT_CONSTRAINTHASHSIZE,
    3747              :                                       &ctl, HASH_ELEM | HASH_BLOBS);
    3748              : 
    3749              :     /* Arrange to flush cache on pg_constraint changes */
    3750          264 :     CacheRegisterSyscacheCallback(CONSTROID,
    3751              :                                   InvalidateConstraintCacheCallBack,
    3752              :                                   (Datum) 0);
    3753              : 
    3754          264 :     ctl.keysize = sizeof(RI_QueryKey);
    3755          264 :     ctl.entrysize = sizeof(RI_QueryHashEntry);
    3756          264 :     ri_query_cache = hash_create("RI query cache",
    3757              :                                  RI_INIT_QUERYHASHSIZE,
    3758              :                                  &ctl, HASH_ELEM | HASH_BLOBS);
    3759              : 
    3760          264 :     ctl.keysize = sizeof(RI_CompareKey);
    3761          264 :     ctl.entrysize = sizeof(RI_CompareHashEntry);
    3762          264 :     ri_compare_cache = hash_create("RI compare cache",
    3763              :                                    RI_INIT_QUERYHASHSIZE,
    3764              :                                    &ctl, HASH_ELEM | HASH_BLOBS);
    3765          264 : }
    3766              : 
    3767              : 
    3768              : /*
    3769              :  * ri_FetchPreparedPlan -
    3770              :  *
    3771              :  * Lookup for a query key in our private hash table of prepared
    3772              :  * and saved SPI execution plans. Return the plan if found or NULL.
    3773              :  */
    3774              : static SPIPlanPtr
    3775         2475 : ri_FetchPreparedPlan(RI_QueryKey *key)
    3776              : {
    3777              :     RI_QueryHashEntry *entry;
    3778              :     SPIPlanPtr  plan;
    3779              : 
    3780              :     /*
    3781              :      * On the first call initialize the hashtable
    3782              :      */
    3783         2475 :     if (!ri_query_cache)
    3784            0 :         ri_InitHashTables();
    3785              : 
    3786              :     /*
    3787              :      * Lookup for the key
    3788              :      */
    3789         2475 :     entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
    3790              :                                               key,
    3791              :                                               HASH_FIND, NULL);
    3792         2475 :     if (entry == NULL)
    3793         1020 :         return NULL;
    3794              : 
    3795              :     /*
    3796              :      * Check whether the plan is still valid.  If it isn't, we don't want to
    3797              :      * simply rely on plancache.c to regenerate it; rather we should start
    3798              :      * from scratch and rebuild the query text too.  This is to cover cases
    3799              :      * such as table/column renames.  We depend on the plancache machinery to
    3800              :      * detect possible invalidations, though.
    3801              :      *
    3802              :      * CAUTION: this check is only trustworthy if the caller has already
    3803              :      * locked both FK and PK rels.
    3804              :      */
    3805         1455 :     plan = entry->plan;
    3806         1455 :     if (plan && SPI_plan_is_valid(plan))
    3807         1287 :         return plan;
    3808              : 
    3809              :     /*
    3810              :      * Otherwise we might as well flush the cached plan now, to free a little
    3811              :      * memory space before we make a new one.
    3812              :      */
    3813          168 :     entry->plan = NULL;
    3814          168 :     if (plan)
    3815          168 :         SPI_freeplan(plan);
    3816              : 
    3817          168 :     return NULL;
    3818              : }
    3819              : 
    3820              : 
    3821              : /*
    3822              :  * ri_HashPreparedPlan -
    3823              :  *
    3824              :  * Add another plan to our private SPI query plan hashtable.
    3825              :  */
    3826              : static void
    3827         1188 : ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
    3828              : {
    3829              :     RI_QueryHashEntry *entry;
    3830              :     bool        found;
    3831              : 
    3832              :     /*
    3833              :      * On the first call initialize the hashtable
    3834              :      */
    3835         1188 :     if (!ri_query_cache)
    3836            0 :         ri_InitHashTables();
    3837              : 
    3838              :     /*
    3839              :      * Add the new plan.  We might be overwriting an entry previously found
    3840              :      * invalid by ri_FetchPreparedPlan.
    3841              :      */
    3842         1188 :     entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
    3843              :                                               key,
    3844              :                                               HASH_ENTER, &found);
    3845              :     Assert(!found || entry->plan == NULL);
    3846         1188 :     entry->plan = plan;
    3847         1188 : }
    3848              : 
    3849              : 
    3850              : /*
    3851              :  * ri_KeysEqual -
    3852              :  *
    3853              :  * Check if all key values in OLD and NEW are "equivalent":
    3854              :  * For normal FKs we check for equality.
    3855              :  * For temporal FKs we check that the PK side is a superset of its old value,
    3856              :  * or the FK side is a subset of its old value.
    3857              :  *
    3858              :  * Note: at some point we might wish to redefine this as checking for
    3859              :  * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
    3860              :  * considered equal.  Currently there is no need since all callers have
    3861              :  * previously found at least one of the rows to contain no nulls.
    3862              :  */
    3863              : static bool
    3864         1423 : ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
    3865              :              const RI_ConstraintInfo *riinfo, bool rel_is_pk)
    3866              : {
    3867              :     const int16 *attnums;
    3868              : 
    3869         1423 :     if (rel_is_pk)
    3870          936 :         attnums = riinfo->pk_attnums;
    3871              :     else
    3872          487 :         attnums = riinfo->fk_attnums;
    3873              : 
    3874              :     /* XXX: could be worthwhile to fetch all necessary attrs at once */
    3875         2193 :     for (int i = 0; i < riinfo->nkeys; i++)
    3876              :     {
    3877              :         Datum       oldvalue;
    3878              :         Datum       newvalue;
    3879              :         bool        isnull;
    3880              : 
    3881              :         /*
    3882              :          * Get one attribute's oldvalue. If it is NULL - they're not equal.
    3883              :          */
    3884         1643 :         oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
    3885         1643 :         if (isnull)
    3886          873 :             return false;
    3887              : 
    3888              :         /*
    3889              :          * Get one attribute's newvalue. If it is NULL - they're not equal.
    3890              :          */
    3891         1625 :         newvalue = slot_getattr(newslot, attnums[i], &isnull);
    3892         1625 :         if (isnull)
    3893            0 :             return false;
    3894              : 
    3895         1625 :         if (rel_is_pk)
    3896              :         {
    3897              :             /*
    3898              :              * If we are looking at the PK table, then do a bytewise
    3899              :              * comparison.  We must propagate PK changes if the value is
    3900              :              * changed to one that "looks" different but would compare as
    3901              :              * equal using the equality operator.  This only makes a
    3902              :              * difference for ON UPDATE CASCADE, but for consistency we treat
    3903              :              * all changes to the PK the same.
    3904              :              */
    3905         1100 :             CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
    3906              : 
    3907         1100 :             if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
    3908          648 :                 return false;
    3909              :         }
    3910              :         else
    3911              :         {
    3912              :             Oid         eq_opr;
    3913              : 
    3914              :             /*
    3915              :              * When comparing the PERIOD columns we can skip the check
    3916              :              * whenever the referencing column stayed equal or shrank, so test
    3917              :              * with the contained-by operator instead.
    3918              :              */
    3919          525 :             if (riinfo->hasperiod && i == riinfo->nkeys - 1)
    3920           32 :                 eq_opr = riinfo->period_contained_by_oper;
    3921              :             else
    3922          493 :                 eq_opr = riinfo->ff_eq_oprs[i];
    3923              : 
    3924              :             /*
    3925              :              * For the FK table, compare with the appropriate equality
    3926              :              * operator.  Changes that compare equal will still satisfy the
    3927              :              * constraint after the update.
    3928              :              */
    3929          525 :             if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
    3930              :                                     newvalue, oldvalue))
    3931          207 :                 return false;
    3932              :         }
    3933              :     }
    3934              : 
    3935          550 :     return true;
    3936              : }
    3937              : 
    3938              : 
    3939              : /*
    3940              :  * ri_CompareWithCast -
    3941              :  *
    3942              :  * Call the appropriate comparison operator for two values.
    3943              :  * Normally this is equality, but for the PERIOD part of foreign keys
    3944              :  * it is ContainedBy, so the order of lhs vs rhs is significant.
    3945              :  * See below for how the collation is applied.
    3946              :  *
    3947              :  * NB: we have already checked that neither value is null.
    3948              :  */
    3949              : static bool
    3950          525 : ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
    3951              :                    Datum lhs, Datum rhs)
    3952              : {
    3953          525 :     RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
    3954              : 
    3955              :     /* Do we need to cast the values? */
    3956          525 :     if (OidIsValid(entry->cast_func_finfo.fn_oid))
    3957              :     {
    3958            8 :         lhs = FunctionCall3(&entry->cast_func_finfo,
    3959              :                             lhs,
    3960              :                             Int32GetDatum(-1),  /* typmod */
    3961              :                             BoolGetDatum(false));   /* implicit coercion */
    3962            8 :         rhs = FunctionCall3(&entry->cast_func_finfo,
    3963              :                             rhs,
    3964              :                             Int32GetDatum(-1),  /* typmod */
    3965              :                             BoolGetDatum(false));   /* implicit coercion */
    3966              :     }
    3967              : 
    3968              :     /*
    3969              :      * Apply the comparison operator.
    3970              :      *
    3971              :      * Note: This function is part of a call stack that determines whether an
    3972              :      * update to a row is significant enough that it needs checking or action
    3973              :      * on the other side of a foreign-key constraint.  Therefore, the
    3974              :      * comparison here would need to be done with the collation of the *other*
    3975              :      * table.  For simplicity (e.g., we might not even have the other table
    3976              :      * open), we'll use our own collation.  This is fine because we require
    3977              :      * that both collations have the same notion of equality (either they are
    3978              :      * both deterministic or else they are both the same).
    3979              :      *
    3980              :      * With range/multirangetypes, the collation of the base type is stored as
    3981              :      * part of the rangetype (pg_range.rngcollation), and always used, so
    3982              :      * there is no danger of inconsistency even using a non-equals operator.
    3983              :      * But if we support arbitrary types with PERIOD, we should perhaps just
    3984              :      * always force a re-check.
    3985              :      */
    3986          525 :     return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
    3987              : }
    3988              : 
    3989              : /*
    3990              :  * ri_HashCompareOp -
    3991              :  *
    3992              :  * Look up or create a cache entry for the given equality operator and
    3993              :  * the caller's value type (typeid).  The entry holds the operator's
    3994              :  * FmgrInfo and, if typeid doesn't match what the operator expects as
    3995              :  * its right-hand input, a cast function to coerce the value before
    3996              :  * comparison.
    3997              :  */
    3998              : static RI_CompareHashEntry *
    3999         1624 : ri_HashCompareOp(Oid eq_opr, Oid typeid)
    4000              : {
    4001              :     RI_CompareKey key;
    4002              :     RI_CompareHashEntry *entry;
    4003              :     bool        found;
    4004              : 
    4005              :     /*
    4006              :      * On the first call initialize the hashtable
    4007              :      */
    4008         1624 :     if (!ri_compare_cache)
    4009            0 :         ri_InitHashTables();
    4010              : 
    4011              :     /*
    4012              :      * Find or create a hash entry.  Note we're assuming RI_CompareKey
    4013              :      * contains no struct padding.
    4014              :      */
    4015         1624 :     key.eq_opr = eq_opr;
    4016         1624 :     key.typeid = typeid;
    4017         1624 :     entry = (RI_CompareHashEntry *) hash_search(ri_compare_cache,
    4018              :                                                 &key,
    4019              :                                                 HASH_ENTER, &found);
    4020         1624 :     if (!found)
    4021          256 :         entry->valid = false;
    4022              : 
    4023              :     /*
    4024              :      * If not already initialized, do so.  Since we'll keep this hash entry
    4025              :      * for the life of the backend, put any subsidiary info for the function
    4026              :      * cache structs into TopMemoryContext.
    4027              :      */
    4028         1624 :     if (!entry->valid)
    4029              :     {
    4030              :         Oid         lefttype,
    4031              :                     righttype,
    4032              :                     castfunc;
    4033              :         CoercionPathType pathtype;
    4034              : 
    4035              :         /* We always need to know how to call the equality operator */
    4036          256 :         fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
    4037              :                       TopMemoryContext);
    4038              : 
    4039              :         /*
    4040              :          * If we chose to use a cast from FK to PK type, we may have to apply
    4041              :          * the cast function to get to the operator's input type.
    4042              :          *
    4043              :          * XXX eventually it would be good to support array-coercion cases
    4044              :          * here and in ri_CompareWithCast().  At the moment there is no point
    4045              :          * because cases involving nonidentical array types will be rejected
    4046              :          * at constraint creation time.
    4047              :          *
    4048              :          * XXX perhaps also consider supporting CoerceViaIO?  No need at the
    4049              :          * moment since that will never be generated for implicit coercions.
    4050              :          */
    4051          256 :         op_input_types(eq_opr, &lefttype, &righttype);
    4052              : 
    4053              :         /*
    4054              :          * pf_eq_oprs (used by the fast path) can be cross-type when the FK
    4055              :          * and PK columns differ in type, e.g. int48eq for int4 PK / int8 FK.
    4056              :          * If the FK column's type already matches what the operator expects
    4057              :          * as its right-hand input, no cast is needed.
    4058              :          */
    4059          256 :         if (typeid == righttype)
    4060          232 :             castfunc = InvalidOid;  /* simplest case */
    4061              :         else
    4062              :         {
    4063           24 :             pathtype = find_coercion_pathway(lefttype, typeid,
    4064              :                                              COERCION_IMPLICIT,
    4065              :                                              &castfunc);
    4066           24 :             if (pathtype != COERCION_PATH_FUNC &&
    4067              :                 pathtype != COERCION_PATH_RELABELTYPE)
    4068              :             {
    4069              :                 /*
    4070              :                  * The declared input type of the eq_opr might be a
    4071              :                  * polymorphic type such as ANYARRAY or ANYENUM, or other
    4072              :                  * special cases such as RECORD; find_coercion_pathway
    4073              :                  * currently doesn't subsume these special cases.
    4074              :                  */
    4075           16 :                 if (!IsBinaryCoercible(typeid, lefttype))
    4076            0 :                     elog(ERROR, "no conversion function from %s to %s",
    4077              :                          format_type_be(typeid),
    4078              :                          format_type_be(lefttype));
    4079              :             }
    4080              :         }
    4081          256 :         if (OidIsValid(castfunc))
    4082            8 :             fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
    4083              :                           TopMemoryContext);
    4084              :         else
    4085          248 :             entry->cast_func_finfo.fn_oid = InvalidOid;
    4086          256 :         entry->valid = true;
    4087              :     }
    4088              : 
    4089         1624 :     return entry;
    4090              : }
    4091              : 
    4092              : 
    4093              : /*
    4094              :  * Given a trigger function OID, determine whether it is an RI trigger,
    4095              :  * and if so whether it is attached to PK or FK relation.
    4096              :  */
    4097              : int
    4098         5788 : RI_FKey_trigger_type(Oid tgfoid)
    4099              : {
    4100         5788 :     switch (tgfoid)
    4101              :     {
    4102         2033 :         case F_RI_FKEY_CASCADE_DEL:
    4103              :         case F_RI_FKEY_CASCADE_UPD:
    4104              :         case F_RI_FKEY_RESTRICT_DEL:
    4105              :         case F_RI_FKEY_RESTRICT_UPD:
    4106              :         case F_RI_FKEY_SETNULL_DEL:
    4107              :         case F_RI_FKEY_SETNULL_UPD:
    4108              :         case F_RI_FKEY_SETDEFAULT_DEL:
    4109              :         case F_RI_FKEY_SETDEFAULT_UPD:
    4110              :         case F_RI_FKEY_NOACTION_DEL:
    4111              :         case F_RI_FKEY_NOACTION_UPD:
    4112         2033 :             return RI_TRIGGER_PK;
    4113              : 
    4114         1850 :         case F_RI_FKEY_CHECK_INS:
    4115              :         case F_RI_FKEY_CHECK_UPD:
    4116         1850 :             return RI_TRIGGER_FK;
    4117              :     }
    4118              : 
    4119         1905 :     return RI_TRIGGER_NONE;
    4120              : }
    4121              : 
    4122              : /*
    4123              :  * ri_FastPathEndBatch
    4124              :  *      Flush remaining rows and tear down cached state.
    4125              :  *
    4126              :  * Registered as an AfterTriggerBatchCallback.  Note: the flush can
    4127              :  * do real work (CCI, security context switch, index probes) and can
    4128              :  * throw ERROR on a constraint violation.  If that happens,
    4129              :  * ri_FastPathTeardown never runs; ResourceOwner + XactCallback
    4130              :  * handle resource cleanup on the abort path.
    4131              :  */
    4132              : static void
    4133         1497 : ri_FastPathEndBatch(void *arg)
    4134              : {
    4135              :     HASH_SEQ_STATUS status;
    4136              :     RI_FastPathEntry *entry;
    4137              : 
    4138         1497 :     if (ri_fastpath_cache == NULL)
    4139            0 :         return;
    4140              : 
    4141              :     /* Flush any partial batches -- can throw ERROR */
    4142         1497 :     hash_seq_init(&status, ri_fastpath_cache);
    4143         4416 :     while ((entry = hash_seq_search(&status)) != NULL)
    4144              :     {
    4145         1715 :         if (entry->batch_count > 0)
    4146              :         {
    4147         1715 :             Relation    fk_rel = table_open(entry->fk_relid, AccessShareLock);
    4148         1715 :             RI_ConstraintInfo *riinfo = ri_LoadConstraintInfo(entry->conoid);
    4149              : 
    4150         1715 :             ri_FastPathBatchFlush(entry, fk_rel, riinfo);
    4151         1422 :             table_close(fk_rel, NoLock);
    4152              :         }
    4153              :     }
    4154              : 
    4155         1204 :     ri_FastPathTeardown();
    4156              : }
    4157              : 
    4158              : /*
    4159              :  * ri_FastPathTeardown
    4160              :  *      Tear down all cached fast-path state.
    4161              :  *
    4162              :  * Called from ri_FastPathEndBatch() after flushing any remaining rows.
    4163              :  */
    4164              : static void
    4165         1204 : ri_FastPathTeardown(void)
    4166              : {
    4167              :     HASH_SEQ_STATUS status;
    4168              :     RI_FastPathEntry *entry;
    4169              : 
    4170         1204 :     if (ri_fastpath_cache == NULL)
    4171            0 :         return;
    4172              : 
    4173         1204 :     hash_seq_init(&status, ri_fastpath_cache);
    4174         3818 :     while ((entry = hash_seq_search(&status)) != NULL)
    4175              :     {
    4176         1410 :         if (entry->idx_rel)
    4177         1410 :             index_close(entry->idx_rel, NoLock);
    4178         1410 :         if (entry->pk_rel)
    4179         1410 :             table_close(entry->pk_rel, NoLock);
    4180         1410 :         if (entry->pk_slot)
    4181         1410 :             ExecDropSingleTupleTableSlot(entry->pk_slot);
    4182         1410 :         if (entry->fk_slot)
    4183         1410 :             ExecDropSingleTupleTableSlot(entry->fk_slot);
    4184         1410 :         if (entry->flush_cxt)
    4185         1410 :             MemoryContextDelete(entry->flush_cxt);
    4186              :     }
    4187              : 
    4188         1204 :     hash_destroy(ri_fastpath_cache);
    4189         1204 :     ri_fastpath_cache = NULL;
    4190         1204 :     ri_fastpath_callback_registered = false;
    4191              : }
    4192              : 
    4193              : static bool ri_fastpath_xact_callback_registered = false;
    4194              : 
    4195              : static void
    4196        73555 : ri_FastPathXactCallback(XactEvent event, void *arg)
    4197              : {
    4198              :     /*
    4199              :      * On abort, ResourceOwner already released relations; on commit,
    4200              :      * ri_FastPathTeardown already ran.  Either way, just NULL the static
    4201              :      * pointers so they don't dangle into the next transaction.
    4202              :      */
    4203        73555 :     ri_fastpath_cache = NULL;
    4204        73555 :     ri_fastpath_callback_registered = false;
    4205        73555 : }
    4206              : 
    4207              : static void
    4208          347 : ri_FastPathSubXactCallback(SubXactEvent event, SubTransactionId mySubid,
    4209              :                            SubTransactionId parentSubid, void *arg)
    4210              : {
    4211          347 :     if (event == SUBXACT_EVENT_ABORT_SUB)
    4212              :     {
    4213              :         /*
    4214              :          * ResourceOwner already released relations.  NULL the static pointers
    4215              :          * so the still-registered batch callback becomes a no-op for the rest
    4216              :          * of this transaction.
    4217              :          */
    4218           94 :         ri_fastpath_cache = NULL;
    4219           94 :         ri_fastpath_callback_registered = false;
    4220              :     }
    4221          347 : }
    4222              : 
    4223              : /*
    4224              :  * ri_FastPathGetEntry
    4225              :  *      Look up or create a per-batch cache entry for the given constraint.
    4226              :  *
    4227              :  * On first call for a constraint within a batch: opens pk_rel and the index,
    4228              :  * allocates slots for both FK row and the looked up PK row, and registers the
    4229              :  * cleanup callback.
    4230              :  *
    4231              :  * On subsequent calls: returns the existing entry.
    4232              :  */
    4233              : static RI_FastPathEntry *
    4234       603651 : ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo, Relation fk_rel)
    4235              : {
    4236              :     RI_FastPathEntry *entry;
    4237              :     bool        found;
    4238              : 
    4239              :     /* Create hash table on first use in this batch */
    4240       603651 :     if (ri_fastpath_cache == NULL)
    4241              :     {
    4242              :         HASHCTL     ctl;
    4243              : 
    4244         1497 :         if (!ri_fastpath_xact_callback_registered)
    4245              :         {
    4246          213 :             RegisterXactCallback(ri_FastPathXactCallback, NULL);
    4247          213 :             RegisterSubXactCallback(ri_FastPathSubXactCallback, NULL);
    4248          213 :             ri_fastpath_xact_callback_registered = true;
    4249              :         }
    4250              : 
    4251         1497 :         ctl.keysize = sizeof(Oid);
    4252         1497 :         ctl.entrysize = sizeof(RI_FastPathEntry);
    4253         1497 :         ctl.hcxt = TopTransactionContext;
    4254         1497 :         ri_fastpath_cache = hash_create("RI fast-path cache",
    4255              :                                         16,
    4256              :                                         &ctl,
    4257              :                                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    4258              :     }
    4259              : 
    4260       603651 :     entry = hash_search(ri_fastpath_cache, &riinfo->constraint_id,
    4261              :                         HASH_ENTER, &found);
    4262              : 
    4263       603651 :     if (!found)
    4264              :     {
    4265              :         MemoryContext oldcxt;
    4266              : 
    4267              :         /*
    4268              :          * Zero out non-key fields so ri_FastPathTeardown is safe if we error
    4269              :          * out during partial initialization below.
    4270              :          */
    4271         1731 :         memset(((char *) entry) + offsetof(RI_FastPathEntry, pk_rel), 0,
    4272              :                sizeof(RI_FastPathEntry) - offsetof(RI_FastPathEntry, pk_rel));
    4273              : 
    4274         1731 :         oldcxt = MemoryContextSwitchTo(TopTransactionContext);
    4275              : 
    4276         1731 :         entry->fk_relid = RelationGetRelid(fk_rel);
    4277              : 
    4278              :         /*
    4279              :          * Open PK table and its unique index.
    4280              :          *
    4281              :          * RowShareLock on pk_rel matches what the SPI path's SELECT ... FOR
    4282              :          * KEY SHARE would acquire as a relation-level lock. AccessShareLock
    4283              :          * on the index is standard for index scans.
    4284              :          *
    4285              :          * We don't release these locks until end of transaction, matching SPI
    4286              :          * behavior.
    4287              :          */
    4288         1731 :         entry->pk_rel = table_open(riinfo->pk_relid, RowShareLock);
    4289         1731 :         entry->idx_rel = index_open(riinfo->conindid, AccessShareLock);
    4290         1731 :         entry->pk_slot = table_slot_create(entry->pk_rel, NULL);
    4291              : 
    4292              :         /*
    4293              :          * Must be TTSOpsHeapTuple because ExecStoreHeapTuple() is used to
    4294              :          * load entries from batch[] into this slot for value extraction.
    4295              :          */
    4296         1731 :         entry->fk_slot = MakeSingleTupleTableSlot(RelationGetDescr(fk_rel),
    4297              :                                                   &TTSOpsHeapTuple);
    4298              : 
    4299         1731 :         entry->flush_cxt = AllocSetContextCreate(TopTransactionContext,
    4300              :                                                  "RI fast path flush temporary context",
    4301              :                                                  ALLOCSET_SMALL_SIZES);
    4302         1731 :         MemoryContextSwitchTo(oldcxt);
    4303              : 
    4304              :         /* Ensure cleanup at end of this trigger-firing batch */
    4305         1731 :         if (!ri_fastpath_callback_registered)
    4306              :         {
    4307         1497 :             RegisterAfterTriggerBatchCallback(ri_FastPathEndBatch, NULL);
    4308         1497 :             ri_fastpath_callback_registered = true;
    4309              :         }
    4310              :     }
    4311              : 
    4312       603651 :     return entry;
    4313              : }
        

Generated by: LCOV version 2.0-1