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_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (TupleDesc tupdesc, 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

◆ RIAttType

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

2491 {
2492  dlist_mutable_iter iter;
2493 
2494  Assert(ri_constraint_cache != NULL);
2495 
2496  /*
2497  * If the list of currently valid entries gets excessively large, we mark
2498  * them all invalid so we can empty the list. This arrangement avoids
2499  * O(N^2) behavior in situations where a session touches many foreign keys
2500  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2501  */
2503  hashvalue = 0; /* pretend it's a cache reset */
2504 
2506  {
2508  valid_link, iter.cur);
2509 
2510  if (hashvalue == 0 || riinfo->oidHashValue == hashvalue)
2511  {
2512  riinfo->valid = false;
2513  /* Remove invalidated entries from the list, too */
2514  dlist_delete(iter.cur);
2516  }
2517  }
2518 }
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:699
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 2127 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().

2128 {
2129  /* Rather than trying to be smart, just always quote it. */
2130  *buffer++ = '"';
2131  while (*name)
2132  {
2133  if (*name == '"')
2134  *buffer++ = '"';
2135  *buffer++ = *name++;
2136  }
2137  *buffer++ = '"';
2138  *buffer = '\0';
2139 }
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 2147 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().

2148 {
2150  buffer += strlen(buffer);
2151  *buffer++ = '.';
2153 }
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2127
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define RelationGetRelationName(relation)
Definition: rel.h:441
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
#define RelationGetNamespace(relation)
Definition: rel.h:448

◆ ri_AttributesEqual()

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

Definition at line 3105 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().

3107 {
3108  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3109 
3110  /* Do we need to cast the values? */
3111  if (OidIsValid(entry->cast_func_finfo.fn_oid))
3112  {
3113  oldvalue = FunctionCall3(&entry->cast_func_finfo,
3114  oldvalue,
3115  Int32GetDatum(-1), /* typmod */
3116  BoolGetDatum(false)); /* implicit coercion */
3117  newvalue = FunctionCall3(&entry->cast_func_finfo,
3118  newvalue,
3119  Int32GetDatum(-1), /* typmod */
3120  BoolGetDatum(false)); /* implicit coercion */
3121  }
3122 
3123  /*
3124  * Apply the comparison operator. We assume it doesn't care about
3125  * collations.
3126  */
3127  return DatumGetBool(FunctionCall2(&entry->eq_opr_finfo,
3128  oldvalue, newvalue));
3129 }
#define FunctionCall2(flinfo, arg1, arg2)
Definition: fmgr.h:610
#define OidIsValid(objectId)
Definition: c.h:605
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:612
#define DatumGetBool(X)
Definition: postgres.h:378
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3139
#define BoolGetDatum(X)
Definition: postgres.h:387
Oid fn_oid
Definition: fmgr.h:59
#define Int32GetDatum(X)
Definition: postgres.h:464
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 2234 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().

2236 {
2237  /*
2238  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2239  * to use memset to clear them.
2240  */
2241  key->constr_id = riinfo->constraint_id;
2242  key->constr_queryno = constr_queryno;
2243 }
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 507 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), Assert, attname, StringInfoData::data, elog, ERROR, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pp_eq_oprs, quoteOneName(), quoteRelationName(), RelationGetDescr, ri_BuildQueryKey(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_NONE_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK_FROM_PK, ri_PlanCheck(), RIAttName, RIAttType, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, and SPI_OK_SELECT.

Referenced by ri_restrict().

510 {
511  SPIPlanPtr qplan;
512  RI_QueryKey qkey;
513  int i;
514  bool result;
515 
516  /* Only called for non-null rows */
517  Assert(ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true) == RI_KEYS_NONE_NULL);
518 
519  if (SPI_connect() != SPI_OK_CONNECT)
520  elog(ERROR, "SPI_connect failed");
521 
522  /*
523  * Fetch or prepare a saved plan for checking PK table with values coming
524  * from a PK row
525  */
527 
528  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
529  {
530  StringInfoData querybuf;
531  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
533  char paramname[16];
534  const char *querysep;
535  Oid queryoids[RI_MAX_NUMKEYS];
536 
537  /* ----------
538  * The query string built is
539  * SELECT 1 FROM ONLY <pktable> x WHERE pkatt1 = $1 [AND ...]
540  * FOR KEY SHARE OF x
541  * The type id's for the $ parameters are those of the
542  * PK attributes themselves.
543  * ----------
544  */
545  initStringInfo(&querybuf);
546  quoteRelationName(pkrelname, pk_rel);
547  appendStringInfo(&querybuf, "SELECT 1 FROM ONLY %s x", pkrelname);
548  querysep = "WHERE";
549  for (i = 0; i < riinfo->nkeys; i++)
550  {
551  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
552 
553  quoteOneName(attname,
554  RIAttName(pk_rel, riinfo->pk_attnums[i]));
555  sprintf(paramname, "$%d", i + 1);
556  ri_GenerateQual(&querybuf, querysep,
557  attname, pk_type,
558  riinfo->pp_eq_oprs[i],
559  paramname, pk_type);
560  querysep = "AND";
561  queryoids[i] = pk_type;
562  }
563  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
564 
565  /* Prepare and save the plan */
566  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
567  &qkey, fk_rel, pk_rel, true);
568  }
569 
570  /*
571  * We have a plan now. Run it.
572  */
573  result = ri_PerformCheck(riinfo, &qkey, qplan,
574  fk_rel, pk_rel,
575  old_row, NULL,
576  true, /* treat like update */
577  SPI_OK_SELECT);
578 
579  if (SPI_finish() != SPI_OK_FINISH)
580  elog(ERROR, "SPI_finish failed");
581 
582  return result;
583 }
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:2164
#define SPI_OK_CONNECT
Definition: spi.h:50
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:161
#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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
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:699
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:2528
#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:2234
#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 2249 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().

