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

Go to the source code of this file.

Data Structures

struct  RI_ConstraintInfo
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 

Macros

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS
 
#define RI_INIT_CONSTRAINTHASHSIZE   64
 
#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)
 
#define RI_KEYS_ALL_NULL   0
 
#define RI_KEYS_SOME_NULL   1
 
#define RI_KEYS_NONE_NULL   2
 
#define RI_PLAN_CHECK_LOOKUPPK   1
 
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2
 
#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK
 
#define RI_PLAN_CASCADE_ONDELETE   3
 
#define RI_PLAN_CASCADE_ONUPDATE   4
 
#define RI_PLAN_RESTRICT   5
 
#define RI_PLAN_SETNULL_ONDELETE   6
 
#define RI_PLAN_SETNULL_ONUPDATE   7
 
#define RI_PLAN_SETDEFAULT_ONDELETE   8
 
#define RI_PLAN_SETDEFAULT_ONUPDATE   9
 
#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)
 
#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)
 
#define RIAttName(rel, attnum)   NameStr(*attnumAttName(rel, attnum))
 
#define RIAttType(rel, attnum)   attnumTypeId(rel, attnum)
 
#define RIAttCollation(rel, attnum)   attnumCollationId(rel, attnum)
 
#define RI_TRIGTYPE_INSERT   1
 
#define RI_TRIGTYPE_UPDATE   2
 
#define RI_TRIGTYPE_DELETE   3
 

Typedefs

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

Functions

