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 dclist_head ri_constraint_cache_valid_list
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

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

2198 {
2199  for (;;)
2200  {
2201  HeapTuple tuple;
2202  Oid constrParentOid;
2203 
2204  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2205  if (!HeapTupleIsValid(tuple))
2206  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2207  constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2208  ReleaseSysCache(tuple);
2209  if (!OidIsValid(constrParentOid))
2210  break; /* we reached the root constraint */
2211  constrOid = constrParentOid;
2212  }
2213  return constrOid;
2214 }
#define OidIsValid(objectId)
Definition: c.h:759
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:865
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:817
@ 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 2231 of file ri_triggers.c.

2232 {
2233  dlist_mutable_iter iter;
2234 
2235  Assert(ri_constraint_cache != NULL);
2236 
2237  /*
2238  * If the list of currently valid entries gets excessively large, we mark
2239  * them all invalid so we can empty the list. This arrangement avoids
2240  * O(N^2) behavior in situations where a session touches many foreign keys
2241  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2242  */
2244  hashvalue = 0; /* pretend it's a cache reset */
2245 
2247  {
2249  valid_link, iter.cur);
2250 
2251  /*
2252  * We must invalidate not only entries directly matching the given
2253  * hash value, but also child entries, in case the invalidation
2254  * affects a root constraint.
2255  */
2256  if (hashvalue == 0 ||
2257  riinfo->oidHashValue == hashvalue ||
2258  riinfo->rootHashValue == hashvalue)
2259  {
2260  riinfo->valid = false;
2261  /* Remove invalidated entries from the list, too */
2263  }
2264  }
2265 }
#define dclist_container(type, membername, ptr)
Definition: ilist.h:947
static uint32 dclist_count(const dclist_head *head)
Definition: ilist.h:932
static void dclist_delete_from(dclist_head *head, dlist_node *node)
Definition: ilist.h:763
#define dclist_foreach_modify(iter, lhead)
Definition: ilist.h:973
Assert(fmt[strlen(fmt) - 1] !='\n')
static dclist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:179
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:176
dlist_node * cur
Definition: ilist.h:200

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

Referenced by ri_InitHashTables().

◆ quoteOneName()

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

Definition at line 1876 of file ri_triggers.c.

1877 {
1878  /* Rather than trying to be smart, just always quote it. */
1879  *buffer++ = '"';
1880  while (*name)
1881  {
1882  if (*name == '"')
1883  *buffer++ = '"';
1884  *buffer++ = *name++;
1885  }
1886  *buffer++ = '"';
1887  *buffer = '\0';
1888 }
const char * name
Definition: encode.c:571

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

1897 {
1899  buffer += strlen(buffer);
1900  *buffer++ = '.';
1901  quoteOneName(buffer, RelationGetRelationName(rel));
1902 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
#define RelationGetRelationName(relation)
Definition: rel.h:537
#define RelationGetNamespace(relation)
Definition: rel.h:544
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1876

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

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

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

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

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

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

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

◆ ri_ExtractValues()

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

Definition at line 2452 of file ri_triggers.c.

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

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

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

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

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

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

◆ RI_FKey_cascade_upd()

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 852 of file ri_triggers.c.

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

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

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

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

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

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

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

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

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

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

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 591 of file ri_triggers.c.

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

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

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

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

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

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 611 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1003 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1018 of file ri_triggers.c.

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

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 973 of file ri_triggers.c.

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

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 988 of file ri_triggers.c.

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

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3004 of file ri_triggers.c.

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

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

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

◆ ri_GenerateQual()

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

Definition at line 1913 of file ri_triggers.c.

1918 {
1919  appendStringInfo(buf, " %s ", sep);
1920  generate_operator_clause(buf, leftop, leftoptype, opoid,
1921  rightop, rightoptype);
1922 }
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:11959

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

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

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

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

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

2677 {
2678  HASHCTL ctl;
2679 
2680  ctl.keysize = sizeof(Oid);
2681  ctl.entrysize = sizeof(RI_ConstraintInfo);
2682  ri_constraint_cache = hash_create("RI constraint cache",
2684  &ctl, HASH_ELEM | HASH_BLOBS);
2685 
2686  /* Arrange to flush cache on pg_constraint changes */
2689  (Datum) 0);
2690 
2691  ctl.keysize = sizeof(RI_QueryKey);
2692  ctl.entrysize = sizeof(RI_QueryHashEntry);
2693  ri_query_cache = hash_create("RI query cache",
2695  &ctl, HASH_ELEM | HASH_BLOBS);
2696 
2697  ctl.keysize = sizeof(RI_CompareKey);
2698  ctl.entrysize = sizeof(RI_CompareHashEntry);
2699  ri_compare_cache = hash_create("RI compare cache",
2701  &ctl, HASH_ELEM | HASH_BLOBS);
2702 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#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:2231
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 1368 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

◆ ri_KeysEqual()

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

Definition at line 2798 of file ri_triggers.c.

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

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

Referenced by ri_FetchConstraintInfo().

◆ ri_NullCheck()

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

Definition at line 2639 of file ri_triggers.c.

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

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

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

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

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

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

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

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

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

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

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

dclist_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().