2250 {
2251  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2252 
2253  if (!CALLED_AS_TRIGGER(fcinfo))
2254  ereport(ERROR,
2255  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2256  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2257 
2258  /*
2259  * Check proper event
2260  */
2261  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2262  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2263  ereport(ERROR,
2264  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2265  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2266 
2267  switch (tgkind)
2268  {
2269  case RI_TRIGTYPE_INSERT:
2270  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2271  ereport(ERROR,
2272  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2273  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2274  break;
2275  case RI_TRIGTYPE_UPDATE:
2276  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2277  ereport(ERROR,
2278  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2279  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2280  break;
2281  case RI_TRIGTYPE_DELETE:
2282  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2283  ereport(ERROR,
2284  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2285  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2286  break;
2287  }
2288 }
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 2712 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().

2715 {
2716  TupleDesc tupdesc = rel->rd_att;
2717  const int16 *attnums;
2718  int i;
2719  bool isnull;
2720 
2721  if (rel_is_pk)
2722  attnums = riinfo->pk_attnums;
2723  else
2724  attnums = riinfo->fk_attnums;
2725 
2726  for (i = 0; i < riinfo->nkeys; i++)
2727  {
2728  vals[i] = heap_getattr(tup, attnums[i], tupdesc,
2729  &isnull);
2730  nulls[i] = isnull ? 'n' : ' ';
2731  }
2732 }
signed short int16
Definition: c.h:312
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:781
TupleDesc rd_att
Definition: rel.h:85
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 2295 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().

2296 {
2297  Oid constraintOid = trigger->tgconstraint;
2298  const RI_ConstraintInfo *riinfo;
2299 
2300  /*
2301  * Check that the FK constraint's OID is available; it might not be if
2302  * we've been invoked via an ordinary trigger or an old-style "constraint
2303  * trigger".
2304  */
2305  if (!OidIsValid(constraintOid))
2306  ereport(ERROR,
2307  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2308  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2309  trigger->tgname, RelationGetRelationName(trig_rel)),
2310  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2311 
2312  /* Find or create a hashtable entry for the constraint */
2313  riinfo = ri_LoadConstraintInfo(constraintOid);
2314 
2315  /* Do some easy cross-checks against the trigger call data */
2316  if (rel_is_pk)
2317  {
2318  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2319  riinfo->pk_relid != RelationGetRelid(trig_rel))
2320  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2321  trigger->tgname, RelationGetRelationName(trig_rel));
2322  }
2323 
2324  return riinfo;
2325 }
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:605
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:441
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:2331
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ ri_FetchPreparedPlan()

static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 2957 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().

2958 {
2959  RI_QueryHashEntry *entry;
2960  SPIPlanPtr plan;
2961 
2962  /*
2963  * On the first call initialize the hashtable
2964  */
2965  if (!ri_query_cache)
2967 
2968  /*
2969  * Lookup for the key
2970  */
2972  (void *) key,
2973  HASH_FIND, NULL);
2974  if (entry == NULL)
2975  return NULL;
2976 
2977  /*
2978  * Check whether the plan is still valid. If it isn't, we don't want to
2979  * simply rely on plancache.c to regenerate it; rather we should start
2980  * from scratch and rebuild the query text too. This is to cover cases
2981  * such as table/column renames. We depend on the plancache machinery to
2982  * detect possible invalidations, though.
2983  *
2984  * CAUTION: this check is only trustworthy if the caller has already
2985  * locked both FK and PK rels.
2986  */
2987  plan = entry->plan;
2988  if (plan && SPI_plan_is_valid(plan))
2989  return plan;
2990 
2991  /*
2992  * Otherwise we might as well flush the cached plan now, to free a little
2993  * memory space before we make a new one.
2994  */
2995  entry->plan = NULL;
2996  if (plan)
2997  SPI_freeplan(plan);
2998 
2999  return NULL;
3000 }
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:906
SPIPlanPtr plan
Definition: ri_triggers.c:148
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:705
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1587
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2917

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 874 of file ri_triggers.c.

References appendStringInfo(), attname, 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(), RelationGetDescr, 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.

875 {
876  TriggerData *trigdata = (TriggerData *) fcinfo->context;
877  const RI_ConstraintInfo *riinfo;
878  Relation fk_rel;
879  Relation pk_rel;
880  HeapTuple old_row;
881  RI_QueryKey qkey;
882  SPIPlanPtr qplan;
883  int i;
884 
885  /*
886  * Check that this is a valid trigger call on the right time and event.
887  */
888  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
889 
890  /*
891  * Get arguments.
892  */
893  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
894  trigdata->tg_relation, true);
895 
896  /*
897  * Get the relation descriptors of the FK and PK tables and the old tuple.
898  *
899  * fk_rel is opened in RowExclusiveLock mode since that's what our
900  * eventual DELETE will get on it.
901  */
902  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
903  pk_rel = trigdata->tg_relation;
904  old_row = trigdata->tg_trigtuple;
905 
906  switch (riinfo->confmatchtype)
907  {
908  /* ----------
909  * SQL:2008 15.17 <Execution of referential actions>
910  * General rules 9) a) i):
911  * MATCH SIMPLE/FULL
912  * ... ON DELETE CASCADE
913  * ----------
914  */
916  case FKCONSTR_MATCH_FULL:
917  switch (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true))
918  {
919  case RI_KEYS_ALL_NULL:
920  case RI_KEYS_SOME_NULL:
921 
922  /*
923  * No check needed - there cannot be any reference to old
924  * key if it contains a NULL
925  */
926  heap_close(fk_rel, RowExclusiveLock);
927  return PointerGetDatum(NULL);
928 
929  case RI_KEYS_NONE_NULL:
930 
931  /*
932  * Have a full qualified key - continue below
933  */
934  break;
935  }
936 
937  if (SPI_connect() != SPI_OK_CONNECT)
938  elog(ERROR, "SPI_connect failed");
939 
940  /*
941  * Fetch or prepare a saved plan for the cascaded delete
942  */
944 
945  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
946  {
947  StringInfoData querybuf;
948  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
950  char paramname[16];
951  const char *querysep;
952  Oid queryoids[RI_MAX_NUMKEYS];
953  const char *fk_only;
954 
955  /* ----------
956  * The query string built is
957  * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
958  * The type id's for the $ parameters are those of the
959  * corresponding PK attributes.
960  * ----------
961  */
962  initStringInfo(&querybuf);
963  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
964  "" : "ONLY ";
965  quoteRelationName(fkrelname, fk_rel);
966  appendStringInfo(&querybuf, "DELETE FROM %s%s",
967  fk_only, fkrelname);
968  querysep = "WHERE";
969  for (i = 0; i < riinfo->nkeys; i++)
970  {
971  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
972  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
973 
974  quoteOneName(attname,
975  RIAttName(fk_rel, riinfo->fk_attnums[i]));
976  sprintf(paramname, "$%d", i + 1);
977  ri_GenerateQual(&querybuf, querysep,
978  paramname, pk_type,
979  riinfo->pf_eq_oprs[i],
980  attname, fk_type);
981  querysep = "AND";
982  queryoids[i] = pk_type;
983  }
984 
985  /* Prepare and save the plan */
986  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
987  &qkey, fk_rel, pk_rel, true);
988  }
989 
990  /*
991  * We have a plan now. Build up the arguments from the key values
992  * in the deleted PK tuple and delete the referencing rows
993  */
994  ri_PerformCheck(riinfo, &qkey, qplan,
995  fk_rel, pk_rel,
996  old_row, NULL,
997  true, /* must detect new rows */
998  SPI_OK_DELETE);
999 
1000  if (SPI_finish() != SPI_OK_FINISH)
1001  elog(ERROR, "SPI_finish failed");
1002 
1003  heap_close(fk_rel, RowExclusiveLock);
1004 
1005  return PointerGetDatum(NULL);
1006 
1007  /*
1008  * Handle MATCH PARTIAL cascaded delete.
1009  */
1011  ereport(ERROR,
1012  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1013  errmsg("MATCH PARTIAL not yet implemented")));
1014  return PointerGetDatum(NULL);
1015 
1016  default:
1017  elog(ERROR, "unrecognized confmatchtype: %d",
1018  riinfo->confmatchtype);
1019  break;
1020  }
1021 
1022  /* Never reached */
1023  return PointerGetDatum(NULL);
1024 }
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:2164
#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:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:541
#define SPI_OK_DELETE
Definition: spi.h:57
int SPI_finish(void)
Definition: spi.c:161
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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2249
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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
#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:2295
#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:1294
#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:2528
#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:2234
#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 1034 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, 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(), RelationGetDescr, 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.

1035 {
1036  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1037  const RI_ConstraintInfo *riinfo;
1038  Relation fk_rel;
1039  Relation pk_rel;
1040  HeapTuple new_row;
1041  HeapTuple old_row;
1042  RI_QueryKey qkey;
1043  SPIPlanPtr qplan;
1044  int i;
1045  int j;
1046 
1047  /*
1048  * Check that this is a valid trigger call on the right time and event.
1049  */
1050  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1051 
1052  /*
1053  * Get arguments.
1054  */
1055  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1056  trigdata->tg_relation, true);
1057 
1058  /*
1059  * Get the relation descriptors of the FK and PK tables and the new and
1060  * old tuple.
1061  *
1062  * fk_rel is opened in RowExclusiveLock mode since that's what our
1063  * eventual UPDATE will get on it.
1064  */
1065  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1066  pk_rel = trigdata->tg_relation;
1067  new_row = trigdata->tg_newtuple;
1068  old_row = trigdata->tg_trigtuple;
1069 
1070  switch (riinfo->confmatchtype)
1071  {
1072  /* ----------
1073  * SQL:2008 15.17 <Execution of referential actions>
1074  * General rules 10) a) i):
1075  * MATCH SIMPLE/FULL
1076  * ... ON UPDATE CASCADE
1077  * ----------
1078  */
1079  case FKCONSTR_MATCH_SIMPLE:
1080  case FKCONSTR_MATCH_FULL:
1081  switch (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true))
1082  {
1083  case RI_KEYS_ALL_NULL:
1084  case RI_KEYS_SOME_NULL:
1085 
1086  /*
1087  * No check needed - there cannot be any reference to old
1088  * key if it contains a NULL
1089  */
1090  heap_close(fk_rel, RowExclusiveLock);
1091  return PointerGetDatum(NULL);
1092 
1093  case RI_KEYS_NONE_NULL:
1094 
1095  /*
1096  * Have a full qualified key - continue below
1097  */
1098  break;
1099  }
1100 
1101  /*
1102  * No need to do anything if old and new keys are equal
1103  */
1104  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1105  {
1106  heap_close(fk_rel, RowExclusiveLock);
1107  return PointerGetDatum(NULL);
1108  }
1109 
1110  if (SPI_connect() != SPI_OK_CONNECT)
1111  elog(ERROR, "SPI_connect failed");
1112 
1113  /*
1114  * Fetch or prepare a saved plan for the cascaded update
1115  */
1117 
1118  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1119  {
1120  StringInfoData querybuf;
1121  StringInfoData qualbuf;
1122  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1124  char paramname[16];
1125  const char *querysep;
1126  const char *qualsep;
1127  Oid queryoids[RI_MAX_NUMKEYS * 2];
1128  const char *fk_only;
1129 
1130  /* ----------
1131  * The query string built is
1132  * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1133  * WHERE $n = fkatt1 [AND ...]
1134  * The type id's for the $ parameters are those of the
1135  * corresponding PK attributes. Note that we are assuming
1136  * there is an assignment cast from the PK to the FK type;
1137  * else the parser will fail.
1138  * ----------
1139  */
1140  initStringInfo(&querybuf);
1141  initStringInfo(&qualbuf);
1142  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1143  "" : "ONLY ";
1144  quoteRelationName(fkrelname, fk_rel);
1145  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1146  fk_only, fkrelname);
1147  querysep = "";
1148  qualsep = "WHERE";
1149  for (i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1150  {
1151  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1152  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1153 
1154  quoteOneName(attname,
1155  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1156  appendStringInfo(&querybuf,
1157  "%s %s = $%d",
1158  querysep, attname, i + 1);
1159  sprintf(paramname, "$%d", j + 1);
1160  ri_GenerateQual(&qualbuf, qualsep,
1161  paramname, pk_type,
1162  riinfo->pf_eq_oprs[i],
1163  attname, fk_type);
1164  querysep = ",";
1165  qualsep = "AND";
1166  queryoids[i] = pk_type;
1167  queryoids[j] = pk_type;
1168  }
1169  appendStringInfoString(&querybuf, qualbuf.data);
1170 
1171  /* Prepare and save the plan */
1172  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1173  &qkey, fk_rel, pk_rel, true);
1174  }
1175 
1176  /*
1177  * We have a plan now. Run it to update the existing references.
1178  */
1179  ri_PerformCheck(riinfo, &qkey, qplan,
1180  fk_rel, pk_rel,
1181  old_row, new_row,
1182  true, /* must detect new rows */
1183  SPI_OK_UPDATE);
1184 
1185  if (SPI_finish() != SPI_OK_FINISH)
1186  elog(ERROR, "SPI_finish failed");
1187 
1188  heap_close(fk_rel, RowExclusiveLock);
1189 
1190  return PointerGetDatum(NULL);
1191 
1192  /*
1193  * Handle MATCH PARTIAL cascade update.
1194  */
1196  ereport(ERROR,
1197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1198  errmsg("MATCH PARTIAL not yet implemented")));
1199  return PointerGetDatum(NULL);
1200 
1201  default:
1202  elog(ERROR, "unrecognized confmatchtype: %d",
1203  riinfo->confmatchtype);
1204  break;
1205  }
1206 
1207  /* Never reached */
1208  return PointerGetDatum(NULL);
1209 }
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:2164
#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:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:541
int SPI_finish(void)
Definition: spi.c:161
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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2249
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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
#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:2295
#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:1294
#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:2528
#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:2234
#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:3045
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_check()