static bool ri_Check_Pk_Match (Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
 
static Datum ri_restrict (TriggerData *trigdata, bool is_no_action)
 
static Datum ri_set (TriggerData *trigdata, bool is_set_null, int tgkind)
 
static void quoteOneName (char *buffer, const char *name)
 
static void quoteRelationName (char *buffer, Relation rel)
 
static void ri_GenerateQual (StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
static void ri_GenerateQualCollation (StringInfo buf, Oid collation)
 
static int ri_NullCheck (TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static void ri_BuildQueryKey (RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
 
static bool ri_KeysEqual (Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
 
static bool ri_CompareWithCast (Oid eq_opr, Oid typeid, Datum lhs, Datum rhs)
 
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 Oid get_ri_constraint_root (Oid constrOid)
 
static SPIPlanPtr ri_PlanCheck (const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
 
static bool ri_PerformCheck (const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
 
static void ri_ExtractValues (Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
 
static void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
 
static Datum RI_FKey_check (TriggerData *trigdata)
 
Datum RI_FKey_check_ins (PG_FUNCTION_ARGS)
 
Datum RI_FKey_check_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_noaction_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_restrict_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_cascade_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setnull_upd (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_del (PG_FUNCTION_ARGS)
 
Datum RI_FKey_setdefault_upd (PG_FUNCTION_ARGS)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
void RI_PartitionRemove_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

static HTABri_constraint_cache = NULL
 
static HTABri_query_cache = NULL
 
static HTABri_compare_cache = NULL
 
static dclist_head ri_constraint_cache_valid_list
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

Definition at line 84 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 85 of file ri_triggers.c.

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 62 of file ri_triggers.c.

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 63 of file ri_triggers.c.

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 65 of file ri_triggers.c.

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

Definition at line 67 of file ri_triggers.c.

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 66 of file ri_triggers.c.

◆ RI_MAX_NUMKEYS

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS

Definition at line 60 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONDELETE

#define RI_PLAN_CASCADE_ONDELETE   3

Definition at line 75 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONUPDATE

#define RI_PLAN_CASCADE_ONUPDATE   4

Definition at line 76 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 71 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 72 of file ri_triggers.c.

◆ RI_PLAN_LAST_ON_PK

#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK

Definition at line 73 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   5

Definition at line 78 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   8

Definition at line 81 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   9

Definition at line 82 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   6

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   7

Definition at line 80 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 93 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 91 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 92 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 89 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 87 of file ri_triggers.c.

◆ RIAttType

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

Definition at line 88 of file ri_triggers.c.

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

typedef struct RI_CompareKey RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

typedef struct RI_QueryKey RI_QueryKey

Function Documentation

◆ get_ri_constraint_root()

static Oid get_ri_constraint_root ( Oid  constrOid)
static

Definition at line 2286 of file ri_triggers.c.

2287 {
2288  for (;;)
2289  {
2290  HeapTuple tuple;
2291  Oid constrParentOid;
2292 
2293  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2294  if (!HeapTupleIsValid(tuple))
2295  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2296  constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2297  ReleaseSysCache(tuple);
2298  if (!OidIsValid(constrParentOid))
2299  break; /* we reached the root constraint */
2300  constrOid = constrParentOid;
2301  }
2302  return constrOid;
2303 }
#define OidIsValid(objectId)
Definition: c.h:766
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

References elog, ERROR, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), and SearchSysCache1().

Referenced by ri_LoadConstraintInfo().

◆ InvalidateConstraintCacheCallBack()

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

Definition at line 2320 of file ri_triggers.c.

2321 {
2322  dlist_mutable_iter iter;
2323 
2324  Assert(ri_constraint_cache != NULL);
2325 
2326  /*
2327  * If the list of currently valid entries gets excessively large, we mark
2328  * them all invalid so we can empty the list. This arrangement avoids
2329  * O(N^2) behavior in situations where a session touches many foreign keys
2330  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2331  */
2333  hashvalue = 0; /* pretend it's a cache reset */
2334 
2336  {
2338  valid_link, iter.cur);
2339 
2340  /*
2341  * We must invalidate not only entries directly matching the given
2342  * hash value, but also child entries, in case the invalidation
2343  * affects a root constraint.
2344  */
2345  if (hashvalue == 0 ||
2346  riinfo->oidHashValue == hashvalue ||
2347  riinfo->rootHashValue == hashvalue)
2348  {
2349  riinfo->valid = false;
2350  /* Remove invalidated entries from the list, too */
2352  }
2353  }
2354 }
#define Assert(condition)
Definition: c.h:849
#define dclist_container(type, membername, ptr)
Definition: ilist.h:947
static uint32 dclist_count(const dclist_head *head)
Definition: ilist.h:932
static void dclist_delete_from(dclist_head *head, dlist_node *node)
Definition: ilist.h:763
#define dclist_foreach_modify(iter, lhead)
Definition: ilist.h:973
static dclist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:184
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:181
dlist_node * cur
Definition: ilist.h:200

References Assert, dlist_mutable_iter::cur, dclist_container, dclist_count(), dclist_delete_from(), dclist_foreach_modify, RI_ConstraintInfo::oidHashValue, ri_constraint_cache, ri_constraint_cache_valid_list, RI_ConstraintInfo::rootHashValue, and RI_ConstraintInfo::valid.

Referenced by ri_InitHashTables().

◆ quoteOneName()

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

Definition at line 1950 of file ri_triggers.c.

1951 {
1952  /* Rather than trying to be smart, just always quote it. */
1953  *buffer++ = '"';
1954  while (*name)
1955  {
1956  if (*name == '"')
1957  *buffer++ = '"';
1958  *buffer++ = *name++;
1959  }
1960  *buffer++ = '"';
1961  *buffer = '\0';
1962 }
const char * name

References name.

Referenced by quoteRelationName(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_GenerateQualCollation(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), and ri_set().

◆ quoteRelationName()

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

Definition at line 1970 of file ri_triggers.c.

1971 {
1973  buffer += strlen(buffer);
1974  *buffer++ = '.';
1975  quoteOneName(buffer, RelationGetRelationName(rel));
1976 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1950

References get_namespace_name(), quoteOneName(), RelationGetNamespace, and RelationGetRelationName.

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

◆ ri_BuildQueryKey()

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

Definition at line 2057 of file ri_triggers.c.

2059 {
2060  /*
2061  * Inherited constraints with a common ancestor can share ri_query_cache
2062  * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2063  * Except in that case, the query processes the other table involved in
2064  * the FK constraint (i.e., not the table on which the trigger has been
2065  * fired), and so it will be the same for all members of the inheritance
2066  * tree. So we may use the root constraint's OID in the hash key, rather
2067  * than the constraint's own OID. This avoids creating duplicate SPI
2068  * plans, saving lots of work and memory when there are many partitions
2069  * with similar FK constraints.
2070  *
2071  * (Note that we must still have a separate RI_ConstraintInfo for each
2072  * constraint, because partitions can have different column orders,
2073  * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2074  *
2075  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2076  * to use memset to clear them.
2077  */
2078  if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2079  key->constr_id = riinfo->constraint_root_id;
2080  else
2081  key->constr_id = riinfo->constraint_id;
2082  key->constr_queryno = constr_queryno;
2083 }
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:72

References RI_ConstraintInfo::constraint_id, RI_ConstraintInfo::constraint_root_id, sort-test::key, and RI_PLAN_CHECK_LOOKUPPK_FROM_PK.

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

◆ ri_Check_Pk_Match()

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

Definition at line 507 of file ri_triggers.c.

510 {
511  SPIPlanPtr qplan;
512  RI_QueryKey qkey;
513  bool result;
514 
515  /* Only called for non-null rows */
516  Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
517 
518  SPI_connect();
519 
520  /*
521  * Fetch or prepare a saved plan for checking PK table with values coming
522  * from a PK row
523  */
525 
526  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
527  {
528  StringInfoData querybuf;
529  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
531  char paramname[16];
532  const char *querysep;
533  const char *pk_only;
534  Oid queryoids[RI_MAX_NUMKEYS];
535 
536  /* ----------
537  * The query string built is
538  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
539  * FOR KEY SHARE OF x
540  * The type id's for the $ parameters are those of the
541  * PK attributes themselves.
542  *
543  * But for temporal FKs we need to make sure
544  * the old PK's range is completely covered.
545  * So we use this query instead:
546  * SELECT 1
547  * FROM (
548  * SELECT pkperiodatt AS r
549  * FROM [ONLY] pktable x
550  * WHERE pkatt1 = $1 [AND ...]
551  * AND pkperiodatt && $n
552  * FOR KEY SHARE OF x
553  * ) x1
554  * HAVING $n <@ range_agg(x1.r)
555  * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
556  * we can make this a bit simpler.
557  * ----------
558  */
559  initStringInfo(&querybuf);
560  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
561  "" : "ONLY ";
562  quoteRelationName(pkrelname, pk_rel);
563  if (riinfo->hasperiod)
564  {
565  quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
566 
567  appendStringInfo(&querybuf,
568  "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
569  attname, pk_only, pkrelname);
570  }
571  else
572  {
573  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
574  pk_only, pkrelname);
575  }
576  querysep = "WHERE";
577  for (int i = 0; i < riinfo->nkeys; i++)
578  {
579  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
580 
582  RIAttName(pk_rel, riinfo->pk_attnums[i]));
583  sprintf(paramname, "$%d", i + 1);
584  ri_GenerateQual(&querybuf, querysep,
585  attname, pk_type,
586  riinfo->pp_eq_oprs[i],
587  paramname, pk_type);
588  querysep = "AND";
589  queryoids[i] = pk_type;
590  }
591  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
592  if (riinfo->hasperiod)
593  {
594  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
595 
596  appendStringInfo(&querybuf, ") x1 HAVING ");
597  sprintf(paramname, "$%d", riinfo->nkeys);
598  ri_GenerateQual(&querybuf, "",
599  paramname, fk_type,
601  "pg_catalog.range_agg", ANYMULTIRANGEOID);
602  appendStringInfo(&querybuf, "(x1.r)");
603  }
604 
605  /* Prepare and save the plan */
606  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
607  &qkey, fk_rel, pk_rel);
608  }
609 
610  /*
611  * We have a plan now. Run it.
612  */
613  result = ri_PerformCheck(riinfo, &qkey, qplan,
614  fk_rel, pk_rel,
615  oldslot, NULL,
616  true, /* treat like update */
617  SPI_OK_SELECT);
618 
619  if (SPI_finish() != SPI_OK_FINISH)
620  elog(ERROR, "SPI_finish failed");
621 
622  return result;
623 }
int i
Definition: isn.c:73
NameData attname
Definition: pg_attribute.h:41
#define sprintf
Definition: port.h:240
#define RelationGetDescr(relation)
Definition: rel.h:531
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2404
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:88
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:85
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1970
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2728
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:1987
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:67
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2057
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2361
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:84
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:87
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:60
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2801
int SPI_connect(void)
Definition: spi.c:94
int SPI_finish(void)
Definition: spi.c:182
#define SPI_OK_FINISH
Definition: spi.h:83
#define SPI_OK_SELECT
Definition: spi.h:86
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:125
Oid agged_period_contained_by_oper
Definition: ri_triggers.c:131
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:126
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:128
Form_pg_class rd_rel
Definition: rel.h:111

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

Referenced by ri_restrict().

◆ ri_CheckTrigger()

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

Definition at line 2089 of file ri_triggers.c.

2090 {
2091  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2092 
2093  if (!CALLED_AS_TRIGGER(fcinfo))
2094  ereport(ERROR,
2095  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2096  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2097 
2098  /*
2099  * Check proper event
2100  */
2101  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2102  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2103  ereport(ERROR,
2104  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2105  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2106 
2107  switch (tgkind)
2108  {
2109  case RI_TRIGTYPE_INSERT:
2110  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2111  ereport(ERROR,
2112  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2113  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2114  break;
2115  case RI_TRIGTYPE_UPDATE:
2116  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2117  ereport(ERROR,
2118  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2119  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2120  break;
2121  case RI_TRIGTYPE_DELETE:
2122  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2123  ereport(ERROR,
2124  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2125  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2126  break;
2127  }
2128 }
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
#define funcname
Definition: indent_codes.h:69
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:91
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:93
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:92
fmNodePtr context
Definition: fmgr.h:88
TriggerEvent tg_event
Definition: trigger.h:34
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:113
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:122
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:131
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:110
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:116

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

◆ ri_CompareWithCast()

static bool ri_CompareWithCast ( Oid  eq_opr,
Oid  typeid,
Datum  lhs,
Datum  rhs 
)
static

Definition at line 2975 of file ri_triggers.c.

2977 {
2978  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
2979 
2980  /* Do we need to cast the values? */
2981  if (OidIsValid(entry->cast_func_finfo.fn_oid))
2982  {
2983  lhs = FunctionCall3(&entry->cast_func_finfo,
2984  lhs,
2985  Int32GetDatum(-1), /* typmod */
2986  BoolGetDatum(false)); /* implicit coercion */
2987  rhs = FunctionCall3(&entry->cast_func_finfo,
2988  rhs,
2989  Int32GetDatum(-1), /* typmod */
2990  BoolGetDatum(false)); /* implicit coercion */
2991  }
2992 
2993  /*
2994  * Apply the comparison operator.
2995  *
2996  * Note: This function is part of a call stack that determines whether an
2997  * update to a row is significant enough that it needs checking or action
2998  * on the other side of a foreign-key constraint. Therefore, the
2999  * comparison here would need to be done with the collation of the *other*
3000  * table. For simplicity (e.g., we might not even have the other table
3001  * open), we'll just use the default collation here, which could lead to
3002  * some false negatives. All this would break if we ever allow
3003  * database-wide collations to be nondeterministic.
3004  *
3005  * With range/multirangetypes, the collation of the base type is stored as
3006  * part of the rangetype (pg_range.rngcollation), and always used, so
3007  * there is no danger of inconsistency even using a non-equals operator.
3008  * But if we support arbitrary types with PERIOD, we should perhaps just
3009  * always force a re-check.
3010  */
3012  DEFAULT_COLLATION_OID,
3013  lhs, rhs));
3014 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:663
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3023
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:174

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

Referenced by ri_KeysEqual().

◆ ri_ExtractValues()

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

Definition at line 2541 of file ri_triggers.c.

2544 {
2545  const int16 *attnums;
2546  bool isnull;
2547 
2548  if (rel_is_pk)
2549  attnums = riinfo->pk_attnums;
2550  else
2551  attnums = riinfo->fk_attnums;
2552 
2553  for (int i = 0; i < riinfo->nkeys; i++)
2554  {
2555  vals[i] = slot_getattr(slot, attnums[i], &isnull);
2556  nulls[i] = isnull ? 'n' : ' ';
2557  }
2558 }
signed short int16
Definition: c.h:495
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395

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

Referenced by ri_PerformCheck().

◆ ri_FetchConstraintInfo()

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

Definition at line 2135 of file ri_triggers.c.

2136 {
2137  Oid constraintOid = trigger->tgconstraint;
2138  const RI_ConstraintInfo *riinfo;
2139 
2140  /*
2141  * Check that the FK constraint's OID is available; it might not be if
2142  * we've been invoked via an ordinary trigger or an old-style "constraint
2143  * trigger".
2144  */
2145  if (!OidIsValid(constraintOid))
2146  ereport(ERROR,
2147  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2148  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2149  trigger->tgname, RelationGetRelationName(trig_rel)),
2150  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2151 
2152  /* Find or create a hashtable entry for the constraint */
2153  riinfo = ri_LoadConstraintInfo(constraintOid);
2154 
2155  /* Do some easy cross-checks against the trigger call data */
2156  if (rel_is_pk)
2157  {
2158  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2159  riinfo->pk_relid != RelationGetRelid(trig_rel))
2160  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2161  trigger->tgname, RelationGetRelationName(trig_rel));
2162  }
2163  else
2164  {
2165  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2166  riinfo->pk_relid != trigger->tgconstrrelid)
2167  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2168  trigger->tgname, RelationGetRelationName(trig_rel));
2169  }
2170 
2171  if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2174  elog(ERROR, "unrecognized confmatchtype: %d",
2175  riinfo->confmatchtype);
2176 
2177  if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2178  ereport(ERROR,
2179  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2180  errmsg("MATCH PARTIAL not yet implemented")));
2181 
2182  return riinfo;
2183 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2741
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2740
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2739
#define RelationGetRelid(relation)
Definition: rel.h:505
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2189
Oid tgconstraint
Definition: reltrigger.h:35
Oid tgconstrrelid
Definition: reltrigger.h:33
char * tgname
Definition: reltrigger.h:27

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

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

◆ ri_FetchPreparedPlan()

static SPIPlanPtr ri_FetchPreparedPlan ( RI_QueryKey key)
static

Definition at line 2801 of file ri_triggers.c.

2802 {
2803  RI_QueryHashEntry *entry;
2804  SPIPlanPtr plan;
2805 
2806  /*
2807  * On the first call initialize the hashtable
2808  */
2809  if (!ri_query_cache)
2811 
2812  /*
2813  * Lookup for the key
2814  */
2816  key,
2817  HASH_FIND, NULL);
2818  if (entry == NULL)
2819  return NULL;
2820 
2821  /*
2822  * Check whether the plan is still valid. If it isn't, we don't want to
2823  * simply rely on plancache.c to regenerate it; rather we should start
2824  * from scratch and rebuild the query text too. This is to cover cases
2825  * such as table/column renames. We depend on the plancache machinery to
2826  * detect possible invalidations, though.
2827  *
2828  * CAUTION: this check is only trustworthy if the caller has already
2829  * locked both FK and PK rels.
2830  */
2831  plan = entry->plan;
2832  if (plan && SPI_plan_is_valid(plan))
2833  return plan;
2834 
2835  /*
2836  * Otherwise we might as well flush the cached plan now, to free a little
2837  * memory space before we make a new one.
2838  */
2839  entry->plan = NULL;
2840  if (plan)
2841  SPI_freeplan(plan);
2842 
2843  return NULL;
2844 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
@ HASH_FIND
Definition: hsearch.h:113
#define plan(x)
Definition: pg_regress.c:162
static HTAB * ri_query_cache
Definition: ri_triggers.c:182
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2765
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1948
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:1025
SPIPlanPtr plan
Definition: ri_triggers.c:152

References HASH_FIND, hash_search(), sort-test::key, RI_QueryHashEntry::plan, plan, ri_InitHashTables(), ri_query_cache, SPI_freeplan(), and SPI_plan_is_valid().

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

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 825 of file ri_triggers.c.

826 {
827  TriggerData *trigdata = (TriggerData *) fcinfo->context;
828  const RI_ConstraintInfo *riinfo;
829  Relation fk_rel;
830  Relation pk_rel;
831  TupleTableSlot *oldslot;
832  RI_QueryKey qkey;
833  SPIPlanPtr qplan;
834 
835  /* Check that this is a valid trigger call on the right time and event. */
836  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
837 
838  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
839  trigdata->tg_relation, true);
840 
841  /*
842  * Get the relation descriptors of the FK and PK tables and the old tuple.
843  *
844  * fk_rel is opened in RowExclusiveLock mode since that's what our
845  * eventual DELETE will get on it.
846  */
847  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
848  pk_rel = trigdata->tg_relation;
849  oldslot = trigdata->tg_trigslot;
850 
851  SPI_connect();
852 
853  /* Fetch or prepare a saved plan for the cascaded delete */
855 
856  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
857  {
858  StringInfoData querybuf;
859  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
861  char paramname[16];
862  const char *querysep;
863  Oid queryoids[RI_MAX_NUMKEYS];
864  const char *fk_only;
865 
866  /* ----------
867  * The query string built is
868  * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
869  * The type id's for the $ parameters are those of the
870  * corresponding PK attributes.
871  * ----------
872  */
873  initStringInfo(&querybuf);
874  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
875  "" : "ONLY ";
876  quoteRelationName(fkrelname, fk_rel);
877  appendStringInfo(&querybuf, "DELETE FROM %s%s",
878  fk_only, fkrelname);
879  querysep = "WHERE";
880  for (int i = 0; i < riinfo->nkeys; i++)
881  {
882  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
883  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
884  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
885  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
886 
888  RIAttName(fk_rel, riinfo->fk_attnums[i]));
889  sprintf(paramname, "$%d", i + 1);
890  ri_GenerateQual(&querybuf, querysep,
891  paramname, pk_type,
892  riinfo->pf_eq_oprs[i],
893  attname, fk_type);
894  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
895  ri_GenerateQualCollation(&querybuf, pk_coll);
896  querysep = "AND";
897  queryoids[i] = pk_type;
898  }
899 
900  /* Prepare and save the plan */
901  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
902  &qkey, fk_rel, pk_rel);
903  }
904 
905  /*
906  * We have a plan now. Build up the arguments from the key values in the
907  * deleted PK tuple and delete the referencing rows
908  */
909  ri_PerformCheck(riinfo, &qkey, qplan,
910  fk_rel, pk_rel,
911  oldslot, NULL,
912  true, /* must detect new rows */
913  SPI_OK_DELETE);
914 
915  if (SPI_finish() != SPI_OK_FINISH)
916  elog(ERROR, "SPI_finish failed");
917 
918  table_close(fk_rel, RowExclusiveLock);
919 
920  return PointerGetDatum(NULL);
921 }
#define RowExclusiveLock
Definition: lockdefs.h:38
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:1054
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:2016
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:89
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2135
#define RI_PLAN_CASCADE_ONDELETE
Definition: ri_triggers.c:75
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2089
#define SPI_OK_DELETE
Definition: spi.h:89
Relation tg_relation
Definition: trigger.h:35
TupleTableSlot * tg_trigslot
Definition: trigger.h:39
Trigger * tg_trigger
Definition: trigger.h:38
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

◆ RI_FKey_cascade_upd()

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS  )

Definition at line 930 of file ri_triggers.c.

931 {
932  TriggerData *trigdata = (TriggerData *) fcinfo->context;
933  const RI_ConstraintInfo *riinfo;
934  Relation fk_rel;
935  Relation pk_rel;
936  TupleTableSlot *newslot;
937  TupleTableSlot *oldslot;
938  RI_QueryKey qkey;
939  SPIPlanPtr qplan;
940 
941  /* Check that this is a valid trigger call on the right time and event. */
942  ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
943 
944  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
945  trigdata->tg_relation, true);
946 
947  /*
948  * Get the relation descriptors of the FK and PK tables and the new and
949  * old tuple.
950  *
951  * fk_rel is opened in RowExclusiveLock mode since that's what our
952  * eventual UPDATE will get on it.
953  */
954  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
955  pk_rel = trigdata->tg_relation;
956  newslot = trigdata->tg_newslot;
957  oldslot = trigdata->tg_trigslot;
958 
959  SPI_connect();
960 
961  /* Fetch or prepare a saved plan for the cascaded update */
963 
964  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
965  {
966  StringInfoData querybuf;
967  StringInfoData qualbuf;
968  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
970  char paramname[16];
971  const char *querysep;
972  const char *qualsep;
973  Oid queryoids[RI_MAX_NUMKEYS * 2];
974  const char *fk_only;
975 
976  /* ----------
977  * The query string built is
978  * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
979  * WHERE $n = fkatt1 [AND ...]
980  * The type id's for the $ parameters are those of the
981  * corresponding PK attributes. Note that we are assuming
982  * there is an assignment cast from the PK to the FK type;
983  * else the parser will fail.
984  * ----------
985  */
986  initStringInfo(&querybuf);
987  initStringInfo(&qualbuf);
988  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
989  "" : "ONLY ";
990  quoteRelationName(fkrelname, fk_rel);
991  appendStringInfo(&querybuf, "UPDATE %s%s SET",
992  fk_only, fkrelname);
993  querysep = "";
994  qualsep = "WHERE";
995  for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
996  {
997  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
998  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
999  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1000  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1001 
1003  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1004  appendStringInfo(&querybuf,
1005  "%s %s = $%d",
1006  querysep, attname, i + 1);
1007  sprintf(paramname, "$%d", j + 1);
1008  ri_GenerateQual(&qualbuf, qualsep,
1009  paramname, pk_type,
1010  riinfo->pf_eq_oprs[i],
1011  attname, fk_type);
1012  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
1013  ri_GenerateQualCollation(&querybuf, pk_coll);
1014  querysep = ",";
1015  qualsep = "AND";
1016  queryoids[i] = pk_type;
1017  queryoids[j] = pk_type;
1018  }
1019  appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
1020 
1021  /* Prepare and save the plan */
1022  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1023  &qkey, fk_rel, pk_rel);
1024  }
1025 
1026  /*
1027  * We have a plan now. Run it to update the existing references.
1028  */
1029  ri_PerformCheck(riinfo, &qkey, qplan,
1030  fk_rel, pk_rel,
1031  oldslot, newslot,
1032  true, /* must detect new rows */
1033  SPI_OK_UPDATE);
1034 
1035  if (SPI_finish() != SPI_OK_FINISH)
1036  elog(ERROR, "SPI_finish failed");
1037 
1038  table_close(fk_rel, RowExclusiveLock);
1039 
1040  return PointerGetDatum(NULL);
1041 }
int j
Definition: isn.c:74
#define RI_PLAN_CASCADE_ONUPDATE
Definition: ri_triggers.c:76
#define SPI_OK_UPDATE
Definition: spi.h:90
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:233
TupleTableSlot * tg_newslot
Definition: trigger.h:40

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

