PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
ri_triggers.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "lib/ilist.h"
#include "parser/parse_coerce.h"
#include "parser/parse_relation.h"
#include "miscadmin.h"
#include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rls.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
Include dependency graph for ri_triggers.c:

Go to the source code of this file.

Data Structures

struct  RI_ConstraintInfo
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 

Macros

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS
 
#define RI_INIT_CONSTRAINTHASHSIZE   64
 
#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)
 
#define RI_KEYS_ALL_NULL   0
 
#define RI_KEYS_SOME_NULL   1
 
#define RI_KEYS_NONE_NULL   2
 
#define RI_PLAN_CHECK_LOOKUPPK   1
 
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2
 
#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK
 
#define RI_PLAN_CASCADE_DEL_DODELETE   3
 
#define RI_PLAN_CASCADE_UPD_DOUPDATE   4
 
#define RI_PLAN_RESTRICT_DEL_CHECKREF   5
 
#define RI_PLAN_RESTRICT_UPD_CHECKREF   6
 
#define RI_PLAN_SETNULL_DEL_DOUPDATE   7
 
#define RI_PLAN_SETNULL_UPD_DOUPDATE   8
 
#define RI_PLAN_SETDEFAULT_DEL_DOUPDATE   9
 
#define RI_PLAN_SETDEFAULT_UPD_DOUPDATE   10
 
#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)
 
#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)
 
#define RIAttName(rel, attnum)   NameStr(*attnumAttName(rel, attnum))
 
#define RIAttType(rel, attnum)   attnumTypeId(rel, attnum)
 
#define RIAttCollation(rel, attnum)   attnumCollationId(rel, attnum)
 
#define RI_TRIGTYPE_INSERT   1
 
#define RI_TRIGTYPE_UPDATE   2
 
#define RI_TRIGTYPE_DELETE   3
 

Typedefs

typedef struct RI_ConstraintInfo RI_ConstraintInfo
 
typedef struct RI_QueryKey RI_QueryKey
 
typedef struct RI_QueryHashEntry RI_QueryHashEntry
 
typedef struct RI_CompareKey RI_CompareKey
 
typedef struct RI_CompareHashEntry RI_CompareHashEntry
 

Functions

static bool ri_Check_Pk_Match (Relation pk_rel, Relation fk_rel, HeapTuple old_row, const RI_ConstraintInfo *riinfo)
 
static Datum ri_restrict_del (TriggerData *trigdata, bool is_no_action)
 
static Datum ri_restrict_upd (TriggerData *trigdata, bool is_no_action)
 
static void quoteOneName (char *buffer, const char *name)
 
static void quoteRelationName (char *buffer, Relation rel)
 
