PostgreSQL Source Code  git master
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_RESTRICT   5
 
#define RI_PLAN_SETNULL_ONDELETE   6
 
#define RI_PLAN_SETNULL_ONUPDATE   7
 
#define RI_PLAN_SETDEFAULT_ONDELETE   8
 
#define RI_PLAN_SETDEFAULT_ONUPDATE   9
 
#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_AttributesEqual (Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
 
static void ri_InitHashTables (void)
 
static void InvalidateConstraintCacheCallBack (Datum arg, int 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 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 void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
 
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 82 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 83 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_RESTRICT

#define RI_PLAN_RESTRICT   5

Definition at line 76 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   8

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   9

Definition at line 80 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   6

Definition at line 77 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   7

Definition at line 78 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 91 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 89 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 90 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 87 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 85 of file ri_triggers.c.

◆ RIAttType

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

Definition at line 86 of file ri_triggers.c.

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

typedef struct RI_CompareKey RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

typedef struct RI_QueryKey RI_QueryKey

Function Documentation

◆ get_ri_constraint_root()

static Oid get_ri_constraint_root ( Oid  constrOid)
static

Definition at line 2194 of file ri_triggers.c.

2195 {
2196  for (;;)
2197  {
2198  HeapTuple tuple;
2199  Oid constrParentOid;
2200 
2201  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2202  if (!HeapTupleIsValid(tuple))
2203  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2204  constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2205  ReleaseSysCache(tuple);
2206  if (!OidIsValid(constrParentOid))
2207  break; /* we reached the root constraint */
2208  constrOid = constrParentOid;
2209  }
2210  return constrOid;
2211 }
#define OidIsValid(objectId)
Definition: c.h:775
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

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

Referenced by ri_LoadConstraintInfo().

◆ InvalidateConstraintCacheCallBack()

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

Definition at line 2228 of file ri_triggers.c.

2229 {
2230  dlist_mutable_iter iter;
2231 
2232  Assert(ri_constraint_cache != NULL);
2233 
2234  /*
2235  * If the list of currently valid entries gets excessively large, we mark
2236  * them all invalid so we can empty the list. This arrangement avoids
2237  * O(N^2) behavior in situations where a session touches many foreign keys
2238  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2239  */
2241  hashvalue = 0; /* pretend it's a cache reset */
2242 
2244  {
2246  valid_link, iter.cur);
2247 
2248  /*
2249  * We must invalidate not only entries directly matching the given
2250  * hash value, but also child entries, in case the invalidation
2251  * affects a root constraint.
2252  */
2253  if (hashvalue == 0 ||
2254  riinfo->oidHashValue == hashvalue ||
2255  riinfo->rootHashValue == hashvalue)
2256  {
2257  riinfo->valid = false;
2258  /* Remove invalidated entries from the list, too */
2260  }
2261  }
2262 }
#define Assert(condition)
Definition: c.h:858
#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
Definition: ri_triggers.c:176
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:173
dlist_node * cur
Definition: ilist.h:200

References Assert, dlist_mutable_iter::cur, dclist_container, dclist_count(), dclist_delete_from(), dclist_foreach_modify, RI_ConstraintInfo::oidHashValue, ri_constraint_cache, ri_constraint_cache_valid_list, RI_ConstraintInfo::rootHashValue, and RI_ConstraintInfo::valid.

Referenced by ri_InitHashTables().

◆ quoteOneName()

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

Definition at line 1873 of file ri_triggers.c.

1874 {
1875  /* Rather than trying to be smart, just always quote it. */
1876  *buffer++ = '"';
1877  while (*name)
1878  {
1879  if (*name == '"')
1880  *buffer++ = '"';
1881  *buffer++ = *name++;
1882  }
1883  *buffer++ = '"';
1884  *buffer = '\0';
1885 }
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 1893 of file ri_triggers.c.

1894 {
1896  buffer += strlen(buffer);
1897  *buffer++ = '.';
1898  quoteOneName(buffer, RelationGetRelationName(rel));
1899 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1873

References 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_AttributesEqual()

static bool ri_AttributesEqual ( Oid  eq_opr,
Oid  typeid,
Datum  oldvalue,
Datum  newvalue 
)
static

Definition at line 2866 of file ri_triggers.c.

2868 {
2869  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
2870 
2871  /* Do we need to cast the values? */
2872  if (OidIsValid(entry->cast_func_finfo.fn_oid))
2873  {
2874  oldvalue = FunctionCall3(&entry->cast_func_finfo,
2875  oldvalue,
2876  Int32GetDatum(-1), /* typmod */
2877  BoolGetDatum(false)); /* implicit coercion */
2878  newvalue = FunctionCall3(&entry->cast_func_finfo,
2879  newvalue,
2880  Int32GetDatum(-1), /* typmod */
2881  BoolGetDatum(false)); /* implicit coercion */
2882  }
2883 
2884  /*
2885  * Apply the comparison operator.
2886  *
2887  * Note: This function is part of a call stack that determines whether an
2888  * update to a row is significant enough that it needs checking or action
2889  * on the other side of a foreign-key constraint. Therefore, the
2890  * comparison here would need to be done with the collation of the *other*
2891  * table. For simplicity (e.g., we might not even have the other table
2892  * open), we'll just use the default collation here, which could lead to
2893  * some false negatives. All this would break if we ever allow
2894  * database-wide collations to be nondeterministic.
2895  */
2897  DEFAULT_COLLATION_OID,
2898  oldvalue, newvalue));
2899 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:664
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:2908
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:166

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

Referenced by ri_KeysEqual().

◆ ri_BuildQueryKey()

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

Definition at line 1980 of file ri_triggers.c.

1982 {
1983  /*
1984  * Inherited constraints with a common ancestor can share ri_query_cache
1985  * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
1986  * Except in that case, the query processes the other table involved in
1987  * the FK constraint (i.e., not the table on which the trigger has been
1988  * fired), and so it will be the same for all members of the inheritance
1989  * tree. So we may use the root constraint's OID in the hash key, rather
1990  * than the constraint's own OID. This avoids creating duplicate SPI
1991  * plans, saving lots of work and memory when there are many partitions
1992  * with similar FK constraints.
1993  *
1994  * (Note that we must still have a separate RI_ConstraintInfo for each
1995  * constraint, because partitions can have different column orders,
1996  * resulting in different pk_attnums[] or fk_attnums[] array contents.)
1997  *
1998  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
1999  * to use memset to clear them.
2000  */
2001  if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2002  key->constr_id = riinfo->constraint_root_id;
2003  else
2004  key->constr_id = riinfo->constraint_id;
2005  key->constr_queryno = constr_queryno;
2006 }
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:70

References RI_ConstraintInfo::constraint_id, RI_ConstraintInfo::constraint_root_id, sort-test::key, 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 461 of file ri_triggers.c.

464 {
465  SPIPlanPtr qplan;
466  RI_QueryKey qkey;
467  bool result;
468 
469  /* Only called for non-null rows */
470  Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
471 
472  if (SPI_connect() != SPI_OK_CONNECT)
473  elog(ERROR, "SPI_connect failed");
474 
475  /*
476  * Fetch or prepare a saved plan for checking PK table with values coming
477  * from a PK row
478  */
480 
481  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
482  {
483  StringInfoData querybuf;
484  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
486  char paramname[16];
487  const char *querysep;
488  const char *pk_only;
489  Oid queryoids[RI_MAX_NUMKEYS];
490 
491  /* ----------
492  * The query string built is
493  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
494  * FOR KEY SHARE OF x
495  * The type id's for the $ parameters are those of the
496  * PK attributes themselves.
497  * ----------
498  */
499  initStringInfo(&querybuf);
500  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
501  "" : "ONLY ";
502  quoteRelationName(pkrelname, pk_rel);
503  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
504  pk_only, pkrelname);
505  querysep = "WHERE";
506  for (int i = 0; i < riinfo->nkeys; i++)
507  {
508  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
509 
511  RIAttName(pk_rel, riinfo->pk_attnums[i]));
512  sprintf(paramname, "$%d", i + 1);
513  ri_GenerateQual(&querybuf, querysep,
514  attname, pk_type,
515  riinfo->pp_eq_oprs[i],
516  paramname, pk_type);
517  querysep = "AND";
518  queryoids[i] = pk_type;
519  }
520  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
521 
522  /* Prepare and save the plan */
523  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
524  &qkey, fk_rel, pk_rel);
525  }
526 
527  /*
528  * We have a plan now. Run it.
529  */
530  result = ri_PerformCheck(riinfo, &qkey, qplan,
531  fk_rel, pk_rel,
532  oldslot, NULL,
533  true, /* treat like update */
534  SPI_OK_SELECT);
535 
536  if (SPI_finish() != SPI_OK_FINISH)
537  elog(ERROR, "SPI_finish failed");
538 
539  return result;
540 }
int i
Definition: isn.c:73
NameData attname
Definition: pg_attribute.h:41
#define sprintf
Definition: port.h:240
#define RelationGetDescr(relation)
Definition: rel.h:531
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2312
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1893
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2636
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ri_triggers.c:1910
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:65
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1980
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2269
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:58
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2709
int SPI_connect(void)
Definition: spi.c:94
int SPI_finish(void)
Definition: spi.c:182
#define SPI_OK_CONNECT
Definition: spi.h:82
#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:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
Form_pg_class rd_rel
Definition: rel.h:111

References appendStringInfo(), appendStringInfoString(), Assert, attname, StringInfoData::data, elog, ERROR, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pp_eq_oprs, quoteOneName(), quoteRelationName(), RelationData::rd_rel, 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_CONNECT, 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 2012 of file ri_triggers.c.