◆ RI_FKey_check()

static Datum RI_FKey_check ( TriggerData trigdata)
static

Definition at line 247 of file ri_triggers.c.

248 {
249  const RI_ConstraintInfo *riinfo;
250  Relation fk_rel;
251  Relation pk_rel;
252  TupleTableSlot *newslot;
253  RI_QueryKey qkey;
254  SPIPlanPtr qplan;
255 
256  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
257  trigdata->tg_relation, false);
258 
259  if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
260  newslot = trigdata->tg_newslot;
261  else
262  newslot = trigdata->tg_trigslot;
263 
264  /*
265  * We should not even consider checking the row if it is no longer valid,
266  * since it was either deleted (so the deferred check should be skipped)
267  * or updated (in which case only the latest version of the row should be
268  * checked). Test its liveness according to SnapshotSelf. We need pin
269  * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
270  * should be holding pin, but not lock.
271  */
272  if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
273  return PointerGetDatum(NULL);
274 
275  /*
276  * Get the relation descriptors of the FK and PK tables.
277  *
278  * pk_rel is opened in RowShareLock mode since that's what our eventual
279  * SELECT FOR KEY SHARE will get on it.
280  */
281  fk_rel = trigdata->tg_relation;
282  pk_rel = table_open(riinfo->pk_relid, RowShareLock);
283 
284  switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
285  {
286  case RI_KEYS_ALL_NULL:
287 
288  /*
289  * No further check needed - an all-NULL key passes every type of
290  * foreign key constraint.
291  */
292  table_close(pk_rel, RowShareLock);
293  return PointerGetDatum(NULL);
294 
295  case RI_KEYS_SOME_NULL:
296 
297  /*
298  * This is the only case that differs between the three kinds of
299  * MATCH.
300  */
301  switch (riinfo->confmatchtype)
302  {
303  case FKCONSTR_MATCH_FULL:
304 
305  /*
306  * Not allowed - MATCH FULL says either all or none of the
307  * attributes can be NULLs
308  */
309  ereport(ERROR,
310  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
311  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
312  RelationGetRelationName(fk_rel),
313  NameStr(riinfo->conname)),
314  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
315  errtableconstraint(fk_rel,
316  NameStr(riinfo->conname))));
317  table_close(pk_rel, RowShareLock);
318  return PointerGetDatum(NULL);
319 
321 
322  /*
323  * MATCH SIMPLE - if ANY column is null, the key passes
324  * the constraint.
325  */
326  table_close(pk_rel, RowShareLock);
327  return PointerGetDatum(NULL);
328 
329 #ifdef NOT_USED
331 
332  /*
333  * MATCH PARTIAL - all non-null columns must match. (not
334  * implemented, can be done by modifying the query below
335  * to only include non-null columns, or by writing a
336  * special version here)
337  */
338  break;
339 #endif
340  }
341 
342  case RI_KEYS_NONE_NULL:
343 
344  /*
345  * Have a full qualified key - continue below for all three kinds
346  * of MATCH.
347  */
348  break;
349  }
350 
351  SPI_connect();
352 
353  /* Fetch or prepare a saved plan for the real check */
355 
356  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
357  {
358  StringInfoData querybuf;
359  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
361  char paramname[16];
362  const char *querysep;
363  Oid queryoids[RI_MAX_NUMKEYS];
364  const char *pk_only;
365 
366  /* ----------
367  * The query string built is
368  * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
369  * FOR KEY SHARE OF x
370  * The type id's for the $ parameters are those of the
371  * corresponding FK attributes.
372  *
373  * But for temporal FKs we need to make sure
374  * the FK's range is completely covered.
375  * So we use this query instead:
376  * SELECT 1
377  * FROM (
378  * SELECT pkperiodatt AS r
379  * FROM [ONLY] pktable x
380  * WHERE pkatt1 = $1 [AND ...]
381  * AND pkperiodatt && $n
382  * FOR KEY SHARE OF x
383  * ) x1
384  * HAVING $n <@ range_agg(x1.r)
385  * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
386  * we can make this a bit simpler.
387  * ----------
388  */
389  initStringInfo(&querybuf);
390  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
391  "" : "ONLY ";
392  quoteRelationName(pkrelname, pk_rel);
393  if (riinfo->hasperiod)
394  {
396  RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
397 
398  appendStringInfo(&querybuf,
399  "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
400  attname, pk_only, pkrelname);
401  }
402  else
403  {
404  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
405  pk_only, pkrelname);
406  }
407  querysep = "WHERE";
408  for (int i = 0; i < riinfo->nkeys; i++)
409  {
410  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
411  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
412 
414  RIAttName(pk_rel, riinfo->pk_attnums[i]));
415  sprintf(paramname, "$%d", i + 1);
416  ri_GenerateQual(&querybuf, querysep,
417  attname, pk_type,
418  riinfo->pf_eq_oprs[i],
419  paramname, fk_type);
420  querysep = "AND";
421  queryoids[i] = fk_type;
422  }
423  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
424  if (riinfo->hasperiod)
425  {
426  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
427 
428  appendStringInfo(&querybuf, ") x1 HAVING ");
429  sprintf(paramname, "$%d", riinfo->nkeys);
430  ri_GenerateQual(&querybuf, "",
431  paramname, fk_type,
433  "pg_catalog.range_agg", ANYMULTIRANGEOID);
434  appendStringInfo(&querybuf, "(x1.r)");
435  }
436 
437  /* Prepare and save the plan */
438  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
439  &qkey, fk_rel, pk_rel);
440  }
441 
442  /*
443  * Now check that foreign key exists in PK table
444  *
445  * XXX detectNewRows must be true when a partitioned table is on the
446  * referenced side. The reason is that our snapshot must be fresh in
447  * order for the hack in find_inheritance_children() to work.
448  */
449  ri_PerformCheck(riinfo, &qkey, qplan,
450  fk_rel, pk_rel,
451  NULL, newslot,
452  pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
453  SPI_OK_SELECT);
454 
455  if (SPI_finish() != SPI_OK_FINISH)
456  elog(ERROR, "SPI_finish failed");
457 
458  table_close(pk_rel, RowShareLock);
459 
460  return PointerGetDatum(NULL);
461 }
#define NameStr(name)
Definition: c.h:737
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define RowShareLock
Definition: lockdefs.h:37
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6015
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:66
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:65
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:71
#define SnapshotSelf
Definition: snapmgr.h:32
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:127
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1335

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

Referenced by RI_FKey_check_ins(), and RI_FKey_check_upd().

◆ RI_FKey_check_ins()

Datum RI_FKey_check_ins ( PG_FUNCTION_ARGS  )

Definition at line 470 of file ri_triggers.c.

471 {
472  /* Check that this is a valid trigger call on the right time and event. */
473  ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
474 
475  /* Share code with UPDATE case. */
476  return RI_FKey_check((TriggerData *) fcinfo->context);
477 }
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:247

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

Referenced by validateForeignKeyConstraint().

◆ RI_FKey_check_upd()

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS  )

Definition at line 486 of file ri_triggers.c.

487 {
488  /* Check that this is a valid trigger call on the right time and event. */
489  ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
490 
491  /* Share code with INSERT case. */
492  return RI_FKey_check((TriggerData *) fcinfo->context);
493 }

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

◆ RI_FKey_fk_upd_check_required()

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

Definition at line 1337 of file ri_triggers.c.

1339 {
1340  const RI_ConstraintInfo *riinfo;
1341  int ri_nullcheck;
1342 
1343  /*
1344  * AfterTriggerSaveEvent() handles things such that this function is never
1345  * called for partitioned tables.
1346  */
1347  Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1348 
1349  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1350 
1351  ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1352 
1353  /*
1354  * If all new key values are NULL, the row satisfies the constraint, so no
1355  * check is needed.
1356  */
1357  if (ri_nullcheck == RI_KEYS_ALL_NULL)
1358  return false;
1359 
1360  /*
1361  * If some new key values are NULL, the behavior depends on the match
1362  * type.
1363  */
1364  else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1365  {
1366  switch (riinfo->confmatchtype)
1367  {
1368  case FKCONSTR_MATCH_SIMPLE:
1369 
1370  /*
1371  * If any new key value is NULL, the row must satisfy the
1372  * constraint, so no check is needed.
1373  */
1374  return false;
1375 
1377 
1378  /*
1379  * Don't know, must run full check.
1380  */
1381  break;
1382 
1383  case FKCONSTR_MATCH_FULL:
1384 
1385  /*
1386  * If some new key values are NULL, the row fails the
1387  * constraint. We must not throw error here, because the row
1388  * might get invalidated before the constraint is to be
1389  * checked, but we should queue the event to apply the check
1390  * later.
1391  */
1392  return true;
1393  }
1394  }
1395 
1396  /*
1397  * Continues here for no new key values are NULL, or we couldn't decide
1398  * yet.
1399  */
1400 
1401  /*
1402  * If the original row was inserted by our own transaction, we must fire
1403  * the trigger whether or not the keys are equal. This is because our
1404  * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1405  * not do anything; so we had better do the UPDATE check. (We could skip
1406  * this if we knew the INSERT trigger already fired, but there is no easy
1407  * way to know that.)
1408  */
1409  if (slot_is_current_xact_tuple(oldslot))
1410  return true;
1411 
1412  /* If all old and new key values are equal, no check is needed */
1413  if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1414  return false;
1415 
1416  /* Else we need to fire the trigger. */
1417  return true;
1418 }
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2890
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition: tuptable.h:445

