PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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_NO_ACTION   5
 
#define RI_PLAN_RESTRICT   6
 
#define RI_PLAN_SETNULL_ONDELETE   7
 
#define RI_PLAN_SETNULL_ONUPDATE   8
 
#define RI_PLAN_SETDEFAULT_ONDELETE   9
 
#define RI_PLAN_SETDEFAULT_ONUPDATE   10
 
#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)
 
#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)
 
#define RIAttName(rel, attnum)   NameStr(*attnumAttName(rel, attnum))
 
#define RIAttType(rel, attnum)   attnumTypeId(rel, attnum)
 
#define RIAttCollation(rel, attnum)   attnumCollationId(rel, attnum)
 
#define RI_TRIGTYPE_INSERT   1
 
#define RI_TRIGTYPE_UPDATE   2
 
#define RI_TRIGTYPE_DELETE   3
 

Typedefs

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

Functions

static bool ri_Check_Pk_Match (Relation pk_rel, Relation fk_rel, 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, Oid collid, 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 is_restrict, 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 pg_noreturn void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
 
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 85 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 86 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_NO_ACTION

#define RI_PLAN_NO_ACTION   5

Definition at line 77 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   6

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   9

Definition at line 82 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   10

Definition at line 83 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   7

Definition at line 80 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   8

Definition at line 81 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 94 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 92 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 93 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 90 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 88 of file ri_triggers.c.

◆ RIAttType

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

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

2367{
2368 for (;;)
2369 {
2370 HeapTuple tuple;
2371 Oid constrParentOid;
2372
2373 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2374 if (!HeapTupleIsValid(tuple))
2375 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2376 constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2377 ReleaseSysCache(tuple);
2378 if (!OidIsValid(constrParentOid))
2379 break; /* we reached the root constraint */
2380 constrOid = constrParentOid;
2381 }
2382 return constrOid;
2383}
#define OidIsValid(objectId)
Definition: c.h:746
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
unsigned int Oid
Definition: postgres_ext.h:30
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 2400 of file ri_triggers.c.

2401{
2402 dlist_mutable_iter iter;
2403
2404 Assert(ri_constraint_cache != NULL);
2405
2406 /*
2407 * If the list of currently valid entries gets excessively large, we mark
2408 * them all invalid so we can empty the list. This arrangement avoids
2409 * O(N^2) behavior in situations where a session touches many foreign keys
2410 * and also does many ALTER TABLEs, such as a restore from pg_dump.
2411 */
2413 hashvalue = 0; /* pretend it's a cache reset */
2414
2416 {
2418 valid_link, iter.cur);
2419
2420 /*
2421 * We must invalidate not only entries directly matching the given
2422 * hash value, but also child entries, in case the invalidation
2423 * affects a root constraint.
2424 */
2425 if (hashvalue == 0 ||
2426 riinfo->oidHashValue == hashvalue ||
2427 riinfo->rootHashValue == hashvalue)
2428 {
2429 riinfo->valid = false;
2430 /* Remove invalidated entries from the list, too */
2432 }
2433 }
2434}
Assert(PointerIsAligned(start, uint64))
#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:186
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:183
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 2031 of file ri_triggers.c.

2032{
2033 /* Rather than trying to be smart, just always quote it. */
2034 *buffer++ = '"';
2035 while (*name)
2036 {
2037 if (*name == '"')
2038 *buffer++ = '"';
2039 *buffer++ = *name++;
2040 }
2041 *buffer++ = '"';
2042 *buffer = '\0';
2043}
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 2051 of file ri_triggers.c.

2052{
2054 buffer += strlen(buffer);
2055 *buffer++ = '.';
2057}
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3506
#define RelationGetRelationName(relation)
Definition: rel.h:550
#define RelationGetNamespace(relation)
Definition: rel.h:557
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2031

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

2138{
2139 /*
2140 * Inherited constraints with a common ancestor can share ri_query_cache
2141 * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2142 * Except in that case, the query processes the other table involved in
2143 * the FK constraint (i.e., not the table on which the trigger has been
2144 * fired), and so it will be the same for all members of the inheritance
2145 * tree. So we may use the root constraint's OID in the hash key, rather
2146 * than the constraint's own OID. This avoids creating duplicate SPI
2147 * plans, saving lots of work and memory when there are many partitions
2148 * with similar FK constraints.
2149 *
2150 * (Note that we must still have a separate RI_ConstraintInfo for each
2151 * constraint, because partitions can have different column orders,
2152 * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2153 *
2154 * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2155 * to use memset to clear them.
2156 */
2157 if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2158 key->constr_id = riinfo->constraint_root_id;
2159 else
2160 key->constr_id = riinfo->constraint_id;
2161 key->constr_queryno = constr_queryno;
2162}
#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 511 of file ri_triggers.c.

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

2169{
2170 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2171
2172 if (!CALLED_AS_TRIGGER(fcinfo))
2173 ereport(ERROR,
2174 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2175 errmsg("function \"%s\" was not called by trigger manager", funcname)));
2176
2177 /*
2178 * Check proper event
2179 */
2180 if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2181 !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2182 ereport(ERROR,
2183 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2184 errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2185
2186 switch (tgkind)
2187 {
2188 case RI_TRIGTYPE_INSERT:
2189 if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2190 ereport(ERROR,
2191 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2192 errmsg("function \"%s\" must be fired for INSERT", funcname)));
2193 break;
2194 case RI_TRIGTYPE_UPDATE:
2195 if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2196 ereport(ERROR,
2197 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2198 errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2199 break;
2200 case RI_TRIGTYPE_DELETE:
2201 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2202 ereport(ERROR,
2203 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2204 errmsg("function \"%s\" must be fired for DELETE", funcname)));
2205 break;
2206 }
2207}
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ereport(elevel,...)
Definition: elog.h:149
#define funcname
Definition: indent_codes.h:69
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:92
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:94
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:93
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,
Oid  collid,
Datum  lhs,
Datum  rhs 
)
static

Definition at line 3071 of file ri_triggers.c.

3073{
3074 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3075
3076 /* Do we need to cast the values? */
3077 if (OidIsValid(entry->cast_func_finfo.fn_oid))
3078 {
3079 lhs = FunctionCall3(&entry->cast_func_finfo,
3080 lhs,
3081 Int32GetDatum(-1), /* typmod */
3082 BoolGetDatum(false)); /* implicit coercion */
3083 rhs = FunctionCall3(&entry->cast_func_finfo,
3084 rhs,
3085 Int32GetDatum(-1), /* typmod */
3086 BoolGetDatum(false)); /* implicit coercion */
3087 }
3088
3089 /*
3090 * Apply the comparison operator.
3091 *
3092 * Note: This function is part of a call stack that determines whether an
3093 * update to a row is significant enough that it needs checking or action
3094 * on the other side of a foreign-key constraint. Therefore, the
3095 * comparison here would need to be done with the collation of the *other*
3096 * table. For simplicity (e.g., we might not even have the other table
3097 * open), we'll use our own collation. This is fine because we require
3098 * that both collations have the same notion of equality (either they are
3099 * both deterministic or else they are both the same).
3100 *
3101 * With range/multirangetypes, the collation of the base type is stored as
3102 * part of the rangetype (pg_range.rngcollation), and always used, so
3103 * there is no danger of inconsistency even using a non-equals operator.
3104 * But if we support arbitrary types with PERIOD, we should perhaps just
3105 * always force a re-check.
3106 */
3107 return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
3108}
Oid collid
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:704
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3117
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:176

References BoolGetDatum(), RI_CompareHashEntry::cast_func_finfo, collid, 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 2622 of file ri_triggers.c.

2625{
2626 const int16 *attnums;
2627 bool isnull;
2628
2629 if (rel_is_pk)
2630 attnums = riinfo->pk_attnums;
2631 else
2632 attnums = riinfo->fk_attnums;
2633
2634 for (int i = 0; i < riinfo->nkeys; i++)
2635 {
2636 vals[i] = slot_getattr(slot, attnums[i], &isnull);
2637 nulls[i] = isnull ? 'n' : ' ';
2638 }
2639}
int16_t int16
Definition: c.h:497
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:399

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

2215{
2216 Oid constraintOid = trigger->tgconstraint;
2217 const RI_ConstraintInfo *riinfo;
2218
2219 /*
2220 * Check that the FK constraint's OID is available; it might not be if
2221 * we've been invoked via an ordinary trigger or an old-style "constraint
2222 * trigger".
2223 */
2224 if (!OidIsValid(constraintOid))
2225 ereport(ERROR,
2226 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2227 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2228 trigger->tgname, RelationGetRelationName(trig_rel)),
2229 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2230
2231 /* Find or create a hashtable entry for the constraint */
2232 riinfo = ri_LoadConstraintInfo(constraintOid);
2233
2234 /* Do some easy cross-checks against the trigger call data */
2235 if (rel_is_pk)
2236 {
2237 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2238 riinfo->pk_relid != RelationGetRelid(trig_rel))
2239 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2240 trigger->tgname, RelationGetRelationName(trig_rel));
2241 }
2242 else
2243 {
2244 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2245 riinfo->pk_relid != trigger->tgconstrrelid)
2246 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2247 trigger->tgname, RelationGetRelationName(trig_rel));
2248 }
2249
2250 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2253 elog(ERROR, "unrecognized confmatchtype: %d",
2254 riinfo->confmatchtype);
2255
2257 ereport(ERROR,
2258 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2259 errmsg("MATCH PARTIAL not yet implemented")));
2260
2261 return riinfo;
2262}
int errhint(const char *fmt,...)
Definition: elog.c:1318
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2817
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2816
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2815
#define RelationGetRelid(relation)
Definition: rel.h:516
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2268
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 2896 of file ri_triggers.c.

