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

Go to the source code of this file.

Data Structures

struct  RI_ConstraintInfo
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 

Macros

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

Typedefs

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

Functions

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

Variables

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

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

Definition at line 84 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 85 of file ri_triggers.c.

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 62 of file ri_triggers.c.

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 63 of file ri_triggers.c.

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 65 of file ri_triggers.c.

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

Definition at line 67 of file ri_triggers.c.

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 66 of file ri_triggers.c.

◆ RI_MAX_NUMKEYS

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS

Definition at line 60 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONDELETE

#define RI_PLAN_CASCADE_ONDELETE   3

Definition at line 75 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONUPDATE

#define RI_PLAN_CASCADE_ONUPDATE   4

Definition at line 76 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 71 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

Definition at line 72 of file ri_triggers.c.

◆ RI_PLAN_LAST_ON_PK

#define RI_PLAN_LAST_ON_PK   RI_PLAN_CHECK_LOOKUPPK_FROM_PK

Definition at line 73 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   5

Definition at line 78 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   8

Definition at line 81 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   9

Definition at line 82 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   6

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   7

Definition at line 80 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 93 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 91 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 92 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 89 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 87 of file ri_triggers.c.

◆ RIAttType

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

Definition at line 88 of file ri_triggers.c.

Typedef Documentation

◆ RI_CompareHashEntry

◆ RI_CompareKey

typedef struct RI_CompareKey RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_QueryHashEntry

◆ RI_QueryKey

typedef struct RI_QueryKey RI_QueryKey

Function Documentation

◆ get_ri_constraint_root()

static Oid get_ri_constraint_root ( Oid  constrOid)
static

Definition at line 2275 of file ri_triggers.c.

2276{
2277 for (;;)
2278 {
2279 HeapTuple tuple;
2280 Oid constrParentOid;
2281
2282 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2283 if (!HeapTupleIsValid(tuple))
2284 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2285 constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2286 ReleaseSysCache(tuple);
2287 if (!OidIsValid(constrParentOid))
2288 break; /* we reached the root constraint */
2289 constrOid = constrParentOid;
2290 }
2291 return constrOid;
2292}
#define OidIsValid(objectId)
Definition: c.h:732
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
unsigned int Oid
Definition: postgres_ext.h:32
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 2309 of file ri_triggers.c.

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

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

Referenced by ri_InitHashTables().

◆ quoteOneName()

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

Definition at line 1941 of file ri_triggers.c.

1942{
1943 /* Rather than trying to be smart, just always quote it. */
1944 *buffer++ = '"';
1945 while (*name)
1946 {
1947 if (*name == '"')
1948 *buffer++ = '"';
1949 *buffer++ = *name++;
1950 }
1951 *buffer++ = '"';
1952 *buffer = '\0';
1953}
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 1961 of file ri_triggers.c.

1962{
1964 buffer += strlen(buffer);
1965 *buffer++ = '.';
1967}
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1941

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

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

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

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

Referenced by ri_restrict().

◆ ri_CheckTrigger()

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

Definition at line 2078 of file ri_triggers.c.

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

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

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

◆ ri_CompareWithCast()

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

Definition at line 2980 of file ri_triggers.c.

2982{
2983 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
2984
2985 /* Do we need to cast the values? */
2986 if (OidIsValid(entry->cast_func_finfo.fn_oid))
2987 {
2988 lhs = FunctionCall3(&entry->cast_func_finfo,
2989 lhs,
2990 Int32GetDatum(-1), /* typmod */
2991 BoolGetDatum(false)); /* implicit coercion */
2992 rhs = FunctionCall3(&entry->cast_func_finfo,
2993 rhs,
2994 Int32GetDatum(-1), /* typmod */
2995 BoolGetDatum(false)); /* implicit coercion */
2996 }
2997
2998 /*
2999 * Apply the comparison operator.
3000 *
3001 * Note: This function is part of a call stack that determines whether an
3002 * update to a row is significant enough that it needs checking or action
3003 * on the other side of a foreign-key constraint. Therefore, the
3004 * comparison here would need to be done with the collation of the *other*
3005 * table. For simplicity (e.g., we might not even have the other table
3006 * open), we'll use our own collation. This is fine because we require
3007 * that both collations have the same notion of equality (either they are
3008 * both deterministic or else they are both the same).
3009 *
3010 * With range/multirangetypes, the collation of the base type is stored as
3011 * part of the rangetype (pg_range.rngcollation), and always used, so
3012 * there is no danger of inconsistency even using a non-equals operator.
3013 * But if we support arbitrary types with PERIOD, we should perhaps just
3014 * always force a re-check.
3015 */
3016 return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
3017}
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:663
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:3026
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:174

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