2013 {
2014  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2015 
2016  if (!CALLED_AS_TRIGGER(fcinfo))
2017  ereport(ERROR,
2018  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2019  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2020 
2021  /*
2022  * Check proper event
2023  */
2024  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2025  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2026  ereport(ERROR,
2027  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2028  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2029 
2030  switch (tgkind)
2031  {
2032  case RI_TRIGTYPE_INSERT:
2033  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2034  ereport(ERROR,
2035  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2036  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2037  break;
2038  case RI_TRIGTYPE_UPDATE:
2039  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2040  ereport(ERROR,
2041  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2042  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2043  break;
2044  case RI_TRIGTYPE_DELETE:
2045  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2046  ereport(ERROR,
2047  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2048  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2049  break;
2050  }
2051 }
int errcode(int sqlerrcode)
Definition: elog.c:855
int errmsg(const char *fmt,...)
Definition: elog.c:1068
#define ereport(elevel,...)
Definition: elog.h:149
#define funcname
Definition: indent_codes.h:69
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:89
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90
fmNodePtr context
Definition: fmgr.h:88
TriggerEvent tg_event
Definition: trigger.h:34
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:113
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:122
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:131
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:110
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:116

References CALLED_AS_TRIGGER, FunctionCallInfoBaseData::context, ereport, errcode(), errmsg(), ERROR, funcname, if(), 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_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 2449 of file ri_triggers.c.

2452 {
2453  const int16 *attnums;
2454  bool isnull;
2455 
2456  if (rel_is_pk)
2457  attnums = riinfo->pk_attnums;
2458  else
2459  attnums = riinfo->fk_attnums;
2460 
2461  for (int i = 0; i < riinfo->nkeys; i++)
2462  {
2463  vals[i] = slot_getattr(slot, attnums[i], &isnull);
2464  nulls[i] = isnull ? 'n' : ' ';
2465  }
2466 }
signed short int16
Definition: c.h:493
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395

References RI_ConstraintInfo::fk_attnums, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, 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 2058 of file ri_triggers.c.

2059 {
2060  Oid constraintOid = trigger->tgconstraint;
2061  const RI_ConstraintInfo *riinfo;
2062 
2063  /*
2064  * Check that the FK constraint's OID is available; it might not be if
2065  * we've been invoked via an ordinary trigger or an old-style "constraint
2066  * trigger".
2067  */
2068  if (!OidIsValid(constraintOid))
2069  ereport(ERROR,
2070  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2071  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2072  trigger->tgname, RelationGetRelationName(trig_rel)),
2073  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2074 
2075  /* Find or create a hashtable entry for the constraint */
2076  riinfo = ri_LoadConstraintInfo(constraintOid);
2077 
2078  /* Do some easy cross-checks against the trigger call data */
2079  if (rel_is_pk)
2080  {
2081  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2082  riinfo->pk_relid != RelationGetRelid(trig_rel))
2083  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2084  trigger->tgname, RelationGetRelationName(trig_rel));
2085  }
2086  else
2087  {
2088  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2089  riinfo->pk_relid != trigger->tgconstrrelid)
2090  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2091  trigger->tgname, RelationGetRelationName(trig_rel));
2092  }
2093 
2094  if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2097  elog(ERROR, "unrecognized confmatchtype: %d",
2098  riinfo->confmatchtype);
2099 
2100  if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2101  ereport(ERROR,
2102  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2103  errmsg("MATCH PARTIAL not yet implemented")));
2104 
2105  return riinfo;
2106 }
int errhint(const char *fmt,...)
Definition: elog.c:1315
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2731
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2730
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2729
#define RelationGetRelid(relation)
Definition: rel.h:505
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2112
Oid tgconstraint
Definition: reltrigger.h:35
Oid tgconstrrelid
Definition: reltrigger.h:33
char * tgname
Definition: reltrigger.h:27

References RI_ConstraintInfo::confmatchtype, elog, ereport, errcode(), errhint(), errmsg(), ERROR, RI_ConstraintInfo::fk_relid, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, OidIsValid, RI_ConstraintInfo::pk_relid, RelationGetRelationName, RelationGetRelid, ri_LoadConstraintInfo(), Trigger::tgconstraint, Trigger::tgconstrrelid, and Trigger::tgname.

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 2709 of file ri_triggers.c.

2710 {
2711  RI_QueryHashEntry *entry;
2712  SPIPlanPtr plan;
2713 
2714  /*
2715  * On the first call initialize the hashtable
2716  */
2717  if (!ri_query_cache)
2719 
2720  /*
2721  * Lookup for the key
2722  */
2724  key,
2725  HASH_FIND, NULL);
2726  if (entry == NULL)
2727  return NULL;
2728 
2729  /*
2730  * Check whether the plan is still valid. If it isn't, we don't want to
2731  * simply rely on plancache.c to regenerate it; rather we should start
2732  * from scratch and rebuild the query text too. This is to cover cases
2733  * such as table/column renames. We depend on the plancache machinery to
2734  * detect possible invalidations, though.
2735  *
2736  * CAUTION: this check is only trustworthy if the caller has already
2737  * locked both FK and PK rels.
2738  */
2739  plan = entry->plan;
2740  if (plan && SPI_plan_is_valid(plan))
2741  return plan;
2742 
2743  /*
2744  * Otherwise we might as well flush the cached plan now, to free a little
2745  * memory space before we make a new one.
2746  */
2747  entry->plan = NULL;
2748  if (plan)
2749  SPI_freeplan(plan);
2750 
2751  return NULL;
2752 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
@ HASH_FIND
Definition: hsearch.h:113
#define plan(x)
Definition: pg_regress.c:162
static HTAB * ri_query_cache
Definition: ri_triggers.c:174
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2673
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1945
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:1022
SPIPlanPtr plan
Definition: ri_triggers.c:144

References HASH_FIND, hash_search(), sort-test::key, 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 743 of file ri_triggers.c.

744 {
745  TriggerData *trigdata = (TriggerData *) fcinfo->context;
746  const RI_ConstraintInfo *riinfo;
747  Relation fk_rel;
748  Relation pk_rel;
749  TupleTableSlot *oldslot;
750  RI_QueryKey qkey;
751  SPIPlanPtr qplan;
752 
753  /* Check that this is a valid trigger call on the right time and event. */
754  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
755 
756  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
757  trigdata->tg_relation, true);
758 
759  /*
760  * Get the relation descriptors of the FK and PK tables and the old tuple.
761  *
762  * fk_rel is opened in RowExclusiveLock mode since that's what our
763  * eventual DELETE will get on it.
764  */
765  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
766  pk_rel = trigdata->tg_relation;
767  oldslot = trigdata->tg_trigslot;
768 
769  if (SPI_connect() != SPI_OK_CONNECT)
770  elog(ERROR, "SPI_connect failed");
771 
772  /* Fetch or prepare a saved plan for the cascaded delete */
774 
775  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
776  {
777  StringInfoData querybuf;
778  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
780  char paramname[16];
781  const char *querysep;
782  Oid queryoids[RI_MAX_NUMKEYS];
783  const char *fk_only;
784 
785  /* ----------
786  * The query string built is
787  * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
788  * The type id's for the $ parameters are those of the
789  * corresponding PK attributes.
790  * ----------
791  */
792  initStringInfo(&querybuf);
793  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
794  "" : "ONLY ";
795  quoteRelationName(fkrelname, fk_rel);
796  appendStringInfo(&querybuf, "DELETE FROM %s%s",
797  fk_only, fkrelname);
798  querysep = "WHERE";
799  for (int i = 0; i < riinfo->nkeys; i++)
800  {
801  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
802  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
803  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
804  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
805 
807  RIAttName(fk_rel, riinfo->fk_attnums[i]));
808  sprintf(paramname, "$%d", i + 1);
809  ri_GenerateQual(&querybuf, querysep,
810  paramname, pk_type,
811  riinfo->pf_eq_oprs[i],
812  attname, fk_type);
813  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
814  ri_GenerateQualCollation(&querybuf, pk_coll);
815  querysep = "AND";
816  queryoids[i] = pk_type;
817  }
818 
819  /* Prepare and save the plan */
820  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
821  &qkey, fk_rel, pk_rel);
822  }
823 
824  /*
825  * We have a plan now. Build up the arguments from the key values in the
826  * deleted PK tuple and delete the referencing rows
827  */
828  ri_PerformCheck(riinfo, &qkey, qplan,
829  fk_rel, pk_rel,
830  oldslot, NULL,
831  true, /* must detect new rows */
832  SPI_OK_DELETE);
833 
834  if (SPI_finish() != SPI_OK_FINISH)
835  elog(ERROR, "SPI_finish failed");
836 
837  table_close(fk_rel, RowExclusiveLock);
838 
839  return PointerGetDatum(NULL);
840 }
#define RowExclusiveLock
Definition: lockdefs.h:38
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:1054
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1939
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2058
#define RI_PLAN_CASCADE_ONDELETE
Definition: ri_triggers.c:73
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2012
#define SPI_OK_DELETE
Definition: spi.h:89
Relation tg_relation
Definition: trigger.h:35
TupleTableSlot * tg_trigslot
Definition: trigger.h:39
Trigger * tg_trigger
Definition: trigger.h:38
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, StringInfoData::data, elog, ERROR, get_collation_isdeterministic(), 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_GenerateQualCollation(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONDELETE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttCollation, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, 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 849 of file ri_triggers.c.

850 {
851  TriggerData *trigdata = (TriggerData *) fcinfo->context;
852  const RI_ConstraintInfo *riinfo;
853  Relation fk_rel;
854  Relation pk_rel;
855  TupleTableSlot *newslot;
856  TupleTableSlot *oldslot;
857  RI_QueryKey qkey;
858  SPIPlanPtr qplan;
859 
860  /* Check that this is a valid trigger call on the right time and event. */
861  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
862 
863  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
864  trigdata->tg_relation, true);
865 
866  /*
867  * Get the relation descriptors of the FK and PK tables and the new and
868  * old tuple.
869  *
870  * fk_rel is opened in RowExclusiveLock mode since that's what our
871  * eventual UPDATE will get on it.
872  */
873  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
874  pk_rel = trigdata->tg_relation;
875  newslot = trigdata->tg_newslot;
876  oldslot = trigdata->tg_trigslot;
877 
878  if (SPI_connect() != SPI_OK_CONNECT)
879  elog(ERROR, "SPI_connect failed");
880 
881  /* Fetch or prepare a saved plan for the cascaded update */
883 
884  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
885  {
886  StringInfoData querybuf;
887  StringInfoData qualbuf;
888  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
890  char paramname[16];
891  const char *querysep;
892  const char *qualsep;
893  Oid queryoids[RI_MAX_NUMKEYS * 2];
894  const char *fk_only;
895 
896  /* ----------
897  * The query string built is
898  * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
899  * WHERE $n = fkatt1 [AND ...]
900  * The type id's for the $ parameters are those of the
901  * corresponding PK attributes. Note that we are assuming
902  * there is an assignment cast from the PK to the FK type;
903  * else the parser will fail.
904  * ----------
905  */
906  initStringInfo(&querybuf);
907  initStringInfo(&qualbuf);
908  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
909  "" : "ONLY ";
910  quoteRelationName(fkrelname, fk_rel);
911  appendStringInfo(&querybuf, "UPDATE %s%s SET",
912  fk_only, fkrelname);
913  querysep = "";
914  qualsep = "WHERE";
915  for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
916  {
917  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
918  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
919  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
920  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
921 
923  RIAttName(fk_rel, riinfo->fk_attnums[i]));
924  appendStringInfo(&querybuf,
925  "%s %s = $%d",
926  querysep, attname, i + 1);
927  sprintf(paramname, "$%d", j + 1);
928  ri_GenerateQual(&qualbuf, qualsep,
929  paramname, pk_type,
930  riinfo->pf_eq_oprs[i],
931  attname, fk_type);
932  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
933  ri_GenerateQualCollation(&querybuf, pk_coll);
934  querysep = ",";
935  qualsep = "AND";
936  queryoids[i] = pk_type;
937  queryoids[j] = pk_type;
938  }
939  appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
940 
941  /* Prepare and save the plan */
942  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
943  &qkey, fk_rel, pk_rel);
944  }
945 
946  /*
947  * We have a plan now. Run it to update the existing references.
948  */
949  ri_PerformCheck(riinfo, &qkey, qplan,
950  fk_rel, pk_rel,
951  oldslot, newslot,
952  true, /* must detect new rows */
953  SPI_OK_UPDATE);
954 
955  if (SPI_finish() != SPI_OK_FINISH)
956  elog(ERROR, "SPI_finish failed");
957 
958  table_close(fk_rel, RowExclusiveLock);
959 
960  return PointerGetDatum(NULL);
961 }
int j
Definition: isn.c:74
#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:233
TupleTableSlot * tg_newslot
Definition: trigger.h:40

