PostgreSQL Source Code  git master
ri_triggers.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "lib/ilist.h"
#include "miscadmin.h"
#include "parser/parse_coerce.h"
#include "parser/parse_relation.h"
#include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for ri_triggers.c:

Go to the source code of this file.

Data Structures

struct  RI_ConstraintInfo
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 

Macros

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS
 
#define RI_INIT_CONSTRAINTHASHSIZE   64
 
#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)
 
#define RI_KEYS_ALL_NULL   0
 
#define RI_KEYS_SOME_NULL   1
 
#define RI_KEYS_NONE_NULL   2
 
#define RI_PLAN_CHECK_LOOKUPPK   1
 
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2
 
#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK
 
#define RI_PLAN_CASCADE_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, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
 
static Datum ri_restrict (TriggerData *trigdata, bool is_no_action)
 
static Datum ri_set (TriggerData *trigdata, bool is_set_null)
 
static void quoteOneName (char *buffer, const char *name)
 
static void quoteRelationName (char *buffer, Relation rel)
 
static void ri_GenerateQual (StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
static void ri_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static void ri_BuildQueryKey (RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
 
static bool ri_KeysEqual (Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static bool ri_AttributesEqual (Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
 
static void ri_InitHashTables (void)
 
static void InvalidateConstraintCacheCallBack (Datum arg, int cacheid, uint32 hashvalue)
 
static SPIPlanPtr ri_FetchPreparedPlan (RI_QueryKey *key)
 
static void ri_HashPreparedPlan (RI_QueryKey *key, SPIPlanPtr plan)
 
static RI_CompareHashEntryri_HashCompareOp (Oid eq_opr, Oid typeid)
 
static void ri_CheckTrigger (FunctionCallInfo fcinfo, const char *funcname, int tgkind)
 
static const RI_ConstraintInfori_FetchConstraintInfo (Trigger *trigger, Relation trig_rel, bool rel_is_pk)
 
static const RI_ConstraintInfori_LoadConstraintInfo (Oid constraintOid)
 
static SPIPlanPtr ri_PlanCheck (const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
 
static bool ri_PerformCheck (const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
 
static void ri_ExtractValues (Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
 
static void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
 
static Datum RI_FKey_check (TriggerData *trigdata)
 
Datum RI_FKey_check_ins (PG_FUNCTION_ARGS)
 
Datum RI_FKey_check_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_upd (PG_FUNCTION_ARGS)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
void RI_PartitionRemove_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

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

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

◆ MAX_QUOTED_REL_NAME_LEN

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 63 of file ri_triggers.c.

Referenced by ri_InitHashTables().

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 64 of file ri_triggers.c.

Referenced by ri_InitHashTables().

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 66 of file ri_triggers.c.

Referenced by RI_FKey_check(), RI_FKey_fk_upd_check_required(), and ri_NullCheck().

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 67 of file ri_triggers.c.

Referenced by RI_FKey_check(), RI_FKey_fk_upd_check_required(), and ri_NullCheck().

◆ RI_MAX_NUMKEYS

◆ RI_PLAN_CASCADE_DEL_DODELETE

#define RI_PLAN_CASCADE_DEL_DODELETE   3

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

Referenced by RI_FKey_cascade_upd().

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

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

Referenced by ri_restrict().

◆ RI_PLAN_SETDEFAULT_DOUPDATE

#define RI_PLAN_SETDEFAULT_DOUPDATE   7

Definition at line 80 of file ri_triggers.c.

Referenced by ri_set().

◆ RI_PLAN_SETNULL_DOUPDATE

#define RI_PLAN_SETNULL_DOUPDATE   6

Definition at line 79 of file ri_triggers.c.

Referenced by ri_set().

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 89 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)

◆ RIAttName

◆ RIAttType

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

typedef struct RI_CompareKey RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

typedef struct RI_QueryKey RI_QueryKey

Function Documentation

◆ InvalidateConstraintCacheCallBack()

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

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

2091 {
2092  dlist_mutable_iter iter;
2093 
2094  Assert(ri_constraint_cache != NULL);
2095 
2096  /*
2097  * If the list of currently valid entries gets excessively large, we mark
2098  * them all invalid so we can empty the list. This arrangement avoids
2099  * O(N^2) behavior in situations where a session touches many foreign keys
2100  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2101  */
2103  hashvalue = 0; /* pretend it's a cache reset */
2104 
2106  {
2108  valid_link, iter.cur);
2109 
2110  if (hashvalue == 0 || riinfo->oidHashValue == hashvalue)
2111  {
2112  riinfo->valid = false;
2113  /* Remove invalidated entries from the list, too */
2114  dlist_delete(iter.cur);
2116  }
2117  }
2118 }
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:166
#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:170
#define Assert(condition)
Definition: c.h:739
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:169

◆ quoteOneName()

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

Definition at line 1784 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_PartitionRemove_Check(), ri_restrict(), and ri_set().

1785 {
1786  /* Rather than trying to be smart, just always quote it. */
1787  *buffer++ = '"';
1788  while (*name)
1789  {
1790  if (*name == '"')
1791  *buffer++ = '"';
1792  *buffer++ = *name++;
1793  }
1794  *buffer++ = '"';
1795  *buffer = '\0';
1796 }
const char * name
Definition: encode.c:521

◆ quoteRelationName()

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

Definition at line 1804 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_PartitionRemove_Check(), ri_restrict(), and ri_set().

1805 {
1807  buffer += strlen(buffer);
1808  *buffer++ = '.';
1809  quoteOneName(buffer, RelationGetRelationName(rel));
1810 }
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define RelationGetNamespace(relation)
Definition: rel.h:463

◆ ri_AttributesEqual()

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

Definition at line 2727 of file ri_triggers.c.

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

Referenced by ri_KeysEqual().

2729 {
2730  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
2731 
2732  /* Do we need to cast the values? */
2733  if (OidIsValid(entry->cast_func_finfo.fn_oid))
2734  {
2735  oldvalue = FunctionCall3(&entry->cast_func_finfo,
2736  oldvalue,
2737  Int32GetDatum(-1), /* typmod */
2738  BoolGetDatum(false)); /* implicit coercion */
2739  newvalue = FunctionCall3(&entry->cast_func_finfo,
2740  newvalue,
2741  Int32GetDatum(-1), /* typmod */
2742  BoolGetDatum(false)); /* implicit coercion */
2743  }
2744 
2745  /*
2746  * Apply the comparison operator.
2747  *
2748  * Note: This function is part of a call stack that determines whether an
2749  * update to a row is significant enough that it needs checking or action
2750  * on the other side of a foreign-key constraint. Therefore, the
2751  * comparison here would need to be done with the collation of the *other*
2752  * table. For simplicity (e.g., we might not even have the other table
2753  * open), we'll just use the default collation here, which could lead to
2754  * some false negatives. All this would break if we ever allow
2755  * database-wide collations to be nondeterministic.
2756  */
2758  DEFAULT_COLLATION_OID,
2759  oldvalue, newvalue));
2760 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define OidIsValid(objectId)
Definition: c.h:645
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:637
#define DatumGetBool(X)
Definition: postgres.h:393
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:2769
#define BoolGetDatum(X)
Definition: postgres.h:402
Oid fn_oid
Definition: fmgr.h:59
#define Int32GetDatum(X)
Definition: postgres.h:479
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:159

◆ ri_BuildQueryKey()

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

Definition at line 1891 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(), and ri_set().

1893 {
1894  /*
1895  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
1896  * to use memset to clear them.
1897  */
1898  key->constr_id = riinfo->constraint_id;
1899  key->constr_queryno = constr_queryno;
1900 }
int32 constr_queryno
Definition: ri_triggers.c:128

◆ ri_Check_Pk_Match()

static bool ri_Check_Pk_Match ( Relation  pk_rel,
Relation  fk_rel,
TupleTableSlot oldslot,
const RI_ConstraintInfo riinfo 
)
static

Definition at line 450 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(), RelationData::rd_rel, RelationGetDescr, ri_BuildQueryKey(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_NONE_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK_FROM_PK, ri_PlanCheck(), RIAttName, RIAttType, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, and sprintf.

Referenced by ri_restrict().

453 {
454  SPIPlanPtr qplan;
455  RI_QueryKey qkey;
456  bool result;
457 
458  /* Only called for non-null rows */
459  Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
460 
461  if (SPI_connect() != SPI_OK_CONNECT)
462  elog(ERROR, "SPI_connect failed");
463 
464  /*
465  * Fetch or prepare a saved plan for checking PK table with values coming
466  * from a PK row
467  */
469 
470  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
471  {
472  StringInfoData querybuf;
473  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
475  char paramname[16];
476  const char *querysep;
477  const char *pk_only;
478  Oid queryoids[RI_MAX_NUMKEYS];
479 
480  /* ----------
481  * The query string built is
482  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
483  * FOR KEY SHARE OF x
484  * The type id's for the $ parameters are those of the
485  * PK attributes themselves.
486  * ----------
487  */
488  initStringInfo(&querybuf);
489  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
490  "" : "ONLY ";
491  quoteRelationName(pkrelname, pk_rel);
492  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
493  pk_only, pkrelname);
494  querysep = "WHERE";
495  for (int i = 0; i < riinfo->nkeys; i++)
496  {
497  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
498 
499  quoteOneName(attname,
500  RIAttName(pk_rel, riinfo->pk_attnums[i]));
501  sprintf(paramname, "$%d", i + 1);
502  ri_GenerateQual(&querybuf, querysep,
503  attname, pk_type,
504  riinfo->pp_eq_oprs[i],
505  paramname, pk_type);
506  querysep = "AND";
507  queryoids[i] = pk_type;
508  }
509  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
510 
511  /* Prepare and save the plan */
512  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
513  &qkey, fk_rel, pk_rel);
514  }
515 
516  /*
517  * We have a plan now. Run it.
518  */
519  result = ri_PerformCheck(riinfo, &qkey, qplan,
520  fk_rel, pk_rel,
521  oldslot, NULL,
522  true, /* treat like update */
523  SPI_OK_SELECT);
524 
525  if (SPI_finish() != SPI_OK_FINISH)
526  elog(ERROR, "SPI_finish failed");
527 
528  return result;
529 }
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
#define RelationGetDescr(relation)
Definition: rel.h:448
int SPI_connect(void)
Definition: spi.c:89
int SPI_finish(void)
Definition: spi.c:176
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:115
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
#define SPI_OK_SELECT
Definition: spi.h:57
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:73
#define Assert(condition)
Definition: c.h:739
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2494
#define SPI_OK_FINISH
Definition: spi.h:54
#define elog(elevel,...)
Definition: elog.h:228
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68

◆ ri_CheckTrigger()

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

Definition at line 1906 of file ri_triggers.c.

References CALLED_AS_TRIGGER, FunctionCallInfoBaseData::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().

1907 {
1908  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1909 
1910  if (!CALLED_AS_TRIGGER(fcinfo))
1911  ereport(ERROR,
1912  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1913  errmsg("function \"%s\" was not called by trigger manager", funcname)));
1914 
1915  /*
1916  * Check proper event
1917  */
1918  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
1919  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1920  ereport(ERROR,
1921  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1922  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
1923 
1924  switch (tgkind)
1925  {
1926  case RI_TRIGTYPE_INSERT:
1927  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1928  ereport(ERROR,
1929  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1930  errmsg("function \"%s\" must be fired for INSERT", funcname)));
1931  break;
1932  case RI_TRIGTYPE_UPDATE:
1933  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1934  ereport(ERROR,
1935  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1936  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
1937  break;
1938  case RI_TRIGTYPE_DELETE:
1939  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1940  ereport(ERROR,
1941  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1942  errmsg("function \"%s\" must be fired for DELETE", funcname)));
1943  break;
1944  }
1945 }
int errcode(int sqlerrcode)
Definition: elog.c:608
fmNodePtr context
Definition: fmgr.h:88
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:137
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:119
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90
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:822
#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:89

◆ ri_ExtractValues()

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

Definition at line 2308 of file ri_triggers.c.

References RI_ConstraintInfo::fk_attnums, i, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pk_attnums, and slot_getattr().

Referenced by ri_PerformCheck().

2311 {
2312  const int16 *attnums;
2313  bool isnull;
2314 
2315  if (rel_is_pk)
2316  attnums = riinfo->pk_attnums;
2317  else
2318  attnums = riinfo->fk_attnums;
2319 
2320  for (int i = 0; i < riinfo->nkeys; i++)
2321  {
2322  vals[i] = slot_getattr(slot, attnums[i], &isnull);
2323  nulls[i] = isnull ? 'n' : ' ';
2324  }
2325 }
signed short int16
Definition: c.h:346
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113

◆ ri_FetchConstraintInfo()

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

Definition at line 1952 of file ri_triggers.c.

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

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

1953 {
1954  Oid constraintOid = trigger->tgconstraint;
1955  const RI_ConstraintInfo *riinfo;
1956 
1957  /*
1958  * Check that the FK constraint's OID is available; it might not be if
1959  * we've been invoked via an ordinary trigger or an old-style "constraint
1960  * trigger".
1961  */
1962  if (!OidIsValid(constraintOid))
1963  ereport(ERROR,
1964  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1965  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
1966  trigger->tgname, RelationGetRelationName(trig_rel)),
1967  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
1968 
1969  /* Find or create a hashtable entry for the constraint */
1970  riinfo = ri_LoadConstraintInfo(constraintOid);
1971 
1972  /* Do some easy cross-checks against the trigger call data */
1973  if (rel_is_pk)
1974  {
1975  if (riinfo->fk_relid != trigger->tgconstrrelid ||
1976  riinfo->pk_relid != RelationGetRelid(trig_rel))
1977  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
1978  trigger->tgname, RelationGetRelationName(trig_rel));
1979  }
1980  else
1981  {
1982  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
1983  riinfo->pk_relid != trigger->tgconstrrelid)
1984  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
1985  trigger->tgname, RelationGetRelationName(trig_rel));
1986  }
1987 
1988  if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
1991  elog(ERROR, "unrecognized confmatchtype: %d",
1992  riinfo->confmatchtype);
1993 
1994  if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
1995  ereport(ERROR,
1996  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1997  errmsg("MATCH PARTIAL not yet implemented")));
1998 
1999  return riinfo;
2000 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2124
int errhint(const char *fmt,...)
Definition: elog.c:1069
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:456
Oid tgconstrrelid
Definition: reltrigger.h:32
#define ereport(elevel, rest)
Definition: elog.h:141
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2122
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2006
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2123
#define RelationGetRelid(relation)
Definition: rel.h:422