2897{
2898 RI_QueryHashEntry *entry;
2900
2901 /*
2902 * On the first call initialize the hashtable
2903 */
2904 if (!ri_query_cache)
2906
2907 /*
2908 * Lookup for the key
2909 */
2911 key,
2912 HASH_FIND, NULL);
2913 if (entry == NULL)
2914 return NULL;
2915
2916 /*
2917 * Check whether the plan is still valid. If it isn't, we don't want to
2918 * simply rely on plancache.c to regenerate it; rather we should start
2919 * from scratch and rebuild the query text too. This is to cover cases
2920 * such as table/column renames. We depend on the plancache machinery to
2921 * detect possible invalidations, though.
2922 *
2923 * CAUTION: this check is only trustworthy if the caller has already
2924 * locked both FK and PK rels.
2925 */
2926 plan = entry->plan;
2927 if (plan && SPI_plan_is_valid(plan))
2928 return plan;
2929
2930 /*
2931 * Otherwise we might as well flush the cached plan now, to free a little
2932 * memory space before we make a new one.
2933 */
2934 entry->plan = NULL;
2935 if (plan)
2937
2938 return NULL;
2939}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:956
@ HASH_FIND
Definition: hsearch.h:113
#define plan(x)
Definition: pg_regress.c:161
static HTAB * ri_query_cache
Definition: ri_triggers.c:184
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2860
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1950
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:1026
SPIPlanPtr plan
Definition: ri_triggers.c:154

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

916{
917 TriggerData *trigdata = (TriggerData *) fcinfo->context;
918 const RI_ConstraintInfo *riinfo;
919 Relation fk_rel;
920 Relation pk_rel;
921 TupleTableSlot *oldslot;
922 RI_QueryKey qkey;
923 SPIPlanPtr qplan;
924
925 /* Check that this is a valid trigger call on the right time and event. */
926 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
927
928 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
929 trigdata->tg_relation, true);
930
931 /*
932 * Get the relation descriptors of the FK and PK tables and the old tuple.
933 *
934 * fk_rel is opened in RowExclusiveLock mode since that's what our
935 * eventual DELETE will get on it.
936 */
937 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
938 pk_rel = trigdata->tg_relation;
939 oldslot = trigdata->tg_trigslot;
940
941 SPI_connect();
942
943 /* Fetch or prepare a saved plan for the cascaded delete */
945
946 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
947 {
948 StringInfoData querybuf;
949 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
951 char paramname[16];
952 const char *querysep;
953 Oid queryoids[RI_MAX_NUMKEYS];
954 const char *fk_only;
955
956 /* ----------
957 * The query string built is
958 * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
959 * The type id's for the $ parameters are those of the
960 * corresponding PK attributes.
961 * ----------
962 */
963 initStringInfo(&querybuf);
964 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
965 "" : "ONLY ";
966 quoteRelationName(fkrelname, fk_rel);
967 appendStringInfo(&querybuf, "DELETE FROM %s%s",
968 fk_only, fkrelname);
969 querysep = "WHERE";
970 for (int i = 0; i < riinfo->nkeys; i++)
971 {
972 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
973 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
974
976 RIAttName(fk_rel, riinfo->fk_attnums[i]));
977 sprintf(paramname, "$%d", i + 1);
978 ri_GenerateQual(&querybuf, querysep,
979 paramname, pk_type,
980 riinfo->pf_eq_oprs[i],
981 attname, fk_type);
982 querysep = "AND";
983 queryoids[i] = pk_type;
984 }
985
986 /* Prepare and save the plan */
987 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
988 &qkey, fk_rel, pk_rel);
989 }
990
991 /*
992 * We have a plan now. Build up the arguments from the key values in the
993 * deleted PK tuple and delete the referencing rows
994 */
995 ri_PerformCheck(riinfo, &qkey, qplan,
996 fk_rel, pk_rel,
997 oldslot, NULL,
998 false,
999 true, /* must detect new rows */
1001
1002 if (SPI_finish() != SPI_OK_FINISH)
1003 elog(ERROR, "SPI_finish failed");
1004
1006
1007 return PointerGetDatum(NULL);
1008}
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2214
#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:2168
#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, 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_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONDELETE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, 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 1017 of file ri_triggers.c.

1018{
1019 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1020 const RI_ConstraintInfo *riinfo;
1021 Relation fk_rel;
1022 Relation pk_rel;
1023 TupleTableSlot *newslot;
1024 TupleTableSlot *oldslot;
1025 RI_QueryKey qkey;
1026 SPIPlanPtr qplan;
1027
1028 /* Check that this is a valid trigger call on the right time and event. */
1029 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1030
1031 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1032 trigdata->tg_relation, true);
1033
1034 /*
1035 * Get the relation descriptors of the FK and PK tables and the new and
1036 * old tuple.
1037 *
1038 * fk_rel is opened in RowExclusiveLock mode since that's what our
1039 * eventual UPDATE will get on it.
1040 */
1041 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1042 pk_rel = trigdata->tg_relation;
1043 newslot = trigdata->tg_newslot;
1044 oldslot = trigdata->tg_trigslot;
1045
1046 SPI_connect();
1047
1048 /* Fetch or prepare a saved plan for the cascaded update */
1050
1051 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1052 {
1053 StringInfoData querybuf;
1054 StringInfoData qualbuf;
1055 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1057 char paramname[16];
1058 const char *querysep;
1059 const char *qualsep;
1060 Oid queryoids[RI_MAX_NUMKEYS * 2];
1061 const char *fk_only;
1062
1063 /* ----------
1064 * The query string built is
1065 * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1066 * WHERE $n = fkatt1 [AND ...]
1067 * The type id's for the $ parameters are those of the
1068 * corresponding PK attributes. Note that we are assuming
1069 * there is an assignment cast from the PK to the FK type;
1070 * else the parser will fail.
1071 * ----------
1072 */
1073 initStringInfo(&querybuf);
1074 initStringInfo(&qualbuf);
1075 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1076 "" : "ONLY ";
1077 quoteRelationName(fkrelname, fk_rel);
1078 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1079 fk_only, fkrelname);
1080 querysep = "";
1081 qualsep = "WHERE";
1082 for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1083 {
1084 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1085 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1086
1088 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1089 appendStringInfo(&querybuf,
1090 "%s %s = $%d",
1091 querysep, attname, i + 1);
1092 sprintf(paramname, "$%d", j + 1);
1093 ri_GenerateQual(&qualbuf, qualsep,
1094 paramname, pk_type,
1095 riinfo->pf_eq_oprs[i],
1096 attname, fk_type);
1097 querysep = ",";
1098 qualsep = "AND";
1099 queryoids[i] = pk_type;
1100 queryoids[j] = pk_type;
1101 }
1102 appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
1103
1104 /* Prepare and save the plan */
1105 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1106 &qkey, fk_rel, pk_rel);
1107 }
1108
1109 /*
1110 * We have a plan now. Run it to update the existing references.
1111 */
1112 ri_PerformCheck(riinfo, &qkey, qplan,
1113 fk_rel, pk_rel,
1114 oldslot, newslot,
1115 false,
1116 true, /* must detect new rows */
1118
1119 if (SPI_finish() != SPI_OK_FINISH)
1120 elog(ERROR, "SPI_finish failed");
1121
1123
1124 return PointerGetDatum(NULL);
1125}
int j
Definition: isn.c:78
#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:281
TupleTableSlot * tg_newslot
Definition: trigger.h:40

References appendBinaryStringInfo(), appendStringInfo(), attname, StringInfoData::data, elog, ERROR, 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_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_CASCADE_ONUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, 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 250 of file ri_triggers.c.

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

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

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

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

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

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

1420{
1421 const RI_ConstraintInfo *riinfo;
1422 int ri_nullcheck;
1423
1424 /*
1425 * AfterTriggerSaveEvent() handles things such that this function is never
1426 * called for partitioned tables.
1427 */
1428 Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1429
1430 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1431
1432 ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1433
1434 /*
1435 * If all new key values are NULL, the row satisfies the constraint, so no
1436 * check is needed.
1437 */
1438 if (ri_nullcheck == RI_KEYS_ALL_NULL)
1439 return false;
1440
1441 /*
1442 * If some new key values are NULL, the behavior depends on the match
1443 * type.
1444 */
1445 else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1446 {
1447 switch (riinfo->confmatchtype)
1448 {
1450
1451 /*
1452 * If any new key value is NULL, the row must satisfy the
1453 * constraint, so no check is needed.
1454 */
1455 return false;
1456
1458
1459 /*
1460 * Don't know, must run full check.
1461 */
1462 break;
1463
1465
1466 /*
1467 * If some new key values are NULL, the row fails the
1468 * constraint. We must not throw error here, because the row
1469 * might get invalidated before the constraint is to be
1470 * checked, but we should queue the event to apply the check
1471 * later.
1472 */
1473 return true;
1474 }
1475 }
1476
1477 /*
1478 * Continues here for no new key values are NULL, or we couldn't decide
1479 * yet.
1480 */
1481
1482 /*
1483 * If the original row was inserted by our own transaction, we must fire
1484 * the trigger whether or not the keys are equal. This is because our
1485 * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1486 * not do anything; so we had better do the UPDATE check. (We could skip
1487 * this if we knew the INSERT trigger already fired, but there is no easy
1488 * way to know that.)
1489 */
1490 if (slot_is_current_xact_tuple(oldslot))
1491 return true;
1492
1493 /* If all old and new key values are equal, no check is needed */
1494 if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1495 return false;
1496
1497 /* Else we need to fire the trigger. */
1498 return true;
1499}
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2985
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition: tuptable.h:449

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

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

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 676 of file ri_triggers.c.

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

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

