LCOV - differential code coverage report
Current view: top level - src/backend/utils/adt - ri_triggers.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 91.7 % 845 775 2 17 48 3 29 454 15 277 37 474 1 7
Current Date: 2023-04-08 17:13:01 Functions: 100.0 % 42 42 42 42
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 (120,180] days: 88.2 % 17 15 2 15
Legend: Lines: hit not hit (240..) days: 91.8 % 828 760 17 48 3 29 454 277 37 472
Function coverage date bins:
(240..) days: 50.0 % 84 42 42 42

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

Generated by: LCOV version v1.16-55-g56c0a2a