PostgreSQL Source Code git master
Loading...
Searching...
No Matches
ri_triggers.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "lib/ilist.h"
#include "miscadmin.h"
#include "parser/parse_coerce.h"
#include "parser/parse_relation.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for ri_triggers.c:

Go to the source code of this file.

Data Structures

struct  RI_ConstraintInfo
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 

Macros

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS
 
#define RI_INIT_CONSTRAINTHASHSIZE   64
 
#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)
 
#define RI_KEYS_ALL_NULL   0
 
#define RI_KEYS_SOME_NULL   1
 
#define RI_KEYS_NONE_NULL   2
 
#define RI_PLAN_CHECK_LOOKUPPK   1
 
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2
 
#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK
 
#define RI_PLAN_CASCADE_ONDELETE   3
 
#define RI_PLAN_CASCADE_ONUPDATE   4
 
#define RI_PLAN_NO_ACTION   5
 
#define RI_PLAN_RESTRICT   6
 
#define RI_PLAN_SETNULL_ONDELETE   7
 
#define RI_PLAN_SETNULL_ONUPDATE   8
 
#define RI_PLAN_SETDEFAULT_ONDELETE   9
 
#define RI_PLAN_SETDEFAULT_ONUPDATE   10
 
#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)
 
#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)
 
#define RIAttName(rel, attnum)   NameStr(*attnumAttName(rel, attnum))
 
#define RIAttType(rel, attnum)   attnumTypeId(rel, attnum)
 
#define RIAttCollation(rel, attnum)   attnumCollationId(rel, attnum)
 
#define RI_TRIGTYPE_INSERT   1
 
#define RI_TRIGTYPE_UPDATE   2
 
#define RI_TRIGTYPE_DELETE   3
 

Typedefs

typedef struct RI_ConstraintInfo RI_ConstraintInfo
 
typedef struct RI_QueryKey RI_QueryKey
 
typedef struct RI_QueryHashEntry RI_QueryHashEntry
 
typedef struct RI_CompareKey RI_CompareKey
 
typedef struct RI_CompareHashEntry RI_CompareHashEntry
 

Functions

static bool ri_Check_Pk_Match (Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
 
static Datum ri_restrict (TriggerData *trigdata, bool is_no_action)
 
static Datum ri_set (TriggerData *trigdata, bool is_set_null, int tgkind)
 
static void quoteOneName (char *buffer, const char *name)
 
static void quoteRelationName (char *buffer, Relation rel)
 
static void ri_GenerateQual (StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
static void ri_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static void ri_BuildQueryKey (RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
 
static bool ri_KeysEqual (Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static bool ri_CompareWithCast (Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
 
static void ri_InitHashTables (void)
 
static void InvalidateConstraintCacheCallBack (Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
 
static SPIPlanPtr ri_FetchPreparedPlan (RI_QueryKey *key)
 
static void ri_HashPreparedPlan (RI_QueryKey *key, SPIPlanPtr plan)
 
static RI_CompareHashEntryri_HashCompareOp (Oid eq_opr, Oid typeid)
 
static void ri_CheckTrigger (FunctionCallInfo fcinfo, const char *funcname, int tgkind)
 
static const RI_ConstraintInfori_FetchConstraintInfo (Trigger *trigger, Relation trig_rel, bool rel_is_pk)
 
static const RI_ConstraintInfori_LoadConstraintInfo (Oid constraintOid)
 
static Oid get_ri_constraint_root (Oid constrOid)
 
static SPIPlanPtr ri_PlanCheck (const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
 
static bool ri_PerformCheck (const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool is_restrict, bool detectNewRows, int expect_OK)
 
static void ri_ExtractValues (Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
 
static pg_noreturn void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
 
static Datum RI_FKey_check (TriggerData *trigdata)
 
Datum RI_FKey_check_ins (PG_FUNCTION_ARGS)
 
Datum RI_FKey_check_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_upd (PG_FUNCTION_ARGS)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
void RI_PartitionRemove_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

static HTABri_constraint_cache = NULL
 
static HTABri_query_cache = NULL
 
static HTABri_compare_cache = NULL
 
static dclist_head ri_constraint_cache_valid_list
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

Definition at line 83 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 84 of file ri_triggers.c.

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 60 of file ri_triggers.c.

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 61 of file ri_triggers.c.

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 63 of file ri_triggers.c.

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

Definition at line 65 of file ri_triggers.c.

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 64 of file ri_triggers.c.

◆ RI_MAX_NUMKEYS

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS

Definition at line 58 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONDELETE

#define RI_PLAN_CASCADE_ONDELETE   3

Definition at line 73 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONUPDATE

#define RI_PLAN_CASCADE_ONUPDATE   4

Definition at line 74 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 69 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 70 of file ri_triggers.c.

◆ RI_PLAN_LAST_ON_PK

#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK

Definition at line 71 of file ri_triggers.c.

◆ RI_PLAN_NO_ACTION

#define RI_PLAN_NO_ACTION   5

Definition at line 75 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   6

Definition at line 77 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   9

Definition at line 80 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   10

Definition at line 81 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   7

Definition at line 78 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   8

Definition at line 79 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 92 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 90 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 91 of file ri_triggers.c.

◆ RIAttCollation

#define RIAttCollation (   rel,
  attnum 
)    attnumCollationId(rel, attnum)

Definition at line 88 of file ri_triggers.c.

◆ RIAttName

#define RIAttName (   rel,
  attnum 
)    NameStr(*attnumAttName(rel, attnum))

Definition at line 86 of file ri_triggers.c.

◆ RIAttType

#define RIAttType (   rel,
  attnum 
)    attnumTypeId(rel, attnum)

Definition at line 87 of file ri_triggers.c.

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

Function Documentation

◆ get_ri_constraint_root()

static Oid get_ri_constraint_root ( Oid  constrOid)
static

Definition at line 2367 of file ri_triggers.c.

2368{
2369 for (;;)
2370 {
2371 HeapTuple tuple;
2373
2375 if (!HeapTupleIsValid(tuple))
2376 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2378 ReleaseSysCache(tuple);
2380 break; /* we reached the root constraint */
2382 }
2383 return constrOid;
2384}
#define OidIsValid(objectId)
Definition c.h:800
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
unsigned int Oid
static int fb(int x)
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220

References elog, ERROR, fb(), Form_pg_constraint, GETSTRUCT(), HeapTupleIsValid, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), and SearchSysCache1().

Referenced by ri_LoadConstraintInfo().

◆ InvalidateConstraintCacheCallBack()

static void InvalidateConstraintCacheCallBack ( Datum  arg,
SysCacheIdentifier  cacheid,
uint32  hashvalue 
)
static

Definition at line 2401 of file ri_triggers.c.

2403{
2404 dlist_mutable_iter iter;
2405
2407
2408 /*
2409 * If the list of currently valid entries gets excessively large, we mark
2410 * them all invalid so we can empty the list. This arrangement avoids
2411 * O(N^2) behavior in situations where a session touches many foreign keys
2412 * and also does many ALTER TABLEs, such as a restore from pg_dump.
2413 */
2415 hashvalue = 0; /* pretend it's a cache reset */
2416
2418 {
2420 valid_link, iter.cur);
2421
2422 /*
2423 * We must invalidate not only entries directly matching the given
2424 * hash value, but also child entries, in case the invalidation
2425 * affects a root constraint.
2426 */
2427 if (hashvalue == 0 ||
2428 riinfo->oidHashValue == hashvalue ||
2429 riinfo->rootHashValue == hashvalue)
2430 {
2431 riinfo->valid = false;
2432 /* Remove invalidated entries from the list, too */
2434 }
2435 }
2436}
#define Assert(condition)
Definition c.h:885
#define dclist_container(type, membername, ptr)
Definition ilist.h:947
static uint32 dclist_count(const dclist_head *head)
Definition ilist.h:932
static void dclist_delete_from(dclist_head *head, dlist_node *node)
Definition ilist.h:763
#define dclist_foreach_modify(iter, lhead)
Definition ilist.h:973
static dclist_head ri_constraint_cache_valid_list
static HTAB * ri_constraint_cache
dlist_node * cur
Definition ilist.h:200

References Assert, dlist_mutable_iter::cur, dclist_container, dclist_count(), dclist_delete_from(), dclist_foreach_modify, fb(), ri_constraint_cache, and ri_constraint_cache_valid_list.

Referenced by ri_InitHashTables().

◆ quoteOneName()

static void quoteOneName ( char buffer,
const char name 
)
static

Definition at line 2032 of file ri_triggers.c.

2033{
2034 /* Rather than trying to be smart, just always quote it. */
2035 *buffer++ = '"';
2036 while (*name)
2037 {
2038 if (*name == '"')
2039 *buffer++ = '"';
2040 *buffer++ = *name++;
2041 }
2042 *buffer++ = '"';
2043 *buffer = '\0';
2044}
const char * name

References name.

Referenced by quoteRelationName(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_GenerateQualCollation(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

◆ quoteRelationName()

static void quoteRelationName ( char buffer,
Relation  rel 
)
static

Definition at line 2052 of file ri_triggers.c.

2053{
2055 buffer += strlen(buffer);
2056 *buffer++ = '.';
2058}
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3518
#define RelationGetRelationName(relation)
Definition rel.h:548
#define RelationGetNamespace(relation)
Definition rel.h:555
static void quoteOneName(char *buffer, const char *name)

References fb(), get_namespace_name(), quoteOneName(), RelationGetNamespace, and RelationGetRelationName.

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

◆ ri_BuildQueryKey()

static void ri_BuildQueryKey ( RI_QueryKey key,
const RI_ConstraintInfo riinfo,
int32  constr_queryno 
)
static

Definition at line 2137 of file ri_triggers.c.

2139{
2140 /*
2141 * Inherited constraints with a common ancestor can share ri_query_cache
2142 * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2143 * Except in that case, the query processes the other table involved in
2144 * the FK constraint (i.e., not the table on which the trigger has been
2145 * fired), and so it will be the same for all members of the inheritance
2146 * tree. So we may use the root constraint's OID in the hash key, rather
2147 * than the constraint's own OID. This avoids creating duplicate SPI
2148 * plans, saving lots of work and memory when there are many partitions
2149 * with similar FK constraints.
2150 *
2151 * (Note that we must still have a separate RI_ConstraintInfo for each
2152 * constraint, because partitions can have different column orders,
2153 * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2154 *
2155 * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2156 * to use memset to clear them.
2157 */
2158 if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2159 key->constr_id = riinfo->constraint_root_id;
2160 else
2161 key->constr_id = riinfo->constraint_id;
2162 key->constr_queryno = constr_queryno;
2163}
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition ri_triggers.c:70

References fb(), and RI_PLAN_CHECK_LOOKUPPK_FROM_PK.

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_restrict(), and ri_set().

◆ ri_Check_Pk_Match()

static bool ri_Check_Pk_Match ( Relation  pk_rel,
Relation  fk_rel,
TupleTableSlot oldslot,
const RI_ConstraintInfo riinfo 
)
static

Definition at line 512 of file ri_triggers.c.

515{
518 bool result;
519
520 /* Only called for non-null rows */
522
523 SPI_connect();
524
525 /*
526 * Fetch or prepare a saved plan for checking PK table with values coming
527 * from a PK row
528 */
530
531 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
532 {
536 char paramname[16];
537 const char *querysep;
538 const char *pk_only;
540
541 /* ----------
542 * The query string built is
543 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
544 * FOR KEY SHARE OF x
545 * The type id's for the $ parameters are those of the
546 * PK attributes themselves.
547 *
548 * But for temporal FKs we need to make sure
549 * the old PK's range is completely covered.
550 * So we use this query instead:
551 * SELECT 1
552 * FROM (
553 * SELECT pkperiodatt AS r
554 * FROM [ONLY] pktable x
555 * WHERE pkatt1 = $1 [AND ...]
556 * AND pkperiodatt && $n
557 * FOR KEY SHARE OF x
558 * ) x1
559 * HAVING $n <@ range_agg(x1.r)
560 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
561 * we can make this a bit simpler.
562 * ----------
563 */
565 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
566 "" : "ONLY ";
568 if (riinfo->hasperiod)
569 {
570 quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
571
573 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
575 }
576 else
577 {
578 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
580 }
581 querysep = "WHERE";
582 for (int i = 0; i < riinfo->nkeys; i++)
583 {
584 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
585
587 RIAttName(pk_rel, riinfo->pk_attnums[i]));
588 sprintf(paramname, "$%d", i + 1);
591 riinfo->pp_eq_oprs[i],
593 querysep = "AND";
595 }
596 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
597 if (riinfo->hasperiod)
598 {
599 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
600
601 appendStringInfoString(&querybuf, ") x1 HAVING ");
602 sprintf(paramname, "$%d", riinfo->nkeys);
605 riinfo->agged_period_contained_by_oper,
606 "pg_catalog.range_agg", ANYMULTIRANGEOID);
608 }
609
610 /* Prepare and save the plan */
612 &qkey, fk_rel, pk_rel);
613 }
614
615 /*
616 * We have a plan now. Run it.
617 */
618 result = ri_PerformCheck(riinfo, &qkey, qplan,
619 fk_rel, pk_rel,
620 oldslot, NULL,
621 false,
622 true, /* treat like update */
624
625 if (SPI_finish() != SPI_OK_FINISH)
626 elog(ERROR, "SPI_finish failed");
627
628 return result;
629}
int i
Definition isn.c:77
NameData attname
#define sprintf
Definition port.h:262
#define RelationGetDescr(relation)
Definition rel.h:540
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool is_restrict, bool detectNewRows, int expect_OK)
#define RIAttType(rel, attnum)
Definition ri_triggers.c:87
#define MAX_QUOTED_REL_NAME_LEN
Definition ri_triggers.c:84
static void quoteRelationName(char *buffer, Relation rel)
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
#define RI_KEYS_NONE_NULL
Definition ri_triggers.c:65
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
#define MAX_QUOTED_NAME_LEN
Definition ri_triggers.c:83
#define RIAttName(rel, attnum)
Definition ri_triggers.c:86
#define RI_MAX_NUMKEYS
Definition ri_triggers.c:58
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
int SPI_connect(void)
Definition spi.c:94
int SPI_finish(void)
Definition spi.c:182
#define SPI_OK_FINISH
Definition spi.h:83
#define SPI_OK_SELECT
Definition spi.h:86
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97

References appendStringInfo(), appendStringInfoString(), Assert, attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, quoteOneName(), quoteRelationName(), RelationGetDescr, ri_BuildQueryKey(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_NONE_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK_FROM_PK, ri_PlanCheck(), RIAttName, RIAttType, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, and sprintf.

Referenced by ri_restrict().

◆ ri_CheckTrigger()

static void ri_CheckTrigger ( FunctionCallInfo  fcinfo,
const char funcname,
int  tgkind 
)
static

Definition at line 2169 of file ri_triggers.c.

2170{
2171 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2172
2173 if (!CALLED_AS_TRIGGER(fcinfo))
2174 ereport(ERROR,
2176 errmsg("function \"%s\" was not called by trigger manager", funcname)));
2177
2178 /*
2179 * Check proper event
2180 */
2181 if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2182 !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2183 ereport(ERROR,
2185 errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2186
2187 switch (tgkind)
2188 {
2189 case RI_TRIGTYPE_INSERT:
2190 if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2191 ereport(ERROR,
2193 errmsg("function \"%s\" must be fired for INSERT", funcname)));
2194 break;
2195 case RI_TRIGTYPE_UPDATE:
2196 if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2197 ereport(ERROR,
2199 errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2200 break;
2201 case RI_TRIGTYPE_DELETE:
2202 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2203 ereport(ERROR,
2205 errmsg("function \"%s\" must be fired for DELETE", funcname)));
2206 break;
2207 }
2208}
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ereport(elevel,...)
Definition elog.h:150
#define funcname
#define RI_TRIGTYPE_INSERT
Definition ri_triggers.c:90
#define RI_TRIGTYPE_DELETE
Definition ri_triggers.c:92
#define RI_TRIGTYPE_UPDATE
Definition ri_triggers.c:91
#define TRIGGER_FIRED_BY_DELETE(event)
Definition trigger.h:115
#define CALLED_AS_TRIGGER(fcinfo)
Definition trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition trigger.h:124
#define TRIGGER_FIRED_AFTER(event)
Definition trigger.h:133
#define TRIGGER_FIRED_BY_INSERT(event)
Definition trigger.h:112
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition trigger.h:118

References CALLED_AS_TRIGGER, FunctionCallInfoBaseData::context, ereport, errcode(), errmsg(), ERROR, fb(), funcname, RI_TRIGTYPE_DELETE, RI_TRIGTYPE_INSERT, RI_TRIGTYPE_UPDATE, TriggerData::tg_event, TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_UPDATE, and TRIGGER_FIRED_FOR_ROW.

Referenced by RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check_ins(), RI_FKey_check_upd(), RI_FKey_noaction_del(), RI_FKey_noaction_upd(), RI_FKey_restrict_del(), RI_FKey_restrict_upd(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), and RI_FKey_setnull_upd().

◆ ri_CompareWithCast()

static bool ri_CompareWithCast ( Oid  eq_opr,
Oid  typeid,
Oid  collid,
Datum  lhs,
Datum  rhs 
)
static

Definition at line 3073 of file ri_triggers.c.

3075{
3076 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3077
3078 /* Do we need to cast the values? */
3079 if (OidIsValid(entry->cast_func_finfo.fn_oid))
3080 {
3082 lhs,
3083 Int32GetDatum(-1), /* typmod */
3084 BoolGetDatum(false)); /* implicit coercion */
3086 rhs,
3087 Int32GetDatum(-1), /* typmod */
3088 BoolGetDatum(false)); /* implicit coercion */
3089 }
3090
3091 /*
3092 * Apply the comparison operator.
3093 *
3094 * Note: This function is part of a call stack that determines whether an
3095 * update to a row is significant enough that it needs checking or action
3096 * on the other side of a foreign-key constraint. Therefore, the
3097 * comparison here would need to be done with the collation of the *other*
3098 * table. For simplicity (e.g., we might not even have the other table
3099 * open), we'll use our own collation. This is fine because we require
3100 * that both collations have the same notion of equality (either they are
3101 * both deterministic or else they are both the same).
3102 *
3103 * With range/multirangetypes, the collation of the base type is stored as
3104 * part of the rangetype (pg_range.rngcollation), and always used, so
3105 * there is no danger of inconsistency even using a non-equals operator.
3106 * But if we support arbitrary types with PERIOD, we should perhaps just
3107 * always force a re-check.
3108 */
3110}
Oid collid
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:1150
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition fmgr.h:706
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Oid fn_oid
Definition fmgr.h:59