1388{
1389 const RI_ConstraintInfo *riinfo;
1390
1391 riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1392
1393 /*
1394 * If any old key value is NULL, the row could not have been referenced by
1395 * an FK row, so no check is needed.
1396 */
1397 if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1398 return false;
1399
1400 /* If all old and new key values are equal, no check is needed */
1401 if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1402 return false;
1403
1404 /* Else we need to fire the trigger. */
1405 return true;
1406}

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

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

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 696 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1164 of file ri_triggers.c.

1165{
1166 /* Check that this is a valid trigger call on the right time and event. */
1167 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1168
1169 /* Share code with UPDATE case */
1170 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1171}
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
Definition: ri_triggers.c:1195

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1179 of file ri_triggers.c.

1180{
1181 /* Check that this is a valid trigger call on the right time and event. */
1182 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1183
1184 /* Share code with DELETE case */
1185 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1186}

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1134 of file ri_triggers.c.

1135{
1136 /* Check that this is a valid trigger call on the right time and event. */
1137 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1138
1139 /* Share code with UPDATE case */
1140 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1141}

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1149 of file ri_triggers.c.

1150{
1151 /* Check that this is a valid trigger call on the right time and event. */
1152 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1153
1154 /* Share code with DELETE case */
1155 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1156}

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3210 of file ri_triggers.c.

3211{
3212 switch (tgfoid)
3213 {
3214 case F_RI_FKEY_CASCADE_DEL:
3215 case F_RI_FKEY_CASCADE_UPD:
3216 case F_RI_FKEY_RESTRICT_DEL:
3217 case F_RI_FKEY_RESTRICT_UPD:
3218 case F_RI_FKEY_SETNULL_DEL:
3219 case F_RI_FKEY_SETNULL_UPD:
3220 case F_RI_FKEY_SETDEFAULT_DEL:
3221 case F_RI_FKEY_SETDEFAULT_UPD:
3222 case F_RI_FKEY_NOACTION_DEL:
3223 case F_RI_FKEY_NOACTION_UPD:
3224 return RI_TRIGGER_PK;
3225
3226 case F_RI_FKEY_CHECK_INS:
3227 case F_RI_FKEY_CHECK_UPD:
3228 return RI_TRIGGER_FK;
3229 }
3230
3231 return RI_TRIGGER_NONE;
3232}
#define RI_TRIGGER_FK
Definition: trigger.h:284
#define RI_TRIGGER_NONE
Definition: trigger.h:285
#define RI_TRIGGER_PK
Definition: trigger.h:283

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

2073{
2074 appendStringInfo(buf, " %s ", sep);
2075 generate_operator_clause(buf, leftop, leftoptype, opoid,
2076 rightop, rightoptype);
2077}
static char * buf
Definition: pg_test_fsync.c:72
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13429

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

2096{
2097 HeapTuple tp;
2098 Form_pg_collation colltup;
2099 char *collname;
2100 char onename[MAX_QUOTED_NAME_LEN];
2101
2102 /* Nothing to do if it's a noncollatable data type */
2103 if (!OidIsValid(collation))
2104 return;
2105
2106 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2107 if (!HeapTupleIsValid(tp))
2108 elog(ERROR, "cache lookup failed for collation %u", collation);
2109 colltup = (Form_pg_collation) GETSTRUCT(tp);
2110 collname = NameStr(colltup->collname);
2111
2112 /*
2113 * We qualify the name always, for simplicity and to ensure the query is
2114 * not search-path-dependent.
2115 */
2116 quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2117 appendStringInfo(buf, " COLLATE %s", onename);
2118 quoteOneName(onename, collname);
2119 appendStringInfo(buf, ".%s", onename);
2120
2121 ReleaseSysCache(tp);
2122}
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_Initial_Check(), and RI_PartitionRemove_Check().

◆ ri_HashCompareOp()

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

Definition at line 3117 of file ri_triggers.c.

3118{
3120 RI_CompareHashEntry *entry;
3121 bool found;
3122
3123 /*
3124 * On the first call initialize the hashtable
3125 */
3126 if (!ri_compare_cache)
3128
3129 /*
3130 * Find or create a hash entry. Note we're assuming RI_CompareKey
3131 * contains no struct padding.
3132 */
3133 key.eq_opr = eq_opr;
3134 key.typeid = typeid;
3136 &key,
3137 HASH_ENTER, &found);
3138 if (!found)
3139 entry->valid = false;
3140
3141 /*
3142 * If not already initialized, do so. Since we'll keep this hash entry
3143 * for the life of the backend, put any subsidiary info for the function
3144 * cache structs into TopMemoryContext.
3145 */
3146 if (!entry->valid)
3147 {
3148 Oid lefttype,
3149 righttype,
3150 castfunc;
3151 CoercionPathType pathtype;
3152
3153 /* We always need to know how to call the equality operator */
3154 fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3156
3157 /*
3158 * If we chose to use a cast from FK to PK type, we may have to apply
3159 * the cast function to get to the operator's input type.
3160 *
3161 * XXX eventually it would be good to support array-coercion cases
3162 * here and in ri_CompareWithCast(). At the moment there is no point
3163 * because cases involving nonidentical array types will be rejected
3164 * at constraint creation time.
3165 *
3166 * XXX perhaps also consider supporting CoerceViaIO? No need at the
3167 * moment since that will never be generated for implicit coercions.
3168 */
3169 op_input_types(eq_opr, &lefttype, &righttype);
3170 Assert(lefttype == righttype);
3171 if (typeid == lefttype)
3172 castfunc = InvalidOid; /* simplest case */
3173 else
3174 {
3175 pathtype = find_coercion_pathway(lefttype, typeid,
3177 &castfunc);
3178 if (pathtype != COERCION_PATH_FUNC &&
3179 pathtype != COERCION_PATH_RELABELTYPE)
3180 {
3181 /*
3182 * The declared input type of the eq_opr might be a
3183 * polymorphic type such as ANYARRAY or ANYENUM, or other
3184 * special cases such as RECORD; find_coercion_pathway
3185 * currently doesn't subsume these special cases.
3186 */
3187 if (!IsBinaryCoercible(typeid, lefttype))
3188 elog(ERROR, "no conversion function from %s to %s",
3189 format_type_be(typeid),
3190 format_type_be(lefttype));
3191 }
3192 }
3193 if (OidIsValid(castfunc))
3194 fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3196 else
3198 entry->valid = true;
3199 }
3200
3201 return entry;
3202}
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:1425
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1498
MemoryContext TopMemoryContext
Definition: mcxt.c:165
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:35
@ COERCION_IMPLICIT
Definition: primnodes.h:731
static HTAB * ri_compare_cache
Definition: ri_triggers.c:185

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

2949{
2950 RI_QueryHashEntry *entry;
2951 bool found;
2952
2953 /*
2954 * On the first call initialize the hashtable
2955 */
2956 if (!ri_query_cache)
2958
2959 /*
2960 * Add the new plan. We might be overwriting an entry previously found
2961 * invalid by ri_FetchPreparedPlan.
2962 */
2964 key,
2965 HASH_ENTER, &found);
2966 Assert(!found || entry->plan == NULL);
2967 entry->plan = plan;
2968}

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