◆ ri_FetchPreparedPlan()

static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 2570 of file ri_triggers.c.

References HASH_FIND, hash_search(), sort-test::key, 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(), and ri_set().

2571 {
2572  RI_QueryHashEntry *entry;
2573  SPIPlanPtr plan;
2574 
2575  /*
2576  * On the first call initialize the hashtable
2577  */
2578  if (!ri_query_cache)
2580 
2581  /*
2582  * Lookup for the key
2583  */
2585  (void *) key,
2586  HASH_FIND, NULL);
2587  if (entry == NULL)
2588  return NULL;
2589 
2590  /*
2591  * Check whether the plan is still valid. If it isn't, we don't want to
2592  * simply rely on plancache.c to regenerate it; rather we should start
2593  * from scratch and rebuild the query text too. This is to cover cases
2594  * such as table/column renames. We depend on the plancache machinery to
2595  * detect possible invalidations, though.
2596  *
2597  * CAUTION: this check is only trustworthy if the caller has already
2598  * locked both FK and PK rels.
2599  */
2600  plan = entry->plan;
2601  if (plan && SPI_plan_is_valid(plan))
2602  return plan;
2603 
2604  /*
2605  * Otherwise we might as well flush the cached plan now, to free a little
2606  * memory space before we make a new one.
2607  */
2608  entry->plan = NULL;
2609  if (plan)
2610  SPI_freeplan(plan);
2611 
2612  return NULL;
2613 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:167
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
SPIPlanPtr plan
Definition: ri_triggers.c:137
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:801
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1681
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2531

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 732 of file ri_triggers.c.

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

733 {
734  TriggerData *trigdata = (TriggerData *) fcinfo->context;
735  const RI_ConstraintInfo *riinfo;
736  Relation fk_rel;
737  Relation pk_rel;
738  TupleTableSlot *oldslot;
739  RI_QueryKey qkey;
740  SPIPlanPtr qplan;
741 
742  /* Check that this is a valid trigger call on the right time and event. */
743  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
744 
745  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
746  trigdata->tg_relation, true);
747 
748  /*
749  * Get the relation descriptors of the FK and PK tables and the old tuple.
750  *
751  * fk_rel is opened in RowExclusiveLock mode since that's what our
752  * eventual DELETE will get on it.
753  */
754  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
755  pk_rel = trigdata->tg_relation;
756  oldslot = trigdata->tg_trigslot;
757 
758  if (SPI_connect() != SPI_OK_CONNECT)
759  elog(ERROR, "SPI_connect failed");
760 
761  /* Fetch or prepare a saved plan for the cascaded delete */
763 
764  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
765  {
766  StringInfoData querybuf;
767  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
769  char paramname[16];
770  const char *querysep;
771  Oid queryoids[RI_MAX_NUMKEYS];
772  const char *fk_only;
773 
774  /* ----------
775  * The query string built is
776  * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
777  * The type id's for the $ parameters are those of the
778  * corresponding PK attributes.
779  * ----------
780  */
781  initStringInfo(&querybuf);
782  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
783  "" : "ONLY ";
784  quoteRelationName(fkrelname, fk_rel);
785  appendStringInfo(&querybuf, "DELETE FROM %s%s",
786  fk_only, fkrelname);
787  querysep = "WHERE";
788  for (int i = 0; i < riinfo->nkeys; i++)
789  {
790  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
791  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
792  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
793  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
794 
795  quoteOneName(attname,
796  RIAttName(fk_rel, riinfo->fk_attnums[i]));
797  sprintf(paramname, "$%d", i + 1);
798  ri_GenerateQual(&querybuf, querysep,
799  paramname, pk_type,
800  riinfo->pf_eq_oprs[i],
801  attname, fk_type);
802  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
803  ri_GenerateQualCollation(&querybuf, pk_coll);
804  querysep = "AND";
805  queryoids[i] = pk_type;
806  }
807 
808  /* Prepare and save the plan */
809  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
810  &qkey, fk_rel, pk_rel);
811  }
812 
813  /*
814  * We have a plan now. Build up the arguments from the key values in the
815  * deleted PK tuple and delete the referencing rows
816  */
817  ri_PerformCheck(riinfo, &qkey, qplan,
818  fk_rel, pk_rel,
819  oldslot, NULL,
820  true, /* must detect new rows */
821  SPI_OK_DELETE);
822 
823  if (SPI_finish() != SPI_OK_FINISH)
824  elog(ERROR, "SPI_finish failed");
825 
826  table_close(fk_rel, RowExclusiveLock);
827 
828  return PointerGetDatum(NULL);
829 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
int SPI_connect(void)
Definition: spi.c:89
#define PointerGetDatum(X)
Definition: postgres.h:556
#define SPI_OK_DELETE
Definition: spi.h:60
int SPI_finish(void)
Definition: spi.c:176
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:942
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define RI_PLAN_CASCADE_DEL_DODELETE
Definition: ri_triggers.c:76
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
#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:1952
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
Trigger * tg_trigger
Definition: trigger.h:37
#define SPI_OK_FINISH
Definition: spi.h:54
#define elog(elevel,...)
Definition: elog.h:228
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_cascade_upd()

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 838 of file ri_triggers.c.

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

839 {
840  TriggerData *trigdata = (TriggerData *) fcinfo->context;
841  const RI_ConstraintInfo *riinfo;
842  Relation fk_rel;
843  Relation pk_rel;
844  TupleTableSlot *newslot;
845  TupleTableSlot *oldslot;
846  RI_QueryKey qkey;
847  SPIPlanPtr qplan;
848 
849  /* Check that this is a valid trigger call on the right time and event. */
850  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
851 
852  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
853  trigdata->tg_relation, true);
854 
855  /*
856  * Get the relation descriptors of the FK and PK tables and the new and
857  * old tuple.
858  *
859  * fk_rel is opened in RowExclusiveLock mode since that's what our
860  * eventual UPDATE will get on it.
861  */
862  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
863  pk_rel = trigdata->tg_relation;
864  newslot = trigdata->tg_newslot;
865  oldslot = trigdata->tg_trigslot;
866 
867  if (SPI_connect() != SPI_OK_CONNECT)
868  elog(ERROR, "SPI_connect failed");
869 
870  /* Fetch or prepare a saved plan for the cascaded update */
872 
873  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
874  {
875  StringInfoData querybuf;
876  StringInfoData qualbuf;
877  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
879  char paramname[16];
880  const char *querysep;
881  const char *qualsep;
882  Oid queryoids[RI_MAX_NUMKEYS * 2];
883  const char *fk_only;
884 
885  /* ----------
886  * The query string built is
887  * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
888  * WHERE $n = fkatt1 [AND ...]
889  * The type id's for the $ parameters are those of the
890  * corresponding PK attributes. Note that we are assuming
891  * there is an assignment cast from the PK to the FK type;
892  * else the parser will fail.
893  * ----------
894  */
895  initStringInfo(&querybuf);
896  initStringInfo(&qualbuf);
897  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
898  "" : "ONLY ";
899  quoteRelationName(fkrelname, fk_rel);
900  appendStringInfo(&querybuf, "UPDATE %s%s SET",
901  fk_only, fkrelname);
902  querysep = "";
903  qualsep = "WHERE";
904  for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
905  {
906  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
907  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
908  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
909  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
910 
911  quoteOneName(attname,
912  RIAttName(fk_rel, riinfo->fk_attnums[i]));
913  appendStringInfo(&querybuf,
914  "%s %s = $%d",
915  querysep, attname, i + 1);
916  sprintf(paramname, "$%d", j + 1);
917  ri_GenerateQual(&qualbuf, qualsep,
918  paramname, pk_type,
919  riinfo->pf_eq_oprs[i],
920  attname, fk_type);
921  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
922  ri_GenerateQualCollation(&querybuf, pk_coll);
923  querysep = ",";
924  qualsep = "AND";
925  queryoids[i] = pk_type;
926  queryoids[j] = pk_type;
927  }
928  appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
929 
930  /* Prepare and save the plan */
931  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
932  &qkey, fk_rel, pk_rel);
933  }
934 
935  /*
936  * We have a plan now. Run it to update the existing references.
937  */
938  ri_PerformCheck(riinfo, &qkey, qplan,
939  fk_rel, pk_rel,
940  oldslot, newslot,
941  true, /* must detect new rows */
942  SPI_OK_UPDATE);
943 
944  if (SPI_finish() != SPI_OK_FINISH)
945  elog(ERROR, "SPI_finish failed");
946 
947  table_close(fk_rel, RowExclusiveLock);
948 
949  return PointerGetDatum(NULL);
950 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
int SPI_connect(void)
Definition: spi.c:89
#define PointerGetDatum(X)
Definition: postgres.h:556
int SPI_finish(void)
Definition: spi.c:176
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:942
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
#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:1952
#define RI_PLAN_CASCADE_UPD_DOUPDATE
Definition: ri_triggers.c:77
TupleTableSlot * tg_newslot
Definition: trigger.h:39
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
Trigger * tg_trigger
Definition: trigger.h:37
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90
#define SPI_OK_FINISH
Definition: spi.h:54
#define SPI_OK_UPDATE
Definition: spi.h:61
#define elog(elevel,...)
Definition: elog.h:228
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_check()