References appendBinaryStringInfo(), appendStringInfo(), attname, StringInfoData::data, elog, ERROR, get_collation_isdeterministic(), i, initStringInfo(), j, StringInfoData::len, MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum(), quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttCollation, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, 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 239 of file ri_triggers.c.

240 {
241  const RI_ConstraintInfo *riinfo;
242  Relation fk_rel;
243  Relation pk_rel;
244  TupleTableSlot *newslot;
245  RI_QueryKey qkey;
246  SPIPlanPtr qplan;
247 
248  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
249  trigdata->tg_relation, false);
250 
251  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
252  newslot = trigdata->tg_newslot;
253  else
254  newslot = trigdata->tg_trigslot;
255 
256  /*
257  * We should not even consider checking the row if it is no longer valid,
258  * since it was either deleted (so the deferred check should be skipped)
259  * or updated (in which case only the latest version of the row should be
260  * checked). Test its liveness according to SnapshotSelf. We need pin
261  * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
262  * should be holding pin, but not lock.
263  */
264  if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
265  return PointerGetDatum(NULL);
266 
267  /*
268  * Get the relation descriptors of the FK and PK tables.
269  *
270  * pk_rel is opened in RowShareLock mode since that's what our eventual
271  * SELECT FOR KEY SHARE will get on it.
272  */
273  fk_rel = trigdata->tg_relation;
274  pk_rel = table_open(riinfo->pk_relid, RowShareLock);
275 
276  switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
277  {
278  case RI_KEYS_ALL_NULL:
279 
280  /*
281  * No further check needed - an all-NULL key passes every type of
282  * foreign key constraint.
283  */
284  table_close(pk_rel, RowShareLock);
285  return PointerGetDatum(NULL);
286 
287  case RI_KEYS_SOME_NULL:
288 
289  /*
290  * This is the only case that differs between the three kinds of
291  * MATCH.
292  */
293  switch (riinfo->confmatchtype)
294  {
295  case FKCONSTR_MATCH_FULL:
296 
297  /*
298  * Not allowed - MATCH FULL says either all or none of the
299  * attributes can be NULLs
300  */
301  ereport(ERROR,
302  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
303  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
304  RelationGetRelationName(fk_rel),
305  NameStr(riinfo->conname)),
306  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
307  errtableconstraint(fk_rel,
308  NameStr(riinfo->conname))));
309  table_close(pk_rel, RowShareLock);
310  return PointerGetDatum(NULL);
311 
313 
314  /*
315  * MATCH SIMPLE - if ANY column is null, the key passes
316  * the constraint.
317  */
318  table_close(pk_rel, RowShareLock);
319  return PointerGetDatum(NULL);
320 
321 #ifdef NOT_USED
323 
324  /*
325  * MATCH PARTIAL - all non-null columns must match. (not
326  * implemented, can be done by modifying the query below
327  * to only include non-null columns, or by writing a
328  * special version here)
329  */
330  break;
331 #endif
332  }
333 
334  case RI_KEYS_NONE_NULL:
335 
336  /*
337  * Have a full qualified key - continue below for all three kinds
338  * of MATCH.
339  */
340  break;
341  }
342 
343  if (SPI_connect() != SPI_OK_CONNECT)
344  elog(ERROR, "SPI_connect failed");
345 
346  /* Fetch or prepare a saved plan for the real check */
348 
349  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
350  {
351  StringInfoData querybuf;
352  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
354  char paramname[16];
355  const char *querysep;
356  Oid queryoids[RI_MAX_NUMKEYS];
357  const char *pk_only;
358 
359  /* ----------
360  * The query string built is
361  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
362  * FOR KEY SHARE OF x
363  * The type id's for the $ parameters are those of the
364  * corresponding FK attributes.
365  * ----------
366  */
367  initStringInfo(&querybuf);
368  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
369  "" : "ONLY ";
370  quoteRelationName(pkrelname, pk_rel);
371  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
372  pk_only, pkrelname);
373  querysep = "WHERE";
374  for (int i = 0; i < riinfo->nkeys; i++)
375  {
376  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
377  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
378 
380  RIAttName(pk_rel, riinfo->pk_attnums[i]));
381  sprintf(paramname, "$%d", i + 1);
382  ri_GenerateQual(&querybuf, querysep,
383  attname, pk_type,
384  riinfo->pf_eq_oprs[i],
385  paramname, fk_type);
386  querysep = "AND";
387  queryoids[i] = fk_type;
388  }
389  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
390 
391  /* Prepare and save the plan */
392  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
393  &qkey, fk_rel, pk_rel);
394  }
395 
396  /*
397  * Now check that foreign key exists in PK table
398  *
399  * XXX detectNewRows must be true when a partitioned table is on the
400  * referenced side. The reason is that our snapshot must be fresh in
401  * order for the hack in find_inheritance_children() to work.
402  */
403  ri_PerformCheck(riinfo, &qkey, qplan,
404  fk_rel, pk_rel,
405  NULL, newslot,
406  pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
407  SPI_OK_SELECT);
408 
409  if (SPI_finish() != SPI_OK_FINISH)
410  elog(ERROR, "SPI_finish failed");
411 
412  table_close(pk_rel, RowShareLock);
413 
414  return PointerGetDatum(NULL);
415 }
#define NameStr(name)
Definition: c.h:746
int errdetail(const char *fmt,...)
Definition: elog.c:1201
#define RowShareLock
Definition: lockdefs.h:37
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6006
#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
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1335

References appendStringInfo(), appendStringInfoString(), attname, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, PointerGetDatum(), quoteOneName(), quoteRelationName(), RelationData::rd_rel, 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_CONNECT, 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 424 of file ri_triggers.c.

