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 "catalog/pg_operator.h"
#include "catalog/pg_type.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 "storage/bufmgr.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 dlist_head ri_constraint_cache_valid_list
 
static int ri_constraint_cache_valid_count = 0
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

Definition at line 85 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 86 of file ri_triggers.c.

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 63 of file ri_triggers.c.

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 64 of file ri_triggers.c.

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 66 of file ri_triggers.c.

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

Definition at line 68 of file ri_triggers.c.

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 67 of file ri_triggers.c.

◆ RI_MAX_NUMKEYS

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS

Definition at line 61 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONDELETE

#define RI_PLAN_CASCADE_ONDELETE   3

Definition at line 76 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONUPDATE

#define RI_PLAN_CASCADE_ONUPDATE   4

Definition at line 77 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 72 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 73 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 74 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   5

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   8

Definition at line 82 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   9

Definition at line 83 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   6

Definition at line 80 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   7

Definition at line 81 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 94 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 92 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 93 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 90 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 88 of file ri_triggers.c.

◆ RIAttType

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

Definition at line 89 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 2190 of file ri_triggers.c.

2191 {
2192  for (;;)
2193  {
2194  HeapTuple tuple;
2195  Oid constrParentOid;
2196 
2197  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2198  if (!HeapTupleIsValid(tuple))
2199  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2200  constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2201  ReleaseSysCache(tuple);
2202  if (!OidIsValid(constrParentOid))
2203  break; /* we reached the root constraint */
2204  constrOid = constrParentOid;
2205  }
2206  return constrOid;
2207 }
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
FormData_pg_constraint * Form_pg_constraint
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ CONSTROID
Definition: syscache.h:53

References CONSTROID, 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 2224 of file ri_triggers.c.

2225 {
2226  dlist_mutable_iter iter;
2227 
2228  Assert(ri_constraint_cache != NULL);
2229 
2230  /*
2231  * If the list of currently valid entries gets excessively large, we mark
2232  * them all invalid so we can empty the list. This arrangement avoids
2233  * O(N^2) behavior in situations where a session touches many foreign keys
2234  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2235  */
2237  hashvalue = 0; /* pretend it's a cache reset */
2238 
2240  {
2242  valid_link, iter.cur);
2243 
2244  /*
2245  * We must invalidate not only entries directly matching the given
2246  * hash value, but also child entries, in case the invalidation
2247  * affects a root constraint.
2248  */
2249  if (hashvalue == 0 ||
2250  riinfo->oidHashValue == hashvalue ||
2251  riinfo->rootHashValue == hashvalue)
2252  {
2253  riinfo->valid = false;
2254  /* Remove invalidated entries from the list, too */
2255  dlist_delete(iter.cur);
2257  }
2258  }
2259 }
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:543
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
Assert(fmt[strlen(fmt) - 1] !='\n')
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:179
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:180
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:176
dlist_node * cur
Definition: ilist.h:180

References Assert(), dlist_mutable_iter::cur, dlist_container, dlist_delete(), dlist_foreach_modify, RI_ConstraintInfo::oidHashValue, ri_constraint_cache, ri_constraint_cache_valid_count, 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 1868 of file ri_triggers.c.

1869 {
1870  /* Rather than trying to be smart, just always quote it. */
1871  *buffer++ = '"';
1872  while (*name)
1873  {
1874  if (*name == '"')
1875  *buffer++ = '"';
1876  *buffer++ = *name++;
1877  }
1878  *buffer++ = '"';
1879  *buffer = '\0';
1880 }
const char * name
Definition: encode.c:561

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