static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 232 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, PointerGetDatum, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SnapshotSelf, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, sprintf, table_close(), table_open(), table_tuple_satisfies_snapshot(), TriggerData::tg_event, TriggerData::tg_newslot, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_check_ins(), and RI_FKey_check_upd().

233 {
234  const RI_ConstraintInfo *riinfo;
235  Relation fk_rel;
236  Relation pk_rel;
237  TupleTableSlot *newslot;
238  RI_QueryKey qkey;
239  SPIPlanPtr qplan;
240 
241  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
242  trigdata->tg_relation, false);
243 
244  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
245  newslot = trigdata->tg_newslot;
246  else
247  newslot = trigdata->tg_trigslot;
248 
249  /*
250  * We should not even consider checking the row if it is no longer valid,
251  * since it was either deleted (so the deferred check should be skipped)
252  * or updated (in which case only the latest version of the row should be
253  * checked). Test its liveness according to SnapshotSelf. We need pin
254  * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
255  * should be holding pin, but not lock.
256  */
257  if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
258  return PointerGetDatum(NULL);
259 
260  /*
261  * Get the relation descriptors of the FK and PK tables.
262  *
263  * pk_rel is opened in RowShareLock mode since that's what our eventual
264  * SELECT FOR KEY SHARE will get on it.
265  */
266  fk_rel = trigdata->tg_relation;
267  pk_rel = table_open(riinfo->pk_relid, RowShareLock);
268 
269  switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
270  {
271  case RI_KEYS_ALL_NULL:
272 
273  /*
274  * No further check needed - an all-NULL key passes every type of
275  * foreign key constraint.
276  */
277  table_close(pk_rel, RowShareLock);
278  return PointerGetDatum(NULL);
279 
280  case RI_KEYS_SOME_NULL:
281 
282  /*
283  * This is the only case that differs between the three kinds of
284  * MATCH.
285  */
286  switch (riinfo->confmatchtype)
287  {
288  case FKCONSTR_MATCH_FULL:
289 
290  /*
291  * Not allowed - MATCH FULL says either all or none of the
292  * attributes can be NULLs
293  */
294  ereport(ERROR,
295  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
296  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
297  RelationGetRelationName(fk_rel),
298  NameStr(riinfo->conname)),
299  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
300  errtableconstraint(fk_rel,
301  NameStr(riinfo->conname))));
302  table_close(pk_rel, RowShareLock);
303  return PointerGetDatum(NULL);
304 
306 
307  /*
308  * MATCH SIMPLE - if ANY column is null, the key passes
309  * the constraint.
310  */
311  table_close(pk_rel, RowShareLock);
312  return PointerGetDatum(NULL);
313 
314 #ifdef NOT_USED
316 
317  /*
318  * MATCH PARTIAL - all non-null columns must match. (not
319  * implemented, can be done by modifying the query below
320  * to only include non-null columns, or by writing a
321  * special version here)
322  */
323  break;
324 #endif
325  }
326 
327  case RI_KEYS_NONE_NULL:
328 
329  /*
330  * Have a full qualified key - continue below for all three kinds
331  * of MATCH.
332  */
333  break;
334  }
335 
336  if (SPI_connect() != SPI_OK_CONNECT)
337  elog(ERROR, "SPI_connect failed");
338 
339  /* Fetch or prepare a saved plan for the real check */
341 
342  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
343  {
344  StringInfoData querybuf;
345  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
347  char paramname[16];
348  const char *querysep;
349  Oid queryoids[RI_MAX_NUMKEYS];
350  const char *pk_only;
351 
352  /* ----------
353  * The query string built is
354  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
355  * FOR KEY SHARE OF x
356  * The type id's for the $ parameters are those of the
357  * corresponding FK attributes.
358  * ----------
359  */
360  initStringInfo(&querybuf);
361  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
362  "" : "ONLY ";
363  quoteRelationName(pkrelname, pk_rel);
364  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
365  pk_only, pkrelname);
366  querysep = "WHERE";
367  for (int i = 0; i < riinfo->nkeys; i++)
368  {
369  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
370  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
371 
372  quoteOneName(attname,
373  RIAttName(pk_rel, riinfo->pk_attnums[i]));
374  sprintf(paramname, "$%d", i + 1);
375  ri_GenerateQual(&querybuf, querysep,
376  attname, pk_type,
377  riinfo->pf_eq_oprs[i],
378  paramname, fk_type);
379  querysep = "AND";
380  queryoids[i] = fk_type;
381  }
382  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
383 
384  /* Prepare and save the plan */
385  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
386  &qkey, fk_rel, pk_rel);
387  }
388 
389  /*
390  * Now check that foreign key exists in PK table
391  */
392  ri_PerformCheck(riinfo, &qkey, qplan,
393  fk_rel, pk_rel,
394  NULL, newslot,
395  false,
396  SPI_OK_SELECT);
397 
398  if (SPI_finish() != SPI_OK_FINISH)
399  elog(ERROR, "SPI_finish failed");
400 
401  table_close(pk_rel, RowShareLock);
402 
403  return PointerGetDatum(NULL);
404 }
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2124
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
#define RelationGetDescr(relation)
Definition: rel.h:448
int SPI_connect(void)
Definition: spi.c:89
#define PointerGetDatum(X)
Definition: postgres.h:556
int SPI_finish(void)
Definition: spi.c:176
int errcode(int sqlerrcode)
Definition: elog.c:608
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5272
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
#define SnapshotSelf
Definition: snapmgr.h:68
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
int errdetail(const char *fmt,...)
Definition: elog.c:955
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
#define RelationGetRelationName(relation)
Definition: rel.h:456
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:72
TupleTableSlot * tg_newslot
Definition: trigger.h:39
#define ereport(elevel, rest)
Definition: elog.h:141
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2122
#define RowShareLock
Definition: lockdefs.h:37
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:66
Trigger * tg_trigger
Definition: trigger.h:37
#define SPI_OK_SELECT
Definition: spi.h:57
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1059
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2494
TriggerEvent tg_event
Definition: trigger.h:33
#define SPI_OK_FINISH
Definition: spi.h:54
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:67
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:616
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2123
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68
Relation tg_relation
Definition: trigger.h:34

◆ RI_FKey_check_ins()

Datum RI_FKey_check_ins ( PG_FUNCTION_ARGS  )

Definition at line 413 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

414 {
415  /* Check that this is a valid trigger call on the right time and event. */
416  ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
417 
418  /* Share code with UPDATE case. */
419  return RI_FKey_check((TriggerData *) fcinfo->context);
420 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:232
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:89

◆ RI_FKey_check_upd()

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS  )

Definition at line 429 of file ri_triggers.c.

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

