PostgreSQL Source Code  git master
ri_triggers.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.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 "parser/parse_coerce.h"
#include "parser/parse_relation.h"
#include "miscadmin.h"
#include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/builtins.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/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.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_DEL_DODELETE   3
 
#define RI_PLAN_CASCADE_UPD_DOUPDATE   4
 
#define RI_PLAN_RESTRICT_CHECKREF   5
 
#define RI_PLAN_SETNULL_DOUPDATE   6
 
#define RI_PLAN_SETDEFAULT_DOUPDATE   7
 
#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, HeapTuple old_row, const RI_ConstraintInfo *riinfo)
 
static Datum ri_restrict (TriggerData *trigdata, bool is_no_action)
 
static Datum ri_setnull (TriggerData *trigdata)
 
static Datum ri_setdefault (TriggerData *trigdata)
 
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_add_cast_to (StringInfo buf, Oid typid)
 
static void ri_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (HeapTuple tup, 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, HeapTuple oldtup, HeapTuple newtup, 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 SPIPlanPtr ri_PlanCheck (const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
 
static bool ri_PerformCheck (const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
 
static void ri_ExtractValues (Relation rel, HeapTuple tup, 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, HeapTuple violator, TupleDesc tupdesc, int queryno) 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, HeapTuple old_row, HeapTuple new_row)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, HeapTuple old_row, HeapTuple new_row)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

static HTABri_constraint_cache = NULL
 
static HTABri_query_cache = NULL
 
static HTABri_compare_cache = NULL
 
static dlist_head ri_constraint_cache_valid_list
 
static int ri_constraint_cache_valid_count = 0
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

◆ MAX_QUOTED_REL_NAME_LEN

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 69 of file ri_triggers.c.

Referenced by ri_InitHashTables().

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 70 of file ri_triggers.c.

Referenced by ri_InitHashTables().

◆ RI_KEYS_ALL_NULL

◆ RI_KEYS_NONE_NULL

◆ RI_KEYS_SOME_NULL

◆ RI_MAX_NUMKEYS

◆ RI_PLAN_CASCADE_DEL_DODELETE

#define RI_PLAN_CASCADE_DEL_DODELETE   3

Definition at line 82 of file ri_triggers.c.

Referenced by RI_FKey_cascade_del().

◆ RI_PLAN_CASCADE_UPD_DOUPDATE

#define RI_PLAN_CASCADE_UPD_DOUPDATE   4

Definition at line 83 of file ri_triggers.c.

Referenced by RI_FKey_cascade_upd().

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 78 of file ri_triggers.c.

Referenced by RI_FKey_check(), RI_Initial_Check(), ri_PerformCheck(), and ri_ReportViolation().

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 79 of file ri_triggers.c.

Referenced by ri_Check_Pk_Match(), and ri_PerformCheck().

◆ RI_PLAN_LAST_ON_PK

#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK

Definition at line 80 of file ri_triggers.c.

Referenced by ri_PerformCheck(), and ri_PlanCheck().

◆ RI_PLAN_RESTRICT_CHECKREF

#define RI_PLAN_RESTRICT_CHECKREF   5

Definition at line 84 of file ri_triggers.c.

Referenced by ri_restrict().

◆ RI_PLAN_SETDEFAULT_DOUPDATE

#define RI_PLAN_SETDEFAULT_DOUPDATE   7

Definition at line 86 of file ri_triggers.c.

Referenced by ri_setdefault().

◆ RI_PLAN_SETNULL_DOUPDATE

#define RI_PLAN_SETNULL_DOUPDATE   6

Definition at line 85 of file ri_triggers.c.

Referenced by ri_setnull().

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 95 of file ri_triggers.c.

Referenced by ri_CheckTrigger(), and RI_FKey_check_ins().

◆ RI_TRIGTYPE_UPDATE

◆ RIAttCollation

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

Definition at line 93 of file ri_triggers.c.

Referenced by RI_Initial_Check().

◆ RIAttName

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

◆ RIAttType

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

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

Function Documentation

◆ InvalidateConstraintCacheCallBack()

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

Definition at line 2530 of file ri_triggers.c.

References Assert, dlist_mutable_iter::cur, dlist_container, dlist_delete(), dlist_foreach_modify, RI_ConstraintInfo::oidHashValue, ri_constraint_cache_valid_count, RI_ConstraintInfo::valid, and RI_ConstraintInfo::valid_link.

Referenced by ri_InitHashTables().

2531 {
2532  dlist_mutable_iter iter;
2533 
2534  Assert(ri_constraint_cache != NULL);
2535 
2536  /*
2537  * If the list of currently valid entries gets excessively large, we mark
2538  * them all invalid so we can empty the list. This arrangement avoids
2539  * O(N^2) behavior in situations where a session touches many foreign keys
2540  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2541  */
2543  hashvalue = 0; /* pretend it's a cache reset */
2544 
2546  {
2548  valid_link, iter.cur);
2549 
2550  if (hashvalue == 0 || riinfo->oidHashValue == hashvalue)
2551  {
2552  riinfo->valid = false;
2553  /* Remove invalidated entries from the list, too */
2554  dlist_delete(iter.cur);
2556  }
2557  }
2558 }
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:182
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:186
#define Assert(condition)
Definition: c.h:680
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:185

◆ quoteOneName()

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

Definition at line 2106 of file ri_triggers.c.