References BoolGetDatum(), RI_CompareHashEntry::cast_func_finfo, collid, DatumGetBool(), RI_CompareHashEntry::eq_opr_finfo, fb(), FmgrInfo::fn_oid, FunctionCall2Coll(), FunctionCall3, Int32GetDatum(), OidIsValid, and ri_HashCompareOp().

Referenced by ri_KeysEqual().

◆ ri_ExtractValues()

static void ri_ExtractValues ( Relation  rel,
TupleTableSlot slot,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk,
Datum vals,
char nulls 
)
static

Definition at line 2624 of file ri_triggers.c.

2627{
2628 const int16 *attnums;
2629 bool isnull;
2630
2631 if (rel_is_pk)
2632 attnums = riinfo->pk_attnums;
2633 else
2634 attnums = riinfo->fk_attnums;
2635
2636 for (int i = 0; i < riinfo->nkeys; i++)
2637 {
2638 vals[i] = slot_getattr(slot, attnums[i], &isnull);
2639 nulls[i] = isnull ? 'n' : ' ';
2640 }
2641}
int16_t int16
Definition c.h:553
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition tuptable.h:398

References fb(), i, and slot_getattr().

Referenced by ri_PerformCheck().

◆ ri_FetchConstraintInfo()

static const RI_ConstraintInfo * ri_FetchConstraintInfo ( Trigger trigger,
Relation  trig_rel,
bool  rel_is_pk 
)
static

Definition at line 2215 of file ri_triggers.c.

2216{
2217 Oid constraintOid = trigger->tgconstraint;
2219
2220 /*
2221 * Check that the FK constraint's OID is available; it might not be if
2222 * we've been invoked via an ordinary trigger or an old-style "constraint
2223 * trigger".
2224 */
2226 ereport(ERROR,
2228 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2230 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2231
2232 /* Find or create a hashtable entry for the constraint */
2234
2235 /* Do some easy cross-checks against the trigger call data */
2236 if (rel_is_pk)
2237 {
2238 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2239 riinfo->pk_relid != RelationGetRelid(trig_rel))
2240 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2242 }
2243 else
2244 {
2245 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2246 riinfo->pk_relid != trigger->tgconstrrelid)
2247 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2249 }
2250
2251 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2252 riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
2253 riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
2254 elog(ERROR, "unrecognized confmatchtype: %d",
2255 riinfo->confmatchtype);
2256
2257 if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2258 ereport(ERROR,
2260 errmsg("MATCH PARTIAL not yet implemented")));
2261
2262 return riinfo;
2263}
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FKCONSTR_MATCH_SIMPLE
#define FKCONSTR_MATCH_PARTIAL
#define FKCONSTR_MATCH_FULL
#define RelationGetRelid(relation)
Definition rel.h:514
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)

References elog, ereport, errcode(), errhint(), errmsg(), ERROR, fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, OidIsValid, RelationGetRelationName, RelationGetRelid, and ri_LoadConstraintInfo().

Referenced by RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

◆ ri_FetchPreparedPlan()

static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 2898 of file ri_triggers.c.

2899{
2900 RI_QueryHashEntry *entry;
2902
2903 /*
2904 * On the first call initialize the hashtable
2905 */
2906 if (!ri_query_cache)
2908
2909 /*
2910 * Lookup for the key
2911 */
2913 key,
2914 HASH_FIND, NULL);
2915 if (entry == NULL)
2916 return NULL;
2917
2918 /*
2919 * Check whether the plan is still valid. If it isn't, we don't want to
2920 * simply rely on plancache.c to regenerate it; rather we should start
2921 * from scratch and rebuild the query text too. This is to cover cases
2922 * such as table/column renames. We depend on the plancache machinery to
2923 * detect possible invalidations, though.
2924 *
2925 * CAUTION: this check is only trustworthy if the caller has already
2926 * locked both FK and PK rels.
2927 */
2928 plan = entry->plan;
2929 if (plan && SPI_plan_is_valid(plan))
2930 return plan;
2931
2932 /*
2933 * Otherwise we might as well flush the cached plan now, to free a little
2934 * memory space before we make a new one.
2935 */
2936 entry->plan = NULL;
2937 if (plan)
2939
2940 return NULL;
2941}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
@ HASH_FIND
Definition hsearch.h:113
#define plan(x)
Definition pg_regress.c:161
static HTAB * ri_query_cache
static void ri_InitHashTables(void)
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition spi.c:1948
int SPI_freeplan(SPIPlanPtr plan)
Definition spi.c:1025