static void ri_GenerateQual (StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
static void ri_add_cast_to (StringInfo buf, Oid typid)
 
static void ri_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static void ri_BuildQueryKey (RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
 
static bool ri_KeysEqual (Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static bool ri_AttributesEqual (Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
 
static void ri_InitHashTables (void)
 
static void InvalidateConstraintCacheCallBack (Datum arg, int cacheid, uint32 hashvalue)
 
static SPIPlanPtr ri_FetchPreparedPlan (RI_QueryKey *key)
 
static void ri_HashPreparedPlan (RI_QueryKey *key, SPIPlanPtr plan)
 
static RI_CompareHashEntryri_HashCompareOp (Oid eq_opr, Oid typeid)
 
static void ri_CheckTrigger (FunctionCallInfo fcinfo, const char *funcname, int tgkind)
 
static const RI_ConstraintInfori_FetchConstraintInfo (Trigger *trigger, Relation trig_rel, bool rel_is_pk)
 
static const RI_ConstraintInfori_LoadConstraintInfo (Oid constraintOid)
 
static SPIPlanPtr ri_PlanCheck (const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
 
static bool ri_PerformCheck (const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
 
static void ri_ExtractValues (Relation rel, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
 
static void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno, bool spi_err)
 
static Datum RI_FKey_check (TriggerData *trigdata)
 
Datum RI_FKey_check_ins (PG_FUNCTION_ARGS)
 
Datum RI_FKey_check_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_upd (PG_FUNCTION_ARGS)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, HeapTuple old_row, HeapTuple new_row)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, HeapTuple old_row, HeapTuple new_row)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

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

Macro Definition Documentation

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 69 of file ri_triggers.c.

Referenced by ri_InitHashTables().

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 70 of file ri_triggers.c.

Referenced by ri_InitHashTables().

#define RI_PLAN_CASCADE_DEL_DODELETE   3

Definition at line 82 of file ri_triggers.c.

Referenced by RI_FKey_cascade_del().

#define RI_PLAN_CASCADE_UPD_DOUPDATE   4

Definition at line 83 of file ri_triggers.c.

Referenced by RI_FKey_cascade_upd().

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 78 of file ri_triggers.c.

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

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 79 of file ri_triggers.c.

Referenced by ri_Check_Pk_Match(), and ri_PerformCheck().

#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK

Definition at line 80 of file ri_triggers.c.

Referenced by ri_PerformCheck(), and ri_PlanCheck().

#define RI_PLAN_RESTRICT_DEL_CHECKREF   5

Definition at line 84 of file ri_triggers.c.

Referenced by ri_restrict_del().

#define RI_PLAN_RESTRICT_UPD_CHECKREF   6

Definition at line 85 of file ri_triggers.c.

Referenced by ri_restrict_upd().

#define RI_PLAN_SETDEFAULT_DEL_DOUPDATE   9

Definition at line 88 of file ri_triggers.c.

Referenced by RI_FKey_setdefault_del().

#define RI_PLAN_SETDEFAULT_UPD_DOUPDATE   10

Definition at line 89 of file ri_triggers.c.

Referenced by RI_FKey_setdefault_upd().

#define RI_PLAN_SETNULL_DEL_DOUPDATE   7

Definition at line 86 of file ri_triggers.c.

Referenced by RI_FKey_setnull_del().

#define RI_PLAN_SETNULL_UPD_DOUPDATE   8

Definition at line 87 of file ri_triggers.c.

Referenced by RI_FKey_setnull_upd().

#define RI_TRIGTYPE_INSERT   1

Definition at line 98 of file ri_triggers.c.

Referenced by ri_CheckTrigger(), and RI_FKey_check_ins().

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

Definition at line 96 of file ri_triggers.c.

Referenced by RI_Initial_Check().

Typedef Documentation

Function Documentation

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

Definition at line 2953 of file ri_triggers.c.

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

Referenced by ri_InitHashTables().

2954 {
2955  dlist_mutable_iter iter;
2956 
2958 
2959  /*
2960  * If the list of currently valid entries gets excessively large, we mark
2961  * them all invalid so we can empty the list. This arrangement avoids
2962  * O(N^2) behavior in situations where a session touches many foreign keys
2963  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2964  */
2966  hashvalue = 0; /* pretend it's a cache reset */
2967 
2969  {
2971  valid_link, iter.cur);
2972 
2973  if (hashvalue == 0 || riinfo->oidHashValue == hashvalue)
2974  {
2975  riinfo->valid = false;
2976  /* Remove invalidated entries from the list, too */
2977  dlist_delete(iter.cur);
2979  }
2980  }
2981 }
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:185
#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:189
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:188
static void quoteOneName ( char *  buffer,
const char *  name 
)
static

Definition at line 2529 of file ri_triggers.c.

Referenced by quoteRelationName(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_GenerateQualCollation(), RI_Initial_Check(), ri_restrict_del(), and ri_restrict_upd().

2530 {
2531  /* Rather than trying to be smart, just always quote it. */
2532  *buffer++ = '"';
2533  while (*name)
2534  {
2535  if (*name == '"')
2536  *buffer++ = '"';
2537  *buffer++ = *name++;
2538  }
2539  *buffer++ = '"';
2540  *buffer = '\0';
2541 }
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
const char * name
Definition: encode.c:521
static void quoteRelationName ( char *  buffer,
Relation  rel 
)
static

Definition at line 2549 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_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), and ri_restrict_upd().

2550 {
2552  buffer += strlen(buffer);
2553  *buffer++ = '.';
2555 }
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define RelationGetRelationName(relation)
Definition: rel.h:436
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
#define RelationGetNamespace(relation)
Definition: rel.h:443
static void ri_add_cast_to ( StringInfo  buf,
Oid  typid 
)
static

Definition at line 2610 of file ri_triggers.c.

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

Referenced by ri_GenerateQual().

2611 {
2612  HeapTuple typetup;
2613  Form_pg_type typform;
2614  char *typname;
2615  char *nspname;
2616 
2617  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2618  if (!HeapTupleIsValid(typetup))
2619  elog(ERROR, "cache lookup failed for type %u", typid);
2620  typform = (Form_pg_type) GETSTRUCT(typetup);
2621 
2622  typname = NameStr(typform->typname);
2623  nspname = get_namespace_name(typform->typnamespace);
2624 
2625  appendStringInfo(buf, "::%s.%s",
2626  quote_identifier(nspname), quote_identifier(typname));
2627 
2628  ReleaseSysCache(typetup);
2629 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static bool ri_AttributesEqual ( Oid  eq_opr,
Oid  typeid,
Datum  oldvalue,
Datum  newvalue 
)
static

Definition at line 3574 of file ri_triggers.c.

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

Referenced by ri_KeysEqual().

3576 {
3577  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3578 
3579  /* Do we need to cast the values? */
3580  if (OidIsValid(entry->cast_func_finfo.fn_oid))
3581  {
3582  oldvalue = FunctionCall3(&entry->cast_func_finfo,
3583  oldvalue,
3584  Int32GetDatum(-1), /* typmod */
3585  BoolGetDatum(false)); /* implicit coercion */
3586  newvalue = FunctionCall3(&entry->cast_func_finfo,
3587  newvalue,
3588  Int32GetDatum(-1), /* typmod */
3589  BoolGetDatum(false)); /* implicit coercion */
3590  }
3591 
3592  /*
3593  * Apply the comparison operator. We assume it doesn't care about
3594  * collations.
3595  */
3596  return DatumGetBool(FunctionCall2(&entry->eq_opr_finfo,
3597  oldvalue, newvalue));
3598 }
#define FunctionCall2(flinfo, arg1, arg2)
Definition: fmgr.h:604
#define OidIsValid(objectId)
Definition: c.h:538
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:606
#define DatumGetBool(X)
Definition: postgres.h:399
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3608
#define BoolGetDatum(X)
Definition: postgres.h:408
Oid fn_oid
Definition: fmgr.h:59
#define Int32GetDatum(X)
Definition: postgres.h:485
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:177
static void ri_BuildQueryKey ( RI_QueryKey key,
const RI_ConstraintInfo riinfo,
int32  constr_queryno 
)
static

Definition at line 2690 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_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), and ri_restrict_upd().

2692 {
2693  /*
2694  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2695  * to use memset to clear them.
2696  */
2697  key->constr_id = riinfo->constraint_id;
2698  key->constr_queryno = constr_queryno;
2699 }
int32 constr_queryno
Definition: ri_triggers.c:140
static bool ri_Check_Pk_Match ( Relation  pk_rel,
Relation  fk_rel,
HeapTuple  old_row,
const RI_ConstraintInfo riinfo 
)
static

Definition at line 510 of file ri_triggers.c.

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

Referenced by ri_restrict_del(), and ri_restrict_upd().

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

Definition at line 2705 of file ri_triggers.c.

References CALLED_AS_TRIGGER, FunctionCallInfoData::context, ereport, errcode(), errmsg(), ERROR, RI_TRIGTYPE_DELETE, RI_TRIGTYPE_INSERT, RI_TRIGTYPE_UPDATE, TriggerData::tg_event, TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_UPDATE, and TRIGGER_FIRED_FOR_ROW.

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

2706 {
2707  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2708 
2709  if (!CALLED_AS_TRIGGER(fcinfo))
2710  ereport(ERROR,
2711  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2712  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2713 
2714  /*
2715  * Check proper event
2716  */
2717  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2718  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2719  ereport(ERROR,
2720  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2721  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2722 
2723  switch (tgkind)
2724  {
2725  case RI_TRIGTYPE_INSERT:
2726  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2727  ereport(ERROR,
2728  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2729  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2730  break;
2731  case RI_TRIGTYPE_UPDATE:
2732  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2733  ereport(ERROR,
2734  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2735  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2736  break;
2737  case RI_TRIGTYPE_DELETE:
2738  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2739  ereport(ERROR,
2740  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2741  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2742  break;
2743  }
2744 }
fmNodePtr context
Definition: fmgr.h:80
int errcode(int sqlerrcode)
Definition: elog.c:575
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:91
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:73
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:70
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:82
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:76
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:98
static void ri_ExtractValues ( Relation  rel,
HeapTuple  tup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk,
Datum vals,
char *  nulls 
)
static

Definition at line 3173 of file ri_triggers.c.

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

Referenced by ri_PerformCheck().

3176 {
3177  TupleDesc tupdesc = rel->rd_att;
3178  const int16 *attnums;
3179  int i;
3180  bool isnull;
3181 
3182  if (rel_is_pk)
3183  attnums = riinfo->pk_attnums;
3184  else
3185  attnums = riinfo->fk_attnums;
3186 
3187  for (i = 0; i < riinfo->nkeys; i++)
3188  {
3189  vals[i] = heap_getattr(tup, attnums[i], tupdesc,
3190  &isnull);
3191  nulls[i] = isnull ? 'n' : ' ';
3192  }
3193 }
signed short int16
Definition: c.h:255
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
TupleDesc rd_att
Definition: rel.h:115
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
static const RI_ConstraintInfo * ri_FetchConstraintInfo ( Trigger trigger,
Relation  trig_rel,
bool  rel_is_pk 
)
static

Definition at line 2751 of file ri_triggers.c.

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

Referenced by RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), and ri_restrict_upd().

2752 {
2753  Oid constraintOid = trigger->tgconstraint;
2754  const RI_ConstraintInfo *riinfo;
2755 
2756  /*
2757  * Check that the FK constraint's OID is available; it might not be if
2758  * we've been invoked via an ordinary trigger or an old-style "constraint
2759  * trigger".
2760  */
2761  if (!OidIsValid(constraintOid))
2762  ereport(ERROR,
2763  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2764  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2765  trigger->tgname, RelationGetRelationName(trig_rel)),
2766  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2767 
2768  /* Find or create a hashtable entry for the constraint */
2769  riinfo = ri_LoadConstraintInfo(constraintOid);
2770 
2771  /* Do some easy cross-checks against the trigger call data */
2772  if (rel_is_pk)
2773  {
2774  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2775  riinfo->pk_relid != RelationGetRelid(trig_rel))
2776  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2777  trigger->tgname, RelationGetRelationName(trig_rel));
2778  }
2779  else
2780  {
2781  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2782  riinfo->pk_relid != trigger->tgconstrrelid)
2783  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2784  trigger->tgname, RelationGetRelationName(trig_rel));
2785  }
2786 
2787  return riinfo;
2788 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:436
Oid tgconstrrelid
Definition: reltrigger.h:32
#define ereport(elevel, rest)
Definition: elog.h:122
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2794
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define RelationGetRelid(relation)
Definition: rel.h:416
static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 3426 of file ri_triggers.c.

References HASH_FIND, hash_search(), NULL, 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_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), and ri_restrict_upd().

3427 {
3428  RI_QueryHashEntry *entry;
3429  SPIPlanPtr plan;
3430 
3431  /*
3432  * On the first call initialize the hashtable
3433  */
3434  if (!ri_query_cache)
3436 
3437  /*
3438  * Lookup for the key
3439  */
3441  (void *) key,
3442  HASH_FIND, NULL);
3443  if (entry == NULL)
3444  return NULL;
3445 
3446  /*
3447  * Check whether the plan is still valid. If it isn't, we don't want to
3448  * simply rely on plancache.c to regenerate it; rather we should start
3449  * from scratch and rebuild the query text too. This is to cover cases
3450  * such as table/column renames. We depend on the plancache machinery to
3451  * detect possible invalidations, though.
3452  *
3453  * CAUTION: this check is only trustworthy if the caller has already
3454  * locked both FK and PK rels.
3455  */
3456  plan = entry->plan;
3457  if (plan && SPI_plan_is_valid(plan))
3458  return plan;
3459 
3460  /*
3461  * Otherwise we might as well flush the cached plan now, to free a little
3462  * memory space before we make a new one.
3463  */
3464  entry->plan = NULL;
3465  if (plan)
3466  SPI_freeplan(plan);
3467 
3468  return NULL;
3469 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:186
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
SPIPlanPtr plan
Definition: ri_triggers.c:151
#define NULL
Definition: c.h:229
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:609
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1489
static void ri_InitHashTables(void)
Definition: ri_triggers.c:3386
Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 1031 of file ri_triggers.c.

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

1032 {
1033  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1034  const RI_ConstraintInfo *riinfo;
1035  Relation fk_rel;
1036  Relation pk_rel;
1037  HeapTuple old_row;
1038  RI_QueryKey qkey;
1039  SPIPlanPtr qplan;
1040  int i;
1041 
1042  /*
1043  * Check that this is a valid trigger call on the right time and event.
1044  */
1045  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
1046 
1047  /*
1048  * Get arguments.
1049  */
1050  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1051  trigdata->tg_relation, true);
1052 
1053  /*
1054  * Get the relation descriptors of the FK and PK tables and the old tuple.
1055  *
1056  * fk_rel is opened in RowExclusiveLock mode since that's what our
1057  * eventual DELETE will get on it.
1058  */
1059  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1060  pk_rel = trigdata->tg_relation;
1061  old_row = trigdata->tg_trigtuple;
1062 
1063  switch (riinfo->confmatchtype)
1064  {
1065  /* ----------
1066  * SQL:2008 15.17 <Execution of referential actions>
1067  * General rules 9) a) i):
1068  * MATCH SIMPLE/FULL
1069  * ... ON DELETE CASCADE
1070  * ----------
1071  */
1072  case FKCONSTR_MATCH_SIMPLE:
1073  case FKCONSTR_MATCH_FULL:
1074  switch (ri_NullCheck(old_row, riinfo, true))
1075  {
1076  case RI_KEYS_ALL_NULL:
1077  case RI_KEYS_SOME_NULL:
1078 
1079  /*
1080  * No check needed - there cannot be any reference to old
1081  * key if it contains a NULL
1082  */
1083  heap_close(fk_rel, RowExclusiveLock);
1084  return PointerGetDatum(NULL);
1085 
1086  case RI_KEYS_NONE_NULL:
1087 
1088  /*
1089  * Have a full qualified key - continue below
1090  */
1091  break;
1092  }
1093 
1094  if (SPI_connect() != SPI_OK_CONNECT)
1095  elog(ERROR, "SPI_connect failed");
1096 
1097  /*
1098  * Fetch or prepare a saved plan for the cascaded delete
1099  */
1101 
1102  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1103  {
1104  StringInfoData querybuf;
1105  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1106  char attname[MAX_QUOTED_NAME_LEN];
1107  char paramname[16];
1108  const char *querysep;
1109  Oid queryoids[RI_MAX_NUMKEYS];
1110 
1111  /* ----------
1112  * The query string built is
1113  * DELETE FROM ONLY <fktable> WHERE $1 = fkatt1 [AND ...]
1114  * The type id's for the $ parameters are those of the
1115  * corresponding PK attributes.
1116  * ----------
1117  */
1118  initStringInfo(&querybuf);
1119  quoteRelationName(fkrelname, fk_rel);
1120  appendStringInfo(&querybuf, "DELETE FROM ONLY %s", fkrelname);
1121  querysep = "WHERE";
1122  for (i = 0; i < riinfo->nkeys; i++)
1123  {
1124  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1125  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1126 
1127  quoteOneName(attname,
1128  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1129  sprintf(paramname, "$%d", i + 1);
1130  ri_GenerateQual(&querybuf, querysep,
1131  paramname, pk_type,
1132  riinfo->pf_eq_oprs[i],
1133  attname, fk_type);
1134  querysep = "AND";
1135  queryoids[i] = pk_type;
1136  }
1137 
1138  /* Prepare and save the plan */
1139  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1140  &qkey, fk_rel, pk_rel, true);
1141  }
1142 
1143  /*
1144  * We have a plan now. Build up the arguments from the key values
1145  * in the deleted PK tuple and delete the referencing rows
1146  */
1147  ri_PerformCheck(riinfo, &qkey, qplan,
1148  fk_rel, pk_rel,
1149  old_row, NULL,
1150  true, /* must detect new rows */
1151  SPI_OK_DELETE);
1152 
1153  if (SPI_finish() != SPI_OK_FINISH)
1154  elog(ERROR, "SPI_finish failed");
1155 
1156  heap_close(fk_rel, RowExclusiveLock);
1157 
1158  return PointerGetDatum(NULL);
1159 
1160  /*
1161  * Handle MATCH PARTIAL cascaded delete.
1162  */
1164  ereport(ERROR,
1165  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1166  errmsg("MATCH PARTIAL not yet implemented")));
1167  return PointerGetDatum(NULL);
1168 
1169  default:
1170  elog(ERROR, "unrecognized confmatchtype: %d",
1171  riinfo->confmatchtype);
1172  break;
1173  }
1174 
1175  /* Never reached */
1176  return PointerGetDatum(NULL);
1177 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
#define SPI_OK_DELETE
Definition: spi.h:57
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define RI_PLAN_CASCADE_DEL_DODELETE
Definition: ri_triggers.c:82
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#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:2751
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
#define NULL
Definition: c.h:229
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
Relation tg_relation
Definition: trigger.h:34
Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 1187 of file ri_triggers.c.

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

1188 {
1189  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1190  const RI_ConstraintInfo *riinfo;
1191  Relation fk_rel;
1192  Relation pk_rel;
1193  HeapTuple new_row;
1194  HeapTuple old_row;
1195  RI_QueryKey qkey;
1196  SPIPlanPtr qplan;
1197  int i;
1198  int j;
1199 
1200  /*
1201  * Check that this is a valid trigger call on the right time and event.
1202  */
1203  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1204 
1205  /*
1206  * Get arguments.
1207  */
1208  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1209  trigdata->tg_relation, true);
1210 
1211  /*
1212  * Get the relation descriptors of the FK and PK tables and the new and
1213  * old tuple.
1214  *
1215  * fk_rel is opened in RowExclusiveLock mode since that's what our
1216  * eventual UPDATE will get on it.
1217  */
1218  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1219  pk_rel = trigdata->tg_relation;
1220  new_row = trigdata->tg_newtuple;
1221  old_row = trigdata->tg_trigtuple;
1222 
1223  switch (riinfo->confmatchtype)
1224  {
1225  /* ----------
1226  * SQL:2008 15.17 <Execution of referential actions>
1227  * General rules 10) a) i):
1228  * MATCH SIMPLE/FULL
1229  * ... ON UPDATE CASCADE
1230  * ----------
1231  */
1232  case FKCONSTR_MATCH_SIMPLE:
1233  case FKCONSTR_MATCH_FULL:
1234  switch (ri_NullCheck(old_row, riinfo, true))
1235  {
1236  case RI_KEYS_ALL_NULL:
1237  case RI_KEYS_SOME_NULL:
1238 
1239  /*
1240  * No check needed - there cannot be any reference to old
1241  * key if it contains a NULL
1242  */
1243  heap_close(fk_rel, RowExclusiveLock);
1244  return PointerGetDatum(NULL);
1245 
1246  case RI_KEYS_NONE_NULL:
1247 
1248  /*
1249  * Have a full qualified key - continue below
1250  */
1251  break;
1252  }
1253 
1254  /*
1255  * No need to do anything if old and new keys are equal
1256  */
1257  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1258  {
1259  heap_close(fk_rel, RowExclusiveLock);
1260  return PointerGetDatum(NULL);
1261  }
1262 
1263  if (SPI_connect() != SPI_OK_CONNECT)
1264  elog(ERROR, "SPI_connect failed");
1265 
1266  /*
1267  * Fetch or prepare a saved plan for the cascaded update
1268  */
1270 
1271  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1272  {
1273  StringInfoData querybuf;
1274  StringInfoData qualbuf;
1275  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1276  char attname[MAX_QUOTED_NAME_LEN];
1277  char paramname[16];
1278  const char *querysep;
1279  const char *qualsep;
1280  Oid queryoids[RI_MAX_NUMKEYS * 2];
1281 
1282  /* ----------
1283  * The query string built is
1284  * UPDATE ONLY <fktable> SET fkatt1 = $1 [, ...]
1285  * WHERE $n = fkatt1 [AND ...]
1286  * The type id's for the $ parameters are those of the
1287  * corresponding PK attributes. Note that we are assuming
1288  * there is an assignment cast from the PK to the FK type;
1289  * else the parser will fail.
1290  * ----------
1291  */
1292  initStringInfo(&querybuf);
1293  initStringInfo(&qualbuf);
1294  quoteRelationName(fkrelname, fk_rel);
1295  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1296  querysep = "";
1297  qualsep = "WHERE";
1298  for (i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1299  {
1300  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1301  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1302 
1303  quoteOneName(attname,
1304  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1305  appendStringInfo(&querybuf,
1306  "%s %s = $%d",
1307  querysep, attname, i + 1);
1308  sprintf(paramname, "$%d", j + 1);
1309  ri_GenerateQual(&qualbuf, qualsep,
1310  paramname, pk_type,
1311  riinfo->pf_eq_oprs[i],
1312  attname, fk_type);
1313  querysep = ",";
1314  qualsep = "AND";
1315  queryoids[i] = pk_type;
1316  queryoids[j] = pk_type;
1317  }
1318  appendStringInfoString(&querybuf, qualbuf.data);
1319 
1320  /* Prepare and save the plan */
1321  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1322  &qkey, fk_rel, pk_rel, true);
1323  }
1324 
1325  /*
1326  * We have a plan now. Run it to update the existing references.
1327  */
1328  ri_PerformCheck(riinfo, &qkey, qplan,
1329  fk_rel, pk_rel,
1330  old_row, new_row,
1331  true, /* must detect new rows */
1332  SPI_OK_UPDATE);
1333 
1334  if (SPI_finish() != SPI_OK_FINISH)
1335  elog(ERROR, "SPI_finish failed");
1336 
1337  heap_close(fk_rel, RowExclusiveLock);
1338 
1339  return PointerGetDatum(NULL);
1340 
1341  /*
1342  * Handle MATCH PARTIAL cascade update.
1343  */
1345  ereport(ERROR,
1346  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1347  errmsg("MATCH PARTIAL not yet implemented")));
1348  return PointerGetDatum(NULL);
1349 
1350  default:
1351  elog(ERROR, "unrecognized confmatchtype: %d",
1352  riinfo->confmatchtype);
1353  break;
1354  }
1355 
1356  /* Never reached */
1357  return PointerGetDatum(NULL);
1358 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#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:2751
#define RI_PLAN_CASCADE_UPD_DOUPDATE
Definition: ri_triggers.c:83
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define NULL
Definition: c.h:229
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3514
Relation tg_relation
Definition: trigger.h:34
static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 255 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), HeapTupleSatisfiesVisibility, i, initStringInfo(), LockBuffer(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, RI_ConstraintInfo::nkeys, NULL, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, PointerGetDatum, quoteOneName(), quoteRelationName(), RelationGetRelationName, ri_BuildQueryKey(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SnapshotSelf, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, and TRIGGER_FIRED_BY_UPDATE.

Referenced by RI_FKey_check_ins(), and RI_FKey_check_upd().

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

Definition at line 463 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

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

Definition at line 484 of file ri_triggers.c.

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

485 {
486  /*
487  * Check that this is a valid trigger call on the right time and event.
488  */
489  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
490 
491  /*
492  * Share code with INSERT case.
493  */
494  return RI_FKey_check((TriggerData *) fcinfo->context);
495 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:255
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
HeapTuple  old_row,
HeapTuple  new_row 
)

Definition at line 2141 of file ri_triggers.c.

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

Referenced by AfterTriggerSaveEvent().

2143 {
2144  const RI_ConstraintInfo *riinfo;
2145 
2146  /*
2147  * Get arguments.
2148  */
2149  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
2150 
2151  switch (riinfo->confmatchtype)
2152  {
2153  case FKCONSTR_MATCH_SIMPLE:
2154 
2155  /*
2156  * If any new key value is NULL, the row must satisfy the
2157  * constraint, so no check is needed.
2158  */
2159  if (ri_NullCheck(new_row, riinfo, false) != RI_KEYS_NONE_NULL)
2160  return false;
2161 
2162  /*
2163  * If the original row was inserted by our own transaction, we
2164  * must fire the trigger whether or not the keys are equal. This
2165  * is because our UPDATE will invalidate the INSERT so that the
2166  * INSERT RI trigger will not do anything; so we had better do the
2167  * UPDATE check. (We could skip this if we knew the INSERT
2168  * trigger already fired, but there is no easy way to know that.)
2169  */
2171  return true;
2172 
2173  /* If all old and new key values are equal, no check is needed */
2174  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
2175  return false;
2176 
2177  /* Else we need to fire the trigger. */
2178  return true;
2179 
2180  case FKCONSTR_MATCH_FULL:
2181 
2182  /*
2183  * If all new key values are NULL, the row must satisfy the
2184  * constraint, so no check is needed. On the other hand, if only
2185  * some of them are NULL, the row must fail the constraint. We
2186  * must not throw error here, because the row might get
2187  * invalidated before the constraint is to be checked, but we
2188  * should queue the event to apply the check later.
2189  */
2190  switch (ri_NullCheck(new_row, riinfo, false))
2191  {
2192  case RI_KEYS_ALL_NULL:
2193  return false;
2194  case RI_KEYS_SOME_NULL:
2195  return true;
2196  case RI_KEYS_NONE_NULL:
2197  break; /* continue with the check */
2198  }
2199 
2200  /*
2201  * If the original row was inserted by our own transaction, we
2202  * must fire the trigger whether or not the keys are equal. This
2203  * is because our UPDATE will invalidate the INSERT so that the
2204  * INSERT RI trigger will not do anything; so we had better do the
2205  * UPDATE check. (We could skip this if we knew the INSERT
2206  * trigger already fired, but there is no easy way to know that.)
2207  */
2209  return true;
2210 
2211  /* If all old and new key values are equal, no check is needed */
2212  if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
2213  return false;
2214 
2215  /* Else we need to fire the trigger. */
2216  return true;
2217 
2218  /* Handle MATCH PARTIAL check. */
2220  ereport(ERROR,
2221  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2222  errmsg("MATCH PARTIAL not yet implemented")));
2223  break;
2224 
2225  default:
2226  elog(ERROR, "unrecognized confmatchtype: %d",
2227  riinfo->confmatchtype);
2228  break;
2229  }
2230 
2231  /* Never reached */
2232  return false;
2233 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTupleHeader t_data
Definition: htup.h:67
#define ERROR
Definition: elog.h:43
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2751
#define ereport(elevel, rest)
Definition: elog.h:122
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3514
Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 598 of file ri_triggers.c.

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

Referenced by RI_FKey_setdefault_del().

599 {
600  /*
601  * Check that this is a valid trigger call on the right time and event.
602  */
603  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
604 
605  /*
606  * Share code with RESTRICT case.
607  */
608  return ri_restrict_del((TriggerData *) fcinfo->context, true);
609 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
static Datum ri_restrict_del(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:643
Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 810 of file ri_triggers.c.

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

Referenced by RI_FKey_setdefault_upd().

811 {
812  /*
813  * Check that this is a valid trigger call on the right time and event.
814  */
815  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
816 
817  /*
818  * Share code with RESTRICT case.
819  */
820  return ri_restrict_upd((TriggerData *) fcinfo->context, true);
821 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
static Datum ri_restrict_upd(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:855
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
HeapTuple  old_row,
HeapTuple  new_row 
)

Definition at line 2084 of file ri_triggers.c.

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

Referenced by AfterTriggerSaveEvent().

2086 {
2087  const RI_ConstraintInfo *riinfo;
2088 
2089  /*
2090  * Get arguments.
2091  */
2092  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
2093 
2094  switch (riinfo->confmatchtype)
2095  {
2096  case FKCONSTR_MATCH_SIMPLE:
2097  case FKCONSTR_MATCH_FULL:
2098 
2099  /*
2100  * If any old key value is NULL, the row could not have been
2101  * referenced by an FK row, so no check is needed.
2102  */
2103  if (ri_NullCheck(old_row, riinfo, true) != RI_KEYS_NONE_NULL)
2104  return false;
2105 
2106  /* If all old and new key values are equal, no check is needed */
2107  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
2108  return false;
2109 
2110  /* Else we need to fire the trigger. */
2111  return true;
2112 
2113  /* Handle MATCH PARTIAL check. */
2115  ereport(ERROR,
2116  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2117  errmsg("MATCH PARTIAL not yet implemented")));
2118  break;
2119 
2120  default:
2121  elog(ERROR, "unrecognized confmatchtype: %d",
2122  riinfo->confmatchtype);
2123  break;
2124  }
2125 
2126  /* Never reached */
2127  return false;
2128 }
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2751
#define ereport(elevel, rest)
Definition: elog.h:122
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3514
Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 623 of file ri_triggers.c.

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

624 {
625  /*
626  * Check that this is a valid trigger call on the right time and event.
627  */
628  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
629 
630  /*
631  * Share code with NO ACTION case.
632  */
633  return ri_restrict_del((TriggerData *) fcinfo->context, false);
634 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
static Datum ri_restrict_del(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:643
Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 835 of file ri_triggers.c.

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

836 {
837  /*
838  * Check that this is a valid trigger call on the right time and event.
839  */
840  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
841 
842  /*
843  * Share code with NO ACTION case.
844  */
845  return ri_restrict_upd((TriggerData *) fcinfo->context, false);
846 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
static Datum ri_restrict_upd(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:855
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1709 of file ri_triggers.c.

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

1710 {
1711  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1712  const RI_ConstraintInfo *riinfo;
1713  Relation fk_rel;
1714  Relation pk_rel;
1715  HeapTuple old_row;
1716  RI_QueryKey qkey;
1717  SPIPlanPtr qplan;
1718 
1719  /*
1720  * Check that this is a valid trigger call on the right time and event.
1721  */
1722  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1723 
1724  /*
1725  * Get arguments.
1726  */
1727  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1728  trigdata->tg_relation, true);
1729 
1730  /*
1731  * Get the relation descriptors of the FK and PK tables and the old tuple.
1732  *
1733  * fk_rel is opened in RowExclusiveLock mode since that's what our
1734  * eventual UPDATE will get on it.
1735  */
1736  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1737  pk_rel = trigdata->tg_relation;
1738  old_row = trigdata->tg_trigtuple;
1739 
1740  switch (riinfo->confmatchtype)
1741  {
1742  /* ----------
1743  * SQL:2008 15.17 <Execution of referential actions>
1744  * General rules 9) a) iii):
1745  * MATCH SIMPLE/FULL
1746  * ... ON DELETE SET DEFAULT
1747  * ----------
1748  */
1749  case FKCONSTR_MATCH_SIMPLE:
1750  case FKCONSTR_MATCH_FULL:
1751  switch (ri_NullCheck(old_row, riinfo, true))
1752  {
1753  case RI_KEYS_ALL_NULL:
1754  case RI_KEYS_SOME_NULL:
1755 
1756  /*
1757  * No check needed - there cannot be any reference to old
1758  * key if it contains a NULL
1759  */
1760  heap_close(fk_rel, RowExclusiveLock);
1761  return PointerGetDatum(NULL);
1762 
1763  case RI_KEYS_NONE_NULL:
1764 
1765  /*
1766  * Have a full qualified key - continue below
1767  */
1768  break;
1769  }
1770 
1771  if (SPI_connect() != SPI_OK_CONNECT)
1772  elog(ERROR, "SPI_connect failed");
1773 
1774  /*
1775  * Fetch or prepare a saved plan for the set default delete
1776  * operation
1777  */
1779 
1780  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1781  {
1782  StringInfoData querybuf;
1783  StringInfoData qualbuf;
1784  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1785  char attname[MAX_QUOTED_NAME_LEN];
1786  char paramname[16];
1787  const char *querysep;
1788  const char *qualsep;
1789  Oid queryoids[RI_MAX_NUMKEYS];
1790  int i;
1791 
1792  /* ----------
1793  * The query string built is
1794  * UPDATE ONLY <fktable> SET fkatt1 = DEFAULT [, ...]
1795  * WHERE $1 = fkatt1 [AND ...]
1796  * The type id's for the $ parameters are those of the
1797  * corresponding PK attributes.
1798  * ----------
1799  */
1800  initStringInfo(&querybuf);
1801  initStringInfo(&qualbuf);
1802  quoteRelationName(fkrelname, fk_rel);
1803  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1804  querysep = "";
1805  qualsep = "WHERE";
1806  for (i = 0; i < riinfo->nkeys; i++)
1807  {
1808  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1809  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1810 
1811  quoteOneName(attname,
1812  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1813  appendStringInfo(&querybuf,
1814  "%s %s = DEFAULT",
1815  querysep, attname);
1816  sprintf(paramname, "$%d", i + 1);
1817  ri_GenerateQual(&qualbuf, qualsep,
1818  paramname, pk_type,
1819  riinfo->pf_eq_oprs[i],
1820  attname, fk_type);
1821  querysep = ",";
1822  qualsep = "AND";
1823  queryoids[i] = pk_type;
1824  }
1825  appendStringInfoString(&querybuf, qualbuf.data);
1826 
1827  /* Prepare and save the plan */
1828  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1829  &qkey, fk_rel, pk_rel, true);
1830  }
1831 
1832  /*
1833  * We have a plan now. Run it to update the existing references.
1834  */
1835  ri_PerformCheck(riinfo, &qkey, qplan,
1836  fk_rel, pk_rel,
1837  old_row, NULL,
1838  true, /* must detect new rows */
1839  SPI_OK_UPDATE);
1840 
1841  if (SPI_finish() != SPI_OK_FINISH)
1842  elog(ERROR, "SPI_finish failed");
1843 
1844  heap_close(fk_rel, RowExclusiveLock);
1845 
1846  /*
1847  * If we just deleted the PK row whose key was equal to the FK
1848  * columns' default values, and a referencing row exists in the FK
1849  * table, we would have updated that row to the same values it
1850  * already had --- and RI_FKey_fk_upd_check_required would hence
1851  * believe no check is necessary. So we need to do another lookup
1852  * now and in case a reference still exists, abort the operation.
1853  * That is already implemented in the NO ACTION trigger, so just
1854  * run it. (This recheck is only needed in the SET DEFAULT case,
1855  * since CASCADE would remove such rows, while SET NULL is certain
1856  * to result in rows that satisfy the FK constraint.)
1857  */
1858  RI_FKey_noaction_del(fcinfo);
1859 
1860  return PointerGetDatum(NULL);
1861 
1862  /*
1863  * Handle MATCH PARTIAL set default delete.
1864  */
1866  ereport(ERROR,
1867  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1868  errmsg("MATCH PARTIAL not yet implemented")));
1869  return PointerGetDatum(NULL);
1870 
1871  default:
1872  elog(ERROR, "unrecognized confmatchtype: %d",
1873  riinfo->confmatchtype);
1874  break;
1875  }
1876 
1877  /* Never reached */
1878  return PointerGetDatum(NULL);
1879 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#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:2751
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
#define NULL
Definition: c.h:229
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:598
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_PLAN_SETDEFAULT_DEL_DOUPDATE
Definition: ri_triggers.c:88
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
Relation tg_relation
Definition: trigger.h:34
Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1889 of file ri_triggers.c.

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

1890 {
1891  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1892  const RI_ConstraintInfo *riinfo;
1893  Relation fk_rel;
1894  Relation pk_rel;
1895  HeapTuple new_row;
1896  HeapTuple old_row;
1897  RI_QueryKey qkey;
1898  SPIPlanPtr qplan;
1899 
1900  /*
1901  * Check that this is a valid trigger call on the right time and event.
1902  */
1903  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1904 
1905  /*
1906  * Get arguments.
1907  */
1908  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1909  trigdata->tg_relation, true);
1910 
1911  /*
1912  * Get the relation descriptors of the FK and PK tables and the old tuple.
1913  *
1914  * fk_rel is opened in RowExclusiveLock mode since that's what our
1915  * eventual UPDATE will get on it.
1916  */
1917  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1918  pk_rel = trigdata->tg_relation;
1919  new_row = trigdata->tg_newtuple;
1920  old_row = trigdata->tg_trigtuple;
1921 
1922  switch (riinfo->confmatchtype)
1923  {
1924  /* ----------
1925  * SQL:2008 15.17 <Execution of referential actions>
1926  * General rules 10) a) iii):
1927  * MATCH SIMPLE/FULL
1928  * ... ON UPDATE SET DEFAULT
1929  * ----------
1930  */
1931  case FKCONSTR_MATCH_SIMPLE:
1932  case FKCONSTR_MATCH_FULL:
1933  switch (ri_NullCheck(old_row, riinfo, true))
1934  {
1935  case RI_KEYS_ALL_NULL:
1936  case RI_KEYS_SOME_NULL:
1937 
1938  /*
1939  * No check needed - there cannot be any reference to old
1940  * key if it contains a NULL
1941  */
1942  heap_close(fk_rel, RowExclusiveLock);
1943  return PointerGetDatum(NULL);
1944 
1945  case RI_KEYS_NONE_NULL:
1946 
1947  /*
1948  * Have a full qualified key - continue below
1949  */
1950  break;
1951  }
1952 
1953  /*
1954  * No need to do anything if old and new keys are equal
1955  */
1956  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1957  {
1958  heap_close(fk_rel, RowExclusiveLock);
1959  return PointerGetDatum(NULL);
1960  }
1961 
1962  if (SPI_connect() != SPI_OK_CONNECT)
1963  elog(ERROR, "SPI_connect failed");
1964 
1965  /*
1966  * Fetch or prepare a saved plan for the set default update
1967  * operation
1968  */
1970 
1971  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1972  {
1973  StringInfoData querybuf;
1974  StringInfoData qualbuf;
1975  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1976  char attname[MAX_QUOTED_NAME_LEN];
1977  char paramname[16];
1978  const char *querysep;
1979  const char *qualsep;
1980  Oid queryoids[RI_MAX_NUMKEYS];
1981  int i;
1982 
1983  /* ----------
1984  * The query string built is
1985  * UPDATE ONLY <fktable> SET fkatt1 = DEFAULT [, ...]
1986  * WHERE $1 = fkatt1 [AND ...]
1987  * The type id's for the $ parameters are those of the
1988  * corresponding PK attributes.
1989  * ----------
1990  */
1991  initStringInfo(&querybuf);
1992  initStringInfo(&qualbuf);
1993  quoteRelationName(fkrelname, fk_rel);
1994  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1995  querysep = "";
1996  qualsep = "WHERE";
1997  for (i = 0; i < riinfo->nkeys; i++)
1998  {
1999  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
2000  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
2001 
2002  quoteOneName(attname,
2003  RIAttName(fk_rel, riinfo->fk_attnums[i]));
2004  appendStringInfo(&querybuf,
2005  "%s %s = DEFAULT",
2006  querysep, attname);
2007  sprintf(paramname, "$%d", i + 1);
2008  ri_GenerateQual(&qualbuf, qualsep,
2009  paramname, pk_type,
2010  riinfo->pf_eq_oprs[i],
2011  attname, fk_type);
2012  querysep = ",";
2013  qualsep = "AND";
2014  queryoids[i] = pk_type;
2015  }
2016  appendStringInfoString(&querybuf, qualbuf.data);
2017 
2018  /* Prepare and save the plan */
2019  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
2020  &qkey, fk_rel, pk_rel, true);
2021  }
2022 
2023  /*
2024  * We have a plan now. Run it to update the existing references.
2025  */
2026  ri_PerformCheck(riinfo, &qkey, qplan,
2027  fk_rel, pk_rel,
2028  old_row, NULL,
2029  true, /* must detect new rows */
2030  SPI_OK_UPDATE);
2031 
2032  if (SPI_finish() != SPI_OK_FINISH)
2033  elog(ERROR, "SPI_finish failed");
2034 
2035  heap_close(fk_rel, RowExclusiveLock);
2036 
2037  /*
2038  * If we just updated the PK row whose key was equal to the FK
2039  * columns' default values, and a referencing row exists in the FK
2040  * table, we would have updated that row to the same values it
2041  * already had --- and RI_FKey_fk_upd_check_required would hence
2042  * believe no check is necessary. So we need to do another lookup
2043  * now and in case a reference still exists, abort the operation.
2044  * That is already implemented in the NO ACTION trigger, so just
2045  * run it. (This recheck is only needed in the SET DEFAULT case,
2046  * since CASCADE must change the FK key values, while SET NULL is
2047  * certain to result in rows that satisfy the FK constraint.)
2048  */
2049  RI_FKey_noaction_upd(fcinfo);
2050 
2051  return PointerGetDatum(NULL);
2052 
2053  /*
2054  * Handle MATCH PARTIAL set default update.
2055  */
2057  ereport(ERROR,
2058  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2059  errmsg("MATCH PARTIAL not yet implemented")));
2060  return PointerGetDatum(NULL);
2061 
2062  default:
2063  elog(ERROR, "unrecognized confmatchtype: %d",
2064  riinfo->confmatchtype);
2065  break;
2066  }
2067 
2068  /* Never reached */
2069  return PointerGetDatum(NULL);
2070 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RI_PLAN_SETDEFAULT_UPD_DOUPDATE
Definition: ri_triggers.c:89
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2751
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define NULL
Definition: c.h:229
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
Datum RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:810
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3514
Relation tg_relation
Definition: trigger.h:34
Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1368 of file ri_triggers.c.

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

1369 {
1370  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1371  const RI_ConstraintInfo *riinfo;
1372  Relation fk_rel;
1373  Relation pk_rel;
1374  HeapTuple old_row;
1375  RI_QueryKey qkey;
1376  SPIPlanPtr qplan;
1377  int i;
1378 
1379  /*
1380  * Check that this is a valid trigger call on the right time and event.
1381  */
1382  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1383 
1384  /*
1385  * Get arguments.
1386  */
1387  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1388  trigdata->tg_relation, true);
1389 
1390  /*
1391  * Get the relation descriptors of the FK and PK tables and the old tuple.
1392  *
1393  * fk_rel is opened in RowExclusiveLock mode since that's what our
1394  * eventual UPDATE will get on it.
1395  */
1396  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1397  pk_rel = trigdata->tg_relation;
1398  old_row = trigdata->tg_trigtuple;
1399 
1400  switch (riinfo->confmatchtype)
1401  {
1402  /* ----------
1403  * SQL:2008 15.17 <Execution of referential actions>
1404  * General rules 9) a) ii):
1405  * MATCH SIMPLE/FULL
1406  * ... ON DELETE SET NULL
1407  * ----------
1408  */
1409  case FKCONSTR_MATCH_SIMPLE:
1410  case FKCONSTR_MATCH_FULL:
1411  switch (ri_NullCheck(old_row, riinfo, true))
1412  {
1413  case RI_KEYS_ALL_NULL:
1414  case RI_KEYS_SOME_NULL:
1415 
1416  /*
1417  * No check needed - there cannot be any reference to old
1418  * key if it contains a NULL
1419  */
1420  heap_close(fk_rel, RowExclusiveLock);
1421  return PointerGetDatum(NULL);
1422 
1423  case RI_KEYS_NONE_NULL:
1424 
1425  /*
1426  * Have a full qualified key - continue below
1427  */
1428  break;
1429  }
1430 
1431  if (SPI_connect() != SPI_OK_CONNECT)
1432  elog(ERROR, "SPI_connect failed");
1433 
1434  /*
1435  * Fetch or prepare a saved plan for the set null delete operation
1436  */
1438 
1439  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1440  {
1441  StringInfoData querybuf;
1442  StringInfoData qualbuf;
1443  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1444  char attname[MAX_QUOTED_NAME_LEN];
1445  char paramname[16];
1446  const char *querysep;
1447  const char *qualsep;
1448  Oid queryoids[RI_MAX_NUMKEYS];
1449 
1450  /* ----------
1451  * The query string built is
1452  * UPDATE ONLY <fktable> SET fkatt1 = NULL [, ...]
1453  * WHERE $1 = fkatt1 [AND ...]
1454  * The type id's for the $ parameters are those of the
1455  * corresponding PK attributes.
1456  * ----------
1457  */
1458  initStringInfo(&querybuf);
1459  initStringInfo(&qualbuf);
1460  quoteRelationName(fkrelname, fk_rel);
1461  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1462  querysep = "";
1463  qualsep = "WHERE";
1464  for (i = 0; i < riinfo->nkeys; i++)
1465  {
1466  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1467  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1468 
1469  quoteOneName(attname,
1470  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1471  appendStringInfo(&querybuf,
1472  "%s %s = NULL",
1473  querysep, attname);
1474  sprintf(paramname, "$%d", i + 1);
1475  ri_GenerateQual(&qualbuf, qualsep,
1476  paramname, pk_type,
1477  riinfo->pf_eq_oprs[i],
1478  attname, fk_type);
1479  querysep = ",";
1480  qualsep = "AND";
1481  queryoids[i] = pk_type;
1482  }
1483  appendStringInfoString(&querybuf, qualbuf.data);
1484 
1485  /* Prepare and save the plan */
1486  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1487  &qkey, fk_rel, pk_rel, true);
1488  }
1489 
1490  /*
1491  * We have a plan now. Run it to check for existing references.
1492  */
1493  ri_PerformCheck(riinfo, &qkey, qplan,
1494  fk_rel, pk_rel,
1495  old_row, NULL,
1496  true, /* must detect new rows */
1497  SPI_OK_UPDATE);
1498 
1499  if (SPI_finish() != SPI_OK_FINISH)
1500  elog(ERROR, "SPI_finish failed");
1501 
1502  heap_close(fk_rel, RowExclusiveLock);
1503 
1504  return PointerGetDatum(NULL);
1505 
1506  /*
1507  * Handle MATCH PARTIAL set null delete.
1508  */
1510  ereport(ERROR,
1511  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1512  errmsg("MATCH PARTIAL not yet implemented")));
1513  return PointerGetDatum(NULL);
1514 
1515  default:
1516  elog(ERROR, "unrecognized confmatchtype: %d",
1517  riinfo->confmatchtype);
1518  break;
1519  }
1520 
1521  /* Never reached */
1522  return PointerGetDatum(NULL);
1523 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#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:2751
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:100
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
#define NULL
Definition: c.h:229
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_PLAN_SETNULL_DEL_DOUPDATE
Definition: ri_triggers.c:86
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
Relation tg_relation
Definition: trigger.h:34
Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1533 of file ri_triggers.c.

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

1534 {
1535  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1536  const RI_ConstraintInfo *riinfo;
1537  Relation fk_rel;
1538  Relation pk_rel;
1539  HeapTuple new_row;
1540  HeapTuple old_row;
1541  RI_QueryKey qkey;
1542  SPIPlanPtr qplan;
1543  int i;
1544 
1545  /*
1546  * Check that this is a valid trigger call on the right time and event.
1547  */
1548  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1549 
1550  /*
1551  * Get arguments.
1552  */
1553  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1554  trigdata->tg_relation, true);
1555 
1556  /*
1557  * Get the relation descriptors of the FK and PK tables and the old tuple.
1558  *
1559  * fk_rel is opened in RowExclusiveLock mode since that's what our
1560  * eventual UPDATE will get on it.
1561  */
1562  fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
1563  pk_rel = trigdata->tg_relation;
1564  new_row = trigdata->tg_newtuple;
1565  old_row = trigdata->tg_trigtuple;
1566 
1567  switch (riinfo->confmatchtype)
1568  {
1569  /* ----------
1570  * SQL:2008 15.17 <Execution of referential actions>
1571  * General rules 10) a) ii):
1572  * MATCH SIMPLE/FULL
1573  * ... ON UPDATE SET NULL
1574  * ----------
1575  */
1576  case FKCONSTR_MATCH_SIMPLE:
1577  case FKCONSTR_MATCH_FULL:
1578  switch (ri_NullCheck(old_row, riinfo, true))
1579  {
1580  case RI_KEYS_ALL_NULL:
1581  case RI_KEYS_SOME_NULL:
1582 
1583  /*
1584  * No check needed - there cannot be any reference to old
1585  * key if it contains a NULL
1586  */
1587  heap_close(fk_rel, RowExclusiveLock);
1588  return PointerGetDatum(NULL);
1589 
1590  case RI_KEYS_NONE_NULL:
1591 
1592  /*
1593  * Have a full qualified key - continue below
1594  */
1595  break;
1596  }
1597 
1598  /*
1599  * No need to do anything if old and new keys are equal
1600  */
1601  if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
1602  {
1603  heap_close(fk_rel, RowExclusiveLock);
1604  return PointerGetDatum(NULL);
1605  }
1606 
1607  if (SPI_connect() != SPI_OK_CONNECT)
1608  elog(ERROR, "SPI_connect failed");
1609 
1610  /*
1611  * Fetch or prepare a saved plan for the set null update operation
1612  */
1614 
1615  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1616  {
1617  StringInfoData querybuf;
1618  StringInfoData qualbuf;
1619  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1620  char attname[MAX_QUOTED_NAME_LEN];
1621  char paramname[16];
1622  const char *querysep;
1623  const char *qualsep;
1624  Oid queryoids[RI_MAX_NUMKEYS];
1625 
1626  /* ----------
1627  * The query string built is
1628  * UPDATE ONLY <fktable> SET fkatt1 = NULL [, ...]
1629  * WHERE $1 = fkatt1 [AND ...]
1630  * The type id's for the $ parameters are those of the
1631  * corresponding PK attributes.
1632  * ----------
1633  */
1634  initStringInfo(&querybuf);
1635  initStringInfo(&qualbuf);
1636  quoteRelationName(fkrelname, fk_rel);
1637  appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
1638  querysep = "";
1639  qualsep = "WHERE";
1640  for (i = 0; i < riinfo->nkeys; i++)
1641  {
1642  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1643  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1644 
1645  quoteOneName(attname,
1646  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1647  appendStringInfo(&querybuf,
1648  "%s %s = NULL",
1649  querysep, attname);
1650  sprintf(paramname, "$%d", i + 1);
1651  ri_GenerateQual(&qualbuf, qualsep,
1652  paramname, pk_type,
1653  riinfo->pf_eq_oprs[i],
1654  attname, fk_type);
1655  querysep = ",";
1656  qualsep = "AND";
1657  queryoids[i] = pk_type;
1658  }
1659  appendStringInfoString(&querybuf, qualbuf.data);
1660 
1661  /* Prepare and save the plan */
1662  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1663  &qkey, fk_rel, pk_rel, true);
1664  }
1665 
1666  /*
1667  * We have a plan now. Run it to update the existing references.
1668  */
1669  ri_PerformCheck(riinfo, &qkey, qplan,
1670  fk_rel, pk_rel,
1671  old_row, NULL,
1672  true, /* must detect new rows */
1673  SPI_OK_UPDATE);
1674 
1675  if (SPI_finish() != SPI_OK_FINISH)
1676  elog(ERROR, "SPI_finish failed");
1677 
1678  heap_close(fk_rel, RowExclusiveLock);
1679 
1680  return PointerGetDatum(NULL);
1681 
1682  /*
1683  * Handle MATCH PARTIAL set null update.
1684  */
1686  ereport(ERROR,
1687  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1688  errmsg("MATCH PARTIAL not yet implemented")));
1689  return PointerGetDatum(NULL);
1690 
1691  default:
1692  elog(ERROR, "unrecognized confmatchtype: %d",
1693  riinfo->confmatchtype);
1694  break;
1695  }
1696 
1697  /* Never reached */
1698  return PointerGetDatum(NULL);
1699 }
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:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
int SPI_connect(void)
Definition: spi.c:84
#define PointerGetDatum(X)
Definition: postgres.h:562
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple tg_trigtuple
Definition: trigger.h:35
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define RI_PLAN_SETNULL_UPD_DOUPDATE
Definition: ri_triggers.c:87
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2705
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, HeapTuple old_tuple, HeapTuple new_tuple, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:3038
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3426
#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:2751
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define NULL
Definition: c.h:229
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:99
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel, bool cache_plan)
Definition: ri_triggers.c:2991
#define SPI_OK_FINISH
Definition: spi.h:51
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SPI_OK_UPDATE
Definition: spi.h:58
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2690
#define elog
Definition: elog.h:219
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3514
Relation tg_relation
Definition: trigger.h:34
int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3701 of file ri_triggers.c.

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and CreateTrigger().

3702 {
3703  switch (tgfoid)
3704  {
3705  case F_RI_FKEY_CASCADE_DEL:
3706  case F_RI_FKEY_CASCADE_UPD:
3707  case F_RI_FKEY_RESTRICT_DEL:
3708  case F_RI_FKEY_RESTRICT_UPD:
3709  case F_RI_FKEY_SETNULL_DEL:
3710  case F_RI_FKEY_SETNULL_UPD:
3711  case F_RI_FKEY_SETDEFAULT_DEL:
3712  case F_RI_FKEY_SETDEFAULT_UPD:
3713  case F_RI_FKEY_NOACTION_DEL:
3714  case F_RI_FKEY_NOACTION_UPD:
3715  return RI_TRIGGER_PK;
3716 
3717  case F_RI_FKEY_CHECK_INS:
3718  case F_RI_FKEY_CHECK_UPD:
3719  return RI_TRIGGER_FK;
3720  }
3721 
3722  return RI_TRIGGER_NONE;
3723 }
#define RI_TRIGGER_FK
Definition: trigger.h:210
#define RI_TRIGGER_PK
Definition: trigger.h:209
#define RI_TRIGGER_NONE
Definition: trigger.h:211
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 2569 of file ri_triggers.c.

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

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), and ri_restrict_upd().

2574 {
2575  HeapTuple opertup;
2576  Form_pg_operator operform;
2577  char *oprname;
2578  char *nspname;
2579 
2580  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
2581  if (!HeapTupleIsValid(opertup))
2582  elog(ERROR, "cache lookup failed for operator %u", opoid);
2583  operform = (Form_pg_operator) GETSTRUCT(opertup);
2584  Assert(operform->oprkind == 'b');
2585  oprname = NameStr(operform->oprname);
2586 
2587  nspname = get_namespace_name(operform->oprnamespace);
2588 
2589  appendStringInfo(buf, " %s %s", sep, leftop);
2590  if (leftoptype != operform->oprleft)
2591  ri_add_cast_to(buf, operform->oprleft);
2592  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
2593  appendStringInfoString(buf, oprname);
2594  appendStringInfo(buf, ") %s", rightop);
2595  if (rightoptype != operform->oprright)
2596  ri_add_cast_to(buf, operform->oprright);
2597 
2598  ReleaseSysCache(opertup);
2599 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:675
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
#define NameStr(name)
Definition: c.h:499
static void ri_add_cast_to(StringInfo buf, Oid typid)
Definition: ri_triggers.c:2610
#define elog
Definition: elog.h:219
static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 2649 of file ri_triggers.c.

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

Referenced by RI_Initial_Check().

2650 {
2651  HeapTuple tp;
2652  Form_pg_collation colltup;
2653  char *collname;
2654  char onename[MAX_QUOTED_NAME_LEN];
2655 
2656  /* Nothing to do if it's a noncollatable data type */
2657  if (!OidIsValid(collation))
2658  return;
2659 
2660  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2661  if (!HeapTupleIsValid(tp))
2662  elog(ERROR, "cache lookup failed for collation %u", collation);
2663  colltup = (Form_pg_collation) GETSTRUCT(tp);
2664  collname = NameStr(colltup->collname);
2665 
2666  /*
2667  * We qualify the name always, for simplicity and to ensure the query is
2668  * not search-path-dependent.
2669  */
2670  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2671  appendStringInfo(buf, " COLLATE %s", onename);
2672  quoteOneName(onename, collname);
2673  appendStringInfo(buf, ".%s", onename);
2674 
2675  ReleaseSysCache(tp);
2676 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:52
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static RI_CompareHashEntry * ri_HashCompareOp ( Oid  eq_opr,
Oid  typeid 
)
static

Definition at line 3608 of file ri_triggers.c.

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

Referenced by ri_AttributesEqual().

3609 {
3610  RI_CompareKey key;
3611  RI_CompareHashEntry *entry;
3612  bool found;
3613 
3614  /*
3615  * On the first call initialize the hashtable
3616  */
3617  if (!ri_compare_cache)
3619 
3620  /*
3621  * Find or create a hash entry. Note we're assuming RI_CompareKey
3622  * contains no struct padding.
3623  */
3624  key.eq_opr = eq_opr;
3625  key.typeid = typeid;
3627  (void *) &key,
3628  HASH_ENTER, &found);
3629  if (!found)
3630  entry->valid = false;
3631 
3632  /*
3633  * If not already initialized, do so. Since we'll keep this hash entry
3634  * for the life of the backend, put any subsidiary info for the function
3635  * cache structs into TopMemoryContext.
3636  */
3637  if (!entry->valid)
3638  {
3639  Oid lefttype,
3640  righttype,
3641  castfunc;
3642  CoercionPathType pathtype;
3643 
3644  /* We always need to know how to call the equality operator */
3645  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3647 
3648  /*
3649  * If we chose to use a cast from FK to PK type, we may have to apply
3650  * the cast function to get to the operator's input type.
3651  *
3652  * XXX eventually it would be good to support array-coercion cases
3653  * here and in ri_AttributesEqual(). At the moment there is no point
3654  * because cases involving nonidentical array types will be rejected
3655  * at constraint creation time.
3656  *
3657  * XXX perhaps also consider supporting CoerceViaIO? No need at the
3658  * moment since that will never be generated for implicit coercions.
3659  */
3660  op_input_types(eq_opr, &lefttype, &righttype);
3661  Assert(lefttype == righttype);
3662  if (typeid == lefttype)
3663  castfunc = InvalidOid; /* simplest case */
3664  else
3665  {
3666  pathtype = find_coercion_pathway(lefttype, typeid,
3668  &castfunc);
3669  if (pathtype != COERCION_PATH_FUNC &&
3670  pathtype != COERCION_PATH_RELABELTYPE)
3671  {
3672  /*
3673  * The declared input type of the eq_opr might be a
3674  * polymorphic type such as ANYARRAY or ANYENUM, or other
3675  * special cases such as RECORD; find_coercion_pathway
3676  * currently doesn't subsume these special cases.
3677  */
3678  if (!IsBinaryCoercible(typeid, lefttype))
3679  elog(ERROR, "no conversion function from %s to %s",
3680  format_type_be(typeid),
3681  format_type_be(lefttype));
3682  }
3683  }
3684  if (OidIsValid(castfunc))
3685  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3687  else
3689  entry->valid = true;
3690  }
3691 
3692  return entry;
3693 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
CoercionPathType
Definition: parse_coerce.h:24
#define ERROR
Definition: elog.h:43
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1167
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
MemoryContext TopMemoryContext
Definition: mcxt.c:43
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
Oid fn_oid
Definition: fmgr.h:59
#define Assert(condition)
Definition: c.h:675
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
static void ri_InitHashTables(void)
Definition: ri_triggers.c:3386
#define elog
Definition: elog.h:219
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:177
static HTAB * ri_compare_cache
Definition: ri_triggers.c:187
static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 3479 of file ri_triggers.c.

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

Referenced by ri_PlanCheck().

3480 {
3481  RI_QueryHashEntry *entry;
3482  bool found;
3483 
3484  /*
3485  * On the first call initialize the hashtable
3486  */
3487  if (!ri_query_cache)
3489 
3490  /*
3491  * Add the new plan. We might be overwriting an entry previously found
3492  * invalid by ri_FetchPreparedPlan.
3493  */
3495  (void *) key,
3496  HASH_ENTER, &found);
3497  Assert(!found || entry->plan == NULL);
3498  entry->plan = plan;
3499 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:186
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
SPIPlanPtr plan
Definition: ri_triggers.c:151
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void ri_InitHashTables(void)
Definition: ri_triggers.c:3386
static void ri_InitHashTables ( void  )
static

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

3387 {
3388  HASHCTL ctl;
3389 
3390  memset(&ctl, 0, sizeof(ctl));
3391  ctl.keysize = sizeof(Oid);
3392  ctl.entrysize = sizeof(RI_ConstraintInfo);
3393  ri_constraint_cache = hash_create("RI constraint cache",
3395  &ctl, HASH_ELEM | HASH_BLOBS);
3396 
3397  /* Arrange to flush cache on pg_constraint changes */
3400  (Datum) 0);
3401 
3402  memset(&ctl, 0, sizeof(ctl));
3403  ctl.keysize = sizeof(RI_QueryKey);
3404  ctl.entrysize = sizeof(RI_QueryHashEntry);
3405  ri_query_cache = hash_create("RI query cache",
3407  &ctl, HASH_ELEM | HASH_BLOBS);
3408 
3409  memset(&ctl, 0, sizeof(ctl));
3410  ctl.keysize = sizeof(RI_CompareKey);
3411  ctl.entrysize = sizeof(RI_CompareHashEntry);
3412  ri_compare_cache = hash_create("RI compare cache",
3414  &ctl, HASH_ELEM | HASH_BLOBS);
3415 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:186
struct RI_CompareKey RI_CompareKey
#define HASH_ELEM
Definition: hsearch.h:87
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:185
Size entrysize
Definition: hsearch.h:73
unsigned int Oid
Definition: postgres_ext.h:31
struct RI_ConstraintInfo RI_ConstraintInfo
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:70
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2953
struct RI_CompareHashEntry RI_CompareHashEntry
#define HASH_BLOBS
Definition: hsearch.h:88
struct RI_QueryKey RI_QueryKey
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1389
uintptr_t Datum
Definition: postgres.h:372
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:69
static HTAB * ri_compare_cache
Definition: ri_triggers.c:187
struct RI_QueryHashEntry RI_QueryHashEntry
bool RI_Initial_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 2254 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

2255 {
2256  const RI_ConstraintInfo *riinfo;
2257  StringInfoData querybuf;
2258  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
2259  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
2260  char pkattname[MAX_QUOTED_NAME_LEN + 3];
2261  char fkattname[MAX_QUOTED_NAME_LEN + 3];
2262  RangeTblEntry *pkrte;
2263  RangeTblEntry *fkrte;
2264  const char *sep;
2265  int i;
2266  int save_nestlevel;
2267  char workmembuf[32];
2268  int spi_result;
2269  SPIPlanPtr qplan;
2270 
2271  /* Fetch constraint info. */
2272  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
2273 
2274  /*
2275  * Check to make sure current user has enough permissions to do the test
2276  * query. (If not, caller can fall back to the trigger method, which
2277  * works because it changes user IDs on the fly.)
2278  *
2279  * XXX are there any other show-stopper conditions to check?
2280  */
2281  pkrte = makeNode(RangeTblEntry);
2282  pkrte->rtekind = RTE_RELATION;
2283  pkrte->relid = RelationGetRelid(pk_rel);
2284  pkrte->relkind = pk_rel->rd_rel->relkind;
2285  pkrte->requiredPerms = ACL_SELECT;
2286 
2287  fkrte = makeNode(RangeTblEntry);
2288  fkrte->rtekind = RTE_RELATION;
2289  fkrte->relid = RelationGetRelid(fk_rel);
2290  fkrte->relkind = fk_rel->rd_rel->relkind;
2291  fkrte->requiredPerms = ACL_SELECT;
2292 
2293  for (i = 0; i < riinfo->nkeys; i++)
2294  {
2295  int attno;
2296 
2297  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
2298  pkrte->selectedCols = bms_add_member(pkrte->selectedCols, attno);
2299 
2300  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
2301  fkrte->selectedCols = bms_add_member(fkrte->selectedCols, attno);
2302  }
2303 
2304  if (!ExecCheckRTPerms(list_make2(fkrte, pkrte), false))
2305  return false;
2306 
2307  /*
2308  * Also punt if RLS is enabled on either table unless this role has the
2309  * bypassrls right or is the table owner of the table(s) involved which
2310  * have RLS enabled.
2311  */
2313  ((pk_rel->rd_rel->relrowsecurity &&
2314  !pg_class_ownercheck(pkrte->relid, GetUserId())) ||
2315  (fk_rel->rd_rel->relrowsecurity &&
2316  !pg_class_ownercheck(fkrte->relid, GetUserId()))))
2317  return false;
2318 
2319  /*----------
2320  * The query string built is:
2321  * SELECT fk.keycols FROM ONLY relname fk
2322  * LEFT OUTER JOIN ONLY pkrelname pk
2323  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
2324  * WHERE pk.pkkeycol1 IS NULL AND
2325  * For MATCH SIMPLE:
2326  * (fk.keycol1 IS NOT NULL [AND ...])
2327  * For MATCH FULL:
2328  * (fk.keycol1 IS NOT NULL [OR ...])
2329  *
2330  * We attach COLLATE clauses to the operators when comparing columns
2331  * that have different collations.
2332  *----------
2333  */
2334  initStringInfo(&querybuf);
2335  appendStringInfoString(&querybuf, "SELECT ");
2336  sep = "";
2337  for (i = 0; i < riinfo->nkeys; i++)
2338  {
2339  quoteOneName(fkattname,
2340  RIAttName(fk_rel, riinfo->fk_attnums[i]));
2341  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
2342  sep = ", ";
2343  }
2344 
2345  quoteRelationName(pkrelname, pk_rel);
2346  quoteRelationName(fkrelname, fk_rel);
2347  appendStringInfo(&querybuf,
2348  " FROM ONLY %s fk LEFT OUTER JOIN ONLY %s pk ON",
2349  fkrelname, pkrelname);
2350 
2351  strcpy(pkattname, "pk.");
2352  strcpy(fkattname, "fk.");
2353  sep = "(";
2354  for (i = 0; i < riinfo->nkeys; i++)
2355  {
2356  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
2357  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
2358  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
2359  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
2360 
2361  quoteOneName(pkattname + 3,
2362  RIAttName(pk_rel, riinfo->pk_attnums[i]));
2363  quoteOneName(fkattname + 3,
2364  RIAttName(fk_rel, riinfo->fk_attnums[i]));
2365  ri_GenerateQual(&querybuf, sep,
2366  pkattname, pk_type,
2367  riinfo->pf_eq_oprs[i],
2368  fkattname, fk_type);
2369  if (pk_coll != fk_coll)
2370  ri_GenerateQualCollation(&querybuf, pk_coll);
2371  sep = "AND";
2372  }
2373 
2374  /*
2375  * It's sufficient to test any one pk attribute for null to detect a join
2376  * failure.
2377  */
2378  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
2379  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
2380 
2381  sep = "";
2382  for (i = 0; i < riinfo->nkeys; i++)
2383  {
2384  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
2385  appendStringInfo(&querybuf,
2386  "%sfk.%s IS NOT NULL",
2387  sep, fkattname);
2388  switch (riinfo->confmatchtype)
2389  {
2390  case FKCONSTR_MATCH_SIMPLE:
2391  sep = " AND ";
2392  break;
2393  case FKCONSTR_MATCH_FULL:
2394  sep = " OR ";
2395  break;
2397  ereport(ERROR,
2398  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2399  errmsg("MATCH PARTIAL not yet implemented")));
2400  break;
2401  default:
2402  elog(ERROR, "unrecognized confmatchtype: %d",
2403  riinfo->confmatchtype);
2404  break;
2405  }
2406  }
2407  appendStringInfoChar(&querybuf, ')');
2408 
2409  /*
2410  * Temporarily increase work_mem so that the check query can be executed
2411  * more efficiently. It seems okay to do this because the query is simple
2412  * enough to not use a multiple of work_mem, and one typically would not
2413  * have many large foreign-key validations happening concurrently. So
2414  * this seems to meet the criteria for being considered a "maintenance"
2415  * operation, and accordingly we use maintenance_work_mem.
2416  *
2417  * We use the equivalent of a function SET option to allow the setting to
2418  * persist for exactly the duration of the check query. guc.c also takes
2419  * care of undoing the setting on error.
2420  */
2421  save_nestlevel = NewGUCNestLevel();
2422 
2423  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
2424  (void) set_config_option("work_mem", workmembuf,
2426  GUC_ACTION_SAVE, true, 0, false);
2427 
2428  if (SPI_connect() != SPI_OK_CONNECT)
2429  elog(ERROR, "SPI_connect failed");
2430 
2431  /*
2432  * Generate the plan. We don't need to cache it, and there are no
2433  * arguments to the plan.
2434  */
2435  qplan = SPI_prepare(querybuf.data, 0, NULL);
2436 
2437  if (qplan == NULL)
2438  elog(ERROR, "SPI_prepare returned %d for %s",
2439  SPI_result, querybuf.data);
2440 
2441  /*
2442  * Run the plan. For safety we force a current snapshot to be used. (In
2443  * transaction-snapshot mode, this arguably violates transaction isolation
2444  * rules, but we really haven't got much choice.) We don't need to
2445  * register the snapshot, because SPI_execute_snapshot will see to it. We
2446  * need at most one tuple returned, so pass limit = 1.
2447  */
2448  spi_result = SPI_execute_snapshot(qplan,
2449  NULL, NULL,
2452  true, false, 1);
2453 
2454  /* Check result */
2455  if (spi_result != SPI_OK_SELECT)
2456  elog(ERROR, "SPI_execute_snapshot returned %d", spi_result);
2457 
2458  /* Did we find a tuple violating the constraint? */
2459  if (SPI_processed > 0)
2460  {
2461  HeapTuple tuple = SPI_tuptable->vals[0];
2462  TupleDesc tupdesc = SPI_tuptable->tupdesc;
2463  RI_ConstraintInfo fake_riinfo;
2464 
2465  /*
2466  * The columns to look at in the result tuple are 1..N, not whatever
2467  * they are in the fk_rel. Hack up riinfo so that the subroutines
2468  * called here will behave properly.
2469  *
2470  * In addition to this, we have to pass the correct tupdesc to
2471  * ri_ReportViolation, overriding its normal habit of using the pk_rel
2472  * or fk_rel's tupdesc.
2473  */
2474  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
2475  for (i = 0; i < fake_riinfo.nkeys; i++)
2476  fake_riinfo.fk_attnums[i] = i + 1;
2477 
2478  /*
2479  * If it's MATCH FULL, and there are any nulls in the FK keys,
2480  * complain about that rather than the lack of a match. MATCH FULL
2481  * disallows partially-null FK rows.
2482  */
2483  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
2484  ri_NullCheck(tuple, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
2485  ereport(ERROR,
2486  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2487  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2488  RelationGetRelationName(fk_rel),
2489  NameStr(fake_riinfo.conname)),
2490  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
2491  errtableconstraint(fk_rel,
2492  NameStr(fake_riinfo.conname))));
2493 
2494  /*
2495  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
2496  * query, which isn't true, but will cause it to use
2497  * fake_riinfo.fk_attnums as we need.
2498  */
2499  ri_ReportViolation(&fake_riinfo,
2500  pk_rel, fk_rel,
2501  tuple, tupdesc,
2502  RI_PLAN_CHECK_LOOKUPPK, false);
2503  }
2504 
2505  if (SPI_finish() != SPI_OK_FINISH)
2506  elog(ERROR, "SPI_finish failed");
2507 
2508  /*
2509  * Restore work_mem.
2510  */
2511  AtEOXact_GUC(true, save_nestlevel);
2512 
2513  return true;
2514 }
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:2649
#define list_make2(x1, x2)
Definition: pg_list.h:140
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ri_triggers.c:2569
#define SPI_OK_CONNECT
Definition: spi.h:50
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2060
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2549
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3348
Oid GetUserId(void)
Definition: miscinit.c:283
int SPI_connect(void)
Definition: spi.c:84
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:482
int SPI_finish(void)
Definition: spi.c:148
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
AclMode requiredPerms
Definition: parsenodes.h:1039
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:28
uint64 SPI_processed
Definition: spi.c:39
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:5190
int SPI_result
Definition: spi.c:42
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5297
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:96
Bitmapset * selectedCols
Definition: parsenodes.h:1041
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2529
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:91
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:92
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno, bool spi_err)
Definition: ri_triggers.c:3205
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5079
int errdetail(const char *fmt,...)
Definition: elog.c:873
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:124
#define RelationGetRelationName(relation)
Definition: rel.h:436
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2751
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
int SPI_execute_snapshot(SPIPlanPtr plan, Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition: spi.c:407
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define InvalidSnapshot
Definition: snapshot.h:25
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2058
#define ACL_SELECT
Definition: parsenodes.h:73
TupleDesc tupdesc
Definition: spi.h:27
#define SPI_OK_SELECT
Definition: spi.h:54
int maintenance_work_mem
Definition: globals.c:114
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
#define SPI_OK_FINISH
Definition: spi.h:51
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:379
RTEKind rtekind
Definition: parsenodes.h:936
int NewGUCNestLevel(void)
Definition: guc.c:5065
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:569
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
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:5908
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2059
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
#define RelationGetRelid(relation)
Definition: rel.h:416
static bool ri_KeysEqual ( Relation  rel,
HeapTuple  oldtup,
HeapTuple  newtup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 3514 of file ri_triggers.c.

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

Referenced by RI_FKey_cascade_upd(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), RI_FKey_setdefault_upd(), RI_FKey_setnull_upd(), and ri_restrict_upd().

3516 {
3517  TupleDesc tupdesc = RelationGetDescr(rel);
3518  const int16 *attnums;
3519  const Oid *eq_oprs;
3520  int i;
3521 
3522  if (rel_is_pk)
3523  {
3524  attnums = riinfo->pk_attnums;
3525  eq_oprs = riinfo->pp_eq_oprs;
3526  }
3527  else
3528  {
3529  attnums = riinfo->fk_attnums;
3530  eq_oprs = riinfo->ff_eq_oprs;
3531  }
3532 
3533  for (i = 0; i < riinfo->nkeys; i++)
3534  {
3535  Datum oldvalue;
3536  Datum newvalue;
3537  bool isnull;
3538 
3539  /*
3540  * Get one attribute's oldvalue. If it is NULL - they're not equal.
3541  */
3542  oldvalue = heap_getattr(oldtup, attnums[i], tupdesc, &isnull);
3543  if (isnull)
3544  return false;
3545 
3546  /*
3547  * Get one attribute's newvalue. If it is NULL - they're not equal.
3548  */
3549  newvalue = heap_getattr(newtup, attnums[i], tupdesc, &isnull);
3550  if (isnull)
3551  return false;
3552 
3553  /*
3554  * Compare them with the appropriate equality operator.
3555  */
3556  if (!ri_AttributesEqual(eq_oprs[i], RIAttType(rel, attnums[i]),
3557  oldvalue, newvalue))
3558  return false;
3559  }
3560 
3561  return true;
3562 }
signed short int16
Definition: c.h:255
#define RelationGetDescr(relation)
Definition: rel.h:428
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
static bool ri_AttributesEqual(Oid eq_opr, Oid typeid, Datum oldvalue, Datum newvalue)
Definition: ri_triggers.c:3574
unsigned int Oid
Definition: postgres_ext.h:31
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:125
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:126
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
uintptr_t Datum
Definition: postgres.h:372
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
static const RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2794 of file ri_triggers.c.

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

Referenced by ri_FetchConstraintInfo().

2795 {
2796  RI_ConstraintInfo *riinfo;
2797  bool found;
2798  HeapTuple tup;
2799  Form_pg_constraint conForm;
2800  Datum adatum;
2801  bool isNull;
2802  ArrayType *arr;
2803  int numkeys;
2804 
2805  /*
2806  * On the first call initialize the hashtable
2807  */
2808  if (!ri_constraint_cache)
2810 
2811  /*
2812  * Find or create a hash entry. If we find a valid one, just return it.
2813  */
2815  (void *) &constraintOid,
2816  HASH_ENTER, &found);
2817  if (!found)
2818  riinfo->valid = false;
2819  else if (riinfo->valid)
2820  return riinfo;
2821 
2822  /*
2823  * Fetch the pg_constraint row so we can fill in the entry.
2824  */
2825  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2826  if (!HeapTupleIsValid(tup)) /* should not happen */
2827  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2828  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2829 
2830  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2831  elog(ERROR, "constraint %u is not a foreign key constraint",
2832  constraintOid);
2833 
2834  /* And extract data */
2835  Assert(riinfo->constraint_id == constraintOid);
2837  ObjectIdGetDatum(constraintOid));
2838  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2839  riinfo->pk_relid = conForm->confrelid;
2840  riinfo->fk_relid = conForm->conrelid;
2841  riinfo->confupdtype = conForm->confupdtype;
2842  riinfo->confdeltype = conForm->confdeltype;
2843  riinfo->confmatchtype = conForm->confmatchtype;
2844 
2845  /*
2846  * We expect the arrays to be 1-D arrays of the right types; verify that.
2847  * We don't need to use deconstruct_array() since the array data is just
2848  * going to look like a C array of values.
2849  */
2850  adatum = SysCacheGetAttr(CONSTROID, tup,
2851  Anum_pg_constraint_conkey, &isNull);
2852  if (isNull)
2853  elog(ERROR, "null conkey for constraint %u", constraintOid);
2854  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2855  if (ARR_NDIM(arr) != 1 ||
2856  ARR_HASNULL(arr) ||
2857  ARR_ELEMTYPE(arr) != INT2OID)
2858  elog(ERROR, "conkey is not a 1-D smallint array");
2859  numkeys = ARR_DIMS(arr)[0];
2860  if (numkeys <= 0 || numkeys > RI_MAX_NUMKEYS)
2861  elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
2862  riinfo->nkeys = numkeys;
2863  memcpy(riinfo->fk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2864  if ((Pointer) arr != DatumGetPointer(adatum))
2865  pfree(arr); /* free de-toasted copy, if any */
2866 
2867  adatum = SysCacheGetAttr(CONSTROID, tup,
2868  Anum_pg_constraint_confkey, &isNull);
2869  if (isNull)
2870  elog(ERROR, "null confkey for constraint %u", constraintOid);
2871  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2872  if (ARR_NDIM(arr) != 1 ||
2873  ARR_DIMS(arr)[0] != numkeys ||
2874  ARR_HASNULL(arr) ||
2875  ARR_ELEMTYPE(arr) != INT2OID)
2876  elog(ERROR, "confkey is not a 1-D smallint array");
2877  memcpy(riinfo->pk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2878  if ((Pointer) arr != DatumGetPointer(adatum))
2879  pfree(arr); /* free de-toasted copy, if any */
2880 
2881  adatum = SysCacheGetAttr(CONSTROID, tup,
2882  Anum_pg_constraint_conpfeqop, &isNull);
2883  if (isNull)
2884  elog(ERROR, "null conpfeqop for constraint %u", constraintOid);
2885  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2886  /* see TryReuseForeignKey if you change the test below */
2887  if (ARR_NDIM(arr) != 1 ||
2888  ARR_DIMS(arr)[0] != numkeys ||
2889  ARR_HASNULL(arr) ||
2890  ARR_ELEMTYPE(arr) != OIDOID)
2891  elog(ERROR, "conpfeqop is not a 1-D Oid array");
2892  memcpy(riinfo->pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2893  if ((Pointer) arr != DatumGetPointer(adatum))
2894  pfree(arr); /* free de-toasted copy, if any */
2895 
2896  adatum = SysCacheGetAttr(CONSTROID, tup,
2897  Anum_pg_constraint_conppeqop, &isNull);
2898  if (isNull)
2899  elog(ERROR, "null conppeqop for constraint %u", constraintOid);
2900  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2901  if (ARR_NDIM(arr) != 1 ||
2902  ARR_DIMS(arr)[0] != numkeys ||
2903  ARR_HASNULL(arr) ||
2904  ARR_ELEMTYPE(arr) != OIDOID)
2905  elog(ERROR, "conppeqop is not a 1-D Oid array");
2906  memcpy(riinfo->pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2907  if ((Pointer) arr != DatumGetPointer(adatum))
2908  pfree(arr); /* free de-toasted copy, if any */
2909 
2910  adatum = SysCacheGetAttr(CONSTROID, tup,
2911  Anum_pg_constraint_conffeqop, &isNull);
2912  if (isNull)
2913  elog(ERROR, "null conffeqop for constraint %u", constraintOid);
2914  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2915  if (ARR_NDIM(arr) != 1 ||
2916  ARR_DIMS(arr)[0] != numkeys ||
2917  ARR_HASNULL(arr) ||
2918  ARR_ELEMTYPE(arr) != OIDOID)
2919  elog(ERROR, "conffeqop is not a 1-D Oid array");
2920  memcpy(riinfo->ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2921  if ((Pointer) arr != DatumGetPointer(adatum))
2922  pfree(arr); /* free de-toasted copy, if any */
2923 
2924  ReleaseSysCache(tup);
2925 
2926  /*
2927  * For efficient processing of invalidation messages below, we keep a
2928  * doubly-linked list, and a count, of all currently valid entries.
2929  */
2932 
2933  riinfo->valid = true;
2934 
2935  return riinfo;
2936 }
signed short int16
Definition: c.h:255
#define CONSTRAINT_FOREIGN
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define Anum_pg_constraint_confkey
#define OIDOID
Definition: pg_type.h:328
#define Anum_pg_constraint_conppeqop
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:185
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:192
dlist_node valid_link
Definition: ri_triggers.c:127
#define Anum_pg_constraint_conffeqop
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
void pfree(void *pointer)
Definition: mcxt.c:950
char * Pointer
Definition: c.h:245
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:275
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
Definition: c.h:493
#define INT2OID
Definition: pg_type.h:308
#define ARR_DATA_PTR(a)
Definition: array.h:303
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:124
#define ARR_HASNULL(a)
Definition: array.h:272
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:125
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:126
#define Anum_pg_constraint_conkey
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:189
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Anum_pg_constraint_conpfeqop
#define Assert(condition)
Definition: c.h:675
#define ARR_NDIM(a)
Definition: array.h:271
#define DatumGetPointer(X)
Definition: postgres.h:555
static dlist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:188
static void ri_InitHashTables(void)
Definition: ri_triggers.c:3386
#define elog
Definition: elog.h:219
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
#define ARR_ELEMTYPE(a)
Definition: array.h:273
#define DatumGetArrayTypeP(X)
Definition: array.h:242
static int ri_NullCheck ( HeapTuple  tup,
const RI_ConstraintInfo riinfo,
bool  rel_is_pk 
)
static

Definition at line 3348 of file ri_triggers.c.

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

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_fk_upd_check_required(), RI_FKey_pk_upd_check_required(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), and ri_restrict_upd().

3350 {
3351  const int16 *attnums;
3352  int i;
3353  bool allnull = true;
3354  bool nonenull = true;
3355 
3356  if (rel_is_pk)
3357  attnums = riinfo->pk_attnums;
3358  else
3359  attnums = riinfo->fk_attnums;
3360 
3361  for (i = 0; i < riinfo->nkeys; i++)
3362  {
3363  if (heap_attisnull(tup, attnums[i]))
3364  nonenull = false;
3365  else
3366  allnull = false;
3367  }
3368 
3369  if (allnull)
3370  return RI_KEYS_ALL_NULL;
3371 
3372  if (nonenull)
3373  return RI_KEYS_NONE_NULL;
3374 
3375  return RI_KEYS_SOME_NULL;
3376 }
signed short int16
Definition: c.h:255
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:297
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:72
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:73
int i
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:74
static bool ri_PerformCheck ( const RI_ConstraintInfo riinfo,
RI_QueryKey qkey,
SPIPlanPtr  qplan,
Relation  fk_rel,
Relation  pk_rel,
HeapTuple  old_tuple,
HeapTuple  new_tuple,
bool  detectNewRows,
int  expect_OK 
)
static

Definition at line 3038 of file ri_triggers.c.

References CommandCounterIncrement(), RI_QueryKey::constr_queryno, elog, ERROR, GetLatestSnapshot(), GetTransactionSnapshot(), GetUserIdAndSecContext(), InvalidSnapshot, IsolationUsesXactSnapshot, RI_ConstraintInfo::nkeys, NULL, RelationGetForm, 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, and SPI_processed.

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), and ri_restrict_upd().

3043 {
3044  Relation query_rel,
3045  source_rel;
3046  bool source_is_pk;
3047  Snapshot test_snapshot;
3048  Snapshot crosscheck_snapshot;
3049  int limit;
3050  int spi_result;
3051  Oid save_userid;
3052  int save_sec_context;
3053  Datum vals[RI_MAX_NUMKEYS * 2];
3054  char nulls[RI_MAX_NUMKEYS * 2];
3055 
3056  /*
3057  * Use the query type code to determine whether the query is run against
3058  * the PK or FK table; we'll do the check as that table's owner
3059  */
3060  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
3061  query_rel = pk_rel;
3062  else
3063  query_rel = fk_rel;
3064 
3065  /*
3066  * The values for the query are taken from the table on which the trigger
3067  * is called - it is normally the other one with respect to query_rel. An
3068  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
3069  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
3070  * need some less klugy way to determine this.
3071  */
3073  {
3074  source_rel = fk_rel;
3075  source_is_pk = false;
3076  }
3077  else
3078  {
3079  source_rel = pk_rel;
3080  source_is_pk = true;
3081  }
3082 
3083  /* Extract the parameters to be passed into the query */
3084  if (new_tuple)
3085  {
3086  ri_ExtractValues(source_rel, new_tuple, riinfo, source_is_pk,
3087  vals, nulls);
3088  if (old_tuple)
3089  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
3090  vals + riinfo->nkeys, nulls + riinfo->nkeys);
3091  }
3092  else
3093  {
3094  ri_ExtractValues(source_rel, old_tuple, riinfo, source_is_pk,
3095  vals, nulls);
3096  }
3097 
3098  /*
3099  * In READ COMMITTED mode, we just need to use an up-to-date regular
3100  * snapshot, and we will see all rows that could be interesting. But in
3101  * transaction-snapshot mode, we can't change the transaction snapshot. If
3102  * the caller passes detectNewRows == false then it's okay to do the query
3103  * with the transaction snapshot; otherwise we use a current snapshot, and
3104  * tell the executor to error out if it finds any rows under the current
3105  * snapshot that wouldn't be visible per the transaction snapshot. Note
3106  * that SPI_execute_snapshot will register the snapshots, so we don't need
3107  * to bother here.
3108  */
3109  if (IsolationUsesXactSnapshot() && detectNewRows)
3110  {
3111  CommandCounterIncrement(); /* be sure all my own work is visible */
3112  test_snapshot = GetLatestSnapshot();
3113  crosscheck_snapshot = GetTransactionSnapshot();
3114  }
3115  else
3116  {
3117  /* the default SPI behavior is okay */
3118  test_snapshot = InvalidSnapshot;
3119  crosscheck_snapshot = InvalidSnapshot;
3120  }
3121 
3122  /*
3123  * If this is a select query (e.g., for a 'no action' or 'restrict'
3124  * trigger), we only need to see if there is a single row in the table,
3125  * matching the key. Otherwise, limit = 0 - because we want the query to
3126  * affect ALL the matching rows.
3127  */
3128  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
3129 
3130  /* Switch to proper UID to perform check as */
3131  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3132  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
3133  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
3135 
3136  /* Finally we can run the query. */
3137  spi_result = SPI_execute_snapshot(qplan,
3138  vals, nulls,
3139  test_snapshot, crosscheck_snapshot,
3140  false, false, limit);
3141 
3142  /* Restore UID and security context */
3143  SetUserIdAndSecContext(save_userid, save_sec_context);
3144 
3145  /* Check result */
3146  if (spi_result < 0)
3147  elog(ERROR, "SPI_execute_snapshot returned %d", spi_result);
3148 
3149  if (expect_OK >= 0 && spi_result != expect_OK)
3150  ri_ReportViolation(riinfo,
3151  pk_rel, fk_rel,
3152  new_tuple ? new_tuple : old_tuple,
3153  NULL,
3154  qkey->constr_queryno, true);
3155 
3156  /* XXX wouldn't it be clearer to do this part at the caller? */
3158  expect_OK == SPI_OK_SELECT &&
3160  ri_ReportViolation(riinfo,
3161  pk_rel, fk_rel,
3162  new_tuple ? new_tuple : old_tuple,
3163  NULL,
3164  qkey->constr_queryno, false);
3165 
3166  return SPI_processed != 0;
3167 }
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:410
int32 constr_queryno
Definition: ri_triggers.c:140
#define IsolationUsesXactSnapshot()
Definition: xact.h:43
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
uint64 SPI_processed
Definition: spi.c:39
#define ERROR
Definition: elog.h:43
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno, bool spi_err)
Definition: ri_triggers.c:3205
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
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:407
#define InvalidSnapshot
Definition: snapshot.h:25
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:922
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:296
#define SPI_OK_SELECT
Definition: spi.h:54
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:79
#define NULL
Definition: c.h:229
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:379
static void ri_ExtractValues(Relation rel, HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:3173
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:298
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:67
static SPIPlanPtr ri_PlanCheck ( const char *  querystr,
int  nargs,
Oid argtypes,
RI_QueryKey qkey,
Relation  fk_rel,
Relation  pk_rel,
bool  cache_plan 
)
static

Definition at line 2991 of file ri_triggers.c.

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

Referenced by ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), and ri_restrict_upd().

2994 {
2995  SPIPlanPtr qplan;
2996  Relation query_rel;
2997  Oid save_userid;
2998  int save_sec_context;
2999 
3000  /*
3001  * Use the query type code to determine whether the query is run against
3002  * the PK or FK table; we'll do the check as that table's owner
3003  */
3004  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
3005  query_rel = pk_rel;
3006  else
3007  query_rel = fk_rel;
3008 
3009  /* Switch to proper UID to perform check as */
3010  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3011  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
3012  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
3014 
3015  /* Create the plan */
3016  qplan = SPI_prepare(querystr, nargs, argtypes);
3017 
3018  if (qplan == NULL)
3019  elog(ERROR, "SPI_prepare returned %d for %s", SPI_result, querystr);
3020 
3021  /* Restore UID and security context */
3022  SetUserIdAndSecContext(save_userid, save_sec_context);
3023 
3024  /* Save the plan if requested */
3025  if (cache_plan)
3026  {
3027  SPI_keepplan(qplan);
3028  ri_HashPreparedPlan(qkey, qplan);
3029  }
3030 
3031  return qplan;
3032 }
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:80
#define RelationGetForm(relation)
Definition: rel.h:410
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:482
int32 constr_queryno
Definition: ri_triggers.c:140
unsigned int Oid
Definition: postgres_ext.h:31
int SPI_result
Definition: spi.c:42
#define ERROR
Definition: elog.h:43
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:3479
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:560
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:296
#define NULL
Definition: c.h:229
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:298
static void ri_ReportViolation ( const RI_ConstraintInfo riinfo,
Relation  pk_rel,
Relation  fk_rel,
HeapTuple  violator,
TupleDesc  tupdesc,
int  queryno,
bool  spi_err 
)
static

Definition at line 3205 of file ri_triggers.c.

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

Referenced by RI_Initial_Check(), and ri_PerformCheck().

3209 {
3210  StringInfoData key_names;
3211  StringInfoData key_values;
3212  bool onfk;
3213  const int16 *attnums;
3214  int idx;
3215  Oid rel_oid;
3216  AclResult aclresult;
3217  bool has_perm = true;
3218 
3219  if (spi_err)
3220  ereport(ERROR,
3221  (errcode(ERRCODE_INTERNAL_ERROR),
3222  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
3223  RelationGetRelationName(pk_rel),
3224  NameStr(riinfo->conname),
3225  RelationGetRelationName(fk_rel)),
3226  errhint("This is most likely due to a rule having rewritten the query.")));
3227 
3228  /*
3229  * Determine which relation to complain about. If tupdesc wasn't passed
3230  * by caller, assume the violator tuple came from there.
3231  */
3232  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
3233  if (onfk)
3234  {
3235  attnums = riinfo->fk_attnums;
3236  rel_oid = fk_rel->rd_id;
3237  if (tupdesc == NULL)
3238  tupdesc = fk_rel->rd_att;
3239  }
3240  else
3241  {
3242  attnums = riinfo->pk_attnums;
3243  rel_oid = pk_rel->rd_id;
3244  if (tupdesc == NULL)
3245  tupdesc = pk_rel->rd_att;
3246  }
3247 
3248  /*
3249  * Check permissions- if the user does not have access to view the data in
3250  * any of the key columns then we don't include the errdetail() below.
3251  *
3252  * Check if RLS is enabled on the relation first. If so, we don't return
3253  * any specifics to avoid leaking data.
3254  *
3255  * Check table-level permissions next and, failing that, column-level
3256  * privileges.
3257  */
3258 
3259  if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
3260  {
3261  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
3262  if (aclresult != ACLCHECK_OK)
3263  {
3264  /* Try for column-level permissions */
3265  for (idx = 0; idx < riinfo->nkeys; idx++)
3266  {
3267  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
3268  GetUserId(),
3269  ACL_SELECT);
3270 
3271  /* No access to the key */
3272  if (aclresult != ACLCHECK_OK)
3273  {
3274  has_perm = false;
3275  break;
3276  }
3277  }
3278  }
3279  }
3280  else
3281  has_perm = false;
3282 
3283  if (has_perm)
3284  {
3285  /* Get printable versions of the keys involved */
3286  initStringInfo(&key_names);
3287  initStringInfo(&key_values);
3288  for (idx = 0; idx < riinfo->nkeys; idx++)
3289  {
3290  int fnum = attnums[idx];
3291  char *name,
3292  *val;
3293 
3294  name = SPI_fname(tupdesc, fnum);
3295  val = SPI_getvalue(violator, tupdesc, fnum);
3296  if (!val)
3297  val = "null";
3298 
3299  if (idx > 0)
3300  {
3301  appendStringInfoString(&key_names, ", ");
3302  appendStringInfoString(&key_values, ", ");
3303  }
3304  appendStringInfoString(&key_names, name);
3305  appendStringInfoString(&key_values, val);
3306  }
3307  }
3308 
3309  if (onfk)
3310  ereport(ERROR,
3311  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3312  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
3313  RelationGetRelationName(fk_rel),
3314  NameStr(riinfo->conname)),
3315  has_perm ?
3316  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
3317  key_names.data, key_values.data,
3318  RelationGetRelationName(pk_rel)) :
3319  errdetail("Key is not present in table \"%s\".",
3320  RelationGetRelationName(pk_rel)),
3321  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3322  else
3323  ereport(ERROR,
3324  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3325  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
3326  RelationGetRelationName(pk_rel),
3327  NameStr(riinfo->conname),
3328  RelationGetRelationName(fk_rel)),
3329  has_perm ?
3330  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3331  key_names.data, key_values.data,
3332  RelationGetRelationName(fk_rel)) :
3333  errdetail("Key is still referenced from table \"%s\".",
3334  RelationGetRelationName(fk_rel)),
3335  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3336 }
signed short int16
Definition: c.h:255
int errhint(const char *fmt,...)
Definition: elog.c:987
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
Oid GetUserId(void)
Definition: miscinit.c:283
int errcode(int sqlerrcode)
Definition: elog.c:575
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:264
unsigned int Oid
Definition: postgres_ext.h:31
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:782
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:804
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5297
#define ERROR
Definition: elog.h:43
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:122
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:78
#define ereport(elevel, rest)
Definition: elog.h:122
Oid rd_id
Definition: rel.h:116
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
AclResult
Definition: acl.h:170
#define ACL_SELECT
Definition: parsenodes.h:73
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:123
long val
Definition: informix.c:689
static Datum ri_restrict_del ( TriggerData trigdata,
bool  is_no_action 
)
static