Referenced by quoteRelationName(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_GenerateQualCollation(), RI_Initial_Check(), ri_restrict(), ri_setdefault(), and ri_setnull().

2107 {
2108  /* Rather than trying to be smart, just always quote it. */
2109  *buffer++ = '"';
2110  while (*name)
2111  {
2112  if (*name == '"')
2113  *buffer++ = '"';
2114  *buffer++ = *name++;
2115  }
2116  *buffer++ = '"';
2117  *buffer = '\0';
2118 }
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
const char * name
Definition: encode.c:521

◆ quoteRelationName()

static void quoteRelationName ( char *  buffer,
Relation  rel 
)
static

Definition at line 2126 of file ri_triggers.c.

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_restrict(), ri_setdefault(), and ri_setnull().

2127 {
2129  buffer += strlen(buffer);
2130  *buffer++ = '.';
2132 }
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define RelationGetRelationName(relation)
Definition: rel.h:445
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
#define RelationGetNamespace(relation)
Definition: rel.h:452

◆ ri_add_cast_to()

static void ri_add_cast_to ( StringInfo  buf,
Oid  typid 
)
static

Definition at line 2187 of file ri_triggers.c.

References appendStringInfo(), elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_identifier(), ReleaseSysCache(), SearchSysCache1(), and TYPEOID.

Referenced by ri_GenerateQual().

2188 {
2189  HeapTuple typetup;
2190  Form_pg_type typform;
2191  char *typname;
2192  char *nspname;
2193 
2194  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2195  if (!HeapTupleIsValid(typetup))
2196  elog(ERROR, "cache lookup failed for type %u", typid);
2197  typform = (Form_pg_type) GETSTRUCT(typetup);
2198 
2199  typname = NameStr(typform->typname);
2200  nspname = get_namespace_name(typform->typnamespace);
2201 
2202  appendStringInfo(buf, "::%s.%s",
2203  quote_identifier(nspname), quote_identifier(typname));
2204 
2205  ReleaseSysCache(typetup);
2206 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10412
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219

◆ ri_AttributesEqual()

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

Definition at line 3144 of file ri_triggers.c.

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

Referenced by ri_KeysEqual().

3146 {
3147  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3148 
3149  /* Do we need to cast the values? */
3150  if (OidIsValid(entry->cast_func_finfo.fn_oid))
3151  {
3152  oldvalue = FunctionCall3(&entry->cast_func_finfo,
3153  oldvalue,
3154  Int32GetDatum(-1), /* typmod */
3155  BoolGetDatum(false)); /* implicit coercion */
3156  newvalue = FunctionCall3(&entry->cast_func_finfo,
3157  newvalue,
3158  Int32GetDatum(-1), /* typmod */
3159  BoolGetDatum(false)); /* implicit coercion */
3160  }
3161 
3162  /*
3163  * Apply the comparison operator. We assume it doesn't care about
3164  * collations.
3165  */
3166  return DatumGetBool(FunctionCall2(&entry->eq_opr_finfo,
3167  oldvalue, newvalue));
3168 }
#define FunctionCall2(flinfo, arg1, arg2)
Definition: fmgr.h:605
#define OidIsValid(objectId)
Definition: c.h:586
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:607
#define DatumGetBool(X)
Definition: postgres.h:399
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3178
#define BoolGetDatum(X)
Definition: postgres.h:408
Oid fn_oid
Definition: fmgr.h:59
#define Int32GetDatum(X)
Definition: postgres.h:485
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:174

◆ ri_BuildQueryKey()

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

Definition at line 2267 of file ri_triggers.c.

References RI_QueryKey::constr_id, RI_QueryKey::constr_queryno, and RI_ConstraintInfo::constraint_id.

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

2269 {
2270  /*
2271  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2272  * to use memset to clear them.
2273  */
2274  key->constr_id = riinfo->constraint_id;
2275  key->constr_queryno = constr_queryno;
2276 }
int32 constr_queryno
Definition: ri_triggers.c:137

◆ ri_Check_Pk_Match()

static bool ri_Check_Pk_Match ( Relation  pk_rel,
Relation  fk_rel,
HeapTuple  old_row,
const RI_ConstraintInfo riinfo 
)
static

Definition at line 508 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), Assert, 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(), 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, and SPI_OK_SELECT.

Referenced by ri_restrict().

511 {
512  SPIPlanPtr qplan;
513  RI_QueryKey qkey;
514  int i;
515  bool result;
516 
517  /* Only called for non-null rows */
518  Assert(ri_NullCheck(old_row, riinfo, true) == RI_KEYS_NONE_NULL);
519 
520  if (SPI_connect() != SPI_OK_CONNECT)
521  elog(ERROR, "SPI_connect failed");
522 
523  /*
524  * Fetch or prepare a saved plan for checking PK table with values coming
525  * from a PK row
526  */
528 
529  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
530  {
531  StringInfoData querybuf;
532  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
533  char attname[MAX_QUOTED_NAME_LEN];
534  char paramname[16];
535  const char *querysep;
536  Oid queryoids[RI_MAX_NUMKEYS];
537 
538  /* ----------
539  * The query string built is
540  * SELECT 1 FROM ONLY <pktable> x WHERE pkatt1 = $1 [AND ...]
541  * FOR KEY SHARE OF x
542  * The type id's for the $ parameters are those of the
543  * PK attributes themselves.
544  * ----------
545  */
546  initStringInfo(&querybuf);
547  quoteRelationName(pkrelname, pk_rel);
548  appendStringInfo(&querybuf, "SELECT 1 FROM ONLY %s x", pkrelname);
549  querysep = "WHERE";
550  for (i = 0; i < riinfo->nkeys; i++)
551  {
552  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
553 
554  quoteOneName(attname,
555  RIAttName(pk_rel, riinfo->pk_attnums[i]));
556  sprintf(paramname, "$%d", i + 1);
557  ri_GenerateQual(&querybuf, querysep,
558  attname, pk_type,
559  riinfo->pp_eq_oprs[i],
560  paramname, pk_type);
561  querysep = "AND";
562  queryoids[i] = pk_type;
563  }
564  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
565 
566  /* Prepare and save the plan */
567  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
568  &qkey, fk_rel, pk_rel, true);
569  }
570 
571  /*
572  * We have a plan now. Run it.
573  */
574  result = ri_PerformCheck(riinfo, &qkey, qplan,
575  fk_rel, pk_rel,
576  old_row, NULL,
577  true, /* treat like update */
578  SPI_OK_SELECT);
579 
580  if (SPI_finish() != SPI_OK_FINISH)
581  elog(ERROR, "SPI_finish failed");
582 
583  return result;
584 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:149
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
unsigned int Oid
Definition: postgres_ext.h:31
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define SPI_OK_SELECT
Definition: spi.h:54
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:79
#define Assert(condition)
Definition: c.h:680
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74

◆ ri_CheckTrigger()

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

Definition at line 2282 of file ri_triggers.c.

References CALLED_AS_TRIGGER, FunctionCallInfoData::context, ereport, errcode(), errmsg(), ERROR, 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().

2283 {
2284  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2285 
2286  if (!CALLED_AS_TRIGGER(fcinfo))
2287  ereport(ERROR,
2288  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2289  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2290 
2291  /*
2292  * Check proper event
2293  */
2294  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2295  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2296  ereport(ERROR,
2297  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2298  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2299 
2300  switch (tgkind)
2301  {
2302  case RI_TRIGTYPE_INSERT:
2303  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2304  ereport(ERROR,
2305  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2306  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2307  break;
2308  case RI_TRIGTYPE_UPDATE:
2309  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2310  ereport(ERROR,
2311  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2312  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2313  break;
2314  case RI_TRIGTYPE_DELETE:
2315  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2316  ereport(ERROR,
2317  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2318  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2319  break;
2320  }
2321 }
fmNodePtr context
Definition: fmgr.h:80
int errcode(int sqlerrcode)
Definition: elog.c:575
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:137
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:119
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:116
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:128
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:95

◆ ri_ExtractValues()

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

Definition at line 2752 of file ri_triggers.c.

References RI_ConstraintInfo::fk_attnums, heap_getattr, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, and RelationData::rd_att.

Referenced by ri_PerformCheck().

2755 {
2756  TupleDesc tupdesc = rel->rd_att;
2757  const int16 *attnums;
2758  int i;
2759  bool isnull;
2760 
2761  if (rel_is_pk)
2762  attnums = riinfo->pk_attnums;
2763  else
2764  attnums = riinfo->fk_attnums;
2765 
2766  for (i = 0; i < riinfo->nkeys; i++)
2767  {
2768  vals[i] = heap_getattr(tup, attnums[i], tupdesc,
2769  &isnull);
2770  nulls[i] = isnull ? 'n' : ' ';
2771  }
2772 }
signed short int16
Definition: c.h:293
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:774
TupleDesc rd_att
Definition: rel.h:115
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120

◆ ri_FetchConstraintInfo()

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

Definition at line 2328 of file ri_triggers.c.

References elog, ereport, errcode(), errhint(), errmsg(), ERROR, RI_ConstraintInfo::fk_relid, 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_restrict(), ri_setdefault(), and ri_setnull().

2329 {
2330  Oid constraintOid = trigger->tgconstraint;
2331  const RI_ConstraintInfo *riinfo;
2332 
2333  /*
2334  * Check that the FK constraint's OID is available; it might not be if
2335  * we've been invoked via an ordinary trigger or an old-style "constraint
2336  * trigger".
2337  */
2338  if (!OidIsValid(constraintOid))
2339  ereport(ERROR,
2340  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2341  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2342  trigger->tgname, RelationGetRelationName(trig_rel)),
2343  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2344 
2345  /* Find or create a hashtable entry for the constraint */
2346  riinfo = ri_LoadConstraintInfo(constraintOid);
2347 
2348  /* Do some easy cross-checks against the trigger call data */
2349  if (rel_is_pk)
2350  {
2351  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2352  riinfo->pk_relid != RelationGetRelid(trig_rel))
2353  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2354  trigger->tgname, RelationGetRelationName(trig_rel));
2355  }
2356  else
2357  {
2358  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2359  riinfo->pk_relid != trigger->tgconstrrelid)
2360  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2361  trigger->tgname, RelationGetRelationName(trig_rel));
2362  }
2363 
2364  return riinfo;
2365 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:445
Oid tgconstrrelid
Definition: reltrigger.h:32
#define ereport(elevel, rest)
Definition: elog.h:122
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2371
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:425

◆ ri_FetchPreparedPlan()

static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 2996 of file ri_triggers.c.

References HASH_FIND, hash_search(), RI_QueryHashEntry::plan, ri_InitHashTables(), 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(), ri_setdefault(), and ri_setnull().

2997 {
2998  RI_QueryHashEntry *entry;
2999  SPIPlanPtr plan;
3000 
3001  /*
3002  * On the first call initialize the hashtable
3003  */
3004  if (!ri_query_cache)
3006 
3007  /*
3008  * Lookup for the key
3009  */
3011  (void *) key,
3012  HASH_FIND, NULL);
3013  if (entry == NULL)
3014  return NULL;
3015 
3016  /*
3017  * Check whether the plan is still valid. If it isn't, we don't want to
3018  * simply rely on plancache.c to regenerate it; rather we should start
3019  * from scratch and rebuild the query text too. This is to cover cases
3020  * such as table/column renames. We depend on the plancache machinery to
3021  * detect possible invalidations, though.
3022  *
3023  * CAUTION: this check is only trustworthy if the caller has already
3024  * locked both FK and PK rels.
3025  */
3026  plan = entry->plan;
3027  if (plan && SPI_plan_is_valid(plan))
3028  return plan;
3029 
3030  /*
3031  * Otherwise we might as well flush the cached plan now, to free a little
3032  * memory space before we make a new one.
3033  */
3034  entry->plan = NULL;
3035  if (plan)
3036  SPI_freeplan(plan);
3037 
3038  return NULL;
3039 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:183
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
SPIPlanPtr plan
Definition: ri_triggers.c:148
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:615
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1497
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2956

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 872 of file ri_triggers.c.

References appendStringInfo(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), 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_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CASCADE_DEL_DODELETE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_DELETE, SPI_OK_FINISH, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

873 {
874  TriggerData *trigdata = (TriggerData *) fcinfo->context;
875  const RI_ConstraintInfo *riinfo;
876  Relation fk_rel;
877  Relation pk_rel;
878  HeapTuple old_row;
879  RI_QueryKey qkey;
880  SPIPlanPtr qplan;
881  int i;
882 
883  /*
884  * Check that this is a valid trigger call on the right time and event.
885  */
886  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
887 
888  /*
889  * Get arguments.
890  */
891  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
892  trigdata->tg_relation, true);
893 
894  /*
895  * Get the relation descriptors of the FK and PK tables and the old tuple.
896  *
897  * fk_rel is opened in RowExclusiveLock mode since that's what our
898  * eventual DELETE will get on it.
899  */
900  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
901  pk_rel = trigdata->tg_relation;
902  old_row = trigdata->tg_trigtuple;
903 
904  switch (riinfo->confmatchtype)
905  {
906  /* ----------
907  * SQL:2008 15.17 <Execution of referential actions>
908  * General rules 9) a) i):
909  * MATCH SIMPLE/FULL
910  * ... ON DELETE CASCADE
911  * ----------
912  */
914  case FKCONSTR_MATCH_FULL:
915  switch (ri_NullCheck(old_row, riinfo, true))
916  {
917  case RI_KEYS_ALL_NULL:
918  case RI_KEYS_SOME_NULL:
919 
920  /*
921  * No check needed - there cannot be any reference to old
922  * key if it contains a NULL
923  */
924  heap_close(fk_rel, RowExclusiveLock);
925  return PointerGetDatum(NULL);
926 
927  case RI_KEYS_NONE_NULL:
928 
929  /*
930  * Have a full qualified key - continue below
931  */
932  break;
933  }
934 
935  if (SPI_connect() != SPI_OK_CONNECT)
936  elog(ERROR, "SPI_connect failed");
937 
938  /*
939  * Fetch or prepare a saved plan for the cascaded delete
940  */
942 
943  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
944  {
945  StringInfoData querybuf;
946  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
947  char attname[MAX_QUOTED_NAME_LEN];
948  char paramname[16];
949  const char *querysep;
950  Oid queryoids[RI_MAX_NUMKEYS];
951 
952  /* ----------
953  * The query string built is
954  * DELETE FROM ONLY <fktable> WHERE $1 = fkatt1 [AND ...]
955  * The type id's for the $ parameters are those of the
956  * corresponding PK attributes.
957  * ----------
958  */
959  initStringInfo(&querybuf);
960  quoteRelationName(fkrelname, fk_rel);
961  appendStringInfo(&querybuf, "DELETE FROM ONLY %s", fkrelname);
962  querysep = "WHERE";
963  for (i = 0; i < riinfo->nkeys; i++)
964  {
965  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
966  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
967 
968  quoteOneName(attname,
969  RIAttName(fk_rel, riinfo->fk_attnums[i]));
970  sprintf(paramname, "$%d", i + 1);
971  ri_GenerateQual(&querybuf, querysep,
972  paramname, pk_type,
973  riinfo->pf_eq_oprs[i],
974  attname, fk_type);
975  querysep = "AND";
976  queryoids[i] = pk_type;
977  }
978 
979  /* Prepare and save the plan */
980  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
981  &qkey, fk_rel, pk_rel, true);
982  }
983 
984  /*
985  * We have a plan now. Build up the arguments from the key values
986  * in the deleted PK tuple and delete the referencing rows
987  */
988  ri_PerformCheck(riinfo, &qkey, qplan,
989  fk_rel, pk_rel,
990  old_row, NULL,
991  true, /* must detect new rows */
992  SPI_OK_DELETE);
993 
994  if (SPI_finish() != SPI_OK_FINISH)
995  elog(ERROR, "SPI_finish failed");
996 
997  heap_close(fk_rel, RowExclusiveLock);
998 
999  return PointerGetDatum(NULL);
1000 
1001  /*
1002  * Handle MATCH PARTIAL cascaded delete.
1003  */
1005  ereport(ERROR,
1006  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1007  errmsg("MATCH PARTIAL not yet implemented")));
1008  return PointerGetDatum(NULL);
1009 
1010  default:
1011  elog(ERROR, "unrecognized confmatchtype: %d",
1012  riinfo->confmatchtype);
1013  break;
1014  }
1015 
1016  /* Never reached */
1017  return PointerGetDatum(NULL);
1018 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
#define SPI_OK_DELETE
Definition: spi.h:57
int SPI_finish(void)
Definition: spi.c:149
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define RI_PLAN_CASCADE_DEL_DODELETE
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
#define RowExclusiveLock
Definition: lockdefs.h:38
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_cascade_upd()

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 1028 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CASCADE_UPD_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

1029 {
1030  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1031  const RI_ConstraintInfo *riinfo;
1032  Relation fk_rel;
1033  Relation pk_rel;
1034  HeapTuple new_row;
1035  HeapTuple old_row;
1036  RI_QueryKey qkey;
1037  SPIPlanPtr qplan;
1038  int i;
1039  int j;
1040 
1041  /*
1042  * Check that this is a valid trigger call on the right time and event.
1043  */
1044  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1045 
1046  /*
1047  * Get arguments.
1048  */
1049  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1050  trigdata->tg_relation, true);
1051 
1052  /*
1053  * Get the relation descriptors of the FK and PK tables and the new and
1054  * old tuple.
1055  *
1056  * fk_rel is opened in RowExclusiveLock mode since that's what our
1057  * eventual UPDATE will get on it.
1058  */
1059  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1060  pk_rel = trigdata->tg_relation;
1061  new_row = trigdata->tg_newtuple;
1062  old_row = trigdata->tg_trigtuple;
1063 
1064  switch (riinfo->confmatchtype)
1065  {
1066  /* ----------
1067  * SQL:2008 15.17 <Execution of referential actions>
1068  * General rules 10) a) i):
1069  * MATCH SIMPLE/FULL
1070  * ... ON UPDATE CASCADE
1071  * ----------
1072  */
1073  case FKCONSTR_MATCH_SIMPLE:
1074  case FKCONSTR_MATCH_FULL:
1075  switch (ri_NullCheck(old_row, riinfo, true))
1076  {
1077  case RI_KEYS_ALL_NULL:
1078  case RI_KEYS_SOME_NULL:
1079 
1080  /*
1081  * No check needed - there cannot be any reference to old
1082  * key if it contains a NULL
1083  */
1084  heap_close(fk_rel, RowExclusiveLock);
1085  return PointerGetDatum(NULL);
1086 
1087  case RI_KEYS_NONE_NULL:
1088 
1089  /*
1090  * Have a full qualified key - continue below
1091  */
1092  break;
1093  }
1094 
1095  /*
1096  * No need to do anything if old and new keys are equal
1097  */
1098  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1099  {
1100  heap_close(fk_rel, RowExclusiveLock);
1101  return PointerGetDatum(NULL);
1102  }
1103 
1104  if (SPI_connect() != SPI_OK_CONNECT)
1105  elog(ERROR, "SPI_connect failed");
1106 
1107  /*
1108  * Fetch or prepare a saved plan for the cascaded update
1109  */
1111 
1112  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1113  {
1114  StringInfoData querybuf;
1115  StringInfoData qualbuf;
1116  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1117  char attname[MAX_QUOTED_NAME_LEN];
1118  char paramname[16];
1119  const char *querysep;
1120  const char *qualsep;
1121  Oid queryoids[RI_MAX_NUMKEYS * 2];
1122 
1123  /* ----------
1124  * The query string built is
1125  * UPDATE ONLY <fktable> SET fkatt1 = $1 [, ...]
1126  * WHERE $n = fkatt1 [AND ...]
1127  * The type id's for the $ parameters are those of the
1128  * corresponding PK attributes. Note that we are assuming
1129  * there is an assignment cast from the PK to the FK type;
1130  * else the parser will fail.
1131  * ----------
1132  */
1133  initStringInfo(&querybuf);
1134  initStringInfo(&qualbuf);
1135  quoteRelationName(fkrelname, fk_rel);
1136  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1137  querysep = "";
1138  qualsep = "WHERE";
1139  for (i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1140  {
1141  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1142  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1143 
1144  quoteOneName(attname,
1145  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1146  appendStringInfo(&querybuf,
1147  "%s %s = $%d",
1148  querysep, attname, i + 1);
1149  sprintf(paramname, "$%d", j + 1);
1150  ri_GenerateQual(&qualbuf, qualsep,
1151  paramname, pk_type,
1152  riinfo->pf_eq_oprs[i],
1153  attname, fk_type);
1154  querysep = ",";
1155  qualsep = "AND";
1156  queryoids[i] = pk_type;
1157  queryoids[j] = pk_type;
1158  }
1159  appendStringInfoString(&querybuf, qualbuf.data);
1160 
1161  /* Prepare and save the plan */
1162  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1163  &qkey, fk_rel, pk_rel, true);
1164  }
1165 
1166  /*
1167  * We have a plan now. Run it to update the existing references.
1168  */
1169  ri_PerformCheck(riinfo, &qkey, qplan,
1170  fk_rel, pk_rel,
1171  old_row, new_row,
1172  true, /* must detect new rows */
1173  SPI_OK_UPDATE);
1174 
1175  if (SPI_finish() != SPI_OK_FINISH)
1176  elog(ERROR, "SPI_finish failed");
1177 
1178  heap_close(fk_rel, RowExclusiveLock);
1179 
1180  return PointerGetDatum(NULL);
1181 
1182  /*
1183  * Handle MATCH PARTIAL cascade update.
1184  */
1186  ereport(ERROR,
1187  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1188  errmsg("MATCH PARTIAL not yet implemented")));
1189  return PointerGetDatum(NULL);
1190 
1191  default:
1192  elog(ERROR, "unrecognized confmatchtype: %d",
1193  riinfo->confmatchtype);
1194  break;
1195  }
1196 
1197  /* Never reached */
1198  return PointerGetDatum(NULL);
1199 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:149
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
#define RowExclusiveLock
Definition: lockdefs.h:38
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define RI_PLAN_CASCADE_UPD_DOUPDATE
Definition: ri_triggers.c:83
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_check()

static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 253 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, 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, heap_close, heap_open(), HeapTupleSatisfiesVisibility, i, initStringInfo(), LockBuffer(), 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(), 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, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_check_ins(), and RI_FKey_check_upd().

254 {
255  const RI_ConstraintInfo *riinfo;
256  Relation fk_rel;
257  Relation pk_rel;
258  HeapTuple new_row;
259  Buffer new_row_buf;
260  RI_QueryKey qkey;
261  SPIPlanPtr qplan;
262  int i;
263 
264  /*
265  * Get arguments.
266  */
267  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
268  trigdata->tg_relation, false);
269 
270  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
271  {
272  new_row = trigdata->tg_newtuple;
273  new_row_buf = trigdata->tg_newtuplebuf;
274  }
275  else
276  {
277  new_row = trigdata->tg_trigtuple;
278  new_row_buf = trigdata->tg_trigtuplebuf;
279  }
280 
281  /*
282  * We should not even consider checking the row if it is no longer valid,
283  * since it was either deleted (so the deferred check should be skipped)
284  * or updated (in which case only the latest version of the row should be
285  * checked). Test its liveness according to SnapshotSelf. We need pin
286  * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
287  * should be holding pin, but not lock.
288  */
289  LockBuffer(new_row_buf, BUFFER_LOCK_SHARE);
290  if (!HeapTupleSatisfiesVisibility(new_row, SnapshotSelf, new_row_buf))
291  {
292  LockBuffer(new_row_buf, BUFFER_LOCK_UNLOCK);
293  return PointerGetDatum(NULL);
294  }
295  LockBuffer(new_row_buf, BUFFER_LOCK_UNLOCK);
296 
297  /*
298  * Get the relation descriptors of the FK and PK tables.
299  *
300  * pk_rel is opened in RowShareLock mode since that's what our eventual
301  * SELECT FOR KEY SHARE will get on it.
302  */
303  fk_rel = trigdata->tg_relation;
304  pk_rel = heap_open(riinfo->pk_relid, RowShareLock);
305 
306  if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
307  ereport(ERROR,
308  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
309  errmsg("MATCH PARTIAL not yet implemented")));
310 
311  switch (ri_NullCheck(new_row, riinfo, false))
312  {
313  case RI_KEYS_ALL_NULL:
314 
315  /*
316  * No further check needed - an all-NULL key passes every type of
317  * foreign key constraint.
318  */
319  heap_close(pk_rel, RowShareLock);
320  return PointerGetDatum(NULL);
321 
322  case RI_KEYS_SOME_NULL:
323 
324  /*
325  * This is the only case that differs between the three kinds of
326  * MATCH.
327  */
328  switch (riinfo->confmatchtype)
329  {
330  case FKCONSTR_MATCH_FULL:
331 
332  /*
333  * Not allowed - MATCH FULL says either all or none of the
334  * attributes can be NULLs
335  */
336  ereport(ERROR,
337  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
338  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
339  RelationGetRelationName(fk_rel),
340  NameStr(riinfo->conname)),
341  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
342  errtableconstraint(fk_rel,
343  NameStr(riinfo->conname))));
344  heap_close(pk_rel, RowShareLock);
345  return PointerGetDatum(NULL);
346 
348 
349  /*
350  * MATCH SIMPLE - if ANY column is null, the key passes
351  * the constraint.
352  */
353  heap_close(pk_rel, RowShareLock);
354  return PointerGetDatum(NULL);
355 
357 
358  /*
359  * MATCH PARTIAL - all non-null columns must match. (not
360  * implemented, can be done by modifying the query below
361  * to only include non-null columns, or by writing a
362  * special version here)
363  */
364  ereport(ERROR,
365  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
366  errmsg("MATCH PARTIAL not yet implemented")));
367  heap_close(pk_rel, RowShareLock);
368  return PointerGetDatum(NULL);
369 
370  default:
371  elog(ERROR, "unrecognized confmatchtype: %d",
372  riinfo->confmatchtype);
373  break;
374  }
375 
376  case RI_KEYS_NONE_NULL:
377 
378  /*
379  * Have a full qualified key - continue below for all three kinds
380  * of MATCH.
381  */
382  break;
383  }
384 
385  if (SPI_connect() != SPI_OK_CONNECT)
386  elog(ERROR, "SPI_connect failed");
387 
388  /*
389  * Fetch or prepare a saved plan for the real check
390  */
392 
393  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
394  {
395  StringInfoData querybuf;
396  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
397  char attname[MAX_QUOTED_NAME_LEN];
398  char paramname[16];
399  const char *querysep;
400  Oid queryoids[RI_MAX_NUMKEYS];
401 
402  /* ----------
403  * The query string built is
404  * SELECT 1 FROM ONLY <pktable> x WHERE pkatt1 = $1 [AND ...]
405  * FOR KEY SHARE OF x
406  * The type id's for the $ parameters are those of the
407  * corresponding FK attributes.
408  * ----------
409  */
410  initStringInfo(&querybuf);
411  quoteRelationName(pkrelname, pk_rel);
412  appendStringInfo(&querybuf, "SELECT 1 FROM ONLY %s x", pkrelname);
413  querysep = "WHERE";
414  for (i = 0; i < riinfo->nkeys; i++)
415  {
416  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
417  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
418 
419  quoteOneName(attname,
420  RIAttName(pk_rel, riinfo->pk_attnums[i]));
421  sprintf(paramname, "$%d", i + 1);
422  ri_GenerateQual(&querybuf, querysep,
423  attname, pk_type,
424  riinfo->pf_eq_oprs[i],
425  paramname, fk_type);
426  querysep = "AND";
427  queryoids[i] = fk_type;
428  }
429  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
430 
431  /* Prepare and save the plan */
432  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
433  &qkey, fk_rel, pk_rel, true);
434  }
435 
436  /*
437  * Now check that foreign key exists in PK table
438  */
439  ri_PerformCheck(riinfo, &qkey, qplan,
440  fk_rel, pk_rel,
441  NULL, new_row,
442  false,
443  SPI_OK_SELECT);
444 
445  if (SPI_finish() != SPI_OK_FINISH)
446  elog(ERROR, "SPI_finish failed");
447 
448  heap_close(pk_rel, RowShareLock);
449 
450  return PointerGetDatum(NULL);
451 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
Buffer tg_newtuplebuf
Definition: trigger.h:39
int SPI_finish(void)
Definition: spi.c:149
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
HeapTuple tg_trigtuple
Definition: trigger.h:35
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5267
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
Buffer tg_trigtuplebuf
Definition: trigger.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
#define RelationGetRelationName(relation)
Definition: rel.h:445
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define SnapshotSelf
Definition: tqual.h:27
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
#define RowShareLock
Definition: lockdefs.h:37
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define SPI_OK_SELECT
Definition: spi.h:54
TriggerEvent tg_event
Definition: trigger.h:33
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:557
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
int Buffer
Definition: buf.h:23
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_check_ins()