References Assert, RI_ConstraintInfo::confmatchtype, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, RelationData::rd_rel, RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_ALL_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), and slot_is_current_xact_tuple().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 634 of file ri_triggers.c.

635 {
636  /* Check that this is a valid trigger call on the right time and event. */
637  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
638 
639  /* Share code with RESTRICT/UPDATE cases. */
640  return ri_restrict((TriggerData *) fcinfo->context, true);
641 }
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:707

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 671 of file ri_triggers.c.

672 {
673  /* Check that this is a valid trigger call on the right time and event. */
674  ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
675 
676  /* Share code with RESTRICT/DELETE cases. */
677  return ri_restrict((TriggerData *) fcinfo->context, true);
678 }

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

◆ RI_FKey_pk_upd_check_required()

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

Definition at line 1305 of file ri_triggers.c.

1307 {
1308  const RI_ConstraintInfo *riinfo;
1309 
1310  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1311 
1312  /*
1313  * If any old key value is NULL, the row could not have been referenced by
1314  * an FK row, so no check is needed.
1315  */
1316  if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1317  return false;
1318 
1319  /* If all old and new key values are equal, no check is needed */
1320  if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1321  return false;
1322 
1323  /* Else we need to fire the trigger. */
1324  return true;
1325 }

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

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_restrict_del()

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS  )

Definition at line 654 of file ri_triggers.c.

655 {
656  /* Check that this is a valid trigger call on the right time and event. */
657  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
658 
659  /* Share code with NO ACTION/UPDATE cases. */
660  return ri_restrict((TriggerData *) fcinfo->context, false);
661 }

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 691 of file ri_triggers.c.

692 {
693  /* Check that this is a valid trigger call on the right time and event. */
694  ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
695 
696  /* Share code with NO ACTION/DELETE cases. */
697  return ri_restrict((TriggerData *) fcinfo->context, false);
698 }

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1080 of file ri_triggers.c.

1081 {
1082  /* Check that this is a valid trigger call on the right time and event. */
1083  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1084 
1085  /* Share code with UPDATE case */
1086  return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1087 }
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
Definition: ri_triggers.c:1111

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1095 of file ri_triggers.c.

1096 {
1097  /* Check that this is a valid trigger call on the right time and event. */
1098  ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1099 
1100  /* Share code with DELETE case */
1101  return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1102 }

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1050 of file ri_triggers.c.

1051 {
1052  /* Check that this is a valid trigger call on the right time and event. */
1053  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1054 
1055  /* Share code with UPDATE case */
1056  return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1057 }

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1065 of file ri_triggers.c.

1066 {
1067  /* Check that this is a valid trigger call on the right time and event. */
1068  ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1069 
1070  /* Share code with DELETE case */
1071  return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1072 }

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3116 of file ri_triggers.c.

3117 {
3118  switch (tgfoid)
3119  {
3120  case F_RI_FKEY_CASCADE_DEL:
3121  case F_RI_FKEY_CASCADE_UPD:
3122  case F_RI_FKEY_RESTRICT_DEL:
3123  case F_RI_FKEY_RESTRICT_UPD:
3124  case F_RI_FKEY_SETNULL_DEL:
3125  case F_RI_FKEY_SETNULL_UPD:
3126  case F_RI_FKEY_SETDEFAULT_DEL:
3127  case F_RI_FKEY_SETDEFAULT_UPD:
3128  case F_RI_FKEY_NOACTION_DEL:
3129  case F_RI_FKEY_NOACTION_UPD:
3130  return RI_TRIGGER_PK;
3131 
3132  case F_RI_FKEY_CHECK_INS:
3133  case F_RI_FKEY_CHECK_UPD:
3134  return RI_TRIGGER_FK;
3135  }
3136 
3137  return RI_TRIGGER_NONE;
3138 }
#define RI_TRIGGER_FK
Definition: trigger.h:283
#define RI_TRIGGER_NONE
Definition: trigger.h:284
#define RI_TRIGGER_PK
Definition: trigger.h:282

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), ExecCrossPartitionUpdateForeignKey(), GetForeignKeyActionTriggers(), and GetForeignKeyCheckTriggers().

◆ ri_GenerateQual()

static void ri_GenerateQual ( StringInfo  buf,
const char *  sep,
const char *  leftop,
Oid  leftoptype,
Oid  opoid,
const char *  rightop,
Oid  rightoptype 
)
static

Definition at line 1987 of file ri_triggers.c.

1992 {
1993  appendStringInfo(buf, " %s ", sep);
1994  generate_operator_clause(buf, leftop, leftoptype, opoid,
1995  rightop, rightoptype);
1996 }
static char * buf
Definition: pg_test_fsync.c:73
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13250

References appendStringInfo(), buf, and generate_operator_clause().

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

◆ ri_GenerateQualCollation()

static void ri_GenerateQualCollation ( StringInfo  buf,
Oid  collation 
)
static

Definition at line 2016 of file ri_triggers.c.

2017 {
2018  HeapTuple tp;
2019  Form_pg_collation colltup;
2020  char *collname;
2021  char onename[MAX_QUOTED_NAME_LEN];
2022 
2023  /* Nothing to do if it's a noncollatable data type */
2024  if (!OidIsValid(collation))
2025  return;
2026 
2027  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2028  if (!HeapTupleIsValid(tp))
2029  elog(ERROR, "cache lookup failed for collation %u", collation);
2030  colltup = (Form_pg_collation) GETSTRUCT(tp);
2031  collname = NameStr(colltup->collname);
2032 
2033  /*
2034  * We qualify the name always, for simplicity and to ensure the query is
2035  * not search-path-dependent.
2036  */
2037  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2038  appendStringInfo(buf, " COLLATE %s", onename);
2039  quoteOneName(onename, collname);
2040  appendStringInfo(buf, ".%s", onename);
2041 
2042  ReleaseSysCache(tp);
2043 }
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58

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

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

◆ ri_HashCompareOp()

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

Definition at line 3023 of file ri_triggers.c.

3024 {
3026  RI_CompareHashEntry *entry;
3027  bool found;
3028 
3029  /*
3030  * On the first call initialize the hashtable
3031  */
3032  if (!ri_compare_cache)
3034 
3035  /*
3036  * Find or create a hash entry. Note we're assuming RI_CompareKey
3037  * contains no struct padding.
3038  */
3039  key.eq_opr = eq_opr;
3040  key.typeid = typeid;
3042  &key,
3043  HASH_ENTER, &found);
3044  if (!found)
3045  entry->valid = false;
3046 
3047  /*
3048  * If not already initialized, do so. Since we'll keep this hash entry
3049  * for the life of the backend, put any subsidiary info for the function
3050  * cache structs into TopMemoryContext.
3051  */
3052  if (!entry->valid)
3053  {
3054  Oid lefttype,
3055  righttype,
3056  castfunc;
3057  CoercionPathType pathtype;
3058 
3059  /* We always need to know how to call the equality operator */
3060  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3062 
3063  /*
3064  * If we chose to use a cast from FK to PK type, we may have to apply
3065  * the cast function to get to the operator's input type.
3066  *
3067  * XXX eventually it would be good to support array-coercion cases
3068  * here and in ri_CompareWithCast(). At the moment there is no point
3069  * because cases involving nonidentical array types will be rejected
3070  * at constraint creation time.
3071  *
3072  * XXX perhaps also consider supporting CoerceViaIO? No need at the
3073  * moment since that will never be generated for implicit coercions.
3074  */
3075  op_input_types(eq_opr, &lefttype, &righttype);
3076  Assert(lefttype == righttype);
3077  if (typeid == lefttype)
3078  castfunc = InvalidOid; /* simplest case */
3079  else
3080  {
3081  pathtype = find_coercion_pathway(lefttype, typeid,
3083  &castfunc);
3084  if (pathtype != COERCION_PATH_FUNC &&
3085  pathtype != COERCION_PATH_RELABELTYPE)
3086  {
3087  /*
3088  * The declared input type of the eq_opr might be a
3089  * polymorphic type such as ANYARRAY or ANYENUM, or other
3090  * special cases such as RECORD; find_coercion_pathway
3091  * currently doesn't subsume these special cases.
3092  */
3093  if (!IsBinaryCoercible(typeid, lefttype))
3094  elog(ERROR, "no conversion function from %s to %s",
3095  format_type_be(typeid),
3096  format_type_be(lefttype));
3097  }
3098  }
3099  if (OidIsValid(castfunc))
3100  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3102  else
3104  entry->valid = true;
3105  }
3106 
3107  return entry;
3108 }
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
@ HASH_ENTER
Definition: hsearch.h:114
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1358
MemoryContext TopMemoryContext
Definition: mcxt.c:149
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
Definition: parse_coerce.h:25
@ COERCION_PATH_FUNC
Definition: parse_coerce.h:27
@ COERCION_PATH_RELABELTYPE
Definition: parse_coerce.h:28
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCION_IMPLICIT
Definition: primnodes.h:714
static HTAB * ri_compare_cache
Definition: ri_triggers.c:183

References Assert, RI_CompareHashEntry::cast_func_finfo, COERCION_IMPLICIT, COERCION_PATH_FUNC, COERCION_PATH_RELABELTYPE, elog, RI_CompareHashEntry::eq_opr_finfo, ERROR, find_coercion_pathway(), fmgr_info_cxt(), FmgrInfo::fn_oid, format_type_be(), get_opcode(), HASH_ENTER, hash_search(), InvalidOid, IsBinaryCoercible(), sort-test::key, OidIsValid, op_input_types(), ri_compare_cache, ri_InitHashTables(), TopMemoryContext, and RI_CompareHashEntry::valid.

Referenced by ri_CompareWithCast().

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 2853 of file ri_triggers.c.

2854 {
2855  RI_QueryHashEntry *entry;
2856  bool found;
2857 
2858  /*
2859  * On the first call initialize the hashtable
2860  */
2861  if (!ri_query_cache)
2863 
2864  /*
2865  * Add the new plan. We might be overwriting an entry previously found
2866  * invalid by ri_FetchPreparedPlan.
2867  */
2869  key,
2870  HASH_ENTER, &found);
2871  Assert(!found || entry->plan == NULL);
2872  entry->plan = plan;
2873 }

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

Referenced by ri_PlanCheck().

◆ ri_InitHashTables()

static void ri_InitHashTables ( void  )
static

Definition at line 2765 of file ri_triggers.c.

2766 {
2767  HASHCTL ctl;
2768 
2769  ctl.keysize = sizeof(Oid);
2770  ctl.entrysize = sizeof(RI_ConstraintInfo);
2771  ri_constraint_cache = hash_create("RI constraint cache",
2773  &ctl, HASH_ELEM | HASH_BLOBS);
2774 
2775  /* Arrange to flush cache on pg_constraint changes */
2778  (Datum) 0);
2779 
2780  ctl.keysize = sizeof(RI_QueryKey);
2781  ctl.entrysize = sizeof(RI_QueryHashEntry);
2782  ri_query_cache = hash_create("RI query cache",
2784  &ctl, HASH_ELEM | HASH_BLOBS);
2785 
2786  ctl.keysize = sizeof(RI_CompareKey);
2787  ctl.entrysize = sizeof(RI_CompareHashEntry);
2788  ri_compare_cache = hash_create("RI compare cache",
2790  &ctl, HASH_ELEM | HASH_BLOBS);
2791 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1516
uintptr_t Datum
Definition: postgres.h:64
tree ctl
Definition: radixtree.h:1853
struct RI_ConstraintInfo RI_ConstraintInfo
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2320
struct RI_QueryKey RI_QueryKey
struct RI_CompareHashEntry RI_CompareHashEntry
struct RI_QueryHashEntry RI_QueryHashEntry
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:63
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:62
struct RI_CompareKey RI_CompareKey