2861{
2862 HASHCTL ctl;
2863
2864 ctl.keysize = sizeof(Oid);
2865 ctl.entrysize = sizeof(RI_ConstraintInfo);
2866 ri_constraint_cache = hash_create("RI constraint cache",
2869
2870 /* Arrange to flush cache on pg_constraint changes */
2873 (Datum) 0);
2874
2875 ctl.keysize = sizeof(RI_QueryKey);
2876 ctl.entrysize = sizeof(RI_QueryHashEntry);
2877 ri_query_cache = hash_create("RI query cache",
2880
2881 ctl.keysize = sizeof(RI_CompareKey);
2882 ctl.entrysize = sizeof(RI_CompareHashEntry);
2883 ri_compare_cache = hash_create("RI compare cache",
2886}
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:1812
uintptr_t Datum
Definition: postgres.h:69
tree ctl
Definition: radixtree.h:1838
struct RI_ConstraintInfo RI_ConstraintInfo
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2400
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 1519 of file ri_triggers.c.

1520{
1521 const RI_ConstraintInfo *riinfo;
1522 StringInfoData querybuf;
1523 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1524 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1525 char pkattname[MAX_QUOTED_NAME_LEN + 3];
1526 char fkattname[MAX_QUOTED_NAME_LEN + 3];
1527 RangeTblEntry *rte;
1528 RTEPermissionInfo *pk_perminfo;
1529 RTEPermissionInfo *fk_perminfo;
1530 List *rtes = NIL;
1531 List *perminfos = NIL;
1532 const char *sep;
1533 const char *fk_only;
1534 const char *pk_only;
1535 int save_nestlevel;
1536 char workmembuf[32];
1537 int spi_result;
1538 SPIPlanPtr qplan;
1539
1540 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1541
1542 /*
1543 * Check to make sure current user has enough permissions to do the test
1544 * query. (If not, caller can fall back to the trigger method, which
1545 * works because it changes user IDs on the fly.)
1546 *
1547 * XXX are there any other show-stopper conditions to check?
1548 */
1549 pk_perminfo = makeNode(RTEPermissionInfo);
1550 pk_perminfo->relid = RelationGetRelid(pk_rel);
1551 pk_perminfo->requiredPerms = ACL_SELECT;
1552 perminfos = lappend(perminfos, pk_perminfo);
1553 rte = makeNode(RangeTblEntry);
1554 rte->rtekind = RTE_RELATION;
1555 rte->relid = RelationGetRelid(pk_rel);
1556 rte->relkind = pk_rel->rd_rel->relkind;
1557 rte->rellockmode = AccessShareLock;
1558 rte->perminfoindex = list_length(perminfos);
1559 rtes = lappend(rtes, rte);
1560
1561 fk_perminfo = makeNode(RTEPermissionInfo);
1562 fk_perminfo->relid = RelationGetRelid(fk_rel);
1563 fk_perminfo->requiredPerms = ACL_SELECT;
1564 perminfos = lappend(perminfos, fk_perminfo);
1565 rte = makeNode(RangeTblEntry);
1566 rte->rtekind = RTE_RELATION;
1567 rte->relid = RelationGetRelid(fk_rel);
1568 rte->relkind = fk_rel->rd_rel->relkind;
1569 rte->rellockmode = AccessShareLock;
1570 rte->perminfoindex = list_length(perminfos);
1571 rtes = lappend(rtes, rte);
1572
1573 for (int i = 0; i < riinfo->nkeys; i++)
1574 {
1575 int attno;
1576
1578 pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1579
1581 fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1582 }
1583
1584 if (!ExecCheckPermissions(rtes, perminfos, false))
1585 return false;
1586
1587 /*
1588 * Also punt if RLS is enabled on either table unless this role has the
1589 * bypassrls right or is the table owner of the table(s) involved which
1590 * have RLS enabled.
1591 */
1593 ((pk_rel->rd_rel->relrowsecurity &&
1594 !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1595 GetUserId())) ||
1596 (fk_rel->rd_rel->relrowsecurity &&
1597 !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1598 GetUserId()))))
1599 return false;
1600
1601 /*----------
1602 * The query string built is:
1603 * SELECT fk.keycols FROM [ONLY] relname fk
1604 * LEFT OUTER JOIN [ONLY] pkrelname pk
1605 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1606 * WHERE pk.pkkeycol1 IS NULL AND
1607 * For MATCH SIMPLE:
1608 * (fk.keycol1 IS NOT NULL [AND ...])
1609 * For MATCH FULL:
1610 * (fk.keycol1 IS NOT NULL [OR ...])
1611 *
1612 * We attach COLLATE clauses to the operators when comparing columns
1613 * that have different collations.
1614 *----------
1615 */
1616 initStringInfo(&querybuf);
1617 appendStringInfoString(&querybuf, "SELECT ");
1618 sep = "";
1619 for (int i = 0; i < riinfo->nkeys; i++)
1620 {
1621 quoteOneName(fkattname,
1622 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1623 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1624 sep = ", ";
1625 }
1626
1627 quoteRelationName(pkrelname, pk_rel);
1628 quoteRelationName(fkrelname, fk_rel);
1629 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1630 "" : "ONLY ";
1631 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1632 "" : "ONLY ";
1633 appendStringInfo(&querybuf,
1634 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1635 fk_only, fkrelname, pk_only, pkrelname);
1636
1637 strcpy(pkattname, "pk.");
1638 strcpy(fkattname, "fk.");
1639 sep = "(";
1640 for (int i = 0; i < riinfo->nkeys; i++)
1641 {
1642 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1643 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1644 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1645 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1646
1647 quoteOneName(pkattname + 3,
1648 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1649 quoteOneName(fkattname + 3,
1650 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1651 ri_GenerateQual(&querybuf, sep,
1652 pkattname, pk_type,
1653 riinfo->pf_eq_oprs[i],
1654 fkattname, fk_type);
1655 if (pk_coll != fk_coll)
1656 ri_GenerateQualCollation(&querybuf, pk_coll);
1657 sep = "AND";
1658 }
1659
1660 /*
1661 * It's sufficient to test any one pk attribute for null to detect a join
1662 * failure.
1663 */
1664 quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1665 appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1666
1667 sep = "";
1668 for (int i = 0; i < riinfo->nkeys; i++)
1669 {
1670 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1671 appendStringInfo(&querybuf,
1672 "%sfk.%s IS NOT NULL",
1673 sep, fkattname);
1674 switch (riinfo->confmatchtype)
1675 {
1677 sep = " AND ";
1678 break;
1680 sep = " OR ";
1681 break;
1682 }
1683 }
1684 appendStringInfoChar(&querybuf, ')');
1685
1686 /*
1687 * Temporarily increase work_mem so that the check query can be executed
1688 * more efficiently. It seems okay to do this because the query is simple
1689 * enough to not use a multiple of work_mem, and one typically would not
1690 * have many large foreign-key validations happening concurrently. So
1691 * this seems to meet the criteria for being considered a "maintenance"
1692 * operation, and accordingly we use maintenance_work_mem. However, we
1693 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1694 * let that get applied to the maintenance_work_mem value.
1695 *
1696 * We use the equivalent of a function SET option to allow the setting to
1697 * persist for exactly the duration of the check query. guc.c also takes
1698 * care of undoing the setting on error.
1699 */
1700 save_nestlevel = NewGUCNestLevel();
1701
1702 snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1703 (void) set_config_option("work_mem", workmembuf,
1705 GUC_ACTION_SAVE, true, 0, false);
1706 (void) set_config_option("hash_mem_multiplier", "1",
1708 GUC_ACTION_SAVE, true, 0, false);
1709
1710 SPI_connect();
1711
1712 /*
1713 * Generate the plan. We don't need to cache it, and there are no
1714 * arguments to the plan.
1715 */
1716 qplan = SPI_prepare(querybuf.data, 0, NULL);
1717
1718 if (qplan == NULL)
1719 elog(ERROR, "SPI_prepare returned %s for %s",
1721
1722 /*
1723 * Run the plan. For safety we force a current snapshot to be used. (In
1724 * transaction-snapshot mode, this arguably violates transaction isolation
1725 * rules, but we really haven't got much choice.) We don't need to
1726 * register the snapshot, because SPI_execute_snapshot will see to it. We
1727 * need at most one tuple returned, so pass limit = 1.
1728 */
1729 spi_result = SPI_execute_snapshot(qplan,
1730 NULL, NULL,
1733 true, false, 1);
1734
1735 /* Check result */
1736 if (spi_result != SPI_OK_SELECT)
1737 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1738
1739 /* Did we find a tuple violating the constraint? */
1740 if (SPI_processed > 0)
1741 {
1742 TupleTableSlot *slot;
1743 HeapTuple tuple = SPI_tuptable->vals[0];
1744 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1745 RI_ConstraintInfo fake_riinfo;
1746
1747 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1748
1749 heap_deform_tuple(tuple, tupdesc,
1750 slot->tts_values, slot->tts_isnull);
1752
1753 /*
1754 * The columns to look at in the result tuple are 1..N, not whatever
1755 * they are in the fk_rel. Hack up riinfo so that the subroutines
1756 * called here will behave properly.
1757 *
1758 * In addition to this, we have to pass the correct tupdesc to
1759 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1760 * or fk_rel's tupdesc.
1761 */
1762 memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1763 for (int i = 0; i < fake_riinfo.nkeys; i++)
1764 fake_riinfo.fk_attnums[i] = i + 1;
1765
1766 /*
1767 * If it's MATCH FULL, and there are any nulls in the FK keys,
1768 * complain about that rather than the lack of a match. MATCH FULL
1769 * disallows partially-null FK rows.
1770 */
1771 if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1772 ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1773 ereport(ERROR,
1774 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1775 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1777 NameStr(fake_riinfo.conname)),
1778 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1779 errtableconstraint(fk_rel,
1780 NameStr(fake_riinfo.conname))));
1781
1782 /*
1783 * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1784 * query, which isn't true, but will cause it to use
1785 * fake_riinfo.fk_attnums as we need.
1786 */
1787 ri_ReportViolation(&fake_riinfo,
1788 pk_rel, fk_rel,
1789 slot, tupdesc,
1790 RI_PLAN_CHECK_LOOKUPPK, false, false);
1791
1793 }
1794
1795 if (SPI_finish() != SPI_OK_FINISH)
1796 elog(ERROR, "SPI_finish failed");
1797
1798 /*
1799 * Restore work_mem and hash_mem_multiplier.
1800 */
1801 AtEOXact_GUC(true, save_nestlevel);
1802
1803 return true;
1804}
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:4173
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4075
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:661
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1427
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1443
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1741
int maintenance_work_mem
Definition: globals.c:134
int NewGUCNestLevel(void)
Definition: guc.c:2235
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2262
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:3342
@ GUC_ACTION_SAVE
Definition: guc.h:205
@ PGC_S_SESSION
Definition: guc.h:126
@ PGC_USERSET
Definition: guc.h:79
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1346
List * lappend(List *list, void *datum)
Definition: list.c:339
#define AccessShareLock
Definition: lockdefs.h:36
Oid GetUserId(void)
Definition: miscinit.c:520
#define makeNode(_type_)
Definition: nodes.h:161
@ RTE_RELATION
Definition: parsenodes.h:1026
#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:239
static pg_noreturn void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
Definition: ri_triggers.c:2651
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:2095
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:90
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:342
#define InvalidSnapshot
Definition: snapshot.h:119
uint64 SPI_processed
Definition: spi.c:44
const char * SPI_result_code_string(int code)
Definition: spi.c:1974
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:774
int SPI_result
Definition: spi.c:46
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:861
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
Definition: pg_list.h:54
Bitmapset * selectedCols
Definition: parsenodes.h:1307
AclMode requiredPerms
Definition: parsenodes.h:1305
RTEKind rtekind
Definition: parsenodes.h:1061
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, 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 2985 of file ri_triggers.c.

2987{
2988 const int16 *attnums;
2989
2990 if (rel_is_pk)
2991 attnums = riinfo->pk_attnums;
2992 else
2993 attnums = riinfo->fk_attnums;
2994
2995 /* XXX: could be worthwhile to fetch all necessary attrs at once */
2996 for (int i = 0; i < riinfo->nkeys; i++)
2997 {
2998 Datum oldvalue;
2999 Datum newvalue;
3000 bool isnull;
3001
3002 /*
3003 * Get one attribute's oldvalue. If it is NULL - they're not equal.
3004 */
3005 oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3006 if (isnull)
3007 return false;
3008
3009 /*
3010 * Get one attribute's newvalue. If it is NULL - they're not equal.
3011 */
3012 newvalue = slot_getattr(newslot, attnums[i], &isnull);
3013 if (isnull)
3014 return false;
3015
3016 if (rel_is_pk)
3017 {
3018 /*
3019 * If we are looking at the PK table, then do a bytewise
3020 * comparison. We must propagate PK changes if the value is
3021 * changed to one that "looks" different but would compare as
3022 * equal using the equality operator. This only makes a
3023 * difference for ON UPDATE CASCADE, but for consistency we treat
3024 * all changes to the PK the same.
3025 */
3026 CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3027
3028 if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3029 return false;
3030 }
3031 else
3032 {
3033 Oid eq_opr;
3034
3035 /*
3036 * When comparing the PERIOD columns we can skip the check
3037 * whenever the referencing column stayed equal or shrank, so test
3038 * with the contained-by operator instead.
3039 */
3040 if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3041 eq_opr = riinfo->period_contained_by_oper;
3042 else
3043 eq_opr = riinfo->ff_eq_oprs[i];
3044
3045 /*
3046 * For the FK table, compare with the appropriate equality
3047 * operator. Changes that compare equal will still satisfy the
3048 * constraint after the update.
3049 */
3050 if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3051 newvalue, oldvalue))
3052 return false;
3053 }
3054 }
3055
3056 return true;
3057}
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
Definition: ri_triggers.c:3071
int16 attlen
Definition: tupdesc.h:71
Oid period_contained_by_oper
Definition: ri_triggers.c:131
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:130
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

