LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - ri_triggers.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 93.9 % 1244 1168 76 1 1167 1
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 59 59 1 58 1
Baseline: lcov-20260827-baseline Branches: 71.8 % 708 508 200 508
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 97.8 % 45 44 1 44
(7,30] days: 96.8 % 31 30 1 30
(30,360] days: 94.8 % 286 271 15 1 270
(360..) days: 93.3 % 882 823 59 823
Function coverage date bins:
(1,7] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 17 17 1 16
(360..) days: 100.0 % 40 40 40
Branch coverage date bins:
(1,7] days: 90.6 % 32 29 3 29
(7,30] days: 85.0 % 20 17 3 17
(30,360] days: 73.5 % 170 125 45 125
(360..) days: 69.3 % 486 337 149 337

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

Generated by: LCOV version 2.0-1