References CacheRegisterSyscacheCallback(), ctl, HASH_BLOBS, hash_create(), HASH_ELEM, InvalidateConstraintCacheCallBack(), ri_compare_cache, ri_constraint_cache, RI_INIT_CONSTRAINTHASHSIZE, RI_INIT_QUERYHASHSIZE, and ri_query_cache.

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

◆ RI_Initial_Check()

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

Definition at line 1438 of file ri_triggers.c.

1439 {
1440  const RI_ConstraintInfo *riinfo;
1441  StringInfoData querybuf;
1442  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1443  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1444  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1445  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1446  RangeTblEntry *rte;
1447  RTEPermissionInfo *pk_perminfo;
1448  RTEPermissionInfo *fk_perminfo;
1449  List *rtes = NIL;
1450  List *perminfos = NIL;
1451  const char *sep;
1452  const char *fk_only;
1453  const char *pk_only;
1454  int save_nestlevel;
1455  char workmembuf[32];
1456  int spi_result;
1457  SPIPlanPtr qplan;
1458 
1459  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1460 
1461  /*
1462  * Check to make sure current user has enough permissions to do the test
1463  * query. (If not, caller can fall back to the trigger method, which
1464  * works because it changes user IDs on the fly.)
1465  *
1466  * XXX are there any other show-stopper conditions to check?
1467  */
1468  pk_perminfo = makeNode(RTEPermissionInfo);
1469  pk_perminfo->relid = RelationGetRelid(pk_rel);
1470  pk_perminfo->requiredPerms = ACL_SELECT;
1471  perminfos = lappend(perminfos, pk_perminfo);
1472  rte = makeNode(RangeTblEntry);
1473  rte->rtekind = RTE_RELATION;
1474  rte->relid = RelationGetRelid(pk_rel);
1475  rte->relkind = pk_rel->rd_rel->relkind;
1476  rte->rellockmode = AccessShareLock;
1477  rte->perminfoindex = list_length(perminfos);
1478  rtes = lappend(rtes, rte);
1479 
1480  fk_perminfo = makeNode(RTEPermissionInfo);
1481  fk_perminfo->relid = RelationGetRelid(fk_rel);
1482  fk_perminfo->requiredPerms = ACL_SELECT;
1483  perminfos = lappend(perminfos, fk_perminfo);
1484  rte = makeNode(RangeTblEntry);
1485  rte->rtekind = RTE_RELATION;
1486  rte->relid = RelationGetRelid(fk_rel);
1487  rte->relkind = fk_rel->rd_rel->relkind;
1488  rte->rellockmode = AccessShareLock;
1489  rte->perminfoindex = list_length(perminfos);
1490  rtes = lappend(rtes, rte);
1491 
1492  for (int i = 0; i < riinfo->nkeys; i++)
1493  {
1494  int attno;
1495 
1496  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1497  pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1498 
1499  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1500  fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1501  }
1502 
1503  if (!ExecCheckPermissions(rtes, perminfos, false))
1504  return false;
1505 
1506  /*
1507  * Also punt if RLS is enabled on either table unless this role has the
1508  * bypassrls right or is the table owner of the table(s) involved which
1509  * have RLS enabled.
1510  */
1512  ((pk_rel->rd_rel->relrowsecurity &&
1513  !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1514  GetUserId())) ||
1515  (fk_rel->rd_rel->relrowsecurity &&
1516  !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1517  GetUserId()))))
1518  return false;
1519 
1520  /*----------
1521  * The query string built is:
1522  * SELECT fk.keycols FROM [ONLY] relname fk
1523  * LEFT OUTER JOIN [ONLY] pkrelname pk
1524  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1525  * WHERE pk.pkkeycol1 IS NULL AND
1526  * For MATCH SIMPLE:
1527  * (fk.keycol1 IS NOT NULL [AND ...])
1528  * For MATCH FULL:
1529  * (fk.keycol1 IS NOT NULL [OR ...])
1530  *
1531  * We attach COLLATE clauses to the operators when comparing columns
1532  * that have different collations.
1533  *----------
1534  */
1535  initStringInfo(&querybuf);
1536  appendStringInfoString(&querybuf, "SELECT ");
1537  sep = "";
1538  for (int i = 0; i < riinfo->nkeys; i++)
1539  {
1540  quoteOneName(fkattname,
1541  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1542  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1543  sep = ", ";
1544  }
1545 
1546  quoteRelationName(pkrelname, pk_rel);
1547  quoteRelationName(fkrelname, fk_rel);
1548  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1549  "" : "ONLY ";
1550  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1551  "" : "ONLY ";
1552  appendStringInfo(&querybuf,
1553  " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1554  fk_only, fkrelname, pk_only, pkrelname);
1555 
1556  strcpy(pkattname, "pk.");
1557  strcpy(fkattname, "fk.");
1558  sep = "(";
1559  for (int i = 0; i < riinfo->nkeys; i++)
1560  {
1561  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1562  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1563  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1564  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1565 
1566  quoteOneName(pkattname + 3,
1567  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1568  quoteOneName(fkattname + 3,
1569  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1570  ri_GenerateQual(&querybuf, sep,
1571  pkattname, pk_type,
1572  riinfo->pf_eq_oprs[i],
1573  fkattname, fk_type);
1574  if (pk_coll != fk_coll)
1575  ri_GenerateQualCollation(&querybuf, pk_coll);
1576  sep = "AND";
1577  }
1578 
1579  /*
1580  * It's sufficient to test any one pk attribute for null to detect a join
1581  * failure.
1582  */
1583  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1584  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1585 
1586  sep = "";
1587  for (int i = 0; i < riinfo->nkeys; i++)
1588  {
1589  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1590  appendStringInfo(&querybuf,
1591  "%sfk.%s IS NOT NULL",
1592  sep, fkattname);
1593  switch (riinfo->confmatchtype)
1594  {
1595  case FKCONSTR_MATCH_SIMPLE:
1596  sep = " AND ";
1597  break;
1598  case FKCONSTR_MATCH_FULL:
1599  sep = " OR ";
1600  break;
1601  }
1602  }
1603  appendStringInfoChar(&querybuf, ')');
1604 
1605  /*
1606  * Temporarily increase work_mem so that the check query can be executed
1607  * more efficiently. It seems okay to do this because the query is simple
1608  * enough to not use a multiple of work_mem, and one typically would not
1609  * have many large foreign-key validations happening concurrently. So
1610  * this seems to meet the criteria for being considered a "maintenance"
1611  * operation, and accordingly we use maintenance_work_mem. However, we
1612  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1613  * let that get applied to the maintenance_work_mem value.
1614  *
1615  * We use the equivalent of a function SET option to allow the setting to
1616  * persist for exactly the duration of the check query. guc.c also takes
1617  * care of undoing the setting on error.
1618  */
1619  save_nestlevel = NewGUCNestLevel();
1620 
1621  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1622  (void) set_config_option("work_mem", workmembuf,
1624  GUC_ACTION_SAVE, true, 0, false);
1625  (void) set_config_option("hash_mem_multiplier", "1",
1627  GUC_ACTION_SAVE, true, 0, false);
1628 
1629  SPI_connect();
1630 
1631  /*
1632  * Generate the plan. We don't need to cache it, and there are no
1633  * arguments to the plan.
1634  */
1635  qplan = SPI_prepare(querybuf.data, 0, NULL);
1636 
1637  if (qplan == NULL)
1638  elog(ERROR, "SPI_prepare returned %s for %s",
1640 
1641  /*
1642  * Run the plan. For safety we force a current snapshot to be used. (In
1643  * transaction-snapshot mode, this arguably violates transaction isolation
1644  * rules, but we really haven't got much choice.) We don't need to
1645  * register the snapshot, because SPI_execute_snapshot will see to it. We
1646  * need at most one tuple returned, so pass limit = 1.
1647  */
1648  spi_result = SPI_execute_snapshot(qplan,
1649  NULL, NULL,
1652  true, false, 1);
1653 
1654  /* Check result */
1655  if (spi_result != SPI_OK_SELECT)
1656  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1657 
1658  /* Did we find a tuple violating the constraint? */
1659  if (SPI_processed > 0)
1660  {
1661  TupleTableSlot *slot;
1662  HeapTuple tuple = SPI_tuptable->vals[0];
1663  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1664  RI_ConstraintInfo fake_riinfo;
1665 
1666  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1667 
1668  heap_deform_tuple(tuple, tupdesc,
1669  slot->tts_values, slot->tts_isnull);
1670  ExecStoreVirtualTuple(slot);
1671 
1672  /*
1673  * The columns to look at in the result tuple are 1..N, not whatever
1674  * they are in the fk_rel. Hack up riinfo so that the subroutines
1675  * called here will behave properly.
1676  *
1677  * In addition to this, we have to pass the correct tupdesc to
1678  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1679  * or fk_rel's tupdesc.
1680  */
1681  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1682  for (int i = 0; i < fake_riinfo.nkeys; i++)
1683  fake_riinfo.fk_attnums[i] = i + 1;
1684 
1685  /*
1686  * If it's MATCH FULL, and there are any nulls in the FK keys,
1687  * complain about that rather than the lack of a match. MATCH FULL
1688  * disallows partially-null FK rows.
1689  */
1690  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1691  ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1692  ereport(ERROR,
1693  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1694  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1695  RelationGetRelationName(fk_rel),
1696  NameStr(fake_riinfo.conname)),
1697  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1698  errtableconstraint(fk_rel,
1699  NameStr(fake_riinfo.conname))));
1700 
1701  /*
1702  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1703  * query, which isn't true, but will cause it to use
1704  * fake_riinfo.fk_attnums as we need.
1705  */
1706  ri_ReportViolation(&fake_riinfo,
1707  pk_rel, fk_rel,
1708  slot, tupdesc,
1709  RI_PLAN_CHECK_LOOKUPPK, false);
1710 
1712  }
1713 
1714  if (SPI_finish() != SPI_OK_FINISH)
1715  elog(ERROR, "SPI_finish failed");
1716 
1717  /*
1718  * Restore work_mem and hash_mem_multiplier.
1719  */
1720  AtEOXact_GUC(true, save_nestlevel);
1721 
1722  return true;
1723 }
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:4245
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4145
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:577
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1639
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1325
int maintenance_work_mem
Definition: globals.c:132
int NewGUCNestLevel(void)
Definition: guc.c:2234
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2261
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:3341
@ GUC_ACTION_SAVE
Definition: guc.h:201
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_USERSET
Definition: guc.h:75
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1345
List * lappend(List *list, void *datum)
Definition: list.c:339
#define AccessShareLock
Definition: lockdefs.h:36
Oid GetUserId(void)
Definition: miscinit.c:514
#define makeNode(_type_)
Definition: nodes.h:155
@ RTE_RELATION
Definition: parsenodes.h:1017
#define ACL_SELECT
Definition: parsenodes.h:77
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define snprintf
Definition: port.h:238
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2570
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:291
#define InvalidSnapshot
Definition: snapshot.h:123
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
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:773
int SPI_result
Definition: spi.c:46
const char * SPI_result_code_string(int code)
Definition: spi.c:1972
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:860
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
Definition: pg_list.h:54
Bitmapset * selectedCols
Definition: parsenodes.h:1293
AclMode requiredPerms
Definition: parsenodes.h:1291
RTEKind rtekind
Definition: parsenodes.h:1047
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References AccessShareLock, ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecCheckPermissions(), ExecDropSingleTupleTableSlot(), ExecStoreVirtualTuple(), FirstLowInvalidHeapAttributeNumber, RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_bypassrls_privilege(), heap_deform_tuple(), i, if(), initStringInfo(), InvalidSnapshot, lappend(), list_length(), maintenance_work_mem, makeNode, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, NewGUCNestLevel(), NIL, RI_ConstraintInfo::nkeys, object_ownercheck(), RI_ConstraintInfo::pf_eq_oprs, PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RTEPermissionInfo::relid, RTEPermissionInfo::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, RTEPermissionInfo::selectedCols, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by validateForeignKeyConstraint().

◆ ri_KeysEqual()

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

Definition at line 2890 of file ri_triggers.c.

2892 {
2893  const int16 *attnums;
2894 
2895  if (rel_is_pk)
2896  attnums = riinfo->pk_attnums;
2897  else
2898  attnums = riinfo->fk_attnums;
2899 
2900  /* XXX: could be worthwhile to fetch all necessary attrs at once */
2901  for (int i = 0; i < riinfo->nkeys; i++)
2902  {
2903  Datum oldvalue;
2904  Datum newvalue;
2905  bool isnull;
2906 
2907  /*
2908  * Get one attribute's oldvalue. If it is NULL - they're not equal.
2909  */
2910  oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
2911  if (isnull)
2912  return false;
2913 
2914  /*
2915  * Get one attribute's newvalue. If it is NULL - they're not equal.
2916  */
2917  newvalue = slot_getattr(newslot, attnums[i], &isnull);
2918  if (isnull)
2919  return false;
2920 
2921  if (rel_is_pk)
2922  {
2923  /*
2924  * If we are looking at the PK table, then do a bytewise
2925  * comparison. We must propagate PK changes if the value is
2926  * changed to one that "looks" different but would compare as
2927  * equal using the equality operator. This only makes a
2928  * difference for ON UPDATE CASCADE, but for consistency we treat
2929  * all changes to the PK the same.
2930  */
2931  Form_pg_attribute att = TupleDescAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
2932 
2933  if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
2934  return false;
2935  }
2936  else
2937  {
2938  Oid eq_opr;
2939 
2940  /*
2941  * When comparing the PERIOD columns we can skip the check
2942  * whenever the referencing column stayed equal or shrank, so test
2943  * with the contained-by operator instead.
2944  */
2945  if (riinfo->hasperiod && i == riinfo->nkeys - 1)
2946  eq_opr = riinfo->period_contained_by_oper;
2947  else
2948  eq_opr = riinfo->ff_eq_oprs[i];
2949 
2950  /*
2951  * For the FK table, compare with the appropriate equality
2952  * operator. Changes that compare equal will still satisfy the
2953  * constraint after the update.
2954  */
2955  if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]),
2956  newvalue, oldvalue))
2957  return false;
2958  }
2959  }
2960 
2961  return true;
2962 }
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Datum lhs, Datum rhs)
Definition: ri_triggers.c:2975
Oid period_contained_by_oper
Definition: ri_triggers.c:130
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:129
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by RI_FKey_fk_upd_check_required(), and RI_FKey_pk_upd_check_required().