References CompactAttribute::attbyval, CompactAttribute::attlen, 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(), RIAttCollation, RIAttType, slot_getattr(), TupleTableSlot::tts_tupleDescriptor, and TupleDescCompactAttr().

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

2269{
2270 RI_ConstraintInfo *riinfo;
2271 bool found;
2272 HeapTuple tup;
2273 Form_pg_constraint conForm;
2274
2275 /*
2276 * On the first call initialize the hashtable
2277 */
2280
2281 /*
2282 * Find or create a hash entry. If we find a valid one, just return it.
2283 */
2285 &constraintOid,
2286 HASH_ENTER, &found);
2287 if (!found)
2288 riinfo->valid = false;
2289 else if (riinfo->valid)
2290 return riinfo;
2291
2292 /*
2293 * Fetch the pg_constraint row so we can fill in the entry.
2294 */
2295 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2296 if (!HeapTupleIsValid(tup)) /* should not happen */
2297 elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2298 conForm = (Form_pg_constraint) GETSTRUCT(tup);
2299
2300 if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2301 elog(ERROR, "constraint %u is not a foreign key constraint",
2302 constraintOid);
2303
2304 /* And extract data */
2305 Assert(riinfo->constraint_id == constraintOid);
2306 if (OidIsValid(conForm->conparentid))
2307 riinfo->constraint_root_id =
2308 get_ri_constraint_root(conForm->conparentid);
2309 else
2310 riinfo->constraint_root_id = constraintOid;
2311 riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2312 ObjectIdGetDatum(constraintOid));
2313 riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2315 memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2316 riinfo->pk_relid = conForm->confrelid;
2317 riinfo->fk_relid = conForm->conrelid;
2318 riinfo->confupdtype = conForm->confupdtype;
2319 riinfo->confdeltype = conForm->confdeltype;
2320 riinfo->confmatchtype = conForm->confmatchtype;
2321 riinfo->hasperiod = conForm->conperiod;
2322
2324 &riinfo->nkeys,
2325 riinfo->fk_attnums,
2326 riinfo->pk_attnums,
2327 riinfo->pf_eq_oprs,
2328 riinfo->pp_eq_oprs,
2329 riinfo->ff_eq_oprs,
2330 &riinfo->ndelsetcols,
2331 riinfo->confdelsetcols);
2332
2333 /*
2334 * For temporal FKs, get the operators and functions we need. We ask the
2335 * opclass of the PK element for these. This all gets cached (as does the
2336 * generated plan), so there's no performance issue.
2337 */
2338 if (riinfo->hasperiod)
2339 {
2340 Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2341
2342 FindFKPeriodOpers(opclass,
2343 &riinfo->period_contained_by_oper,
2345 &riinfo->period_intersect_oper);
2346 }
2347
2348 ReleaseSysCache(tup);
2349
2350 /*
2351 * For efficient processing of invalidation messages below, we keep a
2352 * doubly-linked count list of all currently valid entries.
2353 */
2355
2356 riinfo->valid = true;
2357
2358 return riinfo;
2359}
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:3652
void FindFKPeriodOpers(Oid opclass, Oid *containedbyoperoid, Oid *aggedcontainedbyoperoid, Oid *intersectoperoid)
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)
static Oid get_ri_constraint_root(Oid constrOid)
Definition: ri_triggers.c:2366
dlist_node valid_link
Definition: ri_triggers.c:134
int16 confdelsetcols[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:121
Definition: c.h:712
#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::period_intersect_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 2823 of file ri_triggers.c.

2826{
2827 const int16 *attnums;
2828 bool allnull = true;
2829 bool nonenull = true;
2830
2831 if (rel_is_pk)
2832 attnums = riinfo->pk_attnums;
2833 else
2834 attnums = riinfo->fk_attnums;
2835
2836 for (int i = 0; i < riinfo->nkeys; i++)
2837 {
2838 if (slot_attisnull(slot, attnums[i]))
2839 nonenull = false;
2840 else
2841 allnull = false;
2842 }
2843
2844 if (allnull)
2845 return RI_KEYS_ALL_NULL;
2846
2847 if (nonenull)
2848 return RI_KEYS_NONE_NULL;
2849
2850 return RI_KEYS_SOME_NULL;
2851}
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:385

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

1814{
1815 const RI_ConstraintInfo *riinfo;
1816 StringInfoData querybuf;
1817 char *constraintDef;
1818 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1819 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1820 char pkattname[MAX_QUOTED_NAME_LEN + 3];
1821 char fkattname[MAX_QUOTED_NAME_LEN + 3];
1822 const char *sep;
1823 const char *fk_only;
1824 int save_nestlevel;
1825 char workmembuf[32];
1826 int spi_result;
1827 SPIPlanPtr qplan;
1828 int i;
1829
1830 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1831
1832 /*
1833 * We don't check permissions before displaying the error message, on the
1834 * assumption that the user detaching the partition must have enough
1835 * privileges to examine the table contents anyhow.
1836 */
1837
1838 /*----------
1839 * The query string built is:
1840 * SELECT fk.keycols FROM [ONLY] relname fk
1841 * JOIN pkrelname pk
1842 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1843 * WHERE (<partition constraint>) AND
1844 * For MATCH SIMPLE:
1845 * (fk.keycol1 IS NOT NULL [AND ...])
1846 * For MATCH FULL:
1847 * (fk.keycol1 IS NOT NULL [OR ...])
1848 *
1849 * We attach COLLATE clauses to the operators when comparing columns
1850 * that have different collations.
1851 *----------
1852 */
1853 initStringInfo(&querybuf);
1854 appendStringInfoString(&querybuf, "SELECT ");
1855 sep = "";
1856 for (i = 0; i < riinfo->nkeys; i++)
1857 {
1858 quoteOneName(fkattname,
1859 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1860 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1861 sep = ", ";
1862 }
1863
1864 quoteRelationName(pkrelname, pk_rel);
1865 quoteRelationName(fkrelname, fk_rel);
1866 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1867 "" : "ONLY ";
1868 appendStringInfo(&querybuf,
1869 " FROM %s%s fk JOIN %s pk ON",
1870 fk_only, fkrelname, pkrelname);
1871 strcpy(pkattname, "pk.");
1872 strcpy(fkattname, "fk.");
1873 sep = "(";
1874 for (i = 0; i < riinfo->nkeys; i++)
1875 {
1876 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1877 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1878 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1879 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1880
1881 quoteOneName(pkattname + 3,
1882 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1883 quoteOneName(fkattname + 3,
1884 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1885 ri_GenerateQual(&querybuf, sep,
1886 pkattname, pk_type,
1887 riinfo->pf_eq_oprs[i],
1888 fkattname, fk_type);
1889 if (pk_coll != fk_coll)
1890 ri_GenerateQualCollation(&querybuf, pk_coll);
1891 sep = "AND";
1892 }
1893
1894 /*
1895 * Start the WHERE clause with the partition constraint (except if this is
1896 * the default partition and there's no other partition, because the
1897 * partition constraint is the empty string in that case.)
1898 */
1899 constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1900 if (constraintDef && constraintDef[0] != '\0')
1901 appendStringInfo(&querybuf, ") WHERE %s AND (",
1902 constraintDef);
1903 else
1904 appendStringInfoString(&querybuf, ") WHERE (");
1905
1906 sep = "";
1907 for (i = 0; i < riinfo->nkeys; i++)
1908 {
1909 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1910 appendStringInfo(&querybuf,
1911 "%sfk.%s IS NOT NULL",
1912 sep, fkattname);
1913 switch (riinfo->confmatchtype)
1914 {
1916 sep = " AND ";
1917 break;
1919 sep = " OR ";
1920 break;
1921 }
1922 }
1923 appendStringInfoChar(&querybuf, ')');
1924
1925 /*
1926 * Temporarily increase work_mem so that the check query can be executed
1927 * more efficiently. It seems okay to do this because the query is simple
1928 * enough to not use a multiple of work_mem, and one typically would not
1929 * have many large foreign-key validations happening concurrently. So
1930 * this seems to meet the criteria for being considered a "maintenance"
1931 * operation, and accordingly we use maintenance_work_mem. However, we
1932 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1933 * let that get applied to the maintenance_work_mem value.
1934 *
1935 * We use the equivalent of a function SET option to allow the setting to
1936 * persist for exactly the duration of the check query. guc.c also takes
1937 * care of undoing the setting on error.
1938 */
1939 save_nestlevel = NewGUCNestLevel();
1940
1941 snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1942 (void) set_config_option("work_mem", workmembuf,
1944 GUC_ACTION_SAVE, true, 0, false);
1945 (void) set_config_option("hash_mem_multiplier", "1",
1947 GUC_ACTION_SAVE, true, 0, false);
1948
1949 SPI_connect();
1950
1951 /*
1952 * Generate the plan. We don't need to cache it, and there are no
1953 * arguments to the plan.
1954 */
1955 qplan = SPI_prepare(querybuf.data, 0, NULL);
1956
1957 if (qplan == NULL)
1958 elog(ERROR, "SPI_prepare returned %s for %s",
1960
1961 /*
1962 * Run the plan. For safety we force a current snapshot to be used. (In
1963 * transaction-snapshot mode, this arguably violates transaction isolation
1964 * rules, but we really haven't got much choice.) We don't need to
1965 * register the snapshot, because SPI_execute_snapshot will see to it. We
1966 * need at most one tuple returned, so pass limit = 1.
1967 */
1968 spi_result = SPI_execute_snapshot(qplan,
1969 NULL, NULL,
1972 true, false, 1);
1973
1974 /* Check result */
1975 if (spi_result != SPI_OK_SELECT)
1976 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1977
1978 /* Did we find a tuple that would violate the constraint? */
1979 if (SPI_processed > 0)
1980 {
1981 TupleTableSlot *slot;
1982 HeapTuple tuple = SPI_tuptable->vals[0];
1983 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1984 RI_ConstraintInfo fake_riinfo;
1985
1986 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1987
1988 heap_deform_tuple(tuple, tupdesc,
1989 slot->tts_values, slot->tts_isnull);
1991
1992 /*
1993 * The columns to look at in the result tuple are 1..N, not whatever
1994 * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1995 * will behave properly.
1996 *
1997 * In addition to this, we have to pass the correct tupdesc to
1998 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1999 * or fk_rel's tupdesc.
2000 */
2001 memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
2002 for (i = 0; i < fake_riinfo.nkeys; i++)
2003 fake_riinfo.pk_attnums[i] = i + 1;
2004
2005 ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
2006 slot, tupdesc, 0, false, true);
2007 }
2008
2009 if (SPI_finish() != SPI_OK_FINISH)
2010 elog(ERROR, "SPI_finish failed");
2011
2012 /*
2013 * Restore work_mem and hash_mem_multiplier.
2014 */
2015 AtEOXact_GUC(true, save_nestlevel);
2016}
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2128

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  is_restrict,
bool  detectNewRows,
int  expect_OK 
)
static

Definition at line 2484 of file ri_triggers.c.

2490{
2491 Relation query_rel,
2492 source_rel;
2493 bool source_is_pk;
2494 Snapshot test_snapshot;
2495 Snapshot crosscheck_snapshot;
2496 int limit;
2497 int spi_result;
2498 Oid save_userid;
2499 int save_sec_context;
2500 Datum vals[RI_MAX_NUMKEYS * 2];
2501 char nulls[RI_MAX_NUMKEYS * 2];
2502
2503 /*
2504 * Use the query type code to determine whether the query is run against
2505 * the PK or FK table; we'll do the check as that table's owner
2506 */
2508 query_rel = pk_rel;
2509 else
2510 query_rel = fk_rel;
2511
2512 /*
2513 * The values for the query are taken from the table on which the trigger
2514 * is called - it is normally the other one with respect to query_rel. An
2515 * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2516 * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2517 * need some less klugy way to determine this.
2518 */
2520 {
2521 source_rel = fk_rel;
2522 source_is_pk = false;
2523 }
2524 else
2525 {
2526 source_rel = pk_rel;
2527 source_is_pk = true;
2528 }
2529
2530 /* Extract the parameters to be passed into the query */
2531 if (newslot)
2532 {
2533 ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2534 vals, nulls);
2535 if (oldslot)
2536 ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2537 vals + riinfo->nkeys, nulls + riinfo->nkeys);
2538 }
2539 else
2540 {
2541 ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2542 vals, nulls);
2543 }
2544
2545 /*
2546 * In READ COMMITTED mode, we just need to use an up-to-date regular
2547 * snapshot, and we will see all rows that could be interesting. But in
2548 * transaction-snapshot mode, we can't change the transaction snapshot. If
2549 * the caller passes detectNewRows == false then it's okay to do the query
2550 * with the transaction snapshot; otherwise we use a current snapshot, and
2551 * tell the executor to error out if it finds any rows under the current
2552 * snapshot that wouldn't be visible per the transaction snapshot. Note
2553 * that SPI_execute_snapshot will register the snapshots, so we don't need
2554 * to bother here.
2555 */
2556 if (IsolationUsesXactSnapshot() && detectNewRows)
2557 {
2558 CommandCounterIncrement(); /* be sure all my own work is visible */
2559 test_snapshot = GetLatestSnapshot();
2560 crosscheck_snapshot = GetTransactionSnapshot();
2561 }
2562 else
2563 {
2564 /* the default SPI behavior is okay */
2565 test_snapshot = InvalidSnapshot;
2566 crosscheck_snapshot = InvalidSnapshot;
2567 }
2568
2569 /*
2570 * If this is a select query (e.g., for a 'no action' or 'restrict'
2571 * trigger), we only need to see if there is a single row in the table,
2572 * matching the key. Otherwise, limit = 0 - because we want the query to
2573 * affect ALL the matching rows.
2574 */
2575 limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2576
2577 /* Switch to proper UID to perform check as */
2578 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2579 SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2580 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2582
2583 /* Finally we can run the query. */
2584 spi_result = SPI_execute_snapshot(qplan,
2585 vals, nulls,
2586 test_snapshot, crosscheck_snapshot,
2587 false, false, limit);
2588
2589 /* Restore UID and security context */
2590 SetUserIdAndSecContext(save_userid, save_sec_context);
2591
2592 /* Check result */
2593 if (spi_result < 0)
2594 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2595
2596 if (expect_OK >= 0 && spi_result != expect_OK)
2597 ereport(ERROR,
2598 (errcode(ERRCODE_INTERNAL_ERROR),
2599 errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2601 NameStr(riinfo->conname),
2602 RelationGetRelationName(fk_rel)),
2603 errhint("This is most likely due to a rule having rewritten the query.")));
2604
2605 /* XXX wouldn't it be clearer to do this part at the caller? */
2607 expect_OK == SPI_OK_SELECT &&
2609 ri_ReportViolation(riinfo,
2610 pk_rel, fk_rel,
2611 newslot ? newslot : oldslot,
2612 NULL,
2613 qkey->constr_queryno, is_restrict, false);
2614
2615 return SPI_processed != 0;
2616}
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:320
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:318
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:663
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:670
#define RelationGetForm(relation)
Definition: rel.h:510
#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:2622
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:271
int32 constr_queryno
Definition: ri_triggers.c:145
void CommandCounterIncrement(void)
Definition: xact.c:1100
#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 2441 of file ri_triggers.c.