static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 252 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, 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(), RelationGetDescr, RelationGetRelationName, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SnapshotSelf, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, 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().

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

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

Referenced by validateForeignKeyConstraint().

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

◆ RI_FKey_check_upd()

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS  )

Definition at line 481 of file ri_triggers.c.

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

482 {
483  /*
484  * Check that this is a valid trigger call on the right time and event.
485  */
486  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
487 
488  /*
489  * Share code with INSERT case.
490  */
491  return RI_FKey_check((TriggerData *) fcinfo->context);
492 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:252
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2249
#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 1736 of file ri_triggers.c.

References RI_ConstraintInfo::confmatchtype, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, HeapTupleHeaderGetXmin, RelationGetDescr, 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().

1738 {
1739  const RI_ConstraintInfo *riinfo;
1740 
1741  /*
1742  * Get arguments.
1743  */
1744  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1745 
1746  switch (riinfo->confmatchtype)
1747  {
1748  case FKCONSTR_MATCH_SIMPLE:
1749 
1750  /*
1751  * If any new key value is NULL, the row must satisfy the
1752  * constraint, so no check is needed.
1753  */
1754  if (ri_NullCheck(RelationGetDescr(fk_rel), new_row, riinfo, false) != RI_KEYS_NONE_NULL)
1755  return false;
1756 
1757  /*
1758  * If the original row was inserted by our own transaction, we
1759  * must fire the trigger whether or not the keys are equal. This
1760  * is because our UPDATE will invalidate the INSERT so that the
1761  * INSERT RI trigger will not do anything; so we had better do the
1762  * UPDATE check. (We could skip this if we knew the INSERT
1763  * trigger already fired, but there is no easy way to know that.)
1764  */
1766  return true;
1767 
1768  /* If all old and new key values are equal, no check is needed */
1769  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
1770  return false;
1771 
1772  /* Else we need to fire the trigger. */
1773  return true;
1774 
1775  case FKCONSTR_MATCH_FULL:
1776 
1777  /*
1778  * If all new key values are NULL, the row must satisfy the
1779  * constraint, so no check is needed. On the other hand, if only
1780  * some of them are NULL, the row must fail the constraint. We
1781  * must not throw error here, because the row might get
1782  * invalidated before the constraint is to be checked, but we
1783  * should queue the event to apply the check later.
1784  */
1785  switch (ri_NullCheck(RelationGetDescr(fk_rel), new_row, riinfo, false))
1786  {
1787  case RI_KEYS_ALL_NULL:
1788  return false;
1789  case RI_KEYS_SOME_NULL:
1790  return true;
1791  case RI_KEYS_NONE_NULL:
1792  break; /* continue with the check */
1793  }
1794 
1795  /*
1796  * If the original row was inserted by our own transaction, we
1797  * must fire the trigger whether or not the keys are equal. This
1798  * is because our UPDATE will invalidate the INSERT so that the
1799  * INSERT RI trigger will not do anything; so we had better do the
1800  * UPDATE check. (We could skip this if we knew the INSERT
1801  * trigger already fired, but there is no easy way to know that.)
1802  */
1804  return true;
1805 
1806  /* If all old and new key values are equal, no check is needed */
1807  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
1808  return false;
1809 
1810  /* Else we need to fire the trigger. */
1811  return true;
1812 
1813  /* Handle MATCH PARTIAL check. */
1815  ereport(ERROR,
1816  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1817  errmsg("MATCH PARTIAL not yet implemented")));
1818  break;
1819 
1820  default:
1821  elog(ERROR, "unrecognized confmatchtype: %d",
1822  riinfo->confmatchtype);
1823  break;
1824  }
1825 
1826  /* Never reached */
1827  return false;
1828 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
#define RelationGetDescr(relation)
Definition: rel.h:433
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:765
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTupleHeader t_data
Definition: htup.h:68
#define ERROR
Definition: elog.h:43
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2295
#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:3045

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 595 of file ri_triggers.c.

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

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 642 of file ri_triggers.c.

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

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

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

Referenced by AfterTriggerSaveEvent().

1681 {
1682  const RI_ConstraintInfo *riinfo;
1683 
1684  /*
1685  * Get arguments.
1686  */
1687  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1688 
1689  switch (riinfo->confmatchtype)
1690  {
1691  case FKCONSTR_MATCH_SIMPLE:
1692  case FKCONSTR_MATCH_FULL:
1693 
1694  /*
1695  * If any old key value is NULL, the row could not have been
1696  * referenced by an FK row, so no check is needed.
1697  */
1698  if (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true) != RI_KEYS_NONE_NULL)
1699  return false;
1700 
1701  /* If all old and new key values are equal, no check is needed */
1702  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1703  return false;
1704 
1705  /* Else we need to fire the trigger. */
1706  return true;
1707 
1708  /* Handle MATCH PARTIAL check. */
1710  ereport(ERROR,
1711  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1712  errmsg("MATCH PARTIAL not yet implemented")));
1713  break;
1714 
1715  default:
1716  elog(ERROR, "unrecognized confmatchtype: %d",
1717  riinfo->confmatchtype);
1718  break;
1719  }
1720 
1721  /* Never reached */
1722  return false;
1723 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2087
#define RelationGetDescr(relation)
Definition: rel.h:433
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2295
#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:3045

◆ RI_FKey_restrict_del()

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 620 of file ri_triggers.c.

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

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 667 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1440 of file ri_triggers.c.

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