425 {
426  /* Check that this is a valid trigger call on the right time and event. */
427  ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
428 
429  /* Share code with UPDATE case. */
430  return RI_FKey_check((TriggerData *) fcinfo->context);
431 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:239

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 440 of file ri_triggers.c.

441 {
442  /* Check that this is a valid trigger call on the right time and event. */
443  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
444 
445  /* Share code with INSERT case. */
446  return RI_FKey_check((TriggerData *) fcinfo->context);
447 }

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 1258 of file ri_triggers.c.

1260 {
1261  const RI_ConstraintInfo *riinfo;
1262  int ri_nullcheck;
1263 
1264  /*
1265  * AfterTriggerSaveEvent() handles things such that this function is never
1266  * called for partitioned tables.
1267  */
1268  Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1269 
1270  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1271 
1272  ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1273 
1274  /*
1275  * If all new key values are NULL, the row satisfies the constraint, so no
1276  * check is needed.
1277  */
1278  if (ri_nullcheck == RI_KEYS_ALL_NULL)
1279  return false;
1280 
1281  /*
1282  * If some new key values are NULL, the behavior depends on the match
1283  * type.
1284  */
1285  else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1286  {
1287  switch (riinfo->confmatchtype)
1288  {
1289  case FKCONSTR_MATCH_SIMPLE:
1290 
1291  /*
1292  * If any new key value is NULL, the row must satisfy the
1293  * constraint, so no check is needed.
1294  */
1295  return false;
1296 
1298 
1299  /*
1300  * Don't know, must run full check.
1301  */
1302  break;
1303 
1304  case FKCONSTR_MATCH_FULL:
1305 
1306  /*
1307  * If some new key values are NULL, the row fails the
1308  * constraint. We must not throw error here, because the row
1309  * might get invalidated before the constraint is to be
1310  * checked, but we should queue the event to apply the check
1311  * later.
1312  */
1313  return true;
1314  }
1315  }
1316 
1317  /*
1318  * Continues here for no new key values are NULL, or we couldn't decide
1319  * yet.
1320  */
1321 
1322  /*
1323  * If the original row was inserted by our own transaction, we must fire
1324  * the trigger whether or not the keys are equal. This is because our
1325  * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1326  * not do anything; so we had better do the UPDATE check. (We could skip
1327  * this if we knew the INSERT trigger already fired, but there is no easy
1328  * way to know that.)
1329  */
1330  if (slot_is_current_xact_tuple(oldslot))
1331  return true;
1332 
1333  /* If all old and new key values are equal, no check is needed */
1334  if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1335  return false;
1336 
1337  /* Else we need to fire the trigger. */
1338  return true;
1339 }
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2795
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition: tuptable.h:445

References Assert, RI_ConstraintInfo::confmatchtype, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, RelationData::rd_rel, 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 551 of file ri_triggers.c.

552 {
553  /* Check that this is a valid trigger call on the right time and event. */
554  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
555 
556  /* Share code with RESTRICT/UPDATE cases. */
557  return ri_restrict((TriggerData *) fcinfo->context, true);
558 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:624

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 588 of file ri_triggers.c.

589 {
590  /* Check that this is a valid trigger call on the right time and event. */
591  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
592 
593  /* Share code with RESTRICT/DELETE cases. */
594  return ri_restrict((TriggerData *) fcinfo->context, true);
595 }

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 1226 of file ri_triggers.c.

1228 {
1229  const RI_ConstraintInfo *riinfo;
1230 
1231  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1232 
1233  /*
1234  * If any old key value is NULL, the row could not have been referenced by
1235  * an FK row, so no check is needed.
1236  */
1237  if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1238  return false;
1239 
1240  /* If all old and new key values are equal, no check is needed */
1241  if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1242  return false;
1243 
1244  /* Else we need to fire the trigger. */
1245  return true;
1246 }

References 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 571 of file ri_triggers.c.

572 {
573  /* Check that this is a valid trigger call on the right time and event. */
574  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
575 
576  /* Share code with NO ACTION/UPDATE cases. */
577  return ri_restrict((TriggerData *) fcinfo->context, false);
578 }

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 608 of file ri_triggers.c.

609 {
610  /* Check that this is a valid trigger call on the right time and event. */
611  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
612 
613  /* Share code with NO ACTION/DELETE cases. */
614  return ri_restrict((TriggerData *) fcinfo->context, false);
615 }

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1000 of file ri_triggers.c.

1001 {
1002  /* Check that this is a valid trigger call on the right time and event. */
1003  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1004 
1005  /* Share code with UPDATE case */
1006  return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1007 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
Definition: ri_triggers.c:1031

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1015 of file ri_triggers.c.

1016 {
1017  /* Check that this is a valid trigger call on the right time and event. */
1018  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1019 
1020  /* Share code with DELETE case */
1021  return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1022 }

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 970 of file ri_triggers.c.

971 {
972  /* Check that this is a valid trigger call on the right time and event. */
973  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
974 
975  /* Share code with UPDATE case */
976  return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
977 }

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 985 of file ri_triggers.c.

986 {
987  /* Check that this is a valid trigger call on the right time and event. */
988  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
989 
990  /* Share code with DELETE case */
991  return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
992 }

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3001 of file ri_triggers.c.

3002 {
3003  switch (tgfoid)
3004  {
3005  case F_RI_FKEY_CASCADE_DEL:
3006  case F_RI_FKEY_CASCADE_UPD:
3007  case F_RI_FKEY_RESTRICT_DEL:
3008  case F_RI_FKEY_RESTRICT_UPD:
3009  case F_RI_FKEY_SETNULL_DEL:
3010  case F_RI_FKEY_SETNULL_UPD:
3011  case F_RI_FKEY_SETDEFAULT_DEL:
3012  case F_RI_FKEY_SETDEFAULT_UPD:
3013  case F_RI_FKEY_NOACTION_DEL:
3014  case F_RI_FKEY_NOACTION_UPD:
3015  return RI_TRIGGER_PK;
3016 
3017  case F_RI_FKEY_CHECK_INS:
3018  case F_RI_FKEY_CHECK_UPD:
3019  return RI_TRIGGER_FK;
3020  }
3021 
3022  return RI_TRIGGER_NONE;
3023 }
#define RI_TRIGGER_FK
Definition: trigger.h:283
#define RI_TRIGGER_NONE
Definition: trigger.h:284
#define RI_TRIGGER_PK
Definition: trigger.h:282

References 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 1910 of file ri_triggers.c.

1915 {
1916  appendStringInfo(buf, " %s ", sep);
1917  generate_operator_clause(buf, leftop, leftoptype, opoid,
1918  rightop, rightoptype);
1919 }
static char * buf
Definition: pg_test_fsync.c:73
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13004

References appendStringInfo(), buf, 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 1939 of file ri_triggers.c.

1940 {
1941  HeapTuple tp;
1942  Form_pg_collation colltup;
1943  char *collname;
1944  char onename[MAX_QUOTED_NAME_LEN];
1945 
1946  /* Nothing to do if it's a noncollatable data type */
1947  if (!OidIsValid(collation))
1948  return;
1949 
1950  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1951  if (!HeapTupleIsValid(tp))
1952  elog(ERROR, "cache lookup failed for collation %u", collation);
1953  colltup = (Form_pg_collation) GETSTRUCT(tp);
1954  collname = NameStr(colltup->collname);
1955 
1956  /*
1957  * We qualify the name always, for simplicity and to ensure the query is
1958  * not search-path-dependent.
1959  */
1960  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
1961  appendStringInfo(buf, " COLLATE %s", onename);
1962  quoteOneName(onename, collname);
1963  appendStringInfo(buf, ".%s", onename);
1964 
1965  ReleaseSysCache(tp);
1966 }
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58

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

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

◆ ri_HashCompareOp()

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

Definition at line 2908 of file ri_triggers.c.

2909 {
2911  RI_CompareHashEntry *entry;
2912  bool found;
2913 
2914  /*
2915  * On the first call initialize the hashtable
2916  */
2917  if (!ri_compare_cache)
2919 
2920  /*
2921  * Find or create a hash entry. Note we're assuming RI_CompareKey
2922  * contains no struct padding.
2923  */
2924  key.eq_opr = eq_opr;
2925  key.typeid = typeid;
2927  &key,
2928  HASH_ENTER, &found);
2929  if (!found)
2930  entry->valid = false;
2931 
2932  /*
2933  * If not already initialized, do so. Since we'll keep this hash entry
2934  * for the life of the backend, put any subsidiary info for the function
2935  * cache structs into TopMemoryContext.
2936  */
2937  if (!entry->valid)
2938  {
2939  Oid lefttype,
2940  righttype,
2941  castfunc;
2942  CoercionPathType pathtype;
2943 
2944  /* We always need to know how to call the equality operator */
2945  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
2947 
2948  /*
2949  * If we chose to use a cast from FK to PK type, we may have to apply
2950  * the cast function to get to the operator's input type.
2951  *
2952  * XXX eventually it would be good to support array-coercion cases
2953  * here and in ri_AttributesEqual(). At the moment there is no point
2954  * because cases involving nonidentical array types will be rejected
2955  * at constraint creation time.
2956  *
2957  * XXX perhaps also consider supporting CoerceViaIO? No need at the
2958  * moment since that will never be generated for implicit coercions.
2959  */
2960  op_input_types(eq_opr, &lefttype, &righttype);
2961  Assert(lefttype == righttype);
2962  if (typeid == lefttype)
2963  castfunc = InvalidOid; /* simplest case */
2964  else
2965  {
2966  pathtype = find_coercion_pathway(lefttype, typeid,
2968  &castfunc);
2969  if (pathtype != COERCION_PATH_FUNC &&
2970  pathtype != COERCION_PATH_RELABELTYPE)
2971  {
2972  /*
2973  * The declared input type of the eq_opr might be a
2974  * polymorphic type such as ANYARRAY or ANYENUM, or other
2975  * special cases such as RECORD; find_coercion_pathway
2976  * currently doesn't subsume these special cases.
2977  */
2978  if (!IsBinaryCoercible(typeid, lefttype))
2979  elog(ERROR, "no conversion function from %s to %s",
2980  format_type_be(typeid),
2981  format_type_be(lefttype));
2982  }
2983  }
2984  if (OidIsValid(castfunc))
2985  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
2987  else
2989  entry->valid = true;
2990  }
2991 
2992  return entry;
2993 }
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
@ HASH_ENTER
Definition: hsearch.h:114
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1358
MemoryContext TopMemoryContext
Definition: mcxt.c:149
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
Definition: parse_coerce.h:25
@ COERCION_PATH_FUNC
Definition: parse_coerce.h:27
@ COERCION_PATH_RELABELTYPE
Definition: parse_coerce.h:28
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCION_IMPLICIT
Definition: primnodes.h:714
static HTAB * ri_compare_cache
Definition: ri_triggers.c:175

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(), sort-test::key, OidIsValid, op_input_types(), ri_compare_cache, ri_InitHashTables(), TopMemoryContext, and RI_CompareHashEntry::valid.

Referenced by ri_AttributesEqual().

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 2761 of file ri_triggers.c.

2762 {
2763  RI_QueryHashEntry *entry;
2764  bool found;
2765 
2766  /*
2767  * On the first call initialize the hashtable
2768  */
2769  if (!ri_query_cache)
2771 
2772  /*
2773  * Add the new plan. We might be overwriting an entry previously found
2774  * invalid by ri_FetchPreparedPlan.
2775  */
2777  key,
2778  HASH_ENTER, &found);
2779  Assert(!found || entry->plan == NULL);
2780  entry->plan = plan;
2781 }

References Assert, HASH_ENTER, hash_search(), sort-test::key, 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 2673 of file ri_triggers.c.

2674 {
2675  HASHCTL ctl;
2676 
2677  ctl.keysize = sizeof(Oid);
2678  ctl.entrysize = sizeof(RI_ConstraintInfo);
2679  ri_constraint_cache = hash_create("RI constraint cache",
2681  &ctl, HASH_ELEM | HASH_BLOBS);
2682 
2683  /* Arrange to flush cache on pg_constraint changes */
2686  (Datum) 0);
2687 
2688  ctl.keysize = sizeof(RI_QueryKey);
2689  ctl.entrysize = sizeof(RI_QueryHashEntry);
2690  ri_query_cache = hash_create("RI query cache",
2692  &ctl, HASH_ELEM | HASH_BLOBS);
2693 
2694  ctl.keysize = sizeof(RI_CompareKey);
2695  ctl.entrysize = sizeof(RI_CompareHashEntry);
2696  ri_compare_cache = hash_create("RI compare cache",
2698  &ctl, HASH_ELEM | HASH_BLOBS);
2699 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1516
uintptr_t Datum
Definition: postgres.h:64
tree ctl
Definition: radixtree.h:1853
struct RI_ConstraintInfo RI_ConstraintInfo
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2228
struct RI_QueryKey RI_QueryKey
struct RI_CompareHashEntry RI_CompareHashEntry
struct RI_QueryHashEntry RI_QueryHashEntry
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:61
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:60
struct RI_CompareKey RI_CompareKey

References CacheRegisterSyscacheCallback(), ctl, HASH_BLOBS, hash_create(), HASH_ELEM, InvalidateConstraintCacheCallBack(), 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 1359 of file ri_triggers.c.

1360 {
1361  const RI_ConstraintInfo *riinfo;
1362  StringInfoData querybuf;
1363  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1364  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1365  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1366  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1367  RangeTblEntry *rte;
1368  RTEPermissionInfo *pk_perminfo;
1369  RTEPermissionInfo *fk_perminfo;
1370  List *rtes = NIL;
1371  List *perminfos = NIL;
1372  const char *sep;
1373  const char *fk_only;
1374  const char *pk_only;
1375  int save_nestlevel;
1376  char workmembuf[32];
1377  int spi_result;
1378  SPIPlanPtr qplan;
1379 
1380  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1381 
1382  /*
1383  * Check to make sure current user has enough permissions to do the test
1384  * query. (If not, caller can fall back to the trigger method, which
1385  * works because it changes user IDs on the fly.)
1386  *
1387  * XXX are there any other show-stopper conditions to check?
1388  */
1389  pk_perminfo = makeNode(RTEPermissionInfo);
1390  pk_perminfo->relid = RelationGetRelid(pk_rel);
1391  pk_perminfo->requiredPerms = ACL_SELECT;
1392  perminfos = lappend(perminfos, pk_perminfo);
1393  rte = makeNode(RangeTblEntry);
1394  rte->rtekind = RTE_RELATION;
1395  rte->relid = RelationGetRelid(pk_rel);
1396  rte->relkind = pk_rel->rd_rel->relkind;
1397  rte->rellockmode = AccessShareLock;
1398  rte->perminfoindex = list_length(perminfos);
1399  rtes = lappend(rtes, rte);
1400 
1401  fk_perminfo = makeNode(RTEPermissionInfo);
1402  fk_perminfo->relid = RelationGetRelid(fk_rel);
1403  fk_perminfo->requiredPerms = ACL_SELECT;
1404  perminfos = lappend(perminfos, fk_perminfo);
1405  rte = makeNode(RangeTblEntry);
1406  rte->rtekind = RTE_RELATION;
1407  rte->relid = RelationGetRelid(fk_rel);
1408  rte->relkind = fk_rel->rd_rel->relkind;
1409  rte->rellockmode = AccessShareLock;
1410  rte->perminfoindex = list_length(perminfos);
1411  rtes = lappend(rtes, rte);
1412 
1413  for (int i = 0; i < riinfo->nkeys; i++)
1414  {
1415  int attno;
1416 
1417  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1418  pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1419 
1420  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1421  fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1422  }
1423 
1424  if (!ExecCheckPermissions(rtes, perminfos, false))
1425  return false;
1426 
1427  /*
1428  * Also punt if RLS is enabled on either table unless this role has the
1429  * bypassrls right or is the table owner of the table(s) involved which
1430  * have RLS enabled.
1431  */
1433  ((pk_rel->rd_rel->relrowsecurity &&
1434  !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1435  GetUserId())) ||
1436  (fk_rel->rd_rel->relrowsecurity &&
1437  !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1438  GetUserId()))))
1439  return false;
1440 
1441  /*----------
1442  * The query string built is:
1443  * SELECT fk.keycols FROM [ONLY] relname fk
1444  * LEFT OUTER JOIN [ONLY] pkrelname pk
1445  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1446  * WHERE pk.pkkeycol1 IS NULL AND
1447  * For MATCH SIMPLE:
1448  * (fk.keycol1 IS NOT NULL [AND ...])
1449  * For MATCH FULL:
1450  * (fk.keycol1 IS NOT NULL [OR ...])
1451  *
1452  * We attach COLLATE clauses to the operators when comparing columns
1453  * that have different collations.
1454  *----------
1455  */
1456  initStringInfo(&querybuf);
1457  appendStringInfoString(&querybuf, "SELECT ");
1458  sep = "";
1459  for (int i = 0; i < riinfo->nkeys; i++)
1460  {
1461  quoteOneName(fkattname,
1462  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1463  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1464  sep = ", ";
1465  }
1466 
1467  quoteRelationName(pkrelname, pk_rel);
1468  quoteRelationName(fkrelname, fk_rel);
1469  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1470  "" : "ONLY ";
1471  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1472  "" : "ONLY ";
1473  appendStringInfo(&querybuf,
1474  " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1475  fk_only, fkrelname, pk_only, pkrelname);
1476 
1477  strcpy(pkattname, "pk.");
1478  strcpy(fkattname, "fk.");
1479  sep = "(";
1480  for (int i = 0; i < riinfo->nkeys; i++)
1481  {
1482  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1483  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1484  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1485  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1486 
1487  quoteOneName(pkattname + 3,
1488  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1489  quoteOneName(fkattname + 3,
1490  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1491  ri_GenerateQual(&querybuf, sep,
1492  pkattname, pk_type,
1493  riinfo->pf_eq_oprs[i],
1494  fkattname, fk_type);
1495  if (pk_coll != fk_coll)
1496  ri_GenerateQualCollation(&querybuf, pk_coll);
1497  sep = "AND";
1498  }
1499 
1500  /*
1501  * It's sufficient to test any one pk attribute for null to detect a join
1502  * failure.
1503  */
1504  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1505  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1506 
1507  sep = "";
1508  for (int i = 0; i < riinfo->nkeys; i++)
1509  {
1510  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1511  appendStringInfo(&querybuf,
1512  "%sfk.%s IS NOT NULL",
1513  sep, fkattname);
1514  switch (riinfo->confmatchtype)
1515  {
1516  case FKCONSTR_MATCH_SIMPLE:
1517  sep = " AND ";
1518  break;
1519  case FKCONSTR_MATCH_FULL:
1520  sep = " OR ";
1521  break;
1522  }
1523  }
1524  appendStringInfoChar(&querybuf, ')');
1525 
1526  /*
1527  * Temporarily increase work_mem so that the check query can be executed
1528  * more efficiently. It seems okay to do this because the query is simple
1529  * enough to not use a multiple of work_mem, and one typically would not
1530  * have many large foreign-key validations happening concurrently. So
1531  * this seems to meet the criteria for being considered a "maintenance"
1532  * operation, and accordingly we use maintenance_work_mem. However, we
1533  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1534  * let that get applied to the maintenance_work_mem value.
1535  *
1536  * We use the equivalent of a function SET option to allow the setting to
1537  * persist for exactly the duration of the check query. guc.c also takes
1538  * care of undoing the setting on error.
1539  */
1540  save_nestlevel = NewGUCNestLevel();
1541 
1542  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1543  (void) set_config_option("work_mem", workmembuf,
1545  GUC_ACTION_SAVE, true, 0, false);
1546  (void) set_config_option("hash_mem_multiplier", "1",
1548  GUC_ACTION_SAVE, true, 0, false);
1549 
1550  if (SPI_connect() != SPI_OK_CONNECT)
1551  elog(ERROR, "SPI_connect failed");
1552 
1553  /*
1554  * Generate the plan. We don't need to cache it, and there are no
1555  * arguments to the plan.
1556  */
1557  qplan = SPI_prepare(querybuf.data, 0, NULL);
1558 
1559  if (qplan == NULL)
1560  elog(ERROR, "SPI_prepare returned %s for %s",
1562 
1563  /*
1564  * Run the plan. For safety we force a current snapshot to be used. (In
1565  * transaction-snapshot mode, this arguably violates transaction isolation
1566  * rules, but we really haven't got much choice.) We don't need to
1567  * register the snapshot, because SPI_execute_snapshot will see to it. We
1568  * need at most one tuple returned, so pass limit = 1.
1569  */
1570  spi_result = SPI_execute_snapshot(qplan,
1571  NULL, NULL,
1574  true, false, 1);
1575 
1576  /* Check result */
1577  if (spi_result != SPI_OK_SELECT)
1578  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1579 
1580  /* Did we find a tuple violating the constraint? */
1581  if (SPI_processed > 0)
1582  {
1583  TupleTableSlot *slot;
1584  HeapTuple tuple = SPI_tuptable->vals[0];
1585  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1586  RI_ConstraintInfo fake_riinfo;
1587 
1588  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1589 
1590  heap_deform_tuple(tuple, tupdesc,
1591  slot->tts_values, slot->tts_isnull);
1592  ExecStoreVirtualTuple(slot);
1593 
1594  /*
1595  * The columns to look at in the result tuple are 1..N, not whatever
1596  * they are in the fk_rel. Hack up riinfo so that the subroutines
1597  * called here will behave properly.
1598  *
1599  * In addition to this, we have to pass the correct tupdesc to
1600  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1601  * or fk_rel's tupdesc.
1602  */
1603  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1604  for (int i = 0; i < fake_riinfo.nkeys; i++)
1605  fake_riinfo.fk_attnums[i] = i + 1;
1606 
1607  /*
1608  * If it's MATCH FULL, and there are any nulls in the FK keys,
1609  * complain about that rather than the lack of a match. MATCH FULL
1610  * disallows partially-null FK rows.
1611  */
1612  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1613  ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1614  ereport(ERROR,
1615  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1616  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1617  RelationGetRelationName(fk_rel),
1618  NameStr(fake_riinfo.conname)),
1619  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1620  errtableconstraint(fk_rel,
1621  NameStr(fake_riinfo.conname))));
1622 
1623  /*
1624  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1625  * query, which isn't true, but will cause it to use
1626  * fake_riinfo.fk_attnums as we need.
1627  */
1628  ri_ReportViolation(&fake_riinfo,
1629  pk_rel, fk_rel,
1630  slot, tupdesc,
1631  RI_PLAN_CHECK_LOOKUPPK, false);
1632 
1634  }
1635 
1636  if (SPI_finish() != SPI_OK_FINISH)
1637  elog(ERROR, "SPI_finish failed");
1638 
1639  /*
1640  * Restore work_mem and hash_mem_multiplier.
1641  */
1642  AtEOXact_GUC(true, save_nestlevel);
1643 
1644  return true;
1645 }
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:4242
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:579
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1639
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1325
int maintenance_work_mem
Definition: globals.c:131
int NewGUCNestLevel(void)
Definition: guc.c:2237
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2264
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:3343
@ GUC_ACTION_SAVE
Definition: guc.h:201
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_USERSET
Definition: guc.h:75
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1345
List * lappend(List *list, void *datum)
Definition: list.c:339
#define AccessShareLock
Definition: lockdefs.h:36
Oid GetUserId(void)
Definition: miscinit.c:514
#define makeNode(_type_)
Definition: nodes.h:155
@ RTE_RELATION
Definition: parsenodes.h:1028
#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:238
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2478
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:291
#define InvalidSnapshot
Definition: snapshot.h:123
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_execute_snapshot(SPIPlanPtr plan, Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition: spi.c:770
int SPI_result
Definition: spi.c:46
const char * SPI_result_code_string(int code)
Definition: spi.c:1969
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:857
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
Definition: pg_list.h:54
Bitmapset * selectedCols
Definition: parsenodes.h:1297
AclMode requiredPerms
Definition: parsenodes.h:1295
RTEKind rtekind
Definition: parsenodes.h:1057
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References AccessShareLock, ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecCheckPermissions(), ExecDropSingleTupleTableSlot(), ExecStoreVirtualTuple(), FirstLowInvalidHeapAttributeNumber, RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_bypassrls_privilege(), heap_deform_tuple(), i, if(), initStringInfo(), InvalidSnapshot, lappend(), list_length(), maintenance_work_mem, makeNode, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, NewGUCNestLevel(), NIL, RI_ConstraintInfo::nkeys, object_ownercheck(), RI_ConstraintInfo::pf_eq_oprs, PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RTEPermissionInfo::relid, RTEPermissionInfo::requiredPerms, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_KEYS_NONE_NULL, ri_NullCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, RTE_RELATION, RangeTblEntry::rtekind, RTEPermissionInfo::selectedCols, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_CONNECT, 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 2795 of file ri_triggers.c.

2797 {
2798  const int16 *attnums;
2799 
2800  if (rel_is_pk)
2801  attnums = riinfo->pk_attnums;
2802  else
2803  attnums = riinfo->fk_attnums;
2804 
2805  /* XXX: could be worthwhile to fetch all necessary attrs at once */
2806  for (int i = 0; i < riinfo->nkeys; i++)
2807  {
2808  Datum oldvalue;
2809  Datum newvalue;
2810  bool isnull;
2811 
2812  /*
2813  * Get one attribute's oldvalue. If it is NULL - they're not equal.
2814  */
2815  oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
2816  if (isnull)
2817  return false;
2818 
2819  /*
2820  * Get one attribute's newvalue. If it is NULL - they're not equal.
2821  */
2822  newvalue = slot_getattr(newslot, attnums[i], &isnull);
2823  if (isnull)
2824  return false;
2825 
2826  if (rel_is_pk)
2827  {
2828  /*
2829  * If we are looking at the PK table, then do a bytewise
2830  * comparison. We must propagate PK changes if the value is
2831  * changed to one that "looks" different but would compare as
2832  * equal using the equality operator. This only makes a
2833  * difference for ON UPDATE CASCADE, but for consistency we treat
2834  * all changes to the PK the same.
2835  */
2836  Form_pg_attribute att = TupleDescAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
2837 
2838  if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
2839  return false;
2840  }
2841  else
2842  {
2843  /*
2844  * For the FK table, compare with the appropriate equality
2845  * operator. Changes that compare equal will still satisfy the
2846  * constraint after the update.
2847  */
2848  if (!ri_AttributesEqual(riinfo->ff_eq_oprs[i], RIAttType(rel, attnums[i]),
2849  oldvalue, newvalue))
2850  return false;
2851  }
2852  }
2853 
2854  return true;
2855 }
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static bool ri_AttributesEqual(Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
Definition: ri_triggers.c:2866
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References datum_image_eq(), RI_ConstraintInfo::ff_eq_oprs, RI_ConstraintInfo::fk_attnums, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, ri_AttributesEqual(), RIAttType, slot_getattr(), TupleTableSlot::tts_tupleDescriptor, and TupleDescAttr.

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 2112 of file ri_triggers.c.

2113 {
2114  RI_ConstraintInfo *riinfo;
2115  bool found;
2116  HeapTuple tup;
2117  Form_pg_constraint conForm;
2118 
2119  /*
2120  * On the first call initialize the hashtable
2121  */
2122  if (!ri_constraint_cache)
2124 
2125  /*
2126  * Find or create a hash entry. If we find a valid one, just return it.
2127  */
2129  &constraintOid,
2130  HASH_ENTER, &found);
2131  if (!found)
2132  riinfo->valid = false;
2133  else if (riinfo->valid)
2134  return riinfo;
2135 
2136  /*
2137  * Fetch the pg_constraint row so we can fill in the entry.
2138  */
2139  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2140  if (!HeapTupleIsValid(tup)) /* should not happen */
2141  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2142  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2143 
2144  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2145  elog(ERROR, "constraint %u is not a foreign key constraint",
2146  constraintOid);
2147 
2148  /* And extract data */
2149  Assert(riinfo->constraint_id == constraintOid);
2150  if (OidIsValid(conForm->conparentid))
2151  riinfo->constraint_root_id =
2152  get_ri_constraint_root(conForm->conparentid);
2153  else
2154  riinfo->constraint_root_id = constraintOid;
2155  riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2156  ObjectIdGetDatum(constraintOid));
2157  riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2159  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2160  riinfo->pk_relid = conForm->confrelid;
2161  riinfo->fk_relid = conForm->conrelid;
2162  riinfo->confupdtype = conForm->confupdtype;
2163  riinfo->confdeltype = conForm->confdeltype;
2164  riinfo->confmatchtype = conForm->confmatchtype;
2165 
2167  &riinfo->nkeys,
2168  riinfo->fk_attnums,
2169  riinfo->pk_attnums,
2170  riinfo->pf_eq_oprs,
2171  riinfo->pp_eq_oprs,
2172  riinfo->ff_eq_oprs,
2173  &riinfo->ndelsetcols,
2174  riinfo->confdelsetcols);
2175 
2176  ReleaseSysCache(tup);
2177 
2178  /*
2179  * For efficient processing of invalidation messages below, we keep a
2180  * doubly-linked count list of all currently valid entries.
2181  */
2183 
2184  riinfo->valid = true;
2185 
2186  return riinfo;
2187 }
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition: ilist.h:709
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: ri_triggers.c:2194
dlist_node valid_link
Definition: ri_triggers.c:124
int16 confdelsetcols[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:115
Definition: c.h:741
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:113

References Assert, RI_ConstraintInfo::confdelsetcols, RI_ConstraintInfo::confdeltype, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::confupdtype, RI_ConstraintInfo::conname, RI_ConstraintInfo::constraint_id, RI_ConstraintInfo::constraint_root_id, dclist_push_tail(), DeconstructFkConstraintRow(), elog, ERROR, RI_ConstraintInfo::ff_eq_oprs, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_ri_constraint_root(), GETSTRUCT, GetSysCacheHashValue1, HASH_ENTER, hash_search(), HeapTupleIsValid, RI_ConstraintInfo::ndelsetcols, RI_ConstraintInfo::nkeys, ObjectIdGetDatum(), RI_ConstraintInfo::oidHashValue, OidIsValid, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, RI_ConstraintInfo::pp_eq_oprs, ReleaseSysCache(), ri_constraint_cache, ri_constraint_cache_valid_list, ri_InitHashTables(), RI_ConstraintInfo::rootHashValue, SearchSysCache1(), RI_ConstraintInfo::valid, and RI_ConstraintInfo::valid_link.

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 2636 of file ri_triggers.c.

2639 {
2640  const int16 *attnums;
2641  bool allnull = true;
2642  bool nonenull = true;
2643 
2644  if (rel_is_pk)
2645  attnums = riinfo->pk_attnums;
2646  else
2647  attnums = riinfo->fk_attnums;
2648 
2649  for (int i = 0; i < riinfo->nkeys; i++)
2650  {
2651  if (slot_attisnull(slot, attnums[i]))
2652  nonenull = false;
2653  else
2654  allnull = false;
2655  }
2656 
2657  if (allnull)
2658  return RI_KEYS_ALL_NULL;
2659 
2660  if (nonenull)
2661  return RI_KEYS_NONE_NULL;
2662 
2663  return RI_KEYS_SOME_NULL;
2664 }
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:381

References RI_ConstraintInfo::fk_attnums, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, 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 1654 of file ri_triggers.c.

1655 {
1656  const RI_ConstraintInfo *riinfo;
1657  StringInfoData querybuf;
1658  char *constraintDef;
1659  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1660  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1661  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1662  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1663  const char *sep;
1664  const char *fk_only;
1665  int save_nestlevel;
1666  char workmembuf[32];
1667  int spi_result;
1668  SPIPlanPtr qplan;
1669  int i;
1670 
1671  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1672 
1673  /*
1674  * We don't check permissions before displaying the error message, on the
1675  * assumption that the user detaching the partition must have enough
1676  * privileges to examine the table contents anyhow.
1677  */
1678 
1679  /*----------
1680  * The query string built is:
1681  * SELECT fk.keycols FROM [ONLY] relname fk
1682  * JOIN pkrelname pk
1683  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1684  * WHERE (<partition constraint>) AND
1685  * For MATCH SIMPLE:
1686  * (fk.keycol1 IS NOT NULL [AND ...])
1687  * For MATCH FULL:
1688  * (fk.keycol1 IS NOT NULL [OR ...])
1689  *
1690  * We attach COLLATE clauses to the operators when comparing columns
1691  * that have different collations.
1692  *----------
1693  */
1694  initStringInfo(&querybuf);
1695  appendStringInfoString(&querybuf, "SELECT ");
1696  sep = "";
1697  for (i = 0; i < riinfo->nkeys; i++)
1698  {
1699  quoteOneName(fkattname,
1700  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1701  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1702  sep = ", ";
1703  }
1704 
1705  quoteRelationName(pkrelname, pk_rel);
1706  quoteRelationName(fkrelname, fk_rel);
1707  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1708  "" : "ONLY ";
1709  appendStringInfo(&querybuf,
1710  " FROM %s%s fk JOIN %s pk ON",
1711  fk_only, fkrelname, pkrelname);
1712  strcpy(pkattname, "pk.");
1713  strcpy(fkattname, "fk.");
1714  sep = "(";
1715  for (i = 0; i < riinfo->nkeys; i++)
1716  {
1717  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1718  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1719  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1720  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1721 
1722  quoteOneName(pkattname + 3,
1723  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1724  quoteOneName(fkattname + 3,
1725  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1726  ri_GenerateQual(&querybuf, sep,
1727  pkattname, pk_type,
1728  riinfo->pf_eq_oprs[i],
1729  fkattname, fk_type);
1730  if (pk_coll != fk_coll)
1731  ri_GenerateQualCollation(&querybuf, pk_coll);
1732  sep = "AND";
1733  }
1734 
1735  /*
1736  * Start the WHERE clause with the partition constraint (except if this is
1737  * the default partition and there's no other partition, because the
1738  * partition constraint is the empty string in that case.)
1739  */
1740  constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1741  if (constraintDef && constraintDef[0] != '\0')
1742  appendStringInfo(&querybuf, ") WHERE %s AND (",
1743  constraintDef);
1744  else
1745  appendStringInfoString(&querybuf, ") WHERE (");
1746 
1747  sep = "";
1748  for (i = 0; i < riinfo->nkeys; i++)
1749  {
1750  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1751  appendStringInfo(&querybuf,
1752  "%sfk.%s IS NOT NULL",
1753  sep, fkattname);
1754  switch (riinfo->confmatchtype)
1755  {
1756  case FKCONSTR_MATCH_SIMPLE:
1757  sep = " AND ";
1758  break;
1759  case FKCONSTR_MATCH_FULL:
1760  sep = " OR ";
1761  break;
1762  }
1763  }
1764  appendStringInfoChar(&querybuf, ')');
1765 
1766  /*
1767  * Temporarily increase work_mem so that the check query can be executed
1768  * more efficiently. It seems okay to do this because the query is simple
1769  * enough to not use a multiple of work_mem, and one typically would not
1770  * have many large foreign-key validations happening concurrently. So
1771  * this seems to meet the criteria for being considered a "maintenance"
1772  * operation, and accordingly we use maintenance_work_mem. However, we
1773  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1774  * let that get applied to the maintenance_work_mem value.
1775  *
1776  * We use the equivalent of a function SET option to allow the setting to
1777  * persist for exactly the duration of the check query. guc.c also takes
1778  * care of undoing the setting on error.
1779  */
1780  save_nestlevel = NewGUCNestLevel();
1781 
1782  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1783  (void) set_config_option("work_mem", workmembuf,
1785  GUC_ACTION_SAVE, true, 0, false);
1786  (void) set_config_option("hash_mem_multiplier", "1",
1788  GUC_ACTION_SAVE, true, 0, false);
1789 
1790  if (SPI_connect() != SPI_OK_CONNECT)
1791  elog(ERROR, "SPI_connect failed");
1792 
1793  /*
1794  * Generate the plan. We don't need to cache it, and there are no
1795  * arguments to the plan.
1796  */
1797  qplan = SPI_prepare(querybuf.data, 0, NULL);
1798 
1799  if (qplan == NULL)
1800  elog(ERROR, "SPI_prepare returned %s for %s",
1802 
1803  /*
1804  * Run the plan. For safety we force a current snapshot to be used. (In
1805  * transaction-snapshot mode, this arguably violates transaction isolation
1806  * rules, but we really haven't got much choice.) We don't need to
1807  * register the snapshot, because SPI_execute_snapshot will see to it. We
1808  * need at most one tuple returned, so pass limit = 1.
1809  */
1810  spi_result = SPI_execute_snapshot(qplan,
1811  NULL, NULL,
1814  true, false, 1);
1815 
1816  /* Check result */
1817  if (spi_result != SPI_OK_SELECT)
1818  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1819 
1820  /* Did we find a tuple that would violate the constraint? */
1821  if (SPI_processed > 0)
1822  {
1823  TupleTableSlot *slot;
1824  HeapTuple tuple = SPI_tuptable->vals[0];
1825  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1826  RI_ConstraintInfo fake_riinfo;
1827 
1828  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1829 
1830  heap_deform_tuple(tuple, tupdesc,
1831  slot->tts_values, slot->tts_isnull);
1832  ExecStoreVirtualTuple(slot);
1833 
1834  /*
1835  * The columns to look at in the result tuple are 1..N, not whatever
1836  * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1837  * will behave properly.
1838  *
1839  * In addition to this, we have to pass the correct tupdesc to
1840  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1841  * or fk_rel's tupdesc.
1842  */
1843  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1844  for (i = 0; i < fake_riinfo.nkeys; i++)
1845  fake_riinfo.pk_attnums[i] = i + 1;
1846 
1847  ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
1848  slot, tupdesc, 0, true);
1849  }
1850 
1851  if (SPI_finish() != SPI_OK_FINISH)
1852  elog(ERROR, "SPI_finish failed");
1853 
1854  /*
1855  * Restore work_mem and hash_mem_multiplier.
1856  */
1857  AtEOXact_GUC(true, save_nestlevel);
1858 }
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2112

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ERROR, ExecStoreVirtualTuple(), RI_ConstraintInfo::fk_attnums, 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(), RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, pg_get_partconstrdef_string(), PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, 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_CONNECT, 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  detectNewRows,
int  expect_OK 
)
static

Definition at line 2312 of file ri_triggers.c.

2317 {
2318  Relation query_rel,
2319  source_rel;
2320  bool source_is_pk;
2321  Snapshot test_snapshot;
2322  Snapshot crosscheck_snapshot;
2323  int limit;
2324  int spi_result;
2325  Oid save_userid;
2326  int save_sec_context;
2327  Datum vals[RI_MAX_NUMKEYS * 2];
2328  char nulls[RI_MAX_NUMKEYS * 2];
2329 
2330  /*
2331  * Use the query type code to determine whether the query is run against
2332  * the PK or FK table; we'll do the check as that table's owner
2333  */
2334  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2335  query_rel = pk_rel;
2336  else
2337  query_rel = fk_rel;
2338 
2339  /*
2340  * The values for the query are taken from the table on which the trigger
2341  * is called - it is normally the other one with respect to query_rel. An
2342  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2343  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2344  * need some less klugy way to determine this.
2345  */
2347  {
2348  source_rel = fk_rel;
2349  source_is_pk = false;
2350  }
2351  else
2352  {
2353  source_rel = pk_rel;
2354  source_is_pk = true;
2355  }
2356 
2357  /* Extract the parameters to be passed into the query */
2358  if (newslot)
2359  {
2360  ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2361  vals, nulls);
2362  if (oldslot)
2363  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2364  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2365  }
2366  else
2367  {
2368  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2369  vals, nulls);
2370  }
2371 
2372  /*
2373  * In READ COMMITTED mode, we just need to use an up-to-date regular
2374  * snapshot, and we will see all rows that could be interesting. But in
2375  * transaction-snapshot mode, we can't change the transaction snapshot. If
2376  * the caller passes detectNewRows == false then it's okay to do the query
2377  * with the transaction snapshot; otherwise we use a current snapshot, and
2378  * tell the executor to error out if it finds any rows under the current
2379  * snapshot that wouldn't be visible per the transaction snapshot. Note
2380  * that SPI_execute_snapshot will register the snapshots, so we don't need
2381  * to bother here.
2382  */
2383  if (IsolationUsesXactSnapshot() && detectNewRows)
2384  {
2385  CommandCounterIncrement(); /* be sure all my own work is visible */
2386  test_snapshot = GetLatestSnapshot();
2387  crosscheck_snapshot = GetTransactionSnapshot();
2388  }
2389  else
2390  {
2391  /* the default SPI behavior is okay */
2392  test_snapshot = InvalidSnapshot;
2393  crosscheck_snapshot = InvalidSnapshot;
2394  }
2395 
2396  /*
2397  * If this is a select query (e.g., for a 'no action' or 'restrict'
2398  * trigger), we only need to see if there is a single row in the table,
2399  * matching the key. Otherwise, limit = 0 - because we want the query to
2400  * affect ALL the matching rows.
2401  */
2402  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2403 
2404  /* Switch to proper UID to perform check as */
2405  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2406  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2407  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2409 
2410  /* Finally we can run the query. */
2411  spi_result = SPI_execute_snapshot(qplan,
2412  vals, nulls,
2413  test_snapshot, crosscheck_snapshot,
2414  false, false, limit);
2415 
2416  /* Restore UID and security context */
2417  SetUserIdAndSecContext(save_userid, save_sec_context);
2418 
2419  /* Check result */
2420  if (spi_result < 0)
2421  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2422 
2423  if (expect_OK >= 0 && spi_result != expect_OK)
2424  ereport(ERROR,
2425  (errcode(ERRCODE_INTERNAL_ERROR),
2426  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2427  RelationGetRelationName(pk_rel),
2428  NameStr(riinfo->conname),
2429  RelationGetRelationName(fk_rel)),
2430  errhint("This is most likely due to a rule having rewritten the query.")));
2431 
2432  /* XXX wouldn't it be clearer to do this part at the caller? */
2434  expect_OK == SPI_OK_SELECT &&
2436  ri_ReportViolation(riinfo,
2437  pk_rel, fk_rel,
2438  newslot ? newslot : oldslot,
2439  NULL,
2440  qkey->constr_queryno, false);
2441 
2442  return SPI_processed != 0;
2443 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:316
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:314
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
#define RelationGetForm(relation)
Definition: rel.h:499
#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)
Definition: ri_triggers.c:2449
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
int32 constr_queryno
Definition: ri_triggers.c:135
void CommandCounterIncrement(void)
Definition: xact.c:1098
#define IsolationUsesXactSnapshot()
Definition: xact.h:51

References CommandCounterIncrement(), RI_ConstraintInfo::conname, RI_QueryKey::constr_queryno, elog, ereport, errcode(), errhint(), errmsg(), ERROR, GetLatestSnapshot(), GetTransactionSnapshot(), GetUserIdAndSecContext(), InvalidSnapshot, IsolationUsesXactSnapshot, NameStr, RI_ConstraintInfo::nkeys, 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 2269 of file ri_triggers.c.

2271 {
2272  SPIPlanPtr qplan;
2273  Relation query_rel;
2274  Oid save_userid;
2275  int save_sec_context;
2276 
2277  /*
2278  * Use the query type code to determine whether the query is run against
2279  * the PK or FK table; we'll do the check as that table's owner
2280  */
2281  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2282  query_rel = pk_rel;
2283  else
2284  query_rel = fk_rel;
2285 
2286  /* Switch to proper UID to perform check as */
2287  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2288  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2289  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2291 
2292  /* Create the plan */
2293  qplan = SPI_prepare(querystr, nargs, argtypes);
2294 
2295  if (qplan == NULL)
2296  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2297 
2298  /* Restore UID and security context */
2299  SetUserIdAndSecContext(save_userid, save_sec_context);
2300 
2301  /* Save the plan */
2302  SPI_keepplan(qplan);
2303  ri_HashPreparedPlan(qkey, qplan);
2304 
2305  return qplan;
2306 }
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2761
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:973

References RI_QueryKey::constr_queryno, elog, ERROR, 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  partgone 
)
static

Definition at line 2478 of file ri_triggers.c.

2482 {
2483  StringInfoData key_names;
2484  StringInfoData key_values;
2485  bool onfk;
2486  const int16 *attnums;
2487  Oid rel_oid;
2488  AclResult aclresult;
2489  bool has_perm = true;
2490 
2491  /*
2492  * Determine which relation to complain about. If tupdesc wasn't passed
2493  * by caller, assume the violator tuple came from there.
2494  */
2495  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2496  if (onfk)
2497  {
2498  attnums = riinfo->fk_attnums;
2499  rel_oid = fk_rel->rd_id;
2500  if (tupdesc == NULL)
2501  tupdesc = fk_rel->rd_att;
2502  }
2503  else
2504  {
2505  attnums = riinfo->pk_attnums;
2506  rel_oid = pk_rel->rd_id;
2507  if (tupdesc == NULL)
2508  tupdesc = pk_rel->rd_att;
2509  }
2510 
2511  /*
2512  * Check permissions- if the user does not have access to view the data in
2513  * any of the key columns then we don't include the errdetail() below.
2514  *
2515  * Check if RLS is enabled on the relation first. If so, we don't return
2516  * any specifics to avoid leaking data.
2517  *
2518  * Check table-level permissions next and, failing that, column-level
2519  * privileges.
2520  *
2521  * When a partition at the referenced side is being detached/dropped, we
2522  * needn't check, since the user must be the table owner anyway.
2523  */
2524  if (partgone)
2525  has_perm = true;
2526  else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2527  {
2528  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2529  if (aclresult != ACLCHECK_OK)
2530  {
2531  /* Try for column-level permissions */
2532  for (int idx = 0; idx < riinfo->nkeys; idx++)
2533  {
2534  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2535  GetUserId(),
2536  ACL_SELECT);
2537 
2538  /* No access to the key */
2539  if (aclresult != ACLCHECK_OK)
2540  {
2541  has_perm = false;
2542  break;
2543  }
2544  }
2545  }
2546  }
2547  else
2548  has_perm = false;
2549 
2550  if (has_perm)
2551  {
2552  /* Get printable versions of the keys involved */
2553  initStringInfo(&key_names);
2554  initStringInfo(&key_values);
2555  for (int idx = 0; idx < riinfo->nkeys; idx++)
2556  {
2557  int fnum = attnums[idx];
2558  Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2559  char *name,
2560  *val;
2561  Datum datum;
2562  bool isnull;
2563 
2564  name = NameStr(att->attname);
2565 
2566  datum = slot_getattr(violatorslot, fnum, &isnull);
2567  if (!isnull)
2568  {
2569  Oid foutoid;
2570  bool typisvarlena;
2571 
2572  getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2573  val = OidOutputFunctionCall(foutoid, datum);
2574  }
2575  else
2576  val = "null";
2577 
2578  if (idx > 0)
2579  {
2580  appendStringInfoString(&key_names, ", ");
2581  appendStringInfoString(&key_values, ", ");
2582  }
2583  appendStringInfoString(&key_names, name);
2584  appendStringInfoString(&key_values, val);
2585  }
2586  }
2587 
2588  if (partgone)
2589  ereport(ERROR,
2590  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2591  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2592  RelationGetRelationName(pk_rel),
2593  NameStr(riinfo->conname)),
2594  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2595  key_names.data, key_values.data,
2596  RelationGetRelationName(fk_rel)),
2597  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2598  else if (onfk)
2599  ereport(ERROR,
2600  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2601  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2602  RelationGetRelationName(fk_rel),
2603  NameStr(riinfo->conname)),
2604  has_perm ?
2605  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2606  key_names.data, key_values.data,
2607  RelationGetRelationName(pk_rel)) :
2608  errdetail("Key is not present in table \"%s\".",
2609  RelationGetRelationName(pk_rel)),
2610  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2611  else
2612  ereport(ERROR,
2613  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2614  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2615  RelationGetRelationName(pk_rel),
2616  NameStr(riinfo->conname),
2617  RelationGetRelationName(fk_rel)),
2618  has_perm ?
2619  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2620  key_names.data, key_values.data,
2621  RelationGetRelationName(fk_rel)) :
2622  errdetail("Key is still referenced from table \"%s\".",
2623  RelationGetRelationName(fk_rel)),
2624  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2625 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
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:3920
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4091
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
long val
Definition: informix.c:670
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
TupleDesc rd_att
Definition: rel.h:112
Oid rd_id
Definition: rel.h:113