2443{
2444 SPIPlanPtr qplan;
2445 Relation query_rel;
2446 Oid save_userid;
2447 int save_sec_context;
2448
2449 /*
2450 * Use the query type code to determine whether the query is run against
2451 * the PK or FK table; we'll do the check as that table's owner
2452 */
2454 query_rel = pk_rel;
2455 else
2456 query_rel = fk_rel;
2457
2458 /* Switch to proper UID to perform check as */
2459 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2460 SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2461 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2463
2464 /* Create the plan */
2465 qplan = SPI_prepare(querystr, nargs, argtypes);
2466
2467 if (qplan == NULL)
2468 elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2469
2470 /* Restore UID and security context */
2471 SetUserIdAndSecContext(save_userid, save_sec_context);
2472
2473 /* Save the plan */
2474 SPI_keepplan(qplan);
2475 ri_HashPreparedPlan(qkey, qplan);
2476
2477 return qplan;
2478}
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2948
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:977

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  is_restrict,
bool  partgone 
)
static

Definition at line 2651 of file ri_triggers.c.

2655{
2656 StringInfoData key_names;
2657 StringInfoData key_values;
2658 bool onfk;
2659 const int16 *attnums;
2660 Oid rel_oid;
2661 AclResult aclresult;
2662 bool has_perm = true;
2663
2664 /*
2665 * Determine which relation to complain about. If tupdesc wasn't passed
2666 * by caller, assume the violator tuple came from there.
2667 */
2668 onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2669 if (onfk)
2670 {
2671 attnums = riinfo->fk_attnums;
2672 rel_oid = fk_rel->rd_id;
2673 if (tupdesc == NULL)
2674 tupdesc = fk_rel->rd_att;
2675 }
2676 else
2677 {
2678 attnums = riinfo->pk_attnums;
2679 rel_oid = pk_rel->rd_id;
2680 if (tupdesc == NULL)
2681 tupdesc = pk_rel->rd_att;
2682 }
2683
2684 /*
2685 * Check permissions- if the user does not have access to view the data in
2686 * any of the key columns then we don't include the errdetail() below.
2687 *
2688 * Check if RLS is enabled on the relation first. If so, we don't return
2689 * any specifics to avoid leaking data.
2690 *
2691 * Check table-level permissions next and, failing that, column-level
2692 * privileges.
2693 *
2694 * When a partition at the referenced side is being detached/dropped, we
2695 * needn't check, since the user must be the table owner anyway.
2696 */
2697 if (partgone)
2698 has_perm = true;
2699 else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2700 {
2701 aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2702 if (aclresult != ACLCHECK_OK)
2703 {
2704 /* Try for column-level permissions */
2705 for (int idx = 0; idx < riinfo->nkeys; idx++)
2706 {
2707 aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2708 GetUserId(),
2709 ACL_SELECT);
2710
2711 /* No access to the key */
2712 if (aclresult != ACLCHECK_OK)
2713 {
2714 has_perm = false;
2715 break;
2716 }
2717 }
2718 }
2719 }
2720 else
2721 has_perm = false;
2722
2723 if (has_perm)
2724 {
2725 /* Get printable versions of the keys involved */
2726 initStringInfo(&key_names);
2727 initStringInfo(&key_values);
2728 for (int idx = 0; idx < riinfo->nkeys; idx++)
2729 {
2730 int fnum = attnums[idx];
2731 Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2732 char *name,
2733 *val;
2734 Datum datum;
2735 bool isnull;
2736
2737 name = NameStr(att->attname);
2738
2739 datum = slot_getattr(violatorslot, fnum, &isnull);
2740 if (!isnull)
2741 {
2742 Oid foutoid;
2743 bool typisvarlena;
2744
2745 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2746 val = OidOutputFunctionCall(foutoid, datum);
2747 }
2748 else
2749 val = "null";
2750
2751 if (idx > 0)
2752 {
2753 appendStringInfoString(&key_names, ", ");
2754 appendStringInfoString(&key_values, ", ");
2755 }
2756 appendStringInfoString(&key_names, name);
2757 appendStringInfoString(&key_values, val);
2758 }
2759 }
2760
2761 if (partgone)
2762 ereport(ERROR,
2763 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2764 errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2766 NameStr(riinfo->conname)),
2767 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2768 key_names.data, key_values.data,
2769 RelationGetRelationName(fk_rel)),
2770 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2771 else if (onfk)
2772 ereport(ERROR,
2773 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2774 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2776 NameStr(riinfo->conname)),
2777 has_perm ?
2778 errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2779 key_names.data, key_values.data,
2780 RelationGetRelationName(pk_rel)) :
2781 errdetail("Key is not present in table \"%s\".",
2782 RelationGetRelationName(pk_rel)),
2783 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2784 else if (is_restrict)
2785 ereport(ERROR,
2786 (errcode(ERRCODE_RESTRICT_VIOLATION),
2787 errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
2789 NameStr(riinfo->conname),
2790 RelationGetRelationName(fk_rel)),
2791 has_perm ?
2792 errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
2793 key_names.data, key_values.data,
2794 RelationGetRelationName(fk_rel)) :
2795 errdetail("Key is referenced from table \"%s\".",
2796 RelationGetRelationName(fk_rel)),
2797 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2798 else
2799 ereport(ERROR,
2800 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2801 errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2803 NameStr(riinfo->conname),
2804 RelationGetRelationName(fk_rel)),
2805 has_perm ?
2806 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2807 key_names.data, key_values.data,
2808 RelationGetRelationName(fk_rel)) :
2809 errdetail("Key is still referenced from table \"%s\".",
2810 RelationGetRelationName(fk_rel)),
2811 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2812}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
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:3853
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
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:3047
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
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
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

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