◆ ri_LoadConstraintInfo()

static const RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2189 of file ri_triggers.c.

2190 {
2191  RI_ConstraintInfo *riinfo;
2192  bool found;
2193  HeapTuple tup;
2194  Form_pg_constraint conForm;
2195 
2196  /*
2197  * On the first call initialize the hashtable
2198  */
2199  if (!ri_constraint_cache)
2201 
2202  /*
2203  * Find or create a hash entry. If we find a valid one, just return it.
2204  */
2206  &constraintOid,
2207  HASH_ENTER, &found);
2208  if (!found)
2209  riinfo->valid = false;
2210  else if (riinfo->valid)
2211  return riinfo;
2212 
2213  /*
2214  * Fetch the pg_constraint row so we can fill in the entry.
2215  */
2216  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2217  if (!HeapTupleIsValid(tup)) /* should not happen */
2218  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2219  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2220 
2221  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2222  elog(ERROR, "constraint %u is not a foreign key constraint",
2223  constraintOid);
2224 
2225  /* And extract data */
2226  Assert(riinfo->constraint_id == constraintOid);
2227  if (OidIsValid(conForm->conparentid))
2228  riinfo->constraint_root_id =
2229  get_ri_constraint_root(conForm->conparentid);
2230  else
2231  riinfo->constraint_root_id = constraintOid;
2232  riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2233  ObjectIdGetDatum(constraintOid));
2234  riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2236  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2237  riinfo->pk_relid = conForm->confrelid;
2238  riinfo->fk_relid = conForm->conrelid;
2239  riinfo->confupdtype = conForm->confupdtype;
2240  riinfo->confdeltype = conForm->confdeltype;
2241  riinfo->confmatchtype = conForm->confmatchtype;
2242  riinfo->hasperiod = conForm->conperiod;
2243 
2245  &riinfo->nkeys,
2246  riinfo->fk_attnums,
2247  riinfo->pk_attnums,
2248  riinfo->pf_eq_oprs,
2249  riinfo->pp_eq_oprs,
2250  riinfo->ff_eq_oprs,
2251  &riinfo->ndelsetcols,
2252  riinfo->confdelsetcols);
2253 
2254  /*
2255  * For temporal FKs, get the operators and functions we need. We ask the
2256  * opclass of the PK element for these. This all gets cached (as does the
2257  * generated plan), so there's no performance issue.
2258  */
2259  if (riinfo->hasperiod)
2260  {
2261  Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2262 
2263  FindFKPeriodOpers(opclass,
2264  &riinfo->period_contained_by_oper,
2266  }
2267 
2268  ReleaseSysCache(tup);
2269 
2270  /*
2271  * For efficient processing of invalidation messages below, we keep a
2272  * doubly-linked count list of all currently valid entries.
2273  */
2275 
2276  riinfo->valid = true;
2277 
2278  return riinfo;
2279 }
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition: ilist.h:709
Oid get_index_column_opclass(Oid index_oid, int attno)
Definition: lsyscache.c:3512
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
void FindFKPeriodOpers(Oid opclass, Oid *containedbyoperoid, Oid *aggedcontainedbyoperoid)
static Oid get_ri_constraint_root(Oid constrOid)
Definition: ri_triggers.c:2286
dlist_node valid_link
Definition: ri_triggers.c:132
int16 confdelsetcols[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:120
Definition: c.h:732
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:118

References RI_ConstraintInfo::agged_period_contained_by_oper, Assert, RI_ConstraintInfo::confdelsetcols, RI_ConstraintInfo::confdeltype, RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::confupdtype, RI_ConstraintInfo::conname, RI_ConstraintInfo::constraint_id, RI_ConstraintInfo::constraint_root_id, dclist_push_tail(), DeconstructFkConstraintRow(), elog, ERROR, RI_ConstraintInfo::ff_eq_oprs, FindFKPeriodOpers(), RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, get_index_column_opclass(), get_ri_constraint_root(), GETSTRUCT, GetSysCacheHashValue1, HASH_ENTER, hash_search(), RI_ConstraintInfo::hasperiod, HeapTupleIsValid, RI_ConstraintInfo::ndelsetcols, RI_ConstraintInfo::nkeys, ObjectIdGetDatum(), RI_ConstraintInfo::oidHashValue, OidIsValid, RI_ConstraintInfo::period_contained_by_oper, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, RI_ConstraintInfo::pk_relid, RI_ConstraintInfo::pp_eq_oprs, ReleaseSysCache(), ri_constraint_cache, ri_constraint_cache_valid_list, ri_InitHashTables(), RI_ConstraintInfo::rootHashValue, SearchSysCache1(), RI_ConstraintInfo::valid, and RI_ConstraintInfo::valid_link.

Referenced by ri_FetchConstraintInfo().

◆ ri_NullCheck()

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

Definition at line 2728 of file ri_triggers.c.

2731 {
2732  const int16 *attnums;
2733  bool allnull = true;
2734  bool nonenull = true;
2735 
2736  if (rel_is_pk)
2737  attnums = riinfo->pk_attnums;
2738  else
2739  attnums = riinfo->fk_attnums;
2740 
2741  for (int i = 0; i < riinfo->nkeys; i++)
2742  {
2743  if (slot_attisnull(slot, attnums[i]))
2744  nonenull = false;
2745  else
2746  allnull = false;
2747  }
2748 
2749  if (allnull)
2750  return RI_KEYS_ALL_NULL;
2751 
2752  if (nonenull)
2753  return RI_KEYS_NONE_NULL;
2754 
2755  return RI_KEYS_SOME_NULL;
2756 }
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:381

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

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

◆ RI_PartitionRemove_Check()

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

Definition at line 1732 of file ri_triggers.c.

1733 {
1734  const RI_ConstraintInfo *riinfo;
1735  StringInfoData querybuf;
1736  char *constraintDef;
1737  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1738  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1739  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1740  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1741  const char *sep;
1742  const char *fk_only;
1743  int save_nestlevel;
1744  char workmembuf[32];
1745  int spi_result;
1746  SPIPlanPtr qplan;
1747  int i;
1748 
1749  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1750 
1751  /*
1752  * We don't check permissions before displaying the error message, on the
1753  * assumption that the user detaching the partition must have enough
1754  * privileges to examine the table contents anyhow.
1755  */
1756 
1757  /*----------
1758  * The query string built is:
1759  * SELECT fk.keycols FROM [ONLY] relname fk
1760  * JOIN pkrelname pk
1761  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1762  * WHERE (<partition constraint>) AND
1763  * For MATCH SIMPLE:
1764  * (fk.keycol1 IS NOT NULL [AND ...])
1765  * For MATCH FULL:
1766  * (fk.keycol1 IS NOT NULL [OR ...])
1767  *
1768  * We attach COLLATE clauses to the operators when comparing columns
1769  * that have different collations.
1770  *----------
1771  */
1772  initStringInfo(&querybuf);
1773  appendStringInfoString(&querybuf, "SELECT ");
1774  sep = "";
1775  for (i = 0; i < riinfo->nkeys; i++)
1776  {
1777  quoteOneName(fkattname,
1778  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1779  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1780  sep = ", ";
1781  }
1782 
1783  quoteRelationName(pkrelname, pk_rel);
1784  quoteRelationName(fkrelname, fk_rel);
1785  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1786  "" : "ONLY ";
1787  appendStringInfo(&querybuf,
1788  " FROM %s%s fk JOIN %s pk ON",
1789  fk_only, fkrelname, pkrelname);
1790  strcpy(pkattname, "pk.");
1791  strcpy(fkattname, "fk.");
1792  sep = "(";
1793  for (i = 0; i < riinfo->nkeys; i++)
1794  {
1795  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1796  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1797  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1798  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1799 
1800  quoteOneName(pkattname + 3,
1801  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1802  quoteOneName(fkattname + 3,
1803  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1804  ri_GenerateQual(&querybuf, sep,
1805  pkattname, pk_type,
1806  riinfo->pf_eq_oprs[i],
1807  fkattname, fk_type);
1808  if (pk_coll != fk_coll)
1809  ri_GenerateQualCollation(&querybuf, pk_coll);
1810  sep = "AND";
1811  }
1812 
1813  /*
1814  * Start the WHERE clause with the partition constraint (except if this is
1815  * the default partition and there's no other partition, because the
1816  * partition constraint is the empty string in that case.)
1817  */
1818  constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1819  if (constraintDef && constraintDef[0] != '\0')
1820  appendStringInfo(&querybuf, ") WHERE %s AND (",
1821  constraintDef);
1822  else
1823  appendStringInfoString(&querybuf, ") WHERE (");
1824 
1825  sep = "";
1826  for (i = 0; i < riinfo->nkeys; i++)
1827  {
1828  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1829  appendStringInfo(&querybuf,
1830  "%sfk.%s IS NOT NULL",
1831  sep, fkattname);
1832  switch (riinfo->confmatchtype)
1833  {
1834  case FKCONSTR_MATCH_SIMPLE:
1835  sep = " AND ";
1836  break;
1837  case FKCONSTR_MATCH_FULL:
1838  sep = " OR ";
1839  break;
1840  }
1841  }
1842  appendStringInfoChar(&querybuf, ')');
1843 
1844  /*
1845  * Temporarily increase work_mem so that the check query can be executed
1846  * more efficiently. It seems okay to do this because the query is simple
1847  * enough to not use a multiple of work_mem, and one typically would not
1848  * have many large foreign-key validations happening concurrently. So
1849  * this seems to meet the criteria for being considered a "maintenance"
1850  * operation, and accordingly we use maintenance_work_mem. However, we
1851  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1852  * let that get applied to the maintenance_work_mem value.
1853  *
1854  * We use the equivalent of a function SET option to allow the setting to
1855  * persist for exactly the duration of the check query. guc.c also takes
1856  * care of undoing the setting on error.
1857  */
1858  save_nestlevel = NewGUCNestLevel();
1859 
1860  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1861  (void) set_config_option("work_mem", workmembuf,
1863  GUC_ACTION_SAVE, true, 0, false);
1864  (void) set_config_option("hash_mem_multiplier", "1",
1866  GUC_ACTION_SAVE, true, 0, false);
1867 
1868  SPI_connect();
1869 
1870  /*
1871  * Generate the plan. We don't need to cache it, and there are no
1872  * arguments to the plan.
1873  */
1874  qplan = SPI_prepare(querybuf.data, 0, NULL);
1875 
1876  if (qplan == NULL)
1877  elog(ERROR, "SPI_prepare returned %s for %s",
1879 
1880  /*
1881  * Run the plan. For safety we force a current snapshot to be used. (In
1882  * transaction-snapshot mode, this arguably violates transaction isolation
1883  * rules, but we really haven't got much choice.) We don't need to
1884  * register the snapshot, because SPI_execute_snapshot will see to it. We
1885  * need at most one tuple returned, so pass limit = 1.
1886  */
1887  spi_result = SPI_execute_snapshot(qplan,
1888  NULL, NULL,
1891  true, false, 1);
1892 
1893  /* Check result */
1894  if (spi_result != SPI_OK_SELECT)
1895  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1896 
1897  /* Did we find a tuple that would violate the constraint? */
1898  if (SPI_processed > 0)
1899  {
1900  TupleTableSlot *slot;
1901  HeapTuple tuple = SPI_tuptable->vals[0];
1902  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1903  RI_ConstraintInfo fake_riinfo;
1904 
1905  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1906 
1907  heap_deform_tuple(tuple, tupdesc,
1908  slot->tts_values, slot->tts_isnull);
1909  ExecStoreVirtualTuple(slot);
1910 
1911  /*
1912  * The columns to look at in the result tuple are 1..N, not whatever
1913  * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1914  * will behave properly.
1915  *
1916  * In addition to this, we have to pass the correct tupdesc to
1917  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1918  * or fk_rel's tupdesc.
1919  */
1920  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1921  for (i = 0; i < fake_riinfo.nkeys; i++)
1922  fake_riinfo.pk_attnums[i] = i + 1;
1923 
1924  ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
1925  slot, tupdesc, 0, true);
1926  }
1927 
1928  if (SPI_finish() != SPI_OK_FINISH)
1929  elog(ERROR, "SPI_finish failed");
1930 
1931  /*
1932  * Restore work_mem and hash_mem_multiplier.
1933  */
1934  AtEOXact_GUC(true, save_nestlevel);
1935 }
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2122

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

Referenced by ATDetachCheckNoForeignKeyRefs().

◆ ri_PerformCheck()

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

Definition at line 2404 of file ri_triggers.c.

2409 {
2410  Relation query_rel,
2411  source_rel;
2412  bool source_is_pk;
2413  Snapshot test_snapshot;
2414  Snapshot crosscheck_snapshot;
2415  int limit;
2416  int spi_result;
2417  Oid save_userid;
2418  int save_sec_context;
2419  Datum vals[RI_MAX_NUMKEYS * 2];
2420  char nulls[RI_MAX_NUMKEYS * 2];
2421 
2422  /*
2423  * Use the query type code to determine whether the query is run against
2424  * the PK or FK table; we'll do the check as that table's owner
2425  */
2426  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2427  query_rel = pk_rel;
2428  else
2429  query_rel = fk_rel;
2430 
2431  /*
2432  * The values for the query are taken from the table on which the trigger
2433  * is called - it is normally the other one with respect to query_rel. An
2434  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2435  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2436  * need some less klugy way to determine this.
2437  */
2439  {
2440  source_rel = fk_rel;
2441  source_is_pk = false;
2442  }
2443  else
2444  {
2445  source_rel = pk_rel;
2446  source_is_pk = true;
2447  }
2448 
2449  /* Extract the parameters to be passed into the query */
2450  if (newslot)
2451  {
2452  ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2453  vals, nulls);
2454  if (oldslot)
2455  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2456  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2457  }
2458  else
2459  {
2460  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2461  vals, nulls);
2462  }
2463 
2464  /*
2465  * In READ COMMITTED mode, we just need to use an up-to-date regular
2466  * snapshot, and we will see all rows that could be interesting. But in
2467  * transaction-snapshot mode, we can't change the transaction snapshot. If
2468  * the caller passes detectNewRows == false then it's okay to do the query
2469  * with the transaction snapshot; otherwise we use a current snapshot, and
2470  * tell the executor to error out if it finds any rows under the current
2471  * snapshot that wouldn't be visible per the transaction snapshot. Note
2472  * that SPI_execute_snapshot will register the snapshots, so we don't need
2473  * to bother here.
2474  */
2475  if (IsolationUsesXactSnapshot() && detectNewRows)
2476  {
2477  CommandCounterIncrement(); /* be sure all my own work is visible */
2478  test_snapshot = GetLatestSnapshot();
2479  crosscheck_snapshot = GetTransactionSnapshot();
2480  }
2481  else
2482  {
2483  /* the default SPI behavior is okay */
2484  test_snapshot = InvalidSnapshot;
2485  crosscheck_snapshot = InvalidSnapshot;
2486  }
2487 
2488  /*
2489  * If this is a select query (e.g., for a 'no action' or 'restrict'
2490  * trigger), we only need to see if there is a single row in the table,
2491  * matching the key. Otherwise, limit = 0 - because we want the query to
2492  * affect ALL the matching rows.
2493  */
2494  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2495 
2496  /* Switch to proper UID to perform check as */
2497  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2498  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2499  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2501 
2502  /* Finally we can run the query. */
2503  spi_result = SPI_execute_snapshot(qplan,
2504  vals, nulls,
2505  test_snapshot, crosscheck_snapshot,
2506  false, false, limit);
2507 
2508  /* Restore UID and security context */
2509  SetUserIdAndSecContext(save_userid, save_sec_context);
2510 
2511  /* Check result */
2512  if (spi_result < 0)
2513  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2514 
2515  if (expect_OK >= 0 && spi_result != expect_OK)
2516  ereport(ERROR,
2517  (errcode(ERRCODE_INTERNAL_ERROR),
2518  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2519  RelationGetRelationName(pk_rel),
2520  NameStr(riinfo->conname),
2521  RelationGetRelationName(fk_rel)),
2522  errhint("This is most likely due to a rule having rewritten the query.")));
2523 
2524  /* XXX wouldn't it be clearer to do this part at the caller? */
2526  expect_OK == SPI_OK_SELECT &&
2528  ri_ReportViolation(riinfo,
2529  pk_rel, fk_rel,
2530  newslot ? newslot : oldslot,
2531  NULL,
2532  qkey->constr_queryno, false);
2533 
2534  return SPI_processed != 0;
2535 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:313
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
#define RelationGetForm(relation)
Definition: rel.h:499
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:73
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2541
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
int32 constr_queryno
Definition: ri_triggers.c:143
void CommandCounterIncrement(void)
Definition: xact.c:1099
#define IsolationUsesXactSnapshot()
Definition: xact.h:51

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

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

◆ ri_PlanCheck()

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

Definition at line 2361 of file ri_triggers.c.

2363 {
2364  SPIPlanPtr qplan;
2365  Relation query_rel;
2366  Oid save_userid;
2367  int save_sec_context;
2368 
2369  /*
2370  * Use the query type code to determine whether the query is run against
2371  * the PK or FK table; we'll do the check as that table's owner
2372  */
2373  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2374  query_rel = pk_rel;
2375  else
2376  query_rel = fk_rel;
2377 
2378  /* Switch to proper UID to perform check as */
2379  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2380  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2381  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2383 
2384  /* Create the plan */
2385  qplan = SPI_prepare(querystr, nargs, argtypes);
2386 
2387  if (qplan == NULL)
2388  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2389 
2390  /* Restore UID and security context */
2391  SetUserIdAndSecContext(save_userid, save_sec_context);
2392 
2393  /* Save the plan */
2394  SPI_keepplan(qplan);
2395  ri_HashPreparedPlan(qkey, qplan);
2396 
2397  return qplan;
2398 }
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2853
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:976

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

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

◆ ri_ReportViolation()

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

Definition at line 2570 of file ri_triggers.c.

2574 {
2575  StringInfoData key_names;
2576  StringInfoData key_values;
2577  bool onfk;
2578  const int16 *attnums;
2579  Oid rel_oid;
2580  AclResult aclresult;
2581  bool has_perm = true;
2582 
2583  /*
2584  * Determine which relation to complain about. If tupdesc wasn't passed
2585  * by caller, assume the violator tuple came from there.
2586  */
2587  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2588  if (onfk)
2589  {
2590  attnums = riinfo->fk_attnums;
2591  rel_oid = fk_rel->rd_id;
2592  if (tupdesc == NULL)
2593  tupdesc = fk_rel->rd_att;
2594  }
2595  else
2596  {
2597  attnums = riinfo->pk_attnums;
2598  rel_oid = pk_rel->rd_id;
2599  if (tupdesc == NULL)
2600  tupdesc = pk_rel->rd_att;
2601  }
2602 
2603  /*
2604  * Check permissions- if the user does not have access to view the data in
2605  * any of the key columns then we don't include the errdetail() below.
2606  *
2607  * Check if RLS is enabled on the relation first. If so, we don't return
2608  * any specifics to avoid leaking data.
2609  *
2610  * Check table-level permissions next and, failing that, column-level
2611  * privileges.
2612  *
2613  * When a partition at the referenced side is being detached/dropped, we
2614  * needn't check, since the user must be the table owner anyway.
2615  */
2616  if (partgone)
2617  has_perm = true;
2618  else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2619  {
2620  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2621  if (aclresult != ACLCHECK_OK)
2622  {
2623  /* Try for column-level permissions */
2624  for (int idx = 0; idx < riinfo->nkeys; idx++)
2625  {
2626  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2627  GetUserId(),
2628  ACL_SELECT);
2629 
2630  /* No access to the key */
2631  if (aclresult != ACLCHECK_OK)
2632  {
2633  has_perm = false;
2634  break;
2635  }
2636  }
2637  }
2638  }
2639  else
2640  has_perm = false;
2641 
2642  if (has_perm)
2643  {
2644  /* Get printable versions of the keys involved */
2645  initStringInfo(&key_names);
2646  initStringInfo(&key_values);
2647  for (int idx = 0; idx < riinfo->nkeys; idx++)
2648  {
2649  int fnum = attnums[idx];
2650  Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2651  char *name,
2652  *val;
2653  Datum datum;
2654  bool isnull;
2655 
2656  name = NameStr(att->attname);
2657 
2658  datum = slot_getattr(violatorslot, fnum, &isnull);
2659  if (!isnull)
2660  {
2661  Oid foutoid;
2662  bool typisvarlena;
2663 
2664  getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2665  val = OidOutputFunctionCall(foutoid, datum);
2666  }
2667  else
2668  val = "null";
2669 
2670  if (idx > 0)
2671  {
2672  appendStringInfoString(&key_names, ", ");
2673  appendStringInfoString(&key_values, ", ");
2674  }
2675  appendStringInfoString(&key_names, name);
2676  appendStringInfoString(&key_values, val);
2677  }
2678  }
2679 
2680  if (partgone)
2681  ereport(ERROR,
2682  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2683  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2684  RelationGetRelationName(pk_rel),
2685  NameStr(riinfo->conname)),
2686  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2687  key_names.data, key_values.data,
2688  RelationGetRelationName(fk_rel)),
2689  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2690  else if (onfk)
2691  ereport(ERROR,
2692  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2693  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2694  RelationGetRelationName(fk_rel),
2695  NameStr(riinfo->conname)),
2696  has_perm ?
2697  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2698  key_names.data, key_values.data,
2699  RelationGetRelationName(pk_rel)) :
2700  errdetail("Key is not present in table \"%s\".",
2701  RelationGetRelationName(pk_rel)),
2702  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2703  else
2704  ereport(ERROR,
2705  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2706  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2707  RelationGetRelationName(pk_rel),
2708  NameStr(riinfo->conname),
2709  RelationGetRelationName(fk_rel)),
2710  has_perm ?
2711  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2712  key_names.data, key_values.data,
2713  RelationGetRelationName(fk_rel)) :
2714  errdetail("Key is still referenced from table \"%s\".",
2715  RelationGetRelationName(fk_rel)),
2716  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2717 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3923
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4094
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
long val
Definition: informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
TupleDesc rd_att
Definition: rel.h:112
Oid rd_id
Definition: rel.h:113

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

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