References ACL_SELECT, ACLCHECK_OK, appendStringInfoString(), check_enable_rls(), RI_ConstraintInfo::conname, StringInfoData::data, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), RI_ConstraintInfo::fk_attnums, getTypeOutputInfo(), GetUserId(), idx(), initStringInfo(), InvalidOid, name, NameStr, RI_ConstraintInfo::nkeys, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), RI_ConstraintInfo::pk_attnums, RelationData::rd_att, RelationData::rd_id, 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 624 of file ri_triggers.c.

625 {
626  const RI_ConstraintInfo *riinfo;
627  Relation fk_rel;
628  Relation pk_rel;
629  TupleTableSlot *oldslot;
630  RI_QueryKey qkey;
631  SPIPlanPtr qplan;
632 
633  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
634  trigdata->tg_relation, true);
635 
636  /*
637  * Get the relation descriptors of the FK and PK tables and the old tuple.
638  *
639  * fk_rel is opened in RowShareLock mode since that's what our eventual
640  * SELECT FOR KEY SHARE will get on it.
641  */
642  fk_rel = table_open(riinfo->fk_relid, RowShareLock);
643  pk_rel = trigdata->tg_relation;
644  oldslot = trigdata->tg_trigslot;
645 
646  /*
647  * If another PK row now exists providing the old key values, we should
648  * not do anything. However, this check should only be made in the NO
649  * ACTION case; in RESTRICT cases we don't wish to allow another row to be
650  * substituted.
651  */
652  if (is_no_action &&
653  ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
654  {
655  table_close(fk_rel, RowShareLock);
656  return PointerGetDatum(NULL);
657  }
658 
659  if (SPI_connect() != SPI_OK_CONNECT)
660  elog(ERROR, "SPI_connect failed");
661 
662  /*
663  * Fetch or prepare a saved plan for the restrict lookup (it's the same
664  * query for delete and update cases)
665  */
666  ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_RESTRICT);
667 
668  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
669  {
670  StringInfoData querybuf;
671  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
673  char paramname[16];
674  const char *querysep;
675  Oid queryoids[RI_MAX_NUMKEYS];
676  const char *fk_only;
677 
678  /* ----------
679  * The query string built is
680  * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
681  * FOR KEY SHARE OF x
682  * The type id's for the $ parameters are those of the
683  * corresponding PK attributes.
684  * ----------
685  */
686  initStringInfo(&querybuf);
687  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
688  "" : "ONLY ";
689  quoteRelationName(fkrelname, fk_rel);
690  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
691  fk_only, fkrelname);
692  querysep = "WHERE";
693  for (int i = 0; i < riinfo->nkeys; i++)
694  {
695  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
696  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
697  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
698  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
699 
701  RIAttName(fk_rel, riinfo->fk_attnums[i]));
702  sprintf(paramname, "$%d", i + 1);
703  ri_GenerateQual(&querybuf, querysep,
704  paramname, pk_type,
705  riinfo->pf_eq_oprs[i],
706  attname, fk_type);
707  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
708  ri_GenerateQualCollation(&querybuf, pk_coll);
709  querysep = "AND";
710  queryoids[i] = pk_type;
711  }
712  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
713 
714  /* Prepare and save the plan */
715  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
716  &qkey, fk_rel, pk_rel);
717  }
718 
719  /*
720  * We have a plan now. Run it to check for existing references.
721  */
722  ri_PerformCheck(riinfo, &qkey, qplan,
723  fk_rel, pk_rel,
724  oldslot, NULL,
725  true, /* must detect new rows */
726  SPI_OK_SELECT);
727 
728  if (SPI_finish() != SPI_OK_FINISH)
729  elog(ERROR, "SPI_finish failed");
730 
731  table_close(fk_rel, RowShareLock);
732 
733  return PointerGetDatum(NULL);
734 }
#define RI_PLAN_RESTRICT
Definition: ri_triggers.c:76
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:461