1441 {
1442  /*
1443  * Check that this is a valid trigger call on the right time and event.
1444  */
1445  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1446 
1447  /*
1448  * Share code with UPDATE case
1449  */
1450  return ri_setdefault((TriggerData *) fcinfo->context);
1451 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2249
static Datum ri_setdefault(TriggerData *trigdata)
Definition: ri_triggers.c:1480
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1460 of file ri_triggers.c.

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

1461 {
1462  /*
1463  * Check that this is a valid trigger call on the right time and event.
1464  */
1465  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1466 
1467  /*
1468  * Share code with DELETE case
1469  */
1470  return ri_setdefault((TriggerData *) fcinfo->context);
1471 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2249
static Datum ri_setdefault(TriggerData *trigdata)
Definition: ri_triggers.c:1480
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1219 of file ri_triggers.c.

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

1220 {
1221  /*
1222  * Check that this is a valid trigger call on the right time and event.
1223  */
1224  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1225 
1226  /*
1227  * Share code with UPDATE case
1228  */
1229  return ri_setnull((TriggerData *) fcinfo->context);
1230 }
static Datum ri_setnull(TriggerData *trigdata)
Definition: ri_triggers.c:1259
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2249
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:97

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1239 of file ri_triggers.c.

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

1240 {
1241  /*
1242  * Check that this is a valid trigger call on the right time and event.
1243  */
1244  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1245 
1246  /*
1247  * Share code with DELETE case
1248  */
1249  return ri_setnull((TriggerData *) fcinfo->context);
1250 }
static Datum ri_setnull(TriggerData *trigdata)
Definition: ri_triggers.c:1259
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2249
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:96

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3232 of file ri_triggers.c.

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and CreateTrigger().

3233 {
3234  switch (tgfoid)
3235  {
3236  case F_RI_FKEY_CASCADE_DEL:
3237  case F_RI_FKEY_CASCADE_UPD:
3238  case F_RI_FKEY_RESTRICT_DEL:
3239  case F_RI_FKEY_RESTRICT_UPD:
3240  case F_RI_FKEY_SETNULL_DEL:
3241  case F_RI_FKEY_SETNULL_UPD:
3242  case F_RI_FKEY_SETDEFAULT_DEL:
3243  case F_RI_FKEY_SETDEFAULT_UPD:
3244  case F_RI_FKEY_NOACTION_DEL:
3245  case F_RI_FKEY_NOACTION_UPD:
3246  return RI_TRIGGER_PK;
3247 
3248  case F_RI_FKEY_CHECK_INS:
3249  case F_RI_FKEY_CHECK_UPD:
3250  return RI_TRIGGER_FK;
3251  }
3252 
3253  return RI_TRIGGER_NONE;
3254 }
#define RI_TRIGGER_FK
Definition: trigger.h:268
#define RI_TRIGGER_PK
Definition: trigger.h:267
#define RI_TRIGGER_NONE
Definition: trigger.h:269

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

References appendStringInfo(), and generate_operator_clause().

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

2169 {
2170  appendStringInfo(buf, " %s ", sep);
2171  generate_operator_clause(buf, leftop, leftoptype, opoid,
2172  rightop, rightoptype);
2173 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:10907

◆ ri_GenerateQualCollation()

static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 2193 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().

2194 {
2195  HeapTuple tp;
2196  Form_pg_collation colltup;
2197  char *collname;
2198  char onename[MAX_QUOTED_NAME_LEN];
2199 
2200  /* Nothing to do if it's a noncollatable data type */
2201  if (!OidIsValid(collation))
2202  return;
2203 
2204  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2205  if (!HeapTupleIsValid(tp))
2206  elog(ERROR, "cache lookup failed for collation %u", collation);
2207  colltup = (Form_pg_collation) GETSTRUCT(tp);
2208  collname = NameStr(colltup->collname);
2209 
2210  /*
2211  * We qualify the name always, for simplicity and to ensure the query is
2212  * not search-path-dependent.
2213  */
2214  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2215  appendStringInfo(buf, " COLLATE %s", onename);
2216  quoteOneName(onename, collname);
2217  appendStringInfo(buf, ".%s", onename);
2218 
2219  ReleaseSysCache(tp);
2220 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define OidIsValid(objectId)
Definition: c.h:605
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#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:3051
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:49
#define NameStr(name)
Definition: c.h:576
#define elog
Definition: elog.h:219

◆ ri_HashCompareOp()

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

Definition at line 3139 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().

3140 {
3141  RI_CompareKey key;
3142  RI_CompareHashEntry *entry;
3143  bool found;
3144 
3145  /*
3146  * On the first call initialize the hashtable
3147  */
3148  if (!ri_compare_cache)
3150 
3151  /*
3152  * Find or create a hash entry. Note we're assuming RI_CompareKey
3153  * contains no struct padding.
3154  */
3155  key.eq_opr = eq_opr;
3156  key.typeid = typeid;
3158  (void *) &key,
3159  HASH_ENTER, &found);
3160  if (!found)
3161  entry->valid = false;
3162 
3163  /*
3164  * If not already initialized, do so. Since we'll keep this hash entry
3165  * for the life of the backend, put any subsidiary info for the function
3166  * cache structs into TopMemoryContext.
3167  */
3168  if (!entry->valid)
3169  {
3170  Oid lefttype,
3171  righttype,
3172  castfunc;
3173  CoercionPathType pathtype;
3174 
3175  /* We always need to know how to call the equality operator */
3176  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3178 
3179  /*
3180  * If we chose to use a cast from FK to PK type, we may have to apply
3181  * the cast function to get to the operator's input type.
3182  *
3183  * XXX eventually it would be good to support array-coercion cases
3184  * here and in ri_AttributesEqual(). At the moment there is no point
3185  * because cases involving nonidentical array types will be rejected
3186  * at constraint creation time.
3187  *
3188  * XXX perhaps also consider supporting CoerceViaIO? No need at the
3189  * moment since that will never be generated for implicit coercions.
3190  */
3191  op_input_types(eq_opr, &lefttype, &righttype);
3192  Assert(lefttype == righttype);
3193  if (typeid == lefttype)
3194  castfunc = InvalidOid; /* simplest case */
3195  else
3196  {
3197  pathtype = find_coercion_pathway(lefttype, typeid,
3199  &castfunc);
3200  if (pathtype != COERCION_PATH_FUNC &&
3201  pathtype != COERCION_PATH_RELABELTYPE)
3202  {
3203  /*
3204  * The declared input type of the eq_opr might be a
3205  * polymorphic type such as ANYARRAY or ANYENUM, or other
3206  * special cases such as RECORD; find_coercion_pathway
3207  * currently doesn't subsume these special cases.
3208  */
3209  if (!IsBinaryCoercible(typeid, lefttype))
3210  elog(ERROR, "no conversion function from %s to %s",
3211  format_type_be(typeid),
3212  format_type_be(lefttype));
3213  }
3214  }
3215  if (OidIsValid(castfunc))
3216  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3218  else
3220  entry->valid = true;
3221  }
3222 
3223  return entry;
3224 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
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:1152
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:134
MemoryContext TopMemoryContext
Definition: mcxt.c:44
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1079
Oid fn_oid
Definition: fmgr.h:59
#define Assert(condition)
Definition: c.h:699
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2917
#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 3010 of file ri_triggers.c.

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

Referenced by ri_PlanCheck().

3011 {
3012  RI_QueryHashEntry *entry;
3013  bool found;
3014 
3015  /*
3016  * On the first call initialize the hashtable
3017  */
3018  if (!ri_query_cache)
3020 
3021  /*
3022  * Add the new plan. We might be overwriting an entry previously found
3023  * invalid by ri_FetchPreparedPlan.
3024  */
3026  (void *) key,
3027  HASH_ENTER, &found);
3028  Assert(!found || entry->plan == NULL);
3029  entry->plan = plan;
3030 }
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:906
SPIPlanPtr plan
Definition: ri_triggers.c:148
#define Assert(condition)
Definition: c.h:699
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2917

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

Definition at line 2917 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().

2918 {
2919  HASHCTL ctl;
2920 
2921  memset(&ctl, 0, sizeof(ctl));
2922  ctl.keysize = sizeof(Oid);
2923  ctl.entrysize = sizeof(RI_ConstraintInfo);
2924  ri_constraint_cache = hash_create("RI constraint cache",
2926  &ctl, HASH_ELEM | HASH_BLOBS);
2927 
2928  /* Arrange to flush cache on pg_constraint changes */
2931  (Datum) 0);
2932 
2933  memset(&ctl, 0, sizeof(ctl));
2934  ctl.keysize = sizeof(RI_QueryKey);
2935  ctl.entrysize = sizeof(RI_QueryHashEntry);
2936  ri_query_cache = hash_create("RI query cache",
2938  &ctl, HASH_ELEM | HASH_BLOBS);
2939 
2940  memset(&ctl, 0, sizeof(ctl));
2941  ctl.keysize = sizeof(RI_CompareKey);
2942  ctl.entrysize = sizeof(RI_CompareHashEntry);
2943  ri_compare_cache = hash_create("RI compare cache",
2945  &ctl, HASH_ELEM | HASH_BLOBS);
2946 }
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:2490
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:367
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 1849 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().

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

◆ ri_KeysEqual()

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

Definition at line 3045 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().

3047 {
3048  TupleDesc tupdesc = RelationGetDescr(rel);
3049  const int16 *attnums;
3050  const Oid *eq_oprs;
3051  int i;
3052 
3053  if (rel_is_pk)
3054  {
3055  attnums = riinfo->pk_attnums;
3056  eq_oprs = riinfo->pp_eq_oprs;
3057  }
3058  else
3059  {
3060  attnums = riinfo->fk_attnums;
3061  eq_oprs = riinfo->ff_eq_oprs;
3062  }
3063 
3064  for (i = 0; i < riinfo->nkeys; i++)
3065  {
3066  Datum oldvalue;
3067  Datum newvalue;
3068  bool isnull;
3069 
3070  /*
3071  * Get one attribute's oldvalue. If it is NULL - they're not equal.
3072  */
3073  oldvalue = heap_getattr(oldtup, attnums[i], tupdesc, &isnull);
3074  if (isnull)
3075  return false;
3076 
3077  /*
3078  * Get one attribute's newvalue. If it is NULL - they're not equal.
3079  */
3080  newvalue = heap_getattr(newtup, attnums[i], tupdesc, &isnull);
3081  if (isnull)
3082  return false;
3083 
3084  /*
3085  * Compare them with the appropriate equality operator.
3086  */
3087  if (!ri_AttributesEqual(eq_oprs[i], RIAttType(rel, attnums[i]),
3088  oldvalue, newvalue))
3089  return false;
3090  }
3091 
3092  return true;
3093 }
signed short int16
Definition: c.h:312
#define RelationGetDescr(relation)
Definition: rel.h:433
#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:3105
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:781
uintptr_t Datum
Definition: postgres.h:367
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 2331 of file ri_triggers.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, RI_ConstraintInfo::confdeltype, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::confupdtype, RI_ConstraintInfo::conname, 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, RI_ConstraintInfo::nkeys, ObjectIdGetDatum, RI_ConstraintInfo::oidHashValue, 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().

2332 {
2333  RI_ConstraintInfo *riinfo;
2334  bool found;
2335  HeapTuple tup;
2336  Form_pg_constraint conForm;
2337  Datum adatum;
2338  bool isNull;
2339  ArrayType *arr;
2340  int numkeys;
2341 
2342  /*
2343  * On the first call initialize the hashtable
2344  */
2345  if (!ri_constraint_cache)
2347 
2348  /*
2349  * Find or create a hash entry. If we find a valid one, just return it.
2350  */
2352  (void *) &constraintOid,
2353  HASH_ENTER, &found);
2354  if (!found)
2355  riinfo->valid = false;
2356  else if (riinfo->valid)
2357  return riinfo;
2358 
2359  /*
2360  * Fetch the pg_constraint row so we can fill in the entry.
2361  */
2362  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2363  if (!HeapTupleIsValid(tup)) /* should not happen */
2364  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2365  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2366 
2367  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2368  elog(ERROR, "constraint %u is not a foreign key constraint",
2369  constraintOid);
2370 
2371  /* And extract data */
2372  Assert(riinfo->constraint_id == constraintOid);
2374  ObjectIdGetDatum(constraintOid));
2375  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2376  riinfo->pk_relid = conForm->confrelid;
2377  riinfo->fk_relid = conForm->conrelid;
2378  riinfo->confupdtype = conForm->confupdtype;
2379  riinfo->confdeltype = conForm->confdeltype;
2380  riinfo->confmatchtype = conForm->confmatchtype;
2381 
2382  /*
2383  * We expect the arrays to be 1-D arrays of the right types; verify that.
2384  * We don't need to use deconstruct_array() since the array data is just
2385  * going to look like a C array of values.
2386  */
2387  adatum = SysCacheGetAttr(CONSTROID, tup,
2388  Anum_pg_constraint_conkey, &isNull);
2389  if (isNull)
2390  elog(ERROR, "null conkey for constraint %u", constraintOid);
2391  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2392  if (ARR_NDIM(arr) != 1 ||
2393  ARR_HASNULL(arr) ||
2394  ARR_ELEMTYPE(arr) != INT2OID)
2395  elog(ERROR, "conkey is not a 1-D smallint array");
2396  numkeys = ARR_DIMS(arr)[0];
2397  if (numkeys <= 0 || numkeys > RI_MAX_NUMKEYS)
2398  elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
2399  riinfo->nkeys = numkeys;
2400  memcpy(riinfo->fk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2401  if ((Pointer) arr != DatumGetPointer(adatum))
2402  pfree(arr); /* free de-toasted copy, if any */
2403 
2404  adatum = SysCacheGetAttr(CONSTROID, tup,
2405  Anum_pg_constraint_confkey, &isNull);
2406  if (isNull)
2407  elog(ERROR, "null confkey for constraint %u", constraintOid);
2408  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2409  if (ARR_NDIM(arr) != 1 ||
2410  ARR_DIMS(arr)[0] != numkeys ||
2411  ARR_HASNULL(arr) ||
2412  ARR_ELEMTYPE(arr) != INT2OID)
2413  elog(ERROR, "confkey is not a 1-D smallint array");
2414  memcpy(riinfo->pk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2415  if ((Pointer) arr != DatumGetPointer(adatum))
2416  pfree(arr); /* free de-toasted copy, if any */
2417 
2418  adatum = SysCacheGetAttr(CONSTROID, tup,
2419  Anum_pg_constraint_conpfeqop, &isNull);
2420  if (isNull)
2421  elog(ERROR, "null conpfeqop for constraint %u", constraintOid);
2422  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2423  /* see TryReuseForeignKey if you change the test below */
2424  if (ARR_NDIM(arr) != 1 ||
2425  ARR_DIMS(arr)[0] != numkeys ||
2426  ARR_HASNULL(arr) ||
2427  ARR_ELEMTYPE(arr) != OIDOID)
2428  elog(ERROR, "conpfeqop is not a 1-D Oid array");
2429  memcpy(riinfo->pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2430  if ((Pointer) arr != DatumGetPointer(adatum))
2431  pfree(arr); /* free de-toasted copy, if any */
2432 
2433  adatum = SysCacheGetAttr(CONSTROID, tup,
2434  Anum_pg_constraint_conppeqop, &isNull);
2435  if (isNull)
2436  elog(ERROR, "null conppeqop for constraint %u", constraintOid);
2437  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2438  if (ARR_NDIM(arr) != 1 ||
2439  ARR_DIMS(arr)[0] != numkeys ||
2440  ARR_HASNULL(arr) ||
2441  ARR_ELEMTYPE(arr) != OIDOID)
2442  elog(ERROR, "conppeqop is not a 1-D Oid array");
2443  memcpy(riinfo->pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2444  if ((Pointer) arr != DatumGetPointer(adatum))
2445  pfree(arr); /* free de-toasted copy, if any */
2446 
2447  adatum = SysCacheGetAttr(CONSTROID, tup,
2448  Anum_pg_constraint_conffeqop, &isNull);
2449  if (isNull)
2450  elog(ERROR, "null conffeqop for constraint %u", constraintOid);
2451  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2452  if (ARR_NDIM(arr) != 1 ||
2453  ARR_DIMS(arr)[0] != numkeys ||
2454  ARR_HASNULL(arr) ||
2455  ARR_ELEMTYPE(arr) != OIDOID)
2456  elog(ERROR, "conffeqop is not a 1-D Oid array");
2457  memcpy(riinfo->ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2458  if ((Pointer) arr != DatumGetPointer(adatum))
2459  pfree(arr); /* free de-toasted copy, if any */
2460 
2461  ReleaseSysCache(tup);
2462 
2463  /*
2464  * For efficient processing of invalidation messages below, we keep a
2465  * doubly-linked list, and a count, of all currently valid entries.
2466  */
2469 
2470  riinfo->valid = true;
2471 
2472  return riinfo;
2473 }
signed short int16
Definition: c.h:312
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
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
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1031
char * Pointer
Definition: c.h:302
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#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:570
#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
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
uintptr_t Datum
Definition: postgres.h:367
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:78
#define Assert(condition)
Definition: c.h:699
#define ARR_NDIM(a)
Definition: array.h:275
#define DatumGetPointer(X)
Definition: postgres.h:534
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:185
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2917
#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 ( TupleDesc  tupdesc,
HeapTuple  tup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 2878 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().

2881 {
2882  const int16 *attnums;
2883  int i;
2884  bool allnull = true;
2885  bool nonenull = true;
2886 
2887  if (rel_is_pk)
2888  attnums = riinfo->pk_attnums;
2889  else
2890  attnums = riinfo->fk_attnums;
2891 
2892  for (i = 0; i < riinfo->nkeys; i++)
2893  {
2894  if (heap_attisnull(tup, attnums[i], tupDesc))
2895  nonenull = false;
2896  else
2897  allnull = false;
2898  }
2899 
2900  if (allnull)
2901  return RI_KEYS_ALL_NULL;
2902 
2903  if (nonenull)
2904  return RI_KEYS_NONE_NULL;
2905 
2906  return RI_KEYS_SOME_NULL;
2907 }
signed short int16
Definition: c.h:312
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:397
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
#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 2575 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, relowner, 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().

2580 {
2581  Relation query_rel,
2582  source_rel;
2583  bool source_is_pk;
2584  Snapshot test_snapshot;
2585  Snapshot crosscheck_snapshot;
2586  int limit;
2587  int spi_result;
2588  Oid save_userid;
2589  int save_sec_context;
2590  Datum vals[RI_MAX_NUMKEYS * 2];
2591  char nulls[RI_MAX_NUMKEYS * 2];
2592 
2593  /*
2594  * Use the query type code to determine whether the query is run against
2595  * the PK or FK table; we'll do the check as that table's owner
2596  */
2597  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2598  query_rel = pk_rel;
2599  else
2600  query_rel = fk_rel;
2601 
2602  /*
2603  * The values for the query are taken from the table on which the trigger
2604  * is called - it is normally the other one with respect to query_rel. An
2605  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2606  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2607  * need some less klugy way to determine this.
2608  */
2610  {
2611  source_rel = fk_rel;
2612  source_is_pk = false;
2613  }
2614  else
2615  {
2616  source_rel = pk_rel;
2617  source_is_pk = true;
2618  }
2619 
2620  /* Extract the parameters to be passed into the query */
2621  if (new_tuple)
2622  {
2623  ri_ExtractValues(source_rel, new_tuple, riinfo, source_is_pk,
2624  vals, nulls);
2625  if (old_tuple)
2626  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
2627  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2628  }
2629  else
2630  {
2631  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
2632  vals, nulls);
2633  }
2634 
2635  /*
2636  * In READ COMMITTED mode, we just need to use an up-to-date regular
2637  * snapshot, and we will see all rows that could be interesting. But in
2638  * transaction-snapshot mode, we can't change the transaction snapshot. If
2639  * the caller passes detectNewRows == false then it's okay to do the query
2640  * with the transaction snapshot; otherwise we use a current snapshot, and
2641  * tell the executor to error out if it finds any rows under the current
2642  * snapshot that wouldn't be visible per the transaction snapshot. Note
2643  * that SPI_execute_snapshot will register the snapshots, so we don't need
2644  * to bother here.
2645  */
2646  if (IsolationUsesXactSnapshot() && detectNewRows)
2647  {
2648  CommandCounterIncrement(); /* be sure all my own work is visible */
2649  test_snapshot = GetLatestSnapshot();
2650  crosscheck_snapshot = GetTransactionSnapshot();
2651  }
2652  else
2653  {
2654  /* the default SPI behavior is okay */
2655  test_snapshot = InvalidSnapshot;
2656  crosscheck_snapshot = InvalidSnapshot;
2657  }
2658 
2659  /*
2660  * If this is a select query (e.g., for a 'no action' or 'restrict'
2661  * trigger), we only need to see if there is a single row in the table,
2662  * matching the key. Otherwise, limit = 0 - because we want the query to
2663  * affect ALL the matching rows.
2664  */
2665  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2666 
2667  /* Switch to proper UID to perform check as */
2668  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2670  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2672 
2673  /* Finally we can run the query. */
2674  spi_result = SPI_execute_snapshot(qplan,
2675  vals, nulls,
2676  test_snapshot, crosscheck_snapshot,
2677  false, false, limit);
2678 
2679  /* Restore UID and security context */
2680  SetUserIdAndSecContext(save_userid, save_sec_context);
2681 
2682  /* Check result */
2683  if (spi_result < 0)
2684  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2685 
2686  if (expect_OK >= 0 && spi_result != expect_OK)
2687  ereport(ERROR,
2688  (errcode(ERRCODE_INTERNAL_ERROR),
2689  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2690  RelationGetRelationName(pk_rel),
2691  NameStr(riinfo->conname),
2692  RelationGetRelationName(fk_rel)),
2693  errhint("This is most likely due to a rule having rewritten the query.")));
2694 
2695  /* XXX wouldn't it be clearer to do this part at the caller? */
2697  expect_OK == SPI_OK_SELECT &&
2699  ri_ReportViolation(riinfo,
2700  pk_rel, fk_rel,
2701  new_tuple ? new_tuple : old_tuple,
2702  NULL,
2703  qkey->constr_queryno);
2704 
2705  return SPI_processed != 0;
2706 }
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:2744
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:401
int32 constr_queryno
Definition: ri_triggers.c:137
#define IsolationUsesXactSnapshot()
Definition: xact.h:50
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:1611
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:484
#define RelationGetRelationName(relation)
Definition: rel.h:441
#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:503
#define InvalidSnapshot
Definition: snapshot.h:25
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:914
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
#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:576
static void ri_ExtractValues(Relation rel, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2712
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:299
Oid relowner
Definition: pg_class.h:37
#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 2528 of file ri_triggers.c.

References RI_QueryKey::constr_queryno, elog, ERROR, GetUserIdAndSecContext(), RelationGetForm, relowner, 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().

2531 {
2532  SPIPlanPtr qplan;
2533  Relation query_rel;
2534  Oid save_userid;
2535  int save_sec_context;
2536 
2537  /*
2538  * Use the query type code to determine whether the query is run against
2539  * the PK or FK table; we'll do the check as that table's owner
2540  */
2541  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2542  query_rel = pk_rel;
2543  else
2544  query_rel = fk_rel;
2545 
2546  /* Switch to proper UID to perform check as */
2547  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2549  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2551 
2552  /* Create the plan */
2553  qplan = SPI_prepare(querystr, nargs, argtypes);
2554 
2555  if (qplan == NULL)
2556  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2557 
2558  /* Restore UID and security context */
2559  SetUserIdAndSecContext(save_userid, save_sec_context);
2560 
2561  /* Save the plan if requested */
2562  if (cache_plan)
2563  {
2564  SPI_keepplan(qplan);
2565  ri_HashPreparedPlan(qkey, qplan);
2566  }
2567 
2568  return qplan;
2569 }
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:401
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:578
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:1611
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:3010
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:656
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:484
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:299
Oid relowner
Definition: pg_class.h:37

◆ 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 2744 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().

2748 {
2749  StringInfoData key_names;
2750  StringInfoData key_values;
2751  bool onfk;
2752  const int16 *attnums;
2753  int idx;
2754  Oid rel_oid;
2755  AclResult aclresult;
2756  bool has_perm = true;
2757 
2758  /*
2759  * Determine which relation to complain about. If tupdesc wasn't passed
2760  * by caller, assume the violator tuple came from there.
2761  */
2762  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2763  if (onfk)
2764  {
2765  attnums = riinfo->fk_attnums;
2766  rel_oid = fk_rel->rd_id;
2767  if (tupdesc == NULL)
2768  tupdesc = fk_rel->rd_att;
2769  }
2770  else
2771  {
2772  attnums = riinfo->pk_attnums;
2773  rel_oid = pk_rel->rd_id;
2774  if (tupdesc == NULL)
2775  tupdesc = pk_rel->rd_att;
2776  }
2777 
2778  /*
2779  * Check permissions- if the user does not have access to view the data in
2780  * any of the key columns then we don't include the errdetail() below.
2781  *
2782  * Check if RLS is enabled on the relation first. If so, we don't return
2783  * any specifics to avoid leaking data.
2784  *
2785  * Check table-level permissions next and, failing that, column-level
2786  * privileges.
2787  */
2788 
2789  if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2790  {
2791  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2792  if (aclresult != ACLCHECK_OK)
2793  {
2794  /* Try for column-level permissions */
2795  for (idx = 0; idx < riinfo->nkeys; idx++)
2796  {
2797  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2798  GetUserId(),
2799  ACL_SELECT);
2800 
2801  /* No access to the key */
2802  if (aclresult != ACLCHECK_OK)
2803  {
2804  has_perm = false;
2805  break;
2806  }
2807  }
2808  }
2809  }
2810  else
2811  has_perm = false;
2812 
2813  if (has_perm)
2814  {
2815  /* Get printable versions of the keys involved */
2816  initStringInfo(&key_names);
2817  initStringInfo(&key_values);
2818  for (idx = 0; idx < riinfo->nkeys; idx++)
2819  {
2820  int fnum = attnums[idx];
2821  char *name,
2822  *val;
2823 
2824  name = SPI_fname(tupdesc, fnum);
2825  val = SPI_getvalue(violator, tupdesc, fnum);
2826  if (!val)
2827  val = "null";
2828 
2829  if (idx > 0)
2830  {
2831  appendStringInfoString(&key_names, ", ");
2832  appendStringInfoString(&key_values, ", ");
2833  }
2834  appendStringInfoString(&key_names, name);
2835  appendStringInfoString(&key_values, val);
2836  }
2837  }
2838 
2839  if (onfk)
2840  ereport(ERROR,
2841  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2842  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2843  RelationGetRelationName(fk_rel),
2844  NameStr(riinfo->conname)),
2845  has_perm ?
2846  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2847  key_names.data, key_values.data,
2848  RelationGetRelationName(pk_rel)) :
2849  errdetail("Key is not present in table \"%s\".",
2850  RelationGetRelationName(pk_rel)),
2851  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2852  else
2853  ereport(ERROR,
2854  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2855  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2856  RelationGetRelationName(pk_rel),
2857  NameStr(riinfo->conname),
2858  RelationGetRelationName(fk_rel)),
2859  has_perm ?
2860  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2861  key_names.data, key_values.data,
2862  RelationGetRelationName(fk_rel)) :
2863  errdetail("Key is still referenced from table \"%s\".",
2864  RelationGetRelationName(fk_rel)),
2865  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2866 }
signed short int16
Definition: c.h:312
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4513
Oid GetUserId(void)
Definition: miscinit.c:379
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:880
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:902
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5247
#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:441
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
Oid rd_id
Definition: rel.h:86
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:178
#define ACL_SELECT
Definition: parsenodes.h:75
TupleDesc rd_att
Definition: rel.h:85
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
const char * name
Definition: encode.c:521
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4627
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:576
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 688 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, 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(), RelationData::rd_rel, RelationGetDescr, 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().

689 {
690  const RI_ConstraintInfo *riinfo;
691  Relation fk_rel;
692  Relation pk_rel;
693  HeapTuple old_row;
694  RI_QueryKey qkey;
695  SPIPlanPtr qplan;
696 
697  /*
698  * Get arguments.
699  */
700  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
701  trigdata->tg_relation, true);
702 
703  /*
704  * Get the relation descriptors of the FK and PK tables and the old tuple.
705  *
706  * fk_rel is opened in RowShareLock mode since that's what our eventual
707  * SELECT FOR KEY SHARE will get on it.
708  */
709  fk_rel = heap_open(riinfo->fk_relid, RowShareLock);
710  pk_rel = trigdata->tg_relation;
711  old_row = trigdata->tg_trigtuple;
712 
713  switch (riinfo->confmatchtype)
714  {
715  /* ----------
716  * SQL:2008 15.17 <Execution of referential actions>
717  * General rules 9) a) iv):
718  * MATCH SIMPLE/FULL
719  * ... ON DELETE RESTRICT
720  * General rules 10) a) iv):
721  * MATCH SIMPLE/FULL
722  * ... ON UPDATE RESTRICT
723  * ----------
724  */
726  case FKCONSTR_MATCH_FULL:
727  switch (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true))
728  {
729  case RI_KEYS_ALL_NULL:
730  case RI_KEYS_SOME_NULL:
731 
732  /*
733  * No check needed - there cannot be any reference to old
734  * key if it contains a NULL
735  */
736  heap_close(fk_rel, RowShareLock);
737  return PointerGetDatum(NULL);
738 
739  case RI_KEYS_NONE_NULL:
740 
741  /*
742  * Have a full qualified key - continue below
743  */
744  break;
745  }
746 
747  /*
748  * In UPDATE, no need to do anything if old and new keys are equal
749  */
750  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
751  {
752  HeapTuple new_row = trigdata->tg_newtuple;
753 
754  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
755  {
756  heap_close(fk_rel, RowShareLock);
757  return PointerGetDatum(NULL);
758  }
759  }
760 
761  /*
762  * If another PK row now exists providing the old key values, we
763  * should not do anything. However, this check should only be
764  * made in the NO ACTION case; in RESTRICT cases we don't wish to
765  * allow another row to be substituted.
766  */
767  if (is_no_action &&
768  ri_Check_Pk_Match(pk_rel, fk_rel, old_row, riinfo))
769  {
770  heap_close(fk_rel, RowShareLock);
771  return PointerGetDatum(NULL);
772  }
773 
774  if (SPI_connect() != SPI_OK_CONNECT)
775  elog(ERROR, "SPI_connect failed");
776 
777  /*
778  * Fetch or prepare a saved plan for the restrict lookup (it's the
779  * same query for delete and update cases)
780  */
782 
783  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
784  {
785  StringInfoData querybuf;
786  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
788  char paramname[16];
789  const char *querysep;
790  Oid queryoids[RI_MAX_NUMKEYS];
791  const char *fk_only;
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  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
804  "" : "ONLY ";
805  quoteRelationName(fkrelname, fk_rel);
806  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
807  fk_only, fkrelname);
808  querysep = "WHERE";
809  for (i = 0; i < riinfo->nkeys; i++)
810  {
811  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
812  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
813 
814  quoteOneName(attname,
815  RIAttName(fk_rel, riinfo->fk_attnums[i]));
816  sprintf(paramname, "$%d", i + 1);
817  ri_GenerateQual(&querybuf, querysep,
818  paramname, pk_type,
819  riinfo->pf_eq_oprs[i],
820  attname, fk_type);
821  querysep = "AND";
822  queryoids[i] = pk_type;
823  }
824  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
825 
826  /* Prepare and save the plan */
827  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
828  &qkey, fk_rel, pk_rel, true);
829  }
830 
831  /*
832  * We have a plan now. Run it to check for existing references.
833  */
834  ri_PerformCheck(riinfo, &qkey, qplan,
835  fk_rel, pk_rel,
836  old_row, NULL,
837  true, /* must detect new rows */
838  SPI_OK_SELECT);
839 
840  if (SPI_finish() != SPI_OK_FINISH)
841  elog(ERROR, "SPI_finish failed");
842 
843  heap_close(fk_rel, RowShareLock);
844 
845  return PointerGetDatum(NULL);
846 
847  /*
848  * Handle MATCH PARTIAL restrict delete or update.
849  */
851  ereport(ERROR,
852  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
853  errmsg("MATCH PARTIAL not yet implemented")));
854  return PointerGetDatum(NULL);
855 
856  default:
857  elog(ERROR, "unrecognized confmatchtype: %d",
858  riinfo->confmatchtype);
859  break;
860  }
861 
862  /* Never reached */
863  return PointerGetDatum(NULL);
864 }
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:2164
#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:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:541
int SPI_finish(void)
Definition: spi.c:161
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
Form_pg_class rd_rel
Definition: rel.h:84
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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
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:2295
#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:507
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#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:2528
#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:2234
#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:3045
Relation tg_relation
Definition: trigger.h:34