References fb(), HASH_FIND, hash_search(), RI_QueryHashEntry::plan, plan, ri_InitHashTables(), ri_query_cache, SPI_freeplan(), and SPI_plan_is_valid().

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_restrict(), and ri_set().

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 916 of file ri_triggers.c.

917{
918 TriggerData *trigdata = (TriggerData *) fcinfo->context;
925
926 /* Check that this is a valid trigger call on the right time and event. */
927 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
928
929 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
930 trigdata->tg_relation, true);
931
932 /*
933 * Get the relation descriptors of the FK and PK tables and the old tuple.
934 *
935 * fk_rel is opened in RowExclusiveLock mode since that's what our
936 * eventual DELETE will get on it.
937 */
939 pk_rel = trigdata->tg_relation;
940 oldslot = trigdata->tg_trigslot;
941
942 SPI_connect();
943
944 /* Fetch or prepare a saved plan for the cascaded delete */
946
947 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
948 {
952 char paramname[16];
953 const char *querysep;
955 const char *fk_only;
956
957 /* ----------
958 * The query string built is
959 * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
960 * The type id's for the $ parameters are those of the
961 * corresponding PK attributes.
962 * ----------
963 */
965 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
966 "" : "ONLY ";
968 appendStringInfo(&querybuf, "DELETE FROM %s%s",
970 querysep = "WHERE";
971 for (int i = 0; i < riinfo->nkeys; i++)
972 {
973 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
974 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
975
977 RIAttName(fk_rel, riinfo->fk_attnums[i]));
978 sprintf(paramname, "$%d", i + 1);
981 riinfo->pf_eq_oprs[i],
983 querysep = "AND";
985 }
986
987 /* Prepare and save the plan */
989 &qkey, fk_rel, pk_rel);
990 }
991
992 /*
993 * We have a plan now. Build up the arguments from the key values in the
994 * deleted PK tuple and delete the referencing rows
995 */
997 fk_rel, pk_rel,
998 oldslot, NULL,
999 false,
1000 true, /* must detect new rows */
1002
1003 if (SPI_finish() != SPI_OK_FINISH)
1004 elog(ERROR, "SPI_finish failed");
1005
1007
1008 return PointerGetDatum(NULL);
1009}
#define RowExclusiveLock
Definition lockdefs.h:38
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
#define RI_PLAN_CASCADE_ONDELETE
Definition ri_triggers.c:73
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
#define SPI_OK_DELETE
Definition spi.h:89
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References appendStringInfo(), attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum(), quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONDELETE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_DELETE, SPI_OK_FINISH, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

◆ RI_FKey_cascade_upd()

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 1018 of file ri_triggers.c.

1019{
1020 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1028
1029 /* Check that this is a valid trigger call on the right time and event. */
1030 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1031
1032 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1033 trigdata->tg_relation, true);
1034
1035 /*
1036 * Get the relation descriptors of the FK and PK tables and the new and
1037 * old tuple.
1038 *
1039 * fk_rel is opened in RowExclusiveLock mode since that's what our
1040 * eventual UPDATE will get on it.
1041 */
1043 pk_rel = trigdata->tg_relation;
1044 newslot = trigdata->tg_newslot;
1045 oldslot = trigdata->tg_trigslot;
1046
1047 SPI_connect();
1048
1049 /* Fetch or prepare a saved plan for the cascaded update */
1051
1052 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1053 {
1058 char paramname[16];
1059 const char *querysep;
1060 const char *qualsep;
1062 const char *fk_only;
1063
1064 /* ----------
1065 * The query string built is
1066 * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1067 * WHERE $n = fkatt1 [AND ...]
1068 * The type id's for the $ parameters are those of the
1069 * corresponding PK attributes. Note that we are assuming
1070 * there is an assignment cast from the PK to the FK type;
1071 * else the parser will fail.
1072 * ----------
1073 */
1076 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1077 "" : "ONLY ";
1079 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1081 querysep = "";
1082 qualsep = "WHERE";
1083 for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1084 {
1085 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1086 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1087
1089 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1091 "%s %s = $%d",
1092 querysep, attname, i + 1);
1093 sprintf(paramname, "$%d", j + 1);
1096 riinfo->pf_eq_oprs[i],
1097 attname, fk_type);
1098 querysep = ",";
1099 qualsep = "AND";
1100 queryoids[i] = pk_type;
1101 queryoids[j] = pk_type;
1102 }
1104
1105 /* Prepare and save the plan */
1106 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1107 &qkey, fk_rel, pk_rel);
1108 }
1109
1110 /*
1111 * We have a plan now. Run it to update the existing references.
1112 */
1114 fk_rel, pk_rel,
1116 false,
1117 true, /* must detect new rows */
1119
1120 if (SPI_finish() != SPI_OK_FINISH)
1121 elog(ERROR, "SPI_finish failed");
1122
1124
1125 return PointerGetDatum(NULL);
1126}
int j
Definition isn.c:78
#define RI_PLAN_CASCADE_ONUPDATE
Definition ri_triggers.c:74
#define SPI_OK_UPDATE
Definition spi.h:90
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281

References appendBinaryStringInfo(), appendStringInfo(), attname, elog, ERROR, fb(), i, initStringInfo(), j, MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum(), quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_UPDATE, sprintf, table_close(), table_open(), TriggerData::tg_newslot, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

◆ RI_FKey_check()

static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 251 of file ri_triggers.c.

252{
259
261 trigdata->tg_relation, false);
262
263 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
264 newslot = trigdata->tg_newslot;
265 else
266 newslot = trigdata->tg_trigslot;
267
268 /*
269 * We should not even consider checking the row if it is no longer valid,
270 * since it was either deleted (so the deferred check should be skipped)
271 * or updated (in which case only the latest version of the row should be
272 * checked). Test its liveness according to SnapshotSelf. We need pin
273 * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
274 * should be holding pin, but not lock.
275 */
277 return PointerGetDatum(NULL);
278
279 /*
280 * Get the relation descriptors of the FK and PK tables.
281 *
282 * pk_rel is opened in RowShareLock mode since that's what our eventual
283 * SELECT FOR KEY SHARE will get on it.
284 */
285 fk_rel = trigdata->tg_relation;
286 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
287
289 {
290 case RI_KEYS_ALL_NULL:
291
292 /*
293 * No further check needed - an all-NULL key passes every type of
294 * foreign key constraint.
295 */
297 return PointerGetDatum(NULL);
298
300
301 /*
302 * This is the only case that differs between the three kinds of
303 * MATCH.
304 */
305 switch (riinfo->confmatchtype)
306 {
308
309 /*
310 * Not allowed - MATCH FULL says either all or none of the
311 * attributes can be NULLs
312 */
315 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
317 NameStr(riinfo->conname)),
318 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
320 NameStr(riinfo->conname))));
322 return PointerGetDatum(NULL);
323
325
326 /*
327 * MATCH SIMPLE - if ANY column is null, the key passes
328 * the constraint.
329 */
331 return PointerGetDatum(NULL);
332
333#ifdef NOT_USED
335
336 /*
337 * MATCH PARTIAL - all non-null columns must match. (not
338 * implemented, can be done by modifying the query below
339 * to only include non-null columns, or by writing a
340 * special version here)
341 */
342 break;
343#endif
344 }
345
347
348 /*
349 * Have a full qualified key - continue below for all three kinds
350 * of MATCH.
351 */
352 break;
353 }
354
355 SPI_connect();
356
357 /* Fetch or prepare a saved plan for the real check */
359
360 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
361 {
365 char paramname[16];
366 const char *querysep;
368 const char *pk_only;
369
370 /* ----------
371 * The query string built is
372 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
373 * FOR KEY SHARE OF x
374 * The type id's for the $ parameters are those of the
375 * corresponding FK attributes.
376 *
377 * But for temporal FKs we need to make sure
378 * the FK's range is completely covered.
379 * So we use this query instead:
380 * SELECT 1
381 * FROM (
382 * SELECT pkperiodatt AS r
383 * FROM [ONLY] pktable x
384 * WHERE pkatt1 = $1 [AND ...]
385 * AND pkperiodatt && $n
386 * FOR KEY SHARE OF x
387 * ) x1
388 * HAVING $n <@ range_agg(x1.r)
389 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
390 * we can make this a bit simpler.
391 * ----------
392 */
394 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
395 "" : "ONLY ";
397 if (riinfo->hasperiod)
398 {
400 RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
401
403 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
405 }
406 else
407 {
408 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
410 }
411 querysep = "WHERE";
412 for (int i = 0; i < riinfo->nkeys; i++)
413 {
414 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
415 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
416
418 RIAttName(pk_rel, riinfo->pk_attnums[i]));
419 sprintf(paramname, "$%d", i + 1);
422 riinfo->pf_eq_oprs[i],
424 querysep = "AND";
426 }
427 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
428 if (riinfo->hasperiod)
429 {
430 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
431
432 appendStringInfoString(&querybuf, ") x1 HAVING ");
433 sprintf(paramname, "$%d", riinfo->nkeys);
436 riinfo->agged_period_contained_by_oper,
437 "pg_catalog.range_agg", ANYMULTIRANGEOID);
439 }
440
441 /* Prepare and save the plan */
443 &qkey, fk_rel, pk_rel);
444 }
445
446 /*
447 * Now check that foreign key exists in PK table
448 *
449 * XXX detectNewRows must be true when a partitioned table is on the
450 * referenced side. The reason is that our snapshot must be fresh in
451 * order for the hack in find_inheritance_children() to work.
452 */
454 fk_rel, pk_rel,
455 NULL, newslot,
456 false,
457 pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
459
460 if (SPI_finish() != SPI_OK_FINISH)
461 elog(ERROR, "SPI_finish failed");
462
464
465 return PointerGetDatum(NULL);
466}
#define NameStr(name)
Definition c.h:777
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define RowShareLock
Definition lockdefs.h:37
int errtableconstraint(Relation rel, const char *conname)
Definition relcache.c:6098
#define RI_KEYS_SOME_NULL
Definition ri_triggers.c:64
#define RI_KEYS_ALL_NULL
Definition ri_triggers.c:63
#define RI_PLAN_CHECK_LOOKUPPK
Definition ri_triggers.c:69
#define SnapshotSelf
Definition snapmgr.h:32
Relation tg_relation
Definition trigger.h:35
TriggerEvent tg_event
Definition trigger.h:34
TupleTableSlot * tg_trigslot
Definition trigger.h:39
TupleTableSlot * tg_newslot
Definition trigger.h:40
Trigger * tg_trigger
Definition trigger.h:38
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition tableam.h:1321

References appendStringInfo(), appendStringInfoString(), attname, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, PointerGetDatum(), quoteOneName(), quoteRelationName(), RelationGetDescr, RelationGetRelationName, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SnapshotSelf, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, sprintf, table_close(), table_open(), table_tuple_satisfies_snapshot(), TriggerData::tg_event, TriggerData::tg_newslot, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_check_ins(), and RI_FKey_check_upd().

◆ RI_FKey_check_ins()

Datum RI_FKey_check_ins ( PG_FUNCTION_ARGS  )

Definition at line 475 of file ri_triggers.c.

476{
477 /* Check that this is a valid trigger call on the right time and event. */
478 ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
479
480 /* Share code with UPDATE case. */
481 return RI_FKey_check((TriggerData *) fcinfo->context);
482}
static Datum RI_FKey_check(TriggerData *trigdata)

References ri_CheckTrigger(), RI_FKey_check(), and RI_TRIGTYPE_INSERT.

Referenced by validateForeignKeyConstraint().

◆ RI_FKey_check_upd()

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS  )

Definition at line 491 of file ri_triggers.c.

492{
493 /* Check that this is a valid trigger call on the right time and event. */
494 ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
495
496 /* Share code with INSERT case. */
497 return RI_FKey_check((TriggerData *) fcinfo->context);
498}

