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

Generated by: LCOV version 2.0-1