LCOV - code coverage report
Current view: top level - src/backend/utils/adt - ri_triggers.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 785 845 92.9 %
Date: 2025-01-18 04:15:08 Functions: 42 42 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * ri_triggers.c
       4             :  *
       5             :  *  Generic trigger procedures for referential integrity constraint
       6             :  *  checks.
       7             :  *
       8             :  *  Note about memory management: the private hashtables kept here live
       9             :  *  across query and transaction boundaries, in fact they live as long as
      10             :  *  the backend does.  This works because the hashtable structures
      11             :  *  themselves are allocated by dynahash.c in its permanent DynaHashCxt,
      12             :  *  and the SPI plans they point to are saved using SPI_keepplan().
      13             :  *  There is not currently any provision for throwing away a no-longer-needed
      14             :  *  plan --- consider improving this someday.
      15             :  *
      16             :  *
      17             :  * Portions Copyright (c) 1996-2025, 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/htup_details.h"
      27             : #include "access/sysattr.h"
      28             : #include "access/table.h"
      29             : #include "access/tableam.h"
      30             : #include "access/xact.h"
      31             : #include "catalog/pg_collation.h"
      32             : #include "catalog/pg_constraint.h"
      33             : #include "catalog/pg_proc.h"
      34             : #include "commands/trigger.h"
      35             : #include "executor/executor.h"
      36             : #include "executor/spi.h"
      37             : #include "lib/ilist.h"
      38             : #include "miscadmin.h"
      39             : #include "parser/parse_coerce.h"
      40             : #include "parser/parse_relation.h"
      41             : #include "utils/acl.h"
      42             : #include "utils/builtins.h"
      43             : #include "utils/datum.h"
      44             : #include "utils/fmgroids.h"
      45             : #include "utils/guc.h"
      46             : #include "utils/inval.h"
      47             : #include "utils/lsyscache.h"
      48             : #include "utils/memutils.h"
      49             : #include "utils/rangetypes.h"
      50             : #include "utils/rel.h"
      51             : #include "utils/rls.h"
      52             : #include "utils/ruleutils.h"
      53             : #include "utils/snapmgr.h"
      54             : #include "utils/syscache.h"
      55             : 
      56             : /*
      57             :  * Local definitions
      58             :  */
      59             : 
      60             : #define RI_MAX_NUMKEYS                  INDEX_MAX_KEYS
      61             : 
      62             : #define RI_INIT_CONSTRAINTHASHSIZE      64
      63             : #define RI_INIT_QUERYHASHSIZE           (RI_INIT_CONSTRAINTHASHSIZE * 4)
      64             : 
      65             : #define RI_KEYS_ALL_NULL                0
      66             : #define RI_KEYS_SOME_NULL               1
      67             : #define RI_KEYS_NONE_NULL               2
      68             : 
      69             : /* RI query type codes */
      70             : /* these queries are executed against the PK (referenced) table: */
      71             : #define RI_PLAN_CHECK_LOOKUPPK          1
      72             : #define RI_PLAN_CHECK_LOOKUPPK_FROM_PK  2
      73             : #define RI_PLAN_LAST_ON_PK              RI_PLAN_CHECK_LOOKUPPK_FROM_PK
      74             : /* these queries are executed against the FK (referencing) table: */
      75             : #define RI_PLAN_CASCADE_ONDELETE        3
      76             : #define RI_PLAN_CASCADE_ONUPDATE        4
      77             : /* For RESTRICT, the same plan can be used for both ON DELETE and ON UPDATE triggers. */
      78             : #define RI_PLAN_RESTRICT                5
      79             : #define RI_PLAN_SETNULL_ONDELETE        6
      80             : #define RI_PLAN_SETNULL_ONUPDATE        7
      81             : #define RI_PLAN_SETDEFAULT_ONDELETE     8
      82             : #define RI_PLAN_SETDEFAULT_ONUPDATE     9
      83             : 
      84             : #define MAX_QUOTED_NAME_LEN  (NAMEDATALEN*2+3)
      85             : #define MAX_QUOTED_REL_NAME_LEN  (MAX_QUOTED_NAME_LEN*2)
      86             : 
      87             : #define RIAttName(rel, attnum)  NameStr(*attnumAttName(rel, attnum))
      88             : #define RIAttType(rel, attnum)  attnumTypeId(rel, attnum)
      89             : #define RIAttCollation(rel, attnum) attnumCollationId(rel, attnum)
      90             : 
      91             : #define RI_TRIGTYPE_INSERT 1
      92             : #define RI_TRIGTYPE_UPDATE 2
      93             : #define RI_TRIGTYPE_DELETE 3
      94             : 
      95             : 
      96             : /*
      97             :  * RI_ConstraintInfo
      98             :  *
      99             :  * Information extracted from an FK pg_constraint entry.  This is cached in
     100             :  * ri_constraint_cache.
     101             :  *
     102             :  * Note that pf/pp/ff_eq_oprs may hold the overlaps operator instead of equals
     103             :  * for the PERIOD part of a temporal foreign key.
     104             :  */
     105             : typedef struct RI_ConstraintInfo
     106             : {
     107             :     Oid         constraint_id;  /* OID of pg_constraint entry (hash key) */
     108             :     bool        valid;          /* successfully initialized? */
     109             :     Oid         constraint_root_id; /* OID of topmost ancestor constraint;
     110             :                                      * same as constraint_id if not inherited */
     111             :     uint32      oidHashValue;   /* hash value of constraint_id */
     112             :     uint32      rootHashValue;  /* hash value of constraint_root_id */
     113             :     NameData    conname;        /* name of the FK constraint */
     114             :     Oid         pk_relid;       /* referenced relation */
     115             :     Oid         fk_relid;       /* referencing relation */
     116             :     char        confupdtype;    /* foreign key's ON UPDATE action */
     117             :     char        confdeltype;    /* foreign key's ON DELETE action */
     118             :     int         ndelsetcols;    /* number of columns referenced in ON DELETE
     119             :                                  * SET clause */
     120             :     int16       confdelsetcols[RI_MAX_NUMKEYS]; /* attnums of cols to set on
     121             :                                                  * delete */
     122             :     char        confmatchtype;  /* foreign key's match type */
     123             :     bool        hasperiod;      /* if the foreign key uses PERIOD */
     124             :     int         nkeys;          /* number of key columns */
     125             :     int16       pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
     126             :     int16       fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
     127             :     Oid         pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
     128             :     Oid         pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
     129             :     Oid         ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
     130             :     Oid         period_contained_by_oper;   /* anyrange <@ anyrange */
     131             :     Oid         agged_period_contained_by_oper; /* fkattr <@ range_agg(pkattr) */
     132             :     dlist_node  valid_link;     /* Link in list of valid entries */
     133             : } RI_ConstraintInfo;
     134             : 
     135             : /*
     136             :  * RI_QueryKey
     137             :  *
     138             :  * The key identifying a prepared SPI plan in our query hashtable
     139             :  */
     140             : typedef struct RI_QueryKey
     141             : {
     142             :     Oid         constr_id;      /* OID of pg_constraint entry */
     143             :     int32       constr_queryno; /* query type ID, see RI_PLAN_XXX above */
     144             : } RI_QueryKey;
     145             : 
     146             : /*
     147             :  * RI_QueryHashEntry
     148             :  */
     149             : typedef struct RI_QueryHashEntry
     150             : {
     151             :     RI_QueryKey key;
     152             :     SPIPlanPtr  plan;
     153             : } RI_QueryHashEntry;
     154             : 
     155             : /*
     156             :  * RI_CompareKey
     157             :  *
     158             :  * The key identifying an entry showing how to compare two values
     159             :  */
     160             : typedef struct RI_CompareKey
     161             : {
     162             :     Oid         eq_opr;         /* the equality operator to apply */
     163             :     Oid         typeid;         /* the data type to apply it to */
     164             : } RI_CompareKey;
     165             : 
     166             : /*
     167             :  * RI_CompareHashEntry
     168             :  */
     169             : typedef struct RI_CompareHashEntry
     170             : {
     171             :     RI_CompareKey key;
     172             :     bool        valid;          /* successfully initialized? */
     173             :     FmgrInfo    eq_opr_finfo;   /* call info for equality fn */
     174             :     FmgrInfo    cast_func_finfo;    /* in case we must coerce input */
     175             : } RI_CompareHashEntry;
     176             : 
     177             : 
     178             : /*
     179             :  * Local data
     180             :  */
     181             : static HTAB *ri_constraint_cache = NULL;
     182             : static HTAB *ri_query_cache = NULL;
     183             : static HTAB *ri_compare_cache = NULL;
     184             : static dclist_head ri_constraint_cache_valid_list;
     185             : 
     186             : 
     187             : /*
     188             :  * Local function prototypes
     189             :  */
     190             : static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
     191             :                               TupleTableSlot *oldslot,
     192             :                               const RI_ConstraintInfo *riinfo);
     193             : static Datum ri_restrict(TriggerData *trigdata, bool is_no_action);
     194             : static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind);
     195             : static void quoteOneName(char *buffer, const char *name);
     196             : static void quoteRelationName(char *buffer, Relation rel);
     197             : static void ri_GenerateQual(StringInfo buf,
     198             :                             const char *sep,
     199             :                             const char *leftop, Oid leftoptype,
     200             :                             Oid opoid,
     201             :                             const char *rightop, Oid rightoptype);
     202             : static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
     203             : static int  ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot,
     204             :                          const RI_ConstraintInfo *riinfo, bool rel_is_pk);
     205             : static void ri_BuildQueryKey(RI_QueryKey *key,
     206             :                              const RI_ConstraintInfo *riinfo,
     207             :                              int32 constr_queryno);
     208             : static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
     209             :                          const RI_ConstraintInfo *riinfo, bool rel_is_pk);
     210             : static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
     211             :                                Datum lhs, Datum rhs);
     212             : 
     213             : static void ri_InitHashTables(void);
     214             : static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue);
     215             : static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key);
     216             : static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan);
     217             : static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
     218             : 
     219             : static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
     220             :                             int tgkind);
     221             : static const RI_ConstraintInfo *ri_FetchConstraintInfo(Trigger *trigger,
     222             :                                                        Relation trig_rel, bool rel_is_pk);
     223             : static const RI_ConstraintInfo *ri_LoadConstraintInfo(Oid constraintOid);
     224             : static Oid  get_ri_constraint_root(Oid constrOid);
     225             : static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
     226             :                                RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel);
     227             : static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo,
     228             :                             RI_QueryKey *qkey, SPIPlanPtr qplan,
     229             :                             Relation fk_rel, Relation pk_rel,
     230             :                             TupleTableSlot *oldslot, TupleTableSlot *newslot,
     231             :                             bool is_restrict,
     232             :                             bool detectNewRows, int expect_OK);
     233             : static void ri_ExtractValues(Relation rel, TupleTableSlot *slot,
     234             :                              const RI_ConstraintInfo *riinfo, bool rel_is_pk,
     235             :                              Datum *vals, char *nulls);
     236             : static void ri_ReportViolation(const RI_ConstraintInfo *riinfo,
     237             :                                Relation pk_rel, Relation fk_rel,
     238             :                                TupleTableSlot *violatorslot, TupleDesc tupdesc,
     239             :                                int queryno, bool is_restrict, bool partgone) pg_attribute_noreturn();
     240             : 
     241             : 
     242             : /*
     243             :  * RI_FKey_check -
     244             :  *
     245             :  * Check foreign key existence (combined for INSERT and UPDATE).
     246             :  */
     247             : static Datum
     248        4498 : RI_FKey_check(TriggerData *trigdata)
     249             : {
     250             :     const RI_ConstraintInfo *riinfo;
     251             :     Relation    fk_rel;
     252             :     Relation    pk_rel;
     253             :     TupleTableSlot *newslot;
     254             :     RI_QueryKey qkey;
     255             :     SPIPlanPtr  qplan;
     256             : 
     257        4498 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     258             :                                     trigdata->tg_relation, false);
     259             : 
     260        4498 :     if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
     261         448 :         newslot = trigdata->tg_newslot;
     262             :     else
     263        4050 :         newslot = trigdata->tg_trigslot;
     264             : 
     265             :     /*
     266             :      * We should not even consider checking the row if it is no longer valid,
     267             :      * since it was either deleted (so the deferred check should be skipped)
     268             :      * or updated (in which case only the latest version of the row should be
     269             :      * checked).  Test its liveness according to SnapshotSelf.  We need pin
     270             :      * and lock on the buffer to call HeapTupleSatisfiesVisibility.  Caller
     271             :      * should be holding pin, but not lock.
     272             :      */
     273        4498 :     if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
     274          60 :         return PointerGetDatum(NULL);
     275             : 
     276             :     /*
     277             :      * Get the relation descriptors of the FK and PK tables.
     278             :      *
     279             :      * pk_rel is opened in RowShareLock mode since that's what our eventual
     280             :      * SELECT FOR KEY SHARE will get on it.
     281             :      */
     282        4438 :     fk_rel = trigdata->tg_relation;
     283        4438 :     pk_rel = table_open(riinfo->pk_relid, RowShareLock);
     284             : 
     285        4438 :     switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
     286             :     {
     287         132 :         case RI_KEYS_ALL_NULL:
     288             : 
     289             :             /*
     290             :              * No further check needed - an all-NULL key passes every type of
     291             :              * foreign key constraint.
     292             :              */
     293         132 :             table_close(pk_rel, RowShareLock);
     294         132 :             return PointerGetDatum(NULL);
     295             : 
     296         156 :         case RI_KEYS_SOME_NULL:
     297             : 
     298             :             /*
     299             :              * This is the only case that differs between the three kinds of
     300             :              * MATCH.
     301             :              */
     302         156 :             switch (riinfo->confmatchtype)
     303             :             {
     304          36 :                 case FKCONSTR_MATCH_FULL:
     305             : 
     306             :                     /*
     307             :                      * Not allowed - MATCH FULL says either all or none of the
     308             :                      * attributes can be NULLs
     309             :                      */
     310          36 :                     ereport(ERROR,
     311             :                             (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
     312             :                              errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
     313             :                                     RelationGetRelationName(fk_rel),
     314             :                                     NameStr(riinfo->conname)),
     315             :                              errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
     316             :                              errtableconstraint(fk_rel,
     317             :                                                 NameStr(riinfo->conname))));
     318             :                     table_close(pk_rel, RowShareLock);
     319             :                     return PointerGetDatum(NULL);
     320             : 
     321         120 :                 case FKCONSTR_MATCH_SIMPLE:
     322             : 
     323             :                     /*
     324             :                      * MATCH SIMPLE - if ANY column is null, the key passes
     325             :                      * the constraint.
     326             :                      */
     327         120 :                     table_close(pk_rel, RowShareLock);
     328         120 :                     return PointerGetDatum(NULL);
     329             : 
     330             : #ifdef NOT_USED
     331             :                 case FKCONSTR_MATCH_PARTIAL:
     332             : 
     333             :                     /*
     334             :                      * MATCH PARTIAL - all non-null columns must match. (not
     335             :                      * implemented, can be done by modifying the query below
     336             :                      * to only include non-null columns, or by writing a
     337             :                      * special version here)
     338             :                      */
     339             :                     break;
     340             : #endif
     341             :             }
     342             : 
     343             :         case RI_KEYS_NONE_NULL:
     344             : 
     345             :             /*
     346             :              * Have a full qualified key - continue below for all three kinds
     347             :              * of MATCH.
     348             :              */
     349        4150 :             break;
     350             :     }
     351             : 
     352        4150 :     SPI_connect();
     353             : 
     354             :     /* Fetch or prepare a saved plan for the real check */
     355        4150 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK);
     356             : 
     357        4150 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     358             :     {
     359             :         StringInfoData querybuf;
     360             :         char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
     361             :         char        attname[MAX_QUOTED_NAME_LEN];
     362             :         char        paramname[16];
     363             :         const char *querysep;
     364             :         Oid         queryoids[RI_MAX_NUMKEYS];
     365             :         const char *pk_only;
     366             : 
     367             :         /* ----------
     368             :          * The query string built is
     369             :          *  SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
     370             :          *         FOR KEY SHARE OF x
     371             :          * The type id's for the $ parameters are those of the
     372             :          * corresponding FK attributes.
     373             :          *
     374             :          * But for temporal FKs we need to make sure
     375             :          * the FK's range is completely covered.
     376             :          * So we use this query instead:
     377             :          *  SELECT 1
     378             :          *  FROM    (
     379             :          *      SELECT pkperiodatt AS r
     380             :          *      FROM   [ONLY] pktable x
     381             :          *      WHERE  pkatt1 = $1 [AND ...]
     382             :          *      AND    pkperiodatt && $n
     383             :          *      FOR KEY SHARE OF x
     384             :          *  ) x1
     385             :          *  HAVING $n <@ range_agg(x1.r)
     386             :          * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
     387             :          * we can make this a bit simpler.
     388             :          * ----------
     389             :          */
     390        2196 :         initStringInfo(&querybuf);
     391        4392 :         pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     392        2196 :             "" : "ONLY ";
     393        2196 :         quoteRelationName(pkrelname, pk_rel);
     394        2196 :         if (riinfo->hasperiod)
     395             :         {
     396         128 :             quoteOneName(attname,
     397         128 :                          RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
     398             : 
     399         128 :             appendStringInfo(&querybuf,
     400             :                              "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
     401             :                              attname, pk_only, pkrelname);
     402             :         }
     403             :         else
     404             :         {
     405        2068 :             appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     406             :                              pk_only, pkrelname);
     407             :         }
     408        2196 :         querysep = "WHERE";
     409        4762 :         for (int i = 0; i < riinfo->nkeys; i++)
     410             :         {
     411        2566 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     412        2566 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     413             : 
     414        2566 :             quoteOneName(attname,
     415        2566 :                          RIAttName(pk_rel, riinfo->pk_attnums[i]));
     416        2566 :             sprintf(paramname, "$%d", i + 1);
     417        2566 :             ri_GenerateQual(&querybuf, querysep,
     418             :                             attname, pk_type,
     419             :                             riinfo->pf_eq_oprs[i],
     420             :                             paramname, fk_type);
     421        2566 :             querysep = "AND";
     422        2566 :             queryoids[i] = fk_type;
     423             :         }
     424        2196 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
     425        2196 :         if (riinfo->hasperiod)
     426             :         {
     427         128 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
     428             : 
     429         128 :             appendStringInfo(&querybuf, ") x1 HAVING ");
     430         128 :             sprintf(paramname, "$%d", riinfo->nkeys);
     431         128 :             ri_GenerateQual(&querybuf, "",
     432             :                             paramname, fk_type,
     433             :                             riinfo->agged_period_contained_by_oper,
     434             :                             "pg_catalog.range_agg", ANYMULTIRANGEOID);
     435         128 :             appendStringInfo(&querybuf, "(x1.r)");
     436             :         }
     437             : 
     438             :         /* Prepare and save the plan */
     439        2196 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     440             :                              &qkey, fk_rel, pk_rel);
     441             :     }
     442             : 
     443             :     /*
     444             :      * Now check that foreign key exists in PK table
     445             :      *
     446             :      * XXX detectNewRows must be true when a partitioned table is on the
     447             :      * referenced side.  The reason is that our snapshot must be fresh in
     448             :      * order for the hack in find_inheritance_children() to work.
     449             :      */
     450        4150 :     ri_PerformCheck(riinfo, &qkey, qplan,
     451             :                     fk_rel, pk_rel,
     452             :                     NULL, newslot,
     453             :                     false,
     454        4150 :                     pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
     455             :                     SPI_OK_SELECT);
     456             : 
     457        3596 :     if (SPI_finish() != SPI_OK_FINISH)
     458           0 :         elog(ERROR, "SPI_finish failed");
     459             : 
     460        3596 :     table_close(pk_rel, RowShareLock);
     461             : 
     462        3596 :     return PointerGetDatum(NULL);
     463             : }
     464             : 
     465             : 
     466             : /*
     467             :  * RI_FKey_check_ins -
     468             :  *
     469             :  * Check foreign key existence at insert event on FK table.
     470             :  */
     471             : Datum
     472        4050 : RI_FKey_check_ins(PG_FUNCTION_ARGS)
     473             : {
     474             :     /* Check that this is a valid trigger call on the right time and event. */
     475        4050 :     ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
     476             : 
     477             :     /* Share code with UPDATE case. */
     478        4050 :     return RI_FKey_check((TriggerData *) fcinfo->context);
     479             : }
     480             : 
     481             : 
     482             : /*
     483             :  * RI_FKey_check_upd -
     484             :  *
     485             :  * Check foreign key existence at update event on FK table.
     486             :  */
     487             : Datum
     488         448 : RI_FKey_check_upd(PG_FUNCTION_ARGS)
     489             : {
     490             :     /* Check that this is a valid trigger call on the right time and event. */
     491         448 :     ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
     492             : 
     493             :     /* Share code with INSERT case. */
     494         448 :     return RI_FKey_check((TriggerData *) fcinfo->context);
     495             : }
     496             : 
     497             : 
     498             : /*
     499             :  * ri_Check_Pk_Match
     500             :  *
     501             :  * Check to see if another PK row has been created that provides the same
     502             :  * key values as the "oldslot" that's been modified or deleted in our trigger
     503             :  * event.  Returns true if a match is found in the PK table.
     504             :  *
     505             :  * We assume the caller checked that the oldslot contains no NULL key values,
     506             :  * since otherwise a match is impossible.
     507             :  */
     508             : static bool
     509        1038 : ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
     510             :                   TupleTableSlot *oldslot,
     511             :                   const RI_ConstraintInfo *riinfo)
     512             : {
     513             :     SPIPlanPtr  qplan;
     514             :     RI_QueryKey qkey;
     515             :     bool        result;
     516             : 
     517             :     /* Only called for non-null rows */
     518             :     Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
     519             : 
     520        1038 :     SPI_connect();
     521             : 
     522             :     /*
     523             :      * Fetch or prepare a saved plan for checking PK table with values coming
     524             :      * from a PK row
     525             :      */
     526        1038 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK_FROM_PK);
     527             : 
     528        1038 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     529             :     {
     530             :         StringInfoData querybuf;
     531             :         char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
     532             :         char        attname[MAX_QUOTED_NAME_LEN];
     533             :         char        paramname[16];
     534             :         const char *querysep;
     535             :         const char *pk_only;
     536             :         Oid         queryoids[RI_MAX_NUMKEYS];
     537             : 
     538             :         /* ----------
     539             :          * The query string built is
     540             :          *  SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
     541             :          *         FOR KEY SHARE OF x
     542             :          * The type id's for the $ parameters are those of the
     543             :          * PK attributes themselves.
     544             :          *
     545             :          * But for temporal FKs we need to make sure
     546             :          * the old PK's range is completely covered.
     547             :          * So we use this query instead:
     548             :          *  SELECT 1
     549             :          *  FROM    (
     550             :          *    SELECT pkperiodatt AS r
     551             :          *    FROM   [ONLY] pktable x
     552             :          *    WHERE  pkatt1 = $1 [AND ...]
     553             :          *    AND    pkperiodatt && $n
     554             :          *    FOR KEY SHARE OF x
     555             :          *  ) x1
     556             :          *  HAVING $n <@ range_agg(x1.r)
     557             :          * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
     558             :          * we can make this a bit simpler.
     559             :          * ----------
     560             :          */
     561         468 :         initStringInfo(&querybuf);
     562         936 :         pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     563         468 :             "" : "ONLY ";
     564         468 :         quoteRelationName(pkrelname, pk_rel);
     565         468 :         if (riinfo->hasperiod)
     566             :         {
     567         128 :             quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
     568             : 
     569         128 :             appendStringInfo(&querybuf,
     570             :                              "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
     571             :                              attname, pk_only, pkrelname);
     572             :         }
     573             :         else
     574             :         {
     575         340 :             appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     576             :                              pk_only, pkrelname);
     577             :         }
     578         468 :         querysep = "WHERE";
     579        1174 :         for (int i = 0; i < riinfo->nkeys; i++)
     580             :         {
     581         706 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     582             : 
     583         706 :             quoteOneName(attname,
     584         706 :                          RIAttName(pk_rel, riinfo->pk_attnums[i]));
     585         706 :             sprintf(paramname, "$%d", i + 1);
     586         706 :             ri_GenerateQual(&querybuf, querysep,
     587             :                             attname, pk_type,
     588             :                             riinfo->pp_eq_oprs[i],
     589             :                             paramname, pk_type);
     590         706 :             querysep = "AND";
     591         706 :             queryoids[i] = pk_type;
     592             :         }
     593         468 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
     594         468 :         if (riinfo->hasperiod)
     595             :         {
     596         128 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
     597             : 
     598         128 :             appendStringInfo(&querybuf, ") x1 HAVING ");
     599         128 :             sprintf(paramname, "$%d", riinfo->nkeys);
     600         128 :             ri_GenerateQual(&querybuf, "",
     601             :                             paramname, fk_type,
     602             :                             riinfo->agged_period_contained_by_oper,
     603             :                             "pg_catalog.range_agg", ANYMULTIRANGEOID);
     604         128 :             appendStringInfo(&querybuf, "(x1.r)");
     605             :         }
     606             : 
     607             :         /* Prepare and save the plan */
     608         468 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     609             :                              &qkey, fk_rel, pk_rel);
     610             :     }
     611             : 
     612             :     /*
     613             :      * We have a plan now. Run it.
     614             :      */
     615        1038 :     result = ri_PerformCheck(riinfo, &qkey, qplan,
     616             :                              fk_rel, pk_rel,
     617             :                              oldslot, NULL,
     618             :                              false,
     619             :                              true,  /* treat like update */
     620             :                              SPI_OK_SELECT);
     621             : 
     622        1038 :     if (SPI_finish() != SPI_OK_FINISH)
     623           0 :         elog(ERROR, "SPI_finish failed");
     624             : 
     625        1038 :     return result;
     626             : }
     627             : 
     628             : 
     629             : /*
     630             :  * RI_FKey_noaction_del -
     631             :  *
     632             :  * Give an error and roll back the current transaction if the
     633             :  * delete has resulted in a violation of the given referential
     634             :  * integrity constraint.
     635             :  */
     636             : Datum
     637         438 : RI_FKey_noaction_del(PG_FUNCTION_ARGS)
     638             : {
     639             :     /* Check that this is a valid trigger call on the right time and event. */
     640         438 :     ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
     641             : 
     642             :     /* Share code with RESTRICT/UPDATE cases. */
     643         438 :     return ri_restrict((TriggerData *) fcinfo->context, true);
     644             : }
     645             : 
     646             : /*
     647             :  * RI_FKey_restrict_del -
     648             :  *
     649             :  * Restrict delete from PK table to rows unreferenced by foreign key.
     650             :  *
     651             :  * The SQL standard intends that this referential action occur exactly when
     652             :  * the delete is performed, rather than after.  This appears to be
     653             :  * the only difference between "NO ACTION" and "RESTRICT".  In Postgres
     654             :  * we still implement this as an AFTER trigger, but it's non-deferrable.
     655             :  */
     656             : Datum
     657          78 : RI_FKey_restrict_del(PG_FUNCTION_ARGS)
     658             : {
     659             :     /* Check that this is a valid trigger call on the right time and event. */
     660          78 :     ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
     661             : 
     662             :     /* Share code with NO ACTION/UPDATE cases. */
     663          78 :     return ri_restrict((TriggerData *) fcinfo->context, false);
     664             : }
     665             : 
     666             : /*
     667             :  * RI_FKey_noaction_upd -
     668             :  *
     669             :  * Give an error and roll back the current transaction if the
     670             :  * update has resulted in a violation of the given referential
     671             :  * integrity constraint.
     672             :  */
     673             : Datum
     674         468 : RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
     675             : {
     676             :     /* Check that this is a valid trigger call on the right time and event. */
     677         468 :     ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
     678             : 
     679             :     /* Share code with RESTRICT/DELETE cases. */
     680         468 :     return ri_restrict((TriggerData *) fcinfo->context, true);
     681             : }
     682             : 
     683             : /*
     684             :  * RI_FKey_restrict_upd -
     685             :  *
     686             :  * Restrict update of PK to rows unreferenced by foreign key.
     687             :  *
     688             :  * The SQL standard intends that this referential action occur exactly when
     689             :  * the update is performed, rather than after.  This appears to be
     690             :  * the only difference between "NO ACTION" and "RESTRICT".  In Postgres
     691             :  * we still implement this as an AFTER trigger, but it's non-deferrable.
     692             :  */
     693             : Datum
     694          96 : RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
     695             : {
     696             :     /* Check that this is a valid trigger call on the right time and event. */
     697          96 :     ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
     698             : 
     699             :     /* Share code with NO ACTION/DELETE cases. */
     700          96 :     return ri_restrict((TriggerData *) fcinfo->context, false);
     701             : }
     702             : 
     703             : /*
     704             :  * ri_restrict -
     705             :  *
     706             :  * Common code for ON DELETE RESTRICT, ON DELETE NO ACTION,
     707             :  * ON UPDATE RESTRICT, and ON UPDATE NO ACTION.
     708             :  */
     709             : static Datum
     710        1212 : ri_restrict(TriggerData *trigdata, bool is_no_action)
     711             : {
     712             :     const RI_ConstraintInfo *riinfo;
     713             :     Relation    fk_rel;
     714             :     Relation    pk_rel;
     715             :     TupleTableSlot *oldslot;
     716             :     RI_QueryKey qkey;
     717             :     SPIPlanPtr  qplan;
     718             : 
     719        1212 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     720             :                                     trigdata->tg_relation, true);
     721             : 
     722             :     /*
     723             :      * Get the relation descriptors of the FK and PK tables and the old tuple.
     724             :      *
     725             :      * fk_rel is opened in RowShareLock mode since that's what our eventual
     726             :      * SELECT FOR KEY SHARE will get on it.
     727             :      */
     728        1212 :     fk_rel = table_open(riinfo->fk_relid, RowShareLock);
     729        1212 :     pk_rel = trigdata->tg_relation;
     730        1212 :     oldslot = trigdata->tg_trigslot;
     731             : 
     732             :     /*
     733             :      * If another PK row now exists providing the old key values, we should
     734             :      * not do anything.  However, this check should only be made in the NO
     735             :      * ACTION case; in RESTRICT cases we don't wish to allow another row to be
     736             :      * substituted.
     737             :      */
     738        2250 :     if (is_no_action &&
     739        1038 :         ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
     740             :     {
     741          82 :         table_close(fk_rel, RowShareLock);
     742          82 :         return PointerGetDatum(NULL);
     743             :     }
     744             : 
     745        1130 :     SPI_connect();
     746             : 
     747             :     /*
     748             :      * Fetch or prepare a saved plan for the restrict lookup (it's the same
     749             :      * query for delete and update cases)
     750             :      */
     751        1130 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_RESTRICT);
     752             : 
     753        1130 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     754             :     {
     755             :         StringInfoData querybuf;
     756             :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
     757             :         char        attname[MAX_QUOTED_NAME_LEN];
     758             :         char        paramname[16];
     759             :         const char *querysep;
     760             :         Oid         queryoids[RI_MAX_NUMKEYS];
     761             :         const char *fk_only;
     762             : 
     763             :         /* ----------
     764             :          * The query string built is
     765             :          *  SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
     766             :          *         FOR KEY SHARE OF x
     767             :          * The type id's for the $ parameters are those of the
     768             :          * corresponding PK attributes.
     769             :          * ----------
     770             :          */
     771         468 :         initStringInfo(&querybuf);
     772         936 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     773         468 :             "" : "ONLY ";
     774         468 :         quoteRelationName(fkrelname, fk_rel);
     775         468 :         appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
     776             :                          fk_only, fkrelname);
     777         468 :         querysep = "WHERE";
     778        1216 :         for (int i = 0; i < riinfo->nkeys; i++)
     779             :         {
     780         748 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     781         748 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     782             : 
     783         748 :             quoteOneName(attname,
     784         748 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
     785         748 :             sprintf(paramname, "$%d", i + 1);
     786         748 :             ri_GenerateQual(&querybuf, querysep,
     787             :                             paramname, pk_type,
     788             :                             riinfo->pf_eq_oprs[i],
     789             :                             attname, fk_type);
     790         748 :             querysep = "AND";
     791         748 :             queryoids[i] = pk_type;
     792             :         }
     793         468 :         appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
     794             : 
     795             :         /* Prepare and save the plan */
     796         468 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     797             :                              &qkey, fk_rel, pk_rel);
     798             :     }
     799             : 
     800             :     /*
     801             :      * We have a plan now. Run it to check for existing references.
     802             :      */
     803        1130 :     ri_PerformCheck(riinfo, &qkey, qplan,
     804             :                     fk_rel, pk_rel,
     805             :                     oldslot, NULL,
     806        1130 :                     !is_no_action,
     807             :                     true,       /* must detect new rows */
     808        1130 :                     SPI_OK_SELECT);
     809             : 
     810         634 :     if (SPI_finish() != SPI_OK_FINISH)
     811           0 :         elog(ERROR, "SPI_finish failed");
     812             : 
     813         634 :     table_close(fk_rel, RowShareLock);
     814             : 
     815         634 :     return PointerGetDatum(NULL);
     816             : }
     817             : 
     818             : 
     819             : /*
     820             :  * RI_FKey_cascade_del -
     821             :  *
     822             :  * Cascaded delete foreign key references at delete event on PK table.
     823             :  */
     824             : Datum
     825         148 : RI_FKey_cascade_del(PG_FUNCTION_ARGS)
     826             : {
     827         148 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
     828             :     const RI_ConstraintInfo *riinfo;
     829             :     Relation    fk_rel;
     830             :     Relation    pk_rel;
     831             :     TupleTableSlot *oldslot;
     832             :     RI_QueryKey qkey;
     833             :     SPIPlanPtr  qplan;
     834             : 
     835             :     /* Check that this is a valid trigger call on the right time and event. */
     836         148 :     ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
     837             : 
     838         148 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     839             :                                     trigdata->tg_relation, true);
     840             : 
     841             :     /*
     842             :      * Get the relation descriptors of the FK and PK tables and the old tuple.
     843             :      *
     844             :      * fk_rel is opened in RowExclusiveLock mode since that's what our
     845             :      * eventual DELETE will get on it.
     846             :      */
     847         148 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
     848         148 :     pk_rel = trigdata->tg_relation;
     849         148 :     oldslot = trigdata->tg_trigslot;
     850             : 
     851         148 :     SPI_connect();
     852             : 
     853             :     /* Fetch or prepare a saved plan for the cascaded delete */
     854         148 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONDELETE);
     855             : 
     856         148 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     857             :     {
     858             :         StringInfoData querybuf;
     859             :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
     860             :         char        attname[MAX_QUOTED_NAME_LEN];
     861             :         char        paramname[16];
     862             :         const char *querysep;
     863             :         Oid         queryoids[RI_MAX_NUMKEYS];
     864             :         const char *fk_only;
     865             : 
     866             :         /* ----------
     867             :          * The query string built is
     868             :          *  DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
     869             :          * The type id's for the $ parameters are those of the
     870             :          * corresponding PK attributes.
     871             :          * ----------
     872             :          */
     873          92 :         initStringInfo(&querybuf);
     874         184 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     875          92 :             "" : "ONLY ";
     876          92 :         quoteRelationName(fkrelname, fk_rel);
     877          92 :         appendStringInfo(&querybuf, "DELETE FROM %s%s",
     878             :                          fk_only, fkrelname);
     879          92 :         querysep = "WHERE";
     880         210 :         for (int i = 0; i < riinfo->nkeys; i++)
     881             :         {
     882         118 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     883         118 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     884             : 
     885         118 :             quoteOneName(attname,
     886         118 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
     887         118 :             sprintf(paramname, "$%d", i + 1);
     888         118 :             ri_GenerateQual(&querybuf, querysep,
     889             :                             paramname, pk_type,
     890             :                             riinfo->pf_eq_oprs[i],
     891             :                             attname, fk_type);
     892         118 :             querysep = "AND";
     893         118 :             queryoids[i] = pk_type;
     894             :         }
     895             : 
     896             :         /* Prepare and save the plan */
     897          92 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
     898             :                              &qkey, fk_rel, pk_rel);
     899             :     }
     900             : 
     901             :     /*
     902             :      * We have a plan now. Build up the arguments from the key values in the
     903             :      * deleted PK tuple and delete the referencing rows
     904             :      */
     905         148 :     ri_PerformCheck(riinfo, &qkey, qplan,
     906             :                     fk_rel, pk_rel,
     907             :                     oldslot, NULL,
     908             :                     false,
     909             :                     true,       /* must detect new rows */
     910             :                     SPI_OK_DELETE);
     911             : 
     912         146 :     if (SPI_finish() != SPI_OK_FINISH)
     913           0 :         elog(ERROR, "SPI_finish failed");
     914             : 
     915         146 :     table_close(fk_rel, RowExclusiveLock);
     916             : 
     917         146 :     return PointerGetDatum(NULL);
     918             : }
     919             : 
     920             : 
     921             : /*
     922             :  * RI_FKey_cascade_upd -
     923             :  *
     924             :  * Cascaded update foreign key references at update event on PK table.
     925             :  */
     926             : Datum
     927         204 : RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
     928             : {
     929         204 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
     930             :     const RI_ConstraintInfo *riinfo;
     931             :     Relation    fk_rel;
     932             :     Relation    pk_rel;
     933             :     TupleTableSlot *newslot;
     934             :     TupleTableSlot *oldslot;
     935             :     RI_QueryKey qkey;
     936             :     SPIPlanPtr  qplan;
     937             : 
     938             :     /* Check that this is a valid trigger call on the right time and event. */
     939         204 :     ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
     940             : 
     941         204 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
     942             :                                     trigdata->tg_relation, true);
     943             : 
     944             :     /*
     945             :      * Get the relation descriptors of the FK and PK tables and the new and
     946             :      * old tuple.
     947             :      *
     948             :      * fk_rel is opened in RowExclusiveLock mode since that's what our
     949             :      * eventual UPDATE will get on it.
     950             :      */
     951         204 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
     952         204 :     pk_rel = trigdata->tg_relation;
     953         204 :     newslot = trigdata->tg_newslot;
     954         204 :     oldslot = trigdata->tg_trigslot;
     955             : 
     956         204 :     SPI_connect();
     957             : 
     958             :     /* Fetch or prepare a saved plan for the cascaded update */
     959         204 :     ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONUPDATE);
     960             : 
     961         204 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
     962             :     {
     963             :         StringInfoData querybuf;
     964             :         StringInfoData qualbuf;
     965             :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
     966             :         char        attname[MAX_QUOTED_NAME_LEN];
     967             :         char        paramname[16];
     968             :         const char *querysep;
     969             :         const char *qualsep;
     970             :         Oid         queryoids[RI_MAX_NUMKEYS * 2];
     971             :         const char *fk_only;
     972             : 
     973             :         /* ----------
     974             :          * The query string built is
     975             :          *  UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
     976             :          *          WHERE $n = fkatt1 [AND ...]
     977             :          * The type id's for the $ parameters are those of the
     978             :          * corresponding PK attributes.  Note that we are assuming
     979             :          * there is an assignment cast from the PK to the FK type;
     980             :          * else the parser will fail.
     981             :          * ----------
     982             :          */
     983         116 :         initStringInfo(&querybuf);
     984         116 :         initStringInfo(&qualbuf);
     985         232 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
     986         116 :             "" : "ONLY ";
     987         116 :         quoteRelationName(fkrelname, fk_rel);
     988         116 :         appendStringInfo(&querybuf, "UPDATE %s%s SET",
     989             :                          fk_only, fkrelname);
     990         116 :         querysep = "";
     991         116 :         qualsep = "WHERE";
     992         260 :         for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
     993             :         {
     994         144 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
     995         144 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
     996             : 
     997         144 :             quoteOneName(attname,
     998         144 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
     999         144 :             appendStringInfo(&querybuf,
    1000             :                              "%s %s = $%d",
    1001             :                              querysep, attname, i + 1);
    1002         144 :             sprintf(paramname, "$%d", j + 1);
    1003         144 :             ri_GenerateQual(&qualbuf, qualsep,
    1004             :                             paramname, pk_type,
    1005             :                             riinfo->pf_eq_oprs[i],
    1006             :                             attname, fk_type);
    1007         144 :             querysep = ",";
    1008         144 :             qualsep = "AND";
    1009         144 :             queryoids[i] = pk_type;
    1010         144 :             queryoids[j] = pk_type;
    1011             :         }
    1012         116 :         appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
    1013             : 
    1014             :         /* Prepare and save the plan */
    1015         116 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
    1016             :                              &qkey, fk_rel, pk_rel);
    1017             :     }
    1018             : 
    1019             :     /*
    1020             :      * We have a plan now. Run it to update the existing references.
    1021             :      */
    1022         204 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1023             :                     fk_rel, pk_rel,
    1024             :                     oldslot, newslot,
    1025             :                     false,
    1026             :                     true,       /* must detect new rows */
    1027             :                     SPI_OK_UPDATE);
    1028             : 
    1029         204 :     if (SPI_finish() != SPI_OK_FINISH)
    1030           0 :         elog(ERROR, "SPI_finish failed");
    1031             : 
    1032         204 :     table_close(fk_rel, RowExclusiveLock);
    1033             : 
    1034         204 :     return PointerGetDatum(NULL);
    1035             : }
    1036             : 
    1037             : 
    1038             : /*
    1039             :  * RI_FKey_setnull_del -
    1040             :  *
    1041             :  * Set foreign key references to NULL values at delete event on PK table.
    1042             :  */
    1043             : Datum
    1044          98 : RI_FKey_setnull_del(PG_FUNCTION_ARGS)
    1045             : {
    1046             :     /* Check that this is a valid trigger call on the right time and event. */
    1047          98 :     ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
    1048             : 
    1049             :     /* Share code with UPDATE case */
    1050          98 :     return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
    1051             : }
    1052             : 
    1053             : /*
    1054             :  * RI_FKey_setnull_upd -
    1055             :  *
    1056             :  * Set foreign key references to NULL at update event on PK table.
    1057             :  */
    1058             : Datum
    1059          30 : RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
    1060             : {
    1061             :     /* Check that this is a valid trigger call on the right time and event. */
    1062          30 :     ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
    1063             : 
    1064             :     /* Share code with DELETE case */
    1065          30 :     return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
    1066             : }
    1067             : 
    1068             : /*
    1069             :  * RI_FKey_setdefault_del -
    1070             :  *
    1071             :  * Set foreign key references to defaults at delete event on PK table.
    1072             :  */
    1073             : Datum
    1074          84 : RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
    1075             : {
    1076             :     /* Check that this is a valid trigger call on the right time and event. */
    1077          84 :     ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
    1078             : 
    1079             :     /* Share code with UPDATE case */
    1080          84 :     return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
    1081             : }
    1082             : 
    1083             : /*
    1084             :  * RI_FKey_setdefault_upd -
    1085             :  *
    1086             :  * Set foreign key references to defaults at update event on PK table.
    1087             :  */
    1088             : Datum
    1089          48 : RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
    1090             : {
    1091             :     /* Check that this is a valid trigger call on the right time and event. */
    1092          48 :     ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
    1093             : 
    1094             :     /* Share code with DELETE case */
    1095          48 :     return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
    1096             : }
    1097             : 
    1098             : /*
    1099             :  * ri_set -
    1100             :  *
    1101             :  * Common code for ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE SET
    1102             :  * NULL, and ON UPDATE SET DEFAULT.
    1103             :  */
    1104             : static Datum
    1105         260 : ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
    1106             : {
    1107             :     const RI_ConstraintInfo *riinfo;
    1108             :     Relation    fk_rel;
    1109             :     Relation    pk_rel;
    1110             :     TupleTableSlot *oldslot;
    1111             :     RI_QueryKey qkey;
    1112             :     SPIPlanPtr  qplan;
    1113             :     int32       queryno;
    1114             : 
    1115         260 :     riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
    1116             :                                     trigdata->tg_relation, true);
    1117             : 
    1118             :     /*
    1119             :      * Get the relation descriptors of the FK and PK tables and the old tuple.
    1120             :      *
    1121             :      * fk_rel is opened in RowExclusiveLock mode since that's what our
    1122             :      * eventual UPDATE will get on it.
    1123             :      */
    1124         260 :     fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
    1125         260 :     pk_rel = trigdata->tg_relation;
    1126         260 :     oldslot = trigdata->tg_trigslot;
    1127             : 
    1128         260 :     SPI_connect();
    1129             : 
    1130             :     /*
    1131             :      * Fetch or prepare a saved plan for the trigger.
    1132             :      */
    1133         260 :     switch (tgkind)
    1134             :     {
    1135          78 :         case RI_TRIGTYPE_UPDATE:
    1136          78 :             queryno = is_set_null
    1137             :                 ? RI_PLAN_SETNULL_ONUPDATE
    1138          78 :                 : RI_PLAN_SETDEFAULT_ONUPDATE;
    1139          78 :             break;
    1140         182 :         case RI_TRIGTYPE_DELETE:
    1141         182 :             queryno = is_set_null
    1142             :                 ? RI_PLAN_SETNULL_ONDELETE
    1143         182 :                 : RI_PLAN_SETDEFAULT_ONDELETE;
    1144         182 :             break;
    1145           0 :         default:
    1146           0 :             elog(ERROR, "invalid tgkind passed to ri_set");
    1147             :     }
    1148             : 
    1149         260 :     ri_BuildQueryKey(&qkey, riinfo, queryno);
    1150             : 
    1151         260 :     if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
    1152             :     {
    1153             :         StringInfoData querybuf;
    1154             :         char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1155             :         char        attname[MAX_QUOTED_NAME_LEN];
    1156             :         char        paramname[16];
    1157             :         const char *querysep;
    1158             :         const char *qualsep;
    1159             :         Oid         queryoids[RI_MAX_NUMKEYS];
    1160             :         const char *fk_only;
    1161             :         int         num_cols_to_set;
    1162             :         const int16 *set_cols;
    1163             : 
    1164         154 :         switch (tgkind)
    1165             :         {
    1166          48 :             case RI_TRIGTYPE_UPDATE:
    1167          48 :                 num_cols_to_set = riinfo->nkeys;
    1168          48 :                 set_cols = riinfo->fk_attnums;
    1169          48 :                 break;
    1170         106 :             case RI_TRIGTYPE_DELETE:
    1171             : 
    1172             :                 /*
    1173             :                  * If confdelsetcols are present, then we only update the
    1174             :                  * columns specified in that array, otherwise we update all
    1175             :                  * the referencing columns.
    1176             :                  */
    1177         106 :                 if (riinfo->ndelsetcols != 0)
    1178             :                 {
    1179          28 :                     num_cols_to_set = riinfo->ndelsetcols;
    1180          28 :                     set_cols = riinfo->confdelsetcols;
    1181             :                 }
    1182             :                 else
    1183             :                 {
    1184          78 :                     num_cols_to_set = riinfo->nkeys;
    1185          78 :                     set_cols = riinfo->fk_attnums;
    1186             :                 }
    1187         106 :                 break;
    1188           0 :             default:
    1189           0 :                 elog(ERROR, "invalid tgkind passed to ri_set");
    1190             :         }
    1191             : 
    1192             :         /* ----------
    1193             :          * The query string built is
    1194             :          *  UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
    1195             :          *          WHERE $1 = fkatt1 [AND ...]
    1196             :          * The type id's for the $ parameters are those of the
    1197             :          * corresponding PK attributes.
    1198             :          * ----------
    1199             :          */
    1200         154 :         initStringInfo(&querybuf);
    1201         308 :         fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1202         154 :             "" : "ONLY ";
    1203         154 :         quoteRelationName(fkrelname, fk_rel);
    1204         154 :         appendStringInfo(&querybuf, "UPDATE %s%s SET",
    1205             :                          fk_only, fkrelname);
    1206             : 
    1207             :         /*
    1208             :          * Add assignment clauses
    1209             :          */
    1210         154 :         querysep = "";
    1211         406 :         for (int i = 0; i < num_cols_to_set; i++)
    1212             :         {
    1213         252 :             quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
    1214         252 :             appendStringInfo(&querybuf,
    1215             :                              "%s %s = %s",
    1216             :                              querysep, attname,
    1217             :                              is_set_null ? "NULL" : "DEFAULT");
    1218         252 :             querysep = ",";
    1219             :         }
    1220             : 
    1221             :         /*
    1222             :          * Add WHERE clause
    1223             :          */
    1224         154 :         qualsep = "WHERE";
    1225         434 :         for (int i = 0; i < riinfo->nkeys; i++)
    1226             :         {
    1227         280 :             Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1228         280 :             Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1229             : 
    1230         280 :             quoteOneName(attname,
    1231         280 :                          RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1232             : 
    1233         280 :             sprintf(paramname, "$%d", i + 1);
    1234         280 :             ri_GenerateQual(&querybuf, qualsep,
    1235             :                             paramname, pk_type,
    1236             :                             riinfo->pf_eq_oprs[i],
    1237             :                             attname, fk_type);
    1238         280 :             qualsep = "AND";
    1239         280 :             queryoids[i] = pk_type;
    1240             :         }
    1241             : 
    1242             :         /* Prepare and save the plan */
    1243         154 :         qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
    1244             :                              &qkey, fk_rel, pk_rel);
    1245             :     }
    1246             : 
    1247             :     /*
    1248             :      * We have a plan now. Run it to update the existing references.
    1249             :      */
    1250         260 :     ri_PerformCheck(riinfo, &qkey, qplan,
    1251             :                     fk_rel, pk_rel,
    1252             :                     oldslot, NULL,
    1253             :                     false,
    1254             :                     true,       /* must detect new rows */
    1255             :                     SPI_OK_UPDATE);
    1256             : 
    1257         258 :     if (SPI_finish() != SPI_OK_FINISH)
    1258           0 :         elog(ERROR, "SPI_finish failed");
    1259             : 
    1260         258 :     table_close(fk_rel, RowExclusiveLock);
    1261             : 
    1262         258 :     if (is_set_null)
    1263         126 :         return PointerGetDatum(NULL);
    1264             :     else
    1265             :     {
    1266             :         /*
    1267             :          * If we just deleted or updated the PK row whose key was equal to the
    1268             :          * FK columns' default values, and a referencing row exists in the FK
    1269             :          * table, we would have updated that row to the same values it already
    1270             :          * had --- and RI_FKey_fk_upd_check_required would hence believe no
    1271             :          * check is necessary.  So we need to do another lookup now and in
    1272             :          * case a reference still exists, abort the operation.  That is
    1273             :          * already implemented in the NO ACTION trigger, so just run it. (This
    1274             :          * recheck is only needed in the SET DEFAULT case, since CASCADE would
    1275             :          * remove such rows in case of a DELETE operation or would change the
    1276             :          * FK key values in case of an UPDATE, while SET NULL is certain to
    1277             :          * result in rows that satisfy the FK constraint.)
    1278             :          */
    1279         132 :         return ri_restrict(trigdata, true);
    1280             :     }
    1281             : }
    1282             : 
    1283             : 
    1284             : /*
    1285             :  * RI_FKey_pk_upd_check_required -
    1286             :  *
    1287             :  * Check if we really need to fire the RI trigger for an update or delete to a PK
    1288             :  * relation.  This is called by the AFTER trigger queue manager to see if
    1289             :  * it can skip queuing an instance of an RI trigger.  Returns true if the
    1290             :  * trigger must be fired, false if we can prove the constraint will still
    1291             :  * be satisfied.
    1292             :  *
    1293             :  * newslot will be NULL if this is called for a delete.
    1294             :  */
    1295             : bool
    1296        2440 : RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel,
    1297             :                               TupleTableSlot *oldslot, TupleTableSlot *newslot)
    1298             : {
    1299             :     const RI_ConstraintInfo *riinfo;
    1300             : 
    1301        2440 :     riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
    1302             : 
    1303             :     /*
    1304             :      * If any old key value is NULL, the row could not have been referenced by
    1305             :      * an FK row, so no check is needed.
    1306             :      */
    1307        2440 :     if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
    1308           6 :         return false;
    1309             : 
    1310             :     /* If all old and new key values are equal, no check is needed */
    1311        2434 :     if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
    1312         536 :         return false;
    1313             : 
    1314             :     /* Else we need to fire the trigger. */
    1315        1898 :     return true;
    1316             : }
    1317             : 
    1318             : /*
    1319             :  * RI_FKey_fk_upd_check_required -
    1320             :  *
    1321             :  * Check if we really need to fire the RI trigger for an update to an FK
    1322             :  * relation.  This is called by the AFTER trigger queue manager to see if
    1323             :  * it can skip queuing an instance of an RI trigger.  Returns true if the
    1324             :  * trigger must be fired, false if we can prove the constraint will still
    1325             :  * be satisfied.
    1326             :  */
    1327             : bool
    1328        1080 : RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel,
    1329             :                               TupleTableSlot *oldslot, TupleTableSlot *newslot)
    1330             : {
    1331             :     const RI_ConstraintInfo *riinfo;
    1332             :     int         ri_nullcheck;
    1333             : 
    1334             :     /*
    1335             :      * AfterTriggerSaveEvent() handles things such that this function is never
    1336             :      * called for partitioned tables.
    1337             :      */
    1338             :     Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
    1339             : 
    1340        1080 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1341             : 
    1342        1080 :     ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
    1343             : 
    1344             :     /*
    1345             :      * If all new key values are NULL, the row satisfies the constraint, so no
    1346             :      * check is needed.
    1347             :      */
    1348        1080 :     if (ri_nullcheck == RI_KEYS_ALL_NULL)
    1349         126 :         return false;
    1350             : 
    1351             :     /*
    1352             :      * If some new key values are NULL, the behavior depends on the match
    1353             :      * type.
    1354             :      */
    1355         954 :     else if (ri_nullcheck == RI_KEYS_SOME_NULL)
    1356             :     {
    1357          30 :         switch (riinfo->confmatchtype)
    1358             :         {
    1359          24 :             case FKCONSTR_MATCH_SIMPLE:
    1360             : 
    1361             :                 /*
    1362             :                  * If any new key value is NULL, the row must satisfy the
    1363             :                  * constraint, so no check is needed.
    1364             :                  */
    1365          24 :                 return false;
    1366             : 
    1367           0 :             case FKCONSTR_MATCH_PARTIAL:
    1368             : 
    1369             :                 /*
    1370             :                  * Don't know, must run full check.
    1371             :                  */
    1372           0 :                 break;
    1373             : 
    1374           6 :             case FKCONSTR_MATCH_FULL:
    1375             : 
    1376             :                 /*
    1377             :                  * If some new key values are NULL, the row fails the
    1378             :                  * constraint.  We must not throw error here, because the row
    1379             :                  * might get invalidated before the constraint is to be
    1380             :                  * checked, but we should queue the event to apply the check
    1381             :                  * later.
    1382             :                  */
    1383           6 :                 return true;
    1384             :         }
    1385         924 :     }
    1386             : 
    1387             :     /*
    1388             :      * Continues here for no new key values are NULL, or we couldn't decide
    1389             :      * yet.
    1390             :      */
    1391             : 
    1392             :     /*
    1393             :      * If the original row was inserted by our own transaction, we must fire
    1394             :      * the trigger whether or not the keys are equal.  This is because our
    1395             :      * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
    1396             :      * not do anything; so we had better do the UPDATE check.  (We could skip
    1397             :      * this if we knew the INSERT trigger already fired, but there is no easy
    1398             :      * way to know that.)
    1399             :      */
    1400         924 :     if (slot_is_current_xact_tuple(oldslot))
    1401         124 :         return true;
    1402             : 
    1403             :     /* If all old and new key values are equal, no check is needed */
    1404         800 :     if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
    1405         464 :         return false;
    1406             : 
    1407             :     /* Else we need to fire the trigger. */
    1408         336 :     return true;
    1409             : }
    1410             : 
    1411             : /*
    1412             :  * RI_Initial_Check -
    1413             :  *
    1414             :  * Check an entire table for non-matching values using a single query.
    1415             :  * This is not a trigger procedure, but is called during ALTER TABLE
    1416             :  * ADD FOREIGN KEY to validate the initial table contents.
    1417             :  *
    1418             :  * We expect that the caller has made provision to prevent any problems
    1419             :  * caused by concurrent actions. This could be either by locking rel and
    1420             :  * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
    1421             :  * that triggers implementing the checks are already active.
    1422             :  * Hence, we do not need to lock individual rows for the check.
    1423             :  *
    1424             :  * If the check fails because the current user doesn't have permissions
    1425             :  * to read both tables, return false to let our caller know that they will
    1426             :  * need to do something else to check the constraint.
    1427             :  */
    1428             : bool
    1429         962 : RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
    1430             : {
    1431             :     const RI_ConstraintInfo *riinfo;
    1432             :     StringInfoData querybuf;
    1433             :     char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
    1434             :     char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1435             :     char        pkattname[MAX_QUOTED_NAME_LEN + 3];
    1436             :     char        fkattname[MAX_QUOTED_NAME_LEN + 3];
    1437             :     RangeTblEntry *rte;
    1438             :     RTEPermissionInfo *pk_perminfo;
    1439             :     RTEPermissionInfo *fk_perminfo;
    1440         962 :     List       *rtes = NIL;
    1441         962 :     List       *perminfos = NIL;
    1442             :     const char *sep;
    1443             :     const char *fk_only;
    1444             :     const char *pk_only;
    1445             :     int         save_nestlevel;
    1446             :     char        workmembuf[32];
    1447             :     int         spi_result;
    1448             :     SPIPlanPtr  qplan;
    1449             : 
    1450         962 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1451             : 
    1452             :     /*
    1453             :      * Check to make sure current user has enough permissions to do the test
    1454             :      * query.  (If not, caller can fall back to the trigger method, which
    1455             :      * works because it changes user IDs on the fly.)
    1456             :      *
    1457             :      * XXX are there any other show-stopper conditions to check?
    1458             :      */
    1459         962 :     pk_perminfo = makeNode(RTEPermissionInfo);
    1460         962 :     pk_perminfo->relid = RelationGetRelid(pk_rel);
    1461         962 :     pk_perminfo->requiredPerms = ACL_SELECT;
    1462         962 :     perminfos = lappend(perminfos, pk_perminfo);
    1463         962 :     rte = makeNode(RangeTblEntry);
    1464         962 :     rte->rtekind = RTE_RELATION;
    1465         962 :     rte->relid = RelationGetRelid(pk_rel);
    1466         962 :     rte->relkind = pk_rel->rd_rel->relkind;
    1467         962 :     rte->rellockmode = AccessShareLock;
    1468         962 :     rte->perminfoindex = list_length(perminfos);
    1469         962 :     rtes = lappend(rtes, rte);
    1470             : 
    1471         962 :     fk_perminfo = makeNode(RTEPermissionInfo);
    1472         962 :     fk_perminfo->relid = RelationGetRelid(fk_rel);
    1473         962 :     fk_perminfo->requiredPerms = ACL_SELECT;
    1474         962 :     perminfos = lappend(perminfos, fk_perminfo);
    1475         962 :     rte = makeNode(RangeTblEntry);
    1476         962 :     rte->rtekind = RTE_RELATION;
    1477         962 :     rte->relid = RelationGetRelid(fk_rel);
    1478         962 :     rte->relkind = fk_rel->rd_rel->relkind;
    1479         962 :     rte->rellockmode = AccessShareLock;
    1480         962 :     rte->perminfoindex = list_length(perminfos);
    1481         962 :     rtes = lappend(rtes, rte);
    1482             : 
    1483        2244 :     for (int i = 0; i < riinfo->nkeys; i++)
    1484             :     {
    1485             :         int         attno;
    1486             : 
    1487        1282 :         attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
    1488        1282 :         pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
    1489             : 
    1490        1282 :         attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
    1491        1282 :         fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
    1492             :     }
    1493             : 
    1494         962 :     if (!ExecCheckPermissions(rtes, perminfos, false))
    1495          12 :         return false;
    1496             : 
    1497             :     /*
    1498             :      * Also punt if RLS is enabled on either table unless this role has the
    1499             :      * bypassrls right or is the table owner of the table(s) involved which
    1500             :      * have RLS enabled.
    1501             :      */
    1502         950 :     if (!has_bypassrls_privilege(GetUserId()) &&
    1503           0 :         ((pk_rel->rd_rel->relrowsecurity &&
    1504           0 :           !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
    1505           0 :                              GetUserId())) ||
    1506           0 :          (fk_rel->rd_rel->relrowsecurity &&
    1507           0 :           !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
    1508             :                              GetUserId()))))
    1509           0 :         return false;
    1510             : 
    1511             :     /*----------
    1512             :      * The query string built is:
    1513             :      *  SELECT fk.keycols FROM [ONLY] relname fk
    1514             :      *   LEFT OUTER JOIN [ONLY] pkrelname pk
    1515             :      *   ON (pk.pkkeycol1=fk.keycol1 [AND ...])
    1516             :      *   WHERE pk.pkkeycol1 IS NULL AND
    1517             :      * For MATCH SIMPLE:
    1518             :      *   (fk.keycol1 IS NOT NULL [AND ...])
    1519             :      * For MATCH FULL:
    1520             :      *   (fk.keycol1 IS NOT NULL [OR ...])
    1521             :      *
    1522             :      * We attach COLLATE clauses to the operators when comparing columns
    1523             :      * that have different collations.
    1524             :      *----------
    1525             :      */
    1526         950 :     initStringInfo(&querybuf);
    1527         950 :     appendStringInfoString(&querybuf, "SELECT ");
    1528         950 :     sep = "";
    1529        2208 :     for (int i = 0; i < riinfo->nkeys; i++)
    1530             :     {
    1531        1258 :         quoteOneName(fkattname,
    1532        1258 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1533        1258 :         appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
    1534        1258 :         sep = ", ";
    1535             :     }
    1536             : 
    1537         950 :     quoteRelationName(pkrelname, pk_rel);
    1538         950 :     quoteRelationName(fkrelname, fk_rel);
    1539        1900 :     fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1540         950 :         "" : "ONLY ";
    1541        1900 :     pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1542         950 :         "" : "ONLY ";
    1543         950 :     appendStringInfo(&querybuf,
    1544             :                      " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
    1545             :                      fk_only, fkrelname, pk_only, pkrelname);
    1546             : 
    1547         950 :     strcpy(pkattname, "pk.");
    1548         950 :     strcpy(fkattname, "fk.");
    1549         950 :     sep = "(";
    1550        2208 :     for (int i = 0; i < riinfo->nkeys; i++)
    1551             :     {
    1552        1258 :         Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1553        1258 :         Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1554        1258 :         Oid         pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
    1555        1258 :         Oid         fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
    1556             : 
    1557        1258 :         quoteOneName(pkattname + 3,
    1558        1258 :                      RIAttName(pk_rel, riinfo->pk_attnums[i]));
    1559        1258 :         quoteOneName(fkattname + 3,
    1560        1258 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1561        1258 :         ri_GenerateQual(&querybuf, sep,
    1562             :                         pkattname, pk_type,
    1563             :                         riinfo->pf_eq_oprs[i],
    1564             :                         fkattname, fk_type);
    1565        1258 :         if (pk_coll != fk_coll)
    1566          12 :             ri_GenerateQualCollation(&querybuf, pk_coll);
    1567        1258 :         sep = "AND";
    1568             :     }
    1569             : 
    1570             :     /*
    1571             :      * It's sufficient to test any one pk attribute for null to detect a join
    1572             :      * failure.
    1573             :      */
    1574         950 :     quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
    1575         950 :     appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
    1576             : 
    1577         950 :     sep = "";
    1578        2208 :     for (int i = 0; i < riinfo->nkeys; i++)
    1579             :     {
    1580        1258 :         quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1581        1258 :         appendStringInfo(&querybuf,
    1582             :                          "%sfk.%s IS NOT NULL",
    1583             :                          sep, fkattname);
    1584        1258 :         switch (riinfo->confmatchtype)
    1585             :         {
    1586        1158 :             case FKCONSTR_MATCH_SIMPLE:
    1587        1158 :                 sep = " AND ";
    1588        1158 :                 break;
    1589         100 :             case FKCONSTR_MATCH_FULL:
    1590         100 :                 sep = " OR ";
    1591         100 :                 break;
    1592             :         }
    1593        1258 :     }
    1594         950 :     appendStringInfoChar(&querybuf, ')');
    1595             : 
    1596             :     /*
    1597             :      * Temporarily increase work_mem so that the check query can be executed
    1598             :      * more efficiently.  It seems okay to do this because the query is simple
    1599             :      * enough to not use a multiple of work_mem, and one typically would not
    1600             :      * have many large foreign-key validations happening concurrently.  So
    1601             :      * this seems to meet the criteria for being considered a "maintenance"
    1602             :      * operation, and accordingly we use maintenance_work_mem.  However, we
    1603             :      * must also set hash_mem_multiplier to 1, since it is surely not okay to
    1604             :      * let that get applied to the maintenance_work_mem value.
    1605             :      *
    1606             :      * We use the equivalent of a function SET option to allow the setting to
    1607             :      * persist for exactly the duration of the check query.  guc.c also takes
    1608             :      * care of undoing the setting on error.
    1609             :      */
    1610         950 :     save_nestlevel = NewGUCNestLevel();
    1611             : 
    1612         950 :     snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
    1613         950 :     (void) set_config_option("work_mem", workmembuf,
    1614             :                              PGC_USERSET, PGC_S_SESSION,
    1615             :                              GUC_ACTION_SAVE, true, 0, false);
    1616         950 :     (void) set_config_option("hash_mem_multiplier", "1",
    1617             :                              PGC_USERSET, PGC_S_SESSION,
    1618             :                              GUC_ACTION_SAVE, true, 0, false);
    1619             : 
    1620         950 :     SPI_connect();
    1621             : 
    1622             :     /*
    1623             :      * Generate the plan.  We don't need to cache it, and there are no
    1624             :      * arguments to the plan.
    1625             :      */
    1626         950 :     qplan = SPI_prepare(querybuf.data, 0, NULL);
    1627             : 
    1628         950 :     if (qplan == NULL)
    1629           0 :         elog(ERROR, "SPI_prepare returned %s for %s",
    1630             :              SPI_result_code_string(SPI_result), querybuf.data);
    1631             : 
    1632             :     /*
    1633             :      * Run the plan.  For safety we force a current snapshot to be used. (In
    1634             :      * transaction-snapshot mode, this arguably violates transaction isolation
    1635             :      * rules, but we really haven't got much choice.) We don't need to
    1636             :      * register the snapshot, because SPI_execute_snapshot will see to it. We
    1637             :      * need at most one tuple returned, so pass limit = 1.
    1638             :      */
    1639         950 :     spi_result = SPI_execute_snapshot(qplan,
    1640             :                                       NULL, NULL,
    1641             :                                       GetLatestSnapshot(),
    1642             :                                       InvalidSnapshot,
    1643             :                                       true, false, 1);
    1644             : 
    1645             :     /* Check result */
    1646         950 :     if (spi_result != SPI_OK_SELECT)
    1647           0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    1648             : 
    1649             :     /* Did we find a tuple violating the constraint? */
    1650         950 :     if (SPI_processed > 0)
    1651             :     {
    1652             :         TupleTableSlot *slot;
    1653          62 :         HeapTuple   tuple = SPI_tuptable->vals[0];
    1654          62 :         TupleDesc   tupdesc = SPI_tuptable->tupdesc;
    1655             :         RI_ConstraintInfo fake_riinfo;
    1656             : 
    1657          62 :         slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
    1658             : 
    1659          62 :         heap_deform_tuple(tuple, tupdesc,
    1660             :                           slot->tts_values, slot->tts_isnull);
    1661          62 :         ExecStoreVirtualTuple(slot);
    1662             : 
    1663             :         /*
    1664             :          * The columns to look at in the result tuple are 1..N, not whatever
    1665             :          * they are in the fk_rel.  Hack up riinfo so that the subroutines
    1666             :          * called here will behave properly.
    1667             :          *
    1668             :          * In addition to this, we have to pass the correct tupdesc to
    1669             :          * ri_ReportViolation, overriding its normal habit of using the pk_rel
    1670             :          * or fk_rel's tupdesc.
    1671             :          */
    1672          62 :         memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
    1673         142 :         for (int i = 0; i < fake_riinfo.nkeys; i++)
    1674          80 :             fake_riinfo.fk_attnums[i] = i + 1;
    1675             : 
    1676             :         /*
    1677             :          * If it's MATCH FULL, and there are any nulls in the FK keys,
    1678             :          * complain about that rather than the lack of a match.  MATCH FULL
    1679             :          * disallows partially-null FK rows.
    1680             :          */
    1681          86 :         if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
    1682          24 :             ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
    1683          12 :             ereport(ERROR,
    1684             :                     (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    1685             :                      errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
    1686             :                             RelationGetRelationName(fk_rel),
    1687             :                             NameStr(fake_riinfo.conname)),
    1688             :                      errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
    1689             :                      errtableconstraint(fk_rel,
    1690             :                                         NameStr(fake_riinfo.conname))));
    1691             : 
    1692             :         /*
    1693             :          * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
    1694             :          * query, which isn't true, but will cause it to use
    1695             :          * fake_riinfo.fk_attnums as we need.
    1696             :          */
    1697          50 :         ri_ReportViolation(&fake_riinfo,
    1698             :                            pk_rel, fk_rel,
    1699             :                            slot, tupdesc,
    1700             :                            RI_PLAN_CHECK_LOOKUPPK, false, false);
    1701             : 
    1702             :         ExecDropSingleTupleTableSlot(slot);
    1703             :     }
    1704             : 
    1705         888 :     if (SPI_finish() != SPI_OK_FINISH)
    1706           0 :         elog(ERROR, "SPI_finish failed");
    1707             : 
    1708             :     /*
    1709             :      * Restore work_mem and hash_mem_multiplier.
    1710             :      */
    1711         888 :     AtEOXact_GUC(true, save_nestlevel);
    1712             : 
    1713         888 :     return true;
    1714             : }
    1715             : 
    1716             : /*
    1717             :  * RI_PartitionRemove_Check -
    1718             :  *
    1719             :  * Verify no referencing values exist, when a partition is detached on
    1720             :  * the referenced side of a foreign key constraint.
    1721             :  */
    1722             : void
    1723          86 : RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
    1724             : {
    1725             :     const RI_ConstraintInfo *riinfo;
    1726             :     StringInfoData querybuf;
    1727             :     char       *constraintDef;
    1728             :     char        pkrelname[MAX_QUOTED_REL_NAME_LEN];
    1729             :     char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
    1730             :     char        pkattname[MAX_QUOTED_NAME_LEN + 3];
    1731             :     char        fkattname[MAX_QUOTED_NAME_LEN + 3];
    1732             :     const char *sep;
    1733             :     const char *fk_only;
    1734             :     int         save_nestlevel;
    1735             :     char        workmembuf[32];
    1736             :     int         spi_result;
    1737             :     SPIPlanPtr  qplan;
    1738             :     int         i;
    1739             : 
    1740          86 :     riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
    1741             : 
    1742             :     /*
    1743             :      * We don't check permissions before displaying the error message, on the
    1744             :      * assumption that the user detaching the partition must have enough
    1745             :      * privileges to examine the table contents anyhow.
    1746             :      */
    1747             : 
    1748             :     /*----------
    1749             :      * The query string built is:
    1750             :      *  SELECT fk.keycols FROM [ONLY] relname fk
    1751             :      *    JOIN pkrelname pk
    1752             :      *    ON (pk.pkkeycol1=fk.keycol1 [AND ...])
    1753             :      *    WHERE (<partition constraint>) AND
    1754             :      * For MATCH SIMPLE:
    1755             :      *   (fk.keycol1 IS NOT NULL [AND ...])
    1756             :      * For MATCH FULL:
    1757             :      *   (fk.keycol1 IS NOT NULL [OR ...])
    1758             :      *
    1759             :      * We attach COLLATE clauses to the operators when comparing columns
    1760             :      * that have different collations.
    1761             :      *----------
    1762             :      */
    1763          86 :     initStringInfo(&querybuf);
    1764          86 :     appendStringInfoString(&querybuf, "SELECT ");
    1765          86 :     sep = "";
    1766         172 :     for (i = 0; i < riinfo->nkeys; i++)
    1767             :     {
    1768          86 :         quoteOneName(fkattname,
    1769          86 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1770          86 :         appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
    1771          86 :         sep = ", ";
    1772             :     }
    1773             : 
    1774          86 :     quoteRelationName(pkrelname, pk_rel);
    1775          86 :     quoteRelationName(fkrelname, fk_rel);
    1776         172 :     fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
    1777          86 :         "" : "ONLY ";
    1778          86 :     appendStringInfo(&querybuf,
    1779             :                      " FROM %s%s fk JOIN %s pk ON",
    1780             :                      fk_only, fkrelname, pkrelname);
    1781          86 :     strcpy(pkattname, "pk.");
    1782          86 :     strcpy(fkattname, "fk.");
    1783          86 :     sep = "(";
    1784         172 :     for (i = 0; i < riinfo->nkeys; i++)
    1785             :     {
    1786          86 :         Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
    1787          86 :         Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
    1788          86 :         Oid         pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
    1789          86 :         Oid         fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
    1790             : 
    1791          86 :         quoteOneName(pkattname + 3,
    1792          86 :                      RIAttName(pk_rel, riinfo->pk_attnums[i]));
    1793          86 :         quoteOneName(fkattname + 3,
    1794          86 :                      RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1795          86 :         ri_GenerateQual(&querybuf, sep,
    1796             :                         pkattname, pk_type,
    1797             :                         riinfo->pf_eq_oprs[i],
    1798             :                         fkattname, fk_type);
    1799          86 :         if (pk_coll != fk_coll)
    1800           0 :             ri_GenerateQualCollation(&querybuf, pk_coll);
    1801          86 :         sep = "AND";
    1802             :     }
    1803             : 
    1804             :     /*
    1805             :      * Start the WHERE clause with the partition constraint (except if this is
    1806             :      * the default partition and there's no other partition, because the
    1807             :      * partition constraint is the empty string in that case.)
    1808             :      */
    1809          86 :     constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
    1810          86 :     if (constraintDef && constraintDef[0] != '\0')
    1811          86 :         appendStringInfo(&querybuf, ") WHERE %s AND (",
    1812             :                          constraintDef);
    1813             :     else
    1814           0 :         appendStringInfoString(&querybuf, ") WHERE (");
    1815             : 
    1816          86 :     sep = "";
    1817         172 :     for (i = 0; i < riinfo->nkeys; i++)
    1818             :     {
    1819          86 :         quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
    1820          86 :         appendStringInfo(&querybuf,
    1821             :                          "%sfk.%s IS NOT NULL",
    1822             :                          sep, fkattname);
    1823          86 :         switch (riinfo->confmatchtype)
    1824             :         {
    1825          86 :             case FKCONSTR_MATCH_SIMPLE:
    1826          86 :                 sep = " AND ";
    1827          86 :                 break;
    1828           0 :             case FKCONSTR_MATCH_FULL:
    1829           0 :                 sep = " OR ";
    1830           0 :                 break;
    1831             :         }
    1832          86 :     }
    1833          86 :     appendStringInfoChar(&querybuf, ')');
    1834             : 
    1835             :     /*
    1836             :      * Temporarily increase work_mem so that the check query can be executed
    1837             :      * more efficiently.  It seems okay to do this because the query is simple
    1838             :      * enough to not use a multiple of work_mem, and one typically would not
    1839             :      * have many large foreign-key validations happening concurrently.  So
    1840             :      * this seems to meet the criteria for being considered a "maintenance"
    1841             :      * operation, and accordingly we use maintenance_work_mem.  However, we
    1842             :      * must also set hash_mem_multiplier to 1, since it is surely not okay to
    1843             :      * let that get applied to the maintenance_work_mem value.
    1844             :      *
    1845             :      * We use the equivalent of a function SET option to allow the setting to
    1846             :      * persist for exactly the duration of the check query.  guc.c also takes
    1847             :      * care of undoing the setting on error.
    1848             :      */
    1849          86 :     save_nestlevel = NewGUCNestLevel();
    1850             : 
    1851          86 :     snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
    1852          86 :     (void) set_config_option("work_mem", workmembuf,
    1853             :                              PGC_USERSET, PGC_S_SESSION,
    1854             :                              GUC_ACTION_SAVE, true, 0, false);
    1855          86 :     (void) set_config_option("hash_mem_multiplier", "1",
    1856             :                              PGC_USERSET, PGC_S_SESSION,
    1857             :                              GUC_ACTION_SAVE, true, 0, false);
    1858             : 
    1859          86 :     SPI_connect();
    1860             : 
    1861             :     /*
    1862             :      * Generate the plan.  We don't need to cache it, and there are no
    1863             :      * arguments to the plan.
    1864             :      */
    1865          86 :     qplan = SPI_prepare(querybuf.data, 0, NULL);
    1866             : 
    1867          86 :     if (qplan == NULL)
    1868           0 :         elog(ERROR, "SPI_prepare returned %s for %s",
    1869             :              SPI_result_code_string(SPI_result), querybuf.data);
    1870             : 
    1871             :     /*
    1872             :      * Run the plan.  For safety we force a current snapshot to be used. (In
    1873             :      * transaction-snapshot mode, this arguably violates transaction isolation
    1874             :      * rules, but we really haven't got much choice.) We don't need to
    1875             :      * register the snapshot, because SPI_execute_snapshot will see to it. We
    1876             :      * need at most one tuple returned, so pass limit = 1.
    1877             :      */
    1878          86 :     spi_result = SPI_execute_snapshot(qplan,
    1879             :                                       NULL, NULL,
    1880             :                                       GetLatestSnapshot(),
    1881             :                                       InvalidSnapshot,
    1882             :                                       true, false, 1);
    1883             : 
    1884             :     /* Check result */
    1885          86 :     if (spi_result != SPI_OK_SELECT)
    1886           0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    1887             : 
    1888             :     /* Did we find a tuple that would violate the constraint? */
    1889          86 :     if (SPI_processed > 0)
    1890             :     {
    1891             :         TupleTableSlot *slot;
    1892          34 :         HeapTuple   tuple = SPI_tuptable->vals[0];
    1893          34 :         TupleDesc   tupdesc = SPI_tuptable->tupdesc;
    1894             :         RI_ConstraintInfo fake_riinfo;
    1895             : 
    1896          34 :         slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
    1897             : 
    1898          34 :         heap_deform_tuple(tuple, tupdesc,
    1899             :                           slot->tts_values, slot->tts_isnull);
    1900          34 :         ExecStoreVirtualTuple(slot);
    1901             : 
    1902             :         /*
    1903             :          * The columns to look at in the result tuple are 1..N, not whatever
    1904             :          * they are in the fk_rel.  Hack up riinfo so that ri_ReportViolation
    1905             :          * will behave properly.
    1906             :          *
    1907             :          * In addition to this, we have to pass the correct tupdesc to
    1908             :          * ri_ReportViolation, overriding its normal habit of using the pk_rel
    1909             :          * or fk_rel's tupdesc.
    1910             :          */
    1911          34 :         memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
    1912          68 :         for (i = 0; i < fake_riinfo.nkeys; i++)
    1913          34 :             fake_riinfo.pk_attnums[i] = i + 1;
    1914             : 
    1915          34 :         ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
    1916             :                            slot, tupdesc, 0, false, true);
    1917             :     }
    1918             : 
    1919          52 :     if (SPI_finish() != SPI_OK_FINISH)
    1920           0 :         elog(ERROR, "SPI_finish failed");
    1921             : 
    1922             :     /*
    1923             :      * Restore work_mem and hash_mem_multiplier.
    1924             :      */
    1925          52 :     AtEOXact_GUC(true, save_nestlevel);
    1926          52 : }
    1927             : 
    1928             : 
    1929             : /* ----------
    1930             :  * Local functions below
    1931             :  * ----------
    1932             :  */
    1933             : 
    1934             : 
    1935             : /*
    1936             :  * quoteOneName --- safely quote a single SQL name
    1937             :  *
    1938             :  * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
    1939             :  */
    1940             : static void
    1941       22552 : quoteOneName(char *buffer, const char *name)
    1942             : {
    1943             :     /* Rather than trying to be smart, just always quote it. */
    1944       22552 :     *buffer++ = '"';
    1945      143278 :     while (*name)
    1946             :     {
    1947      120726 :         if (*name == '"')
    1948           0 :             *buffer++ = '"';
    1949      120726 :         *buffer++ = *name++;
    1950             :     }
    1951       22552 :     *buffer++ = '"';
    1952       22552 :     *buffer = '\0';
    1953       22552 : }
    1954             : 
    1955             : /*
    1956             :  * quoteRelationName --- safely quote a fully qualified relation name
    1957             :  *
    1958             :  * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
    1959             :  */
    1960             : static void
    1961        5566 : quoteRelationName(char *buffer, Relation rel)
    1962             : {
    1963        5566 :     quoteOneName(buffer, get_namespace_name(RelationGetNamespace(rel)));
    1964        5566 :     buffer += strlen(buffer);
    1965        5566 :     *buffer++ = '.';
    1966        5566 :     quoteOneName(buffer, RelationGetRelationName(rel));
    1967        5566 : }
    1968             : 
    1969             : /*
    1970             :  * ri_GenerateQual --- generate a WHERE clause equating two variables
    1971             :  *
    1972             :  * This basically appends " sep leftop op rightop" to buf, adding casts
    1973             :  * and schema qualification as needed to ensure that the parser will select
    1974             :  * the operator we specify.  leftop and rightop should be parenthesized
    1975             :  * if they aren't variables or parameters.
    1976             :  */
    1977             : static void
    1978        6162 : ri_GenerateQual(StringInfo buf,
    1979             :                 const char *sep,
    1980             :                 const char *leftop, Oid leftoptype,
    1981             :                 Oid opoid,
    1982             :                 const char *rightop, Oid rightoptype)
    1983             : {
    1984        6162 :     appendStringInfo(buf, " %s ", sep);
    1985        6162 :     generate_operator_clause(buf, leftop, leftoptype, opoid,
    1986             :                              rightop, rightoptype);
    1987        6162 : }
    1988             : 
    1989             : /*
    1990             :  * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
    1991             :  *
    1992             :  * We only have to use this function when directly comparing the referencing
    1993             :  * and referenced columns, if they are of different collations; else the
    1994             :  * parser will fail to resolve the collation to use.  We don't need to use
    1995             :  * this function for RI queries that compare a variable to a $n parameter.
    1996             :  * Since parameter symbols always have default collation, the effect will be
    1997             :  * to use the variable's collation.
    1998             :  *
    1999             :  * Note that we require that the collations of the referencing and the
    2000             :  * referenced column have the same notion of equality: Either they have to
    2001             :  * both be deterministic or else they both have to be the same.  (See also
    2002             :  * ATAddForeignKeyConstraint().)
    2003             :  */
    2004             : static void
    2005          12 : ri_GenerateQualCollation(StringInfo buf, Oid collation)
    2006             : {
    2007             :     HeapTuple   tp;
    2008             :     Form_pg_collation colltup;
    2009             :     char       *collname;
    2010             :     char        onename[MAX_QUOTED_NAME_LEN];
    2011             : 
    2012             :     /* Nothing to do if it's a noncollatable data type */
    2013          12 :     if (!OidIsValid(collation))
    2014           0 :         return;
    2015             : 
    2016          12 :     tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
    2017          12 :     if (!HeapTupleIsValid(tp))
    2018           0 :         elog(ERROR, "cache lookup failed for collation %u", collation);
    2019          12 :     colltup = (Form_pg_collation) GETSTRUCT(tp);
    2020          12 :     collname = NameStr(colltup->collname);
    2021             : 
    2022             :     /*
    2023             :      * We qualify the name always, for simplicity and to ensure the query is
    2024             :      * not search-path-dependent.
    2025             :      */
    2026          12 :     quoteOneName(onename, get_namespace_name(colltup->collnamespace));
    2027          12 :     appendStringInfo(buf, " COLLATE %s", onename);
    2028          12 :     quoteOneName(onename, collname);
    2029          12 :     appendStringInfo(buf, ".%s", onename);
    2030             : 
    2031          12 :     ReleaseSysCache(tp);
    2032             : }
    2033             : 
    2034             : /* ----------
    2035             :  * ri_BuildQueryKey -
    2036             :  *
    2037             :  *  Construct a hashtable key for a prepared SPI plan of an FK constraint.
    2038             :  *
    2039             :  *      key: output argument, *key is filled in based on the other arguments
    2040             :  *      riinfo: info derived from pg_constraint entry
    2041             :  *      constr_queryno: an internal number identifying the query type
    2042             :  *          (see RI_PLAN_XXX constants at head of file)
    2043             :  * ----------
    2044             :  */
    2045             : static void
    2046        6930 : ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo,
    2047             :                  int32 constr_queryno)
    2048             : {
    2049             :     /*
    2050             :      * Inherited constraints with a common ancestor can share ri_query_cache
    2051             :      * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
    2052             :      * Except in that case, the query processes the other table involved in
    2053             :      * the FK constraint (i.e., not the table on which the trigger has been
    2054             :      * fired), and so it will be the same for all members of the inheritance
    2055             :      * tree.  So we may use the root constraint's OID in the hash key, rather
    2056             :      * than the constraint's own OID.  This avoids creating duplicate SPI
    2057             :      * plans, saving lots of work and memory when there are many partitions
    2058             :      * with similar FK constraints.
    2059             :      *
    2060             :      * (Note that we must still have a separate RI_ConstraintInfo for each
    2061             :      * constraint, because partitions can have different column orders,
    2062             :      * resulting in different pk_attnums[] or fk_attnums[] array contents.)
    2063             :      *
    2064             :      * We assume struct RI_QueryKey contains no padding bytes, else we'd need
    2065             :      * to use memset to clear them.
    2066             :      */
    2067        6930 :     if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
    2068        5892 :         key->constr_id = riinfo->constraint_root_id;
    2069             :     else
    2070        1038 :         key->constr_id = riinfo->constraint_id;
    2071        6930 :     key->constr_queryno = constr_queryno;
    2072        6930 : }
    2073             : 
    2074             : /*
    2075             :  * Check that RI trigger function was called in expected context
    2076             :  */
    2077             : static void
    2078        6190 : ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
    2079             : {
    2080        6190 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
    2081             : 
    2082        6190 :     if (!CALLED_AS_TRIGGER(fcinfo))
    2083           0 :         ereport(ERROR,
    2084             :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2085             :                  errmsg("function \"%s\" was not called by trigger manager", funcname)));
    2086             : 
    2087             :     /*
    2088             :      * Check proper event
    2089             :      */
    2090        6190 :     if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
    2091        6190 :         !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
    2092           0 :         ereport(ERROR,
    2093             :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2094             :                  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
    2095             : 
    2096        6190 :     switch (tgkind)
    2097             :     {
    2098        4050 :         case RI_TRIGTYPE_INSERT:
    2099        4050 :             if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    2100           0 :                 ereport(ERROR,
    2101             :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2102             :                          errmsg("function \"%s\" must be fired for INSERT", funcname)));
    2103        4050 :             break;
    2104        1294 :         case RI_TRIGTYPE_UPDATE:
    2105        1294 :             if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    2106           0 :                 ereport(ERROR,
    2107             :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2108             :                          errmsg("function \"%s\" must be fired for UPDATE", funcname)));
    2109        1294 :             break;
    2110         846 :         case RI_TRIGTYPE_DELETE:
    2111         846 :             if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    2112           0 :                 ereport(ERROR,
    2113             :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2114             :                          errmsg("function \"%s\" must be fired for DELETE", funcname)));
    2115         846 :             break;
    2116             :     }
    2117        6190 : }
    2118             : 
    2119             : 
    2120             : /*
    2121             :  * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
    2122             :  */
    2123             : static const RI_ConstraintInfo *
    2124       10890 : ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
    2125             : {
    2126       10890 :     Oid         constraintOid = trigger->tgconstraint;
    2127             :     const RI_ConstraintInfo *riinfo;
    2128             : 
    2129             :     /*
    2130             :      * Check that the FK constraint's OID is available; it might not be if
    2131             :      * we've been invoked via an ordinary trigger or an old-style "constraint
    2132             :      * trigger".
    2133             :      */
    2134       10890 :     if (!OidIsValid(constraintOid))
    2135           0 :         ereport(ERROR,
    2136             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2137             :                  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2138             :                         trigger->tgname, RelationGetRelationName(trig_rel)),
    2139             :                  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
    2140             : 
    2141             :     /* Find or create a hashtable entry for the constraint */
    2142       10890 :     riinfo = ri_LoadConstraintInfo(constraintOid);
    2143             : 
    2144             :     /* Do some easy cross-checks against the trigger call data */
    2145       10890 :     if (rel_is_pk)
    2146             :     {
    2147        4264 :         if (riinfo->fk_relid != trigger->tgconstrrelid ||
    2148        4264 :             riinfo->pk_relid != RelationGetRelid(trig_rel))
    2149           0 :             elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2150             :                  trigger->tgname, RelationGetRelationName(trig_rel));
    2151             :     }
    2152             :     else
    2153             :     {
    2154        6626 :         if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
    2155        6626 :             riinfo->pk_relid != trigger->tgconstrrelid)
    2156           0 :             elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
    2157             :                  trigger->tgname, RelationGetRelationName(trig_rel));
    2158             :     }
    2159             : 
    2160       10890 :     if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
    2161       10426 :         riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
    2162       10426 :         riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
    2163           0 :         elog(ERROR, "unrecognized confmatchtype: %d",
    2164             :              riinfo->confmatchtype);
    2165             : 
    2166       10890 :     if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
    2167           0 :         ereport(ERROR,
    2168             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2169             :                  errmsg("MATCH PARTIAL not yet implemented")));
    2170             : 
    2171       10890 :     return riinfo;
    2172             : }
    2173             : 
    2174             : /*
    2175             :  * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
    2176             :  */
    2177             : static const RI_ConstraintInfo *
    2178       10890 : ri_LoadConstraintInfo(Oid constraintOid)
    2179             : {
    2180             :     RI_ConstraintInfo *riinfo;
    2181             :     bool        found;
    2182             :     HeapTuple   tup;
    2183             :     Form_pg_constraint conForm;
    2184             : 
    2185             :     /*
    2186             :      * On the first call initialize the hashtable
    2187             :      */
    2188       10890 :     if (!ri_constraint_cache)
    2189         422 :         ri_InitHashTables();
    2190             : 
    2191             :     /*
    2192             :      * Find or create a hash entry.  If we find a valid one, just return it.
    2193             :      */
    2194       10890 :     riinfo = (RI_ConstraintInfo *) hash_search(ri_constraint_cache,
    2195             :                                                &constraintOid,
    2196             :                                                HASH_ENTER, &found);
    2197       10890 :     if (!found)
    2198        3844 :         riinfo->valid = false;
    2199        7046 :     else if (riinfo->valid)
    2200        6734 :         return riinfo;
    2201             : 
    2202             :     /*
    2203             :      * Fetch the pg_constraint row so we can fill in the entry.
    2204             :      */
    2205        4156 :     tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
    2206        4156 :     if (!HeapTupleIsValid(tup)) /* should not happen */
    2207           0 :         elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
    2208        4156 :     conForm = (Form_pg_constraint) GETSTRUCT(tup);
    2209             : 
    2210        4156 :     if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
    2211           0 :         elog(ERROR, "constraint %u is not a foreign key constraint",
    2212             :              constraintOid);
    2213             : 
    2214             :     /* And extract data */
    2215             :     Assert(riinfo->constraint_id == constraintOid);
    2216        4156 :     if (OidIsValid(conForm->conparentid))
    2217        1434 :         riinfo->constraint_root_id =
    2218        1434 :             get_ri_constraint_root(conForm->conparentid);
    2219             :     else
    2220        2722 :         riinfo->constraint_root_id = constraintOid;
    2221        4156 :     riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
    2222             :                                                  ObjectIdGetDatum(constraintOid));
    2223        4156 :     riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
    2224             :                                                   ObjectIdGetDatum(riinfo->constraint_root_id));
    2225        4156 :     memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
    2226        4156 :     riinfo->pk_relid = conForm->confrelid;
    2227        4156 :     riinfo->fk_relid = conForm->conrelid;
    2228        4156 :     riinfo->confupdtype = conForm->confupdtype;
    2229        4156 :     riinfo->confdeltype = conForm->confdeltype;
    2230        4156 :     riinfo->confmatchtype = conForm->confmatchtype;
    2231        4156 :     riinfo->hasperiod = conForm->conperiod;
    2232             : 
    2233        4156 :     DeconstructFkConstraintRow(tup,
    2234             :                                &riinfo->nkeys,
    2235        4156 :                                riinfo->fk_attnums,
    2236        4156 :                                riinfo->pk_attnums,
    2237        4156 :                                riinfo->pf_eq_oprs,
    2238        4156 :                                riinfo->pp_eq_oprs,
    2239        4156 :                                riinfo->ff_eq_oprs,
    2240             :                                &riinfo->ndelsetcols,
    2241        4156 :                                riinfo->confdelsetcols);
    2242             : 
    2243             :     /*
    2244             :      * For temporal FKs, get the operators and functions we need. We ask the
    2245             :      * opclass of the PK element for these. This all gets cached (as does the
    2246             :      * generated plan), so there's no performance issue.
    2247             :      */
    2248        4156 :     if (riinfo->hasperiod)
    2249             :     {
    2250         254 :         Oid         opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
    2251             : 
    2252         254 :         FindFKPeriodOpers(opclass,
    2253             :                           &riinfo->period_contained_by_oper,
    2254             :                           &riinfo->agged_period_contained_by_oper);
    2255             :     }
    2256             : 
    2257        4156 :     ReleaseSysCache(tup);
    2258             : 
    2259             :     /*
    2260             :      * For efficient processing of invalidation messages below, we keep a
    2261             :      * doubly-linked count list of all currently valid entries.
    2262             :      */
    2263        4156 :     dclist_push_tail(&ri_constraint_cache_valid_list, &riinfo->valid_link);
    2264             : 
    2265        4156 :     riinfo->valid = true;
    2266             : 
    2267        4156 :     return riinfo;
    2268             : }
    2269             : 
    2270             : /*
    2271             :  * get_ri_constraint_root
    2272             :  *      Returns the OID of the constraint's root parent
    2273             :  */
    2274             : static Oid
    2275        1756 : get_ri_constraint_root(Oid constrOid)
    2276             : {
    2277             :     for (;;)
    2278         322 :     {
    2279             :         HeapTuple   tuple;
    2280             :         Oid         constrParentOid;
    2281             : 
    2282        1756 :         tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
    2283        1756 :         if (!HeapTupleIsValid(tuple))
    2284           0 :             elog(ERROR, "cache lookup failed for constraint %u", constrOid);
    2285        1756 :         constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
    2286        1756 :         ReleaseSysCache(tuple);
    2287        1756 :         if (!OidIsValid(constrParentOid))
    2288        1434 :             break;              /* we reached the root constraint */
    2289         322 :         constrOid = constrParentOid;
    2290             :     }
    2291        1434 :     return constrOid;
    2292             : }
    2293             : 
    2294             : /*
    2295             :  * Callback for pg_constraint inval events
    2296             :  *
    2297             :  * While most syscache callbacks just flush all their entries, pg_constraint
    2298             :  * gets enough update traffic that it's probably worth being smarter.
    2299             :  * Invalidate any ri_constraint_cache entry associated with the syscache
    2300             :  * entry with the specified hash value, or all entries if hashvalue == 0.
    2301             :  *
    2302             :  * Note: at the time a cache invalidation message is processed there may be
    2303             :  * active references to the cache.  Because of this we never remove entries
    2304             :  * from the cache, but only mark them invalid, which is harmless to active
    2305             :  * uses.  (Any query using an entry should hold a lock sufficient to keep that
    2306             :  * data from changing under it --- but we may get cache flushes anyway.)
    2307             :  */
    2308             : static void
    2309       68950 : InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
    2310             : {
    2311             :     dlist_mutable_iter iter;
    2312             : 
    2313             :     Assert(ri_constraint_cache != NULL);
    2314             : 
    2315             :     /*
    2316             :      * If the list of currently valid entries gets excessively large, we mark
    2317             :      * them all invalid so we can empty the list.  This arrangement avoids
    2318             :      * O(N^2) behavior in situations where a session touches many foreign keys
    2319             :      * and also does many ALTER TABLEs, such as a restore from pg_dump.
    2320             :      */
    2321       68950 :     if (dclist_count(&ri_constraint_cache_valid_list) > 1000)
    2322           0 :         hashvalue = 0;          /* pretend it's a cache reset */
    2323             : 
    2324      254650 :     dclist_foreach_modify(iter, &ri_constraint_cache_valid_list)
    2325             :     {
    2326      185700 :         RI_ConstraintInfo *riinfo = dclist_container(RI_ConstraintInfo,
    2327             :                                                      valid_link, iter.cur);
    2328             : 
    2329             :         /*
    2330             :          * We must invalidate not only entries directly matching the given
    2331             :          * hash value, but also child entries, in case the invalidation
    2332             :          * affects a root constraint.
    2333             :          */
    2334      185700 :         if (hashvalue == 0 ||
    2335      185642 :             riinfo->oidHashValue == hashvalue ||
    2336      183118 :             riinfo->rootHashValue == hashvalue)
    2337             :         {
    2338        2828 :             riinfo->valid = false;
    2339             :             /* Remove invalidated entries from the list, too */
    2340        2828 :             dclist_delete_from(&ri_constraint_cache_valid_list, iter.cur);
    2341             :         }
    2342             :     }
    2343       68950 : }
    2344             : 
    2345             : 
    2346             : /*
    2347             :  * Prepare execution plan for a query to enforce an RI restriction
    2348             :  */
    2349             : static SPIPlanPtr
    2350        3494 : ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
    2351             :              RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
    2352             : {
    2353             :     SPIPlanPtr  qplan;
    2354             :     Relation    query_rel;
    2355             :     Oid         save_userid;
    2356             :     int         save_sec_context;
    2357             : 
    2358             :     /*
    2359             :      * Use the query type code to determine whether the query is run against
    2360             :      * the PK or FK table; we'll do the check as that table's owner
    2361             :      */
    2362        3494 :     if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
    2363        2664 :         query_rel = pk_rel;
    2364             :     else
    2365         830 :         query_rel = fk_rel;
    2366             : 
    2367             :     /* Switch to proper UID to perform check as */
    2368        3494 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2369        3494 :     SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
    2370             :                            save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
    2371             :                            SECURITY_NOFORCE_RLS);
    2372             : 
    2373             :     /* Create the plan */
    2374        3494 :     qplan = SPI_prepare(querystr, nargs, argtypes);
    2375             : 
    2376        3494 :     if (qplan == NULL)
    2377           0 :         elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
    2378             : 
    2379             :     /* Restore UID and security context */
    2380        3494 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2381             : 
    2382             :     /* Save the plan */
    2383        3494 :     SPI_keepplan(qplan);
    2384        3494 :     ri_HashPreparedPlan(qkey, qplan);
    2385             : 
    2386        3494 :     return qplan;
    2387             : }
    2388             : 
    2389             : /*
    2390             :  * Perform a query to enforce an RI restriction
    2391             :  */
    2392             : static bool
    2393        6930 : ri_PerformCheck(const RI_ConstraintInfo *riinfo,
    2394             :                 RI_QueryKey *qkey, SPIPlanPtr qplan,
    2395             :                 Relation fk_rel, Relation pk_rel,
    2396             :                 TupleTableSlot *oldslot, TupleTableSlot *newslot,
    2397             :                 bool is_restrict,
    2398             :                 bool detectNewRows, int expect_OK)
    2399             : {
    2400             :     Relation    query_rel,
    2401             :                 source_rel;
    2402             :     bool        source_is_pk;
    2403             :     Snapshot    test_snapshot;
    2404             :     Snapshot    crosscheck_snapshot;
    2405             :     int         limit;
    2406             :     int         spi_result;
    2407             :     Oid         save_userid;
    2408             :     int         save_sec_context;
    2409             :     Datum       vals[RI_MAX_NUMKEYS * 2];
    2410             :     char        nulls[RI_MAX_NUMKEYS * 2];
    2411             : 
    2412             :     /*
    2413             :      * Use the query type code to determine whether the query is run against
    2414             :      * the PK or FK table; we'll do the check as that table's owner
    2415             :      */
    2416        6930 :     if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
    2417        5188 :         query_rel = pk_rel;
    2418             :     else
    2419        1742 :         query_rel = fk_rel;
    2420             : 
    2421             :     /*
    2422             :      * The values for the query are taken from the table on which the trigger
    2423             :      * is called - it is normally the other one with respect to query_rel. An
    2424             :      * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
    2425             :      * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK).  We might eventually
    2426             :      * need some less klugy way to determine this.
    2427             :      */
    2428        6930 :     if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
    2429             :     {
    2430        4150 :         source_rel = fk_rel;
    2431        4150 :         source_is_pk = false;
    2432             :     }
    2433             :     else
    2434             :     {
    2435        2780 :         source_rel = pk_rel;
    2436        2780 :         source_is_pk = true;
    2437             :     }
    2438             : 
    2439             :     /* Extract the parameters to be passed into the query */
    2440        6930 :     if (newslot)
    2441             :     {
    2442        4354 :         ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
    2443             :                          vals, nulls);
    2444        4354 :         if (oldslot)
    2445         204 :             ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
    2446         204 :                              vals + riinfo->nkeys, nulls + riinfo->nkeys);
    2447             :     }
    2448             :     else
    2449             :     {
    2450        2576 :         ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
    2451             :                          vals, nulls);
    2452             :     }
    2453             : 
    2454             :     /*
    2455             :      * In READ COMMITTED mode, we just need to use an up-to-date regular
    2456             :      * snapshot, and we will see all rows that could be interesting. But in
    2457             :      * transaction-snapshot mode, we can't change the transaction snapshot. If
    2458             :      * the caller passes detectNewRows == false then it's okay to do the query
    2459             :      * with the transaction snapshot; otherwise we use a current snapshot, and
    2460             :      * tell the executor to error out if it finds any rows under the current
    2461             :      * snapshot that wouldn't be visible per the transaction snapshot.  Note
    2462             :      * that SPI_execute_snapshot will register the snapshots, so we don't need
    2463             :      * to bother here.
    2464             :      */
    2465        6930 :     if (IsolationUsesXactSnapshot() && detectNewRows)
    2466             :     {
    2467          32 :         CommandCounterIncrement();  /* be sure all my own work is visible */
    2468          32 :         test_snapshot = GetLatestSnapshot();
    2469          32 :         crosscheck_snapshot = GetTransactionSnapshot();
    2470             :     }
    2471             :     else
    2472             :     {
    2473             :         /* the default SPI behavior is okay */
    2474        6898 :         test_snapshot = InvalidSnapshot;
    2475        6898 :         crosscheck_snapshot = InvalidSnapshot;
    2476             :     }
    2477             : 
    2478             :     /*
    2479             :      * If this is a select query (e.g., for a 'no action' or 'restrict'
    2480             :      * trigger), we only need to see if there is a single row in the table,
    2481             :      * matching the key.  Otherwise, limit = 0 - because we want the query to
    2482             :      * affect ALL the matching rows.
    2483             :      */
    2484        6930 :     limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
    2485             : 
    2486             :     /* Switch to proper UID to perform check as */
    2487        6930 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2488        6930 :     SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
    2489             :                            save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
    2490             :                            SECURITY_NOFORCE_RLS);
    2491             : 
    2492             :     /* Finally we can run the query. */
    2493        6930 :     spi_result = SPI_execute_snapshot(qplan,
    2494             :                                       vals, nulls,
    2495             :                                       test_snapshot, crosscheck_snapshot,
    2496             :                                       false, false, limit);
    2497             : 
    2498             :     /* Restore UID and security context */
    2499        6916 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2500             : 
    2501             :     /* Check result */
    2502        6916 :     if (spi_result < 0)
    2503           0 :         elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
    2504             : 
    2505        6916 :     if (expect_OK >= 0 && spi_result != expect_OK)
    2506           0 :         ereport(ERROR,
    2507             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    2508             :                  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
    2509             :                         RelationGetRelationName(pk_rel),
    2510             :                         NameStr(riinfo->conname),
    2511             :                         RelationGetRelationName(fk_rel)),
    2512             :                  errhint("This is most likely due to a rule having rewritten the query.")));
    2513             : 
    2514             :     /* XXX wouldn't it be clearer to do this part at the caller? */
    2515        6916 :     if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
    2516        5270 :         expect_OK == SPI_OK_SELECT &&
    2517        5270 :         (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
    2518        1040 :         ri_ReportViolation(riinfo,
    2519             :                            pk_rel, fk_rel,
    2520             :                            newslot ? newslot : oldslot,
    2521             :                            NULL,
    2522             :                            qkey->constr_queryno, is_restrict, false);
    2523             : 
    2524        5876 :     return SPI_processed != 0;
    2525             : }
    2526             : 
    2527             : /*
    2528             :  * Extract fields from a tuple into Datum/nulls arrays
    2529             :  */
    2530             : static void
    2531        7134 : ri_ExtractValues(Relation rel, TupleTableSlot *slot,
    2532             :                  const RI_ConstraintInfo *riinfo, bool rel_is_pk,
    2533             :                  Datum *vals, char *nulls)
    2534             : {
    2535             :     const int16 *attnums;
    2536             :     bool        isnull;
    2537             : 
    2538        7134 :     if (rel_is_pk)
    2539        2984 :         attnums = riinfo->pk_attnums;
    2540             :     else
    2541        4150 :         attnums = riinfo->fk_attnums;
    2542             : 
    2543       16960 :     for (int i = 0; i < riinfo->nkeys; i++)
    2544             :     {
    2545        9826 :         vals[i] = slot_getattr(slot, attnums[i], &isnull);
    2546        9826 :         nulls[i] = isnull ? 'n' : ' ';
    2547             :     }
    2548        7134 : }
    2549             : 
    2550             : /*
    2551             :  * Produce an error report
    2552             :  *
    2553             :  * If the failed constraint was on insert/update to the FK table,
    2554             :  * we want the key names and values extracted from there, and the error
    2555             :  * message to look like 'key blah is not present in PK'.
    2556             :  * Otherwise, the attr names and values come from the PK table and the
    2557             :  * message looks like 'key blah is still referenced from FK'.
    2558             :  */
    2559             : static void
    2560        1124 : ri_ReportViolation(const RI_ConstraintInfo *riinfo,
    2561             :                    Relation pk_rel, Relation fk_rel,
    2562             :                    TupleTableSlot *violatorslot, TupleDesc tupdesc,
    2563             :                    int queryno, bool is_restrict, bool partgone)
    2564             : {
    2565             :     StringInfoData key_names;
    2566             :     StringInfoData key_values;
    2567             :     bool        onfk;
    2568             :     const int16 *attnums;
    2569             :     Oid         rel_oid;
    2570             :     AclResult   aclresult;
    2571        1124 :     bool        has_perm = true;
    2572             : 
    2573             :     /*
    2574             :      * Determine which relation to complain about.  If tupdesc wasn't passed
    2575             :      * by caller, assume the violator tuple came from there.
    2576             :      */
    2577        1124 :     onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
    2578        1124 :     if (onfk)
    2579             :     {
    2580         594 :         attnums = riinfo->fk_attnums;
    2581         594 :         rel_oid = fk_rel->rd_id;
    2582         594 :         if (tupdesc == NULL)
    2583         544 :             tupdesc = fk_rel->rd_att;
    2584             :     }
    2585             :     else
    2586             :     {
    2587         530 :         attnums = riinfo->pk_attnums;
    2588         530 :         rel_oid = pk_rel->rd_id;
    2589         530 :         if (tupdesc == NULL)
    2590         496 :             tupdesc = pk_rel->rd_att;
    2591             :     }
    2592             : 
    2593             :     /*
    2594             :      * Check permissions- if the user does not have access to view the data in
    2595             :      * any of the key columns then we don't include the errdetail() below.
    2596             :      *
    2597             :      * Check if RLS is enabled on the relation first.  If so, we don't return
    2598             :      * any specifics to avoid leaking data.
    2599             :      *
    2600             :      * Check table-level permissions next and, failing that, column-level
    2601             :      * privileges.
    2602             :      *
    2603             :      * When a partition at the referenced side is being detached/dropped, we
    2604             :      * needn't check, since the user must be the table owner anyway.
    2605             :      */
    2606        1124 :     if (partgone)
    2607          34 :         has_perm = true;
    2608        1090 :     else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
    2609             :     {
    2610        1084 :         aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
    2611        1084 :         if (aclresult != ACLCHECK_OK)
    2612             :         {
    2613             :             /* Try for column-level permissions */
    2614           0 :             for (int idx = 0; idx < riinfo->nkeys; idx++)
    2615             :             {
    2616           0 :                 aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
    2617             :                                                   GetUserId(),
    2618             :                                                   ACL_SELECT);
    2619             : 
    2620             :                 /* No access to the key */
    2621           0 :                 if (aclresult != ACLCHECK_OK)
    2622             :                 {
    2623           0 :                     has_perm = false;
    2624           0 :                     break;
    2625             :                 }
    2626             :             }
    2627             :         }
    2628             :     }
    2629             :     else
    2630           6 :         has_perm = false;
    2631             : 
    2632        1124 :     if (has_perm)
    2633             :     {
    2634             :         /* Get printable versions of the keys involved */
    2635        1118 :         initStringInfo(&key_names);
    2636        1118 :         initStringInfo(&key_values);
    2637        2800 :         for (int idx = 0; idx < riinfo->nkeys; idx++)
    2638             :         {
    2639        1682 :             int         fnum = attnums[idx];
    2640        1682 :             Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
    2641             :             char       *name,
    2642             :                        *val;
    2643             :             Datum       datum;
    2644             :             bool        isnull;
    2645             : 
    2646        1682 :             name = NameStr(att->attname);
    2647             : 
    2648        1682 :             datum = slot_getattr(violatorslot, fnum, &isnull);
    2649        1682 :             if (!isnull)
    2650             :             {
    2651             :                 Oid         foutoid;
    2652             :                 bool        typisvarlena;
    2653             : 
    2654        1682 :                 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
    2655        1682 :                 val = OidOutputFunctionCall(foutoid, datum);
    2656             :             }
    2657             :             else
    2658           0 :                 val = "null";
    2659             : 
    2660        1682 :             if (idx > 0)
    2661             :             {
    2662         564 :                 appendStringInfoString(&key_names, ", ");
    2663         564 :                 appendStringInfoString(&key_values, ", ");
    2664             :             }
    2665        1682 :             appendStringInfoString(&key_names, name);
    2666        1682 :             appendStringInfoString(&key_values, val);
    2667             :         }
    2668             :     }
    2669             : 
    2670        1124 :     if (partgone)
    2671          34 :         ereport(ERROR,
    2672             :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    2673             :                  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
    2674             :                         RelationGetRelationName(pk_rel),
    2675             :                         NameStr(riinfo->conname)),
    2676             :                  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
    2677             :                            key_names.data, key_values.data,
    2678             :                            RelationGetRelationName(fk_rel)),
    2679             :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    2680        1090 :     else if (onfk)
    2681         594 :         ereport(ERROR,
    2682             :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    2683             :                  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
    2684             :                         RelationGetRelationName(fk_rel),
    2685             :                         NameStr(riinfo->conname)),
    2686             :                  has_perm ?
    2687             :                  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
    2688             :                            key_names.data, key_values.data,
    2689             :                            RelationGetRelationName(pk_rel)) :
    2690             :                  errdetail("Key is not present in table \"%s\".",
    2691             :                            RelationGetRelationName(pk_rel)),
    2692             :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    2693         496 :     else if (is_restrict)
    2694          90 :         ereport(ERROR,
    2695             :                 (errcode(ERRCODE_RESTRICT_VIOLATION),
    2696             :                  errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
    2697             :                         RelationGetRelationName(pk_rel),
    2698             :                         NameStr(riinfo->conname),
    2699             :                         RelationGetRelationName(fk_rel)),
    2700             :                  has_perm ?
    2701             :                  errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
    2702             :                            key_names.data, key_values.data,
    2703             :                            RelationGetRelationName(fk_rel)) :
    2704             :                  errdetail("Key is referenced from table \"%s\".",
    2705             :                            RelationGetRelationName(fk_rel)),
    2706             :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    2707             :     else
    2708         406 :         ereport(ERROR,
    2709             :                 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
    2710             :                  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
    2711             :                         RelationGetRelationName(pk_rel),
    2712             :                         NameStr(riinfo->conname),
    2713             :                         RelationGetRelationName(fk_rel)),
    2714             :                  has_perm ?
    2715             :                  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
    2716             :                            key_names.data, key_values.data,
    2717             :                            RelationGetRelationName(fk_rel)) :
    2718             :                  errdetail("Key is still referenced from table \"%s\".",
    2719             :                            RelationGetRelationName(fk_rel)),
    2720             :                  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
    2721             : }
    2722             : 
    2723             : 
    2724             : /*
    2725             :  * ri_NullCheck -
    2726             :  *
    2727             :  * Determine the NULL state of all key values in a tuple
    2728             :  *
    2729             :  * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
    2730             :  */
    2731             : static int
    2732        7982 : ri_NullCheck(TupleDesc tupDesc,
    2733             :              TupleTableSlot *slot,
    2734             :              const RI_ConstraintInfo *riinfo, bool rel_is_pk)
    2735             : {
    2736             :     const int16 *attnums;
    2737        7982 :     bool        allnull = true;
    2738        7982 :     bool        nonenull = true;
    2739             : 
    2740        7982 :     if (rel_is_pk)
    2741        2440 :         attnums = riinfo->pk_attnums;
    2742             :     else
    2743        5542 :         attnums = riinfo->fk_attnums;
    2744             : 
    2745       18554 :     for (int i = 0; i < riinfo->nkeys; i++)
    2746             :     {
    2747       10572 :         if (slot_attisnull(slot, attnums[i]))
    2748         534 :             nonenull = false;
    2749             :         else
    2750       10038 :             allnull = false;
    2751             :     }
    2752             : 
    2753        7982 :     if (allnull)
    2754         258 :         return RI_KEYS_ALL_NULL;
    2755             : 
    2756        7724 :     if (nonenull)
    2757        7520 :         return RI_KEYS_NONE_NULL;
    2758             : 
    2759         204 :     return RI_KEYS_SOME_NULL;
    2760             : }
    2761             : 
    2762             : 
    2763             : /*
    2764             :  * ri_InitHashTables -
    2765             :  *
    2766             :  * Initialize our internal hash tables.
    2767             :  */
    2768             : static void
    2769         422 : ri_InitHashTables(void)
    2770             : {
    2771             :     HASHCTL     ctl;
    2772             : 
    2773         422 :     ctl.keysize = sizeof(Oid);
    2774         422 :     ctl.entrysize = sizeof(RI_ConstraintInfo);
    2775         422 :     ri_constraint_cache = hash_create("RI constraint cache",
    2776             :                                       RI_INIT_CONSTRAINTHASHSIZE,
    2777             :                                       &ctl, HASH_ELEM | HASH_BLOBS);
    2778             : 
    2779             :     /* Arrange to flush cache on pg_constraint changes */
    2780         422 :     CacheRegisterSyscacheCallback(CONSTROID,
    2781             :                                   InvalidateConstraintCacheCallBack,
    2782             :                                   (Datum) 0);
    2783             : 
    2784         422 :     ctl.keysize = sizeof(RI_QueryKey);
    2785         422 :     ctl.entrysize = sizeof(RI_QueryHashEntry);
    2786         422 :     ri_query_cache = hash_create("RI query cache",
    2787             :                                  RI_INIT_QUERYHASHSIZE,
    2788             :                                  &ctl, HASH_ELEM | HASH_BLOBS);
    2789             : 
    2790         422 :     ctl.keysize = sizeof(RI_CompareKey);
    2791         422 :     ctl.entrysize = sizeof(RI_CompareHashEntry);
    2792         422 :     ri_compare_cache = hash_create("RI compare cache",
    2793             :                                    RI_INIT_QUERYHASHSIZE,
    2794             :                                    &ctl, HASH_ELEM | HASH_BLOBS);
    2795         422 : }
    2796             : 
    2797             : 
    2798             : /*
    2799             :  * ri_FetchPreparedPlan -
    2800             :  *
    2801             :  * Lookup for a query key in our private hash table of prepared
    2802             :  * and saved SPI execution plans. Return the plan if found or NULL.
    2803             :  */
    2804             : static SPIPlanPtr
    2805        6930 : ri_FetchPreparedPlan(RI_QueryKey *key)
    2806             : {
    2807             :     RI_QueryHashEntry *entry;
    2808             :     SPIPlanPtr  plan;
    2809             : 
    2810             :     /*
    2811             :      * On the first call initialize the hashtable
    2812             :      */
    2813        6930 :     if (!ri_query_cache)
    2814           0 :         ri_InitHashTables();
    2815             : 
    2816             :     /*
    2817             :      * Lookup for the key
    2818             :      */
    2819        6930 :     entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
    2820             :                                               key,
    2821             :                                               HASH_FIND, NULL);
    2822        6930 :     if (entry == NULL)
    2823        3074 :         return NULL;
    2824             : 
    2825             :     /*
    2826             :      * Check whether the plan is still valid.  If it isn't, we don't want to
    2827             :      * simply rely on plancache.c to regenerate it; rather we should start
    2828             :      * from scratch and rebuild the query text too.  This is to cover cases
    2829             :      * such as table/column renames.  We depend on the plancache machinery to
    2830             :      * detect possible invalidations, though.
    2831             :      *
    2832             :      * CAUTION: this check is only trustworthy if the caller has already
    2833             :      * locked both FK and PK rels.
    2834             :      */
    2835        3856 :     plan = entry->plan;
    2836        3856 :     if (plan && SPI_plan_is_valid(plan))
    2837        3436 :         return plan;
    2838             : 
    2839             :     /*
    2840             :      * Otherwise we might as well flush the cached plan now, to free a little
    2841             :      * memory space before we make a new one.
    2842             :      */
    2843         420 :     entry->plan = NULL;
    2844         420 :     if (plan)
    2845         420 :         SPI_freeplan(plan);
    2846             : 
    2847         420 :     return NULL;
    2848             : }
    2849             : 
    2850             : 
    2851             : /*
    2852             :  * ri_HashPreparedPlan -
    2853             :  *
    2854             :  * Add another plan to our private SPI query plan hashtable.
    2855             :  */
    2856             : static void
    2857        3494 : ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
    2858             : {
    2859             :     RI_QueryHashEntry *entry;
    2860             :     bool        found;
    2861             : 
    2862             :     /*
    2863             :      * On the first call initialize the hashtable
    2864             :      */
    2865        3494 :     if (!ri_query_cache)
    2866           0 :         ri_InitHashTables();
    2867             : 
    2868             :     /*
    2869             :      * Add the new plan.  We might be overwriting an entry previously found
    2870             :      * invalid by ri_FetchPreparedPlan.
    2871             :      */
    2872        3494 :     entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
    2873             :                                               key,
    2874             :                                               HASH_ENTER, &found);
    2875             :     Assert(!found || entry->plan == NULL);
    2876        3494 :     entry->plan = plan;
    2877        3494 : }
    2878             : 
    2879             : 
    2880             : /*
    2881             :  * ri_KeysEqual -
    2882             :  *
    2883             :  * Check if all key values in OLD and NEW are "equivalent":
    2884             :  * For normal FKs we check for equality.
    2885             :  * For temporal FKs we check that the PK side is a superset of its old value,
    2886             :  * or the FK side is a subset of its old value.
    2887             :  *
    2888             :  * Note: at some point we might wish to redefine this as checking for
    2889             :  * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
    2890             :  * considered equal.  Currently there is no need since all callers have
    2891             :  * previously found at least one of the rows to contain no nulls.
    2892             :  */
    2893             : static bool
    2894        2308 : ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
    2895             :              const RI_ConstraintInfo *riinfo, bool rel_is_pk)
    2896             : {
    2897             :     const int16 *attnums;
    2898             : 
    2899        2308 :     if (rel_is_pk)
    2900        1508 :         attnums = riinfo->pk_attnums;
    2901             :     else
    2902         800 :         attnums = riinfo->fk_attnums;
    2903             : 
    2904             :     /* XXX: could be worthwhile to fetch all necessary attrs at once */
    2905        3692 :     for (int i = 0; i < riinfo->nkeys; i++)
    2906             :     {
    2907             :         Datum       oldvalue;
    2908             :         Datum       newvalue;
    2909             :         bool        isnull;
    2910             : 
    2911             :         /*
    2912             :          * Get one attribute's oldvalue. If it is NULL - they're not equal.
    2913             :          */
    2914        2692 :         oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
    2915        2692 :         if (isnull)
    2916        1308 :             return false;
    2917             : 
    2918             :         /*
    2919             :          * Get one attribute's newvalue. If it is NULL - they're not equal.
    2920             :          */
    2921        2662 :         newvalue = slot_getattr(newslot, attnums[i], &isnull);
    2922        2662 :         if (isnull)
    2923           0 :             return false;
    2924             : 
    2925        2662 :         if (rel_is_pk)
    2926             :         {
    2927             :             /*
    2928             :              * If we are looking at the PK table, then do a bytewise
    2929             :              * comparison.  We must propagate PK changes if the value is
    2930             :              * changed to one that "looks" different but would compare as
    2931             :              * equal using the equality operator.  This only makes a
    2932             :              * difference for ON UPDATE CASCADE, but for consistency we treat
    2933             :              * all changes to the PK the same.
    2934             :              */
    2935        1808 :             CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
    2936             : 
    2937        1808 :             if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
    2938         972 :                 return false;
    2939             :         }
    2940             :         else
    2941             :         {
    2942             :             Oid         eq_opr;
    2943             : 
    2944             :             /*
    2945             :              * When comparing the PERIOD columns we can skip the check
    2946             :              * whenever the referencing column stayed equal or shrank, so test
    2947             :              * with the contained-by operator instead.
    2948             :              */
    2949         854 :             if (riinfo->hasperiod && i == riinfo->nkeys - 1)
    2950          48 :                 eq_opr = riinfo->period_contained_by_oper;
    2951             :             else
    2952         806 :                 eq_opr = riinfo->ff_eq_oprs[i];
    2953             : 
    2954             :             /*
    2955             :              * For the FK table, compare with the appropriate equality
    2956             :              * operator.  Changes that compare equal will still satisfy the
    2957             :              * constraint after the update.
    2958             :              */
    2959         854 :             if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
    2960             :                                     newvalue, oldvalue))
    2961         306 :                 return false;
    2962             :         }
    2963             :     }
    2964             : 
    2965        1000 :     return true;
    2966             : }
    2967             : 
    2968             : 
    2969             : /*
    2970             :  * ri_CompareWithCast -
    2971             :  *
    2972             :  * Call the appropriate comparison operator for two values.
    2973             :  * Normally this is equality, but for the PERIOD part of foreign keys
    2974             :  * it is ContainedBy, so the order of lhs vs rhs is significant.
    2975             :  * See below for how the collation is applied.
    2976             :  *
    2977             :  * NB: we have already checked that neither value is null.
    2978             :  */
    2979             : static bool
    2980         854 : ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
    2981             :                    Datum lhs, Datum rhs)
    2982             : {
    2983         854 :     RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
    2984             : 
    2985             :     /* Do we need to cast the values? */
    2986         854 :     if (OidIsValid(entry->cast_func_finfo.fn_oid))
    2987             :     {
    2988          12 :         lhs = FunctionCall3(&entry->cast_func_finfo,
    2989             :                             lhs,
    2990             :                             Int32GetDatum(-1),  /* typmod */
    2991             :                             BoolGetDatum(false));   /* implicit coercion */
    2992          12 :         rhs = FunctionCall3(&entry->cast_func_finfo,
    2993             :                             rhs,
    2994             :                             Int32GetDatum(-1),  /* typmod */
    2995             :                             BoolGetDatum(false));   /* implicit coercion */
    2996             :     }
    2997             : 
    2998             :     /*
    2999             :      * Apply the comparison operator.
    3000             :      *
    3001             :      * Note: This function is part of a call stack that determines whether an
    3002             :      * update to a row is significant enough that it needs checking or action
    3003             :      * on the other side of a foreign-key constraint.  Therefore, the
    3004             :      * comparison here would need to be done with the collation of the *other*
    3005             :      * table.  For simplicity (e.g., we might not even have the other table
    3006             :      * open), we'll use our own collation.  This is fine because we require
    3007             :      * that both collations have the same notion of equality (either they are
    3008             :      * both deterministic or else they are both the same).
    3009             :      *
    3010             :      * With range/multirangetypes, the collation of the base type is stored as
    3011             :      * part of the rangetype (pg_range.rngcollation), and always used, so
    3012             :      * there is no danger of inconsistency even using a non-equals operator.
    3013             :      * But if we support arbitrary types with PERIOD, we should perhaps just
    3014             :      * always force a re-check.
    3015             :      */
    3016         854 :     return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
    3017             : }
    3018             : 
    3019             : /*
    3020             :  * ri_HashCompareOp -
    3021             :  *
    3022             :  * See if we know how to compare two values, and create a new hash entry
    3023             :  * if not.
    3024             :  */
    3025             : static RI_CompareHashEntry *
    3026         854 : ri_HashCompareOp(Oid eq_opr, Oid typeid)
    3027             : {
    3028             :     RI_CompareKey key;
    3029             :     RI_CompareHashEntry *entry;
    3030             :     bool        found;
    3031             : 
    3032             :     /*
    3033             :      * On the first call initialize the hashtable
    3034             :      */
    3035         854 :     if (!ri_compare_cache)
    3036           0 :         ri_InitHashTables();
    3037             : 
    3038             :     /*
    3039             :      * Find or create a hash entry.  Note we're assuming RI_CompareKey
    3040             :      * contains no struct padding.
    3041             :      */
    3042         854 :     key.eq_opr = eq_opr;
    3043         854 :     key.typeid = typeid;
    3044         854 :     entry = (RI_CompareHashEntry *) hash_search(ri_compare_cache,
    3045             :                                                 &key,
    3046             :                                                 HASH_ENTER, &found);
    3047         854 :     if (!found)
    3048         292 :         entry->valid = false;
    3049             : 
    3050             :     /*
    3051             :      * If not already initialized, do so.  Since we'll keep this hash entry
    3052             :      * for the life of the backend, put any subsidiary info for the function
    3053             :      * cache structs into TopMemoryContext.
    3054             :      */
    3055         854 :     if (!entry->valid)
    3056             :     {
    3057             :         Oid         lefttype,
    3058             :                     righttype,
    3059             :                     castfunc;
    3060             :         CoercionPathType pathtype;
    3061             : 
    3062             :         /* We always need to know how to call the equality operator */
    3063         292 :         fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
    3064             :                       TopMemoryContext);
    3065             : 
    3066             :         /*
    3067             :          * If we chose to use a cast from FK to PK type, we may have to apply
    3068             :          * the cast function to get to the operator's input type.
    3069             :          *
    3070             :          * XXX eventually it would be good to support array-coercion cases
    3071             :          * here and in ri_CompareWithCast().  At the moment there is no point
    3072             :          * because cases involving nonidentical array types will be rejected
    3073             :          * at constraint creation time.
    3074             :          *
    3075             :          * XXX perhaps also consider supporting CoerceViaIO?  No need at the
    3076             :          * moment since that will never be generated for implicit coercions.
    3077             :          */
    3078         292 :         op_input_types(eq_opr, &lefttype, &righttype);
    3079             :         Assert(lefttype == righttype);
    3080         292 :         if (typeid == lefttype)
    3081         268 :             castfunc = InvalidOid;  /* simplest case */
    3082             :         else
    3083             :         {
    3084          24 :             pathtype = find_coercion_pathway(lefttype, typeid,
    3085             :                                              COERCION_IMPLICIT,
    3086             :                                              &castfunc);
    3087          24 :             if (pathtype != COERCION_PATH_FUNC &&
    3088             :                 pathtype != COERCION_PATH_RELABELTYPE)
    3089             :             {
    3090             :                 /*
    3091             :                  * The declared input type of the eq_opr might be a
    3092             :                  * polymorphic type such as ANYARRAY or ANYENUM, or other
    3093             :                  * special cases such as RECORD; find_coercion_pathway
    3094             :                  * currently doesn't subsume these special cases.
    3095             :                  */
    3096          18 :                 if (!IsBinaryCoercible(typeid, lefttype))
    3097           0 :                     elog(ERROR, "no conversion function from %s to %s",
    3098             :                          format_type_be(typeid),
    3099             :                          format_type_be(lefttype));
    3100             :             }
    3101             :         }
    3102         292 :         if (OidIsValid(castfunc))
    3103           6 :             fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
    3104             :                           TopMemoryContext);
    3105             :         else
    3106         286 :             entry->cast_func_finfo.fn_oid = InvalidOid;
    3107         292 :         entry->valid = true;
    3108             :     }
    3109             : 
    3110         854 :     return entry;
    3111             : }
    3112             : 
    3113             : 
    3114             : /*
    3115             :  * Given a trigger function OID, determine whether it is an RI trigger,
    3116             :  * and if so whether it is attached to PK or FK relation.
    3117             :  */
    3118             : int
    3119        8252 : RI_FKey_trigger_type(Oid tgfoid)
    3120             : {
    3121        8252 :     switch (tgfoid)
    3122             :     {
    3123        3028 :         case F_RI_FKEY_CASCADE_DEL:
    3124             :         case F_RI_FKEY_CASCADE_UPD:
    3125             :         case F_RI_FKEY_RESTRICT_DEL:
    3126             :         case F_RI_FKEY_RESTRICT_UPD:
    3127             :         case F_RI_FKEY_SETNULL_DEL:
    3128             :         case F_RI_FKEY_SETNULL_UPD:
    3129             :         case F_RI_FKEY_SETDEFAULT_DEL:
    3130             :         case F_RI_FKEY_SETDEFAULT_UPD:
    3131             :         case F_RI_FKEY_NOACTION_DEL:
    3132             :         case F_RI_FKEY_NOACTION_UPD:
    3133        3028 :             return RI_TRIGGER_PK;
    3134             : 
    3135        2474 :         case F_RI_FKEY_CHECK_INS:
    3136             :         case F_RI_FKEY_CHECK_UPD:
    3137        2474 :             return RI_TRIGGER_FK;
    3138             :     }
    3139             : 
    3140        2750 :     return RI_TRIGGER_NONE;
    3141             : }

Generated by: LCOV version 1.14