References ri_CheckTrigger(), RI_FKey_check(), and RI_TRIGTYPE_UPDATE.

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1419 of file ri_triggers.c.

1421{
1423 int ri_nullcheck;
1424
1425 /*
1426 * AfterTriggerSaveEvent() handles things such that this function is never
1427 * called for partitioned tables.
1428 */
1429 Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1430
1432
1434
1435 /*
1436 * If all new key values are NULL, the row satisfies the constraint, so no
1437 * check is needed.
1438 */
1440 return false;
1441
1442 /*
1443 * If some new key values are NULL, the behavior depends on the match
1444 * type.
1445 */
1446 else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1447 {
1448 switch (riinfo->confmatchtype)
1449 {
1451
1452 /*
1453 * If any new key value is NULL, the row must satisfy the
1454 * constraint, so no check is needed.
1455 */
1456 return false;
1457
1459
1460 /*
1461 * Don't know, must run full check.
1462 */
1463 break;
1464
1466
1467 /*
1468 * If some new key values are NULL, the row fails the
1469 * constraint. We must not throw error here, because the row
1470 * might get invalidated before the constraint is to be
1471 * checked, but we should queue the event to apply the check
1472 * later.
1473 */
1474 return true;
1475 }
1476 }
1477
1478 /*
1479 * Continues here for no new key values are NULL, or we couldn't decide
1480 * yet.
1481 */
1482
1483 /*
1484 * If the original row was inserted by our own transaction, we must fire
1485 * the trigger whether or not the keys are equal. This is because our
1486 * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1487 * not do anything; so we had better do the UPDATE check. (We could skip
1488 * this if we knew the INSERT trigger already fired, but there is no easy
1489 * way to know that.)
1490 */
1492 return true;
1493
1494 /* If all old and new key values are equal, no check is needed */
1495 if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1496 return false;
1497
1498 /* Else we need to fire the trigger. */
1499 return true;
1500}
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition tuptable.h:448

References Assert, fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_ALL_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), and slot_is_current_xact_tuple().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 640 of file ri_triggers.c.

641{
642 /* Check that this is a valid trigger call on the right time and event. */
643 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
644
645 /* Share code with RESTRICT/UPDATE cases. */
646 return ri_restrict((TriggerData *) fcinfo->context, true);
647}
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)

References ri_CheckTrigger(), ri_restrict(), and RI_TRIGTYPE_DELETE.

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 677 of file ri_triggers.c.

678{
679 /* Check that this is a valid trigger call on the right time and event. */
680 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
681
682 /* Share code with RESTRICT/DELETE cases. */
683 return ri_restrict((TriggerData *) fcinfo->context, true);
684}

References ri_CheckTrigger(), ri_restrict(), and RI_TRIGTYPE_UPDATE.

◆ RI_FKey_pk_upd_check_required()

bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1387 of file ri_triggers.c.

1389{
1391
1393
1394 /*
1395 * If any old key value is NULL, the row could not have been referenced by
1396 * an FK row, so no check is needed.
1397 */
1399 return false;
1400
1401 /* If all old and new key values are equal, no check is needed */
1403 return false;
1404
1405 /* Else we need to fire the trigger. */
1406 return true;
1407}

References fb(), RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_NONE_NULL, ri_KeysEqual(), and ri_NullCheck().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_restrict_del()

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 660 of file ri_triggers.c.

661{
662 /* Check that this is a valid trigger call on the right time and event. */
663 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
664
665 /* Share code with NO ACTION/UPDATE cases. */
666 return ri_restrict((TriggerData *) fcinfo->context, false);
667}

References ri_CheckTrigger(), ri_restrict(), and RI_TRIGTYPE_DELETE.

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 697 of file ri_triggers.c.

698{
699 /* Check that this is a valid trigger call on the right time and event. */
700 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
701
702 /* Share code with NO ACTION/DELETE cases. */
703 return ri_restrict((TriggerData *) fcinfo->context, false);
704}

References ri_CheckTrigger(), ri_restrict(), and RI_TRIGTYPE_UPDATE.

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1165 of file ri_triggers.c.

1166{
1167 /* Check that this is a valid trigger call on the right time and event. */
1168 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1169
1170 /* Share code with UPDATE case */
1171 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1172}
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)

References ri_CheckTrigger(), ri_set(), and RI_TRIGTYPE_DELETE.

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1180 of file ri_triggers.c.

1181{
1182 /* Check that this is a valid trigger call on the right time and event. */
1183 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1184
1185 /* Share code with DELETE case */
1186 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1187}

References ri_CheckTrigger(), ri_set(), and RI_TRIGTYPE_UPDATE.

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1135 of file ri_triggers.c.

1136{
1137 /* Check that this is a valid trigger call on the right time and event. */
1138 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1139
1140 /* Share code with UPDATE case */
1141 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1142}

References ri_CheckTrigger(), ri_set(), and RI_TRIGTYPE_DELETE.

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1150 of file ri_triggers.c.

1151{
1152 /* Check that this is a valid trigger call on the right time and event. */
1153 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1154
1155 /* Share code with DELETE case */
1156 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1157}

References ri_CheckTrigger(), ri_set(), and RI_TRIGTYPE_UPDATE.

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3212 of file ri_triggers.c.

3213{
3214 switch (tgfoid)
3215 {
3226 return RI_TRIGGER_PK;
3227
3230 return RI_TRIGGER_FK;
3231 }
3232
3233 return RI_TRIGGER_NONE;
3234}
#define RI_TRIGGER_FK
Definition trigger.h:287
#define RI_TRIGGER_NONE
Definition trigger.h:288
#define RI_TRIGGER_PK
Definition trigger.h:286

References fb(), RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), ExecCrossPartitionUpdateForeignKey(), GetForeignKeyActionTriggers(), and GetForeignKeyCheckTriggers().

◆ ri_GenerateQual()

static void ri_GenerateQual ( StringInfo  buf,
const char sep,
const char leftop,
Oid  leftoptype,
Oid  opoid,
const char rightop,
Oid  rightoptype 
)
static

Definition at line 2069 of file ri_triggers.c.

2074{
2075 appendStringInfo(buf, " %s ", sep);
2078}
static char buf[DEFAULT_XLOG_SEG_SIZE]
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)

References appendStringInfo(), buf, fb(), and generate_operator_clause().

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

◆ ri_GenerateQualCollation()

static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 2096 of file ri_triggers.c.

2097{
2098 HeapTuple tp;
2100 char *collname;
2102
2103 /* Nothing to do if it's a noncollatable data type */
2104 if (!OidIsValid(collation))
2105 return;
2106
2107 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2108 if (!HeapTupleIsValid(tp))
2109 elog(ERROR, "cache lookup failed for collation %u", collation);
2111 collname = NameStr(colltup->collname);
2112
2113 /*
2114 * We qualify the name always, for simplicity and to ensure the query is
2115 * not search-path-dependent.
2116 */
2118 appendStringInfo(buf, " COLLATE %s", onename);
2119 quoteOneName(onename, collname);
2120 appendStringInfo(buf, ".%s", onename);
2121
2122 ReleaseSysCache(tp);
2123}
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation

References appendStringInfo(), buf, elog, ERROR, fb(), Form_pg_collation, get_namespace_name(), GETSTRUCT(), HeapTupleIsValid, MAX_QUOTED_NAME_LEN, NameStr, ObjectIdGetDatum(), OidIsValid, quoteOneName(), ReleaseSysCache(), and SearchSysCache1().

Referenced by RI_Initial_Check(), and RI_PartitionRemove_Check().

◆ ri_HashCompareOp()

static RI_CompareHashEntry * ri_HashCompareOp ( Oid  eq_opr,
Oid  typeid 
)
static

Definition at line 3119 of file ri_triggers.c.

3120{
3122 RI_CompareHashEntry *entry;
3123 bool found;
3124
3125 /*
3126 * On the first call initialize the hashtable
3127 */
3128 if (!ri_compare_cache)
3130
3131 /*
3132 * Find or create a hash entry. Note we're assuming RI_CompareKey
3133 * contains no struct padding.
3134 */
3135 key.eq_opr = eq_opr;
3136 key.typeid = typeid;
3138 &key,
3139 HASH_ENTER, &found);
3140 if (!found)
3141 entry->valid = false;
3142
3143 /*
3144 * If not already initialized, do so. Since we'll keep this hash entry
3145 * for the life of the backend, put any subsidiary info for the function
3146 * cache structs into TopMemoryContext.
3147 */
3148 if (!entry->valid)
3149 {
3150 Oid lefttype,
3151 righttype,
3152 castfunc;
3153 CoercionPathType pathtype;
3154
3155 /* We always need to know how to call the equality operator */
3156 fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3158
3159 /*
3160 * If we chose to use a cast from FK to PK type, we may have to apply
3161 * the cast function to get to the operator's input type.
3162 *
3163 * XXX eventually it would be good to support array-coercion cases
3164 * here and in ri_CompareWithCast(). At the moment there is no point
3165 * because cases involving nonidentical array types will be rejected
3166 * at constraint creation time.
3167 *
3168 * XXX perhaps also consider supporting CoerceViaIO? No need at the
3169 * moment since that will never be generated for implicit coercions.
3170 */
3171 op_input_types(eq_opr, &lefttype, &righttype);
3172 Assert(lefttype == righttype);
3173 if (typeid == lefttype)
3174 castfunc = InvalidOid; /* simplest case */
3175 else
3176 {
3177 pathtype = find_coercion_pathway(lefttype, typeid,
3179 &castfunc);
3180 if (pathtype != COERCION_PATH_FUNC &&
3181 pathtype != COERCION_PATH_RELABELTYPE)
3182 {
3183 /*
3184 * The declared input type of the eq_opr might be a
3185 * polymorphic type such as ANYARRAY or ANYENUM, or other
3186 * special cases such as RECORD; find_coercion_pathway
3187 * currently doesn't subsume these special cases.
3188 */
3189 if (!IsBinaryCoercible(typeid, lefttype))
3190 elog(ERROR, "no conversion function from %s to %s",
3191 format_type_be(typeid),
3192 format_type_be(lefttype));
3193 }
3194 }
3195 if (OidIsValid(castfunc))
3196 fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3198 else
3200 entry->valid = true;
3201 }
3202
3203 return entry;
3204}
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition fmgr.c:138
char * format_type_be(Oid type_oid)
@ HASH_ENTER
Definition hsearch.h:114
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1435
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition lsyscache.c:1508
MemoryContext TopMemoryContext
Definition mcxt.c:166
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
@ COERCION_PATH_FUNC
@ COERCION_PATH_RELABELTYPE
#define InvalidOid
@ COERCION_IMPLICIT
Definition primnodes.h:747
static HTAB * ri_compare_cache

References Assert, RI_CompareHashEntry::cast_func_finfo, COERCION_IMPLICIT, COERCION_PATH_FUNC, COERCION_PATH_RELABELTYPE, elog, RI_CompareHashEntry::eq_opr_finfo, ERROR, find_coercion_pathway(), fmgr_info_cxt(), FmgrInfo::fn_oid, format_type_be(), get_opcode(), HASH_ENTER, hash_search(), InvalidOid, IsBinaryCoercible(), OidIsValid, op_input_types(), ri_compare_cache, ri_InitHashTables(), TopMemoryContext, and RI_CompareHashEntry::valid.

Referenced by ri_CompareWithCast().

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 2950 of file ri_triggers.c.