713{
714 const RI_ConstraintInfo *riinfo;
715 Relation fk_rel;
716 Relation pk_rel;
717 TupleTableSlot *oldslot;
718 RI_QueryKey qkey;
719 SPIPlanPtr qplan;
720
721 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
722 trigdata->tg_relation, true);
723
724 /*
725 * Get the relation descriptors of the FK and PK tables and the old tuple.
726 *
727 * fk_rel is opened in RowShareLock mode since that's what our eventual
728 * SELECT FOR KEY SHARE will get on it.
729 */
730 fk_rel = table_open(riinfo->fk_relid, RowShareLock);
731 pk_rel = trigdata->tg_relation;
732 oldslot = trigdata->tg_trigslot;
733
734 /*
735 * If another PK row now exists providing the old key values, we should
736 * not do anything. However, this check should only be made in the NO
737 * ACTION case; in RESTRICT cases we don't wish to allow another row to be
738 * substituted.
739 *
740 * If the foreign key has PERIOD, we incorporate looking for replacement
741 * rows in the main SQL query below, so we needn't do it here.
742 */
743 if (is_no_action && !riinfo->hasperiod &&
744 ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
745 {
746 table_close(fk_rel, RowShareLock);
747 return PointerGetDatum(NULL);
748 }
749
750 SPI_connect();
751
752 /*
753 * Fetch or prepare a saved plan for the restrict lookup (it's the same
754 * query for delete and update cases)
755 */
756 ri_BuildQueryKey(&qkey, riinfo, is_no_action ? RI_PLAN_NO_ACTION : RI_PLAN_RESTRICT);
757
758 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
759 {
760 StringInfoData querybuf;
761 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
762 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
764 char periodattname[MAX_QUOTED_NAME_LEN];
765 char paramname[16];
766 const char *querysep;
767 Oid queryoids[RI_MAX_NUMKEYS];
768 const char *fk_only;
769
770 /* ----------
771 * The query string built is
772 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
773 * FOR KEY SHARE OF x
774 * The type id's for the $ parameters are those of the
775 * corresponding PK attributes.
776 * ----------
777 */
778 initStringInfo(&querybuf);
779 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
780 "" : "ONLY ";
781 quoteRelationName(fkrelname, fk_rel);
782 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
783 fk_only, fkrelname);
784 querysep = "WHERE";
785 for (int i = 0; i < riinfo->nkeys; i++)
786 {
787 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
788 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
789
791 RIAttName(fk_rel, riinfo->fk_attnums[i]));
792 sprintf(paramname, "$%d", i + 1);
793 ri_GenerateQual(&querybuf, querysep,
794 paramname, pk_type,
795 riinfo->pf_eq_oprs[i],
796 attname, fk_type);
797 querysep = "AND";
798 queryoids[i] = pk_type;
799 }
800
801 /*----------
802 * For temporal foreign keys, a reference could still be valid if the
803 * referenced range didn't change too much. Also if a referencing
804 * range extends past the current PK row, we don't want to check that
805 * part: some other PK row should fulfill it. We only want to check
806 * the part matching the PK record we've changed. Therefore to find
807 * invalid records we do this:
808 *
809 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
810 * -- begin temporal
811 * AND $n && x.fkperiod
812 * AND NOT coalesce((x.fkperiod * $n) <@
813 * (SELECT range_agg(r)
814 * FROM (SELECT y.pkperiod r
815 * FROM [ONLY] <pktable> y
816 * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
817 * FOR KEY SHARE OF y) y2), false)
818 * -- end temporal
819 * FOR KEY SHARE OF x
820 *
821 * We need the coalesce in case the first subquery returns no rows.
822 * We need the second subquery because FOR KEY SHARE doesn't support
823 * aggregate queries.
824 */
825 if (riinfo->hasperiod && is_no_action)
826 {
827 Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
828 Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
829 StringInfoData intersectbuf;
830 StringInfoData replacementsbuf;
831 char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
832 "" : "ONLY ";
833
834 quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
835 sprintf(paramname, "$%d", riinfo->nkeys);
836
837 appendStringInfoString(&querybuf, " AND NOT coalesce(");
838
839 /* Intersect the fk with the old pk range */
840 initStringInfo(&intersectbuf);
841 appendStringInfoChar(&intersectbuf, '(');
842 ri_GenerateQual(&intersectbuf, "",
843 attname, fk_period_type,
844 riinfo->period_intersect_oper,
845 paramname, pk_period_type);
846 appendStringInfoChar(&intersectbuf, ')');
847
848 /* Find the remaining history */
849 initStringInfo(&replacementsbuf);
850 appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
851
852 quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
853 quoteRelationName(pkrelname, pk_rel);
854 appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
855 periodattname, pk_only, pkrelname);
856
857 /* Restrict pk rows to what matches */
858 querysep = "WHERE";
859 for (int i = 0; i < riinfo->nkeys; i++)
860 {
861 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
862
864 RIAttName(pk_rel, riinfo->pk_attnums[i]));
865 sprintf(paramname, "$%d", i + 1);
866 ri_GenerateQual(&replacementsbuf, querysep,
867 paramname, pk_type,
868 riinfo->pp_eq_oprs[i],
869 attname, pk_type);
870 querysep = "AND";
871 queryoids[i] = pk_type;
872 }
873 appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
874
875 ri_GenerateQual(&querybuf, "",
876 intersectbuf.data, fk_period_type,
878 replacementsbuf.data, ANYMULTIRANGEOID);
879 /* end of coalesce: */
880 appendStringInfoString(&querybuf, ", false)");
881 }
882
883 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
884
885 /* Prepare and save the plan */
886 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
887 &qkey, fk_rel, pk_rel);
888 }
889
890 /*
891 * We have a plan now. Run it to check for existing references.
892 */
893 ri_PerformCheck(riinfo, &qkey, qplan,
894 fk_rel, pk_rel,
895 oldslot, NULL,
896 !is_no_action,
897 true, /* must detect new rows */
899
900 if (SPI_finish() != SPI_OK_FINISH)
901 elog(ERROR, "SPI_finish failed");
902
903 table_close(fk_rel, RowShareLock);
904
905 return PointerGetDatum(NULL);
906}
#define RI_PLAN_RESTRICT
Definition: ri_triggers.c:79
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:511
#define RI_PLAN_NO_ACTION
Definition: ri_triggers.c:77