2534{
2535 const int16 *attnums;
2536 bool isnull;
2537
2538 if (rel_is_pk)
2539 attnums = riinfo->pk_attnums;
2540 else
2541 attnums = riinfo->fk_attnums;
2542
2543 for (int i = 0; i < riinfo->nkeys; i++)
2544 {
2545 vals[i] = slot_getattr(slot, attnums[i], &isnull);
2546 nulls[i] = isnull ? 'n' : ' ';
2547 }
2548}
int16_t int16
Definition: c.h:483
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395

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

Referenced by ri_PerformCheck().

◆ ri_FetchConstraintInfo()

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

Definition at line 2124 of file ri_triggers.c.

2125{
2126 Oid constraintOid = trigger->tgconstraint;
2127 const RI_ConstraintInfo *riinfo;
2128
2129 /*
2130 * Check that the FK constraint's OID is available; it might not be if
2131 * we've been invoked via an ordinary trigger or an old-style "constraint
2132 * trigger".
2133 */
2134 if (!OidIsValid(constraintOid))
2135 ereport(ERROR,
2136 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2137 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2138 trigger->tgname, RelationGetRelationName(trig_rel)),
2139 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2140
2141 /* Find or create a hashtable entry for the constraint */
2142 riinfo = ri_LoadConstraintInfo(constraintOid);
2143
2144 /* Do some easy cross-checks against the trigger call data */
2145 if (rel_is_pk)
2146 {
2147 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2148 riinfo->pk_relid != RelationGetRelid(trig_rel))
2149 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2150 trigger->tgname, RelationGetRelationName(trig_rel));
2151 }
2152 else
2153 {
2154 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2155 riinfo->pk_relid != trigger->tgconstrrelid)
2156 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2157 trigger->tgname, RelationGetRelationName(trig_rel));
2158 }
2159
2160 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2163 elog(ERROR, "unrecognized confmatchtype: %d",
2164 riinfo->confmatchtype);
2165
2167 ereport(ERROR,
2168 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2169 errmsg("MATCH PARTIAL not yet implemented")));
2170
2171 return riinfo;
2172}
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2797
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2796
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2795
#define RelationGetRelid(relation)
Definition: rel.h:505
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2178
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 2805 of file ri_triggers.c.

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

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

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

◆ RI_FKey_cascade_del()

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS  )

Definition at line 825 of file ri_triggers.c.

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

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

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

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

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

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

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

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

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

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

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_noaction_del()

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS  )

Definition at line 637 of file ri_triggers.c.

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

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 674 of file ri_triggers.c.

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

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

1298{
1299 const RI_ConstraintInfo *riinfo;
1300
1301 riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1302
1303 /*
1304 * If any old key value is NULL, the row could not have been referenced by
1305 * an FK row, so no check is needed.
1306 */
1307 if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1308 return false;
1309
1310 /* If all old and new key values are equal, no check is needed */
1311 if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1312 return false;
1313
1314 /* Else we need to fire the trigger. */
1315 return true;
1316}

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

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

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 694 of file ri_triggers.c.

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

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1074 of file ri_triggers.c.

1075{
1076 /* Check that this is a valid trigger call on the right time and event. */
1077 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1078
1079 /* Share code with UPDATE case */
1080 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1081}
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
Definition: ri_triggers.c:1105

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1089 of file ri_triggers.c.

1090{
1091 /* Check that this is a valid trigger call on the right time and event. */
1092 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1093
1094 /* Share code with DELETE case */
1095 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1096}

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1044 of file ri_triggers.c.