◆ ri_restrict()

static Datum ri_restrict ( TriggerData trigdata,
bool  is_no_action 
)
static

Definition at line 707 of file ri_triggers.c.

708 {
709  const RI_ConstraintInfo *riinfo;
710  Relation fk_rel;
711  Relation pk_rel;
712  TupleTableSlot *oldslot;
713  RI_QueryKey qkey;
714  SPIPlanPtr qplan;
715 
716  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
717  trigdata->tg_relation, true);
718 
719  /*
720  * Get the relation descriptors of the FK and PK tables and the old tuple.
721  *
722  * fk_rel is opened in RowShareLock mode since that's what our eventual
723  * SELECT FOR KEY SHARE will get on it.
724  */
725  fk_rel = table_open(riinfo->fk_relid, RowShareLock);
726  pk_rel = trigdata->tg_relation;
727  oldslot = trigdata->tg_trigslot;
728 
729  /*
730  * If another PK row now exists providing the old key values, we should
731  * not do anything. However, this check should only be made in the NO
732  * ACTION case; in RESTRICT cases we don't wish to allow another row to be
733  * substituted.
734  */
735  if (is_no_action &&
736  ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
737  {
738  table_close(fk_rel, RowShareLock);
739  return PointerGetDatum(NULL);
740  }
741 
742  SPI_connect();
743 
744  /*
745  * Fetch or prepare a saved plan for the restrict lookup (it's the same
746  * query for delete and update cases)
747  */
748  ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_RESTRICT);
749 
750  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
751  {
752  StringInfoData querybuf;
753  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
755  char paramname[16];
756  const char *querysep;
757  Oid queryoids[RI_MAX_NUMKEYS];
758  const char *fk_only;
759 
760  /* ----------
761  * The query string built is
762  * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
763  * FOR KEY SHARE OF x
764  * The type id's for the $ parameters are those of the
765  * corresponding PK attributes.
766  * ----------
767  */
768  initStringInfo(&querybuf);
769  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
770  "" : "ONLY ";
771  quoteRelationName(fkrelname, fk_rel);
772  appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
773  fk_only, fkrelname);
774  querysep = "WHERE";
775  for (int i = 0; i < riinfo->nkeys; i++)
776  {
777  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
778  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
779  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
780  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
781 
783  RIAttName(fk_rel, riinfo->fk_attnums[i]));
784  sprintf(paramname, "$%d", i + 1);
785  ri_GenerateQual(&querybuf, querysep,
786  paramname, pk_type,
787  riinfo->pf_eq_oprs[i],
788  attname, fk_type);
789  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
790  ri_GenerateQualCollation(&querybuf, pk_coll);
791  querysep = "AND";
792  queryoids[i] = pk_type;
793  }
794  appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
795 
796  /* Prepare and save the plan */
797  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
798  &qkey, fk_rel, pk_rel);
799  }
800 
801  /*
802  * We have a plan now. Run it to check for existing references.
803  */
804  ri_PerformCheck(riinfo, &qkey, qplan,
805  fk_rel, pk_rel,
806  oldslot, NULL,
807  true, /* must detect new rows */
808  SPI_OK_SELECT);
809 
810  if (SPI_finish() != SPI_OK_FINISH)
811  elog(ERROR, "SPI_finish failed");
812 
813  table_close(fk_rel, RowShareLock);
814 
815  return PointerGetDatum(NULL);
816 }
#define RI_PLAN_RESTRICT
Definition: ri_triggers.c:78
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:507

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

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

