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

2957 {
2958  dlist_mutable_iter iter;
2959 
2961 
2962  /*
2963  * If the list of currently valid entries gets excessively large, we mark
2964  * them all invalid so we can empty the list. This arrangement avoids
2965  * O(N^2) behavior in situations where a session touches many foreign keys
2966  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2967  */
2969  hashvalue = 0; /* pretend it's a cache reset */
2970 
2972  {
2974  valid_link, iter.cur);
2975 
2976  if (hashvalue == 0 || riinfo->oidHashValue == hashvalue)
2977  {
2978  riinfo->valid = false;
2979  /* Remove invalidated entries from the list, too */
2980  dlist_delete(iter.cur);
2982  }
2983  }
2984 }
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:188
#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:192
#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:191
static void quoteOneName ( char *  buffer,
const char *  name 
)
static

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

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

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

2553 {
2555  buffer += strlen(buffer);
2556  *buffer++ = '.';
2558 }
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2532
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define RelationGetRelationName(relation)
Definition: rel.h:437
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define RelationGetNamespace(relation)
Definition: rel.h:444
static void ri_add_cast_to ( StringInfo  buf,
Oid  typid 
)
static

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

2614 {
2615  HeapTuple typetup;
2616  Form_pg_type typform;
2617  char *typname;
2618  char *nspname;
2619 
2620  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2621  if (!HeapTupleIsValid(typetup))
2622  elog(ERROR, "cache lookup failed for type %u", typid);
2623  typform = (Form_pg_type) GETSTRUCT(typetup);
2624 
2625  typname = NameStr(typform->typname);
2626  nspname = get_namespace_name(typform->typnamespace);
2627 
2628  appendStringInfo(buf, "::%s.%s",
2629  quote_identifier(nspname), quote_identifier(typname));
2630 
2631  ReleaseSysCache(typetup);
2632 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10195
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#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 3577 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().

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

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

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

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

516 {
517  SPIPlanPtr qplan;
518  RI_QueryKey qkey;
519  int i;
520  bool result;
521 
522  /* Only called for non-null rows */
523  Assert(ri_NullCheck(old_row, riinfo, true) == RI_KEYS_NONE_NULL);
524 
525  if (SPI_connect() != SPI_OK_CONNECT)
526  elog(ERROR, "SPI_connect failed");
527 
528  /*
529  * Fetch or prepare a saved plan for checking PK table with values coming
530  * from a PK row
531  */
533 
534  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
535  {
536  StringInfoData querybuf;
537  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
538  char attname[MAX_QUOTED_NAME_LEN];
539  char paramname[16];
540  const char *querysep;
541  Oid queryoids[RI_MAX_NUMKEYS];
542 
543  /* ----------
544  * The query string built is
545  * SELECT 1 FROM ONLY <pktable> x WHERE pkatt1 = $1 [AND ...]
546  * FOR KEY SHARE OF x
547  * The type id's for the $ parameters are those of the
548  * PK attributes themselves.
549  * ----------
550  */
551  initStringInfo(&querybuf);
552  quoteRelationName(pkrelname, pk_rel);
553  appendStringInfo(&querybuf, "SELECT 1 FROM ONLY %s x", pkrelname);
554  querysep = "WHERE";
555  for (i = 0; i < riinfo->nkeys; i++)
556  {
557  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
558 
559  quoteOneName(attname,
560  RIAttName(pk_rel, riinfo->pk_attnums[i]));
561  sprintf(paramname, "$%d", i + 1);
562  ri_GenerateQual(&querybuf, querysep,
563  attname, pk_type,
564  riinfo->pp_eq_oprs[i],
565  paramname, pk_type);
566  querysep = "AND";
567  queryoids[i] = pk_type;
568  }
569  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
570 
571  /* Prepare and save the plan */
572  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
573  &qkey, fk_rel, pk_rel, true);
574  }
575 
576  /*
577  * We have a plan now. Run it.
578  */
579  result = ri_PerformCheck(riinfo, &qkey, qplan,
580  fk_rel, pk_rel,
581  old_row, NULL,
582  true, /* treat like update */
583  SPI_OK_SELECT);
584 
585  if (SPI_finish() != SPI_OK_FINISH)
586  elog(ERROR, "SPI_finish failed");
587 
588  return result;
589 }
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:2572
#define SPI_OK_CONNECT
Definition: spi.h:47
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2552
static int ri_NullCheck(HeapTuple tup, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:3351
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:147
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:95
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:94
return result
Definition: formatting.c:1618
unsigned int Oid
Definition: postgres_ext.h:31
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2532
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#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:189
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:3041
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:3429
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:126
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
#define SPI_OK_SELECT
Definition: spi.h:51
#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:2994
#define SPI_OK_FINISH
Definition: spi.h:48
int i
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2693
#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 2708 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().

2709 {
2710  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2711 
2712  if (!CALLED_AS_TRIGGER(fcinfo))
2713  ereport(ERROR,
2714  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2715  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2716 
2717  /*
2718  * Check proper event
2719  */
2720  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2721  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2722  ereport(ERROR,
2723  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2724  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2725 
2726  switch (tgkind)
2727  {
2728  case RI_TRIGTYPE_INSERT:
2729  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2730  ereport(ERROR,
2731  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2732  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2733  break;
2734  case RI_TRIGTYPE_UPDATE:
2735  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2736  ereport(ERROR,
2737  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2738  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2739  break;
2740  case RI_TRIGTYPE_DELETE:
2741  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2742  ereport(ERROR,
2743  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2744  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2745  break;
2746  }
2747 }
fmNodePtr context
Definition: fmgr.h:72
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 3176 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().

3179 {
3180  TupleDesc tupdesc = rel->rd_att;
3181  const int16 *attnums;
3182  int i;
3183  bool isnull;
3184 
3185  if (rel_is_pk)
3186  attnums = riinfo->pk_attnums;
3187  else
3188  attnums = riinfo->fk_attnums;
3189 
3190  for (i = 0; i < riinfo->nkeys; i++)
3191  {
3192  vals[i] = heap_getattr(tup, attnums[i], tupdesc,
3193  &isnull);
3194  nulls[i] = isnull ? 'n' : ' ';
3195  }
3196 }
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 2754 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().

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

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

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

Definition at line 1034 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.

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

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

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

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

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

Referenced by validateForeignKeyConstraint().

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

Definition at line 487 of file ri_triggers.c.

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

488 {
489  /*
490  * Check that this is a valid trigger call on the right time and event.
491  */
492  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
493 
494  /*
495  * Share code with INSERT case.
496  */
497  return RI_FKey_check((TriggerData *) fcinfo->context);
498 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:258
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2708
#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 2144 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().

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

Definition at line 601 of file ri_triggers.c.

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

Referenced by RI_FKey_setdefault_del().

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

Definition at line 813 of file ri_triggers.c.

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

Referenced by RI_FKey_setdefault_upd().

814 {
815  /*
816  * Check that this is a valid trigger call on the right time and event.
817  */
818  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
819 
820  /*
821  * Share code with RESTRICT case.
822  */
823  return ri_restrict_upd((TriggerData *) fcinfo->context, true);
824 }
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2708
static Datum ri_restrict_upd(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:858
#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 2087 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().

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

Definition at line 626 of file ri_triggers.c.

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

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

Definition at line 838 of file ri_triggers.c.

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

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

Definition at line 1712 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.

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

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

Definition at line 1371 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.

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

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

Definition at line 3704 of file ri_triggers.c.

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and CreateTrigger().

3705 {
3706  switch (tgfoid)
3707  {
3708  case F_RI_FKEY_CASCADE_DEL:
3709  case F_RI_FKEY_CASCADE_UPD:
3710  case F_RI_FKEY_RESTRICT_DEL:
3711  case F_RI_FKEY_RESTRICT_UPD:
3712  case F_RI_FKEY_SETNULL_DEL:
3713  case F_RI_FKEY_SETNULL_UPD:
3714  case F_RI_FKEY_SETDEFAULT_DEL:
3715  case F_RI_FKEY_SETDEFAULT_UPD:
3716  case F_RI_FKEY_NOACTION_DEL:
3717  case F_RI_FKEY_NOACTION_UPD:
3718  return RI_TRIGGER_PK;
3719 
3720  case F_RI_FKEY_CHECK_INS:
3721  case F_RI_FKEY_CHECK_UPD:
3722  return RI_TRIGGER_FK;
3723  }
3724 
3725  return RI_TRIGGER_NONE;
3726 }
#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 2572 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().

2577 {
2578  HeapTuple opertup;
2579  Form_pg_operator operform;
2580  char *oprname;
2581  char *nspname;
2582 
2583  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
2584  if (!HeapTupleIsValid(opertup))
2585  elog(ERROR, "cache lookup failed for operator %u", opoid);
2586  operform = (Form_pg_operator) GETSTRUCT(opertup);
2587  Assert(operform->oprkind == 'b');
2588  oprname = NameStr(operform->oprname);
2589 
2590  nspname = get_namespace_name(operform->oprnamespace);
2591 
2592  appendStringInfo(buf, " %s %s", sep, leftop);
2593  if (leftoptype != operform->oprleft)
2594  ri_add_cast_to(buf, operform->oprleft);
2595  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
2596  appendStringInfoString(buf, oprname);
2597  appendStringInfo(buf, ") %s", rightop);
2598  if (rightoptype != operform->oprright)
2599  ri_add_cast_to(buf, operform->oprright);
2600 
2601  ReleaseSysCache(opertup);
2602 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10195
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#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:2613
#define elog
Definition: elog.h:219
static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

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

2653 {
2654  HeapTuple tp;
2655  Form_pg_collation colltup;
2656  char *collname;
2657  char onename[MAX_QUOTED_NAME_LEN];
2658 
2659  /* Nothing to do if it's a noncollatable data type */
2660  if (!OidIsValid(collation))
2661  return;
2662 
2663  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2664  if (!HeapTupleIsValid(tp))
2665  elog(ERROR, "cache lookup failed for collation %u", collation);
2666  colltup = (Form_pg_collation) GETSTRUCT(tp);
2667  collname = NameStr(colltup->collname);
2668 
2669  /*
2670  * We qualify the name always, for simplicity and to ensure the query is
2671  * not search-path-dependent.
2672  */
2673  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2674  appendStringInfo(buf, " COLLATE %s", onename);
2675  quoteOneName(onename, collname);
2676  appendStringInfo(buf, ".%s", onename);
2677 
2678  ReleaseSysCache(tp);
2679 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2532
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#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:3006
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#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 3611 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().

3612 {
3613  RI_CompareKey key;
3614  RI_CompareHashEntry *entry;
3615  bool found;
3616 
3617  /*
3618  * On the first call initialize the hashtable
3619  */
3620  if (!ri_compare_cache)
3622 
3623  /*
3624  * Find or create a hash entry. Note we're assuming RI_CompareKey
3625  * contains no struct padding.
3626  */
3627  key.eq_opr = eq_opr;
3628  key.typeid = typeid;
3630  (void *) &key,
3631  HASH_ENTER, &found);
3632  if (!found)
3633  entry->valid = false;
3634 
3635  /*
3636  * If not already initialized, do so. Since we'll keep this hash entry
3637  * for the life of the backend, put any subsidiary info for the function
3638  * cache structs into TopMemoryContext.
3639  */
3640  if (!entry->valid)
3641  {
3642  Oid lefttype,
3643  righttype,
3644  castfunc;
3645  CoercionPathType pathtype;
3646 
3647  /* We always need to know how to call the equality operator */
3648  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3650 
3651  /*
3652  * If we chose to use a cast from FK to PK type, we may have to apply
3653  * the cast function to get to the operator's input type.
3654  *
3655  * XXX eventually it would be good to support array-coercion cases
3656  * here and in ri_AttributesEqual(). At the moment there is no point
3657  * because cases involving nonidentical array types will be rejected
3658  * at constraint creation time.
3659  *
3660  * XXX perhaps also consider supporting CoerceViaIO? No need at the
3661  * moment since that will never be generated for implicit coercions.
3662  */
3663  op_input_types(eq_opr, &lefttype, &righttype);
3664  Assert(lefttype == righttype);
3665  if (typeid == lefttype)
3666  castfunc = InvalidOid; /* simplest case */
3667  else
3668  {
3669  pathtype = find_coercion_pathway(lefttype, typeid,
3671  &castfunc);
3672  if (pathtype != COERCION_PATH_FUNC &&
3673  pathtype != COERCION_PATH_RELABELTYPE)
3674  {
3675  /*
3676  * The declared input type of the eq_opr might be a
3677  * polymorphic type such as ANYARRAY or ANYENUM, or other
3678  * special cases such as RECORD; find_coercion_pathway
3679  * currently doesn't subsume these special cases.
3680  */
3681  if (!IsBinaryCoercible(typeid, lefttype))
3682  elog(ERROR, "no conversion function from %s to %s",
3683  format_type_be(typeid),
3684  format_type_be(lefttype));
3685  }
3686  }
3687  if (OidIsValid(castfunc))
3688  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3690  else
3692  entry->valid = true;
3693  }
3694 
3695  return entry;
3696 }
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:1135
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:169
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:1062
Oid fn_oid
Definition: fmgr.h:56
#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:3389
#define elog
Definition: elog.h:219
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:180
static HTAB * ri_compare_cache
Definition: ri_triggers.c:190
static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 3482 of file ri_triggers.c.

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

Referenced by ri_PlanCheck().

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

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

3390 {
3391  HASHCTL ctl;
3392 
3393  memset(&ctl, 0, sizeof(ctl));
3394  ctl.keysize = sizeof(Oid);
3395  ctl.entrysize = sizeof(RI_ConstraintInfo);
3396  ri_constraint_cache = hash_create("RI constraint cache",
3398  &ctl, HASH_ELEM | HASH_BLOBS);
3399 
3400  /* Arrange to flush cache on pg_constraint changes */
3403  (Datum) 0);
3404 
3405  memset(&ctl, 0, sizeof(ctl));
3406  ctl.keysize = sizeof(RI_QueryKey);
3407  ctl.entrysize = sizeof(RI_QueryHashEntry);
3408  ri_query_cache = hash_create("RI query cache",
3410  &ctl, HASH_ELEM | HASH_BLOBS);
3411 
3412  memset(&ctl, 0, sizeof(ctl));
3413  ctl.keysize = sizeof(RI_CompareKey);
3414  ctl.entrysize = sizeof(RI_CompareHashEntry);
3415  ri_compare_cache = hash_create("RI compare cache",
3417  &ctl, HASH_ELEM | HASH_BLOBS);
3418 }
static HTAB * ri_query_cache
Definition: ri_triggers.c:189
struct RI_CompareKey RI_CompareKey
#define HASH_ELEM
Definition: hsearch.h:87
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:188
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:2956
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:1381
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:190
struct RI_QueryHashEntry RI_QueryHashEntry
bool RI_Initial_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

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

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

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

3519 {
3520  TupleDesc tupdesc = RelationGetDescr(rel);
3521  const int16 *attnums;
3522  const Oid *eq_oprs;
3523  int i;
3524 
3525  if (rel_is_pk)
3526  {
3527  attnums = riinfo->pk_attnums;
3528  eq_oprs = riinfo->pp_eq_oprs;
3529  }
3530  else
3531  {
3532  attnums = riinfo->fk_attnums;
3533  eq_oprs = riinfo->ff_eq_oprs;
3534  }
3535 
3536  for (i = 0; i < riinfo->nkeys; i++)
3537  {
3538  Datum oldvalue;
3539  Datum newvalue;
3540  bool isnull;
3541 
3542  /*
3543  * Get one attribute's oldvalue. If it is NULL - they're not equal.
3544  */
3545  oldvalue = heap_getattr(oldtup, attnums[i], tupdesc, &isnull);
3546  if (isnull)
3547  return false;
3548 
3549  /*
3550  * Get one attribute's newvalue. If it is NULL - they're not equal.
3551  */
3552  newvalue = heap_getattr(newtup, attnums[i], tupdesc, &isnull);
3553  if (isnull)
3554  return false;
3555 
3556  /*
3557  * Compare them with the appropriate equality operator.
3558  */
3559  if (!ri_AttributesEqual(eq_oprs[i], RIAttType(rel, attnums[i]),
3560  oldvalue, newvalue))
3561  return false;
3562  }
3563 
3564  return true;
3565 }
signed short int16
Definition: c.h:255
#define RelationGetDescr(relation)
Definition: rel.h:429
#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:3577
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:126
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:128
#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 2797 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().

2798 {
2799  RI_ConstraintInfo *riinfo;
2800  bool found;
2801  HeapTuple tup;
2802  Form_pg_constraint conForm;
2803  Datum adatum;
2804  bool isNull;
2805  ArrayType *arr;
2806  int numkeys;
2807 
2808  /*
2809  * On the first call initialize the hashtable
2810  */
2811  if (!ri_constraint_cache)
2813 
2814  /*
2815  * Find or create a hash entry. If we find a valid one, just return it.
2816  */
2818  (void *) &constraintOid,
2819  HASH_ENTER, &found);
2820  if (!found)
2821  riinfo->valid = false;
2822  else if (riinfo->valid)
2823  return riinfo;
2824 
2825  /*
2826  * Fetch the pg_constraint row so we can fill in the entry.
2827  */
2828  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2829  if (!HeapTupleIsValid(tup)) /* should not happen */
2830  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2831  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2832 
2833  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2834  elog(ERROR, "constraint %u is not a foreign key constraint",
2835  constraintOid);
2836 
2837  /* And extract data */
2838  Assert(riinfo->constraint_id == constraintOid);
2840  ObjectIdGetDatum(constraintOid));
2841  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2842  riinfo->pk_relid = conForm->confrelid;
2843  riinfo->fk_relid = conForm->conrelid;
2844  riinfo->confupdtype = conForm->confupdtype;
2845  riinfo->confdeltype = conForm->confdeltype;
2846  riinfo->confmatchtype = conForm->confmatchtype;
2847 
2848  /*
2849  * We expect the arrays to be 1-D arrays of the right types; verify that.
2850  * We don't need to use deconstruct_array() since the array data is just
2851  * going to look like a C array of values.
2852  */
2853  adatum = SysCacheGetAttr(CONSTROID, tup,
2854  Anum_pg_constraint_conkey, &isNull);
2855  if (isNull)
2856  elog(ERROR, "null conkey for constraint %u", constraintOid);
2857  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2858  if (ARR_NDIM(arr) != 1 ||
2859  ARR_HASNULL(arr) ||
2860  ARR_ELEMTYPE(arr) != INT2OID)
2861  elog(ERROR, "conkey is not a 1-D smallint array");
2862  numkeys = ARR_DIMS(arr)[0];
2863  if (numkeys <= 0 || numkeys > RI_MAX_NUMKEYS)
2864  elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
2865  riinfo->nkeys = numkeys;
2866  memcpy(riinfo->fk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2867  if ((Pointer) arr != DatumGetPointer(adatum))
2868  pfree(arr); /* free de-toasted copy, if any */
2869 
2870  adatum = SysCacheGetAttr(CONSTROID, tup,
2871  Anum_pg_constraint_confkey, &isNull);
2872  if (isNull)
2873  elog(ERROR, "null confkey for constraint %u", constraintOid);
2874  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2875  if (ARR_NDIM(arr) != 1 ||
2876  ARR_DIMS(arr)[0] != numkeys ||
2877  ARR_HASNULL(arr) ||
2878  ARR_ELEMTYPE(arr) != INT2OID)
2879  elog(ERROR, "confkey is not a 1-D smallint array");
2880  memcpy(riinfo->pk_attnums, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
2881  if ((Pointer) arr != DatumGetPointer(adatum))
2882  pfree(arr); /* free de-toasted copy, if any */
2883 
2884  adatum = SysCacheGetAttr(CONSTROID, tup,
2885  Anum_pg_constraint_conpfeqop, &isNull);
2886  if (isNull)
2887  elog(ERROR, "null conpfeqop for constraint %u", constraintOid);
2888  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2889  /* see TryReuseForeignKey if you change the test below */
2890  if (ARR_NDIM(arr) != 1 ||
2891  ARR_DIMS(arr)[0] != numkeys ||
2892  ARR_HASNULL(arr) ||
2893  ARR_ELEMTYPE(arr) != OIDOID)
2894  elog(ERROR, "conpfeqop is not a 1-D Oid array");
2895  memcpy(riinfo->pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2896  if ((Pointer) arr != DatumGetPointer(adatum))
2897  pfree(arr); /* free de-toasted copy, if any */
2898 
2899  adatum = SysCacheGetAttr(CONSTROID, tup,
2900  Anum_pg_constraint_conppeqop, &isNull);
2901  if (isNull)
2902  elog(ERROR, "null conppeqop for constraint %u", constraintOid);
2903  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2904  if (ARR_NDIM(arr) != 1 ||
2905  ARR_DIMS(arr)[0] != numkeys ||
2906  ARR_HASNULL(arr) ||
2907  ARR_ELEMTYPE(arr) != OIDOID)
2908  elog(ERROR, "conppeqop is not a 1-D Oid array");
2909  memcpy(riinfo->pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2910  if ((Pointer) arr != DatumGetPointer(adatum))
2911  pfree(arr); /* free de-toasted copy, if any */
2912 
2913  adatum = SysCacheGetAttr(CONSTROID, tup,
2914  Anum_pg_constraint_conffeqop, &isNull);
2915  if (isNull)
2916  elog(ERROR, "null conffeqop for constraint %u", constraintOid);
2917  arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
2918  if (ARR_NDIM(arr) != 1 ||
2919  ARR_DIMS(arr)[0] != numkeys ||
2920  ARR_HASNULL(arr) ||
2921  ARR_ELEMTYPE(arr) != OIDOID)
2922  elog(ERROR, "conffeqop is not a 1-D Oid array");
2923  memcpy(riinfo->ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
2924  if ((Pointer) arr != DatumGetPointer(adatum))
2925  pfree(arr); /* free de-toasted copy, if any */
2926 
2927  ReleaseSysCache(tup);
2928 
2929  /*
2930  * For efficient processing of invalidation messages below, we keep a
2931  * doubly-linked list, and a count, of all currently valid entries.
2932  */
2935 
2936  riinfo->valid = true;
2937 
2938  return riinfo;
2939 }
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:188
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:188
dlist_node valid_link
Definition: ri_triggers.c:130
#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:152
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:126
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:128
#define Anum_pg_constraint_conkey
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1278
static int ri_constraint_cache_valid_count
Definition: ri_triggers.c:192
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:191
static void ri_InitHashTables(void)
Definition: ri_triggers.c:3389
#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 3351 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().

3353 {
3354  const int16 *attnums;
3355  int i;
3356  bool allnull = true;
3357  bool nonenull = true;
3358 
3359  if (rel_is_pk)
3360  attnums = riinfo->pk_attnums;
3361  else
3362  attnums = riinfo->fk_attnums;
3363 
3364  for (i = 0; i < riinfo->nkeys; i++)
3365  {
3366  if (heap_attisnull(tup, attnums[i]))
3367  nonenull = false;
3368  else
3369  allnull = false;
3370  }
3371 
3372  if (allnull)
3373  return RI_KEYS_ALL_NULL;
3374 
3375  if (nonenull)
3376  return RI_KEYS_NONE_NULL;
3377 
3378  return RI_KEYS_SOME_NULL;
3379 }
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 3041 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().

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

2997 {
2998  SPIPlanPtr qplan;
2999  Relation query_rel;
3000  Oid save_userid;
3001  int save_sec_context;
3002 
3003  /*
3004  * Use the query type code to determine whether the query is run against
3005  * the PK or FK table; we'll do the check as that table's owner
3006  */
3007  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
3008  query_rel = pk_rel;
3009  else
3010  query_rel = fk_rel;
3011 
3012  /* Switch to proper UID to perform check as */
3013  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3014  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
3015  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
3017 
3018  /* Create the plan */
3019  qplan = SPI_prepare(querystr, nargs, argtypes);
3020 
3021  if (qplan == NULL)
3022  elog(ERROR, "SPI_prepare returned %d for %s", SPI_result, querystr);
3023 
3024  /* Restore UID and security context */
3025  SetUserIdAndSecContext(save_userid, save_sec_context);
3026 
3027  /* Save the plan if requested */
3028  if (cache_plan)
3029  {
3030  SPI_keepplan(qplan);
3031  ri_HashPreparedPlan(qkey, qplan);
3032  }
3033 
3034  return qplan;
3035 }
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:411
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:481
int32 constr_queryno
Definition: ri_triggers.c:143
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:3482
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:559
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:388
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:291
#define NULL
Definition: c.h:229
#define elog
Definition: elog.h:219
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:293
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 3208 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().

3212 {
3213  StringInfoData key_names;
3214  StringInfoData key_values;
3215  bool onfk;
3216  const int16 *attnums;
3217  int idx;
3218  Oid rel_oid;
3219  AclResult aclresult;
3220  bool has_perm = true;
3221 
3222  if (spi_err)
3223  ereport(ERROR,
3224  (errcode(ERRCODE_INTERNAL_ERROR),
3225  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
3226  RelationGetRelationName(pk_rel),
3227  NameStr(riinfo->conname),
3228  RelationGetRelationName(fk_rel)),
3229  errhint("This is most likely due to a rule having rewritten the query.")));
3230 
3231  /*
3232  * Determine which relation to complain about. If tupdesc wasn't passed
3233  * by caller, assume the violator tuple came from there.
3234  */
3235  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
3236  if (onfk)
3237  {
3238  attnums = riinfo->fk_attnums;
3239  rel_oid = fk_rel->rd_id;
3240  if (tupdesc == NULL)
3241  tupdesc = fk_rel->rd_att;
3242  }
3243  else
3244  {
3245  attnums = riinfo->pk_attnums;
3246  rel_oid = pk_rel->rd_id;
3247  if (tupdesc == NULL)
3248  tupdesc = pk_rel->rd_att;
3249  }
3250 
3251  /*
3252  * Check permissions- if the user does not have access to view the data in
3253  * any of the key columns then we don't include the errdetail() below.
3254  *
3255  * Check if RLS is enabled on the relation first. If so, we don't return
3256  * any specifics to avoid leaking data.
3257  *
3258  * Check table-level permissions next and, failing that, column-level
3259  * privileges.
3260  */
3261 
3262  if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
3263  {
3264  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
3265  if (aclresult != ACLCHECK_OK)
3266  {
3267  /* Try for column-level permissions */
3268  for (idx = 0; idx < riinfo->nkeys; idx++)
3269  {
3270  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
3271  GetUserId(),
3272  ACL_SELECT);
3273 
3274  /* No access to the key */
3275  if (aclresult != ACLCHECK_OK)
3276  {
3277  has_perm = false;
3278  break;
3279  }
3280  }
3281  }
3282  }
3283  else
3284  has_perm = false;
3285 
3286  if (has_perm)
3287  {
3288  /* Get printable versions of the keys involved */
3289  initStringInfo(&key_names);
3290  initStringInfo(&key_values);
3291  for (idx = 0; idx < riinfo->nkeys; idx++)
3292  {
3293  int fnum = attnums[idx];
3294  char *name,
3295  *val;
3296 
3297  name = SPI_fname(tupdesc, fnum);
3298  val = SPI_getvalue(violator, tupdesc, fnum);
3299  if (!val)
3300  val = "null";
3301 
3302  if (idx > 0)
3303  {
3304  appendStringInfoString(&key_names, ", ");
3305  appendStringInfoString(&key_values, ", ");
3306  }
3307  appendStringInfoString(&key_names, name);
3308  appendStringInfoString(&key_values, val);
3309  }
3310  }
3311 
3312  if (onfk)
3313  ereport(ERROR,
3314  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3315  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
3316  RelationGetRelationName(fk_rel),
3317  NameStr(riinfo->conname)),
3318  has_perm ?
3319  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
3320  key_names.data, key_values.data,
3321  RelationGetRelationName(pk_rel)) :
3322  errdetail("Key is not present in table \"%s\".",
3323  RelationGetRelationName(pk_rel)),
3324  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3325  else
3326  ereport(ERROR,
3327  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3328  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
3329  RelationGetRelationName(pk_rel),
3330  NameStr(riinfo->conname),
3331  RelationGetRelationName(fk_rel)),
3332  has_perm ?
3333  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3334  key_names.data, key_values.data,
3335  RelationGetRelationName(fk_rel)) :
3336  errdetail("Key is still referenced from table \"%s\".",
3337  RelationGetRelationName(fk_rel)),
3338  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3339 }
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:4291
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:781
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:803
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5286
#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:189
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#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:65
AclResult
Definition: acl.h:170
#define ACL_SELECT
Definition: parsenodes.h:66
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:4405
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 646 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().

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