2951{
2952 RI_QueryHashEntry *entry;
2953 bool found;
2954
2955 /*
2956 * On the first call initialize the hashtable
2957 */
2958 if (!ri_query_cache)
2960
2961 /*
2962 * Add the new plan. We might be overwriting an entry previously found
2963 * invalid by ri_FetchPreparedPlan.
2964 */
2966 key,
2967 HASH_ENTER, &found);
2968 Assert(!found || entry->plan == NULL);
2969 entry->plan = plan;
2970}

References Assert, fb(), HASH_ENTER, hash_search(), RI_QueryHashEntry::plan, plan, ri_InitHashTables(), and ri_query_cache.

Referenced by ri_PlanCheck().

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

Definition at line 2862 of file ri_triggers.c.

2863{
2864 HASHCTL ctl;
2865
2866 ctl.keysize = sizeof(Oid);
2867 ctl.entrysize = sizeof(RI_ConstraintInfo);
2868 ri_constraint_cache = hash_create("RI constraint cache",
2871
2872 /* Arrange to flush cache on pg_constraint changes */
2875 (Datum) 0);
2876
2877 ctl.keysize = sizeof(RI_QueryKey);
2878 ctl.entrysize = sizeof(RI_QueryHashEntry);
2879 ri_query_cache = hash_create("RI query cache",
2882
2883 ctl.keysize = sizeof(RI_CompareKey);
2884 ctl.entrysize = sizeof(RI_CompareHashEntry);
2885 ri_compare_cache = hash_create("RI compare cache",
2888}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_BLOBS
Definition hsearch.h:97
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
uint64_t Datum
Definition postgres.h:70
tree ctl
Definition radixtree.h:1838
#define RI_INIT_QUERYHASHSIZE
Definition ri_triggers.c:61
#define RI_INIT_CONSTRAINTHASHSIZE
Definition ri_triggers.c:60
static void InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
Size keysize
Definition hsearch.h:75

References CacheRegisterSyscacheCallback(), ctl, fb(), HASH_BLOBS, hash_create(), HASH_ELEM, InvalidateConstraintCacheCallBack(), HASHCTL::keysize, ri_compare_cache, ri_constraint_cache, RI_INIT_CONSTRAINTHASHSIZE, RI_INIT_QUERYHASHSIZE, and ri_query_cache.

Referenced by ri_FetchPreparedPlan(), ri_HashCompareOp(), ri_HashPreparedPlan(), and ri_LoadConstraintInfo().

◆ RI_Initial_Check()

bool RI_Initial_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 1520 of file ri_triggers.c.

1521{
1531 List *rtes = NIL;
1532 List *perminfos = NIL;
1533 const char *sep;
1534 const char *fk_only;
1535 const char *pk_only;
1536 int save_nestlevel;
1537 char workmembuf[32];
1538 int spi_result;
1540
1542
1543 /*
1544 * Check to make sure current user has enough permissions to do the test
1545 * query. (If not, caller can fall back to the trigger method, which
1546 * works because it changes user IDs on the fly.)
1547 *
1548 * XXX are there any other show-stopper conditions to check?
1549 */
1552 pk_perminfo->requiredPerms = ACL_SELECT;
1555 rte->rtekind = RTE_RELATION;
1556 rte->relid = RelationGetRelid(pk_rel);
1557 rte->relkind = pk_rel->rd_rel->relkind;
1558 rte->rellockmode = AccessShareLock;
1559 rte->perminfoindex = list_length(perminfos);
1560 rtes = lappend(rtes, rte);
1561
1564 fk_perminfo->requiredPerms = ACL_SELECT;
1567 rte->rtekind = RTE_RELATION;
1568 rte->relid = RelationGetRelid(fk_rel);
1569 rte->relkind = fk_rel->rd_rel->relkind;
1570 rte->rellockmode = AccessShareLock;
1571 rte->perminfoindex = list_length(perminfos);
1572 rtes = lappend(rtes, rte);
1573
1574 for (int i = 0; i < riinfo->nkeys; i++)
1575 {
1576 int attno;
1577
1578 attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1579 pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1580
1581 attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1582 fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1583 }
1584
1585 if (!ExecCheckPermissions(rtes, perminfos, false))
1586 return false;
1587
1588 /*
1589 * Also punt if RLS is enabled on either table unless this role has the
1590 * bypassrls right or is the table owner of the table(s) involved which
1591 * have RLS enabled.
1592 */
1594 ((pk_rel->rd_rel->relrowsecurity &&
1596 GetUserId())) ||
1597 (fk_rel->rd_rel->relrowsecurity &&
1599 GetUserId()))))
1600 return false;
1601
1602 /*----------
1603 * The query string built is:
1604 * SELECT fk.keycols FROM [ONLY] relname fk
1605 * LEFT OUTER JOIN [ONLY] pkrelname pk
1606 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1607 * WHERE pk.pkkeycol1 IS NULL AND
1608 * For MATCH SIMPLE:
1609 * (fk.keycol1 IS NOT NULL [AND ...])
1610 * For MATCH FULL:
1611 * (fk.keycol1 IS NOT NULL [OR ...])
1612 *
1613 * We attach COLLATE clauses to the operators when comparing columns
1614 * that have different collations.
1615 *----------
1616 */
1618 appendStringInfoString(&querybuf, "SELECT ");
1619 sep = "";
1620 for (int i = 0; i < riinfo->nkeys; i++)
1621 {
1623 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1624 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1625 sep = ", ";
1626 }
1627
1630 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1631 "" : "ONLY ";
1632 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1633 "" : "ONLY ";
1635 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1637
1638 strcpy(pkattname, "pk.");
1639 strcpy(fkattname, "fk.");
1640 sep = "(";
1641 for (int i = 0; i < riinfo->nkeys; i++)
1642 {
1643 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1644 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1645 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1646 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1647
1649 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1651 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1654 riinfo->pf_eq_oprs[i],
1656 if (pk_coll != fk_coll)
1658 sep = "AND";
1659 }
1660
1661 /*
1662 * It's sufficient to test any one pk attribute for null to detect a join
1663 * failure.
1664 */
1665 quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1666 appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1667
1668 sep = "";
1669 for (int i = 0; i < riinfo->nkeys; i++)
1670 {
1671 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1673 "%sfk.%s IS NOT NULL",
1674 sep, fkattname);
1675 switch (riinfo->confmatchtype)
1676 {
1678 sep = " AND ";
1679 break;
1681 sep = " OR ";
1682 break;
1683 }
1684 }
1686
1687 /*
1688 * Temporarily increase work_mem so that the check query can be executed
1689 * more efficiently. It seems okay to do this because the query is simple
1690 * enough to not use a multiple of work_mem, and one typically would not
1691 * have many large foreign-key validations happening concurrently. So
1692 * this seems to meet the criteria for being considered a "maintenance"
1693 * operation, and accordingly we use maintenance_work_mem. However, we
1694 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1695 * let that get applied to the maintenance_work_mem value.
1696 *
1697 * We use the equivalent of a function SET option to allow the setting to
1698 * persist for exactly the duration of the check query. guc.c also takes
1699 * care of undoing the setting on error.
1700 */
1701 save_nestlevel = NewGUCNestLevel();
1702
1704 (void) set_config_option("work_mem", workmembuf,
1706 GUC_ACTION_SAVE, true, 0, false);
1707 (void) set_config_option("hash_mem_multiplier", "1",
1709 GUC_ACTION_SAVE, true, 0, false);
1710
1711 SPI_connect();
1712
1713 /*
1714 * Generate the plan. We don't need to cache it, and there are no
1715 * arguments to the plan.
1716 */
1717 qplan = SPI_prepare(querybuf.data, 0, NULL);
1718
1719 if (qplan == NULL)
1720 elog(ERROR, "SPI_prepare returned %s for %s",
1722
1723 /*
1724 * Run the plan. For safety we force a current snapshot to be used. (In
1725 * transaction-snapshot mode, this arguably violates transaction isolation
1726 * rules, but we really haven't got much choice.) We don't need to
1727 * register the snapshot, because SPI_execute_snapshot will see to it. We
1728 * need at most one tuple returned, so pass limit = 1.
1729 */
1731 NULL, NULL,
1734 true, false, 1);
1735
1736 /* Check result */
1738 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1739
1740 /* Did we find a tuple violating the constraint? */
1741 if (SPI_processed > 0)
1742 {
1743 TupleTableSlot *slot;
1744 HeapTuple tuple = SPI_tuptable->vals[0];
1745 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1747
1748 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1749
1750 heap_deform_tuple(tuple, tupdesc,
1751 slot->tts_values, slot->tts_isnull);
1753
1754 /*
1755 * The columns to look at in the result tuple are 1..N, not whatever
1756 * they are in the fk_rel. Hack up riinfo so that the subroutines
1757 * called here will behave properly.
1758 *
1759 * In addition to this, we have to pass the correct tupdesc to
1760 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1761 * or fk_rel's tupdesc.
1762 */
1764 for (int i = 0; i < fake_riinfo.nkeys; i++)
1765 fake_riinfo.fk_attnums[i] = i + 1;
1766
1767 /*
1768 * If it's MATCH FULL, and there are any nulls in the FK keys,
1769 * complain about that rather than the lack of a match. MATCH FULL
1770 * disallows partially-null FK rows.
1771 */
1772 if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1773 ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1774 ereport(ERROR,
1776 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1778 NameStr(fake_riinfo.conname)),
1779 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1781 NameStr(fake_riinfo.conname))));
1782
1783 /*
1784 * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1785 * query, which isn't true, but will cause it to use
1786 * fake_riinfo.fk_attnums as we need.
1787 */
1789 pk_rel, fk_rel,
1790 slot, tupdesc,
1791 RI_PLAN_CHECK_LOOKUPPK, false, false);
1792
1794 }
1795
1796 if (SPI_finish() != SPI_OK_FINISH)
1797 elog(ERROR, "SPI_finish failed");
1798
1799 /*
1800 * Restore work_mem and hash_mem_multiplier.
1801 */
1802 AtEOXact_GUC(true, save_nestlevel);
1803
1804 return true;
1805}
bool has_bypassrls_privilege(Oid roleid)
Definition aclchk.c:4206
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4108
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition execMain.c:582
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
int maintenance_work_mem
Definition globals.c:133
int NewGUCNestLevel(void)
Definition guc.c:2110
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2137
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition guc.c:3216
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_USERSET
Definition guc.h:79
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition heaptuple.c:1346
List * lappend(List *list, void *datum)
Definition list.c:339
#define AccessShareLock
Definition lockdefs.h:36
Oid GetUserId(void)
Definition miscinit.c:469
#define makeNode(_type_)
Definition nodes.h:161
@ RTE_RELATION
#define ACL_SELECT
Definition parsenodes.h:77
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define snprintf
Definition port.h:260
static pg_noreturn void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
#define RIAttCollation(rel, attnum)
Definition ri_triggers.c:88
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
#define InvalidSnapshot
Definition snapshot.h:119
uint64 SPI_processed
Definition spi.c:44
const char * SPI_result_code_string(int code)
Definition spi.c:1972
SPITupleTable * SPI_tuptable
Definition spi.c:45
int SPI_result
Definition spi.c:46
int SPI_execute_snapshot(SPIPlanPtr plan, const Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition spi.c:773
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition spi.c:860
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
Definition pg_list.h:54
TupleDesc tupdesc
Definition spi.h:25
HeapTuple * vals
Definition spi.h:26
bool * tts_isnull
Definition tuptable.h:126
Datum * tts_values
Definition tuptable.h:124
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References AccessShareLock, ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecCheckPermissions(), ExecDropSingleTupleTableSlot(), ExecStoreVirtualTuple(), fb(), FirstLowInvalidHeapAttributeNumber, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_bypassrls_privilege(), heap_deform_tuple(), i, initStringInfo(), InvalidSnapshot, lappend(), list_length(), maintenance_work_mem, makeNode, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, NewGUCNestLevel(), NIL, object_ownercheck(), PGC_S_SESSION, PGC_USERSET, quoteOneName(), quoteRelationName(), RelationGetRelationName, RelationGetRelid, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_KEYS_NONE_NULL, ri_NullCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, RTE_RELATION, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by validateForeignKeyConstraint().

◆ ri_KeysEqual()

static bool ri_KeysEqual ( Relation  rel,
TupleTableSlot oldslot,
TupleTableSlot newslot,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 2987 of file ri_triggers.c.

2989{
2990 const int16 *attnums;
2991
2992 if (rel_is_pk)
2993 attnums = riinfo->pk_attnums;
2994 else
2995 attnums = riinfo->fk_attnums;
2996
2997 /* XXX: could be worthwhile to fetch all necessary attrs at once */
2998 for (int i = 0; i < riinfo->nkeys; i++)
2999 {
3002 bool isnull;
3003
3004 /*
3005 * Get one attribute's oldvalue. If it is NULL - they're not equal.
3006 */
3007 oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3008 if (isnull)
3009 return false;
3010
3011 /*
3012 * Get one attribute's newvalue. If it is NULL - they're not equal.
3013 */
3014 newvalue = slot_getattr(newslot, attnums[i], &isnull);
3015 if (isnull)
3016 return false;
3017
3018 if (rel_is_pk)
3019 {
3020 /*
3021 * If we are looking at the PK table, then do a bytewise
3022 * comparison. We must propagate PK changes if the value is
3023 * changed to one that "looks" different but would compare as
3024 * equal using the equality operator. This only makes a
3025 * difference for ON UPDATE CASCADE, but for consistency we treat
3026 * all changes to the PK the same.
3027 */
3028 CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3029
3030 if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3031 return false;
3032 }
3033 else
3034 {
3035 Oid eq_opr;
3036
3037 /*
3038 * When comparing the PERIOD columns we can skip the check
3039 * whenever the referencing column stayed equal or shrank, so test
3040 * with the contained-by operator instead.
3041 */
3042 if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3043 eq_opr = riinfo->period_contained_by_oper;
3044 else
3045 eq_opr = riinfo->ff_eq_oprs[i];
3046
3047 /*
3048 * For the FK table, compare with the appropriate equality
3049 * operator. Changes that compare equal will still satisfy the
3050 * constraint after the update.
3051 */
3052 if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3054 return false;
3055 }
3056 }
3057
3058 return true;
3059}
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition datum.c:266
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:175

References datum_image_eq(), fb(), i, ri_CompareWithCast(), RIAttCollation, RIAttType, slot_getattr(), and TupleDescCompactAttr().

Referenced by RI_FKey_fk_upd_check_required(), and RI_FKey_pk_upd_check_required().

◆ ri_LoadConstraintInfo()

static const RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2269 of file ri_triggers.c.

2270{
2272 bool found;
2273 HeapTuple tup;
2275
2276 /*
2277 * On the first call initialize the hashtable
2278 */
2281
2282 /*
2283 * Find or create a hash entry. If we find a valid one, just return it.
2284 */
2287 HASH_ENTER, &found);
2288 if (!found)
2289 riinfo->valid = false;
2290 else if (riinfo->valid)
2291 return riinfo;
2292
2293 /*
2294 * Fetch the pg_constraint row so we can fill in the entry.
2295 */
2297 if (!HeapTupleIsValid(tup)) /* should not happen */
2298 elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2300
2301 if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2302 elog(ERROR, "constraint %u is not a foreign key constraint",
2304
2305 /* And extract data */
2306 Assert(riinfo->constraint_id == constraintOid);
2307 if (OidIsValid(conForm->conparentid))
2308 riinfo->constraint_root_id =
2309 get_ri_constraint_root(conForm->conparentid);
2310 else
2311 riinfo->constraint_root_id = constraintOid;
2312 riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2314 riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2315 ObjectIdGetDatum(riinfo->constraint_root_id));
2316 memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2317 riinfo->pk_relid = conForm->confrelid;
2318 riinfo->fk_relid = conForm->conrelid;
2319 riinfo->confupdtype = conForm->confupdtype;
2320 riinfo->confdeltype = conForm->confdeltype;
2321 riinfo->confmatchtype = conForm->confmatchtype;
2322 riinfo->hasperiod = conForm->conperiod;
2323
2325 &riinfo->nkeys,
2326 riinfo->fk_attnums,
2327 riinfo->pk_attnums,
2328 riinfo->pf_eq_oprs,
2329 riinfo->pp_eq_oprs,
2330 riinfo->ff_eq_oprs,
2331 &riinfo->ndelsetcols,
2332 riinfo->confdelsetcols);
2333
2334 /*
2335 * For temporal FKs, get the operators and functions we need. We ask the
2336 * opclass of the PK element for these. This all gets cached (as does the
2337 * generated plan), so there's no performance issue.
2338 */
2339 if (riinfo->hasperiod)
2340 {
2341 Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2342
2343 FindFKPeriodOpers(opclass,
2344 &riinfo->period_contained_by_oper,
2345 &riinfo->agged_period_contained_by_oper,
2346 &riinfo->period_intersect_oper);
2347 }
2348
2350
2351 /*
2352 * For efficient processing of invalidation messages below, we keep a
2353 * doubly-linked count list of all currently valid entries.
2354 */
2356
2357 riinfo->valid = true;
2358
2359 return riinfo;
2360}
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition ilist.h:709
Oid get_index_column_opclass(Oid index_oid, int attno)
Definition lsyscache.c:3664
void FindFKPeriodOpers(Oid opclass, Oid *containedbyoperoid, Oid *aggedcontainedbyoperoid, Oid *intersectoperoid)
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
static Oid get_ri_constraint_root(Oid constrOid)
Definition c.h:772
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118

