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

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

Generated by: LCOV version 2.0-1