References RI_ConstraintInfo::agged_period_contained_by_oper, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attname, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, RI_ConstraintInfo::hasperiod, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, RI_ConstraintInfo::nkeys, RI_ConstraintInfo::period_intersect_oper, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum(), RI_ConstraintInfo::pp_eq_oprs, quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), RI_PLAN_NO_ACTION, RI_PLAN_RESTRICT, ri_PlanCheck(), 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 1195 of file ri_triggers.c.

1196{
1197 const RI_ConstraintInfo *riinfo;
1198 Relation fk_rel;
1199 Relation pk_rel;
1200 TupleTableSlot *oldslot;
1201 RI_QueryKey qkey;
1202 SPIPlanPtr qplan;
1203 int32 queryno;
1204
1205 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1206 trigdata->tg_relation, true);
1207
1208 /*
1209 * Get the relation descriptors of the FK and PK tables and the old tuple.
1210 *
1211 * fk_rel is opened in RowExclusiveLock mode since that's what our
1212 * eventual UPDATE will get on it.
1213 */
1214 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1215 pk_rel = trigdata->tg_relation;
1216 oldslot = trigdata->tg_trigslot;
1217
1218 SPI_connect();
1219
1220 /*
1221 * Fetch or prepare a saved plan for the trigger.
1222 */
1223 switch (tgkind)
1224 {
1225 case RI_TRIGTYPE_UPDATE:
1226 queryno = is_set_null
1229 break;
1230 case RI_TRIGTYPE_DELETE:
1231 queryno = is_set_null
1234 break;
1235 default:
1236 elog(ERROR, "invalid tgkind passed to ri_set");
1237 }
1238
1239 ri_BuildQueryKey(&qkey, riinfo, queryno);
1240
1241 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1242 {
1243 StringInfoData querybuf;
1244 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1246 char paramname[16];
1247 const char *querysep;
1248 const char *qualsep;
1249 Oid queryoids[RI_MAX_NUMKEYS];
1250 const char *fk_only;
1251 int num_cols_to_set;
1252 const int16 *set_cols;
1253
1254 switch (tgkind)
1255 {
1256 case RI_TRIGTYPE_UPDATE:
1257 num_cols_to_set = riinfo->nkeys;
1258 set_cols = riinfo->fk_attnums;
1259 break;
1260 case RI_TRIGTYPE_DELETE:
1261
1262 /*
1263 * If confdelsetcols are present, then we only update the
1264 * columns specified in that array, otherwise we update all
1265 * the referencing columns.
1266 */
1267 if (riinfo->ndelsetcols != 0)
1268 {
1269 num_cols_to_set = riinfo->ndelsetcols;
1270 set_cols = riinfo->confdelsetcols;
1271 }
1272 else
1273 {
1274 num_cols_to_set = riinfo->nkeys;
1275 set_cols = riinfo->fk_attnums;
1276 }
1277 break;
1278 default:
1279 elog(ERROR, "invalid tgkind passed to ri_set");
1280 }
1281
1282 /* ----------
1283 * The query string built is
1284 * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1285 * WHERE $1 = fkatt1 [AND ...]
1286 * The type id's for the $ parameters are those of the
1287 * corresponding PK attributes.
1288 * ----------
1289 */
1290 initStringInfo(&querybuf);
1291 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1292 "" : "ONLY ";
1293 quoteRelationName(fkrelname, fk_rel);
1294 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1295 fk_only, fkrelname);
1296
1297 /*
1298 * Add assignment clauses
1299 */
1300 querysep = "";
1301 for (int i = 0; i < num_cols_to_set; i++)
1302 {
1303 quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
1304 appendStringInfo(&querybuf,
1305 "%s %s = %s",
1306 querysep, attname,
1307 is_set_null ? "NULL" : "DEFAULT");
1308 querysep = ",";
1309 }
1310
1311 /*
1312 * Add WHERE clause
1313 */
1314 qualsep = "WHERE";
1315 for (int i = 0; i < riinfo->nkeys; i++)
1316 {
1317 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1318 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1319
1321 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1322
1323 sprintf(paramname, "$%d", i + 1);
1324 ri_GenerateQual(&querybuf, qualsep,
1325 paramname, pk_type,
1326 riinfo->pf_eq_oprs[i],
1327 attname, fk_type);
1328 qualsep = "AND";
1329 queryoids[i] = pk_type;
1330 }
1331
1332 /* Prepare and save the plan */
1333 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1334 &qkey, fk_rel, pk_rel);
1335 }
1336
1337 /*
1338 * We have a plan now. Run it to update the existing references.
1339 */
1340 ri_PerformCheck(riinfo, &qkey, qplan,
1341 fk_rel, pk_rel,
1342 oldslot, NULL,
1343 false,
1344 true, /* must detect new rows */
1346
1347 if (SPI_finish() != SPI_OK_FINISH)
1348 elog(ERROR, "SPI_finish failed");
1349
1351
1352 if (is_set_null)
1353 return PointerGetDatum(NULL);
1354 else
1355 {
1356 /*
1357 * If we just deleted or updated the PK row whose key was equal to the
1358 * FK columns' default values, and a referencing row exists in the FK
1359 * table, we would have updated that row to the same values it already
1360 * had --- and RI_FKey_fk_upd_check_required would hence believe no
1361 * check is necessary. So we need to do another lookup now and in
1362 * case a reference still exists, abort the operation. That is
1363 * already implemented in the NO ACTION trigger, so just run it. (This
1364 * recheck is only needed in the SET DEFAULT case, since CASCADE would
1365 * remove such rows in case of a DELETE operation or would change the
1366 * FK key values in case of an UPDATE, while SET NULL is certain to
1367 * result in rows that satisfy the FK constraint.)
1368 */
1369 return ri_restrict(trigdata, true);
1370 }
1371}
int32_t int32
Definition: c.h:498
#define RI_PLAN_SETNULL_ONUPDATE
Definition: ri_triggers.c:81
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition: ri_triggers.c:82
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition: ri_triggers.c:83
#define RI_PLAN_SETNULL_ONDELETE
Definition: ri_triggers.c:80

References appendStringInfo(), attname, RI_ConstraintInfo::confdelsetcols, StringInfoData::data, elog, ERROR, RI_ConstraintInfo::fk_attnums, RI_ConstraintInfo::fk_relid, 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_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, 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 185 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 186 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 184 of file ri_triggers.c.

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