◆ ri_setdefault()

static Datum ri_setdefault ( TriggerData trigdata)
static

Definition at line 1480 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, 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(), RelationData::rd_rel, RelationGetDescr, 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().

1481 {
1482  const RI_ConstraintInfo *riinfo;
1483  Relation fk_rel;
1484  Relation pk_rel;
1485  HeapTuple old_row;
1486  RI_QueryKey qkey;
1487  SPIPlanPtr qplan;
1488 
1489  /*
1490  * Get arguments.
1491  */
1492  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1493  trigdata->tg_relation, true);
1494 
1495  /*
1496  * Get the relation descriptors of the FK and PK tables and the old tuple.
1497  *
1498  * fk_rel is opened in RowExclusiveLock mode since that's what our
1499  * eventual UPDATE will get on it.
1500  */
1501  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1502  pk_rel = trigdata->tg_relation;
1503  old_row = trigdata->tg_trigtuple;
1504 
1505  switch (riinfo->confmatchtype)
1506  {
1507  /* ----------
1508  * SQL:2008 15.17 <Execution of referential actions>
1509  * General rules 9) a) iii):
1510  * MATCH SIMPLE/FULL
1511  * ... ON DELETE SET DEFAULT
1512  * General rules 10) a) iii):
1513  * MATCH SIMPLE/FULL
1514  * ... ON UPDATE SET DEFAULT
1515  * ----------
1516  */
1517  case FKCONSTR_MATCH_SIMPLE:
1518  case FKCONSTR_MATCH_FULL:
1519  switch (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true))
1520  {
1521  case RI_KEYS_ALL_NULL:
1522  case RI_KEYS_SOME_NULL:
1523 
1524  /*
1525  * No check needed - there cannot be any reference to old
1526  * key if it contains a NULL
1527  */
1528  heap_close(fk_rel, RowExclusiveLock);
1529  return PointerGetDatum(NULL);
1530 
1531  case RI_KEYS_NONE_NULL:
1532 
1533  /*
1534  * Have a full qualified key - continue below
1535  */
1536  break;
1537  }
1538 
1539  /*
1540  * In UPDATE, no need to do anything if old and new keys are equal
1541  */
1542  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1543  {
1544  HeapTuple new_row = trigdata->tg_newtuple;
1545 
1546  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1547  {
1548  heap_close(fk_rel, RowExclusiveLock);
1549  return PointerGetDatum(NULL);
1550  }
1551  }
1552 
1553  if (SPI_connect() != SPI_OK_CONNECT)
1554  elog(ERROR, "SPI_connect failed");
1555 
1556  /*
1557  * Fetch or prepare a saved plan for the set default operation
1558  * (it's the same query for delete and update cases)
1559  */
1561 
1562  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1563  {
1564  StringInfoData querybuf;
1565  StringInfoData qualbuf;
1566  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1568  char paramname[16];
1569  const char *querysep;
1570  const char *qualsep;
1571  Oid queryoids[RI_MAX_NUMKEYS];
1572  const char *fk_only;
1573  int i;
1574 
1575  /* ----------
1576  * The query string built is
1577  * UPDATE [ONLY] <fktable> SET fkatt1 = DEFAULT [, ...]
1578  * WHERE $1 = fkatt1 [AND ...]
1579  * The type id's for the $ parameters are those of the
1580  * corresponding PK attributes.
1581  * ----------
1582  */
1583  initStringInfo(&querybuf);
1584  initStringInfo(&qualbuf);
1585  quoteRelationName(fkrelname, fk_rel);
1586  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1587  "" : "ONLY ";
1588  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1589  fk_only, fkrelname);
1590  querysep = "";
1591  qualsep = "WHERE";
1592  for (i = 0; i < riinfo->nkeys; i++)
1593  {
1594  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1595  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1596 
1597  quoteOneName(attname,
1598  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1599  appendStringInfo(&querybuf,
1600  "%s %s = DEFAULT",
1601  querysep, attname);
1602  sprintf(paramname, "$%d", i + 1);
1603  ri_GenerateQual(&qualbuf, qualsep,
1604  paramname, pk_type,
1605  riinfo->pf_eq_oprs[i],
1606  attname, fk_type);
1607  querysep = ",";
1608  qualsep = "AND";
1609  queryoids[i] = pk_type;
1610  }
1611  appendStringInfoString(&querybuf, qualbuf.data);
1612 
1613  /* Prepare and save the plan */
1614  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1615  &qkey, fk_rel, pk_rel, true);
1616  }
1617 
1618  /*
1619  * We have a plan now. Run it to update the existing references.
1620  */
1621  ri_PerformCheck(riinfo, &qkey, qplan,
1622  fk_rel, pk_rel,
1623  old_row, NULL,
1624  true, /* must detect new rows */
1625  SPI_OK_UPDATE);
1626 
1627  if (SPI_finish() != SPI_OK_FINISH)
1628  elog(ERROR, "SPI_finish failed");
1629 
1630  heap_close(fk_rel, RowExclusiveLock);
1631 
1632  /*
1633  * If we just deleted or updated the PK row whose key was equal to
1634  * the FK columns' default values, and a referencing row exists in
1635  * the FK table, we would have updated that row to the same values
1636  * it already had --- and RI_FKey_fk_upd_check_required would
1637  * hence believe no check is necessary. So we need to do another
1638  * lookup now and in case a reference still exists, abort the
1639  * operation. That is already implemented in the NO ACTION
1640  * trigger, so just run it. (This recheck is only needed in the
1641  * SET DEFAULT case, since CASCADE would remove such rows in case
1642  * of a DELETE operation or would change the FK key values in case
1643  * of an UPDATE, while SET NULL is certain to result in rows that
1644  * satisfy the FK constraint.)
1645  */
1646  return ri_restrict(trigdata, true);
1647 
1648  /*
1649  * Handle MATCH PARTIAL set default delete or update.
1650  */
1652  ereport(ERROR,
1653  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1654  errmsg("MATCH PARTIAL not yet implemented")));
1655  return PointerGetDatum(NULL);
1656 
1657  default:
1658  elog(ERROR, "unrecognized confmatchtype: %d",
1659  riinfo->confmatchtype);
1660  break;
1661  }
1662 
1663  /* Never reached */
1664  return PointerGetDatum(NULL);
1665 }
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:2164
#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:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:541
int SPI_finish(void)
Definition: spi.c:161
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:688
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
Form_pg_class rd_rel
Definition: rel.h:84
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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
#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:2295
#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:1294
#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:2528
#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:2234
#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:3045
Relation tg_relation
Definition: trigger.h:34