Datum RI_FKey_check_ins ( PG_FUNCTION_ARGS  )

Definition at line 461 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

462 {
463  /*
464  * Check that this is a valid trigger call on the right time and event.
465  */
466  ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
467 
468  /*
469  * Share code with UPDATE case.
470  */
471  return RI_FKey_check((TriggerData *) fcinfo->context);
472 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:253
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:95

◆ RI_FKey_check_upd()

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS  )

Definition at line 482 of file ri_triggers.c.

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

483 {
484  /*
485  * Check that this is a valid trigger call on the right time and event.
486  */
487  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
488 
489  /*
490  * Share code with INSERT case.
491  */
492  return RI_FKey_check((TriggerData *) fcinfo->context);
493 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:253
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
HeapTuple  old_row,
HeapTuple  new_row 
)

Definition at line 1718 of file ri_triggers.c.

References RI_ConstraintInfo::confmatchtype, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, HeapTupleHeaderGetXmin, ri_FetchConstraintInfo(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), HeapTupleData::t_data, and TransactionIdIsCurrentTransactionId().

Referenced by AfterTriggerSaveEvent().

1720 {
1721  const RI_ConstraintInfo *riinfo;
1722 
1723  /*
1724  * Get arguments.
1725  */
1726  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1727 
1728  switch (riinfo->confmatchtype)
1729  {
1730  case FKCONSTR_MATCH_SIMPLE:
1731 
1732  /*
1733  * If any new key value is NULL, the row must satisfy the
1734  * constraint, so no check is needed.
1735  */
1736  if (ri_NullCheck(new_row, riinfo, false) != RI_KEYS_NONE_NULL)
1737  return false;
1738 
1739  /*
1740  * If the original row was inserted by our own transaction, we
1741  * must fire the trigger whether or not the keys are equal. This
1742  * is because our UPDATE will invalidate the INSERT so that the
1743  * INSERT RI trigger will not do anything; so we had better do the
1744  * UPDATE check. (We could skip this if we knew the INSERT
1745  * trigger already fired, but there is no easy way to know that.)
1746  */
1748  return true;
1749 
1750  /* If all old and new key values are equal, no check is needed */
1751  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
1752  return false;
1753 
1754  /* Else we need to fire the trigger. */
1755  return true;
1756 
1757  case FKCONSTR_MATCH_FULL:
1758 
1759  /*
1760  * If all new key values are NULL, the row must satisfy the
1761  * constraint, so no check is needed. On the other hand, if only
1762  * some of them are NULL, the row must fail the constraint. We
1763  * must not throw error here, because the row might get
1764  * invalidated before the constraint is to be checked, but we
1765  * should queue the event to apply the check later.
1766  */
1767  switch (ri_NullCheck(new_row, riinfo, false))
1768  {
1769  case RI_KEYS_ALL_NULL:
1770  return false;
1771  case RI_KEYS_SOME_NULL:
1772  return true;
1773  case RI_KEYS_NONE_NULL:
1774  break; /* continue with the check */
1775  }
1776 
1777  /*
1778  * If the original row was inserted by our own transaction, we
1779  * must fire the trigger whether or not the keys are equal. This
1780  * is because our UPDATE will invalidate the INSERT so that the
1781  * INSERT RI trigger will not do anything; so we had better do the
1782  * UPDATE check. (We could skip this if we knew the INSERT
1783  * trigger already fired, but there is no easy way to know that.)
1784  */
1786  return true;
1787 
1788  /* If all old and new key values are equal, no check is needed */
1789  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
1790  return false;
1791 
1792  /* Else we need to fire the trigger. */
1793  return true;
1794 
1795  /* Handle MATCH PARTIAL check. */
1797  ereport(ERROR,
1798  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1799  errmsg("MATCH PARTIAL not yet implemented")));
1800  break;
1801 
1802  default:
1803  elog(ERROR, "unrecognized confmatchtype: %d",
1804  riinfo->confmatchtype);
1805  break;
1806  }
1807 
1808  /* Never reached */
1809  return false;
1810 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:766
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 596 of file ri_triggers.c.

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