References appendStringInfo(), appendStringInfoString(), attname, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_collation_isdeterministic(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum(), quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_RESTRICT, ri_PlanCheck(), RIAttCollation, RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, 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 1031 of file ri_triggers.c.

1032 {
1033  const RI_ConstraintInfo *riinfo;
1034  Relation fk_rel;
1035  Relation pk_rel;
1036  TupleTableSlot *oldslot;
1037  RI_QueryKey qkey;
1038  SPIPlanPtr qplan;
1039  int32 queryno;
1040 
1041  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1042  trigdata->tg_relation, true);
1043 
1044  /*
1045  * Get the relation descriptors of the FK and PK tables and the old tuple.
1046  *
1047  * fk_rel is opened in RowExclusiveLock mode since that's what our
1048  * eventual UPDATE will get on it.
1049  */
1050  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1051  pk_rel = trigdata->tg_relation;
1052  oldslot = trigdata->tg_trigslot;
1053 
1054  if (SPI_connect() != SPI_OK_CONNECT)
1055  elog(ERROR, "SPI_connect failed");
1056 
1057  /*
1058  * Fetch or prepare a saved plan for the trigger.
1059  */
1060  switch (tgkind)
1061  {
1062  case RI_TRIGTYPE_UPDATE:
1063  queryno = is_set_null
1066  break;
1067  case RI_TRIGTYPE_DELETE:
1068  queryno = is_set_null
1071  break;
1072  default:
1073  elog(ERROR, "invalid tgkind passed to ri_set");
1074  }
1075 
1076  ri_BuildQueryKey(&qkey, riinfo, queryno);
1077 
1078  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1079  {
1080  StringInfoData querybuf;
1081  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1083  char paramname[16];
1084  const char *querysep;
1085  const char *qualsep;
1086  Oid queryoids[RI_MAX_NUMKEYS];
1087  const char *fk_only;
1088  int num_cols_to_set;
1089  const int16 *set_cols;
1090 
1091  switch (tgkind)
1092  {
1093  case RI_TRIGTYPE_UPDATE:
1094  num_cols_to_set = riinfo->nkeys;
1095  set_cols = riinfo->fk_attnums;
1096  break;
1097  case RI_TRIGTYPE_DELETE:
1098 
1099  /*
1100  * If confdelsetcols are present, then we only update the
1101  * columns specified in that array, otherwise we update all
1102  * the referencing columns.
1103  */
1104  if (riinfo->ndelsetcols != 0)
1105  {
1106  num_cols_to_set = riinfo->ndelsetcols;
1107  set_cols = riinfo->confdelsetcols;
1108  }
1109  else
1110  {
1111  num_cols_to_set = riinfo->nkeys;
1112  set_cols = riinfo->fk_attnums;
1113  }
1114  break;
1115  default:
1116  elog(ERROR, "invalid tgkind passed to ri_set");
1117  }
1118 
1119  /* ----------
1120  * The query string built is
1121  * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1122  * WHERE $1 = fkatt1 [AND ...]
1123  * The type id's for the $ parameters are those of the
1124  * corresponding PK attributes.
1125  * ----------
1126  */
1127  initStringInfo(&querybuf);
1128  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1129  "" : "ONLY ";
1130  quoteRelationName(fkrelname, fk_rel);
1131  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1132  fk_only, fkrelname);
1133 
1134  /*
1135  * Add assignment clauses
1136  */
1137  querysep = "";
1138  for (int i = 0; i < num_cols_to_set; i++)
1139  {
1140  quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
1141  appendStringInfo(&querybuf,
1142  "%s %s = %s",
1143  querysep, attname,
1144  is_set_null ? "NULL" : "DEFAULT");
1145  querysep = ",";
1146  }
1147 
1148  /*
1149  * Add WHERE clause
1150  */
1151  qualsep = "WHERE";
1152  for (int i = 0; i < riinfo->nkeys; i++)
1153  {
1154  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1155  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1156  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1157  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1158 
1160  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1161 
1162  sprintf(paramname, "$%d", i + 1);
1163  ri_GenerateQual(&querybuf, qualsep,
1164  paramname, pk_type,
1165  riinfo->pf_eq_oprs[i],
1166  attname, fk_type);
1167  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
1168  ri_GenerateQualCollation(&querybuf, pk_coll);
1169  qualsep = "AND";
1170  queryoids[i] = pk_type;
1171  }
1172 
1173  /* Prepare and save the plan */
1174  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1175  &qkey, fk_rel, pk_rel);
1176  }
1177 
1178  /*
1179  * We have a plan now. Run it to update the existing references.
1180  */
1181  ri_PerformCheck(riinfo, &qkey, qplan,
1182  fk_rel, pk_rel,
1183  oldslot, NULL,
1184  true, /* must detect new rows */
1185  SPI_OK_UPDATE);
1186 
1187  if (SPI_finish() != SPI_OK_FINISH)
1188  elog(ERROR, "SPI_finish failed");
1189 
1190  table_close(fk_rel, RowExclusiveLock);
1191 
1192  if (is_set_null)
1193  return PointerGetDatum(NULL);
1194  else
1195  {
1196  /*
1197  * If we just deleted or updated the PK row whose key was equal to the
1198  * FK columns' default values, and a referencing row exists in the FK
1199  * table, we would have updated that row to the same values it already
1200  * had --- and RI_FKey_fk_upd_check_required would hence believe no
1201  * check is necessary. So we need to do another lookup now and in
1202  * case a reference still exists, abort the operation. That is
1203  * already implemented in the NO ACTION trigger, so just run it. (This
1204  * recheck is only needed in the SET DEFAULT case, since CASCADE would
1205  * remove such rows in case of a DELETE operation or would change the
1206  * FK key values in case of an UPDATE, while SET NULL is certain to
1207  * result in rows that satisfy the FK constraint.)
1208  */
1209  return ri_restrict(trigdata, true);
1210  }
1211 }
signed int int32
Definition: c.h:494
#define RI_PLAN_SETNULL_ONUPDATE
Definition: ri_triggers.c:78
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition: ri_triggers.c:79
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition: ri_triggers.c:80
#define RI_PLAN_SETNULL_ONDELETE
Definition: ri_triggers.c:77

References appendStringInfo(), attname, RI_ConstraintInfo::confdelsetcols, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_collation_isdeterministic(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::ndelsetcols, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum(), quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), ri_GenerateQualCollation(), 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, RIAttCollation, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, 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 175 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 176 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 174 of file ri_triggers.c.

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