References Assert, dclist_push_tail(), DeconstructFkConstraintRow(), elog, ERROR, fb(), FindFKPeriodOpers(), Form_pg_constraint, get_index_column_opclass(), get_ri_constraint_root(), GETSTRUCT(), GetSysCacheHashValue1, HASH_ENTER, hash_search(), HeapTupleIsValid, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), ri_constraint_cache, ri_constraint_cache_valid_list, ri_InitHashTables(), and SearchSysCache1().

Referenced by ri_FetchConstraintInfo().

◆ ri_NullCheck()

static int ri_NullCheck ( TupleDesc  tupDesc,
TupleTableSlot slot,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 2825 of file ri_triggers.c.

2828{
2829 const int16 *attnums;
2830 bool allnull = true;
2831 bool nonenull = true;
2832
2833 if (rel_is_pk)
2834 attnums = riinfo->pk_attnums;
2835 else
2836 attnums = riinfo->fk_attnums;
2837
2838 for (int i = 0; i < riinfo->nkeys; i++)
2839 {
2840 if (slot_attisnull(slot, attnums[i]))
2841 nonenull = false;
2842 else
2843 allnull = false;
2844 }
2845
2846 if (allnull)
2847 return RI_KEYS_ALL_NULL;
2848
2849 if (nonenull)
2850 return RI_KEYS_NONE_NULL;
2851
2852 return RI_KEYS_SOME_NULL;
2853}
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:384

References fb(), i, RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, and slot_attisnull().

Referenced by ri_Check_Pk_Match(), RI_FKey_check(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), and RI_Initial_Check().

◆ RI_PartitionRemove_Check()

void RI_PartitionRemove_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 1814 of file ri_triggers.c.

1815{
1818 char *constraintDef;
1823 const char *sep;
1824 const char *fk_only;
1825 int save_nestlevel;
1826 char workmembuf[32];
1827 int spi_result;
1829 int i;
1830
1832
1833 /*
1834 * We don't check permissions before displaying the error message, on the
1835 * assumption that the user detaching the partition must have enough
1836 * privileges to examine the table contents anyhow.
1837 */
1838
1839 /*----------
1840 * The query string built is:
1841 * SELECT fk.keycols FROM [ONLY] relname fk
1842 * JOIN pkrelname pk
1843 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1844 * WHERE (<partition constraint>) AND
1845 * For MATCH SIMPLE:
1846 * (fk.keycol1 IS NOT NULL [AND ...])
1847 * For MATCH FULL:
1848 * (fk.keycol1 IS NOT NULL [OR ...])
1849 *
1850 * We attach COLLATE clauses to the operators when comparing columns
1851 * that have different collations.
1852 *----------
1853 */
1855 appendStringInfoString(&querybuf, "SELECT ");
1856 sep = "";
1857 for (i = 0; i < riinfo->nkeys; i++)
1858 {
1860 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1861 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1862 sep = ", ";
1863 }
1864
1867 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1868 "" : "ONLY ";
1870 " FROM %s%s fk JOIN %s pk ON",
1872 strcpy(pkattname, "pk.");
1873 strcpy(fkattname, "fk.");
1874 sep = "(";
1875 for (i = 0; i < riinfo->nkeys; i++)
1876 {
1877 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1878 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1879 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1880 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1881
1883 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1885 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1888 riinfo->pf_eq_oprs[i],
1890 if (pk_coll != fk_coll)
1892 sep = "AND";
1893 }
1894
1895 /*
1896 * Start the WHERE clause with the partition constraint (except if this is
1897 * the default partition and there's no other partition, because the
1898 * partition constraint is the empty string in that case.)
1899 */
1901 if (constraintDef && constraintDef[0] != '\0')
1902 appendStringInfo(&querybuf, ") WHERE %s AND (",
1904 else
1905 appendStringInfoString(&querybuf, ") WHERE (");
1906
1907 sep = "";
1908 for (i = 0; i < riinfo->nkeys; i++)
1909 {
1910 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1912 "%sfk.%s IS NOT NULL",
1913 sep, fkattname);
1914 switch (riinfo->confmatchtype)
1915 {
1917 sep = " AND ";
1918 break;
1920 sep = " OR ";
1921 break;
1922 }
1923 }
1925
1926 /*
1927 * Temporarily increase work_mem so that the check query can be executed
1928 * more efficiently. It seems okay to do this because the query is simple
1929 * enough to not use a multiple of work_mem, and one typically would not
1930 * have many large foreign-key validations happening concurrently. So
1931 * this seems to meet the criteria for being considered a "maintenance"
1932 * operation, and accordingly we use maintenance_work_mem. However, we
1933 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1934 * let that get applied to the maintenance_work_mem value.
1935 *
1936 * We use the equivalent of a function SET option to allow the setting to
1937 * persist for exactly the duration of the check query. guc.c also takes
1938 * care of undoing the setting on error.
1939 */
1940 save_nestlevel = NewGUCNestLevel();
1941
1943 (void) set_config_option("work_mem", workmembuf,
1945 GUC_ACTION_SAVE, true, 0, false);
1946 (void) set_config_option("hash_mem_multiplier", "1",
1948 GUC_ACTION_SAVE, true, 0, false);
1949
1950 SPI_connect();
1951
1952 /*
1953 * Generate the plan. We don't need to cache it, and there are no
1954 * arguments to the plan.
1955 */
1956 qplan = SPI_prepare(querybuf.data, 0, NULL);
1957
1958 if (qplan == NULL)
1959 elog(ERROR, "SPI_prepare returned %s for %s",
1961
1962 /*
1963 * Run the plan. For safety we force a current snapshot to be used. (In
1964 * transaction-snapshot mode, this arguably violates transaction isolation
1965 * rules, but we really haven't got much choice.) We don't need to
1966 * register the snapshot, because SPI_execute_snapshot will see to it. We
1967 * need at most one tuple returned, so pass limit = 1.
1968 */
1970 NULL, NULL,
1973 true, false, 1);
1974
1975 /* Check result */
1977 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1978
1979 /* Did we find a tuple that would violate the constraint? */
1980 if (SPI_processed > 0)
1981 {
1982 TupleTableSlot *slot;
1983 HeapTuple tuple = SPI_tuptable->vals[0];
1984 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1986
1987 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1988
1989 heap_deform_tuple(tuple, tupdesc,
1990 slot->tts_values, slot->tts_isnull);
1992
1993 /*
1994 * The columns to look at in the result tuple are 1..N, not whatever
1995 * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1996 * will behave properly.
1997 *
1998 * In addition to this, we have to pass the correct tupdesc to
1999 * ri_ReportViolation, overriding its normal habit of using the pk_rel
2000 * or fk_rel's tupdesc.
2001 */
2003 for (i = 0; i < fake_riinfo.nkeys; i++)
2004 fake_riinfo.pk_attnums[i] = i + 1;
2005
2007 slot, tupdesc, 0, false, true);
2008 }
2009
2010 if (SPI_finish() != SPI_OK_FINISH)
2011 elog(ERROR, "SPI_finish failed");
2012
2013 /*
2014 * Restore work_mem and hash_mem_multiplier.
2015 */
2016 AtEOXact_GUC(true, save_nestlevel);
2017}
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition ruleutils.c:2128

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), elog, ERROR, ExecStoreVirtualTuple(), fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GUC_ACTION_SAVE, heap_deform_tuple(), i, initStringInfo(), InvalidSnapshot, maintenance_work_mem, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NewGUCNestLevel(), pg_get_partconstrdef_string(), PGC_S_SESSION, PGC_USERSET, quoteOneName(), quoteRelationName(), RelationGetRelid, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by ATDetachCheckNoForeignKeyRefs().