Definition at line 643 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, NULL, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_RESTRICT_DEL_CHECKREF, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

Referenced by RI_FKey_noaction_del(), and RI_FKey_restrict_del().

644 {
645  const RI_ConstraintInfo *riinfo;
646  Relation fk_rel;
647  Relation pk_rel;
648  HeapTuple old_row;
649  RI_QueryKey qkey;
650  SPIPlanPtr qplan;
651  int i;
652 
653  /*
654  * Get arguments.
655  */
656  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
657  trigdata->tg_relation, true);
658 
659  /*
660  * Get the relation descriptors of the FK and PK tables and the old tuple.
661  *
662  * fk_rel is opened in RowShareLock mode since that's what our eventual
663  * SELECT FOR KEY SHARE will get on it.
664  */
665  fk_rel = heap_open(riinfo->fk_relid, RowShareLock);
666  pk_rel = trigdata->tg_relation;
667  old_row = trigdata->tg_trigtuple;
668 
669  switch (riinfo->confmatchtype)
670  {
671  /* ----------
672  * SQL:2008 15.17 <Execution of referential actions>
673  * General rules 9) a) iv):
674  * MATCH SIMPLE/FULL
675  * ... ON DELETE RESTRICT
676  * ----------
677  */
679  case FKCONSTR_MATCH_FULL:
680  switch (ri_NullCheck(old_row, riinfo, true))
681  {
682  case RI_KEYS_ALL_NULL:
683  case RI_KEYS_SOME_NULL:
684 
685  /*
686  * No check needed - there cannot be any reference to old
687  * key if it contains a NULL
688  */
689  heap_close(fk_rel, RowShareLock);
690  return PointerGetDatum(NULL);
691 
692  case RI_KEYS_NONE_NULL:
693 
694  /*
695  * Have a full qualified key - continue below
696  */
697  break;
698  }
699 
700  /*
701  * If another PK row now exists providing the old key values, we
702  * should not do anything. However, this check should only be
703  * made in the NO ACTION case; in RESTRICT cases we don't wish to
704  * allow another row to be substituted.
705  */