◆ ri_setnull()

static Datum ri_setnull ( TriggerData trigdata)
static

Definition at line 1259 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, 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(), RelationData::rd_rel, RelationGetDescr, 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().

1260 {
1261  const RI_ConstraintInfo *riinfo;
1262  Relation fk_rel;
1263  Relation pk_rel;
1264  HeapTuple old_row;
1265  RI_QueryKey qkey;
1266  SPIPlanPtr qplan;
1267  int i;
1268 
1269  /*
1270  * Get arguments.
1271  */
1272  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1273  trigdata->tg_relation, true);
1274 
1275  /*
1276  * Get the relation descriptors of the FK and PK tables and the old tuple.
1277  *
1278  * fk_rel is opened in RowExclusiveLock mode since that's what our
1279  * eventual UPDATE will get on it.
1280  */
1281  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1282  pk_rel = trigdata->tg_relation;
1283  old_row = trigdata->tg_trigtuple;
1284 
1285  switch (riinfo->confmatchtype)
1286  {
1287  /* ----------
1288  * SQL:2008 15.17 <Execution of referential actions>
1289  * General rules 9) a) ii):
1290  * MATCH SIMPLE/FULL
1291  * ... ON DELETE SET NULL
1292  * General rules 10) a) ii):
1293  * MATCH SIMPLE/FULL
1294  * ... ON UPDATE SET NULL
1295  * ----------
1296  */
1297  case FKCONSTR_MATCH_SIMPLE:
1298  case FKCONSTR_MATCH_FULL:
1299  switch (ri_NullCheck(RelationGetDescr(pk_rel), old_row, riinfo, true))
1300  {
1301  case RI_KEYS_ALL_NULL:
1302  case RI_KEYS_SOME_NULL:
1303 
1304  /*
1305  * No check needed - there cannot be any reference to old
1306  * key if it contains a NULL
1307  */
1308  heap_close(fk_rel, RowExclusiveLock);
1309  return PointerGetDatum(NULL);
1310 
1311  case RI_KEYS_NONE_NULL:
1312 
1313  /*
1314  * Have a full qualified key - continue below
1315  */
1316  break;
1317  }
1318 
1319  /*
1320  * In UPDATE, no need to do anything if old and new keys are equal
1321  */
1322  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1323  {
1324  HeapTuple new_row = trigdata->tg_newtuple;
1325 
1326  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1327  {
1328  heap_close(fk_rel, RowExclusiveLock);
1329  return PointerGetDatum(NULL);
1330  }
1331  }
1332 
1333  if (SPI_connect() != SPI_OK_CONNECT)
1334  elog(ERROR, "SPI_connect failed");
1335 
1336  /*
1337  * Fetch or prepare a saved plan for the set null operation (it's
1338  * the same query for delete and update cases)
1339  */
1341 
1342  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1343  {
1344  StringInfoData querybuf;
1345  StringInfoData qualbuf;
1346  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1348  char paramname[16];
1349  const char *querysep;
1350  const char *qualsep;
1351  const char *fk_only;
1352  Oid queryoids[RI_MAX_NUMKEYS];
1353 
1354  /* ----------
1355  * The query string built is
1356  * UPDATE [ONLY] <fktable> SET fkatt1 = NULL [, ...]
1357  * WHERE $1 = fkatt1 [AND ...]
1358  * The type id's for the $ parameters are those of the
1359  * corresponding PK attributes.
1360  * ----------
1361  */
1362  initStringInfo(&querybuf);
1363  initStringInfo(&qualbuf);
1364  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1365  "" : "ONLY ";
1366  quoteRelationName(fkrelname, fk_rel);
1367  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1368  fk_only, fkrelname);
1369  querysep = "";
1370  qualsep = "WHERE";
1371  for (i = 0; i < riinfo->nkeys; i++)
1372  {
1373  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1374  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1375 
1376  quoteOneName(attname,
1377  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1378  appendStringInfo(&querybuf,
1379  "%s %s = NULL",
1380  querysep, attname);
1381  sprintf(paramname, "$%d", i + 1);
1382  ri_GenerateQual(&qualbuf, qualsep,
1383  paramname, pk_type,
1384  riinfo->pf_eq_oprs[i],
1385  attname, fk_type);
1386  querysep = ",";
1387  qualsep = "AND";
1388  queryoids[i] = pk_type;
1389  }
1390  appendStringInfoString(&querybuf, qualbuf.data);
1391 
1392  /* Prepare and save the plan */
1393  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1394  &qkey, fk_rel, pk_rel, true);
1395  }
1396 
1397  /*
1398  * We have a plan now. Run it to update the existing references.
1399  */
1400  ri_PerformCheck(riinfo, &qkey, qplan,
1401  fk_rel, pk_rel,
1402  old_row, NULL,
1403  true, /* must detect new rows */
1404  SPI_OK_UPDATE);
1405 
1406  if (SPI_finish() != SPI_OK_FINISH)
1407  elog(ERROR, "SPI_finish failed");
1408 
1409  heap_close(fk_rel, RowExclusiveLock);
1410 
1411  return PointerGetDatum(NULL);
1412 
1413  /*
1414  * Handle MATCH PARTIAL set null delete or update.
1415  */
1417  ereport(ERROR,
1418  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1419  errmsg("MATCH PARTIAL not yet implemented")));
1420  return PointerGetDatum(NULL);
1421 
1422  default:
1423  elog(ERROR, "unrecognized confmatchtype: %d",
1424  riinfo->confmatchtype);
1425  break;
1426  }
1427 
1428  /* Never reached */
1429  return PointerGetDatum(NULL);
1430 }
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:2164
#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:2147
#define RelationGetDescr(relation)
Definition: rel.h:433
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:541
int SPI_finish(void)
Definition: spi.c:161
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
Form_pg_class rd_rel
Definition: rel.h:84
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:2127
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#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:2575
static int ri_NullCheck(TupleDesc tupdesc, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2878
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2957
#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:2295
#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:1294
#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:2528
#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:2234
#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:3045
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.