LCOV - code coverage report
Current view: top level - src/backend/utils/adt - ri_triggers.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.8 % 1189 1103
Test Date: 2026-08-11 20:15:55 Functions: 100.0 % 58 58
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 70.9 % 636 451

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

Generated by: LCOV version 2.0-1