597 {
598  /*
599  * Check that this is a valid trigger call on the right time and event.
600  */
601  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
602 
603  /*
604  * Share code with RESTRICT/UPDATE cases.
605  */
606  return ri_restrict((TriggerData *) fcinfo->context, true);
607 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:689
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 643 of file ri_triggers.c.

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

644 {
645  /*
646  * Check that this is a valid trigger call on the right time and event.
647  */
648  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
649 
650  /*
651  * Share code with RESTRICT/DELETE cases.
652  */
653  return ri_restrict((TriggerData *) fcinfo->context, true);
654 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:689
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_pk_upd_check_required()

bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
HeapTuple  old_row,
HeapTuple  new_row 
)

Definition at line 1661 of file ri_triggers.c.

References RI_ConstraintInfo::confmatchtype, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, ri_FetchConstraintInfo(), RI_KEYS_NONE_NULL, ri_KeysEqual(), and ri_NullCheck().

Referenced by AfterTriggerSaveEvent().

1663 {
1664  const RI_ConstraintInfo *riinfo;
1665 
1666  /*
1667  * Get arguments.
1668  */
1669  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1670 
1671  switch (riinfo->confmatchtype)
1672  {
1673  case FKCONSTR_MATCH_SIMPLE:
1674  case FKCONSTR_MATCH_FULL:
1675 
1676  /*
1677  * If any old key value is NULL, the row could not have been
1678  * referenced by an FK row, so no check is needed.
1679  */
1680  if (ri_NullCheck(old_row, riinfo, true) != RI_KEYS_NONE_NULL)
1681  return false;
1682 
1683  /* If all old and new key values are equal, no check is needed */
1684  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1685  return false;
1686 
1687  /* Else we need to fire the trigger. */
1688  return true;
1689 
1690  /* Handle MATCH PARTIAL check. */
1692  ereport(ERROR,
1693  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1694  errmsg("MATCH PARTIAL not yet implemented")));
1695  break;
1696 
1697  default:
1698  elog(ERROR, "unrecognized confmatchtype: %d",
1699  riinfo->confmatchtype);
1700  break;
1701  }
1702 
1703  /* Never reached */
1704  return false;
1705 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084

◆ RI_FKey_restrict_del()

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 621 of file ri_triggers.c.

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

622 {
623  /*
624  * Check that this is a valid trigger call on the right time and event.
625  */
626  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
627 
628  /*
629  * Share code with NO ACTION/UPDATE cases.
630  */
631  return ri_restrict((TriggerData *) fcinfo->context, false);
632 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:689
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 668 of file ri_triggers.c.

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

669 {
670  /*
671  * Check that this is a valid trigger call on the right time and event.
672  */
673  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
674 
675  /*
676  * Share code with NO ACTION/DELETE cases.
677  */
678  return ri_restrict((TriggerData *) fcinfo->context, false);
679 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:689
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1426 of file ri_triggers.c.

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

1427 {
1428  /*
1429  * Check that this is a valid trigger call on the right time and event.
1430  */
1431  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1432 
1433  /*
1434  * Share code with UPDATE case
1435  */
1436  return ri_setdefault((TriggerData *) fcinfo->context);
1437 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
static Datum ri_setdefault(TriggerData *trigdata)
Definition: ri_triggers.c:1466
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1446 of file ri_triggers.c.

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

1447 {
1448  /*
1449  * Check that this is a valid trigger call on the right time and event.
1450  */
1451  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1452 
1453  /*
1454  * Share code with DELETE case
1455  */
1456  return ri_setdefault((TriggerData *) fcinfo->context);
1457 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
static Datum ri_setdefault(TriggerData *trigdata)
Definition: ri_triggers.c:1466
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1209 of file ri_triggers.c.

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

1210 {
1211  /*
1212  * Check that this is a valid trigger call on the right time and event.
1213  */
1214  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1215 
1216  /*
1217  * Share code with UPDATE case
1218  */
1219  return ri_setnull((TriggerData *) fcinfo->context);
1220 }
static Datum ri_setnull(TriggerData *trigdata)
Definition: ri_triggers.c:1249
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1229 of file ri_triggers.c.

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

1230 {
1231  /*
1232  * Check that this is a valid trigger call on the right time and event.
1233  */
1234  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1235 
1236  /*
1237  * Share code with DELETE case
1238  */
1239  return ri_setnull((TriggerData *) fcinfo->context);
1240 }
static Datum ri_setnull(TriggerData *trigdata)
Definition: ri_triggers.c:1249
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2282
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3271 of file ri_triggers.c.

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and CreateTrigger().

3272 {
3273  switch (tgfoid)
3274  {
3275  case F_RI_FKEY_CASCADE_DEL:
3276  case F_RI_FKEY_CASCADE_UPD:
3277  case F_RI_FKEY_RESTRICT_DEL:
3278  case F_RI_FKEY_RESTRICT_UPD:
3279  case F_RI_FKEY_SETNULL_DEL:
3280  case F_RI_FKEY_SETNULL_UPD:
3281  case F_RI_FKEY_SETDEFAULT_DEL:
3282  case F_RI_FKEY_SETDEFAULT_UPD:
3283  case F_RI_FKEY_NOACTION_DEL:
3284  case F_RI_FKEY_NOACTION_UPD:
3285  return RI_TRIGGER_PK;
3286 
3287  case F_RI_FKEY_CHECK_INS:
3288  case F_RI_FKEY_CHECK_UPD:
3289  return RI_TRIGGER_FK;
3290  }
3291 
3292  return RI_TRIGGER_NONE;
3293 }
#define RI_TRIGGER_FK
Definition: trigger.h:267
#define RI_TRIGGER_PK
Definition: trigger.h:266
#define RI_TRIGGER_NONE
Definition: trigger.h:268

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

References appendStringInfo(), appendStringInfoString(), Assert, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, OPEROID, quote_identifier(), ReleaseSysCache(), ri_add_cast_to(), and SearchSysCache1().

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_Initial_Check(), ri_restrict(), ri_setdefault(), and ri_setnull().

2151 {
2152  HeapTuple opertup;
2153  Form_pg_operator operform;
2154  char *oprname;
2155  char *nspname;
2156 
2157  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
2158  if (!HeapTupleIsValid(opertup))
2159  elog(ERROR, "cache lookup failed for operator %u", opoid);
2160  operform = (Form_pg_operator) GETSTRUCT(opertup);
2161  Assert(operform->oprkind == 'b');
2162  oprname = NameStr(operform->oprname);
2163 
2164  nspname = get_namespace_name(operform->oprnamespace);
2165 
2166  appendStringInfo(buf, " %s %s", sep, leftop);
2167  if (leftoptype != operform->oprleft)
2168  ri_add_cast_to(buf, operform->oprleft);
2169  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
2170  appendStringInfoString(buf, oprname);
2171  appendStringInfo(buf, ") %s", rightop);
2172  if (rightoptype != operform->oprright)
2173  ri_add_cast_to(buf, operform->oprright);
2174 
2175  ReleaseSysCache(opertup);
2176 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10412
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:680
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:57
#define NameStr(name)
Definition: c.h:557
static void ri_add_cast_to(StringInfo buf, Oid typid)
Definition: ri_triggers.c:2187
#define elog
Definition: elog.h:219

◆ ri_GenerateQualCollation()

static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 2226 of file ri_triggers.c.

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

Referenced by RI_Initial_Check().

2227 {
2228  HeapTuple tp;
2229  Form_pg_collation colltup;
2230  char *collname;
2231  char onename[MAX_QUOTED_NAME_LEN];
2232 
2233  /* Nothing to do if it's a noncollatable data type */
2234  if (!OidIsValid(collation))
2235  return;
2236 
2237  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2238  if (!HeapTupleIsValid(tp))
2239  elog(ERROR, "cache lookup failed for collation %u", collation);
2240  colltup = (Form_pg_collation) GETSTRUCT(tp);
2241  collname = NameStr(colltup->collname);
2242 
2243  /*
2244  * We qualify the name always, for simplicity and to ensure the query is
2245  * not search-path-dependent.
2246  */
2247  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2248  appendStringInfo(buf, " COLLATE %s", onename);
2249  quoteOneName(onename, collname);
2250  appendStringInfo(buf, ".%s", onename);
2251 
2252  ReleaseSysCache(tp);
2253 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define OidIsValid(objectId)
Definition: c.h:586
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:52
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219

◆ ri_HashCompareOp()

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

Definition at line 3178 of file ri_triggers.c.

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

Referenced by ri_AttributesEqual().

3179 {
3180  RI_CompareKey key;
3181  RI_CompareHashEntry *entry;
3182  bool found;
3183 
3184  /*
3185  * On the first call initialize the hashtable
3186  */
3187  if (!ri_compare_cache)
3189 
3190  /*
3191  * Find or create a hash entry. Note we're assuming RI_CompareKey
3192  * contains no struct padding.
3193  */
3194  key.eq_opr = eq_opr;
3195  key.typeid = typeid;
3197  (void *) &key,
3198  HASH_ENTER, &found);
3199  if (!found)
3200  entry->valid = false;
3201 
3202  /*
3203  * If not already initialized, do so. Since we'll keep this hash entry
3204  * for the life of the backend, put any subsidiary info for the function
3205  * cache structs into TopMemoryContext.
3206  */
3207  if (!entry->valid)
3208  {
3209  Oid lefttype,
3210  righttype,
3211  castfunc;
3212  CoercionPathType pathtype;
3213 
3214  /* We always need to know how to call the equality operator */
3215  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3217 
3218  /*
3219  * If we chose to use a cast from FK to PK type, we may have to apply
3220  * the cast function to get to the operator's input type.
3221  *
3222  * XXX eventually it would be good to support array-coercion cases
3223  * here and in ri_AttributesEqual(). At the moment there is no point
3224  * because cases involving nonidentical array types will be rejected
3225  * at constraint creation time.
3226  *
3227  * XXX perhaps also consider supporting CoerceViaIO? No need at the
3228  * moment since that will never be generated for implicit coercions.
3229  */
3230  op_input_types(eq_opr, &lefttype, &righttype);
3231  Assert(lefttype == righttype);
3232  if (typeid == lefttype)
3233  castfunc = InvalidOid; /* simplest case */
3234  else
3235  {
3236  pathtype = find_coercion_pathway(lefttype, typeid,
3238  &castfunc);
3239  if (pathtype != COERCION_PATH_FUNC &&
3240  pathtype != COERCION_PATH_RELABELTYPE)
3241  {
3242  /*
3243  * The declared input type of the eq_opr might be a
3244  * polymorphic type such as ANYARRAY or ANYENUM, or other
3245  * special cases such as RECORD; find_coercion_pathway
3246  * currently doesn't subsume these special cases.
3247  */
3248  if (!IsBinaryCoercible(typeid, lefttype))
3249  elog(ERROR, "no conversion function from %s to %s",
3250  format_type_be(typeid),
3251  format_type_be(lefttype));
3252  }
3253  }
3254  if (OidIsValid(castfunc))
3255  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3257  else
3259  entry->valid = true;
3260  }
3261 
3262  return entry;
3263 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:586
CoercionPathType
Definition: parse_coerce.h:24
#define ERROR
Definition: elog.h:43
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1167
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:132
MemoryContext TopMemoryContext
Definition: mcxt.c:43
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
Oid fn_oid
Definition: fmgr.h:59
#define Assert(condition)
Definition: c.h:680
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2956
#define elog
Definition: elog.h:219
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:174
static HTAB * ri_compare_cache
Definition: ri_triggers.c:184

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 3049 of file ri_triggers.c.

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

Referenced by ri_PlanCheck().

3050 {
3051  RI_QueryHashEntry *entry;
3052  bool found;
3053 
3054  /*
3055  * On the first call initialize the hashtable
3056  */
3057  if (!ri_query_cache)
3059 
3060  /*
3061  * Add the new plan. We might be overwriting an entry previously found
3062  * invalid by ri_FetchPreparedPlan.
3063  */
3065  (void *) key,
3066  HASH_ENTER, &found);
3067  Assert(!found || entry->plan == NULL);
3068  entry->plan = plan;
3069 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:183
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
SPIPlanPtr plan
Definition: ri_triggers.c:148
#define Assert(condition)
Definition: c.h:680
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2956

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

Definition at line 2956 of file ri_triggers.c.

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

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

2957 {
2958  HASHCTL ctl;
2959 
2960  memset(&ctl, 0, sizeof(ctl));
2961  ctl.keysize = sizeof(Oid);
2962  ctl.entrysize = sizeof(RI_ConstraintInfo);
2963  ri_constraint_cache = hash_create("RI constraint cache",
2965  &ctl, HASH_ELEM | HASH_BLOBS);
2966 
2967  /* Arrange to flush cache on pg_constraint changes */
2970  (Datum) 0);
2971 
2972  memset(&ctl, 0, sizeof(ctl));
2973  ctl.keysize = sizeof(RI_QueryKey);
2974  ctl.entrysize = sizeof(RI_QueryHashEntry);
2975  ri_query_cache = hash_create("RI query cache",
2977  &ctl, HASH_ELEM | HASH_BLOBS);
2978 
2979  memset(&ctl, 0, sizeof(ctl));
2980  ctl.keysize = sizeof(RI_CompareKey);
2981  ctl.entrysize = sizeof(RI_CompareHashEntry);
2982  ri_compare_cache = hash_create("RI compare cache",
2984  &ctl, HASH_ELEM | HASH_BLOBS);
2985 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:183
struct RI_CompareKey RI_CompareKey
#define HASH_ELEM
Definition: hsearch.h:87
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:182
Size entrysize
Definition: hsearch.h:73
unsigned int Oid
Definition: postgres_ext.h:31
struct RI_ConstraintInfo RI_ConstraintInfo
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:70
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2530
struct RI_CompareHashEntry RI_CompareHashEntry
#define HASH_BLOBS
Definition: hsearch.h:88
struct RI_QueryKey RI_QueryKey
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1389
uintptr_t Datum
Definition: postgres.h:372
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:69
static HTAB * ri_compare_cache
Definition: ri_triggers.c:184
struct RI_QueryHashEntry RI_QueryHashEntry

◆ RI_Initial_Check()

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

Definition at line 1831 of file ri_triggers.c.

References ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecCheckRTPerms(), FirstLowInvalidHeapAttributeNumber, RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_bypassrls_privilege(), i, initStringInfo(), InvalidSnapshot, list_make2, maintenance_work_mem, makeNode, MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, NewGUCNestLevel(), RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, pg_class_ownercheck(), PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::requiredPerms, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_KEYS_NONE_NULL, ri_NullCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, RTE_RELATION, RangeTblEntry::rtekind, RangeTblEntry::selectedCols, set_config_option(), snprintf(), SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by validateForeignKeyConstraint().

1832 {
1833  const RI_ConstraintInfo *riinfo;
1834  StringInfoData querybuf;
1835  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1836  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1837  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1838  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1839  RangeTblEntry *pkrte;
1840  RangeTblEntry *fkrte;
1841  const char *sep;
1842  int i;
1843  int save_nestlevel;
1844  char workmembuf[32];
1845  int spi_result;
1846  SPIPlanPtr qplan;
1847 
1848  /* Fetch constraint info. */
1849  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1850 
1851  /*
1852  * Check to make sure current user has enough permissions to do the test
1853  * query. (If not, caller can fall back to the trigger method, which
1854  * works because it changes user IDs on the fly.)
1855  *
1856  * XXX are there any other show-stopper conditions to check?
1857  */
1858  pkrte = makeNode(RangeTblEntry);
1859  pkrte->rtekind = RTE_RELATION;
1860  pkrte->relid = RelationGetRelid(pk_rel);
1861  pkrte->relkind = pk_rel->rd_rel->relkind;
1862  pkrte->requiredPerms = ACL_SELECT;
1863 
1864  fkrte = makeNode(RangeTblEntry);
1865  fkrte->rtekind = RTE_RELATION;
1866  fkrte->relid = RelationGetRelid(fk_rel);
1867  fkrte->relkind = fk_rel->rd_rel->relkind;
1868  fkrte->requiredPerms = ACL_SELECT;
1869 
1870  for (i = 0; i < riinfo->nkeys; i++)
1871  {
1872  int attno;
1873 
1874  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1875  pkrte->selectedCols = bms_add_member(pkrte->selectedCols, attno);
1876 
1877  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1878  fkrte->selectedCols = bms_add_member(fkrte->selectedCols, attno);
1879  }
1880 
1881  if (!ExecCheckRTPerms(list_make2(fkrte, pkrte), false))
1882  return false;
1883 
1884  /*
1885  * Also punt if RLS is enabled on either table unless this role has the
1886  * bypassrls right or is the table owner of the table(s) involved which
1887  * have RLS enabled.
1888  */
1890  ((pk_rel->rd_rel->relrowsecurity &&
1891  !pg_class_ownercheck(pkrte->relid, GetUserId())) ||
1892  (fk_rel->rd_rel->relrowsecurity &&
1893  !pg_class_ownercheck(fkrte->relid, GetUserId()))))
1894  return false;
1895 
1896  /*----------
1897  * The query string built is:
1898  * SELECT fk.keycols FROM ONLY relname fk
1899  * LEFT OUTER JOIN ONLY pkrelname pk
1900  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1901  * WHERE pk.pkkeycol1 IS NULL AND
1902  * For MATCH SIMPLE:
1903  * (fk.keycol1 IS NOT NULL [AND ...])
1904  * For MATCH FULL:
1905  * (fk.keycol1 IS NOT NULL [OR ...])
1906  *
1907  * We attach COLLATE clauses to the operators when comparing columns
1908  * that have different collations.
1909  *----------
1910  */
1911  initStringInfo(&querybuf);
1912  appendStringInfoString(&querybuf, "SELECT ");
1913  sep = "";
1914  for (i = 0; i < riinfo->nkeys; i++)
1915  {
1916  quoteOneName(fkattname,
1917  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1918  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1919  sep = ", ";
1920  }
1921 
1922  quoteRelationName(pkrelname, pk_rel);
1923  quoteRelationName(fkrelname, fk_rel);
1924  appendStringInfo(&querybuf,
1925  " FROM ONLY %s fk LEFT OUTER JOIN ONLY %s pk ON",
1926  fkrelname, pkrelname);
1927 
1928  strcpy(pkattname, "pk.");
1929  strcpy(fkattname, "fk.");
1930  sep = "(";
1931  for (i = 0; i < riinfo->nkeys; i++)
1932  {
1933  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1934  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1935  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1936  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1937 
1938  quoteOneName(pkattname + 3,
1939  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1940  quoteOneName(fkattname + 3,
1941  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1942  ri_GenerateQual(&querybuf, sep,
1943  pkattname, pk_type,
1944  riinfo->pf_eq_oprs[i],
1945  fkattname, fk_type);
1946  if (pk_coll != fk_coll)
1947  ri_GenerateQualCollation(&querybuf, pk_coll);
1948  sep = "AND";
1949  }
1950 
1951  /*
1952  * It's sufficient to test any one pk attribute for null to detect a join
1953  * failure.
1954  */
1955  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1956  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1957 
1958  sep = "";
1959  for (i = 0; i < riinfo->nkeys; i++)
1960  {
1961  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1962  appendStringInfo(&querybuf,
1963  "%sfk.%s IS NOT NULL",
1964  sep, fkattname);
1965  switch (riinfo->confmatchtype)
1966  {
1967  case FKCONSTR_MATCH_SIMPLE:
1968  sep = " AND ";
1969  break;
1970  case FKCONSTR_MATCH_FULL:
1971  sep = " OR ";
1972  break;
1974  ereport(ERROR,
1975  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1976  errmsg("MATCH PARTIAL not yet implemented")));
1977  break;
1978  default:
1979  elog(ERROR, "unrecognized confmatchtype: %d",
1980  riinfo->confmatchtype);
1981  break;
1982  }
1983  }
1984  appendStringInfoChar(&querybuf, ')');
1985 
1986  /*
1987  * Temporarily increase work_mem so that the check query can be executed
1988  * more efficiently. It seems okay to do this because the query is simple
1989  * enough to not use a multiple of work_mem, and one typically would not
1990  * have many large foreign-key validations happening concurrently. So
1991  * this seems to meet the criteria for being considered a "maintenance"
1992  * operation, and accordingly we use maintenance_work_mem.
1993  *
1994  * We use the equivalent of a function SET option to allow the setting to
1995  * persist for exactly the duration of the check query. guc.c also takes
1996  * care of undoing the setting on error.
1997  */
1998  save_nestlevel = NewGUCNestLevel();
1999 
2000  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
2001  (void) set_config_option("work_mem", workmembuf,
2003  GUC_ACTION_SAVE, true, 0, false);
2004 
2005  if (SPI_connect() != SPI_OK_CONNECT)
2006  elog(ERROR, "SPI_connect failed");
2007 
2008  /*
2009  * Generate the plan. We don't need to cache it, and there are no
2010  * arguments to the plan.
2011  */
2012  qplan = SPI_prepare(querybuf.data, 0, NULL);
2013 
2014  if (qplan == NULL)
2015  elog(ERROR, "SPI_prepare returned %s for %s",
2017 
2018  /*
2019  * Run the plan. For safety we force a current snapshot to be used. (In
2020  * transaction-snapshot mode, this arguably violates transaction isolation
2021  * rules, but we really haven't got much choice.) We don't need to
2022  * register the snapshot, because SPI_execute_snapshot will see to it. We
2023  * need at most one tuple returned, so pass limit = 1.
2024  */
2025  spi_result = SPI_execute_snapshot(qplan,
2026  NULL, NULL,
2029  true, false, 1);
2030 
2031  /* Check result */
2032  if (spi_result != SPI_OK_SELECT)
2033  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2034 
2035  /* Did we find a tuple violating the constraint? */
2036  if (SPI_processed > 0)
2037  {
2038  HeapTuple tuple = SPI_tuptable->vals[0];
2039  TupleDesc tupdesc = SPI_tuptable->tupdesc;
2040  RI_ConstraintInfo fake_riinfo;
2041 
2042  /*
2043  * The columns to look at in the result tuple are 1..N, not whatever
2044  * they are in the fk_rel. Hack up riinfo so that the subroutines
2045  * called here will behave properly.
2046  *
2047  * In addition to this, we have to pass the correct tupdesc to
2048  * ri_ReportViolation, overriding its normal habit of using the pk_rel
2049  * or fk_rel's tupdesc.
2050  */
2051  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
2052  for (i = 0; i < fake_riinfo.nkeys; i++)
2053  fake_riinfo.fk_attnums[i] = i + 1;
2054 
2055  /*
2056  * If it's MATCH FULL, and there are any nulls in the FK keys,
2057  * complain about that rather than the lack of a match. MATCH FULL
2058  * disallows partially-null FK rows.
2059  */
2060  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
2061  ri_NullCheck(tuple, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
2062  ereport(ERROR,
2063  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2064  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2065  RelationGetRelationName(fk_rel),
2066  NameStr(fake_riinfo.conname)),
2067  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
2068  errtableconstraint(fk_rel,
2069  NameStr(fake_riinfo.conname))));
2070 
2071  /*
2072  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
2073  * query, which isn't true, but will cause it to use
2074  * fake_riinfo.fk_attnums as we need.
2075  */
2076  ri_ReportViolation(&fake_riinfo,
2077  pk_rel, fk_rel,
2078  tuple, tupdesc,
2080  }
2081 
2082  if (SPI_finish() != SPI_OK_FINISH)
2083  elog(ERROR, "SPI_finish failed");
2084 
2085  /*
2086  * Restore work_mem.
2087  */
2088  AtEOXact_GUC(true, save_nestlevel);
2089 
2090  return true;
2091 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:2226
#define list_make2(x1, x2)
Definition: pg_list.h:140
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno) pg_attribute_noreturn()
Definition: ri_triggers.c:2784
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
Oid GetUserId(void)
Definition: miscinit.c:284
int SPI_connect(void)
Definition: spi.c:84
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:488
int SPI_finish(void)
Definition: spi.c:149
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
AclMode requiredPerms
Definition: parsenodes.h:1059
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:28
uint64 SPI_processed
Definition: spi.c:39
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:5248
int SPI_result
Definition: spi.c:42
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5267
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:93
Bitmapset * selectedCols
Definition: parsenodes.h:1061
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
const char * SPI_result_code_string(int code)
Definition: spi.c:1521
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5115
int errdetail(const char *fmt,...)
Definition: elog.c:873
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
#define RelationGetRelationName(relation)
Definition: rel.h:445
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
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:413
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define InvalidSnapshot
Definition: snapshot.h:25
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
#define ACL_SELECT
Definition: parsenodes.h:73
TupleDesc tupdesc
Definition: spi.h:27
#define SPI_OK_SELECT
Definition: spi.h:54
int maintenance_work_mem
Definition: globals.c:114
#define makeNode(_type_)
Definition: nodes.h:560
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
#define SPI_OK_FINISH
Definition: spi.h:51
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:742
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:379
RTEKind rtekind
Definition: parsenodes.h:951
int NewGUCNestLevel(void)
Definition: guc.c:5101
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:568
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
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:5944
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
#define RelationGetRelid(relation)
Definition: rel.h:425

◆ ri_KeysEqual()

static bool ri_KeysEqual ( Relation  rel,
HeapTuple  oldtup,
HeapTuple  newtup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 3084 of file ri_triggers.c.

References RI_ConstraintInfo::ff_eq_oprs, RI_ConstraintInfo::fk_attnums, heap_getattr, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pp_eq_oprs, RelationGetDescr, ri_AttributesEqual(), and RIAttType.

Referenced by RI_FKey_cascade_upd(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), ri_restrict(), ri_setdefault(), and ri_setnull().

3086 {
3087  TupleDesc tupdesc = RelationGetDescr(rel);
3088  const int16 *attnums;
3089  const Oid *eq_oprs;
3090  int i;
3091 
3092  if (rel_is_pk)
3093  {
3094  attnums = riinfo->pk_attnums;
3095  eq_oprs = riinfo->pp_eq_oprs;
3096  }
3097  else
3098  {
3099  attnums = riinfo->fk_attnums;
3100  eq_oprs = riinfo->ff_eq_oprs;
3101  }
3102 
3103  for (i = 0; i < riinfo->nkeys; i++)
3104  {
3105  Datum oldvalue;
3106  Datum newvalue;
3107  bool isnull;
3108 
3109  /*
3110  * Get one attribute's oldvalue. If it is NULL - they're not equal.
3111  */
3112  oldvalue = heap_getattr(oldtup, attnums[i], tupdesc, &isnull);
3113  if (isnull)
3114  return false;
3115 
3116  /*
3117  * Get one attribute's newvalue. If it is NULL - they're not equal.
3118  */
3119  newvalue = heap_getattr(newtup, attnums[i], tupdesc, &isnull);
3120  if (isnull)
3121  return false;
3122 
3123  /*
3124  * Compare them with the appropriate equality operator.
3125  */
3126  if (!ri_AttributesEqual(eq_oprs[i], RIAttType(rel, attnums[i]),
3127  oldvalue, newvalue))
3128  return false;
3129  }
3130 
3131  return true;
3132 }
signed short int16
Definition: c.h:293
#define RelationGetDescr(relation)
Definition: rel.h:437
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
static bool ri_AttributesEqual(Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
Definition: ri_triggers.c:3144
unsigned int Oid
Definition: postgres_ext.h:31
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:774
uintptr_t Datum
Definition: postgres.h:372
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120

◆ ri_LoadConstraintInfo()

static const RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2371 of file ri_triggers.c.

References Anum_pg_constraint_conffeqop, Anum_pg_constraint_confkey, Anum_pg_constraint_conkey, Anum_pg_constraint_conpfeqop, Anum_pg_constraint_conppeqop, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, RI_ConstraintInfo::confdeltype, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::confupdtype, RI_ConstraintInfo::conname, CONSTRAINT_FOREIGN, RI_ConstraintInfo::constraint_id, CONSTROID, DatumGetArrayTypeP, DatumGetPointer, dlist_push_tail(), elog, ERROR, RI_ConstraintInfo::ff_eq_oprs, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, GETSTRUCT, GetSysCacheHashValue1, HASH_ENTER, hash_search(), HeapTupleIsValid, INT2OID, RI_ConstraintInfo::nkeys, ObjectIdGetDatum, RI_ConstraintInfo::oidHashValue, OIDOID, RI_ConstraintInfo::pf_eq_oprs, pfree(), RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, RI_ConstraintInfo::pp_eq_oprs, ReleaseSysCache(), ri_constraint_cache_valid_count, ri_InitHashTables(), RI_MAX_NUMKEYS, SearchSysCache1(), SysCacheGetAttr(), RI_ConstraintInfo::valid, and RI_ConstraintInfo::valid_link.

Referenced by ri_FetchConstraintInfo().

2372 {
2373  RI_ConstraintInfo *riinfo;
2374  bool found;
2375  HeapTuple tup;
2376  Form_pg_constraint conForm;
2377  Datum adatum;
2378  bool isNull;
2379  ArrayType *arr;
2380  int numkeys;
2381 
2382  /*
2383  * On the first call initialize the hashtable
2384  */
2385  if (!ri_constraint_cache)
2387 
2388  /*
2389  * Find or create a hash entry. If we find a valid one, just return it.
2390  */
2392  (void *) &constraintOid,
2393  HASH_ENTER, &found);
2394  if (!found)
2395  riinfo->valid = false;
2396  else if (riinfo->valid)
2397  return riinfo;
2398 
2399  /*
2400  * Fetch the pg_constraint row so we can fill in the entry.
2401  */
2402  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2403  if (!HeapTupleIsValid(tup)) /* should not happen */
2404  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2405  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2406 
2407  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2408  elog(ERROR, "constraint %u is not a foreign key constraint",
2409  constraintOid);
2410 
2411  /* And extract data */
2412  Assert(riinfo->constraint_id == constraintOid);
2414  ObjectIdGetDatum(constraintOid));
2415  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2416  riinfo->pk_relid = conForm->confrelid;
2417  riinfo->fk_relid = conForm->conrelid;
2418  riinfo->confupdtype = conForm->confupdtype;
2419  riinfo->confdeltype = conForm->confdeltype;
2420  riinfo->confmatchtype = conForm->confmatchtype;
2421 
2422  /*
2423  * We expect the arrays to be 1-D arrays of the right types; verify that.
2424  * We don't need to use deconstruct_array() since the array data is just
2425  * going to look like a C array of values.
2426  */
2427  adatum = SysCacheGetAttr(CONSTROID, tup,
2428  Anum_pg_constraint_conkey, &isNull);
2429  if (isNull)
2430  elog(ERROR, "null conkey for constraint %u", constraintOid);
2431  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2432  if (ARR_NDIM(arr) != 1 ||
2433  ARR_HASNULL(arr) ||
2434  ARR_ELEMTYPE(arr) != INT2OID)
2435  elog(ERROR, "conkey is not a 1-D smallint array");
2436  numkeys = ARR_DIMS(arr)[0];
2437  if (numkeys <= 0 || numkeys > RI_MAX_NUMKEYS)
2438  elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
2439  riinfo->nkeys = numkeys;
2440  memcpy(riinfo->fk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2441  if ((Pointer) arr != DatumGetPointer(adatum))
2442  pfree(arr); /* free de-toasted copy, if any */
2443 
2444  adatum = SysCacheGetAttr(CONSTROID, tup,
2445  Anum_pg_constraint_confkey, &isNull);
2446  if (isNull)
2447  elog(ERROR, "null confkey for constraint %u", constraintOid);
2448  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2449  if (ARR_NDIM(arr) != 1 ||
2450  ARR_DIMS(arr)[0] != numkeys ||
2451  ARR_HASNULL(arr) ||
2452  ARR_ELEMTYPE(arr) != INT2OID)
2453  elog(ERROR, "confkey is not a 1-D smallint array");
2454  memcpy(riinfo->pk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2455  if ((Pointer) arr != DatumGetPointer(adatum))
2456  pfree(arr); /* free de-toasted copy, if any */
2457 
2458  adatum = SysCacheGetAttr(CONSTROID, tup,
2459  Anum_pg_constraint_conpfeqop, &isNull);
2460  if (isNull)
2461  elog(ERROR, "null conpfeqop for constraint %u", constraintOid);
2462  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2463  /* see TryReuseForeignKey if you change the test below */
2464  if (ARR_NDIM(arr) != 1 ||
2465  ARR_DIMS(arr)[0] != numkeys ||
2466  ARR_HASNULL(arr) ||
2467  ARR_ELEMTYPE(arr) != OIDOID)
2468  elog(ERROR, "conpfeqop is not a 1-D Oid array");
2469  memcpy(riinfo->pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2470  if ((Pointer) arr != DatumGetPointer(adatum))
2471  pfree(arr); /* free de-toasted copy, if any */
2472 
2473  adatum = SysCacheGetAttr(CONSTROID, tup,
2474  Anum_pg_constraint_conppeqop, &isNull);
2475  if (isNull)
2476  elog(ERROR, "null conppeqop for constraint %u", constraintOid);
2477  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2478  if (ARR_NDIM(arr) != 1 ||
2479  ARR_DIMS(arr)[0] != numkeys ||
2480  ARR_HASNULL(arr) ||
2481  ARR_ELEMTYPE(arr) != OIDOID)
2482  elog(ERROR, "conppeqop is not a 1-D Oid array");
2483  memcpy(riinfo->pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2484  if ((Pointer) arr != DatumGetPointer(adatum))
2485  pfree(arr); /* free de-toasted copy, if any */
2486 
2487  adatum = SysCacheGetAttr(CONSTROID, tup,
2488  Anum_pg_constraint_conffeqop, &isNull);
2489  if (isNull)
2490  elog(ERROR, "null conffeqop for constraint %u", constraintOid);
2491  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2492  if (ARR_NDIM(arr) != 1 ||
2493  ARR_DIMS(arr)[0] != numkeys ||
2494  ARR_HASNULL(arr) ||
2495  ARR_ELEMTYPE(arr) != OIDOID)
2496  elog(ERROR, "conffeqop is not a 1-D Oid array");
2497  memcpy(riinfo->ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2498  if ((Pointer) arr != DatumGetPointer(adatum))
2499  pfree(arr); /* free de-toasted copy, if any */
2500 
2501  ReleaseSysCache(tup);
2502 
2503  /*
2504  * For efficient processing of invalidation messages below, we keep a
2505  * doubly-linked list, and a count, of all currently valid entries.
2506  */
2509 
2510  riinfo->valid = true;
2511 
2512  return riinfo;
2513 }
signed short int16
Definition: c.h:293
#define CONSTRAINT_FOREIGN
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define Anum_pg_constraint_confkey
#define OIDOID
Definition: pg_type.h:328
#define Anum_pg_constraint_conppeqop
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:182
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:200
dlist_node valid_link
Definition: ri_triggers.c:124
#define Anum_pg_constraint_conffeqop
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:936
char * Pointer
Definition: c.h:283
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:279
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
Definition: c.h:551
#define INT2OID
Definition: pg_type.h:308
#define ARR_DATA_PTR(a)
Definition: array.h:307
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
#define ARR_HASNULL(a)
Definition: array.h:276
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
#define Anum_pg_constraint_conkey
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:186
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Anum_pg_constraint_conpfeqop
#define Assert(condition)
Definition: c.h:680
#define ARR_NDIM(a)
Definition: array.h:275
#define DatumGetPointer(X)
Definition: postgres.h:555
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:185
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2956
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define ARR_ELEMTYPE(a)
Definition: array.h:277
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ ri_NullCheck()

static int ri_NullCheck ( HeapTuple  tup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 2918 of file ri_triggers.c.

References RI_ConstraintInfo::fk_attnums, heap_attisnull(), i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, and RI_KEYS_SOME_NULL.

Referenced by ri_Check_Pk_Match(), 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_restrict(), ri_setdefault(), and ri_setnull().

2920 {
2921  const int16 *attnums;
2922  int i;
2923  bool allnull = true;
2924  bool nonenull = true;
2925 
2926  if (rel_is_pk)
2927  attnums = riinfo->pk_attnums;
2928  else
2929  attnums = riinfo->fk_attnums;
2930 
2931  for (i = 0; i < riinfo->nkeys; i++)
2932  {
2933  if (heap_attisnull(tup, attnums[i]))
2934  nonenull = false;
2935  else
2936  allnull = false;
2937  }
2938 
2939  if (allnull)
2940  return RI_KEYS_ALL_NULL;
2941 
2942  if (nonenull)
2943  return RI_KEYS_NONE_NULL;
2944 
2945  return RI_KEYS_SOME_NULL;
2946 }
signed short int16
Definition: c.h:293
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:296
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74

◆ ri_PerformCheck()

static bool ri_PerformCheck ( const RI_ConstraintInfo riinfo,
RI_QueryKey qkey,
SPIPlanPtr  qplan,
Relation  fk_rel,
Relation  pk_rel,
HeapTuple  old_tuple,
HeapTuple  new_tuple,
bool  detectNewRows,
int  expect_OK 
)
static

Definition at line 2615 of file ri_triggers.c.

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(), ri_setdefault(), and ri_setnull().

2620 {
2621  Relation query_rel,
2622  source_rel;
2623  bool source_is_pk;
2624  Snapshot test_snapshot;
2625  Snapshot crosscheck_snapshot;
2626  int limit;
2627  int spi_result;
2628  Oid save_userid;
2629  int save_sec_context;
2630  Datum vals[RI_MAX_NUMKEYS * 2];
2631  char nulls[RI_MAX_NUMKEYS * 2];
2632 
2633  /*
2634  * Use the query type code to determine whether the query is run against
2635  * the PK or FK table; we'll do the check as that table's owner
2636  */
2637  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2638  query_rel = pk_rel;
2639  else
2640  query_rel = fk_rel;
2641 
2642  /*
2643  * The values for the query are taken from the table on which the trigger
2644  * is called - it is normally the other one with respect to query_rel. An
2645  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2646  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2647  * need some less klugy way to determine this.
2648  */
2650  {
2651  source_rel = fk_rel;
2652  source_is_pk = false;
2653  }
2654  else
2655  {
2656  source_rel = pk_rel;
2657  source_is_pk = true;
2658  }
2659 
2660  /* Extract the parameters to be passed into the query */
2661  if (new_tuple)
2662  {
2663  ri_ExtractValues(source_rel, new_tuple, riinfo, source_is_pk,
2664  vals, nulls);
2665  if (old_tuple)
2666  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
2667  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2668  }
2669  else
2670  {
2671  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
2672  vals, nulls);
2673  }
2674 
2675  /*
2676  * In READ COMMITTED mode, we just need to use an up-to-date regular
2677  * snapshot, and we will see all rows that could be interesting. But in
2678  * transaction-snapshot mode, we can't change the transaction snapshot. If
2679  * the caller passes detectNewRows == false then it's okay to do the query
2680  * with the transaction snapshot; otherwise we use a current snapshot, and
2681  * tell the executor to error out if it finds any rows under the current
2682  * snapshot that wouldn't be visible per the transaction snapshot. Note
2683  * that SPI_execute_snapshot will register the snapshots, so we don't need
2684  * to bother here.
2685  */
2686  if (IsolationUsesXactSnapshot() && detectNewRows)
2687  {
2688  CommandCounterIncrement(); /* be sure all my own work is visible */
2689  test_snapshot = GetLatestSnapshot();
2690  crosscheck_snapshot = GetTransactionSnapshot();
2691  }
2692  else
2693  {
2694  /* the default SPI behavior is okay */
2695  test_snapshot = InvalidSnapshot;
2696  crosscheck_snapshot = InvalidSnapshot;
2697  }
2698 
2699  /*
2700  * If this is a select query (e.g., for a 'no action' or 'restrict'
2701  * trigger), we only need to see if there is a single row in the table,
2702  * matching the key. Otherwise, limit = 0 - because we want the query to
2703  * affect ALL the matching rows.
2704  */
2705  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2706 
2707  /* Switch to proper UID to perform check as */
2708  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2709  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2710  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2712 
2713  /* Finally we can run the query. */
2714  spi_result = SPI_execute_snapshot(qplan,
2715  vals, nulls,
2716  test_snapshot, crosscheck_snapshot,
2717  false, false, limit);
2718 
2719  /* Restore UID and security context */
2720  SetUserIdAndSecContext(save_userid, save_sec_context);
2721 
2722  /* Check result */
2723  if (spi_result < 0)
2724  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2725 
2726  if (expect_OK >= 0 && spi_result != expect_OK)
2727  ereport(ERROR,
2728  (errcode(ERRCODE_INTERNAL_ERROR),
2729  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2730  RelationGetRelationName(pk_rel),
2731  NameStr(riinfo->conname),
2732  RelationGetRelationName(fk_rel)),
2733  errhint("This is most likely due to a rule having rewritten the query.")));
2734 
2735  /* XXX wouldn't it be clearer to do this part at the caller? */
2737  expect_OK == SPI_OK_SELECT &&
2739  ri_ReportViolation(riinfo,
2740  pk_rel, fk_rel,
2741  new_tuple ? new_tuple : old_tuple,
2742  NULL,
2743  qkey->constr_queryno);
2744 
2745  return SPI_processed != 0;
2746 }
int errhint(const char *fmt,...)
Definition: elog.c:987
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno) pg_attribute_noreturn()
Definition: ri_triggers.c:2784
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:419
int32 constr_queryno
Definition: ri_triggers.c:137
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
uint64 SPI_processed
Definition: spi.c:39
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1521
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
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:413
#define InvalidSnapshot
Definition: snapshot.h:25
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:915
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:293
#define SPI_OK_SELECT
Definition: spi.h:54
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:79
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:379
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:557
static void ri_ExtractValues(Relation rel, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2752
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:295
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67

◆ ri_PlanCheck()

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

Definition at line 2568 of file ri_triggers.c.

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(), ri_setdefault(), and ri_setnull().

2571 {
2572  SPIPlanPtr qplan;
2573  Relation query_rel;
2574  Oid save_userid;
2575  int save_sec_context;
2576 
2577  /*
2578  * Use the query type code to determine whether the query is run against
2579  * the PK or FK table; we'll do the check as that table's owner
2580  */
2581  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2582  query_rel = pk_rel;
2583  else
2584  query_rel = fk_rel;
2585 
2586  /* Switch to proper UID to perform check as */
2587  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2588  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2589  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2591 
2592  /* Create the plan */
2593  qplan = SPI_prepare(querystr, nargs, argtypes);
2594 
2595  if (qplan == NULL)
2596  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2597 
2598  /* Restore UID and security context */
2599  SetUserIdAndSecContext(save_userid, save_sec_context);
2600 
2601  /* Save the plan if requested */
2602  if (cache_plan)
2603  {
2604  SPI_keepplan(qplan);
2605  ri_HashPreparedPlan(qkey, qplan);
2606  }
2607 
2608  return qplan;
2609 }
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:419
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:488
int32 constr_queryno
Definition: ri_triggers.c:137
unsigned int Oid
Definition: postgres_ext.h:31
int SPI_result
Definition: spi.c:42
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1521
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:3049
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:566
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:293
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:295

◆ ri_ReportViolation()

static void ri_ReportViolation ( const RI_ConstraintInfo riinfo,
Relation  pk_rel,
Relation  fk_rel,
HeapTuple  violator,
TupleDesc  tupdesc,
int  queryno 
)
static

Definition at line 2784 of file ri_triggers.c.

References ACL_SELECT, ACLCHECK_OK, appendStringInfoString(), check_enable_rls(), RI_ConstraintInfo::conname, StringInfoData::data, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), RI_ConstraintInfo::fk_attnums, GetUserId(), idx(), initStringInfo(), InvalidOid, name, NameStr, RI_ConstraintInfo::nkeys, pg_attribute_aclcheck(), pg_class_aclcheck(), RI_ConstraintInfo::pk_attnums, RelationData::rd_att, RelationData::rd_id, RelationGetRelationName, RI_PLAN_CHECK_LOOKUPPK, RLS_ENABLED, SPI_fname(), SPI_getvalue(), and val.

Referenced by RI_Initial_Check(), and ri_PerformCheck().

2788 {
2789  StringInfoData key_names;
2790  StringInfoData key_values;
2791  bool onfk;
2792  const int16 *attnums;
2793  int idx;
2794  Oid rel_oid;
2795  AclResult aclresult;
2796  bool has_perm = true;
2797 
2798  /*
2799  * Determine which relation to complain about. If tupdesc wasn't passed
2800  * by caller, assume the violator tuple came from there.
2801  */
2802  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2803  if (onfk)
2804  {
2805  attnums = riinfo->fk_attnums;
2806  rel_oid = fk_rel->rd_id;
2807  if (tupdesc == NULL)
2808  tupdesc = fk_rel->rd_att;
2809  }
2810  else
2811  {
2812  attnums = riinfo->pk_attnums;
2813  rel_oid = pk_rel->rd_id;
2814  if (tupdesc == NULL)
2815  tupdesc = pk_rel->rd_att;
2816  }
2817 
2818  /*
2819  * Check permissions- if the user does not have access to view the data in
2820  * any of the key columns then we don't include the errdetail() below.
2821  *
2822  * Check if RLS is enabled on the relation first. If so, we don't return
2823  * any specifics to avoid leaking data.
2824  *
2825  * Check table-level permissions next and, failing that, column-level
2826  * privileges.
2827  */
2828 
2829  if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2830  {
2831  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2832  if (aclresult != ACLCHECK_OK)
2833  {
2834  /* Try for column-level permissions */
2835  for (idx = 0; idx < riinfo->nkeys; idx++)
2836  {
2837  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2838  GetUserId(),
2839  ACL_SELECT);
2840 
2841  /* No access to the key */
2842  if (aclresult != ACLCHECK_OK)
2843  {
2844  has_perm = false;
2845  break;
2846  }
2847  }
2848  }
2849  }
2850  else
2851  has_perm = false;
2852 
2853  if (has_perm)
2854  {
2855  /* Get printable versions of the keys involved */
2856  initStringInfo(&key_names);
2857  initStringInfo(&key_values);
2858  for (idx = 0; idx < riinfo->nkeys; idx++)
2859  {
2860  int fnum = attnums[idx];
2861  char *name,
2862  *val;
2863 
2864  name = SPI_fname(tupdesc, fnum);
2865  val = SPI_getvalue(violator, tupdesc, fnum);
2866  if (!val)
2867  val = "null";
2868 
2869  if (idx > 0)
2870  {
2871  appendStringInfoString(&key_names, ", ");
2872  appendStringInfoString(&key_values, ", ");
2873  }
2874  appendStringInfoString(&key_names, name);
2875  appendStringInfoString(&key_values, val);
2876  }
2877  }
2878 
2879  if (onfk)
2880  ereport(ERROR,
2881  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2882  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2883  RelationGetRelationName(fk_rel),
2884  NameStr(riinfo->conname)),
2885  has_perm ?
2886  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2887  key_names.data, key_values.data,
2888  RelationGetRelationName(pk_rel)) :
2889  errdetail("Key is not present in table \"%s\".",
2890  RelationGetRelationName(pk_rel)),
2891  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2892  else
2893  ereport(ERROR,
2894  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2895  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2896  RelationGetRelationName(pk_rel),
2897  NameStr(riinfo->conname),
2898  RelationGetRelationName(fk_rel)),
2899  has_perm ?
2900  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2901  key_names.data, key_values.data,
2902  RelationGetRelationName(fk_rel)) :
2903  errdetail("Key is still referenced from table \"%s\".",
2904  RelationGetRelationName(fk_rel)),
2905  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2906 }
signed short int16
Definition: c.h:293
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4366
Oid GetUserId(void)
Definition: miscinit.c:284
int errcode(int sqlerrcode)
Definition: elog.c:575
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:264
unsigned int Oid
Definition: postgres_ext.h:31
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:790
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:812
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5267
#define ERROR
Definition: elog.h:43
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
Oid rd_id
Definition: rel.h:116
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:178
#define ACL_SELECT
Definition: parsenodes.h:73
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
const char * name
Definition: encode.c:521
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4480
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:557
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
long val
Definition: informix.c:689

◆ ri_restrict()

static Datum ri_restrict ( TriggerData trigdata,
bool  is_no_action 
)
static

Definition at line 689 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), 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(), ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_RESTRICT_CHECKREF, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, and TRIGGER_FIRED_BY_UPDATE.

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

690 {
691  const RI_ConstraintInfo *riinfo;
692  Relation fk_rel;
693  Relation pk_rel;
694  HeapTuple old_row;
695  RI_QueryKey qkey;
696  SPIPlanPtr qplan;
697 
698  /*
699  * Get arguments.
700  */
701  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
702  trigdata->tg_relation, true);
703 
704  /*
705  * Get the relation descriptors of the FK and PK tables and the old tuple.
706  *
707  * fk_rel is opened in RowShareLock mode since that's what our eventual
708  * SELECT FOR KEY SHARE will get on it.
709  */
710  fk_rel = heap_open(riinfo->fk_relid, RowShareLock);
711  pk_rel = trigdata->tg_relation;
712  old_row = trigdata->tg_trigtuple;
713 
714  switch (riinfo->confmatchtype)
715  {
716  /* ----------
717  * SQL:2008 15.17 <Execution of referential actions>
718  * General rules 9) a) iv):
719  * MATCH SIMPLE/FULL
720  * ... ON DELETE RESTRICT
721  * General rules 10) a) iv):
722  * MATCH SIMPLE/FULL
723  * ... ON UPDATE RESTRICT
724  * ----------
725  */
727  case FKCONSTR_MATCH_FULL:
728  switch (ri_NullCheck(old_row, riinfo, true))
729  {
730  case RI_KEYS_ALL_NULL:
731  case RI_KEYS_SOME_NULL:
732 
733  /*
734  * No check needed - there cannot be any reference to old
735  * key if it contains a NULL
736  */
737  heap_close(fk_rel, RowShareLock);
738  return PointerGetDatum(NULL);
739 
740  case RI_KEYS_NONE_NULL:
741 
742  /*
743  * Have a full qualified key - continue below
744  */
745  break;
746  }
747 
748  /*
749  * In UPDATE, no need to do anything if old and new keys are equal
750  */
751  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
752  {
753  HeapTuple new_row = trigdata->tg_newtuple;
754 
755  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
756  {
757  heap_close(fk_rel, RowShareLock);
758  return PointerGetDatum(NULL);
759  }
760  }
761 
762  /*
763  * If another PK row now exists providing the old key values, we
764  * should not do anything. However, this check should only be
765  * made in the NO ACTION case; in RESTRICT cases we don't wish to
766  * allow another row to be substituted.
767  */
768  if (is_no_action &&
769  ri_Check_Pk_Match(pk_rel, fk_rel, old_row, riinfo))
770  {
771  heap_close(fk_rel, RowShareLock);
772  return PointerGetDatum(NULL);
773  }
774 
775  if (SPI_connect() != SPI_OK_CONNECT)
776  elog(ERROR, "SPI_connect failed");
777 
778  /*
779  * Fetch or prepare a saved plan for the restrict lookup (it's the
780  * same query for delete and update cases)
781  */
783 
784  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
785  {
786  StringInfoData querybuf;
787  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
788  char attname[MAX_QUOTED_NAME_LEN];
789  char paramname[16];
790  const char *querysep;
791  Oid queryoids[RI_MAX_NUMKEYS];
792  int i;
793 
794  /* ----------
795  * The query string built is
796  * SELECT 1 FROM ONLY <fktable> x WHERE $1 = fkatt1 [AND ...]
797  * FOR KEY SHARE OF x
798  * The type id's for the $ parameters are those of the
799  * corresponding PK attributes.
800  * ----------
801  */
802  initStringInfo(&querybuf);
803  quoteRelationName(fkrelname, fk_rel);
804  appendStringInfo(&querybuf, "SELECT 1 FROM ONLY %s x",
805  fkrelname);
806  querysep = "WHERE";
807  for (i = 0; i < riinfo->nkeys; i++)
808  {
809  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
810  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
811 
812  quoteOneName(attname,
813  RIAttName(fk_rel, riinfo->fk_attnums[i]));
814  sprintf(paramname, "$%d", i + 1);
815  ri_GenerateQual(&querybuf, querysep,
816  paramname, pk_type,
817  riinfo->pf_eq_oprs[i],
818  attname, fk_type);
819  querysep = "AND";
820  queryoids[i] = pk_type;
821  }
822  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
823 
824  /* Prepare and save the plan */
825  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
826  &qkey, fk_rel, pk_rel, true);
827  }
828 
829  /*
830  * We have a plan now. Run it to check for existing references.
831  */
832  ri_PerformCheck(riinfo, &qkey, qplan,
833  fk_rel, pk_rel,
834  old_row, NULL,
835  true, /* must detect new rows */
836  SPI_OK_SELECT);
837 
838  if (SPI_finish() != SPI_OK_FINISH)
839  elog(ERROR, "SPI_finish failed");
840 
841  heap_close(fk_rel, RowShareLock);
842 
843  return PointerGetDatum(NULL);
844 
845  /*
846  * Handle MATCH PARTIAL restrict delete or update.
847  */
849  ereport(ERROR,
850  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
851  errmsg("MATCH PARTIAL not yet implemented")));
852  return PointerGetDatum(NULL);
853 
854  default:
855  elog(ERROR, "unrecognized confmatchtype: %d",
856  riinfo->confmatchtype);
857  break;
858  }
859 
860  /* Never reached */
861  return PointerGetDatum(NULL);
862 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:149
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
#define RowShareLock
Definition: lockdefs.h:37
#define RI_PLAN_RESTRICT_CHECKREF
Definition: ri_triggers.c:84
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, HeapTuple old_row, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:508
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define SPI_OK_SELECT
Definition: spi.h:54
TriggerEvent tg_event
Definition: trigger.h:33
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084
Relation tg_relation
Definition: trigger.h:34

◆ ri_setdefault()

static Datum ri_setdefault ( TriggerData trigdata)
static

Definition at line 1466 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), 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(), ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETDEFAULT_DOUPDATE, ri_PlanCheck(), ri_restrict(), RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_setdefault_del(), and RI_FKey_setdefault_upd().

1467 {
1468  const RI_ConstraintInfo *riinfo;
1469  Relation fk_rel;
1470  Relation pk_rel;
1471  HeapTuple old_row;
1472  RI_QueryKey qkey;
1473  SPIPlanPtr qplan;
1474 
1475  /*
1476  * Get arguments.
1477  */
1478  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1479  trigdata->tg_relation, true);
1480 
1481  /*
1482  * Get the relation descriptors of the FK and PK tables and the old tuple.
1483  *
1484  * fk_rel is opened in RowExclusiveLock mode since that's what our
1485  * eventual UPDATE will get on it.
1486  */
1487  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1488  pk_rel = trigdata->tg_relation;
1489  old_row = trigdata->tg_trigtuple;
1490 
1491  switch (riinfo->confmatchtype)
1492  {
1493  /* ----------
1494  * SQL:2008 15.17 <Execution of referential actions>
1495  * General rules 9) a) iii):
1496  * MATCH SIMPLE/FULL
1497  * ... ON DELETE SET DEFAULT
1498  * General rules 10) a) iii):
1499  * MATCH SIMPLE/FULL
1500  * ... ON UPDATE SET DEFAULT
1501  * ----------
1502  */
1503  case FKCONSTR_MATCH_SIMPLE:
1504  case FKCONSTR_MATCH_FULL:
1505  switch (ri_NullCheck(old_row, riinfo, true))
1506  {
1507  case RI_KEYS_ALL_NULL:
1508  case RI_KEYS_SOME_NULL:
1509 
1510  /*
1511  * No check needed - there cannot be any reference to old
1512  * key if it contains a NULL
1513  */
1514  heap_close(fk_rel, RowExclusiveLock);
1515  return PointerGetDatum(NULL);
1516 
1517  case RI_KEYS_NONE_NULL:
1518 
1519  /*
1520  * Have a full qualified key - continue below
1521  */
1522  break;
1523  }
1524 
1525  /*
1526  * In UPDATE, no need to do anything if old and new keys are equal
1527  */
1528  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1529  {
1530  HeapTuple new_row = trigdata->tg_newtuple;
1531 
1532  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1533  {
1534  heap_close(fk_rel, RowExclusiveLock);
1535  return PointerGetDatum(NULL);
1536  }
1537  }
1538 
1539  if (SPI_connect() != SPI_OK_CONNECT)
1540  elog(ERROR, "SPI_connect failed");
1541 
1542  /*
1543  * Fetch or prepare a saved plan for the set default operation
1544  * (it's the same query for delete and update cases)
1545  */
1547 
1548  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1549  {
1550  StringInfoData querybuf;
1551  StringInfoData qualbuf;
1552  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1553  char attname[MAX_QUOTED_NAME_LEN];
1554  char paramname[16];
1555  const char *querysep;
1556  const char *qualsep;
1557  Oid queryoids[RI_MAX_NUMKEYS];
1558  int i;
1559 
1560  /* ----------
1561  * The query string built is
1562  * UPDATE ONLY <fktable> SET fkatt1 = DEFAULT [, ...]
1563  * WHERE $1 = fkatt1 [AND ...]
1564  * The type id's for the $ parameters are those of the
1565  * corresponding PK attributes.
1566  * ----------
1567  */
1568  initStringInfo(&querybuf);
1569  initStringInfo(&qualbuf);
1570  quoteRelationName(fkrelname, fk_rel);
1571  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1572  querysep = "";
1573  qualsep = "WHERE";
1574  for (i = 0; i < riinfo->nkeys; i++)
1575  {
1576  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1577  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1578 
1579  quoteOneName(attname,
1580  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1581  appendStringInfo(&querybuf,
1582  "%s %s = DEFAULT",
1583  querysep, attname);
1584  sprintf(paramname, "$%d", i + 1);
1585  ri_GenerateQual(&qualbuf, qualsep,
1586  paramname, pk_type,
1587  riinfo->pf_eq_oprs[i],
1588  attname, fk_type);
1589  querysep = ",";
1590  qualsep = "AND";
1591  queryoids[i] = pk_type;
1592  }
1593  appendStringInfoString(&querybuf, qualbuf.data);
1594 
1595  /* Prepare and save the plan */
1596  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1597  &qkey, fk_rel, pk_rel, true);
1598  }
1599 
1600  /*
1601  * We have a plan now. Run it to update the existing references.
1602  */
1603  ri_PerformCheck(riinfo, &qkey, qplan,
1604  fk_rel, pk_rel,
1605  old_row, NULL,
1606  true, /* must detect new rows */
1607  SPI_OK_UPDATE);
1608 
1609  if (SPI_finish() != SPI_OK_FINISH)
1610  elog(ERROR, "SPI_finish failed");
1611 
1612  heap_close(fk_rel, RowExclusiveLock);
1613 
1614  /*
1615  * If we just deleted or updated the PK row whose key was equal to
1616  * the FK columns' default values, and a referencing row exists in
1617  * the FK table, we would have updated that row to the same values
1618  * it already had --- and RI_FKey_fk_upd_check_required would
1619  * hence believe no check is necessary. So we need to do another
1620  * lookup now and in case a reference still exists, abort the
1621  * operation. That is already implemented in the NO ACTION
1622  * trigger, so just run it. (This recheck is only needed in the
1623  * SET DEFAULT case, since CASCADE would remove such rows in case
1624  * of a DELETE operation or would change the FK key values in case
1625  * of an UPDATE, while SET NULL is certain to result in rows that
1626  * satisfy the FK constraint.)
1627  */
1628  return ri_restrict(trigdata, true);
1629 
1630  /*
1631  * Handle MATCH PARTIAL set default delete or update.
1632  */
1634  ereport(ERROR,
1635  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1636  errmsg("MATCH PARTIAL not yet implemented")));
1637  return PointerGetDatum(NULL);
1638 
1639  default:
1640  elog(ERROR, "unrecognized confmatchtype: %d",
1641  riinfo->confmatchtype);
1642  break;
1643  }
1644 
1645  /* Never reached */
1646  return PointerGetDatum(NULL);
1647 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:149
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:689
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define RI_PLAN_SETDEFAULT_DOUPDATE
Definition: ri_triggers.c:86
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
TriggerEvent tg_event
Definition: trigger.h:33
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084
Relation tg_relation
Definition: trigger.h:34

◆ ri_setnull()

static Datum ri_setnull ( TriggerData trigdata)
static

Definition at line 1249 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), 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(), ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETNULL_DOUPDATE, ri_PlanCheck(), RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_setnull_del(), and RI_FKey_setnull_upd().

1250 {
1251  const RI_ConstraintInfo *riinfo;
1252  Relation fk_rel;
1253  Relation pk_rel;
1254  HeapTuple old_row;
1255  RI_QueryKey qkey;
1256  SPIPlanPtr qplan;
1257  int i;
1258 
1259  /*
1260  * Get arguments.
1261  */
1262  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1263  trigdata->tg_relation, true);
1264 
1265  /*
1266  * Get the relation descriptors of the FK and PK tables and the old tuple.
1267  *
1268  * fk_rel is opened in RowExclusiveLock mode since that's what our
1269  * eventual UPDATE will get on it.
1270  */
1271  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1272  pk_rel = trigdata->tg_relation;
1273  old_row = trigdata->tg_trigtuple;
1274 
1275  switch (riinfo->confmatchtype)
1276  {
1277  /* ----------
1278  * SQL:2008 15.17 <Execution of referential actions>
1279  * General rules 9) a) ii):
1280  * MATCH SIMPLE/FULL
1281  * ... ON DELETE SET NULL
1282  * General rules 10) a) ii):
1283  * MATCH SIMPLE/FULL
1284  * ... ON UPDATE SET NULL
1285  * ----------
1286  */
1287  case FKCONSTR_MATCH_SIMPLE:
1288  case FKCONSTR_MATCH_FULL:
1289  switch (ri_NullCheck(old_row, riinfo, true))
1290  {
1291  case RI_KEYS_ALL_NULL:
1292  case RI_KEYS_SOME_NULL:
1293 
1294  /*
1295  * No check needed - there cannot be any reference to old
1296  * key if it contains a NULL
1297  */
1298  heap_close(fk_rel, RowExclusiveLock);
1299  return PointerGetDatum(NULL);
1300 
1301  case RI_KEYS_NONE_NULL:
1302 
1303  /*
1304  * Have a full qualified key - continue below
1305  */
1306  break;
1307  }
1308 
1309  /*
1310  * In UPDATE, no need to do anything if old and new keys are equal
1311  */
1312  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1313  {
1314  HeapTuple new_row = trigdata->tg_newtuple;
1315 
1316  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1317  {
1318  heap_close(fk_rel, RowExclusiveLock);
1319  return PointerGetDatum(NULL);
1320  }
1321  }
1322 
1323  if (SPI_connect() != SPI_OK_CONNECT)
1324  elog(ERROR, "SPI_connect failed");
1325 
1326  /*
1327  * Fetch or prepare a saved plan for the set null operation (it's
1328  * the same query for delete and update cases)
1329  */
1331 
1332  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1333  {
1334  StringInfoData querybuf;
1335  StringInfoData qualbuf;
1336  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1337  char attname[MAX_QUOTED_NAME_LEN];
1338  char paramname[16];
1339  const char *querysep;
1340  const char *qualsep;
1341  Oid queryoids[RI_MAX_NUMKEYS];
1342 
1343  /* ----------
1344  * The query string built is
1345  * UPDATE ONLY <fktable> SET fkatt1 = NULL [, ...]
1346  * WHERE $1 = fkatt1 [AND ...]
1347  * The type id's for the $ parameters are those of the
1348  * corresponding PK attributes.
1349  * ----------
1350  */
1351  initStringInfo(&querybuf);
1352  initStringInfo(&qualbuf);
1353  quoteRelationName(fkrelname, fk_rel);
1354  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1355  querysep = "";
1356  qualsep = "WHERE";
1357  for (i = 0; i < riinfo->nkeys; i++)
1358  {
1359  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1360  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1361 
1362  quoteOneName(attname,
1363  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1364  appendStringInfo(&querybuf,
1365  "%s %s = NULL",
1366  querysep, attname);
1367  sprintf(paramname, "$%d", i + 1);
1368  ri_GenerateQual(&qualbuf, qualsep,
1369  paramname, pk_type,
1370  riinfo->pf_eq_oprs[i],
1371  attname, fk_type);
1372  querysep = ",";
1373  qualsep = "AND";
1374  queryoids[i] = pk_type;
1375  }
1376  appendStringInfoString(&querybuf, qualbuf.data);
1377 
1378  /* Prepare and save the plan */
1379  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1380  &qkey, fk_rel, pk_rel, true);
1381  }
1382 
1383  /*
1384  * We have a plan now. Run it to update the existing references.
1385  */
1386  ri_PerformCheck(riinfo, &qkey, qplan,
1387  fk_rel, pk_rel,
1388  old_row, NULL,
1389  true, /* must detect new rows */
1390  SPI_OK_UPDATE);
1391 
1392  if (SPI_finish() != SPI_OK_FINISH)
1393  elog(ERROR, "SPI_finish failed");
1394 
1395  heap_close(fk_rel, RowExclusiveLock);
1396 
1397  return PointerGetDatum(NULL);
1398 
1399  /*
1400  * Handle MATCH PARTIAL set null delete or update.
1401  */
1403  ereport(ERROR,
1404  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1405  errmsg("MATCH PARTIAL not yet implemented")));
1406  return PointerGetDatum(NULL);
1407 
1408  default:
1409  elog(ERROR, "unrecognized confmatchtype: %d",
1410  riinfo->confmatchtype);
1411  break;
1412  }
1413 
1414  /* Never reached */
1415  return PointerGetDatum(NULL);
1416 }
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:2146
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2126
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2918
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:149
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:92
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:91
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2106
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:89
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2615
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2996
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
#define RI_PLAN_SETNULL_DOUPDATE
Definition: ri_triggers.c:85
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2328
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2085
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
TriggerEvent tg_event
Definition: trigger.h:33
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2568
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2267
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2086
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3084
Relation tg_relation
Definition: trigger.h:34

Variable Documentation

◆ ri_compare_cache

HTAB* ri_compare_cache = NULL
static

Definition at line 184 of file ri_triggers.c.

◆ ri_constraint_cache

HTAB* ri_constraint_cache = NULL
static

Definition at line 182 of file ri_triggers.c.

◆ ri_constraint_cache_valid_count

int ri_constraint_cache_valid_count = 0
static

Definition at line 186 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_constraint_cache_valid_list

dlist_head ri_constraint_cache_valid_list
static

Definition at line 185 of file ri_triggers.c.

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 183 of file ri_triggers.c.