◆ ri_PerformCheck()

static bool ri_PerformCheck ( const RI_ConstraintInfo riinfo,
RI_QueryKey qkey,
SPIPlanPtr  qplan,
Relation  fk_rel,
Relation  pk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot,
bool  is_restrict,
bool  detectNewRows,
int  expect_OK 
)
static

Definition at line 2486 of file ri_triggers.c.

2492{
2494 source_rel;
2495 bool source_is_pk;
2497 Snapshot crosscheck_snapshot;
2498 int limit;
2499 int spi_result;
2500 Oid save_userid;
2501 int save_sec_context;
2502 Datum vals[RI_MAX_NUMKEYS * 2];
2503 char nulls[RI_MAX_NUMKEYS * 2];
2504
2505 /*
2506 * Use the query type code to determine whether the query is run against
2507 * the PK or FK table; we'll do the check as that table's owner
2508 */
2509 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2510 query_rel = pk_rel;
2511 else
2512 query_rel = fk_rel;
2513
2514 /*
2515 * The values for the query are taken from the table on which the trigger
2516 * is called - it is normally the other one with respect to query_rel. An
2517 * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2518 * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2519 * need some less klugy way to determine this.
2520 */
2521 if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
2522 {
2524 source_is_pk = false;
2525 }
2526 else
2527 {
2529 source_is_pk = true;
2530 }
2531
2532 /* Extract the parameters to be passed into the query */
2533 if (newslot)
2534 {
2536 vals, nulls);
2537 if (oldslot)
2539 vals + riinfo->nkeys, nulls + riinfo->nkeys);
2540 }
2541 else
2542 {
2544 vals, nulls);
2545 }
2546
2547 /*
2548 * In READ COMMITTED mode, we just need to use an up-to-date regular
2549 * snapshot, and we will see all rows that could be interesting. But in
2550 * transaction-snapshot mode, we can't change the transaction snapshot. If
2551 * the caller passes detectNewRows == false then it's okay to do the query
2552 * with the transaction snapshot; otherwise we use a current snapshot, and
2553 * tell the executor to error out if it finds any rows under the current
2554 * snapshot that wouldn't be visible per the transaction snapshot. Note
2555 * that SPI_execute_snapshot will register the snapshots, so we don't need
2556 * to bother here.
2557 */
2559 {
2560 CommandCounterIncrement(); /* be sure all my own work is visible */
2562 crosscheck_snapshot = GetTransactionSnapshot();
2563 }
2564 else
2565 {
2566 /* the default SPI behavior is okay */
2568 crosscheck_snapshot = InvalidSnapshot;
2569 }
2570
2571 /*
2572 * If this is a select query (e.g., for a 'no action' or 'restrict'
2573 * trigger), we only need to see if there is a single row in the table,
2574 * matching the key. Otherwise, limit = 0 - because we want the query to
2575 * affect ALL the matching rows.
2576 */
2577 limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2578
2579 /* Switch to proper UID to perform check as */
2580 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2582 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2584
2585 /* Finally we can run the query. */
2587 vals, nulls,
2588 test_snapshot, crosscheck_snapshot,
2589 false, false, limit);
2590
2591 /* Restore UID and security context */
2592 SetUserIdAndSecContext(save_userid, save_sec_context);
2593
2594 /* Check result */
2595 if (spi_result < 0)
2596 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2597
2598 if (expect_OK >= 0 && spi_result != expect_OK)
2599 ereport(ERROR,
2601 errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2603 NameStr(riinfo->conname),
2605 errhint("This is most likely due to a rule having rewritten the query.")));
2606
2607 /* XXX wouldn't it be clearer to do this part at the caller? */
2608 if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
2610 (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
2612 pk_rel, fk_rel,
2614 NULL,
2615 qkey->constr_queryno, is_restrict, false);
2616
2617 return SPI_processed != 0;
2618}
#define false
#define SECURITY_NOFORCE_RLS
Definition miscadmin.h:320
#define SECURITY_LOCAL_USERID_CHANGE
Definition miscadmin.h:318
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:612
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:619
#define RelationGetForm(relation)
Definition rel.h:508
#define RI_PLAN_LAST_ON_PK
Definition ri_triggers.c:71
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void CommandCounterIncrement(void)
Definition xact.c:1101
#define IsolationUsesXactSnapshot()
Definition xact.h:52

References CommandCounterIncrement(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, fb(), GetLatestSnapshot(), GetTransactionSnapshot(), GetUserIdAndSecContext(), InvalidSnapshot, IsolationUsesXactSnapshot, NameStr, RelationGetForm, RelationGetRelationName, ri_ExtractValues(), RI_MAX_NUMKEYS, RI_PLAN_CHECK_LOOKUPPK, RI_PLAN_CHECK_LOOKUPPK_FROM_PK, RI_PLAN_LAST_ON_PK, ri_ReportViolation(), SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SPI_execute_snapshot(), SPI_OK_SELECT, SPI_processed, and SPI_result_code_string().

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_restrict(), and ri_set().

◆ ri_PlanCheck()

static SPIPlanPtr ri_PlanCheck ( const char querystr,
int  nargs,
Oid argtypes,
RI_QueryKey qkey,
Relation  fk_rel,
Relation  pk_rel 
)
static

Definition at line 2443 of file ri_triggers.c.

2445{
2448 Oid save_userid;
2449 int save_sec_context;
2450
2451 /*
2452 * Use the query type code to determine whether the query is run against
2453 * the PK or FK table; we'll do the check as that table's owner
2454 */
2455 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2456 query_rel = pk_rel;
2457 else
2458 query_rel = fk_rel;
2459
2460 /* Switch to proper UID to perform check as */
2461 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2463 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2465
2466 /* Create the plan */
2467 qplan = SPI_prepare(querystr, nargs, argtypes);
2468
2469 if (qplan == NULL)
2470 elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2471
2472 /* Restore UID and security context */
2473 SetUserIdAndSecContext(save_userid, save_sec_context);
2474
2475 /* Save the plan */
2478
2479 return qplan;
2480}
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
int SPI_keepplan(SPIPlanPtr plan)
Definition spi.c:976

References elog, ERROR, fb(), GetUserIdAndSecContext(), RelationGetForm, ri_HashPreparedPlan(), RI_PLAN_LAST_ON_PK, SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SPI_keepplan(), SPI_prepare(), SPI_result, and SPI_result_code_string().

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_restrict(), and ri_set().

◆ ri_ReportViolation()

static void ri_ReportViolation ( const RI_ConstraintInfo riinfo,
Relation  pk_rel,
Relation  fk_rel,
TupleTableSlot violatorslot,
TupleDesc  tupdesc,
int  queryno,
bool  is_restrict,
bool  partgone 
)
static

Definition at line 2653 of file ri_triggers.c.

2657{
2660 bool onfk;
2661 const int16 *attnums;
2662 Oid rel_oid;
2664 bool has_perm = true;
2665
2666 /*
2667 * Determine which relation to complain about. If tupdesc wasn't passed
2668 * by caller, assume the violator tuple came from there.
2669 */
2671 if (onfk)
2672 {
2673 attnums = riinfo->fk_attnums;
2674 rel_oid = fk_rel->rd_id;
2675 if (tupdesc == NULL)
2676 tupdesc = fk_rel->rd_att;
2677 }
2678 else
2679 {
2680 attnums = riinfo->pk_attnums;
2681 rel_oid = pk_rel->rd_id;
2682 if (tupdesc == NULL)
2683 tupdesc = pk_rel->rd_att;
2684 }
2685
2686 /*
2687 * Check permissions- if the user does not have access to view the data in
2688 * any of the key columns then we don't include the errdetail() below.
2689 *
2690 * Check if RLS is enabled on the relation first. If so, we don't return
2691 * any specifics to avoid leaking data.
2692 *
2693 * Check table-level permissions next and, failing that, column-level
2694 * privileges.
2695 *
2696 * When a partition at the referenced side is being detached/dropped, we
2697 * needn't check, since the user must be the table owner anyway.
2698 */
2699 if (partgone)
2700 has_perm = true;
2701 else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2702 {
2704 if (aclresult != ACLCHECK_OK)
2705 {
2706 /* Try for column-level permissions */
2707 for (int idx = 0; idx < riinfo->nkeys; idx++)
2708 {
2710 GetUserId(),
2711 ACL_SELECT);
2712
2713 /* No access to the key */
2714 if (aclresult != ACLCHECK_OK)
2715 {
2716 has_perm = false;
2717 break;
2718 }
2719 }
2720 }
2721 }
2722 else
2723 has_perm = false;
2724
2725 if (has_perm)
2726 {
2727 /* Get printable versions of the keys involved */
2730 for (int idx = 0; idx < riinfo->nkeys; idx++)
2731 {
2732 int fnum = attnums[idx];
2733 Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2734 char *name,
2735 *val;
2736 Datum datum;
2737 bool isnull;
2738
2739 name = NameStr(att->attname);
2740
2741 datum = slot_getattr(violatorslot, fnum, &isnull);
2742 if (!isnull)
2743 {
2744 Oid foutoid;
2745 bool typisvarlena;
2746
2747 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2749 }
2750 else
2751 val = "null";
2752
2753 if (idx > 0)
2754 {
2757 }
2760 }
2761 }
2762
2763 if (partgone)
2764 ereport(ERROR,
2766 errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2768 NameStr(riinfo->conname)),
2769 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2770 key_names.data, key_values.data,
2773 else if (onfk)
2774 ereport(ERROR,
2776 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2778 NameStr(riinfo->conname)),
2779 has_perm ?
2780 errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2781 key_names.data, key_values.data,
2783 errdetail("Key is not present in table \"%s\".",
2786 else if (is_restrict)
2787 ereport(ERROR,
2789 errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
2791 NameStr(riinfo->conname),
2793 has_perm ?
2794 errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
2795 key_names.data, key_values.data,
2797 errdetail("Key is referenced from table \"%s\".",
2800 else
2801 ereport(ERROR,
2803 errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2805 NameStr(riinfo->conname),
2807 has_perm ?
2808 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2809 key_names.data, key_values.data,
2811 errdetail("Key is still referenced from table \"%s\".",
2814}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:262
AclResult
Definition acl.h:182
@ ACLCHECK_OK
Definition acl.h:183
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition aclchk.c:3886
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4057
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition fmgr.c:1763
long val
Definition informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3059
FormData_pg_attribute * Form_pg_attribute
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition rls.c:52
@ RLS_ENABLED
Definition rls.h:45
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:160

References ACL_SELECT, ACLCHECK_OK, appendStringInfoString(), check_enable_rls(), ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), fb(), getTypeOutputInfo(), GetUserId(), idx(), initStringInfo(), InvalidOid, name, NameStr, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), RelationGetRelationName, RI_PLAN_CHECK_LOOKUPPK, RLS_ENABLED, slot_getattr(), TupleDescAttr(), and val.

Referenced by RI_Initial_Check(), RI_PartitionRemove_Check(), and ri_PerformCheck().

◆ ri_restrict()

static Datum ri_restrict ( TriggerData trigdata,
bool  is_no_action 
)
static

Definition at line 713 of file ri_triggers.c.

714{
721
723 trigdata->tg_relation, true);
724
725 /*
726 * Get the relation descriptors of the FK and PK tables and the old tuple.
727 *
728 * fk_rel is opened in RowShareLock mode since that's what our eventual
729 * SELECT FOR KEY SHARE will get on it.
730 */
731 fk_rel = table_open(riinfo->fk_relid, RowShareLock);
732 pk_rel = trigdata->tg_relation;
733 oldslot = trigdata->tg_trigslot;
734
735 /*
736 * If another PK row now exists providing the old key values, we should
737 * not do anything. However, this check should only be made in the NO
738 * ACTION case; in RESTRICT cases we don't wish to allow another row to be
739 * substituted.
740 *
741 * If the foreign key has PERIOD, we incorporate looking for replacement
742 * rows in the main SQL query below, so we needn't do it here.
743 */
744 if (is_no_action && !riinfo->hasperiod &&
746 {
748 return PointerGetDatum(NULL);
749 }
750
751 SPI_connect();
752
753 /*
754 * Fetch or prepare a saved plan for the restrict lookup (it's the same
755 * query for delete and update cases)
756 */
758
759 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
760 {
766 char paramname[16];
767 const char *querysep;
769 const char *fk_only;
770
771 /* ----------
772 * The query string built is
773 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
774 * FOR KEY SHARE OF x
775 * The type id's for the $ parameters are those of the
776 * corresponding PK attributes.
777 * ----------
778 */
780 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
781 "" : "ONLY ";
783 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
785 querysep = "WHERE";
786 for (int i = 0; i < riinfo->nkeys; i++)
787 {
788 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
789 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
790
792 RIAttName(fk_rel, riinfo->fk_attnums[i]));
793 sprintf(paramname, "$%d", i + 1);
796 riinfo->pf_eq_oprs[i],
798 querysep = "AND";
800 }
801
802 /*----------
803 * For temporal foreign keys, a reference could still be valid if the
804 * referenced range didn't change too much. Also if a referencing
805 * range extends past the current PK row, we don't want to check that
806 * part: some other PK row should fulfill it. We only want to check
807 * the part matching the PK record we've changed. Therefore to find
808 * invalid records we do this:
809 *
810 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
811 * -- begin temporal
812 * AND $n && x.fkperiod
813 * AND NOT coalesce((x.fkperiod * $n) <@
814 * (SELECT range_agg(r)
815 * FROM (SELECT y.pkperiod r
816 * FROM [ONLY] <pktable> y
817 * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
818 * FOR KEY SHARE OF y) y2), false)
819 * -- end temporal
820 * FOR KEY SHARE OF x
821 *
822 * We need the coalesce in case the first subquery returns no rows.
823 * We need the second subquery because FOR KEY SHARE doesn't support
824 * aggregate queries.
825 */
826 if (riinfo->hasperiod && is_no_action)
827 {
828 Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
829 Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
832 char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
833 "" : "ONLY ";
834
835 quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
836 sprintf(paramname, "$%d", riinfo->nkeys);
837
838 appendStringInfoString(&querybuf, " AND NOT coalesce(");
839
840 /* Intersect the fk with the old pk range */
845 riinfo->period_intersect_oper,
848
849 /* Find the remaining history */
851 appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
852
853 quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
855 appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
857
858 /* Restrict pk rows to what matches */
859 querysep = "WHERE";
860 for (int i = 0; i < riinfo->nkeys; i++)
861 {
862 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
863
865 RIAttName(pk_rel, riinfo->pk_attnums[i]));
866 sprintf(paramname, "$%d", i + 1);
869 riinfo->pp_eq_oprs[i],
871 querysep = "AND";
873 }
874 appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
875
878 riinfo->agged_period_contained_by_oper,
880 /* end of coalesce: */
881 appendStringInfoString(&querybuf, ", false)");
882 }
883
884 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
885
886 /* Prepare and save the plan */
888 &qkey, fk_rel, pk_rel);
889 }
890
891 /*
892 * We have a plan now. Run it to check for existing references.
893 */
895 fk_rel, pk_rel,
896 oldslot, NULL,
898 true, /* must detect new rows */
900
901 if (SPI_finish() != SPI_OK_FINISH)
902 elog(ERROR, "SPI_finish failed");
903
905
906 return PointerGetDatum(NULL);
907}
#define RI_PLAN_RESTRICT
Definition ri_triggers.c:77
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
#define RI_PLAN_NO_ACTION
Definition ri_triggers.c:75

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum(), quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_NO_ACTION, RI_PLAN_RESTRICT, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