430 {
431  /* Check that this is a valid trigger call on the right time and event. */
432  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
433 
434  /* Share code with INSERT case. */
435  return RI_FKey_check((TriggerData *) fcinfo->context);
436 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:232
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1194 of file ri_triggers.c.

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

Referenced by AfterTriggerSaveEvent().

1196 {
1197  const RI_ConstraintInfo *riinfo;
1198  int ri_nullcheck;
1199  Datum xminDatum;
1200  TransactionId xmin;
1201  bool isnull;
1202 
1203  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1204 
1205  ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1206 
1207  /*
1208  * If all new key values are NULL, the row satisfies the constraint, so no
1209  * check is needed.
1210  */
1211  if (ri_nullcheck == RI_KEYS_ALL_NULL)
1212  return false;
1213 
1214  /*
1215  * If some new key values are NULL, the behavior depends on the match
1216  * type.
1217  */
1218  else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1219  {
1220  switch (riinfo->confmatchtype)
1221  {
1222  case FKCONSTR_MATCH_SIMPLE:
1223 
1224  /*
1225  * If any new key value is NULL, the row must satisfy the
1226  * constraint, so no check is needed.
1227  */
1228  return false;
1229 
1231 
1232  /*
1233  * Don't know, must run full check.
1234  */
1235  break;
1236 
1237  case FKCONSTR_MATCH_FULL:
1238 
1239  /*
1240  * If some new key values are NULL, the row fails the
1241  * constraint. We must not throw error here, because the row
1242  * might get invalidated before the constraint is to be
1243  * checked, but we should queue the event to apply the check
1244  * later.
1245  */
1246  return true;
1247  }
1248  }
1249 
1250  /*
1251  * Continues here for no new key values are NULL, or we couldn't decide
1252  * yet.
1253  */
1254 
1255  /*
1256  * If the original row was inserted by our own transaction, we must fire
1257  * the trigger whether or not the keys are equal. This is because our
1258  * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1259  * not do anything; so we had better do the UPDATE check. (We could skip
1260  * this if we knew the INSERT trigger already fired, but there is no easy
1261  * way to know that.)
1262  */
1263  xminDatum = slot_getsysattr(oldslot, MinTransactionIdAttributeNumber, &isnull);
1264  Assert(!isnull);
1265  xmin = DatumGetTransactionId(xminDatum);
1267  return true;
1268 
1269  /* If all old and new key values are equal, no check is needed */
1270  if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1271  return false;
1272 
1273  /* Else we need to fire the trigger. */
1274  return true;
1275 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2124
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2656
uint32 TransactionId
Definition: c.h:514
#define RelationGetDescr(relation)
Definition: rel.h:448
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:853
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2122
uintptr_t Datum
Definition: postgres.h:367
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:66
#define Assert(condition)
Definition: c.h:739
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2494
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:67
#define DatumGetTransactionId(X)
Definition: postgres.h:514
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2123

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 540 of file ri_triggers.c.

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

541 {
542  /* Check that this is a valid trigger call on the right time and event. */
543  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
544 
545  /* Share code with RESTRICT/UPDATE cases. */
546  return ri_restrict((TriggerData *) fcinfo->context, true);
547 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:613
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 577 of file ri_triggers.c.

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

578 {
579  /* Check that this is a valid trigger call on the right time and event. */
580  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
581 
582  /* Share code with RESTRICT/DELETE cases. */
583  return ri_restrict((TriggerData *) fcinfo->context, true);
584 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:613
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90

◆ RI_FKey_pk_upd_check_required()

bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1162 of file ri_triggers.c.

References RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_NONE_NULL, ri_KeysEqual(), and ri_NullCheck().

Referenced by AfterTriggerSaveEvent().

1164 {
1165  const RI_ConstraintInfo *riinfo;
1166 
1167  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1168 
1169  /*
1170  * If any old key value is NULL, the row could not have been referenced by
1171  * an FK row, so no check is needed.
1172  */
1173  if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1174  return false;
1175 
1176  /* If all old and new key values are equal, no check is needed */
1177  if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1178  return false;
1179 
1180  /* Else we need to fire the trigger. */
1181  return true;
1182 }
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2656
#define RelationGetDescr(relation)
Definition: rel.h:448
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2494
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68

◆ RI_FKey_restrict_del()

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 560 of file ri_triggers.c.

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

561 {
562  /* Check that this is a valid trigger call on the right time and event. */
563  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
564 
565  /* Share code with NO ACTION/UPDATE cases. */
566  return ri_restrict((TriggerData *) fcinfo->context, false);
567 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:613
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 597 of file ri_triggers.c.

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

598 {
599  /* Check that this is a valid trigger call on the right time and event. */
600  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
601 
602  /* Share code with NO ACTION/DELETE cases. */
603  return ri_restrict((TriggerData *) fcinfo->context, false);
604 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:613
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 989 of file ri_triggers.c.

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

990 {
991  /* Check that this is a valid trigger call on the right time and event. */
992  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
993 
994  /* Share code with UPDATE case */
995  return ri_set((TriggerData *) fcinfo->context, false);
996 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null)
Definition: ri_triggers.c:1020
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1004 of file ri_triggers.c.

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

1005 {
1006  /* Check that this is a valid trigger call on the right time and event. */
1007  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1008 
1009  /* Share code with DELETE case */
1010  return ri_set((TriggerData *) fcinfo->context, false);
1011 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null)
Definition: ri_triggers.c:1020
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 959 of file ri_triggers.c.

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

960 {
961  /* Check that this is a valid trigger call on the right time and event. */
962  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
963 
964  /* Share code with UPDATE case */
965  return ri_set((TriggerData *) fcinfo->context, true);
966 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null)
Definition: ri_triggers.c:1020
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:91

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 974 of file ri_triggers.c.

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

975 {
976  /* Check that this is a valid trigger call on the right time and event. */
977  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
978 
979  /* Share code with DELETE case */
980  return ri_set((TriggerData *) fcinfo->context, true);
981 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null)
Definition: ri_triggers.c:1020
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:1906
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:90

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 2862 of file ri_triggers.c.

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and CreateTrigger().

2863 {
2864  switch (tgfoid)
2865  {
2866  case F_RI_FKEY_CASCADE_DEL:
2867  case F_RI_FKEY_CASCADE_UPD:
2868  case F_RI_FKEY_RESTRICT_DEL:
2869  case F_RI_FKEY_RESTRICT_UPD:
2870  case F_RI_FKEY_SETNULL_DEL:
2871  case F_RI_FKEY_SETNULL_UPD:
2872  case F_RI_FKEY_SETDEFAULT_DEL:
2873  case F_RI_FKEY_SETDEFAULT_UPD:
2874  case F_RI_FKEY_NOACTION_DEL:
2875  case F_RI_FKEY_NOACTION_UPD:
2876  return RI_TRIGGER_PK;
2877 
2878  case F_RI_FKEY_CHECK_INS:
2879  case F_RI_FKEY_CHECK_UPD:
2880  return RI_TRIGGER_FK;
2881  }
2882 
2883  return RI_TRIGGER_NONE;
2884 }
#define RI_TRIGGER_FK
Definition: trigger.h:271
#define RI_TRIGGER_PK
Definition: trigger.h:270
#define RI_TRIGGER_NONE
Definition: trigger.h:272

◆ 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 1821 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_PartitionRemove_Check(), ri_restrict(), and ri_set().

1826 {
1827  appendStringInfo(buf, " %s ", sep);
1828  generate_operator_clause(buf, leftop, leftoptype, opoid,
1829  rightop, rightoptype);
1830 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:11052

◆ ri_GenerateQualCollation()

static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 1850 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_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

1851 {
1852  HeapTuple tp;
1853  Form_pg_collation colltup;
1854  char *collname;
1855  char onename[MAX_QUOTED_NAME_LEN];
1856 
1857  /* Nothing to do if it's a noncollatable data type */
1858  if (!OidIsValid(collation))
1859  return;
1860 
1861  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1862  if (!HeapTupleIsValid(tp))
1863  elog(ERROR, "cache lookup failed for collation %u", collation);
1864  colltup = (Form_pg_collation) GETSTRUCT(tp);
1865  collname = NameStr(colltup->collname);
1866 
1867  /*
1868  * We qualify the name always, for simplicity and to ensure the query is
1869  * not search-path-dependent.
1870  */
1871  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
1872  appendStringInfo(buf, " COLLATE %s", onename);
1873  quoteOneName(onename, collname);
1874  appendStringInfo(buf, ".%s", onename);
1875 
1876  ReleaseSysCache(tp);
1877 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define OidIsValid(objectId)
Definition: c.h:645
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ ri_HashCompareOp()

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

Definition at line 2769 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(), sort-test::key, OidIsValid, op_input_types(), ri_InitHashTables(), TopMemoryContext, RI_CompareKey::typeid, and RI_CompareHashEntry::valid.

Referenced by ri_AttributesEqual().

2770 {
2772  RI_CompareHashEntry *entry;
2773  bool found;
2774 
2775  /*
2776  * On the first call initialize the hashtable
2777  */
2778  if (!ri_compare_cache)
2780 
2781  /*
2782  * Find or create a hash entry. Note we're assuming RI_CompareKey
2783  * contains no struct padding.
2784  */
2785  key.eq_opr = eq_opr;
2786  key.typeid = typeid;
2788  (void *) &key,
2789  HASH_ENTER, &found);
2790  if (!found)
2791  entry->valid = false;
2792 
2793  /*
2794  * If not already initialized, do so. Since we'll keep this hash entry
2795  * for the life of the backend, put any subsidiary info for the function
2796  * cache structs into TopMemoryContext.
2797  */
2798  if (!entry->valid)
2799  {
2800  Oid lefttype,
2801  righttype,
2802  castfunc;
2803  CoercionPathType pathtype;
2804 
2805  /* We always need to know how to call the equality operator */
2806  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
2808 
2809  /*
2810  * If we chose to use a cast from FK to PK type, we may have to apply
2811  * the cast function to get to the operator's input type.
2812  *
2813  * XXX eventually it would be good to support array-coercion cases
2814  * here and in ri_AttributesEqual(). At the moment there is no point
2815  * because cases involving nonidentical array types will be rejected
2816  * at constraint creation time.
2817  *
2818  * XXX perhaps also consider supporting CoerceViaIO? No need at the
2819  * moment since that will never be generated for implicit coercions.
2820  */
2821  op_input_types(eq_opr, &lefttype, &righttype);
2822  Assert(lefttype == righttype);
2823  if (typeid == lefttype)
2824  castfunc = InvalidOid; /* simplest case */
2825  else
2826  {
2827  pathtype = find_coercion_pathway(lefttype, typeid,
2829  &castfunc);
2830  if (pathtype != COERCION_PATH_FUNC &&
2831  pathtype != COERCION_PATH_RELABELTYPE)
2832  {
2833  /*
2834  * The declared input type of the eq_opr might be a
2835  * polymorphic type such as ANYARRAY or ANYENUM, or other
2836  * special cases such as RECORD; find_coercion_pathway
2837  * currently doesn't subsume these special cases.
2838  */
2839  if (!IsBinaryCoercible(typeid, lefttype))
2840  elog(ERROR, "no conversion function from %s to %s",
2841  format_type_be(typeid),
2842  format_type_be(lefttype));
2843  }
2844  }
2845  if (OidIsValid(castfunc))
2846  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
2848  else
2850  entry->valid = true;
2851  }
2852 
2853  return entry;
2854 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
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:645
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:1165
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:1092
Oid fn_oid
Definition: fmgr.h:59
#define Assert(condition)
Definition: c.h:739
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
#define elog(elevel,...)
Definition: elog.h:228
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2531
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:159
static HTAB * ri_compare_cache
Definition: ri_triggers.c:168

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 2622 of file ri_triggers.c.

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

Referenced by ri_PlanCheck().

2623 {
2624  RI_QueryHashEntry *entry;
2625  bool found;
2626 
2627  /*
2628  * On the first call initialize the hashtable
2629  */
2630  if (!ri_query_cache)
2632 
2633  /*
2634  * Add the new plan. We might be overwriting an entry previously found
2635  * invalid by ri_FetchPreparedPlan.
2636  */
2638  (void *) key,
2639  HASH_ENTER, &found);
2640  Assert(!found || entry->plan == NULL);
2641  entry->plan = plan;
2642 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:167
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
SPIPlanPtr plan
Definition: ri_triggers.c:137
#define Assert(condition)
Definition: c.h:739
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2531

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

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

2532 {
2533  HASHCTL ctl;
2534 
2535  memset(&ctl, 0, sizeof(ctl));
2536  ctl.keysize = sizeof(Oid);
2537  ctl.entrysize = sizeof(RI_ConstraintInfo);
2538  ri_constraint_cache = hash_create("RI constraint cache",
2540  &ctl, HASH_ELEM | HASH_BLOBS);
2541 
2542  /* Arrange to flush cache on pg_constraint changes */
2545  (Datum) 0);
2546 
2547  memset(&ctl, 0, sizeof(ctl));
2548  ctl.keysize = sizeof(RI_QueryKey);
2549  ctl.entrysize = sizeof(RI_QueryHashEntry);
2550  ri_query_cache = hash_create("RI query cache",
2552  &ctl, HASH_ELEM | HASH_BLOBS);
2553 
2554  memset(&ctl, 0, sizeof(ctl));
2555  ctl.keysize = sizeof(RI_CompareKey);
2556  ctl.entrysize = sizeof(RI_CompareHashEntry);
2557  ri_compare_cache = hash_create("RI compare cache",
2559  &ctl, HASH_ELEM | HASH_BLOBS);
2560 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:167
struct RI_CompareKey RI_CompareKey
#define HASH_ELEM
Definition: hsearch.h:87
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:166
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:64
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2090
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:1426
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:63
static HTAB * ri_compare_cache
Definition: ri_triggers.c:168
struct RI_QueryHashEntry RI_QueryHashEntry

◆ RI_Initial_Check()

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

Definition at line 1295 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

1296 {
1297  const RI_ConstraintInfo *riinfo;
1298  StringInfoData querybuf;
1299  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1300  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1301  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1302  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1303  RangeTblEntry *pkrte;
1304  RangeTblEntry *fkrte;
1305  const char *sep;
1306  const char *fk_only;
1307  const char *pk_only;
1308  int save_nestlevel;
1309  char workmembuf[32];
1310  int spi_result;
1311  SPIPlanPtr qplan;
1312 
1313  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1314 
1315  /*
1316  * Check to make sure current user has enough permissions to do the test
1317  * query. (If not, caller can fall back to the trigger method, which
1318  * works because it changes user IDs on the fly.)
1319  *
1320  * XXX are there any other show-stopper conditions to check?
1321  */
1322  pkrte = makeNode(RangeTblEntry);
1323  pkrte->rtekind = RTE_RELATION;
1324  pkrte->relid = RelationGetRelid(pk_rel);
1325  pkrte->relkind = pk_rel->rd_rel->relkind;
1326  pkrte->rellockmode = AccessShareLock;
1327  pkrte->requiredPerms = ACL_SELECT;
1328 
1329  fkrte = makeNode(RangeTblEntry);
1330  fkrte->rtekind = RTE_RELATION;
1331  fkrte->relid = RelationGetRelid(fk_rel);
1332  fkrte->relkind = fk_rel->rd_rel->relkind;
1333  fkrte->rellockmode = AccessShareLock;
1334  fkrte->requiredPerms = ACL_SELECT;
1335 
1336  for (int i = 0; i < riinfo->nkeys; i++)
1337  {
1338  int attno;
1339 
1340  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1341  pkrte->selectedCols = bms_add_member(pkrte->selectedCols, attno);
1342 
1343  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1344  fkrte->selectedCols = bms_add_member(fkrte->selectedCols, attno);
1345  }
1346 
1347  if (!ExecCheckRTPerms(list_make2(fkrte, pkrte), false))
1348  return false;
1349 
1350  /*
1351  * Also punt if RLS is enabled on either table unless this role has the
1352  * bypassrls right or is the table owner of the table(s) involved which
1353  * have RLS enabled.
1354  */
1356  ((pk_rel->rd_rel->relrowsecurity &&
1357  !pg_class_ownercheck(pkrte->relid, GetUserId())) ||
1358  (fk_rel->rd_rel->relrowsecurity &&
1359  !pg_class_ownercheck(fkrte->relid, GetUserId()))))
1360  return false;
1361 
1362  /*----------
1363  * The query string built is:
1364  * SELECT fk.keycols FROM [ONLY] relname fk
1365  * LEFT OUTER JOIN [ONLY] pkrelname pk
1366  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1367  * WHERE pk.pkkeycol1 IS NULL AND
1368  * For MATCH SIMPLE:
1369  * (fk.keycol1 IS NOT NULL [AND ...])
1370  * For MATCH FULL:
1371  * (fk.keycol1 IS NOT NULL [OR ...])
1372  *
1373  * We attach COLLATE clauses to the operators when comparing columns
1374  * that have different collations.
1375  *----------
1376  */
1377  initStringInfo(&querybuf);
1378  appendStringInfoString(&querybuf, "SELECT ");
1379  sep = "";
1380  for (int i = 0; i < riinfo->nkeys; i++)
1381  {
1382  quoteOneName(fkattname,
1383  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1384  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1385  sep = ", ";
1386  }
1387 
1388  quoteRelationName(pkrelname, pk_rel);
1389  quoteRelationName(fkrelname, fk_rel);
1390  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1391  "" : "ONLY ";
1392  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1393  "" : "ONLY ";
1394  appendStringInfo(&querybuf,
1395  " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1396  fk_only, fkrelname, pk_only, pkrelname);
1397 
1398  strcpy(pkattname, "pk.");
1399  strcpy(fkattname, "fk.");
1400  sep = "(";
1401  for (int i = 0; i < riinfo->nkeys; i++)
1402  {
1403  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1404  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1405  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1406  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1407 
1408  quoteOneName(pkattname + 3,
1409  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1410  quoteOneName(fkattname + 3,
1411  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1412  ri_GenerateQual(&querybuf, sep,
1413  pkattname, pk_type,
1414  riinfo->pf_eq_oprs[i],
1415  fkattname, fk_type);
1416  if (pk_coll != fk_coll)
1417  ri_GenerateQualCollation(&querybuf, pk_coll);
1418  sep = "AND";
1419  }
1420 
1421  /*
1422  * It's sufficient to test any one pk attribute for null to detect a join
1423  * failure.
1424  */
1425  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1426  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1427 
1428  sep = "";
1429  for (int i = 0; i < riinfo->nkeys; i++)
1430  {
1431  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1432  appendStringInfo(&querybuf,
1433  "%sfk.%s IS NOT NULL",
1434  sep, fkattname);
1435  switch (riinfo->confmatchtype)
1436  {
1437  case FKCONSTR_MATCH_SIMPLE:
1438  sep = " AND ";
1439  break;
1440  case FKCONSTR_MATCH_FULL:
1441  sep = " OR ";
1442  break;
1443  }
1444  }
1445  appendStringInfoChar(&querybuf, ')');
1446 
1447  /*
1448  * Temporarily increase work_mem so that the check query can be executed
1449  * more efficiently. It seems okay to do this because the query is simple
1450  * enough to not use a multiple of work_mem, and one typically would not
1451  * have many large foreign-key validations happening concurrently. So
1452  * this seems to meet the criteria for being considered a "maintenance"
1453  * operation, and accordingly we use maintenance_work_mem.
1454  *
1455  * We use the equivalent of a function SET option to allow the setting to
1456  * persist for exactly the duration of the check query. guc.c also takes
1457  * care of undoing the setting on error.
1458  */
1459  save_nestlevel = NewGUCNestLevel();
1460 
1461  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1462  (void) set_config_option("work_mem", workmembuf,
1464  GUC_ACTION_SAVE, true, 0, false);
1465 
1466  if (SPI_connect() != SPI_OK_CONNECT)
1467  elog(ERROR, "SPI_connect failed");
1468 
1469  /*
1470  * Generate the plan. We don't need to cache it, and there are no
1471  * arguments to the plan.
1472  */
1473  qplan = SPI_prepare(querybuf.data, 0, NULL);
1474 
1475  if (qplan == NULL)
1476  elog(ERROR, "SPI_prepare returned %s for %s",
1478 
1479  /*
1480  * Run the plan. For safety we force a current snapshot to be used. (In
1481  * transaction-snapshot mode, this arguably violates transaction isolation
1482  * rules, but we really haven't got much choice.) We don't need to
1483  * register the snapshot, because SPI_execute_snapshot will see to it. We
1484  * need at most one tuple returned, so pass limit = 1.
1485  */
1486  spi_result = SPI_execute_snapshot(qplan,
1487  NULL, NULL,
1490  true, false, 1);
1491 
1492  /* Check result */
1493  if (spi_result != SPI_OK_SELECT)
1494  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1495 
1496  /* Did we find a tuple violating the constraint? */
1497  if (SPI_processed > 0)
1498  {
1499  TupleTableSlot *slot;
1500  HeapTuple tuple = SPI_tuptable->vals[0];
1501  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1502  RI_ConstraintInfo fake_riinfo;
1503 
1504  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1505 
1506  heap_deform_tuple(tuple, tupdesc,
1507  slot->tts_values, slot->tts_isnull);
1508  ExecStoreVirtualTuple(slot);
1509 
1510  /*
1511  * The columns to look at in the result tuple are 1..N, not whatever
1512  * they are in the fk_rel. Hack up riinfo so that the subroutines
1513  * called here will behave properly.
1514  *
1515  * In addition to this, we have to pass the correct tupdesc to
1516  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1517  * or fk_rel's tupdesc.
1518  */
1519  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1520  for (int i = 0; i < fake_riinfo.nkeys; i++)
1521  fake_riinfo.fk_attnums[i] = i + 1;
1522 
1523  /*
1524  * If it's MATCH FULL, and there are any nulls in the FK keys,
1525  * complain about that rather than the lack of a match. MATCH FULL
1526  * disallows partially-null FK rows.
1527  */
1528  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1529  ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1530  ereport(ERROR,
1531  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1532  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1533  RelationGetRelationName(fk_rel),
1534  NameStr(fake_riinfo.conname)),
1535  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1536  errtableconstraint(fk_rel,
1537  NameStr(fake_riinfo.conname))));
1538 
1539  /*
1540  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1541  * query, which isn't true, but will cause it to use
1542  * fake_riinfo.fk_attnums as we need.
1543  */
1544  ri_ReportViolation(&fake_riinfo,
1545  pk_rel, fk_rel,
1546  slot, tupdesc,
1547  RI_PLAN_CHECK_LOOKUPPK, false);
1548 
1550  }
1551 
1552  if (SPI_finish() != SPI_OK_FINISH)
1553  elog(ERROR, "SPI_finish failed");
1554 
1555  /*
1556  * Restore work_mem.
1557  */
1558  AtEOXact_GUC(true, save_nestlevel);
1559 
1560  return true;
1561 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
#define list_make2(x1, x2)
Definition: pg_list.h:229
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2124
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
Oid GetUserId(void)
Definition: miscinit.c:380
int SPI_connect(void)
Definition: spi.c:89
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2337
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:674
int SPI_finish(void)
Definition: spi.c:176
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
#define AccessShareLock
Definition: lockdefs.h:36
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:608
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Datum * tts_values
Definition: tuptable.h:126
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
AclMode requiredPerms
Definition: parsenodes.h:1096
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:26
uint64 SPI_processed
Definition: spi.c:45
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:5397
int SPI_result
Definition: spi.c:47
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5272
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
Bitmapset * selectedCols
Definition: parsenodes.h:1098
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
bool * tts_isnull
Definition: tuptable.h:128
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5782
int errdetail(const char *fmt,...)
Definition: elog.c:955
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
#define RelationGetRelationName(relation)
Definition: rel.h:456
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:72
#define ereport(elevel, rest)
Definition: elog.h:141
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:599
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define InvalidSnapshot
Definition: snapshot.h:123
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2122
#define ACL_SELECT
Definition: parsenodes.h:75
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
int maintenance_work_mem
Definition: globals.c:122
#define makeNode(_type_)
Definition: nodes.h:573
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2494
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4753
#define SPI_OK_FINISH
Definition: spi.h:54
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
RTEKind rtekind
Definition: parsenodes.h:974
int NewGUCNestLevel(void)
Definition: guc.c:5768
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
int i
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:571
#define NameStr(name)
Definition: c.h:616
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
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:6775
#define snprintf
Definition: port.h:192
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68
#define RelationGetRelid(relation)
Definition: rel.h:422
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522

◆ ri_KeysEqual()

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

Definition at line 2656 of file ri_triggers.c.

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

Referenced by RI_FKey_fk_upd_check_required(), and RI_FKey_pk_upd_check_required().

2658 {
2659  const int16 *attnums;
2660 
2661  if (rel_is_pk)
2662  attnums = riinfo->pk_attnums;
2663  else
2664  attnums = riinfo->fk_attnums;
2665 
2666  /* XXX: could be worthwhile to fetch all necessary attrs at once */
2667  for (int i = 0; i < riinfo->nkeys; i++)
2668  {
2669  Datum oldvalue;
2670  Datum newvalue;
2671  bool isnull;
2672 
2673  /*
2674  * Get one attribute's oldvalue. If it is NULL - they're not equal.
2675  */
2676  oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
2677  if (isnull)
2678  return false;
2679 
2680  /*
2681  * Get one attribute's newvalue. If it is NULL - they're not equal.
2682  */
2683  newvalue = slot_getattr(newslot, attnums[i], &isnull);
2684  if (isnull)
2685  return false;
2686 
2687  if (rel_is_pk)
2688  {
2689  /*
2690  * If we are looking at the PK table, then do a bytewise
2691  * comparison. We must propagate PK changes if the value is
2692  * changed to one that "looks" different but would compare as
2693  * equal using the equality operator. This only makes a
2694  * difference for ON UPDATE CASCADE, but for consistency we treat
2695  * all changes to the PK the same.
2696  */
2697  Form_pg_attribute att = TupleDescAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
2698 
2699  if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
2700  return false;
2701  }
2702  else
2703  {
2704  /*
2705  * For the FK table, compare with the appropriate equality
2706  * operator. Changes that compare equal will still satisfy the
2707  * constraint after the update.
2708  */
2709  if (!ri_AttributesEqual(riinfo->ff_eq_oprs[i], RIAttType(rel, attnums[i]),
2710  oldvalue, newvalue))
2711  return false;
2712  }
2713  }
2714 
2715  return true;
2716 }
signed short int16
Definition: c.h:346
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
static bool ri_AttributesEqual(Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
Definition: ri_triggers.c:2727
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:116
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
uintptr_t Datum
Definition: postgres.h:367
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
int i
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:264
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113

◆ ri_LoadConstraintInfo()

static const RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2006 of file ri_triggers.c.

References Assert, RI_ConstraintInfo::confdeltype, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::confupdtype, RI_ConstraintInfo::conname, RI_ConstraintInfo::constraint_id, CONSTROID, DeconstructFkConstraintRow(), 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, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, RI_ConstraintInfo::pp_eq_oprs, ReleaseSysCache(), ri_constraint_cache_valid_count, ri_InitHashTables(), SearchSysCache1(), RI_ConstraintInfo::valid, and RI_ConstraintInfo::valid_link.

Referenced by ri_FetchConstraintInfo().

2007 {
2008  RI_ConstraintInfo *riinfo;
2009  bool found;
2010  HeapTuple tup;
2011  Form_pg_constraint conForm;
2012 
2013  /*
2014  * On the first call initialize the hashtable
2015  */
2016  if (!ri_constraint_cache)
2018 
2019  /*
2020  * Find or create a hash entry. If we find a valid one, just return it.
2021  */
2023  (void *) &constraintOid,
2024  HASH_ENTER, &found);
2025  if (!found)
2026  riinfo->valid = false;
2027  else if (riinfo->valid)
2028  return riinfo;
2029 
2030  /*
2031  * Fetch the pg_constraint row so we can fill in the entry.
2032  */
2033  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2034  if (!HeapTupleIsValid(tup)) /* should not happen */
2035  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2036  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2037 
2038  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2039  elog(ERROR, "constraint %u is not a foreign key constraint",
2040  constraintOid);
2041 
2042  /* And extract data */
2043  Assert(riinfo->constraint_id == constraintOid);
2045  ObjectIdGetDatum(constraintOid));
2046  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2047  riinfo->pk_relid = conForm->confrelid;
2048  riinfo->fk_relid = conForm->conrelid;
2049  riinfo->confupdtype = conForm->confupdtype;
2050  riinfo->confdeltype = conForm->confdeltype;
2051  riinfo->confmatchtype = conForm->confmatchtype;
2052 
2054  &riinfo->nkeys,
2055  riinfo->fk_attnums,
2056  riinfo->pk_attnums,
2057  riinfo->pf_eq_oprs,
2058  riinfo->pp_eq_oprs,
2059  riinfo->ff_eq_oprs);
2060 
2061  ReleaseSysCache(tup);
2062 
2063  /*
2064  * For efficient processing of invalidation messages below, we keep a
2065  * doubly-linked list, and a count, of all currently valid entries.
2066  */
2069 
2070  riinfo->valid = true;
2071 
2072  return riinfo;
2073 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs)
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:166
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
dlist_node valid_link
Definition: ri_triggers.c:117
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
Definition: c.h:610
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:115
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:116
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:170
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:169
#define elog(elevel,...)
Definition: elog.h:228
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2531
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113

◆ ri_NullCheck()

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

Definition at line 2494 of file ri_triggers.c.

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

Referenced by ri_Check_Pk_Match(), RI_FKey_check(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), and RI_Initial_Check().

2497 {
2498  const int16 *attnums;
2499  bool allnull = true;
2500  bool nonenull = true;
2501 
2502  if (rel_is_pk)
2503  attnums = riinfo->pk_attnums;
2504  else
2505  attnums = riinfo->fk_attnums;
2506 
2507  for (int i = 0; i < riinfo->nkeys; i++)
2508  {
2509  if (slot_attisnull(slot, attnums[i]))
2510  nonenull = false;
2511  else
2512  allnull = false;
2513  }
2514 
2515  if (allnull)
2516  return RI_KEYS_ALL_NULL;
2517 
2518  if (nonenull)
2519  return RI_KEYS_NONE_NULL;
2520 
2521  return RI_KEYS_SOME_NULL;
2522 }
signed short int16
Definition: c.h:346
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:66
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:67
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:367
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68

◆ RI_PartitionRemove_Check()

void RI_PartitionRemove_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 1570 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ERROR, ExecStoreVirtualTuple(), RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GUC_ACTION_SAVE, heap_deform_tuple(), i, initStringInfo(), InvalidSnapshot, maintenance_work_mem, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NewGUCNestLevel(), RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, pg_get_partconstrdef_string(), PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelid, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by ATDetachCheckNoForeignKeyRefs().

1571 {
1572  const RI_ConstraintInfo *riinfo;
1573  StringInfoData querybuf;
1574  char *constraintDef;
1575  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1576  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1577  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1578  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1579  const char *sep;
1580  const char *fk_only;
1581  int save_nestlevel;
1582  char workmembuf[32];
1583  int spi_result;
1584  SPIPlanPtr qplan;
1585  int i;
1586 
1587  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1588 
1589  /*
1590  * We don't check permissions before displaying the error message, on the
1591  * assumption that the user detaching the partition must have enough
1592  * privileges to examine the table contents anyhow.
1593  */
1594 
1595  /*----------
1596  * The query string built is:
1597  * SELECT fk.keycols FROM [ONLY] relname fk
1598  * JOIN pkrelname pk
1599  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1600  * WHERE (<partition constraint>) AND
1601  * For MATCH SIMPLE:
1602  * (fk.keycol1 IS NOT NULL [AND ...])
1603  * For MATCH FULL:
1604  * (fk.keycol1 IS NOT NULL [OR ...])
1605  *
1606  * We attach COLLATE clauses to the operators when comparing columns
1607  * that have different collations.
1608  *----------
1609  */
1610  initStringInfo(&querybuf);
1611  appendStringInfoString(&querybuf, "SELECT ");
1612  sep = "";
1613  for (i = 0; i < riinfo->nkeys; i++)
1614  {
1615  quoteOneName(fkattname,
1616  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1617  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1618  sep = ", ";
1619  }
1620 
1621  quoteRelationName(pkrelname, pk_rel);
1622  quoteRelationName(fkrelname, fk_rel);
1623  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1624  "" : "ONLY ";
1625  appendStringInfo(&querybuf,
1626  " FROM %s%s fk JOIN %s pk ON",
1627  fk_only, fkrelname, pkrelname);
1628  strcpy(pkattname, "pk.");
1629  strcpy(fkattname, "fk.");
1630  sep = "(";
1631  for (i = 0; i < riinfo->nkeys; i++)
1632  {
1633  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1634  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1635  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1636  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1637 
1638  quoteOneName(pkattname + 3,
1639  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1640  quoteOneName(fkattname + 3,
1641  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1642  ri_GenerateQual(&querybuf, sep,
1643  pkattname, pk_type,
1644  riinfo->pf_eq_oprs[i],
1645  fkattname, fk_type);
1646  if (pk_coll != fk_coll)
1647  ri_GenerateQualCollation(&querybuf, pk_coll);
1648  sep = "AND";
1649  }
1650 
1651  /*
1652  * Start the WHERE clause with the partition constraint (except if this is
1653  * the default partition and there's no other partition, because the
1654  * partition constraint is the empty string in that case.)
1655  */
1656  constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1657  if (constraintDef && constraintDef[0] != '\0')
1658  appendStringInfo(&querybuf, ") WHERE %s AND (",
1659  constraintDef);
1660  else
1661  appendStringInfo(&querybuf, ") WHERE (");
1662 
1663  sep = "";
1664  for (i = 0; i < riinfo->nkeys; i++)
1665  {
1666  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1667  appendStringInfo(&querybuf,
1668  "%sfk.%s IS NOT NULL",
1669  sep, fkattname);
1670  switch (riinfo->confmatchtype)
1671  {
1672  case FKCONSTR_MATCH_SIMPLE:
1673  sep = " AND ";
1674  break;
1675  case FKCONSTR_MATCH_FULL:
1676  sep = " OR ";
1677  break;
1678  }
1679  }
1680  appendStringInfoChar(&querybuf, ')');
1681 
1682  /*
1683  * Temporarily increase work_mem so that the check query can be executed
1684  * more efficiently. It seems okay to do this because the query is simple
1685  * enough to not use a multiple of work_mem, and one typically would not
1686  * have many large foreign-key validations happening concurrently. So
1687  * this seems to meet the criteria for being considered a "maintenance"
1688  * operation, and accordingly we use maintenance_work_mem.
1689  *
1690  * We use the equivalent of a function SET option to allow the setting to
1691  * persist for exactly the duration of the check query. guc.c also takes
1692  * care of undoing the setting on error.
1693  */
1694  save_nestlevel = NewGUCNestLevel();
1695 
1696  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1697  (void) set_config_option("work_mem", workmembuf,
1699  GUC_ACTION_SAVE, true, 0, false);
1700 
1701  if (SPI_connect() != SPI_OK_CONNECT)
1702  elog(ERROR, "SPI_connect failed");
1703 
1704  /*
1705  * Generate the plan. We don't need to cache it, and there are no
1706  * arguments to the plan.
1707  */
1708  qplan = SPI_prepare(querybuf.data, 0, NULL);
1709 
1710  if (qplan == NULL)
1711  elog(ERROR, "SPI_prepare returned %s for %s",
1713 
1714  /*
1715  * Run the plan. For safety we force a current snapshot to be used. (In
1716  * transaction-snapshot mode, this arguably violates transaction isolation
1717  * rules, but we really haven't got much choice.) We don't need to
1718  * register the snapshot, because SPI_execute_snapshot will see to it. We
1719  * need at most one tuple returned, so pass limit = 1.
1720  */
1721  spi_result = SPI_execute_snapshot(qplan,
1722  NULL, NULL,
1725  true, false, 1);
1726 
1727  /* Check result */
1728  if (spi_result != SPI_OK_SELECT)
1729  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1730 
1731  /* Did we find a tuple that would violate the constraint? */
1732  if (SPI_processed > 0)
1733  {
1734  TupleTableSlot *slot;
1735  HeapTuple tuple = SPI_tuptable->vals[0];
1736  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1737  RI_ConstraintInfo fake_riinfo;
1738 
1739  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1740 
1741  heap_deform_tuple(tuple, tupdesc,
1742  slot->tts_values, slot->tts_isnull);
1743  ExecStoreVirtualTuple(slot);
1744 
1745  /*
1746  * The columns to look at in the result tuple are 1..N, not whatever
1747  * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1748  * will behave properly.
1749  *
1750  * In addition to this, we have to pass the correct tupdesc to
1751  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1752  * or fk_rel's tupdesc.
1753  */
1754  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1755  for (i = 0; i < fake_riinfo.nkeys; i++)
1756  fake_riinfo.pk_attnums[i] = i + 1;
1757 
1758  ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
1759  slot, tupdesc, 0, true);
1760  }
1761 
1762  if (SPI_finish() != SPI_OK_FINISH)
1763  elog(ERROR, "SPI_finish failed");
1764 
1765  /*
1766  * Restore work_mem.
1767  */
1768  AtEOXact_GUC(true, save_nestlevel);
1769 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2124
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
int SPI_connect(void)
Definition: spi.c:89
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2337
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:674
int SPI_finish(void)
Definition: spi.c:176
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
SPITupleTable * SPI_tuptable
Definition: spi.c:46
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Datum * tts_values
Definition: tuptable.h:126
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:26
uint64 SPI_processed
Definition: spi.c:45
int SPI_result
Definition: spi.c:47
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
bool * tts_isnull
Definition: tuptable.h:128
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5782
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
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:599
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define InvalidSnapshot
Definition: snapshot.h:123
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2122
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
int maintenance_work_mem
Definition: globals.c:122
#define SPI_OK_FINISH
Definition: spi.h:54
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
int NewGUCNestLevel(void)
Definition: guc.c:5768
#define elog(elevel,...)
Definition: elog.h:228
int i
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:1844
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
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:6775
#define snprintf
Definition: port.h:192
#define RelationGetRelid(relation)
Definition: rel.h:422
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522

◆ ri_PerformCheck()

static bool ri_PerformCheck ( const RI_ConstraintInfo riinfo,
RI_QueryKey qkey,
SPIPlanPtr  qplan,
Relation  fk_rel,
Relation  pk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot,
bool  detectNewRows,
int  expect_OK 
)
static

Definition at line 2171 of file ri_triggers.c.

References CommandCounterIncrement(), RI_ConstraintInfo::conname, RI_QueryKey::constr_queryno, elog, ereport, errcode(), errhint(), errmsg(), ERROR, GetLatestSnapshot(), GetTransactionSnapshot(), GetUserIdAndSecContext(), InvalidSnapshot, IsolationUsesXactSnapshot, NameStr, RI_ConstraintInfo::nkeys, RelationGetForm, RelationGetRelationName, ri_ExtractValues(), RI_MAX_NUMKEYS, RI_PLAN_CHECK_LOOKUPPK, RI_PLAN_CHECK_LOOKUPPK_FROM_PK, RI_PLAN_LAST_ON_PK, ri_ReportViolation(), SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SPI_execute_snapshot(), SPI_OK_SELECT, SPI_processed, and SPI_result_code_string().

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

2176 {
2177  Relation query_rel,
2178  source_rel;
2179  bool source_is_pk;
2180  Snapshot test_snapshot;
2181  Snapshot crosscheck_snapshot;
2182  int limit;
2183  int spi_result;
2184  Oid save_userid;
2185  int save_sec_context;
2186  Datum vals[RI_MAX_NUMKEYS * 2];
2187  char nulls[RI_MAX_NUMKEYS * 2];
2188 
2189  /*
2190  * Use the query type code to determine whether the query is run against
2191  * the PK or FK table; we'll do the check as that table's owner
2192  */
2193  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2194  query_rel = pk_rel;
2195  else
2196  query_rel = fk_rel;
2197 
2198  /*
2199  * The values for the query are taken from the table on which the trigger
2200  * is called - it is normally the other one with respect to query_rel. An
2201  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2202  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2203  * need some less klugy way to determine this.
2204  */
2206  {
2207  source_rel = fk_rel;
2208  source_is_pk = false;
2209  }
2210  else
2211  {
2212  source_rel = pk_rel;
2213  source_is_pk = true;
2214  }
2215 
2216  /* Extract the parameters to be passed into the query */
2217  if (newslot)
2218  {
2219  ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2220  vals, nulls);
2221  if (oldslot)
2222  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2223  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2224  }
2225  else
2226  {
2227  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2228  vals, nulls);
2229  }
2230 
2231  /*
2232  * In READ COMMITTED mode, we just need to use an up-to-date regular
2233  * snapshot, and we will see all rows that could be interesting. But in
2234  * transaction-snapshot mode, we can't change the transaction snapshot. If
2235  * the caller passes detectNewRows == false then it's okay to do the query
2236  * with the transaction snapshot; otherwise we use a current snapshot, and
2237  * tell the executor to error out if it finds any rows under the current
2238  * snapshot that wouldn't be visible per the transaction snapshot. Note
2239  * that SPI_execute_snapshot will register the snapshots, so we don't need
2240  * to bother here.
2241  */
2242  if (IsolationUsesXactSnapshot() && detectNewRows)
2243  {
2244  CommandCounterIncrement(); /* be sure all my own work is visible */
2245  test_snapshot = GetLatestSnapshot();
2246  crosscheck_snapshot = GetTransactionSnapshot();
2247  }
2248  else
2249  {
2250  /* the default SPI behavior is okay */
2251  test_snapshot = InvalidSnapshot;
2252  crosscheck_snapshot = InvalidSnapshot;
2253  }
2254 
2255  /*
2256  * If this is a select query (e.g., for a 'no action' or 'restrict'
2257  * trigger), we only need to see if there is a single row in the table,
2258  * matching the key. Otherwise, limit = 0 - because we want the query to
2259  * affect ALL the matching rows.
2260  */
2261  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2262 
2263  /* Switch to proper UID to perform check as */
2264  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2265  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2266  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2268 
2269  /* Finally we can run the query. */
2270  spi_result = SPI_execute_snapshot(qplan,
2271  vals, nulls,
2272  test_snapshot, crosscheck_snapshot,
2273  false, false, limit);
2274 
2275  /* Restore UID and security context */
2276  SetUserIdAndSecContext(save_userid, save_sec_context);
2277 
2278  /* Check result */
2279  if (spi_result < 0)
2280  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2281 
2282  if (expect_OK >= 0 && spi_result != expect_OK)
2283  ereport(ERROR,
2284  (errcode(ERRCODE_INTERNAL_ERROR),
2285  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2286  RelationGetRelationName(pk_rel),
2287  NameStr(riinfo->conname),
2288  RelationGetRelationName(fk_rel)),
2289  errhint("This is most likely due to a rule having rewritten the query.")));
2290 
2291  /* XXX wouldn't it be clearer to do this part at the caller? */
2293  expect_OK == SPI_OK_SELECT &&
2295  ri_ReportViolation(riinfo,
2296  pk_rel, fk_rel,
2297  newslot ? newslot : oldslot,
2298  NULL,
2299  qkey->constr_queryno, false);
2300 
2301  return SPI_processed != 0;
2302 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:492
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2337
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:74
#define RelationGetForm(relation)
Definition: rel.h:416
int32 constr_queryno
Definition: ri_triggers.c:128
#define IsolationUsesXactSnapshot()
Definition: xact.h:51
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
uint64 SPI_processed
Definition: spi.c:45
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:485
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:72
#define ereport(elevel, rest)
Definition: elog.h:141
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:599
#define InvalidSnapshot
Definition: snapshot.h:123
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:299
#define SPI_OK_SELECT
Definition: spi.h:57
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:73
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:301
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2308

◆ ri_PlanCheck()

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

Definition at line 2128 of file ri_triggers.c.

References RI_QueryKey::constr_queryno, elog, ERROR, GetUserIdAndSecContext(), RelationGetForm, ri_HashPreparedPlan(), RI_PLAN_LAST_ON_PK, SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SPI_keepplan(), SPI_prepare(), SPI_result, and SPI_result_code_string().

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

2130 {
2131  SPIPlanPtr qplan;
2132  Relation query_rel;
2133  Oid save_userid;
2134  int save_sec_context;
2135 
2136  /*
2137  * Use the query type code to determine whether the query is run against
2138  * the PK or FK table; we'll do the check as that table's owner
2139  */
2140  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2141  query_rel = pk_rel;
2142  else
2143  query_rel = fk_rel;
2144 
2145  /* Switch to proper UID to perform check as */
2146  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2147  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2148  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2150 
2151  /* Create the plan */
2152  qplan = SPI_prepare(querystr, nargs, argtypes);
2153 
2154  if (qplan == NULL)
2155  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2156 
2157  /* Restore UID and security context */
2158  SetUserIdAndSecContext(save_userid, save_sec_context);
2159 
2160  /* Save the plan */
2161  SPI_keepplan(qplan);
2162  ri_HashPreparedPlan(qkey, qplan);
2163 
2164  return qplan;
2165 }
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:492
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:74
#define RelationGetForm(relation)
Definition: rel.h:416
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:674
int32 constr_queryno
Definition: ri_triggers.c:128
unsigned int Oid
Definition: postgres_ext.h:31
int SPI_result
Definition: spi.c:47
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2622
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:752
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:485
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:299
#define elog(elevel,...)
Definition: elog.h:228
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:301

◆ ri_ReportViolation()

static void ri_ReportViolation ( const RI_ConstraintInfo riinfo,
Relation  pk_rel,
Relation  fk_rel,
TupleTableSlot violatorslot,
TupleDesc  tupdesc,
int  queryno,
bool  partgone 
)
static

Definition at line 2337 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, getTypeOutputInfo(), GetUserId(), idx(), initStringInfo(), InvalidOid, name, NameStr, RI_ConstraintInfo::nkeys, OidOutputFunctionCall(), pg_attribute_aclcheck(), pg_class_aclcheck(), RI_ConstraintInfo::pk_attnums, RelationData::rd_att, RelationData::rd_id, RelationGetRelationName, RI_PLAN_CHECK_LOOKUPPK, RLS_ENABLED, slot_getattr(), TupleDescAttr, and val.

Referenced by RI_Initial_Check(), RI_PartitionRemove_Check(), and ri_PerformCheck().

2341 {
2342  StringInfoData key_names;
2343  StringInfoData key_values;
2344  bool onfk;
2345  const int16 *attnums;
2346  Oid rel_oid;
2347  AclResult aclresult;
2348  bool has_perm = true;
2349 
2350  /*
2351  * Determine which relation to complain about. If tupdesc wasn't passed
2352  * by caller, assume the violator tuple came from there.
2353  */
2354  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2355  if (onfk)
2356  {
2357  attnums = riinfo->fk_attnums;
2358  rel_oid = fk_rel->rd_id;
2359  if (tupdesc == NULL)
2360  tupdesc = fk_rel->rd_att;
2361  }
2362  else
2363  {
2364  attnums = riinfo->pk_attnums;
2365  rel_oid = pk_rel->rd_id;
2366  if (tupdesc == NULL)
2367  tupdesc = pk_rel->rd_att;
2368  }
2369 
2370  /*
2371  * Check permissions- if the user does not have access to view the data in
2372  * any of the key columns then we don't include the errdetail() below.
2373  *
2374  * Check if RLS is enabled on the relation first. If so, we don't return
2375  * any specifics to avoid leaking data.
2376  *
2377  * Check table-level permissions next and, failing that, column-level
2378  * privileges.
2379  *
2380  * When a partition at the referenced side is being detached/dropped, we
2381  * needn't check, since the user must be the table owner anyway.
2382  */
2383  if (partgone)
2384  has_perm = true;
2385  else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2386  {
2387  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2388  if (aclresult != ACLCHECK_OK)
2389  {
2390  /* Try for column-level permissions */
2391  for (int idx = 0; idx < riinfo->nkeys; idx++)
2392  {
2393  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2394  GetUserId(),
2395  ACL_SELECT);
2396 
2397  /* No access to the key */
2398  if (aclresult != ACLCHECK_OK)
2399  {
2400  has_perm = false;
2401  break;
2402  }
2403  }
2404  }
2405  }
2406  else
2407  has_perm = false;
2408 
2409  if (has_perm)
2410  {
2411  /* Get printable versions of the keys involved */
2412  initStringInfo(&key_names);
2413  initStringInfo(&key_values);
2414  for (int idx = 0; idx < riinfo->nkeys; idx++)
2415  {
2416  int fnum = attnums[idx];
2417  Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2418  char *name,
2419  *val;
2420  Datum datum;
2421  bool isnull;
2422 
2423  name = NameStr(att->attname);
2424 
2425  datum = slot_getattr(violatorslot, fnum, &isnull);
2426  if (!isnull)
2427  {
2428  Oid foutoid;
2429  bool typisvarlena;
2430 
2431  getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2432  val = OidOutputFunctionCall(foutoid, datum);
2433  }
2434  else
2435  val = "null";
2436 
2437  if (idx > 0)
2438  {
2439  appendStringInfoString(&key_names, ", ");
2440  appendStringInfoString(&key_values, ", ");
2441  }
2442  appendStringInfoString(&key_names, name);
2443  appendStringInfoString(&key_values, val);
2444  }
2445  }
2446 
2447  if (partgone)
2448  ereport(ERROR,
2449  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2450  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2451  RelationGetRelationName(pk_rel),
2452  NameStr(riinfo->conname)),
2453  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2454  key_names.data, key_values.data,
2455  RelationGetRelationName(fk_rel))));
2456  else if (onfk)
2457  ereport(ERROR,
2458  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2459  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2460  RelationGetRelationName(fk_rel),
2461  NameStr(riinfo->conname)),
2462  has_perm ?
2463  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2464  key_names.data, key_values.data,
2465  RelationGetRelationName(pk_rel)) :
2466  errdetail("Key is not present in table \"%s\".",
2467  RelationGetRelationName(pk_rel)),
2468  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2469  else
2470  ereport(ERROR,
2471  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2472  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2473  RelationGetRelationName(pk_rel),
2474  NameStr(riinfo->conname),
2475  RelationGetRelationName(fk_rel)),
2476  has_perm ?
2477  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2478  key_names.data, key_values.data,
2479  RelationGetRelationName(fk_rel)) :
2480  errdetail("Key is still referenced from table \"%s\".",
2481  RelationGetRelationName(fk_rel)),
2482  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2483 }
signed short int16
Definition: c.h:346
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2674
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4515
Oid GetUserId(void)
Definition: miscinit.c:380
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:608
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:263
unsigned int Oid
Definition: postgres_ext.h:31
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5272
#define ERROR
Definition: elog.h:43
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define RelationGetRelationName(relation)
Definition: rel.h:456
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:72
#define ereport(elevel, rest)
Definition: elog.h:141
Oid rd_id
Definition: rel.h:85
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
#define ACL_SELECT
Definition: parsenodes.h:75
TupleDesc rd_att
Definition: rel.h:84
#define InvalidOid
Definition: postgres_ext.h:36
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
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:4629
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1655
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define NameStr(name)
Definition: c.h:616
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
long val
Definition: informix.c:664

◆ ri_restrict()

static Datum ri_restrict ( TriggerData trigdata,
bool  is_no_action 
)
static

Definition at line 613 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), attname, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_collation_isdeterministic(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum, quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_RESTRICT_CHECKREF, ri_PlanCheck(), RIAttCollation, RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

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

614 {
615  const RI_ConstraintInfo *riinfo;
616  Relation fk_rel;
617  Relation pk_rel;
618  TupleTableSlot *oldslot;
619  RI_QueryKey qkey;
620  SPIPlanPtr qplan;
621 
622  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
623  trigdata->tg_relation, true);
624 
625  /*
626  * Get the relation descriptors of the FK and PK tables and the old tuple.
627  *
628  * fk_rel is opened in RowShareLock mode since that's what our eventual
629  * SELECT FOR KEY SHARE will get on it.
630  */
631  fk_rel = table_open(riinfo->fk_relid, RowShareLock);
632  pk_rel = trigdata->tg_relation;
633  oldslot = trigdata->tg_trigslot;
634 
635  /*
636  * If another PK row now exists providing the old key values, we should
637  * not do anything. However, this check should only be made in the NO
638  * ACTION case; in RESTRICT cases we don't wish to allow another row to be
639  * substituted.
640  */
641  if (is_no_action &&
642  ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
643  {
644  table_close(fk_rel, RowShareLock);
645  return PointerGetDatum(NULL);
646  }
647 
648  if (SPI_connect() != SPI_OK_CONNECT)
649  elog(ERROR, "SPI_connect failed");
650 
651  /*
652  * Fetch or prepare a saved plan for the restrict lookup (it's the same
653  * query for delete and update cases)
654  */
656 
657  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
658  {
659  StringInfoData querybuf;
660  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
662  char paramname[16];
663  const char *querysep;
664  Oid queryoids[RI_MAX_NUMKEYS];
665  const char *fk_only;
666 
667  /* ----------
668  * The query string built is
669  * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
670  * FOR KEY SHARE OF x
671  * The type id's for the $ parameters are those of the
672  * corresponding PK attributes.
673  * ----------
674  */
675  initStringInfo(&querybuf);
676  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
677  "" : "ONLY ";
678  quoteRelationName(fkrelname, fk_rel);
679  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
680  fk_only, fkrelname);
681  querysep = "WHERE";
682  for (int i = 0; i < riinfo->nkeys; i++)
683  {
684  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
685  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
686  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
687  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
688 
689  quoteOneName(attname,
690  RIAttName(fk_rel, riinfo->fk_attnums[i]));
691  sprintf(paramname, "$%d", i + 1);
692  ri_GenerateQual(&querybuf, querysep,
693  paramname, pk_type,
694  riinfo->pf_eq_oprs[i],
695  attname, fk_type);
696  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
697  ri_GenerateQualCollation(&querybuf, pk_coll);
698  querysep = "AND";
699  queryoids[i] = pk_type;
700  }
701  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
702 
703  /* Prepare and save the plan */
704  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
705  &qkey, fk_rel, pk_rel);
706  }
707 
708  /*
709  * We have a plan now. Run it to check for existing references.
710  */
711  ri_PerformCheck(riinfo, &qkey, qplan,
712  fk_rel, pk_rel,
713  oldslot, NULL,
714  true, /* must detect new rows */
715  SPI_OK_SELECT);
716 
717  if (SPI_finish() != SPI_OK_FINISH)
718  elog(ERROR, "SPI_finish failed");
719 
720  table_close(fk_rel, RowShareLock);
721 
722  return PointerGetDatum(NULL);
723 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
int SPI_connect(void)
Definition: spi.c:89
#define PointerGetDatum(X)
Definition: postgres.h:556
int SPI_finish(void)
Definition: spi.c:176
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:942
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:450
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define RowShareLock
Definition: lockdefs.h:37
#define RI_PLAN_RESTRICT_CHECKREF
Definition: ri_triggers.c:78
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
Trigger * tg_trigger
Definition: trigger.h:37
#define SPI_OK_SELECT
Definition: spi.h:57
#define SPI_OK_FINISH
Definition: spi.h:54
#define elog(elevel,...)
Definition: elog.h:228
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation tg_relation
Definition: trigger.h:34

◆ ri_set()

static Datum ri_set ( TriggerData trigdata,
bool  is_set_null 
)
static

Definition at line 1020 of file ri_triggers.c.

References appendBinaryStringInfo(), appendStringInfo(), attname, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_collation_isdeterministic(), i, initStringInfo(), StringInfoData::len, MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum, quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_SETDEFAULT_DOUPDATE, RI_PLAN_SETNULL_DOUPDATE, ri_PlanCheck(), ri_restrict(), RIAttCollation, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

Referenced by RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), and RI_FKey_setnull_upd().

1021 {
1022  const RI_ConstraintInfo *riinfo;
1023  Relation fk_rel;
1024  Relation pk_rel;
1025  TupleTableSlot *oldslot;
1026  RI_QueryKey qkey;
1027  SPIPlanPtr qplan;
1028 
1029  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1030  trigdata->tg_relation, true);
1031 
1032  /*
1033  * Get the relation descriptors of the FK and PK tables and the old tuple.
1034  *
1035  * fk_rel is opened in RowExclusiveLock mode since that's what our
1036  * eventual UPDATE will get on it.
1037  */
1038  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1039  pk_rel = trigdata->tg_relation;
1040  oldslot = trigdata->tg_trigslot;
1041 
1042  if (SPI_connect() != SPI_OK_CONNECT)
1043  elog(ERROR, "SPI_connect failed");
1044 
1045  /*
1046  * Fetch or prepare a saved plan for the set null/default operation (it's
1047  * the same query for delete and update cases)
1048  */
1049  ri_BuildQueryKey(&qkey, riinfo,
1050  (is_set_null
1053 
1054  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1055  {
1056  StringInfoData querybuf;
1057  StringInfoData qualbuf;
1058  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1060  char paramname[16];
1061  const char *querysep;
1062  const char *qualsep;
1063  Oid queryoids[RI_MAX_NUMKEYS];
1064  const char *fk_only;
1065 
1066  /* ----------
1067  * The query string built is
1068  * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1069  * WHERE $1 = fkatt1 [AND ...]
1070  * The type id's for the $ parameters are those of the
1071  * corresponding PK attributes.
1072  * ----------
1073  */
1074  initStringInfo(&querybuf);
1075  initStringInfo(&qualbuf);
1076  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1077  "" : "ONLY ";
1078  quoteRelationName(fkrelname, fk_rel);
1079  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1080  fk_only, fkrelname);
1081  querysep = "";
1082  qualsep = "WHERE";
1083  for (int i = 0; i < riinfo->nkeys; i++)
1084  {
1085  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1086  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1087  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1088  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1089 
1090  quoteOneName(attname,
1091  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1092  appendStringInfo(&querybuf,
1093  "%s %s = %s",
1094  querysep, attname,
1095  is_set_null ? "NULL" : "DEFAULT");
1096  sprintf(paramname, "$%d", i + 1);
1097  ri_GenerateQual(&qualbuf, qualsep,
1098  paramname, pk_type,
1099  riinfo->pf_eq_oprs[i],
1100  attname, fk_type);
1101  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
1102  ri_GenerateQualCollation(&querybuf, pk_coll);
1103  querysep = ",";
1104  qualsep = "AND";
1105  queryoids[i] = pk_type;
1106  }
1107  appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
1108 
1109  /* Prepare and save the plan */
1110  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1111  &qkey, fk_rel, pk_rel);
1112  }
1113 
1114  /*
1115  * We have a plan now. Run it to update the existing references.
1116  */
1117  ri_PerformCheck(riinfo, &qkey, qplan,
1118  fk_rel, pk_rel,
1119  oldslot, NULL,
1120  true, /* must detect new rows */
1121  SPI_OK_UPDATE);
1122 
1123  if (SPI_finish() != SPI_OK_FINISH)
1124  elog(ERROR, "SPI_finish failed");
1125 
1126  table_close(fk_rel, RowExclusiveLock);
1127 
1128  if (is_set_null)
1129  return PointerGetDatum(NULL);
1130  else
1131  {
1132  /*
1133  * If we just deleted or updated the PK row whose key was equal to the
1134  * FK columns' default values, and a referencing row exists in the FK
1135  * table, we would have updated that row to the same values it already
1136  * had --- and RI_FKey_fk_upd_check_required would hence believe no
1137  * check is necessary. So we need to do another lookup now and in
1138  * case a reference still exists, abort the operation. That is
1139  * already implemented in the NO ACTION trigger, so just run it. (This
1140  * recheck is only needed in the SET DEFAULT case, since CASCADE would
1141  * remove such rows in case of a DELETE operation or would change the
1142  * FK key values in case of an UPDATE, while SET NULL is certain to
1143  * result in rows that satisfy the FK constraint.)
1144  */
1145  return ri_restrict(trigdata, true);
1146  }
1147 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1850
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:1821
#define SPI_OK_CONNECT
Definition: spi.h:53
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1804
int SPI_connect(void)
Definition: spi.c:89
#define PointerGetDatum(X)
Definition: postgres.h:556
int SPI_finish(void)
Definition: spi.c:176
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:942
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:613
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:86
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:85
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2128
#define sprintf
Definition: port.h:194
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:87
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1784
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:82
#define RI_PLAN_SETDEFAULT_DOUPDATE
Definition: ri_triggers.c:80
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:83
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:112
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2570
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:114
#define RI_PLAN_SETNULL_DOUPDATE
Definition: ri_triggers.c:79
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:1952
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2171
Trigger * tg_trigger
Definition: trigger.h:37
#define SPI_OK_FINISH
Definition: spi.h:54
#define SPI_OK_UPDATE
Definition: spi.h:61
#define elog(elevel,...)
Definition: elog.h:228
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1891
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:113
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:61
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
Relation tg_relation
Definition: trigger.h:34

Variable Documentation

◆ ri_compare_cache

HTAB* ri_compare_cache = NULL
static

Definition at line 168 of file ri_triggers.c.

◆ ri_constraint_cache

HTAB* ri_constraint_cache = NULL
static

Definition at line 166 of file ri_triggers.c.

◆ ri_constraint_cache_valid_count

int ri_constraint_cache_valid_count = 0
static

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

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 167 of file ri_triggers.c.