1889 {
1891  buffer += strlen(buffer);
1892  *buffer++ = '.';
1893  quoteOneName(buffer, RelationGetRelationName(rel));
1894 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
#define RelationGetRelationName(relation)
Definition: rel.h:523
#define RelationGetNamespace(relation)
Definition: rel.h:530
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1868

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

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

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

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

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

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

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

2008 {
2009  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2010 
2011  if (!CALLED_AS_TRIGGER(fcinfo))
2012  ereport(ERROR,
2013  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2014  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2015 
2016  /*
2017  * Check proper event
2018  */
2019  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2020  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2021  ereport(ERROR,
2022  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2023  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2024 
2025  switch (tgkind)
2026  {
2027  case RI_TRIGTYPE_INSERT:
2028  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2029  ereport(ERROR,
2030  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2031  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2032  break;
2033  case RI_TRIGTYPE_UPDATE:
2034  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2035  ereport(ERROR,
2036  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2037  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2038  break;
2039  case RI_TRIGTYPE_DELETE:
2040  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2041  ereport(ERROR,
2042  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2043  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2044  break;
2045  }
2046 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ereport(elevel,...)
Definition: elog.h:143
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:92
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:94
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:93
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, 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 2446 of file ri_triggers.c.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

References Assert(), RI_ConstraintInfo::confmatchtype, DatumGetTransactionId, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, MinTransactionIdAttributeNumber, RelationData::rd_rel, RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_ALL_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), slot_getsysattr(), and TransactionIdIsCurrentTransactionId().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 555 of file ri_triggers.c.

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

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 592 of file ri_triggers.c.

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

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

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

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

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

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 612 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1004 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1019 of file ri_triggers.c.

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

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 974 of file ri_triggers.c.

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

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 989 of file ri_triggers.c.

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

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 2998 of file ri_triggers.c.

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

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and ExecCrossPartitionUpdateForeignKey().

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

1910 {
1911  appendStringInfo(buf, " %s ", sep);
1912  generate_operator_clause(buf, leftop, leftoptype, opoid,
1913  rightop, rightoptype);
1914 }
static char * buf
Definition: pg_test_fsync.c:67
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:12600

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

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

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

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

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

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

References Assert(), HASH_ENTER, hash_search(), sort-test::key, RI_QueryHashEntry::plan, ri_InitHashTables(), and ri_query_cache.

Referenced by ri_PlanCheck().

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

Definition at line 2670 of file ri_triggers.c.

2671 {
2672  HASHCTL ctl;
2673 
2674  ctl.keysize = sizeof(Oid);
2675  ctl.entrysize = sizeof(RI_ConstraintInfo);
2676  ri_constraint_cache = hash_create("RI constraint cache",
2678  &ctl, HASH_ELEM | HASH_BLOBS);
2679 
2680  /* Arrange to flush cache on pg_constraint changes */
2683  (Datum) 0);
2684 
2685  ctl.keysize = sizeof(RI_QueryKey);
2686  ctl.entrysize = sizeof(RI_QueryHashEntry);
2687  ri_query_cache = hash_create("RI query cache",
2689  &ctl, HASH_ELEM | HASH_BLOBS);
2690 
2691  ctl.keysize = sizeof(RI_CompareKey);
2692  ctl.entrysize = sizeof(RI_CompareHashEntry);
2693  ri_compare_cache = hash_create("RI compare cache",
2695  &ctl, HASH_ELEM | HASH_BLOBS);
2696 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
#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:1519
struct RI_ConstraintInfo RI_ConstraintInfo
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2224
struct RI_QueryKey RI_QueryKey
struct RI_CompareHashEntry RI_CompareHashEntry
struct RI_QueryHashEntry RI_QueryHashEntry
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:64
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:63
struct RI_CompareKey RI_CompareKey
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76

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

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

◆ RI_Initial_Check()

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

Definition at line 1369 of file ri_triggers.c.

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

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

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

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, CONSTROID, DeconstructFkConstraintRow(), dlist_push_tail(), 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_count, 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 2633 of file ri_triggers.c.

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

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

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

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

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

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

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

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

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

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

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

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

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 178 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_count

int ri_constraint_cache_valid_count = 0
static

Definition at line 180 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_constraint_cache_valid_list

dlist_head ri_constraint_cache_valid_list
static

Definition at line 179 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 177 of file ri_triggers.c.

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