Referenced by RI_FKey_noaction_del(), RI_FKey_noaction_upd(), RI_FKey_restrict_del(), RI_FKey_restrict_upd(), and ri_set().

◆ ri_set()

static Datum ri_set ( TriggerData trigdata,
bool  is_set_null,
int  tgkind 
)
static

Definition at line 1196 of file ri_triggers.c.

1197{
1204 int32 queryno;
1205
1207 trigdata->tg_relation, true);
1208
1209 /*
1210 * Get the relation descriptors of the FK and PK tables and the old tuple.
1211 *
1212 * fk_rel is opened in RowExclusiveLock mode since that's what our
1213 * eventual UPDATE will get on it.
1214 */
1216 pk_rel = trigdata->tg_relation;
1217 oldslot = trigdata->tg_trigslot;
1218
1219 SPI_connect();
1220
1221 /*
1222 * Fetch or prepare a saved plan for the trigger.
1223 */
1224 switch (tgkind)
1225 {
1226 case RI_TRIGTYPE_UPDATE:
1230 break;
1231 case RI_TRIGTYPE_DELETE:
1235 break;
1236 default:
1237 elog(ERROR, "invalid tgkind passed to ri_set");
1238 }
1239
1241
1242 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1243 {
1247 char paramname[16];
1248 const char *querysep;
1249 const char *qualsep;
1251 const char *fk_only;
1252 int num_cols_to_set;
1253 const int16 *set_cols;
1254
1255 switch (tgkind)
1256 {
1257 case RI_TRIGTYPE_UPDATE:
1258 num_cols_to_set = riinfo->nkeys;
1259 set_cols = riinfo->fk_attnums;
1260 break;
1261 case RI_TRIGTYPE_DELETE:
1262
1263 /*
1264 * If confdelsetcols are present, then we only update the
1265 * columns specified in that array, otherwise we update all
1266 * the referencing columns.
1267 */
1268 if (riinfo->ndelsetcols != 0)
1269 {
1270 num_cols_to_set = riinfo->ndelsetcols;
1271 set_cols = riinfo->confdelsetcols;
1272 }
1273 else
1274 {
1275 num_cols_to_set = riinfo->nkeys;
1276 set_cols = riinfo->fk_attnums;
1277 }
1278 break;
1279 default:
1280 elog(ERROR, "invalid tgkind passed to ri_set");
1281 }
1282
1283 /* ----------
1284 * The query string built is
1285 * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1286 * WHERE $1 = fkatt1 [AND ...]
1287 * The type id's for the $ parameters are those of the
1288 * corresponding PK attributes.
1289 * ----------
1290 */
1292 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1293 "" : "ONLY ";
1295 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1297
1298 /*
1299 * Add assignment clauses
1300 */
1301 querysep = "";
1302 for (int i = 0; i < num_cols_to_set; i++)
1303 {
1306 "%s %s = %s",
1308 is_set_null ? "NULL" : "DEFAULT");
1309 querysep = ",";
1310 }
1311
1312 /*
1313 * Add WHERE clause
1314 */
1315 qualsep = "WHERE";
1316 for (int i = 0; i < riinfo->nkeys; i++)
1317 {
1318 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1319 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1320
1322 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1323
1324 sprintf(paramname, "$%d", i + 1);
1327 riinfo->pf_eq_oprs[i],
1328 attname, fk_type);
1329 qualsep = "AND";
1330 queryoids[i] = pk_type;
1331 }
1332
1333 /* Prepare and save the plan */
1334 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1335 &qkey, fk_rel, pk_rel);
1336 }
1337
1338 /*
1339 * We have a plan now. Run it to update the existing references.
1340 */
1342 fk_rel, pk_rel,
1343 oldslot, NULL,
1344 false,
1345 true, /* must detect new rows */
1347
1348 if (SPI_finish() != SPI_OK_FINISH)
1349 elog(ERROR, "SPI_finish failed");
1350
1352
1353 if (is_set_null)
1354 return PointerGetDatum(NULL);
1355 else
1356 {
1357 /*
1358 * If we just deleted or updated the PK row whose key was equal to the
1359 * FK columns' default values, and a referencing row exists in the FK
1360 * table, we would have updated that row to the same values it already
1361 * had --- and RI_FKey_fk_upd_check_required would hence believe no
1362 * check is necessary. So we need to do another lookup now and in
1363 * case a reference still exists, abort the operation. That is
1364 * already implemented in the NO ACTION trigger, so just run it. (This
1365 * recheck is only needed in the SET DEFAULT case, since CASCADE would
1366 * remove such rows in case of a DELETE operation or would change the
1367 * FK key values in case of an UPDATE, while SET NULL is certain to
1368 * result in rows that satisfy the FK constraint.)
1369 */
1370 return ri_restrict(trigdata, true);
1371 }
1372}
int32_t int32
Definition c.h:554
#define RI_PLAN_SETNULL_ONUPDATE
Definition ri_triggers.c:79
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition ri_triggers.c:80
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition ri_triggers.c:81
#define RI_PLAN_SETNULL_ONDELETE
Definition ri_triggers.c:78

References appendStringInfo(), attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum(), quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_SETDEFAULT_ONDELETE, RI_PLAN_SETDEFAULT_ONUPDATE, RI_PLAN_SETNULL_ONDELETE, RI_PLAN_SETNULL_ONUPDATE, ri_PlanCheck(), ri_restrict(), RI_TRIGTYPE_DELETE, RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_UPDATE, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

Referenced by RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), and RI_FKey_setnull_upd().

Variable Documentation

◆ ri_compare_cache

HTAB* ri_compare_cache = NULL
static

Definition at line 185 of file ri_triggers.c.

Referenced by ri_HashCompareOp(), and ri_InitHashTables().

◆ ri_constraint_cache

HTAB* ri_constraint_cache = NULL
static

◆ ri_constraint_cache_valid_list

dclist_head ri_constraint_cache_valid_list
static

Definition at line 186 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 184 of file ri_triggers.c.

Referenced by ri_FetchPreparedPlan(), ri_HashPreparedPlan(), and ri_InitHashTables().