◆ ri_set()

static Datum ri_set ( TriggerData trigdata,
bool  is_set_null,
int  tgkind 
)
static

Definition at line 1111 of file ri_triggers.c.

1112 {
1113  const RI_ConstraintInfo *riinfo;
1114  Relation fk_rel;
1115  Relation pk_rel;
1116  TupleTableSlot *oldslot;
1117  RI_QueryKey qkey;
1118  SPIPlanPtr qplan;
1119  int32 queryno;
1120 
1121  riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1122  trigdata->tg_relation, true);
1123 
1124  /*
1125  * Get the relation descriptors of the FK and PK tables and the old tuple.
1126  *
1127  * fk_rel is opened in RowExclusiveLock mode since that's what our
1128  * eventual UPDATE will get on it.
1129  */
1130  fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1131  pk_rel = trigdata->tg_relation;
1132  oldslot = trigdata->tg_trigslot;
1133 
1134  SPI_connect();
1135 
1136  /*
1137  * Fetch or prepare a saved plan for the trigger.
1138  */
1139  switch (tgkind)
1140  {
1141  case RI_TRIGTYPE_UPDATE:
1142  queryno = is_set_null
1145  break;
1146  case RI_TRIGTYPE_DELETE:
1147  queryno = is_set_null
1150  break;
1151  default:
1152  elog(ERROR, "invalid tgkind passed to ri_set");
1153  }
1154 
1155  ri_BuildQueryKey(&qkey, riinfo, queryno);
1156 
1157  if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1158  {
1159  StringInfoData querybuf;
1160  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1162  char paramname[16];
1163  const char *querysep;
1164  const char *qualsep;
1165  Oid queryoids[RI_MAX_NUMKEYS];
1166  const char *fk_only;
1167  int num_cols_to_set;
1168  const int16 *set_cols;
1169 
1170  switch (tgkind)
1171  {
1172  case RI_TRIGTYPE_UPDATE:
1173  num_cols_to_set = riinfo->nkeys;
1174  set_cols = riinfo->fk_attnums;
1175  break;
1176  case RI_TRIGTYPE_DELETE:
1177 
1178  /*
1179  * If confdelsetcols are present, then we only update the
1180  * columns specified in that array, otherwise we update all
1181  * the referencing columns.
1182  */
1183  if (riinfo->ndelsetcols != 0)
1184  {
1185  num_cols_to_set = riinfo->ndelsetcols;
1186  set_cols = riinfo->confdelsetcols;
1187  }
1188  else
1189  {
1190  num_cols_to_set = riinfo->nkeys;
1191  set_cols = riinfo->fk_attnums;
1192  }
1193  break;
1194  default:
1195  elog(ERROR, "invalid tgkind passed to ri_set");
1196  }
1197 
1198  /* ----------
1199  * The query string built is
1200  * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1201  * WHERE $1 = fkatt1 [AND ...]
1202  * The type id's for the $ parameters are those of the
1203  * corresponding PK attributes.
1204  * ----------
1205  */
1206  initStringInfo(&querybuf);
1207  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1208  "" : "ONLY ";
1209  quoteRelationName(fkrelname, fk_rel);
1210  appendStringInfo(&querybuf, "UPDATE %s%s SET",
1211  fk_only, fkrelname);
1212 
1213  /*
1214  * Add assignment clauses
1215  */
1216  querysep = "";
1217  for (int i = 0; i < num_cols_to_set; i++)
1218  {
1219  quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
1220  appendStringInfo(&querybuf,
1221  "%s %s = %s",
1222  querysep, attname,
1223  is_set_null ? "NULL" : "DEFAULT");
1224  querysep = ",";
1225  }
1226 
1227  /*
1228  * Add WHERE clause
1229  */
1230  qualsep = "WHERE";
1231  for (int i = 0; i < riinfo->nkeys; i++)
1232  {
1233  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1234  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1235  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1236  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1237 
1239  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1240 
1241  sprintf(paramname, "$%d", i + 1);
1242  ri_GenerateQual(&querybuf, qualsep,
1243  paramname, pk_type,
1244  riinfo->pf_eq_oprs[i],
1245  attname, fk_type);
1246  if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
1247  ri_GenerateQualCollation(&querybuf, pk_coll);
1248  qualsep = "AND";
1249  queryoids[i] = pk_type;
1250  }
1251 
1252  /* Prepare and save the plan */
1253  qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1254  &qkey, fk_rel, pk_rel);
1255  }
1256 
1257  /*
1258  * We have a plan now. Run it to update the existing references.
1259  */
1260  ri_PerformCheck(riinfo, &qkey, qplan,
1261  fk_rel, pk_rel,
1262  oldslot, NULL,
1263  true, /* must detect new rows */
1264  SPI_OK_UPDATE);
1265 
1266  if (SPI_finish() != SPI_OK_FINISH)
1267  elog(ERROR, "SPI_finish failed");
1268 
1269  table_close(fk_rel, RowExclusiveLock);
1270 
1271  if (is_set_null)
1272  return PointerGetDatum(NULL);
1273  else
1274  {
1275  /*
1276  * If we just deleted or updated the PK row whose key was equal to the
1277  * FK columns' default values, and a referencing row exists in the FK
1278  * table, we would have updated that row to the same values it already
1279  * had --- and RI_FKey_fk_upd_check_required would hence believe no
1280  * check is necessary. So we need to do another lookup now and in
1281  * case a reference still exists, abort the operation. That is
1282  * already implemented in the NO ACTION trigger, so just run it. (This
1283  * recheck is only needed in the SET DEFAULT case, since CASCADE would
1284  * remove such rows in case of a DELETE operation or would change the
1285  * FK key values in case of an UPDATE, while SET NULL is certain to
1286  * result in rows that satisfy the FK constraint.)
1287  */
1288  return ri_restrict(trigdata, true);
1289  }
1290 }
signed int int32
Definition: c.h:496
#define RI_PLAN_SETNULL_ONUPDATE
Definition: ri_triggers.c:80
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition: ri_triggers.c:81
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition: ri_triggers.c:82
#define RI_PLAN_SETNULL_ONDELETE
Definition: ri_triggers.c:79

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

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

Variable Documentation

◆ ri_compare_cache

HTAB* ri_compare_cache = NULL
static

Definition at line 183 of file ri_triggers.c.

Referenced by ri_HashCompareOp(), and ri_InitHashTables().

◆ ri_constraint_cache

HTAB* ri_constraint_cache = NULL
static

◆ ri_constraint_cache_valid_list

dclist_head ri_constraint_cache_valid_list
static

Definition at line 184 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 182 of file ri_triggers.c.

Referenced by ri_FetchPreparedPlan(), ri_HashPreparedPlan(), and ri_InitHashTables().