1045{
1046 /* Check that this is a valid trigger call on the right time and event. */
1047 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1048
1049 /* Share code with UPDATE case */
1050 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1051}

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1059 of file ri_triggers.c.

1060{
1061 /* Check that this is a valid trigger call on the right time and event. */
1062 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1063
1064 /* Share code with DELETE case */
1065 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1066}

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 3119 of file ri_triggers.c.

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

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

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

◆ ri_GenerateQual()

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

Definition at line 1978 of file ri_triggers.c.

1983{
1984 appendStringInfo(buf, " %s ", sep);
1985 generate_operator_clause(buf, leftop, leftoptype, opoid,
1986 rightop, rightoptype);
1987}
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:13350

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

2006{
2007 HeapTuple tp;
2008 Form_pg_collation colltup;
2009 char *collname;
2010 char onename[MAX_QUOTED_NAME_LEN];
2011
2012 /* Nothing to do if it's a noncollatable data type */
2013 if (!OidIsValid(collation))
2014 return;
2015
2016 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2017 if (!HeapTupleIsValid(tp))
2018 elog(ERROR, "cache lookup failed for collation %u", collation);
2019 colltup = (Form_pg_collation) GETSTRUCT(tp);
2020 collname = NameStr(colltup->collname);
2021
2022 /*
2023 * We qualify the name always, for simplicity and to ensure the query is
2024 * not search-path-dependent.
2025 */
2026 quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2027 appendStringInfo(buf, " COLLATE %s", onename);
2028 quoteOneName(onename, collname);
2029 appendStringInfo(buf, ".%s", onename);
2030
2031 ReleaseSysCache(tp);
2032}
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 3026 of file ri_triggers.c.

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

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

Referenced by ri_CompareWithCast().

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 2857 of file ri_triggers.c.

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

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

2770{
2771 HASHCTL ctl;
2772
2773 ctl.keysize = sizeof(Oid);
2774 ctl.entrysize = sizeof(RI_ConstraintInfo);
2775 ri_constraint_cache = hash_create("RI constraint cache",
2778
2779 /* Arrange to flush cache on pg_constraint changes */
2782 (Datum) 0);
2783
2784 ctl.keysize = sizeof(RI_QueryKey);
2785 ctl.entrysize = sizeof(RI_QueryHashEntry);
2786 ri_query_cache = hash_create("RI query cache",
2789
2790 ctl.keysize = sizeof(RI_CompareKey);
2791 ctl.entrysize = sizeof(RI_CompareHashEntry);
2792 ri_compare_cache = hash_create("RI compare cache",
2795}
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:1704
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:2309
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 1429 of file ri_triggers.c.

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

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

Referenced by validateForeignKeyConstraint().

◆ ri_KeysEqual()

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

Definition at line 2894 of file ri_triggers.c.

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

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

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

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

Referenced by ri_FetchConstraintInfo().

◆ ri_NullCheck()

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

Definition at line 2732 of file ri_triggers.c.

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

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

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

◆ RI_PartitionRemove_Check()

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

Definition at line 1723 of file ri_triggers.c.

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

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

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

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

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

◆ ri_PlanCheck()

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

Definition at line 2350 of file ri_triggers.c.

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

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

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

◆ ri_ReportViolation()

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

Definition at line 2560 of file ri_triggers.c.

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

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

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

References appendStringInfo(), appendStringInfoString(), attname, 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::nkeys, RI_ConstraintInfo::pf_eq_oprs, RI_ConstraintInfo::pk_attnums, PointerGetDatum(), quoteOneName(), quoteRelationName(), RelationData::rd_rel, ri_BuildQueryKey(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_MAX_NUMKEYS, ri_PerformCheck(), 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 1105 of file ri_triggers.c.

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

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

Referenced by ri_HashCompareOp(), and ri_InitHashTables().

◆ ri_constraint_cache

HTAB* ri_constraint_cache = NULL
static

◆ ri_constraint_cache_valid_list

dclist_head ri_constraint_cache_valid_list
static

Definition at line 184 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 182 of file ri_triggers.c.

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