PostgreSQL Source Code git master
Loading...
Searching...
No Matches
ri_triggers.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/skey.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_namespace.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/hsearch.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.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  FastPathMeta
 
struct  RI_QueryKey
 
struct  RI_QueryHashEntry
 
struct  RI_CompareKey
 
struct  RI_CompareHashEntry
 
struct  RI_FastPathEntry
 

Macros

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

Typedefs

typedef struct FastPathMeta FastPathMeta
 
typedef struct RI_ConstraintInfo RI_ConstraintInfo
 
typedef struct RI_CompareHashEntry RI_CompareHashEntry
 
typedef struct RI_QueryKey RI_QueryKey
 
typedef struct RI_QueryHashEntry RI_QueryHashEntry
 
typedef struct RI_CompareKey RI_CompareKey
 
typedef struct RI_FastPathEntry RI_FastPathEntry
 

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, SysCacheIdentifier 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 RI_ConstraintInfori_FetchConstraintInfo (Trigger *trigger, Relation trig_rel, bool rel_is_pk)
 
static 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_FastPathCheck (RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
 
static void ri_FastPathBatchAdd (RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
 
static void ri_FastPathBatchFlush (RI_FastPathEntry *fpentry, Relation fk_rel, RI_ConstraintInfo *riinfo)
 
static int ri_FastPathFlushArray (RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
 
static int ri_FastPathFlushLoop (RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
 
static bool ri_FastPathProbeOne (Relation pk_rel, Relation idx_rel, IndexScanDesc scandesc, TupleTableSlot *slot, Snapshot snapshot, const RI_ConstraintInfo *riinfo, ScanKeyData *skey, int nkeys)
 
static bool ri_LockPKTuple (Relation pk_rel, TupleTableSlot *slot, Snapshot snap, bool *concurrently_updated)
 
static bool ri_fastpath_is_applicable (const RI_ConstraintInfo *riinfo)
 
static void ri_CheckPermissions (Relation query_rel)
 
static bool recheck_matched_pk_tuple (Relation idxrel, ScanKeyData *skeys, int nkeys, TupleTableSlot *new_slot)
 
static void build_index_scankeys (const RI_ConstraintInfo *riinfo, Relation idx_rel, Datum *pk_vals, char *pk_nulls, ScanKey skeys)
 
static void ri_populate_fastpath_metadata (RI_ConstraintInfo *riinfo, Relation fk_rel, Relation idx_rel)
 
static void ri_ExtractValues (Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
 
static pg_noreturn void ri_ReportViolation (const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
 
static RI_FastPathEntryri_FastPathGetEntry (const RI_ConstraintInfo *riinfo, Relation fk_rel)
 
static void ri_FastPathEndBatch (void *arg)
 
static void ri_FastPathTeardown (void)
 
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)
 
static void ri_FastPathXactCallback (XactEvent event, void *arg)
 
static void ri_FastPathSubXactCallback (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
 

Variables

static HTABri_constraint_cache = NULL
 
static HTABri_query_cache = NULL
 
static HTABri_compare_cache = NULL
 
static dclist_head ri_constraint_cache_valid_list
 
static HTABri_fastpath_cache = NULL
 
static bool ri_fastpath_callback_registered = false
 
static bool ri_fastpath_xact_callback_registered = false
 

Macro Definition Documentation

◆ MAX_QUOTED_NAME_LEN

#define MAX_QUOTED_NAME_LEN   (NAMEDATALEN*2+3)

Definition at line 89 of file ri_triggers.c.

◆ MAX_QUOTED_REL_NAME_LEN

#define MAX_QUOTED_REL_NAME_LEN   (MAX_QUOTED_NAME_LEN*2)

Definition at line 90 of file ri_triggers.c.

◆ RI_FASTPATH_BATCH_SIZE

#define RI_FASTPATH_BATCH_SIZE   64

Definition at line 214 of file ri_triggers.c.

◆ RI_INIT_CONSTRAINTHASHSIZE

#define RI_INIT_CONSTRAINTHASHSIZE   64

Definition at line 66 of file ri_triggers.c.

◆ RI_INIT_QUERYHASHSIZE

#define RI_INIT_QUERYHASHSIZE   (RI_INIT_CONSTRAINTHASHSIZE * 4)

Definition at line 67 of file ri_triggers.c.

◆ RI_KEYS_ALL_NULL

#define RI_KEYS_ALL_NULL   0

Definition at line 69 of file ri_triggers.c.

◆ RI_KEYS_NONE_NULL

#define RI_KEYS_NONE_NULL   2

Definition at line 71 of file ri_triggers.c.

◆ RI_KEYS_SOME_NULL

#define RI_KEYS_SOME_NULL   1

Definition at line 70 of file ri_triggers.c.

◆ RI_MAX_NUMKEYS

#define RI_MAX_NUMKEYS   INDEX_MAX_KEYS

Definition at line 64 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONDELETE

#define RI_PLAN_CASCADE_ONDELETE   3

Definition at line 79 of file ri_triggers.c.

◆ RI_PLAN_CASCADE_ONUPDATE

#define RI_PLAN_CASCADE_ONUPDATE   4

Definition at line 80 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK

#define RI_PLAN_CHECK_LOOKUPPK   1

Definition at line 75 of file ri_triggers.c.

◆ RI_PLAN_CHECK_LOOKUPPK_FROM_PK

#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK   2

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

◆ RI_PLAN_NO_ACTION

#define RI_PLAN_NO_ACTION   5

Definition at line 81 of file ri_triggers.c.

◆ RI_PLAN_RESTRICT

#define RI_PLAN_RESTRICT   6

Definition at line 83 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONDELETE

#define RI_PLAN_SETDEFAULT_ONDELETE   9

Definition at line 86 of file ri_triggers.c.

◆ RI_PLAN_SETDEFAULT_ONUPDATE

#define RI_PLAN_SETDEFAULT_ONUPDATE   10

Definition at line 87 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONDELETE

#define RI_PLAN_SETNULL_ONDELETE   7

Definition at line 84 of file ri_triggers.c.

◆ RI_PLAN_SETNULL_ONUPDATE

#define RI_PLAN_SETNULL_ONUPDATE   8

Definition at line 85 of file ri_triggers.c.

◆ RI_TRIGTYPE_DELETE

#define RI_TRIGTYPE_DELETE   3

Definition at line 98 of file ri_triggers.c.

◆ RI_TRIGTYPE_INSERT

#define RI_TRIGTYPE_INSERT   1

Definition at line 96 of file ri_triggers.c.

◆ RI_TRIGTYPE_UPDATE

#define RI_TRIGTYPE_UPDATE   2

Definition at line 97 of file ri_triggers.c.

◆ RIAttCollation

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

Definition at line 94 of file ri_triggers.c.

◆ RIAttName

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

Definition at line 92 of file ri_triggers.c.

◆ RIAttType

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

Definition at line 93 of file ri_triggers.c.

Typedef Documentation

◆ FastPathMeta

Definition at line 100 of file ri_triggers.c.

◆ RI_CompareHashEntry

Definition at line 149 of file ri_triggers.c.

◆ RI_CompareKey

◆ RI_ConstraintInfo

◆ RI_FastPathEntry

◆ RI_QueryHashEntry

◆ RI_QueryKey

Function Documentation

◆ build_index_scankeys()

static void build_index_scankeys ( const RI_ConstraintInfo riinfo,
Relation  idx_rel,
Datum pk_vals,
char pk_nulls,
ScanKey  skeys 
)
static

Definition at line 3395 of file ri_triggers.c.

3398{
3399 FastPathMeta *fpmeta = riinfo->fpmeta;
3400
3401 Assert(fpmeta);
3402
3403 /*
3404 * May need to cast each of the individual values of the foreign key to
3405 * the corresponding PK column's type if the equality operator demands it.
3406 */
3407 for (int i = 0; i < riinfo->nkeys; i++)
3408 {
3409 if (pk_nulls[i] != 'n' &&
3412 pk_vals[i],
3413 Int32GetDatum(-1), /* typmod */
3414 BoolGetDatum(false)); /* implicit coercion */
3415 }
3416
3417 /*
3418 * Set up ScanKeys for the index scan. This is essentially how
3419 * ExecIndexBuildScanKeys() sets them up. Use the cached index_attnos and
3420 * the corresponding collation since FK columns may be in a different
3421 * order than PK index columns. Place each scan key at the array position
3422 * corresponding to its index column, since btree requires keys to be
3423 * ordered by attribute number.
3424 */
3425 for (int i = 0; i < riinfo->nkeys; i++)
3426 {
3427 AttrNumber pkattrno = fpmeta->index_attnos[i];
3428 int skey_pos = pkattrno - 1; /* 0-based array position */
3429
3431 fpmeta->strats[i], fpmeta->subtypes[i],
3432 idx_rel->rd_indcollation[skey_pos], fpmeta->regops[i],
3433 pk_vals[i]);
3434 }
3435}
int16 AttrNumber
Definition attnum.h:21
#define Assert(condition)
Definition c.h:943
#define OidIsValid(objectId)
Definition c.h:858
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition fmgr.h:706
int i
Definition isn.c:77
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
static int fb(int x)
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition scankey.c:32
AttrNumber index_attnos[RI_MAX_NUMKEYS]
RegProcedure regops[RI_MAX_NUMKEYS]
int strats[RI_MAX_NUMKEYS]
Oid subtypes[RI_MAX_NUMKEYS]
FmgrInfo cast_func_finfo[RI_MAX_NUMKEYS]
Oid fn_oid
Definition fmgr.h:59
Oid * rd_indcollation
Definition rel.h:217

References Assert, BoolGetDatum(), FastPathMeta::cast_func_finfo, fb(), FmgrInfo::fn_oid, FunctionCall3, i, FastPathMeta::index_attnos, Int32GetDatum(), OidIsValid, RelationData::rd_indcollation, FastPathMeta::regops, ScanKeyEntryInitialize(), FastPathMeta::strats, and FastPathMeta::subtypes.

Referenced by ri_FastPathCheck(), and ri_FastPathFlushLoop().

◆ get_ri_constraint_root()

static Oid get_ri_constraint_root ( Oid  constrOid)
static

Definition at line 2504 of file ri_triggers.c.

2505{
2506 for (;;)
2507 {
2508 HeapTuple tuple;
2510
2512 if (!HeapTupleIsValid(tuple))
2513 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2515 ReleaseSysCache(tuple);
2517 break; /* we reached the root constraint */
2519 }
2520 return constrOid;
2521}
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
unsigned int Oid
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

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

Referenced by ri_LoadConstraintInfo().

◆ InvalidateConstraintCacheCallBack()

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

Definition at line 2538 of file ri_triggers.c.

2540{
2541 dlist_mutable_iter iter;
2542
2544
2545 /*
2546 * If the list of currently valid entries gets excessively large, we mark
2547 * them all invalid so we can empty the list. This arrangement avoids
2548 * O(N^2) behavior in situations where a session touches many foreign keys
2549 * and also does many ALTER TABLEs, such as a restore from pg_dump.
2550 */
2552 hashvalue = 0; /* pretend it's a cache reset */
2553
2555 {
2557 valid_link, iter.cur);
2558
2559 /*
2560 * We must invalidate not only entries directly matching the given
2561 * hash value, but also child entries, in case the invalidation
2562 * affects a root constraint.
2563 */
2564 if (hashvalue == 0 ||
2565 riinfo->oidHashValue == hashvalue ||
2566 riinfo->rootHashValue == hashvalue)
2567 {
2568 riinfo->valid = false;
2569 if (riinfo->fpmeta)
2570 {
2571 pfree(riinfo->fpmeta);
2572 riinfo->fpmeta = NULL;
2573 }
2574 /* Remove invalidated entries from the list, too */
2576 }
2577 }
2578}
#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
void pfree(void *pointer)
Definition mcxt.c:1616
static dclist_head ri_constraint_cache_valid_list
static HTAB * ri_constraint_cache
dlist_node * cur
Definition ilist.h:200

References Assert, dlist_mutable_iter::cur, dclist_container, dclist_count(), dclist_delete_from(), dclist_foreach_modify, fb(), pfree(), ri_constraint_cache, and ri_constraint_cache_valid_list.

Referenced by ri_InitHashTables().

◆ quoteOneName()

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

Definition at line 2162 of file ri_triggers.c.

2163{
2164 /* Rather than trying to be smart, just always quote it. */
2165 *buffer++ = '"';
2166 while (*name)
2167 {
2168 if (*name == '"')
2169 *buffer++ = '"';
2170 *buffer++ = *name++;
2171 }
2172 *buffer++ = '"';
2173 *buffer = '\0';
2174}
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 2182 of file ri_triggers.c.

2183{
2185 buffer += strlen(buffer);
2186 *buffer++ = '.';
2188}
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3561
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationGetNamespace(relation)
Definition rel.h:557
static void quoteOneName(char *buffer, const char *name)

References fb(), 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().

◆ recheck_matched_pk_tuple()

static bool recheck_matched_pk_tuple ( Relation  idxrel,
ScanKeyData skeys,
int  nkeys,
TupleTableSlot new_slot 
)
static

Definition at line 3345 of file ri_triggers.c.

3347{
3348 /*
3349 * TODO: BuildIndexInfo does a syscache lookup + palloc on every call.
3350 * This only fires on the concurrent-update path (tmfd.traversed), which
3351 * should be rare, so the cost is acceptable for now. If profiling shows
3352 * otherwise, cache the IndexInfo in FastPathMeta.
3353 */
3354 IndexInfo *indexInfo = BuildIndexInfo(idxrel);
3356 bool isnull[INDEX_MAX_KEYS];
3357 bool matched = true;
3358
3359 /* PK indexes never have these. */
3360 Assert(indexInfo->ii_Expressions == NIL &&
3361 indexInfo->ii_ExclusionOps == NULL);
3362
3363 /* Form the index values and isnull flags given the table tuple. */
3364 Assert(nkeys == indexInfo->ii_NumIndexKeyAttrs);
3365 FormIndexDatum(indexInfo, new_slot, NULL, values, isnull);
3366 for (int i = 0; i < nkeys; i++)
3367 {
3368 ScanKeyData *skey = &skeys[i];
3369
3370 /* A PK column can never be set to NULL. */
3371 Assert(!isnull[i]);
3372 if (!DatumGetBool(FunctionCall2Coll(&skey->sk_func,
3373 skey->sk_collation,
3374 values[i],
3375 skey->sk_argument)))
3376 {
3377 matched = false;
3378 break;
3379 }
3380 }
3381
3382 return matched;
3383}
static Datum values[MAXATTR]
Definition bootstrap.c:190
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:1151
IndexInfo * BuildIndexInfo(Relation index)
Definition index.c:2446
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition index.c:2748
#define INDEX_MAX_KEYS
#define NIL
Definition pg_list.h:68
static bool DatumGetBool(Datum X)
Definition postgres.h:100
uint64_t Datum
Definition postgres.h:70
Oid * ii_ExclusionOps
Definition execnodes.h:202
int ii_NumIndexKeyAttrs
Definition execnodes.h:183
List * ii_Expressions
Definition execnodes.h:192

References Assert, BuildIndexInfo(), DatumGetBool(), fb(), FormIndexDatum(), FunctionCall2Coll(), i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_NumIndexKeyAttrs, INDEX_MAX_KEYS, NIL, and values.

Referenced by ri_FastPathFlushArray(), and ri_FastPathProbeOne().

◆ ri_BuildQueryKey()

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

Definition at line 2267 of file ri_triggers.c.

2269{
2270 /*
2271 * Inherited constraints with a common ancestor can share ri_query_cache
2272 * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2273 * Except in that case, the query processes the other table involved in
2274 * the FK constraint (i.e., not the table on which the trigger has been
2275 * fired), and so it will be the same for all members of the inheritance
2276 * tree. So we may use the root constraint's OID in the hash key, rather
2277 * than the constraint's own OID. This avoids creating duplicate SPI
2278 * plans, saving lots of work and memory when there are many partitions
2279 * with similar FK constraints.
2280 *
2281 * (Note that we must still have a separate RI_ConstraintInfo for each
2282 * constraint, because partitions can have different column orders,
2283 * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2284 *
2285 * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2286 * to use memset to clear them.
2287 */
2288 if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2289 key->constr_id = riinfo->constraint_root_id;
2290 else
2291 key->constr_id = riinfo->constraint_id;
2292 key->constr_queryno = constr_queryno;
2293}
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition ri_triggers.c:76

References fb(), 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 642 of file ri_triggers.c.

645{
648 bool result;
649
650 /* Only called for non-null rows */
652
653 SPI_connect();
654
655 /*
656 * Fetch or prepare a saved plan for checking PK table with values coming
657 * from a PK row
658 */
660
661 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
662 {
666 char paramname[16];
667 const char *querysep;
668 const char *pk_only;
670
671 /* ----------
672 * The query string built is
673 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
674 * FOR KEY SHARE OF x
675 * The type id's for the $ parameters are those of the
676 * PK attributes themselves.
677 *
678 * But for temporal FKs we need to make sure
679 * the old PK's range is completely covered.
680 * So we use this query instead:
681 * SELECT 1
682 * FROM (
683 * SELECT pkperiodatt AS r
684 * FROM [ONLY] pktable x
685 * WHERE pkatt1 = $1 [AND ...]
686 * AND pkperiodatt && $n
687 * FOR KEY SHARE OF x
688 * ) x1
689 * HAVING $n <@ range_agg(x1.r)
690 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
691 * we can make this a bit simpler.
692 * ----------
693 */
695 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
696 "" : "ONLY ";
698 if (riinfo->hasperiod)
699 {
700 quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
701
703 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
705 }
706 else
707 {
708 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
710 }
711 querysep = "WHERE";
712 for (int i = 0; i < riinfo->nkeys; i++)
713 {
714 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
715
717 RIAttName(pk_rel, riinfo->pk_attnums[i]));
718 sprintf(paramname, "$%d", i + 1);
721 riinfo->pp_eq_oprs[i],
723 querysep = "AND";
725 }
726 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
727 if (riinfo->hasperiod)
728 {
729 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
730
731 appendStringInfoString(&querybuf, ") x1 HAVING ");
732 sprintf(paramname, "$%d", riinfo->nkeys);
735 riinfo->agged_period_contained_by_oper,
736 "pg_catalog.range_agg", ANYMULTIRANGEOID);
738 }
739
740 /* Prepare and save the plan */
742 &qkey, fk_rel, pk_rel);
743 }
744
745 /*
746 * We have a plan now. Run it.
747 */
749 fk_rel, pk_rel,
750 oldslot, NULL,
751 false,
752 true, /* treat like update */
754
755 if (SPI_finish() != SPI_OK_FINISH)
756 elog(ERROR, "SPI_finish failed");
757
758 return result;
759}
uint32 result
NameData attname
#define sprintf
Definition port.h:262
#define RelationGetDescr(relation)
Definition rel.h:542
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool is_restrict, bool detectNewRows, int expect_OK)
#define RIAttType(rel, attnum)
Definition ri_triggers.c:93
#define MAX_QUOTED_REL_NAME_LEN
Definition ri_triggers.c:90
static void quoteRelationName(char *buffer, Relation rel)
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
#define RI_KEYS_NONE_NULL
Definition ri_triggers.c:71
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
#define MAX_QUOTED_NAME_LEN
Definition ri_triggers.c:89
#define RIAttName(rel, attnum)
Definition ri_triggers.c:92
#define RI_MAX_NUMKEYS
Definition ri_triggers.c:64
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
int SPI_connect(void)
Definition spi.c:95
int SPI_finish(void)
Definition spi.c:183
#define SPI_OK_FINISH
Definition spi.h:83
#define SPI_OK_SELECT
Definition spi.h:86
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
Form_pg_class rd_rel
Definition rel.h:111

References appendStringInfo(), appendStringInfoString(), Assert, attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetDescr, result, ri_BuildQueryKey(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_NONE_NULL, RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CHECK_LOOKUPPK_FROM_PK, ri_PlanCheck(), RIAttName, RIAttType, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, and sprintf.

Referenced by ri_restrict().

◆ ri_CheckPermissions()

static void ri_CheckPermissions ( Relation  query_rel)
static

Definition at line 3314 of file ri_triggers.c.

3315{
3317
3318 /* USAGE on schema. */
3321 GetUserId(), ACL_USAGE);
3322 if (aclresult != ACLCHECK_OK)
3325
3326 /* SELECT on relation. */
3328 ACL_SELECT);
3329 if (aclresult != ACLCHECK_OK)
3332}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
Oid GetUserId(void)
Definition miscinit.c:470
#define ACL_USAGE
Definition parsenodes.h:84
@ OBJECT_SCHEMA
@ OBJECT_TABLE
#define ACL_SELECT
Definition parsenodes.h:77
#define RelationGetRelid(relation)
Definition rel.h:516

References ACL_SELECT, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, fb(), get_namespace_name(), GetUserId(), object_aclcheck(), OBJECT_SCHEMA, OBJECT_TABLE, pg_class_aclcheck(), RelationGetNamespace, RelationGetRelationName, and RelationGetRelid.

Referenced by ri_FastPathBatchFlush(), and ri_FastPathCheck().

◆ ri_CheckTrigger()

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

Definition at line 2299 of file ri_triggers.c.

2300{
2301 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2302
2303 if (!CALLED_AS_TRIGGER(fcinfo))
2304 ereport(ERROR,
2306 errmsg("function \"%s\" was not called by trigger manager", funcname)));
2307
2308 /*
2309 * Check proper event
2310 */
2311 if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2312 !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2313 ereport(ERROR,
2315 errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2316
2317 switch (tgkind)
2318 {
2319 case RI_TRIGTYPE_INSERT:
2320 if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2321 ereport(ERROR,
2323 errmsg("function \"%s\" must be fired for INSERT", funcname)));
2324 break;
2325 case RI_TRIGTYPE_UPDATE:
2326 if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2327 ereport(ERROR,
2329 errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2330 break;
2331 case RI_TRIGTYPE_DELETE:
2332 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2333 ereport(ERROR,
2335 errmsg("function \"%s\" must be fired for DELETE", funcname)));
2336 break;
2337 }
2338}
int errcode(int sqlerrcode)
Definition elog.c:875
#define ereport(elevel,...)
Definition elog.h:152
#define funcname
static char * errmsg
#define RI_TRIGTYPE_INSERT
Definition ri_triggers.c:96
#define RI_TRIGTYPE_DELETE
Definition ri_triggers.c:98
#define RI_TRIGTYPE_UPDATE
Definition ri_triggers.c:97
#define TRIGGER_FIRED_BY_DELETE(event)
Definition trigger.h:115
#define CALLED_AS_TRIGGER(fcinfo)
Definition trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition trigger.h:124
#define TRIGGER_FIRED_AFTER(event)
Definition trigger.h:133
#define TRIGGER_FIRED_BY_INSERT(event)
Definition trigger.h:112
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition trigger.h:118

References CALLED_AS_TRIGGER, FunctionCallInfoBaseData::context, ereport, errcode(), errmsg, ERROR, fb(), funcname, 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 3950 of file ri_triggers.c.

3952{
3953 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3954
3955 /* Do we need to cast the values? */
3956 if (OidIsValid(entry->cast_func_finfo.fn_oid))
3957 {
3959 lhs,
3960 Int32GetDatum(-1), /* typmod */
3961 BoolGetDatum(false)); /* implicit coercion */
3963 rhs,
3964 Int32GetDatum(-1), /* typmod */
3965 BoolGetDatum(false)); /* implicit coercion */
3966 }
3967
3968 /*
3969 * Apply the comparison operator.
3970 *
3971 * Note: This function is part of a call stack that determines whether an
3972 * update to a row is significant enough that it needs checking or action
3973 * on the other side of a foreign-key constraint. Therefore, the
3974 * comparison here would need to be done with the collation of the *other*
3975 * table. For simplicity (e.g., we might not even have the other table
3976 * open), we'll use our own collation. This is fine because we require
3977 * that both collations have the same notion of equality (either they are
3978 * both deterministic or else they are both the same).
3979 *
3980 * With range/multirangetypes, the collation of the base type is stored as
3981 * part of the rangetype (pg_range.rngcollation), and always used, so
3982 * there is no danger of inconsistency even using a non-equals operator.
3983 * But if we support arbitrary types with PERIOD, we should perhaps just
3984 * always force a re-check.
3985 */
3987}
Oid collid
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)

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

3504{
3505 const int16 *attnums;
3506 bool isnull;
3507
3508 if (rel_is_pk)
3509 attnums = riinfo->pk_attnums;
3510 else
3511 attnums = riinfo->fk_attnums;
3512
3513 for (int i = 0; i < riinfo->nkeys; i++)
3514 {
3515 vals[i] = slot_getattr(slot, attnums[i], &isnull);
3516 nulls[i] = isnull ? 'n' : ' ';
3517 }
3518}
int16_t int16
Definition c.h:619
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition tuptable.h:417

References fb(), i, and slot_getattr().

Referenced by ri_FastPathCheck(), ri_FastPathFlushArray(), ri_FastPathFlushLoop(), and ri_PerformCheck().

◆ ri_fastpath_is_applicable()

static bool ri_fastpath_is_applicable ( const RI_ConstraintInfo riinfo)
static

Definition at line 3287 of file ri_triggers.c.

3288{
3289 /*
3290 * Partitioned referenced tables are skipped for simplicity, since they
3291 * require routing the probe through the correct partition using
3292 * PartitionDirectory.
3293 */
3294 if (riinfo->pk_is_partitioned)
3295 return false;
3296
3297 /*
3298 * Temporal foreign keys use range overlap and containment semantics (&&,
3299 * <@, range_agg()) that inherently involve aggregation and multiple-row
3300 * reasoning, so they stay on the SPI path.
3301 */
3302 if (riinfo->hasperiod)
3303 return false;
3304
3305 return true;
3306}

References fb().

Referenced by RI_FKey_check().

◆ ri_FastPathBatchAdd()

static void ri_FastPathBatchAdd ( RI_ConstraintInfo riinfo,
Relation  fk_rel,
TupleTableSlot newslot 
)
static

Definition at line 2859 of file ri_triggers.c.

2861{
2864
2865 oldcxt = MemoryContextSwitchTo(fpentry->flush_cxt);
2866 fpentry->batch[fpentry->batch_count] =
2868 fpentry->batch_count++;
2870
2871 if (fpentry->batch_count >= RI_FASTPATH_BATCH_SIZE)
2873}
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define RI_FASTPATH_BATCH_SIZE
static void ri_FastPathBatchFlush(RI_FastPathEntry *fpentry, Relation fk_rel, RI_ConstraintInfo *riinfo)
static RI_FastPathEntry * ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo, Relation fk_rel)
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition tuptable.h:503

References ExecCopySlotHeapTuple(), fb(), MemoryContextSwitchTo(), RI_FASTPATH_BATCH_SIZE, ri_FastPathBatchFlush(), and ri_FastPathGetEntry().

Referenced by RI_FKey_check().

◆ ri_FastPathBatchFlush()

static void ri_FastPathBatchFlush ( RI_FastPathEntry fpentry,
Relation  fk_rel,
RI_ConstraintInfo riinfo 
)
static

Definition at line 2885 of file ri_triggers.c.

2887{
2888 Relation pk_rel = fpentry->pk_rel;
2889 Relation idx_rel = fpentry->idx_rel;
2890 TupleTableSlot *fk_slot = fpentry->fk_slot;
2891 Snapshot snapshot;
2892 IndexScanDesc scandesc;
2896 int violation_index;
2897
2898 if (fpentry->batch_count == 0)
2899 return;
2900
2901 /*
2902 * CCI and security context switch are done once for the entire batch.
2903 * Per-row CCI is unnecessary because by the time a flush runs, all AFTER
2904 * triggers for the buffered rows have already fired (trigger invocations
2905 * strictly alternate per row), so a single CCI advances past all their
2906 * effects. Per-row security context switch is unnecessary because each
2907 * row's probe runs entirely as the PK table owner, same as the SPI path
2908 * -- the only difference is that the SPI path sets and restores the
2909 * context per row whereas we do it once around the whole batch.
2910 */
2913
2914 /*
2915 * build_index_scankeys() may palloc cast results for cross-type FKs. Use
2916 * the entry's short-lived flush context so these don't accumulate across
2917 * batches.
2918 */
2919 oldcxt = MemoryContextSwitchTo(fpentry->flush_cxt);
2920
2921 scandesc = index_beginscan(pk_rel, idx_rel, snapshot, NULL,
2922 riinfo->nkeys, 0, SO_NONE);
2923
2929
2930 /*
2931 * Check that the current user has permission to access pk_rel. Done here
2932 * rather than at entry creation so that permission changes between
2933 * flushes are respected, matching the per-row behavior of the SPI path,
2934 * albeit checked once per flush rather than once per row, like in
2935 * ri_FastPathCheck().
2936 */
2937 ri_CheckPermissions(pk_rel);
2938
2939 if (riinfo->fpmeta == NULL)
2940 {
2941 /* Reload to ensure it's valid. */
2942 riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2944 }
2945 Assert(riinfo->fpmeta);
2946
2947 /* Skip array overhead for single-row batches. */
2948 if (riinfo->nkeys == 1 && fpentry->batch_count > 1)
2950 fk_rel, snapshot, scandesc);
2951 else
2953 fk_rel, snapshot, scandesc);
2954
2956 UnregisterSnapshot(snapshot);
2957 index_endscan(scandesc);
2958
2959 if (violation_index >= 0)
2960 {
2961 ExecStoreHeapTuple(fpentry->batch[violation_index], fk_slot, false);
2963 fk_slot, NULL,
2964 RI_PLAN_CHECK_LOOKUPPK, false, false);
2965 }
2966
2967 MemoryContextReset(fpentry->flush_cxt);
2969
2970 /* Reset. */
2971 fpentry->batch_count = 0;
2972}
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, IndexScanInstrumentation *instrument, int nkeys, int norderbys, uint32 flags)
Definition indexam.c:257
void index_endscan(IndexScanDesc scan)
Definition indexam.c:394
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
#define SECURITY_NOFORCE_RLS
Definition miscadmin.h:332
#define SECURITY_LOCAL_USERID_CHANGE
Definition miscadmin.h:330
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:613
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:620
#define RelationGetForm(relation)
Definition rel.h:510
static pg_noreturn void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
static int ri_FastPathFlushLoop(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
static void ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo, Relation fk_rel, Relation idx_rel)
#define RI_PLAN_CHECK_LOOKUPPK
Definition ri_triggers.c:75
static int ri_FastPathFlushArray(RI_FastPathEntry *fpentry, TupleTableSlot *fk_slot, const RI_ConstraintInfo *riinfo, Relation fk_rel, Snapshot snapshot, IndexScanDesc scandesc)
static void ri_CheckPermissions(Relation query_rel)
static RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
@ SO_NONE
Definition tableam.h:49
void CommandCounterIncrement(void)
Definition xact.c:1130

References Assert, CommandCounterIncrement(), ExecStoreHeapTuple(), fb(), GetTransactionSnapshot(), GetUserIdAndSecContext(), index_beginscan(), index_endscan(), MemoryContextReset(), MemoryContextSwitchTo(), RegisterSnapshot(), RelationGetForm, ri_CheckPermissions(), ri_FastPathFlushArray(), ri_FastPathFlushLoop(), ri_LoadConstraintInfo(), RI_PLAN_CHECK_LOOKUPPK, ri_populate_fastpath_metadata(), ri_ReportViolation(), SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SO_NONE, and UnregisterSnapshot().

Referenced by ri_FastPathBatchAdd(), and ri_FastPathEndBatch().

◆ ri_FastPathCheck()

static void ri_FastPathCheck ( RI_ConstraintInfo riinfo,
Relation  fk_rel,
TupleTableSlot newslot 
)
static

Definition at line 2780 of file ri_triggers.c.

2782{
2783 Relation pk_rel;
2784 Relation idx_rel;
2785 IndexScanDesc scandesc;
2786 TupleTableSlot *slot;
2790 bool found = false;
2793 Snapshot snapshot;
2794
2795 /*
2796 * Advance the command counter so the snapshot sees the effects of prior
2797 * triggers in this statement. Mirrors what the SPI path does in
2798 * ri_PerformCheck().
2799 */
2802
2803 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
2804 idx_rel = index_open(riinfo->conindid, AccessShareLock);
2805
2806 slot = table_slot_create(pk_rel, NULL);
2807 scandesc = index_beginscan(pk_rel, idx_rel,
2808 snapshot, NULL,
2809 riinfo->nkeys, 0,
2810 SO_NONE);
2811
2817 ri_CheckPermissions(pk_rel);
2818
2819 if (riinfo->fpmeta == NULL)
2820 {
2821 /* Reload to ensure it's valid. */
2822 riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2824 }
2825 Assert(riinfo->fpmeta);
2828 found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, slot,
2829 snapshot, riinfo, skey, riinfo->nkeys);
2831 index_endscan(scandesc);
2833 UnregisterSnapshot(snapshot);
2834
2835 if (!found)
2837 newslot, NULL,
2838 RI_PLAN_CHECK_LOOKUPPK, false, false);
2839
2840 index_close(idx_rel, NoLock);
2841 table_close(pk_rel, NoLock);
2842}
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
#define NoLock
Definition lockdefs.h:34
#define AccessShareLock
Definition lockdefs.h:36
#define RowShareLock
Definition lockdefs.h:37
static void build_index_scankeys(const RI_ConstraintInfo *riinfo, Relation idx_rel, Datum *pk_vals, char *pk_nulls, ScanKey skeys)
static bool ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel, IndexScanDesc scandesc, TupleTableSlot *slot, Snapshot snapshot, const RI_ConstraintInfo *riinfo, ScanKeyData *skey, int nkeys)
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition tableam.c:92

References AccessShareLock, Assert, build_index_scankeys(), CommandCounterIncrement(), ExecDropSingleTupleTableSlot(), fb(), GetTransactionSnapshot(), GetUserIdAndSecContext(), index_beginscan(), index_close(), index_endscan(), INDEX_MAX_KEYS, index_open(), NoLock, RegisterSnapshot(), RelationGetForm, ri_CheckPermissions(), ri_ExtractValues(), ri_FastPathProbeOne(), ri_LoadConstraintInfo(), RI_PLAN_CHECK_LOOKUPPK, ri_populate_fastpath_metadata(), ri_ReportViolation(), RowShareLock, SECURITY_LOCAL_USERID_CHANGE, SECURITY_NOFORCE_RLS, SetUserIdAndSecContext(), SO_NONE, table_close(), table_open(), table_slot_create(), and UnregisterSnapshot().

Referenced by RI_FKey_check().

◆ ri_FastPathEndBatch()

static void ri_FastPathEndBatch ( void arg)
static

Definition at line 4133 of file ri_triggers.c.

4134{
4135 HASH_SEQ_STATUS status;
4136 RI_FastPathEntry *entry;
4137
4138 if (ri_fastpath_cache == NULL)
4139 return;
4140
4141 /* Flush any partial batches -- can throw ERROR */
4143 while ((entry = hash_seq_search(&status)) != NULL)
4144 {
4145 if (entry->batch_count > 0)
4146 {
4149
4152 }
4153 }
4154
4156}
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
static HTAB * ri_fastpath_cache
static void ri_FastPathTeardown(void)

References AccessShareLock, RI_FastPathEntry::batch_count, RI_FastPathEntry::conoid, fb(), RI_FastPathEntry::fk_relid, hash_seq_init(), hash_seq_search(), NoLock, ri_fastpath_cache, ri_FastPathBatchFlush(), ri_FastPathTeardown(), ri_LoadConstraintInfo(), table_close(), and table_open().

Referenced by ri_FastPathGetEntry().

◆ ri_FastPathFlushArray()

static int ri_FastPathFlushArray ( RI_FastPathEntry fpentry,
TupleTableSlot fk_slot,
const RI_ConstraintInfo riinfo,
Relation  fk_rel,
Snapshot  snapshot,
IndexScanDesc  scandesc 
)
static

Definition at line 3030 of file ri_triggers.c.

3033{
3034 FastPathMeta *fpmeta = riinfo->fpmeta;
3035 Relation pk_rel = fpentry->pk_rel;
3036 Relation idx_rel = fpentry->idx_rel;
3037 TupleTableSlot *pk_slot = fpentry->pk_slot;
3039 bool matched[RI_FASTPATH_BATCH_SIZE];
3040 int nvals = fpentry->batch_count;
3043 ScanKeyData skey[1];
3044 FmgrInfo *cast_func_finfo;
3045 FmgrInfo *eq_opr_finfo;
3046 Oid elem_type;
3048 bool elem_byval;
3049 char elem_align;
3050 ArrayType *arr;
3051
3052 Assert(fpmeta);
3053
3054 memset(matched, 0, nvals * sizeof(bool));
3055
3056 /*
3057 * Extract FK values, casting to the operator's expected input type if
3058 * needed (e.g. int8 FK -> int4 for int48eq).
3059 */
3060 cast_func_finfo = &fpmeta->cast_func_finfo[0];
3061 eq_opr_finfo = &fpmeta->eq_opr_finfo[0];
3062 for (int i = 0; i < nvals; i++)
3063 {
3064 ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
3065 ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
3066
3067 /* Cast if needed (e.g. int8 FK -> numeric PK) */
3068 if (OidIsValid(cast_func_finfo->fn_oid))
3069 search_vals[i] = FunctionCall3(cast_func_finfo,
3070 pk_vals[0],
3071 Int32GetDatum(-1),
3072 BoolGetDatum(false));
3073 else
3074 search_vals[i] = pk_vals[0];
3075 }
3076
3077 /*
3078 * Array element type must match the operator's right-hand input type,
3079 * which is what the index comparison expects on the search side.
3080 * ri_populate_fastpath_metadata() stores exactly this via
3081 * get_op_opfamily_properties(), which returns the operator's right-hand
3082 * type as the subtype for cross-type operators (e.g. int8 for int48eq)
3083 * and the common type for same-type operators.
3084 */
3085 elem_type = fpmeta->subtypes[0];
3088
3091
3092 /*
3093 * Build scan key with SK_SEARCHARRAY. The index AM code will internally
3094 * sort and deduplicate, then walk leaf pages in order.
3095 *
3096 * PK indexes are always btree, which supports SK_SEARCHARRAY.
3097 *
3098 * This path handles single-column FKs only, so index_attnos[0] == 1.
3099 */
3100 Assert(idx_rel->rd_indam->amsearcharray);
3101 Assert(fpmeta->index_attnos[0] == 1);
3104 fpmeta->index_attnos[0],
3105 fpmeta->strats[0],
3106 fpmeta->subtypes[0],
3107 idx_rel->rd_indcollation[fpmeta->index_attnos[0] - 1],
3108 fpmeta->regops[0],
3109 PointerGetDatum(arr));
3110
3111 index_rescan(scandesc, skey, 1, NULL, 0);
3112
3113 /*
3114 * Walk all matches. The index AM returns them in index order. For each
3115 * match, find which batch item(s) it satisfies.
3116 */
3117 while (index_getnext_slot(scandesc, ForwardScanDirection, pk_slot))
3118 {
3120 bool found_null;
3123
3124 if (!ri_LockPKTuple(pk_rel, pk_slot, snapshot, &concurrently_updated))
3125 continue;
3126
3127 /* Extract the PK value from the matched and locked tuple */
3128 found_val = slot_getattr(pk_slot, riinfo->pk_attnums[0], &found_null);
3130
3132 {
3133 /*
3134 * Build a single-key scankey for recheck. We need the actual PK
3135 * value that was found, not the FK search value.
3136 */
3138 fpmeta->strats[0],
3139 fpmeta->subtypes[0],
3140 idx_rel->rd_indcollation[0],
3141 fpmeta->regops[0],
3142 found_val);
3143 if (!recheck_matched_pk_tuple(idx_rel, recheck_skey, 1, pk_slot))
3144 continue;
3145 }
3146
3147 /*
3148 * Linear scan to mark all batch items matching this PK value.
3149 * O(batch_size) per match, O(batch_size^2) worst case -- fine for the
3150 * current batch size of 64.
3151 */
3152 for (int i = 0; i < nvals; i++)
3153 {
3154 if (!matched[i] &&
3155 DatumGetBool(FunctionCall2Coll(eq_opr_finfo,
3156 idx_rel->rd_indcollation[0],
3157 found_val,
3158 search_vals[i])))
3159 matched[i] = true;
3160 }
3161 }
3162
3163 /* Report first unmatched row */
3164 for (int i = 0; i < nvals; i++)
3165 if (!matched[i])
3166 return i;
3167
3168 /* All pass. */
3169 return -1;
3170}
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition indexam.c:698
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition indexam.c:368
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2464
#define PointerGetDatum(X)
Definition postgres.h:354
static bool recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys, int nkeys, TupleTableSlot *new_slot)
static bool ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap, bool *concurrently_updated)
@ ForwardScanDirection
Definition sdir.h:28
#define SK_SEARCHARRAY
Definition skey.h:120
FmgrInfo eq_opr_finfo[RI_MAX_NUMKEYS]
bool amsearcharray
Definition amapi.h:264
const struct IndexAmRoutine * rd_indam
Definition rel.h:206

References IndexAmRoutine::amsearcharray, Assert, BoolGetDatum(), FastPathMeta::cast_func_finfo, construct_array(), DatumGetBool(), FastPathMeta::eq_opr_finfo, ExecStoreHeapTuple(), fb(), FmgrInfo::fn_oid, ForwardScanDirection, FunctionCall2Coll(), FunctionCall3, get_typlenbyvalalign(), i, FastPathMeta::index_attnos, index_getnext_slot(), INDEX_MAX_KEYS, index_rescan(), Int32GetDatum(), OidIsValid, PointerGetDatum, RelationData::rd_indam, RelationData::rd_indcollation, recheck_matched_pk_tuple(), FastPathMeta::regops, ri_ExtractValues(), RI_FASTPATH_BATCH_SIZE, ri_LockPKTuple(), ScanKeyEntryInitialize(), SK_SEARCHARRAY, slot_getattr(), FastPathMeta::strats, and FastPathMeta::subtypes.

Referenced by ri_FastPathBatchFlush().

◆ ri_FastPathFlushLoop()

static int ri_FastPathFlushLoop ( RI_FastPathEntry fpentry,
TupleTableSlot fk_slot,
const RI_ConstraintInfo riinfo,
Relation  fk_rel,
Snapshot  snapshot,
IndexScanDesc  scandesc 
)
static

Definition at line 2986 of file ri_triggers.c.

2989{
2990 Relation pk_rel = fpentry->pk_rel;
2991 Relation idx_rel = fpentry->idx_rel;
2992 TupleTableSlot *pk_slot = fpentry->pk_slot;
2996 bool found = true;
2997
2998 for (int i = 0; i < fpentry->batch_count; i++)
2999 {
3000 ExecStoreHeapTuple(fpentry->batch[i], fk_slot, false);
3001 ri_ExtractValues(fk_rel, fk_slot, riinfo, false, pk_vals, pk_nulls);
3003
3004 found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, pk_slot,
3005 snapshot, riinfo, skey, riinfo->nkeys);
3006
3007 /* Report first unmatched row */
3008 if (!found)
3009 return i;
3010 }
3011
3012 /* All pass. */
3013 return -1;
3014}

References build_index_scankeys(), ExecStoreHeapTuple(), fb(), i, INDEX_MAX_KEYS, ri_ExtractValues(), and ri_FastPathProbeOne().

Referenced by ri_FastPathBatchFlush().

◆ ri_FastPathGetEntry()

static RI_FastPathEntry * ri_FastPathGetEntry ( const RI_ConstraintInfo riinfo,
Relation  fk_rel 
)
static

Definition at line 4234 of file ri_triggers.c.

4235{
4236 RI_FastPathEntry *entry;
4237 bool found;
4238
4239 /* Create hash table on first use in this batch */
4240 if (ri_fastpath_cache == NULL)
4241 {
4242 HASHCTL ctl;
4243
4245 {
4249 }
4250
4251 ctl.keysize = sizeof(Oid);
4252 ctl.entrysize = sizeof(RI_FastPathEntry);
4254 ri_fastpath_cache = hash_create("RI fast-path cache",
4255 16,
4256 &ctl,
4258 }
4259
4260 entry = hash_search(ri_fastpath_cache, &riinfo->constraint_id,
4261 HASH_ENTER, &found);
4262
4263 if (!found)
4264 {
4266
4267 /*
4268 * Zero out non-key fields so ri_FastPathTeardown is safe if we error
4269 * out during partial initialization below.
4270 */
4271 memset(((char *) entry) + offsetof(RI_FastPathEntry, pk_rel), 0,
4272 sizeof(RI_FastPathEntry) - offsetof(RI_FastPathEntry, pk_rel));
4273
4275
4276 entry->fk_relid = RelationGetRelid(fk_rel);
4277
4278 /*
4279 * Open PK table and its unique index.
4280 *
4281 * RowShareLock on pk_rel matches what the SPI path's SELECT ... FOR
4282 * KEY SHARE would acquire as a relation-level lock. AccessShareLock
4283 * on the index is standard for index scans.
4284 *
4285 * We don't release these locks until end of transaction, matching SPI
4286 * behavior.
4287 */
4288 entry->pk_rel = table_open(riinfo->pk_relid, RowShareLock);
4289 entry->idx_rel = index_open(riinfo->conindid, AccessShareLock);
4290 entry->pk_slot = table_slot_create(entry->pk_rel, NULL);
4291
4292 /*
4293 * Must be TTSOpsHeapTuple because ExecStoreHeapTuple() is used to
4294 * load entries from batch[] into this slot for value extraction.
4295 */
4298
4300 "RI fast path flush temporary context",
4303
4304 /* Ensure cleanup at end of this trigger-firing batch */
4306 {
4309 }
4310 }
4311
4312 return entry;
4313}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsHeapTuple
Definition execTuples.c:85
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
MemoryContext TopTransactionContext
Definition mcxt.c:171
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition memutils.h:170
tree ctl
Definition radixtree.h:1838
static void ri_FastPathEndBatch(void *arg)
static bool ri_fastpath_xact_callback_registered
static void ri_FastPathSubXactCallback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
static bool ri_fastpath_callback_registered
static void ri_FastPathXactCallback(XactEvent event, void *arg)
void RegisterAfterTriggerBatchCallback(AfterTriggerBatchCallback callback, void *arg)
Definition trigger.c:6833
void RegisterXactCallback(XactCallback callback, void *arg)
Definition xact.c:3855
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition xact.c:3915

References AccessShareLock, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, ctl, fb(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), index_open(), MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), RegisterAfterTriggerBatchCallback(), RegisterSubXactCallback(), RegisterXactCallback(), RelationGetDescr, RelationGetRelid, ri_fastpath_cache, ri_fastpath_callback_registered, ri_fastpath_xact_callback_registered, ri_FastPathEndBatch(), ri_FastPathSubXactCallback(), ri_FastPathXactCallback(), RowShareLock, table_open(), table_slot_create(), TopTransactionContext, and TTSOpsHeapTuple.

Referenced by ri_FastPathBatchAdd().

◆ ri_FastPathProbeOne()

static bool ri_FastPathProbeOne ( Relation  pk_rel,
Relation  idx_rel,
IndexScanDesc  scandesc,
TupleTableSlot slot,
Snapshot  snapshot,
const RI_ConstraintInfo riinfo,
ScanKeyData skey,
int  nkeys 
)
static

Definition at line 3181 of file ri_triggers.c.

3185{
3186 bool found = false;
3187
3188 index_rescan(scandesc, skey, nkeys, NULL, 0);
3189
3190 if (index_getnext_slot(scandesc, ForwardScanDirection, slot))
3191 {
3193
3194 if (ri_LockPKTuple(pk_rel, slot, snapshot,
3196 {
3198 found = recheck_matched_pk_tuple(idx_rel, skey, nkeys, slot);
3199 else
3200 found = true;
3201 }
3202 }
3203
3204 return found;
3205}

References fb(), ForwardScanDirection, index_getnext_slot(), index_rescan(), recheck_matched_pk_tuple(), and ri_LockPKTuple().

Referenced by ri_FastPathCheck(), and ri_FastPathFlushLoop().

◆ ri_FastPathSubXactCallback()

static void ri_FastPathSubXactCallback ( SubXactEvent  event,
SubTransactionId  mySubid,
SubTransactionId  parentSubid,
void arg 
)
static

Definition at line 4208 of file ri_triggers.c.

4210{
4211 if (event == SUBXACT_EVENT_ABORT_SUB)
4212 {
4213 /*
4214 * ResourceOwner already released relations. NULL the static pointers
4215 * so the still-registered batch callback becomes a no-op for the rest
4216 * of this transaction.
4217 */
4220 }
4221}
@ SUBXACT_EVENT_ABORT_SUB
Definition xact.h:145

References fb(), ri_fastpath_cache, ri_fastpath_callback_registered, and SUBXACT_EVENT_ABORT_SUB.

Referenced by ri_FastPathGetEntry().

◆ ri_FastPathTeardown()

static void ri_FastPathTeardown ( void  )
static

Definition at line 4165 of file ri_triggers.c.

4166{
4167 HASH_SEQ_STATUS status;
4168 RI_FastPathEntry *entry;
4169
4170 if (ri_fastpath_cache == NULL)
4171 return;
4172
4174 while ((entry = hash_seq_search(&status)) != NULL)
4175 {
4176 if (entry->idx_rel)
4177 index_close(entry->idx_rel, NoLock);
4178 if (entry->pk_rel)
4179 table_close(entry->pk_rel, NoLock);
4180 if (entry->pk_slot)
4182 if (entry->fk_slot)
4184 if (entry->flush_cxt)
4186 }
4187
4191}
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
TupleTableSlot * fk_slot
TupleTableSlot * pk_slot
MemoryContext flush_cxt

References ExecDropSingleTupleTableSlot(), fb(), RI_FastPathEntry::fk_slot, RI_FastPathEntry::flush_cxt, hash_destroy(), hash_seq_init(), hash_seq_search(), RI_FastPathEntry::idx_rel, index_close(), MemoryContextDelete(), NoLock, RI_FastPathEntry::pk_rel, RI_FastPathEntry::pk_slot, ri_fastpath_cache, ri_fastpath_callback_registered, and table_close().

Referenced by ri_FastPathEndBatch().

◆ ri_FastPathXactCallback()

static void ri_FastPathXactCallback ( XactEvent  event,
void arg 
)
static

Definition at line 4196 of file ri_triggers.c.

4197{
4198 /*
4199 * On abort, ResourceOwner already released relations; on commit,
4200 * ri_FastPathTeardown already ran. Either way, just NULL the static
4201 * pointers so they don't dangle into the next transaction.
4202 */
4205}

References fb(), ri_fastpath_cache, and ri_fastpath_callback_registered.

Referenced by ri_FastPathGetEntry().

◆ ri_FetchConstraintInfo()

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

Definition at line 2345 of file ri_triggers.c.

2346{
2347 Oid constraintOid = trigger->tgconstraint;
2349
2350 /*
2351 * Check that the FK constraint's OID is available; it might not be if
2352 * we've been invoked via an ordinary trigger or an old-style "constraint
2353 * trigger".
2354 */
2356 ereport(ERROR,
2358 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2360 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2361
2362 /* Find or create a hashtable entry for the constraint */
2364
2365 /* Do some easy cross-checks against the trigger call data */
2366 if (rel_is_pk)
2367 {
2368 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2369 riinfo->pk_relid != RelationGetRelid(trig_rel))
2370 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2372 }
2373 else
2374 {
2375 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2376 riinfo->pk_relid != trigger->tgconstrrelid)
2377 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2379 }
2380
2381 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2382 riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
2383 riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
2384 elog(ERROR, "unrecognized confmatchtype: %d",
2385 riinfo->confmatchtype);
2386
2387 if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2388 ereport(ERROR,
2390 errmsg("MATCH PARTIAL not yet implemented")));
2391
2392 return riinfo;
2393}
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FKCONSTR_MATCH_SIMPLE
#define FKCONSTR_MATCH_PARTIAL
#define FKCONSTR_MATCH_FULL

References elog, ereport, errcode(), errhint(), errmsg, ERROR, fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, OidIsValid, RelationGetRelationName, RelationGetRelid, and ri_LoadConstraintInfo().

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

3776{
3777 RI_QueryHashEntry *entry;
3779
3780 /*
3781 * On the first call initialize the hashtable
3782 */
3783 if (!ri_query_cache)
3785
3786 /*
3787 * Lookup for the key
3788 */
3790 key,
3791 HASH_FIND, NULL);
3792 if (entry == NULL)
3793 return NULL;
3794
3795 /*
3796 * Check whether the plan is still valid. If it isn't, we don't want to
3797 * simply rely on plancache.c to regenerate it; rather we should start
3798 * from scratch and rebuild the query text too. This is to cover cases
3799 * such as table/column renames. We depend on the plancache machinery to
3800 * detect possible invalidations, though.
3801 *
3802 * CAUTION: this check is only trustworthy if the caller has already
3803 * locked both FK and PK rels.
3804 */
3805 plan = entry->plan;
3806 if (plan && SPI_plan_is_valid(plan))
3807 return plan;
3808
3809 /*
3810 * Otherwise we might as well flush the cached plan now, to free a little
3811 * memory space before we make a new one.
3812 */
3813 entry->plan = NULL;
3814 if (plan)
3816
3817 return NULL;
3818}
@ HASH_FIND
Definition hsearch.h:108
#define plan(x)
Definition pg_regress.c:164
static HTAB * ri_query_cache
static void ri_InitHashTables(void)
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition spi.c:1949
int SPI_freeplan(SPIPlanPtr plan)
Definition spi.c:1026

References fb(), HASH_FIND, hash_search(), 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 1046 of file ri_triggers.c.

1047{
1048 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1051 Relation pk_rel;
1055
1056 /* Check that this is a valid trigger call on the right time and event. */
1057 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
1058
1059 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1060 trigdata->tg_relation, true);
1061
1062 /*
1063 * Get the relation descriptors of the FK and PK tables and the old tuple.
1064 *
1065 * fk_rel is opened in RowExclusiveLock mode since that's what our
1066 * eventual DELETE will get on it.
1067 */
1069 pk_rel = trigdata->tg_relation;
1070 oldslot = trigdata->tg_trigslot;
1071
1072 SPI_connect();
1073
1074 /* Fetch or prepare a saved plan for the cascaded delete */
1076
1077 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1078 {
1082 char paramname[16];
1083 const char *querysep;
1085 const char *fk_only;
1086
1087 /* ----------
1088 * The query string built is
1089 * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
1090 * The type id's for the $ parameters are those of the
1091 * corresponding PK attributes.
1092 * ----------
1093 */
1095 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1096 "" : "ONLY ";
1098 appendStringInfo(&querybuf, "DELETE FROM %s%s",
1100 querysep = "WHERE";
1101 for (int i = 0; i < riinfo->nkeys; i++)
1102 {
1103 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1104 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1105
1107 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1108 sprintf(paramname, "$%d", i + 1);
1111 riinfo->pf_eq_oprs[i],
1112 attname, fk_type);
1113 querysep = "AND";
1114 queryoids[i] = pk_type;
1115 }
1116
1117 /* Prepare and save the plan */
1118 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1119 &qkey, fk_rel, pk_rel);
1120 }
1121
1122 /*
1123 * We have a plan now. Build up the arguments from the key values in the
1124 * deleted PK tuple and delete the referencing rows
1125 */
1127 fk_rel, pk_rel,
1128 oldslot, NULL,
1129 false,
1130 true, /* must detect new rows */
1132
1133 if (SPI_finish() != SPI_OK_FINISH)
1134 elog(ERROR, "SPI_finish failed");
1135
1137
1138 return PointerGetDatum(NULL);
1139}
#define RowExclusiveLock
Definition lockdefs.h:38
#define RI_PLAN_CASCADE_ONDELETE
Definition ri_triggers.c:79
static RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
#define SPI_OK_DELETE
Definition spi.h:89

References appendStringInfo(), attname, elog, ERROR, fb(), 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 1148 of file ri_triggers.c.

1149{
1150 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1153 Relation pk_rel;
1158
1159 /* Check that this is a valid trigger call on the right time and event. */
1160 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1161
1162 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1163 trigdata->tg_relation, true);
1164
1165 /*
1166 * Get the relation descriptors of the FK and PK tables and the new and
1167 * old tuple.
1168 *
1169 * fk_rel is opened in RowExclusiveLock mode since that's what our
1170 * eventual UPDATE will get on it.
1171 */
1173 pk_rel = trigdata->tg_relation;
1174 newslot = trigdata->tg_newslot;
1175 oldslot = trigdata->tg_trigslot;
1176
1177 SPI_connect();
1178
1179 /* Fetch or prepare a saved plan for the cascaded update */
1181
1182 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1183 {
1188 char paramname[16];
1189 const char *querysep;
1190 const char *qualsep;
1192 const char *fk_only;
1193
1194 /* ----------
1195 * The query string built is
1196 * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1197 * WHERE $n = fkatt1 [AND ...]
1198 * The type id's for the $ parameters are those of the
1199 * corresponding PK attributes. Note that we are assuming
1200 * there is an assignment cast from the PK to the FK type;
1201 * else the parser will fail.
1202 * ----------
1203 */
1206 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1207 "" : "ONLY ";
1209 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1211 querysep = "";
1212 qualsep = "WHERE";
1213 for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1214 {
1215 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1216 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1217
1219 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1221 "%s %s = $%d",
1222 querysep, attname, i + 1);
1223 sprintf(paramname, "$%d", j + 1);
1226 riinfo->pf_eq_oprs[i],
1227 attname, fk_type);
1228 querysep = ",";
1229 qualsep = "AND";
1230 queryoids[i] = pk_type;
1231 queryoids[j] = pk_type;
1232 }
1234
1235 /* Prepare and save the plan */
1236 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1237 &qkey, fk_rel, pk_rel);
1238 }
1239
1240 /*
1241 * We have a plan now. Run it to update the existing references.
1242 */
1244 fk_rel, pk_rel,
1246 false,
1247 true, /* must detect new rows */
1249
1250 if (SPI_finish() != SPI_OK_FINISH)
1251 elog(ERROR, "SPI_finish failed");
1252
1254
1255 return PointerGetDatum(NULL);
1256}
int j
Definition isn.c:78
#define RI_PLAN_CASCADE_ONUPDATE
Definition ri_triggers.c:80
#define SPI_OK_UPDATE
Definition spi.h:90
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281

References appendBinaryStringInfo(), appendStringInfo(), attname, elog, ERROR, fb(), i, initStringInfo(), j, 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 358 of file ri_triggers.c.

359{
362 Relation pk_rel;
366
368 trigdata->tg_relation, false);
369
370 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
371 newslot = trigdata->tg_newslot;
372 else
373 newslot = trigdata->tg_trigslot;
374
375 /*
376 * We should not even consider checking the row if it is no longer valid,
377 * since it was either deleted (so the deferred check should be skipped)
378 * or updated (in which case only the latest version of the row should be
379 * checked). Test its liveness according to SnapshotSelf. We need pin
380 * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
381 * should be holding pin, but not lock.
382 */
384 return PointerGetDatum(NULL);
385
386 fk_rel = trigdata->tg_relation;
387
389 {
390 case RI_KEYS_ALL_NULL:
391
392 /*
393 * No further check needed - an all-NULL key passes every type of
394 * foreign key constraint.
395 */
396 return PointerGetDatum(NULL);
397
399
400 /*
401 * This is the only case that differs between the three kinds of
402 * MATCH.
403 */
404 switch (riinfo->confmatchtype)
405 {
407
408 /*
409 * Not allowed - MATCH FULL says either all or none of the
410 * attributes can be NULLs
411 */
414 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
416 NameStr(riinfo->conname)),
417 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
419 NameStr(riinfo->conname))));
420 return PointerGetDatum(NULL);
421
423
424 /*
425 * MATCH SIMPLE - if ANY column is null, the key passes
426 * the constraint.
427 */
428 return PointerGetDatum(NULL);
429
430#ifdef NOT_USED
432
433 /*
434 * MATCH PARTIAL - all non-null columns must match. (not
435 * implemented, can be done by modifying the query below
436 * to only include non-null columns, or by writing a
437 * special version here)
438 */
439 break;
440#endif
441 }
442
444
445 /*
446 * Have a full qualified key - continue below for all three kinds
447 * of MATCH.
448 */
449 break;
450 }
451
452 /*
453 * Fast path: probe the PK unique index directly, bypassing SPI.
454 *
455 * For non-partitioned, non-temporal FKs, we can skip the SPI machinery
456 * (plan cache, executor setup, etc.) and do a direct index scan + tuple
457 * lock. This is semantically equivalent to the SPI path below but avoids
458 * the per-row executor overhead.
459 *
460 * ri_FastPathBatchAdd() and ri_FastPathCheck() report the violation
461 * themselves if no matching PK row is found, so they only return on
462 * success.
463 */
465 {
467 {
468 /* Batched path: buffer and probe in groups */
470 }
471 else
472 {
473 /* ALTER TABLE validation: per-row, no cache */
475 }
476 return PointerGetDatum(NULL);
477 }
478
479 SPI_connect();
480
481 /*
482 * pk_rel is opened in RowShareLock mode since that's what our eventual
483 * SELECT FOR KEY SHARE will get on it.
484 */
485 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
486
487 /* Fetch or prepare a saved plan for the real check */
489
490 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
491 {
495 char paramname[16];
496 const char *querysep;
498 const char *pk_only;
499
500 /* ----------
501 * The query string built is
502 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
503 * FOR KEY SHARE OF x
504 * The type id's for the $ parameters are those of the
505 * corresponding FK attributes.
506 *
507 * But for temporal FKs we need to make sure
508 * the FK's range is completely covered.
509 * So we use this query instead:
510 * SELECT 1
511 * FROM (
512 * SELECT pkperiodatt AS r
513 * FROM [ONLY] pktable x
514 * WHERE pkatt1 = $1 [AND ...]
515 * AND pkperiodatt && $n
516 * FOR KEY SHARE OF x
517 * ) x1
518 * HAVING $n <@ range_agg(x1.r)
519 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
520 * we can make this a bit simpler.
521 * ----------
522 */
524 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
525 "" : "ONLY ";
527 if (riinfo->hasperiod)
528 {
530 RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
531
533 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
535 }
536 else
537 {
538 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
540 }
541 querysep = "WHERE";
542 for (int i = 0; i < riinfo->nkeys; i++)
543 {
544 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
545 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
546
548 RIAttName(pk_rel, riinfo->pk_attnums[i]));
549 sprintf(paramname, "$%d", i + 1);
552 riinfo->pf_eq_oprs[i],
554 querysep = "AND";
556 }
557 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
558 if (riinfo->hasperiod)
559 {
560 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
561
562 appendStringInfoString(&querybuf, ") x1 HAVING ");
563 sprintf(paramname, "$%d", riinfo->nkeys);
566 riinfo->agged_period_contained_by_oper,
567 "pg_catalog.range_agg", ANYMULTIRANGEOID);
569 }
570
571 /* Prepare and save the plan */
573 &qkey, fk_rel, pk_rel);
574 }
575
576 /*
577 * Now check that foreign key exists in PK table
578 *
579 * XXX detectNewRows must be true when a partitioned table is on the
580 * referenced side. The reason is that our snapshot must be fresh in
581 * order for the hack in find_inheritance_children() to work.
582 */
584 fk_rel, pk_rel,
585 NULL, newslot,
586 false,
587 pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
589
590 if (SPI_finish() != SPI_OK_FINISH)
591 elog(ERROR, "SPI_finish failed");
592
593 table_close(pk_rel, RowShareLock);
594
595 return PointerGetDatum(NULL);
596}
#define NameStr(name)
Definition c.h:835
int errdetail(const char *fmt,...) pg_attribute_printf(1
int errtableconstraint(Relation rel, const char *conname)
Definition relcache.c:6117
#define RI_KEYS_SOME_NULL
Definition ri_triggers.c:70
static void ri_FastPathCheck(RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
static void ri_FastPathBatchAdd(RI_ConstraintInfo *riinfo, Relation fk_rel, TupleTableSlot *newslot)
#define RI_KEYS_ALL_NULL
Definition ri_triggers.c:69
static bool ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo)
#define SnapshotSelf
Definition snapmgr.h:32
Relation tg_relation
Definition trigger.h:35
TriggerEvent tg_event
Definition trigger.h:34
TupleTableSlot * tg_trigslot
Definition trigger.h:39
TupleTableSlot * tg_newslot
Definition trigger.h:40
Trigger * tg_trigger
Definition trigger.h:38
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition tableam.h:1391
bool AfterTriggerIsActive(void)
Definition trigger.c:6898

References AfterTriggerIsActive(), appendStringInfo(), appendStringInfoString(), attname, elog, ereport, errcode(), errdetail(), errmsg, ERROR, errtableconstraint(), fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NameStr, PointerGetDatum, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, ri_BuildQueryKey(), ri_fastpath_is_applicable(), ri_FastPathBatchAdd(), ri_FastPathCheck(), 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 605 of file ri_triggers.c.

606{
607 /* Check that this is a valid trigger call on the right time and event. */
608 ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
609
610 /* Share code with UPDATE case. */
611 return RI_FKey_check((TriggerData *) fcinfo->context);
612}
static Datum RI_FKey_check(TriggerData *trigdata)

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

622{
623 /* Check that this is a valid trigger call on the right time and event. */
624 ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
625
626 /* Share code with INSERT case. */
627 return RI_FKey_check((TriggerData *) fcinfo->context);
628}

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

1551{
1553 int ri_nullcheck;
1554
1555 /*
1556 * AfterTriggerSaveEvent() handles things such that this function is never
1557 * called for partitioned tables.
1558 */
1559 Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1560
1562
1564
1565 /*
1566 * If all new key values are NULL, the row satisfies the constraint, so no
1567 * check is needed.
1568 */
1570 return false;
1571
1572 /*
1573 * If some new key values are NULL, the behavior depends on the match
1574 * type.
1575 */
1576 else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1577 {
1578 switch (riinfo->confmatchtype)
1579 {
1581
1582 /*
1583 * If any new key value is NULL, the row must satisfy the
1584 * constraint, so no check is needed.
1585 */
1586 return false;
1587
1589
1590 /*
1591 * Don't know, must run full check.
1592 */
1593 break;
1594
1596
1597 /*
1598 * If some new key values are NULL, the row fails the
1599 * constraint. We must not throw error here, because the row
1600 * might get invalidated before the constraint is to be
1601 * checked, but we should queue the event to apply the check
1602 * later.
1603 */
1604 return true;
1605 }
1606 }
1607
1608 /*
1609 * Continues here for no new key values are NULL, or we couldn't decide
1610 * yet.
1611 */
1612
1613 /*
1614 * If the original row was inserted by our own transaction, we must fire
1615 * the trigger whether or not the keys are equal. This is because our
1616 * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1617 * not do anything; so we had better do the UPDATE check. (We could skip
1618 * this if we knew the INSERT trigger already fired, but there is no easy
1619 * way to know that.)
1620 */
1622 return true;
1623
1624 /* If all old and new key values are equal, no check is needed */
1625 if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1626 return false;
1627
1628 /* Else we need to fire the trigger. */
1629 return true;
1630}
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition tuptable.h:467

References Assert, fb(), FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, 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 770 of file ri_triggers.c.

771{
772 /* Check that this is a valid trigger call on the right time and event. */
773 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
774
775 /* Share code with RESTRICT/UPDATE cases. */
776 return ri_restrict((TriggerData *) fcinfo->context, true);
777}
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)

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

◆ RI_FKey_noaction_upd()

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS  )

Definition at line 807 of file ri_triggers.c.

808{
809 /* Check that this is a valid trigger call on the right time and event. */
810 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
811
812 /* Share code with RESTRICT/DELETE cases. */
813 return ri_restrict((TriggerData *) fcinfo->context, true);
814}

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

1519{
1521
1522 riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1523
1524 /*
1525 * If any old key value is NULL, the row could not have been referenced by
1526 * an FK row, so no check is needed.
1527 */
1529 return false;
1530
1531 /* If all old and new key values are equal, no check is needed */
1532 if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1533 return false;
1534
1535 /* Else we need to fire the trigger. */
1536 return true;
1537}

References fb(), 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 790 of file ri_triggers.c.

791{
792 /* Check that this is a valid trigger call on the right time and event. */
793 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
794
795 /* Share code with NO ACTION/UPDATE cases. */
796 return ri_restrict((TriggerData *) fcinfo->context, false);
797}

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

◆ RI_FKey_restrict_upd()

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS  )

Definition at line 827 of file ri_triggers.c.

828{
829 /* Check that this is a valid trigger call on the right time and event. */
830 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
831
832 /* Share code with NO ACTION/DELETE cases. */
833 return ri_restrict((TriggerData *) fcinfo->context, false);
834}

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

◆ RI_FKey_setdefault_del()

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS  )

Definition at line 1295 of file ri_triggers.c.

1296{
1297 /* Check that this is a valid trigger call on the right time and event. */
1298 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1299
1300 /* Share code with UPDATE case */
1301 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1302}
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)

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

◆ RI_FKey_setdefault_upd()

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS  )

Definition at line 1310 of file ri_triggers.c.

1311{
1312 /* Check that this is a valid trigger call on the right time and event. */
1313 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1314
1315 /* Share code with DELETE case */
1316 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1317}

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

◆ RI_FKey_setnull_del()

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS  )

Definition at line 1265 of file ri_triggers.c.

1266{
1267 /* Check that this is a valid trigger call on the right time and event. */
1268 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1269
1270 /* Share code with UPDATE case */
1271 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1272}

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

◆ RI_FKey_setnull_upd()

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS  )

Definition at line 1280 of file ri_triggers.c.

1281{
1282 /* Check that this is a valid trigger call on the right time and event. */
1283 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1284
1285 /* Share code with DELETE case */
1286 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1287}

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

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 4098 of file ri_triggers.c.

4099{
4100 switch (tgfoid)
4101 {
4112 return RI_TRIGGER_PK;
4113
4116 return RI_TRIGGER_FK;
4117 }
4118
4119 return RI_TRIGGER_NONE;
4120}
#define RI_TRIGGER_FK
Definition trigger.h:287
#define RI_TRIGGER_NONE
Definition trigger.h:288
#define RI_TRIGGER_PK
Definition trigger.h:286

References fb(), 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 2199 of file ri_triggers.c.

2204{
2205 appendStringInfo(buf, " %s ", sep);
2208}
static char buf[DEFAULT_XLOG_SEG_SIZE]
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)

References appendStringInfo(), buf, fb(), 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 2226 of file ri_triggers.c.

2227{
2228 HeapTuple tp;
2230 char *collname;
2232
2233 /* Nothing to do if it's a noncollatable data type */
2234 if (!OidIsValid(collation))
2235 return;
2236
2237 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2238 if (!HeapTupleIsValid(tp))
2239 elog(ERROR, "cache lookup failed for collation %u", collation);
2241 collname = NameStr(colltup->collname);
2242
2243 /*
2244 * We qualify the name always, for simplicity and to ensure the query is
2245 * not search-path-dependent.
2246 */
2248 appendStringInfo(buf, " COLLATE %s", onename);
2249 quoteOneName(onename, collname);
2250 appendStringInfo(buf, ".%s", onename);
2251
2252 ReleaseSysCache(tp);
2253}
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation

References appendStringInfo(), buf, elog, ERROR, fb(), Form_pg_collation, 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 3999 of file ri_triggers.c.

4000{
4002 RI_CompareHashEntry *entry;
4003 bool found;
4004
4005 /*
4006 * On the first call initialize the hashtable
4007 */
4008 if (!ri_compare_cache)
4010
4011 /*
4012 * Find or create a hash entry. Note we're assuming RI_CompareKey
4013 * contains no struct padding.
4014 */
4015 key.eq_opr = eq_opr;
4016 key.typeid = typeid;
4018 &key,
4019 HASH_ENTER, &found);
4020 if (!found)
4021 entry->valid = false;
4022
4023 /*
4024 * If not already initialized, do so. Since we'll keep this hash entry
4025 * for the life of the backend, put any subsidiary info for the function
4026 * cache structs into TopMemoryContext.
4027 */
4028 if (!entry->valid)
4029 {
4030 Oid lefttype,
4031 righttype,
4032 castfunc;
4033 CoercionPathType pathtype;
4034
4035 /* We always need to know how to call the equality operator */
4036 fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
4038
4039 /*
4040 * If we chose to use a cast from FK to PK type, we may have to apply
4041 * the cast function to get to the operator's input type.
4042 *
4043 * XXX eventually it would be good to support array-coercion cases
4044 * here and in ri_CompareWithCast(). At the moment there is no point
4045 * because cases involving nonidentical array types will be rejected
4046 * at constraint creation time.
4047 *
4048 * XXX perhaps also consider supporting CoerceViaIO? No need at the
4049 * moment since that will never be generated for implicit coercions.
4050 */
4051 op_input_types(eq_opr, &lefttype, &righttype);
4052
4053 /*
4054 * pf_eq_oprs (used by the fast path) can be cross-type when the FK
4055 * and PK columns differ in type, e.g. int48eq for int4 PK / int8 FK.
4056 * If the FK column's type already matches what the operator expects
4057 * as its right-hand input, no cast is needed.
4058 */
4059 if (typeid == righttype)
4060 castfunc = InvalidOid; /* simplest case */
4061 else
4062 {
4063 pathtype = find_coercion_pathway(lefttype, typeid,
4065 &castfunc);
4066 if (pathtype != COERCION_PATH_FUNC &&
4067 pathtype != COERCION_PATH_RELABELTYPE)
4068 {
4069 /*
4070 * The declared input type of the eq_opr might be a
4071 * polymorphic type such as ANYARRAY or ANYENUM, or other
4072 * special cases such as RECORD; find_coercion_pathway
4073 * currently doesn't subsume these special cases.
4074 */
4075 if (!IsBinaryCoercible(typeid, lefttype))
4076 elog(ERROR, "no conversion function from %s to %s",
4077 format_type_be(typeid),
4078 format_type_be(lefttype));
4079 }
4080 }
4081 if (OidIsValid(castfunc))
4082 fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
4084 else
4086 entry->valid = true;
4087 }
4088
4089 return entry;
4090}
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition fmgr.c:139
char * format_type_be(Oid type_oid)
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1478
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition lsyscache.c:1551
MemoryContext TopMemoryContext
Definition mcxt.c:166
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
@ COERCION_PATH_FUNC
@ COERCION_PATH_RELABELTYPE
#define InvalidOid
@ COERCION_IMPLICIT
Definition primnodes.h:747
static HTAB * ri_compare_cache

References 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(), OidIsValid, op_input_types(), ri_compare_cache, ri_InitHashTables(), TopMemoryContext, and RI_CompareHashEntry::valid.

Referenced by ri_CompareWithCast(), and ri_populate_fastpath_metadata().

◆ ri_HashPreparedPlan()

static void ri_HashPreparedPlan ( RI_QueryKey key,
SPIPlanPtr  plan 
)
static

Definition at line 3827 of file ri_triggers.c.

3828{
3829 RI_QueryHashEntry *entry;
3830 bool found;
3831
3832 /*
3833 * On the first call initialize the hashtable
3834 */
3835 if (!ri_query_cache)
3837
3838 /*
3839 * Add the new plan. We might be overwriting an entry previously found
3840 * invalid by ri_FetchPreparedPlan.
3841 */
3843 key,
3844 HASH_ENTER, &found);
3845 Assert(!found || entry->plan == NULL);
3846 entry->plan = plan;
3847}

References Assert, fb(), HASH_ENTER, hash_search(), 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 3739 of file ri_triggers.c.

3740{
3741 HASHCTL ctl;
3742
3743 ctl.keysize = sizeof(Oid);
3744 ctl.entrysize = sizeof(RI_ConstraintInfo);
3745 ri_constraint_cache = hash_create("RI constraint cache",
3748
3749 /* Arrange to flush cache on pg_constraint changes */
3752 (Datum) 0);
3753
3754 ctl.keysize = sizeof(RI_QueryKey);
3755 ctl.entrysize = sizeof(RI_QueryHashEntry);
3756 ri_query_cache = hash_create("RI query cache",
3759
3760 ctl.keysize = sizeof(RI_CompareKey);
3761 ctl.entrysize = sizeof(RI_CompareHashEntry);
3762 ri_compare_cache = hash_create("RI compare cache",
3765}
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
#define RI_INIT_QUERYHASHSIZE
Definition ri_triggers.c:67
#define RI_INIT_CONSTRAINTHASHSIZE
Definition ri_triggers.c:66
static void InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
Size keysize
Definition hsearch.h:69

References CacheRegisterSyscacheCallback(), ctl, fb(), HASH_BLOBS, hash_create(), HASH_ELEM, InvalidateConstraintCacheCallBack(), HASHCTL::keysize, 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 1650 of file ri_triggers.c.

1651{
1661 List *rtes = NIL;
1662 List *perminfos = NIL;
1663 const char *sep;
1664 const char *fk_only;
1665 const char *pk_only;
1666 int save_nestlevel;
1667 char workmembuf[32];
1668 int spi_result;
1670
1672
1673 /*
1674 * Check to make sure current user has enough permissions to do the test
1675 * query. (If not, caller can fall back to the trigger method, which
1676 * works because it changes user IDs on the fly.)
1677 *
1678 * XXX are there any other show-stopper conditions to check?
1679 */
1681 pk_perminfo->relid = RelationGetRelid(pk_rel);
1682 pk_perminfo->requiredPerms = ACL_SELECT;
1685 rte->rtekind = RTE_RELATION;
1686 rte->relid = RelationGetRelid(pk_rel);
1687 rte->relkind = pk_rel->rd_rel->relkind;
1688 rte->rellockmode = AccessShareLock;
1689 rte->perminfoindex = list_length(perminfos);
1690 rtes = lappend(rtes, rte);
1691
1694 fk_perminfo->requiredPerms = ACL_SELECT;
1697 rte->rtekind = RTE_RELATION;
1698 rte->relid = RelationGetRelid(fk_rel);
1699 rte->relkind = fk_rel->rd_rel->relkind;
1700 rte->rellockmode = AccessShareLock;
1701 rte->perminfoindex = list_length(perminfos);
1702 rtes = lappend(rtes, rte);
1703
1704 for (int i = 0; i < riinfo->nkeys; i++)
1705 {
1706 int attno;
1707
1708 attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1709 pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1710
1711 attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1712 fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1713 }
1714
1715 if (!ExecCheckPermissions(rtes, perminfos, false))
1716 return false;
1717
1718 /*
1719 * Also punt if RLS is enabled on either table unless this role has the
1720 * bypassrls right or is the table owner of the table(s) involved which
1721 * have RLS enabled.
1722 */
1724 ((pk_rel->rd_rel->relrowsecurity &&
1726 GetUserId())) ||
1727 (fk_rel->rd_rel->relrowsecurity &&
1729 GetUserId()))))
1730 return false;
1731
1732 /*----------
1733 * The query string built is:
1734 * SELECT fk.keycols FROM [ONLY] relname fk
1735 * LEFT OUTER JOIN [ONLY] pkrelname pk
1736 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1737 * WHERE pk.pkkeycol1 IS NULL AND
1738 * For MATCH SIMPLE:
1739 * (fk.keycol1 IS NOT NULL [AND ...])
1740 * For MATCH FULL:
1741 * (fk.keycol1 IS NOT NULL [OR ...])
1742 *
1743 * We attach COLLATE clauses to the operators when comparing columns
1744 * that have different collations.
1745 *----------
1746 */
1748 appendStringInfoString(&querybuf, "SELECT ");
1749 sep = "";
1750 for (int i = 0; i < riinfo->nkeys; i++)
1751 {
1753 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1754 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1755 sep = ", ";
1756 }
1757
1760 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1761 "" : "ONLY ";
1762 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1763 "" : "ONLY ";
1765 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1767
1768 strcpy(pkattname, "pk.");
1769 strcpy(fkattname, "fk.");
1770 sep = "(";
1771 for (int i = 0; i < riinfo->nkeys; i++)
1772 {
1773 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1774 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1775 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1776 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1777
1779 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1781 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1784 riinfo->pf_eq_oprs[i],
1786 if (pk_coll != fk_coll)
1788 sep = "AND";
1789 }
1790
1791 /*
1792 * It's sufficient to test any one pk attribute for null to detect a join
1793 * failure.
1794 */
1795 quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1796 appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1797
1798 sep = "";
1799 for (int i = 0; i < riinfo->nkeys; i++)
1800 {
1801 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1803 "%sfk.%s IS NOT NULL",
1804 sep, fkattname);
1805 switch (riinfo->confmatchtype)
1806 {
1808 sep = " AND ";
1809 break;
1811 sep = " OR ";
1812 break;
1813 }
1814 }
1816
1817 /*
1818 * Temporarily increase work_mem so that the check query can be executed
1819 * more efficiently. It seems okay to do this because the query is simple
1820 * enough to not use a multiple of work_mem, and one typically would not
1821 * have many large foreign-key validations happening concurrently. So
1822 * this seems to meet the criteria for being considered a "maintenance"
1823 * operation, and accordingly we use maintenance_work_mem. However, we
1824 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1825 * let that get applied to the maintenance_work_mem value.
1826 *
1827 * We use the equivalent of a function SET option to allow the setting to
1828 * persist for exactly the duration of the check query. guc.c also takes
1829 * care of undoing the setting on error.
1830 */
1831 save_nestlevel = NewGUCNestLevel();
1832
1834 (void) set_config_option("work_mem", workmembuf,
1836 GUC_ACTION_SAVE, true, 0, false);
1837 (void) set_config_option("hash_mem_multiplier", "1",
1839 GUC_ACTION_SAVE, true, 0, false);
1840
1841 SPI_connect();
1842
1843 /*
1844 * Generate the plan. We don't need to cache it, and there are no
1845 * arguments to the plan.
1846 */
1847 qplan = SPI_prepare(querybuf.data, 0, NULL);
1848
1849 if (qplan == NULL)
1850 elog(ERROR, "SPI_prepare returned %s for %s",
1852
1853 /*
1854 * Run the plan. For safety we force a current snapshot to be used. (In
1855 * transaction-snapshot mode, this arguably violates transaction isolation
1856 * rules, but we really haven't got much choice.) We don't need to
1857 * register the snapshot, because SPI_execute_snapshot will see to it. We
1858 * need at most one tuple returned, so pass limit = 1.
1859 */
1861 NULL, NULL,
1864 true, false, 1);
1865
1866 /* Check result */
1868 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1869
1870 /* Did we find a tuple violating the constraint? */
1871 if (SPI_processed > 0)
1872 {
1873 TupleTableSlot *slot;
1874 HeapTuple tuple = SPI_tuptable->vals[0];
1875 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1877
1878 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1879
1880 heap_deform_tuple(tuple, tupdesc,
1881 slot->tts_values, slot->tts_isnull);
1883
1884 /*
1885 * The columns to look at in the result tuple are 1..N, not whatever
1886 * they are in the fk_rel. Hack up riinfo so that the subroutines
1887 * called here will behave properly.
1888 *
1889 * In addition to this, we have to pass the correct tupdesc to
1890 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1891 * or fk_rel's tupdesc.
1892 */
1894 for (int i = 0; i < fake_riinfo.nkeys; i++)
1895 fake_riinfo.fk_attnums[i] = i + 1;
1896
1897 /*
1898 * If it's MATCH FULL, and there are any nulls in the FK keys,
1899 * complain about that rather than the lack of a match. MATCH FULL
1900 * disallows partially-null FK rows.
1901 */
1902 if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1903 ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1904 ereport(ERROR,
1906 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1908 NameStr(fake_riinfo.conname)),
1909 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1911 NameStr(fake_riinfo.conname))));
1912
1913 /*
1914 * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1915 * query, which isn't true, but will cause it to use
1916 * fake_riinfo.fk_attnums as we need.
1917 */
1919 pk_rel, fk_rel,
1920 slot, tupdesc,
1921 RI_PLAN_CHECK_LOOKUPPK, false, false);
1922
1924 }
1925
1926 if (SPI_finish() != SPI_OK_FINISH)
1927 elog(ERROR, "SPI_finish failed");
1928
1929 /*
1930 * Restore work_mem and hash_mem_multiplier.
1931 */
1932 AtEOXact_GUC(true, save_nestlevel);
1933
1934 return true;
1935}
bool has_bypassrls_privilege(Oid roleid)
Definition aclchk.c:4231
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition execMain.c:593
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
int maintenance_work_mem
Definition globals.c:135
int NewGUCNestLevel(void)
Definition guc.c:2142
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169
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:3248
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_USERSET
Definition guc.h:79
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition heaptuple.c:1254
List * lappend(List *list, void *datum)
Definition list.c:339
#define makeNode(_type_)
Definition nodes.h:161
@ RTE_RELATION
static int list_length(const List *l)
Definition pg_list.h:152
#define snprintf
Definition port.h:260
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
#define RIAttCollation(rel, attnum)
Definition ri_triggers.c:94
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
#define InvalidSnapshot
Definition snapshot.h:119
uint64 SPI_processed
Definition spi.c:45
const char * SPI_result_code_string(int code)
Definition spi.c:1973
SPITupleTable * SPI_tuptable
Definition spi.c:46
int SPI_result
Definition spi.c:47
int SPI_execute_snapshot(SPIPlanPtr plan, const Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition spi.c:774
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition spi.c:861
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
Definition pg_list.h:54
TupleDesc tupdesc
Definition spi.h:25
HeapTuple * vals
Definition spi.h:26
bool * tts_isnull
Definition tuptable.h:133
Datum * tts_values
Definition tuptable.h:131
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References AccessShareLock, ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), elog, ereport, errcode(), errdetail(), errmsg, ERROR, errtableconstraint(), ExecCheckPermissions(), ExecDropSingleTupleTableSlot(), ExecStoreVirtualTuple(), fb(), FirstLowInvalidHeapAttributeNumber, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GetUserId(), GUC_ACTION_SAVE, has_bypassrls_privilege(), heap_deform_tuple(), i, initStringInfo(), InvalidSnapshot, lappend(), list_length(), maintenance_work_mem, makeNode, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, memcpy(), NameStr, NewGUCNestLevel(), NIL, object_ownercheck(), PGC_S_SESSION, PGC_USERSET, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_KEYS_NONE_NULL, ri_NullCheck(), RI_PLAN_CHECK_LOOKUPPK, ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, RTE_RELATION, 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 3864 of file ri_triggers.c.

3866{
3867 const int16 *attnums;
3868
3869 if (rel_is_pk)
3870 attnums = riinfo->pk_attnums;
3871 else
3872 attnums = riinfo->fk_attnums;
3873
3874 /* XXX: could be worthwhile to fetch all necessary attrs at once */
3875 for (int i = 0; i < riinfo->nkeys; i++)
3876 {
3879 bool isnull;
3880
3881 /*
3882 * Get one attribute's oldvalue. If it is NULL - they're not equal.
3883 */
3884 oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3885 if (isnull)
3886 return false;
3887
3888 /*
3889 * Get one attribute's newvalue. If it is NULL - they're not equal.
3890 */
3891 newvalue = slot_getattr(newslot, attnums[i], &isnull);
3892 if (isnull)
3893 return false;
3894
3895 if (rel_is_pk)
3896 {
3897 /*
3898 * If we are looking at the PK table, then do a bytewise
3899 * comparison. We must propagate PK changes if the value is
3900 * changed to one that "looks" different but would compare as
3901 * equal using the equality operator. This only makes a
3902 * difference for ON UPDATE CASCADE, but for consistency we treat
3903 * all changes to the PK the same.
3904 */
3905 CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3906
3907 if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3908 return false;
3909 }
3910 else
3911 {
3912 Oid eq_opr;
3913
3914 /*
3915 * When comparing the PERIOD columns we can skip the check
3916 * whenever the referencing column stayed equal or shrank, so test
3917 * with the contained-by operator instead.
3918 */
3919 if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3920 eq_opr = riinfo->period_contained_by_oper;
3921 else
3922 eq_opr = riinfo->ff_eq_oprs[i];
3923
3924 /*
3925 * For the FK table, compare with the appropriate equality
3926 * operator. Changes that compare equal will still satisfy the
3927 * constraint after the update.
3928 */
3929 if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3931 return false;
3932 }
3933 }
3934
3935 return true;
3936}
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition datum.c:271
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195

References CompactAttribute::attbyval, CompactAttribute::attlen, datum_image_eq(), fb(), i, ri_CompareWithCast(), RIAttCollation, RIAttType, slot_getattr(), and TupleDescCompactAttr().

Referenced by RI_FKey_fk_upd_check_required(), and RI_FKey_pk_upd_check_required().

◆ ri_LoadConstraintInfo()

static RI_ConstraintInfo * ri_LoadConstraintInfo ( Oid  constraintOid)
static

Definition at line 2399 of file ri_triggers.c.

2400{
2402 bool found;
2403 HeapTuple tup;
2405
2406 /*
2407 * On the first call initialize the hashtable
2408 */
2411
2412 /*
2413 * Find or create a hash entry. If we find a valid one, just return it.
2414 */
2417 HASH_ENTER, &found);
2418 if (!found)
2419 riinfo->valid = false;
2420 else if (riinfo->valid)
2421 return riinfo;
2422
2423 /*
2424 * Fetch the pg_constraint row so we can fill in the entry.
2425 */
2427 if (!HeapTupleIsValid(tup)) /* should not happen */
2428 elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2430
2431 if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2432 elog(ERROR, "constraint %u is not a foreign key constraint",
2434
2435 /* And extract data */
2436 Assert(riinfo->constraint_id == constraintOid);
2437 if (OidIsValid(conForm->conparentid))
2438 riinfo->constraint_root_id =
2439 get_ri_constraint_root(conForm->conparentid);
2440 else
2441 riinfo->constraint_root_id = constraintOid;
2442 riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2444 riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2445 ObjectIdGetDatum(riinfo->constraint_root_id));
2446 memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2447 riinfo->pk_relid = conForm->confrelid;
2448 riinfo->fk_relid = conForm->conrelid;
2449 riinfo->confupdtype = conForm->confupdtype;
2450 riinfo->confdeltype = conForm->confdeltype;
2451 riinfo->confmatchtype = conForm->confmatchtype;
2452 riinfo->hasperiod = conForm->conperiod;
2453
2455 &riinfo->nkeys,
2456 riinfo->fk_attnums,
2457 riinfo->pk_attnums,
2458 riinfo->pf_eq_oprs,
2459 riinfo->pp_eq_oprs,
2460 riinfo->ff_eq_oprs,
2461 &riinfo->ndelsetcols,
2462 riinfo->confdelsetcols);
2463
2464 /*
2465 * For temporal FKs, get the operators and functions we need. We ask the
2466 * opclass of the PK element for these. This all gets cached (as does the
2467 * generated plan), so there's no performance issue.
2468 */
2469 if (riinfo->hasperiod)
2470 {
2471 Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2472
2473 FindFKPeriodOpers(opclass,
2474 &riinfo->period_contained_by_oper,
2475 &riinfo->agged_period_contained_by_oper,
2476 &riinfo->period_intersect_oper);
2477 }
2478
2479 /* Metadata used by fast path. */
2480 riinfo->conindid = conForm->conindid;
2481 riinfo->pk_is_partitioned =
2483
2485
2486 /*
2487 * For efficient processing of invalidation messages below, we keep a
2488 * doubly-linked count list of all currently valid entries.
2489 */
2491
2492 riinfo->valid = true;
2493
2494 riinfo->fpmeta = NULL;
2495
2496 return riinfo;
2497}
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition ilist.h:709
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2196
Oid get_index_column_opclass(Oid index_oid, int attno)
Definition lsyscache.c:3732
void FindFKPeriodOpers(Oid opclass, Oid *containedbyoperoid, Oid *aggedcontainedbyoperoid, Oid *intersectoperoid)
void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks, AttrNumber *conkey, AttrNumber *confkey, Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs, int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
static Oid get_ri_constraint_root(Oid constrOid)
Definition c.h:830
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118

References Assert, dclist_push_tail(), DeconstructFkConstraintRow(), elog, ERROR, fb(), FindFKPeriodOpers(), Form_pg_constraint, get_index_column_opclass(), get_rel_relkind(), get_ri_constraint_root(), GETSTRUCT(), GetSysCacheHashValue1, HASH_ENTER, hash_search(), HeapTupleIsValid, memcpy(), ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), ri_constraint_cache, ri_constraint_cache_valid_list, ri_InitHashTables(), and SearchSysCache1().

Referenced by ri_FastPathBatchFlush(), ri_FastPathCheck(), ri_FastPathEndBatch(), and ri_FetchConstraintInfo().

◆ ri_LockPKTuple()

static bool ri_LockPKTuple ( Relation  pk_rel,
TupleTableSlot slot,
Snapshot  snap,
bool concurrently_updated 
)
static

Definition at line 3219 of file ri_triggers.c.

3221{
3222 TM_FailureData tmfd;
3225
3226 *concurrently_updated = false;
3227
3230
3231 result = table_tuple_lock(pk_rel, &slot->tts_tid, snap,
3232 slot, GetCurrentCommandId(false),
3234 lockflags, &tmfd);
3235
3236 switch (result)
3237 {
3238 case TM_Ok:
3239 if (tmfd.traversed)
3240 *concurrently_updated = true;
3241 return true;
3242
3243 case TM_Deleted:
3245 ereport(ERROR,
3247 errmsg("could not serialize access due to concurrent update")));
3248 return false;
3249
3250 case TM_Updated:
3252 ereport(ERROR,
3254 errmsg("could not serialize access due to concurrent update")));
3255
3256 /*
3257 * In READ COMMITTED, FIND_LAST_VERSION should have chased the
3258 * chain and returned TM_Ok. Getting here means something
3259 * unexpected -- fall through to error.
3260 */
3261 elog(ERROR, "unexpected table_tuple_lock status: %u", result);
3262 break;
3263
3264 case TM_SelfModified:
3265
3266 /*
3267 * The current command or a later command in this transaction
3268 * modified the PK row. This shouldn't normally happen during an
3269 * FK check (we're not modifying pk_rel), but handle it safely by
3270 * treating the tuple as not found.
3271 */
3272 return false;
3273
3274 case TM_Invisible:
3275 elog(ERROR, "attempted to lock invisible tuple");
3276 break;
3277
3278 default:
3279 elog(ERROR, "unrecognized table_tuple_lock status: %u", result);
3280 break;
3281 }
3282
3283 return false; /* keep compiler quiet */
3284}
@ LockWaitBlock
Definition lockoptions.h:40
@ LockTupleKeyShare
Definition lockoptions.h:53
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition pgbench.c:77
ItemPointerData tts_tid
Definition tuptable.h:142
TM_Result
Definition tableam.h:95
@ TM_Ok
Definition tableam.h:100
@ TM_Deleted
Definition tableam.h:115
@ TM_Updated
Definition tableam.h:112
@ TM_SelfModified
Definition tableam.h:106
@ TM_Invisible
Definition tableam.h:103
static TM_Result table_tuple_lock(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, uint8 flags, TM_FailureData *tmfd)
Definition tableam.h:1646
#define TUPLE_LOCK_FLAG_FIND_LAST_VERSION
Definition tableam.h:299
#define TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS
Definition tableam.h:297
CommandId GetCurrentCommandId(bool used)
Definition xact.c:831
#define IsolationUsesXactSnapshot()
Definition xact.h:52

References elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errmsg, ERROR, fb(), GetCurrentCommandId(), IsolationUsesXactSnapshot, LockTupleKeyShare, LockWaitBlock, result, table_tuple_lock(), TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TM_FailureData::traversed, TupleTableSlot::tts_tid, TUPLE_LOCK_FLAG_FIND_LAST_VERSION, and TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS.

Referenced by ri_FastPathFlushArray(), and ri_FastPathProbeOne().

◆ ri_NullCheck()

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

Definition at line 3702 of file ri_triggers.c.

3705{
3706 const int16 *attnums;
3707 bool allnull = true;
3708 bool nonenull = true;
3709
3710 if (rel_is_pk)
3711 attnums = riinfo->pk_attnums;
3712 else
3713 attnums = riinfo->fk_attnums;
3714
3715 for (int i = 0; i < riinfo->nkeys; i++)
3716 {
3717 if (slot_attisnull(slot, attnums[i]))
3718 nonenull = false;
3719 else
3720 allnull = false;
3721 }
3722
3723 if (allnull)
3724 return RI_KEYS_ALL_NULL;
3725
3726 if (nonenull)
3727 return RI_KEYS_NONE_NULL;
3728
3729 return RI_KEYS_SOME_NULL;
3730}
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:403

References fb(), i, 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 1944 of file ri_triggers.c.

1945{
1948 char *constraintDef;
1953 const char *sep;
1954 const char *fk_only;
1955 int save_nestlevel;
1956 char workmembuf[32];
1957 int spi_result;
1959 int i;
1960
1962
1963 /*
1964 * We don't check permissions before displaying the error message, on the
1965 * assumption that the user detaching the partition must have enough
1966 * privileges to examine the table contents anyhow.
1967 */
1968
1969 /*----------
1970 * The query string built is:
1971 * SELECT fk.keycols FROM [ONLY] relname fk
1972 * JOIN pkrelname pk
1973 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1974 * WHERE (<partition constraint>) AND
1975 * For MATCH SIMPLE:
1976 * (fk.keycol1 IS NOT NULL [AND ...])
1977 * For MATCH FULL:
1978 * (fk.keycol1 IS NOT NULL [OR ...])
1979 *
1980 * We attach COLLATE clauses to the operators when comparing columns
1981 * that have different collations.
1982 *----------
1983 */
1985 appendStringInfoString(&querybuf, "SELECT ");
1986 sep = "";
1987 for (i = 0; i < riinfo->nkeys; i++)
1988 {
1990 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1991 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1992 sep = ", ";
1993 }
1994
1997 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1998 "" : "ONLY ";
2000 " FROM %s%s fk JOIN %s pk ON",
2002 strcpy(pkattname, "pk.");
2003 strcpy(fkattname, "fk.");
2004 sep = "(";
2005 for (i = 0; i < riinfo->nkeys; i++)
2006 {
2007 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
2008 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
2009 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
2010 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
2011
2013 RIAttName(pk_rel, riinfo->pk_attnums[i]));
2015 RIAttName(fk_rel, riinfo->fk_attnums[i]));
2018 riinfo->pf_eq_oprs[i],
2020 if (pk_coll != fk_coll)
2022 sep = "AND";
2023 }
2024
2025 /*
2026 * Start the WHERE clause with the partition constraint (except if this is
2027 * the default partition and there's no other partition, because the
2028 * partition constraint is the empty string in that case.)
2029 */
2031 if (constraintDef && constraintDef[0] != '\0')
2032 appendStringInfo(&querybuf, ") WHERE %s AND (",
2034 else
2035 appendStringInfoString(&querybuf, ") WHERE (");
2036
2037 sep = "";
2038 for (i = 0; i < riinfo->nkeys; i++)
2039 {
2040 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
2042 "%sfk.%s IS NOT NULL",
2043 sep, fkattname);
2044 switch (riinfo->confmatchtype)
2045 {
2047 sep = " AND ";
2048 break;
2050 sep = " OR ";
2051 break;
2052 }
2053 }
2055
2056 /*
2057 * Temporarily increase work_mem so that the check query can be executed
2058 * more efficiently. It seems okay to do this because the query is simple
2059 * enough to not use a multiple of work_mem, and one typically would not
2060 * have many large foreign-key validations happening concurrently. So
2061 * this seems to meet the criteria for being considered a "maintenance"
2062 * operation, and accordingly we use maintenance_work_mem. However, we
2063 * must also set hash_mem_multiplier to 1, since it is surely not okay to
2064 * let that get applied to the maintenance_work_mem value.
2065 *
2066 * We use the equivalent of a function SET option to allow the setting to
2067 * persist for exactly the duration of the check query. guc.c also takes
2068 * care of undoing the setting on error.
2069 */
2070 save_nestlevel = NewGUCNestLevel();
2071
2073 (void) set_config_option("work_mem", workmembuf,
2075 GUC_ACTION_SAVE, true, 0, false);
2076 (void) set_config_option("hash_mem_multiplier", "1",
2078 GUC_ACTION_SAVE, true, 0, false);
2079
2080 SPI_connect();
2081
2082 /*
2083 * Generate the plan. We don't need to cache it, and there are no
2084 * arguments to the plan.
2085 */
2086 qplan = SPI_prepare(querybuf.data, 0, NULL);
2087
2088 if (qplan == NULL)
2089 elog(ERROR, "SPI_prepare returned %s for %s",
2091
2092 /*
2093 * Run the plan. For safety we force a current snapshot to be used. (In
2094 * transaction-snapshot mode, this arguably violates transaction isolation
2095 * rules, but we really haven't got much choice.) We don't need to
2096 * register the snapshot, because SPI_execute_snapshot will see to it. We
2097 * need at most one tuple returned, so pass limit = 1.
2098 */
2100 NULL, NULL,
2103 true, false, 1);
2104
2105 /* Check result */
2107 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2108
2109 /* Did we find a tuple that would violate the constraint? */
2110 if (SPI_processed > 0)
2111 {
2112 TupleTableSlot *slot;
2113 HeapTuple tuple = SPI_tuptable->vals[0];
2114 TupleDesc tupdesc = SPI_tuptable->tupdesc;
2116
2117 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
2118
2119 heap_deform_tuple(tuple, tupdesc,
2120 slot->tts_values, slot->tts_isnull);
2122
2123 /*
2124 * The columns to look at in the result tuple are 1..N, not whatever
2125 * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
2126 * will behave properly.
2127 *
2128 * In addition to this, we have to pass the correct tupdesc to
2129 * ri_ReportViolation, overriding its normal habit of using the pk_rel
2130 * or fk_rel's tupdesc.
2131 */
2133 for (i = 0; i < fake_riinfo.nkeys; i++)
2134 fake_riinfo.pk_attnums[i] = i + 1;
2135
2137 slot, tupdesc, 0, false, true);
2138 }
2139
2140 if (SPI_finish() != SPI_OK_FINISH)
2141 elog(ERROR, "SPI_finish failed");
2142
2143 /*
2144 * Restore work_mem and hash_mem_multiplier.
2145 */
2146 AtEOXact_GUC(true, save_nestlevel);
2147}
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition ruleutils.c:2486

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), elog, ERROR, ExecStoreVirtualTuple(), fb(), 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, memcpy(), NewGUCNestLevel(), pg_get_partconstrdef_string(), PGC_S_SESSION, PGC_USERSET, quoteOneName(), quoteRelationName(), 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 2628 of file ri_triggers.c.

2634{
2636 source_rel;
2637 bool source_is_pk;
2639 Snapshot crosscheck_snapshot;
2640 int limit;
2641 int spi_result;
2642 Oid save_userid;
2643 int save_sec_context;
2644 Datum vals[RI_MAX_NUMKEYS * 2];
2645 char nulls[RI_MAX_NUMKEYS * 2];
2646
2647 /*
2648 * Use the query type code to determine whether the query is run against
2649 * the PK or FK table; we'll do the check as that table's owner
2650 */
2651 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2652 query_rel = pk_rel;
2653 else
2654 query_rel = fk_rel;
2655
2656 /*
2657 * The values for the query are taken from the table on which the trigger
2658 * is called - it is normally the other one with respect to query_rel. An
2659 * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2660 * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2661 * need some less klugy way to determine this.
2662 */
2663 if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
2664 {
2666 source_is_pk = false;
2667 }
2668 else
2669 {
2670 source_rel = pk_rel;
2671 source_is_pk = true;
2672 }
2673
2674 /* Extract the parameters to be passed into the query */
2675 if (newslot)
2676 {
2678 vals, nulls);
2679 if (oldslot)
2681 vals + riinfo->nkeys, nulls + riinfo->nkeys);
2682 }
2683 else
2684 {
2686 vals, nulls);
2687 }
2688
2689 /*
2690 * In READ COMMITTED mode, we just need to use an up-to-date regular
2691 * snapshot, and we will see all rows that could be interesting. But in
2692 * transaction-snapshot mode, we can't change the transaction snapshot. If
2693 * the caller passes detectNewRows == false then it's okay to do the query
2694 * with the transaction snapshot; otherwise we use a current snapshot, and
2695 * tell the executor to error out if it finds any rows under the current
2696 * snapshot that wouldn't be visible per the transaction snapshot. Note
2697 * that SPI_execute_snapshot will register the snapshots, so we don't need
2698 * to bother here.
2699 */
2701 {
2702 CommandCounterIncrement(); /* be sure all my own work is visible */
2704 crosscheck_snapshot = GetTransactionSnapshot();
2705 }
2706 else
2707 {
2708 /* the default SPI behavior is okay */
2710 crosscheck_snapshot = InvalidSnapshot;
2711 }
2712
2713 /*
2714 * If this is a select query (e.g., for a 'no action' or 'restrict'
2715 * trigger), we only need to see if there is a single row in the table,
2716 * matching the key. Otherwise, limit = 0 - because we want the query to
2717 * affect ALL the matching rows.
2718 */
2719 limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2720
2721 /* Switch to proper UID to perform check as */
2722 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2724 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2726
2727 /*
2728 * Finally we can run the query.
2729 *
2730 * Set fire_triggers to false to ensure that AFTER triggers are queued in
2731 * the outer query's after-trigger context and fire after all RI updates
2732 * on the same row are complete, rather than immediately.
2733 */
2735 vals, nulls,
2736 test_snapshot, crosscheck_snapshot,
2737 false, false, limit);
2738
2739 /* Restore UID and security context */
2740 SetUserIdAndSecContext(save_userid, save_sec_context);
2741
2742 /* Check result */
2743 if (spi_result < 0)
2744 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2745
2746 if (expect_OK >= 0 && spi_result != expect_OK)
2747 ereport(ERROR,
2749 errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2751 NameStr(riinfo->conname),
2753 errhint("This is most likely due to a rule having rewritten the query.")));
2754
2755 /* XXX wouldn't it be clearer to do this part at the caller? */
2756 if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
2758 (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
2760 pk_rel, fk_rel,
2762 NULL,
2763 qkey->constr_queryno, is_restrict, false);
2764
2765 return SPI_processed != 0;
2766}
#define false
#define RI_PLAN_LAST_ON_PK
Definition ri_triggers.c:77

References CommandCounterIncrement(), elog, ereport, errcode(), errhint(), errmsg, ERROR, fb(), GetLatestSnapshot(), GetTransactionSnapshot(), GetUserIdAndSecContext(), InvalidSnapshot, IsolationUsesXactSnapshot, NameStr, 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 2585 of file ri_triggers.c.

2587{
2590 Oid save_userid;
2591 int save_sec_context;
2592
2593 /*
2594 * Use the query type code to determine whether the query is run against
2595 * the PK or FK table; we'll do the check as that table's owner
2596 */
2597 if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2598 query_rel = pk_rel;
2599 else
2600 query_rel = fk_rel;
2601
2602 /* Switch to proper UID to perform check as */
2603 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2605 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2607
2608 /* Create the plan */
2609 qplan = SPI_prepare(querystr, nargs, argtypes);
2610
2611 if (qplan == NULL)
2612 elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2613
2614 /* Restore UID and security context */
2615 SetUserIdAndSecContext(save_userid, save_sec_context);
2616
2617 /* Save the plan */
2620
2621 return qplan;
2622}
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
int SPI_keepplan(SPIPlanPtr plan)
Definition spi.c:977

References elog, ERROR, fb(), 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_populate_fastpath_metadata()

static void ri_populate_fastpath_metadata ( RI_ConstraintInfo riinfo,
Relation  fk_rel,
Relation  idx_rel 
)
static

Definition at line 3446 of file ri_triggers.c.

3448{
3449 FastPathMeta *fpmeta;
3451
3452 Assert(riinfo != NULL && riinfo->valid);
3453
3454 fpmeta = palloc_object(FastPathMeta);
3455 for (int i = 0; i < riinfo->nkeys; i++)
3456 {
3457 Oid eq_opr = riinfo->pf_eq_oprs[i];
3458 Oid typeid = RIAttType(fk_rel, riinfo->fk_attnums[i]);
3459 Oid lefttype;
3460 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3461 int idx_col;
3462
3463 /*
3464 * Find the index column position for this constraint key. The FK
3465 * constraint may reference columns in a different order than they
3466 * appear in the PK index, so we must map pk_attnums[i] to the
3467 * corresponding index column position.
3468 */
3469 for (idx_col = 0; idx_col < riinfo->nkeys; idx_col++)
3470 {
3471 if (idx_rel->rd_index->indkey.values[idx_col] == riinfo->pk_attnums[i])
3472 break;
3473 }
3475
3476 /* 1-based attribute number */
3477 fpmeta->index_attnos[i] = idx_col + 1;
3478
3481 fmgr_info_copy(&fpmeta->eq_opr_finfo[i], &entry->eq_opr_finfo,
3483 fpmeta->regops[i] = get_opcode(eq_opr);
3484
3486 idx_rel->rd_opfamily[idx_col],
3487 false,
3488 &fpmeta->strats[i],
3489 &lefttype,
3490 &fpmeta->subtypes[i]);
3491 }
3492
3493 riinfo->fpmeta = fpmeta;
3495}
#define palloc_object(type)
Definition fe_memutils.h:74
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition fmgr.c:582
void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op, int *strategy, Oid *lefttype, Oid *righttype)
Definition lsyscache.c:140
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
Form_pg_index rd_index
Definition rel.h:192
Oid * rd_opfamily
Definition rel.h:207

References Assert, FastPathMeta::cast_func_finfo, RI_CompareHashEntry::cast_func_finfo, CurrentMemoryContext, FastPathMeta::eq_opr_finfo, RI_CompareHashEntry::eq_opr_finfo, fb(), fmgr_info_copy(), get_op_opfamily_properties(), get_opcode(), i, FastPathMeta::index_attnos, MemoryContextSwitchTo(), palloc_object, RelationData::rd_index, RelationData::rd_opfamily, FastPathMeta::regops, ri_HashCompareOp(), RIAttType, FastPathMeta::strats, FastPathMeta::subtypes, and TopMemoryContext.

Referenced by ri_FastPathBatchFlush(), and ri_FastPathCheck().

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

3534{
3537 bool onfk;
3538 const int16 *attnums;
3539 Oid rel_oid;
3541 bool has_perm = true;
3542
3543 /*
3544 * Determine which relation to complain about. If tupdesc wasn't passed
3545 * by caller, assume the violator tuple came from there.
3546 */
3548 if (onfk)
3549 {
3550 attnums = riinfo->fk_attnums;
3551 rel_oid = fk_rel->rd_id;
3552 if (tupdesc == NULL)
3553 tupdesc = fk_rel->rd_att;
3554 }
3555 else
3556 {
3557 attnums = riinfo->pk_attnums;
3558 rel_oid = pk_rel->rd_id;
3559 if (tupdesc == NULL)
3560 tupdesc = pk_rel->rd_att;
3561 }
3562
3563 /*
3564 * Check permissions- if the user does not have access to view the data in
3565 * any of the key columns then we don't include the errdetail() below.
3566 *
3567 * Check if RLS is enabled on the relation first. If so, we don't return
3568 * any specifics to avoid leaking data.
3569 *
3570 * Check table-level permissions next and, failing that, column-level
3571 * privileges.
3572 *
3573 * When a partition at the referenced side is being detached/dropped, we
3574 * needn't check, since the user must be the table owner anyway.
3575 */
3576 if (partgone)
3577 has_perm = true;
3578 else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
3579 {
3581 if (aclresult != ACLCHECK_OK)
3582 {
3583 /* Try for column-level permissions */
3584 for (int idx = 0; idx < riinfo->nkeys; idx++)
3585 {
3587 GetUserId(),
3588 ACL_SELECT);
3589
3590 /* No access to the key */
3591 if (aclresult != ACLCHECK_OK)
3592 {
3593 has_perm = false;
3594 break;
3595 }
3596 }
3597 }
3598 }
3599 else
3600 has_perm = false;
3601
3602 if (has_perm)
3603 {
3604 /* Get printable versions of the keys involved */
3607 for (int idx = 0; idx < riinfo->nkeys; idx++)
3608 {
3609 int fnum = attnums[idx];
3610 Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
3611 char *name,
3612 *val;
3613 Datum datum;
3614 bool isnull;
3615
3616 name = NameStr(att->attname);
3617
3618 datum = slot_getattr(violatorslot, fnum, &isnull);
3619 if (!isnull)
3620 {
3621 Oid foutoid;
3622 bool typisvarlena;
3623
3624 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
3626 }
3627 else
3628 val = "null";
3629
3630 if (idx > 0)
3631 {
3634 }
3637 }
3638 }
3639
3640 if (partgone)
3641 ereport(ERROR,
3643 errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
3645 NameStr(riinfo->conname)),
3646 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3647 key_names.data, key_values.data,
3650 else if (onfk)
3651 ereport(ERROR,
3653 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
3655 NameStr(riinfo->conname)),
3656 has_perm ?
3657 errdetail("Key (%s)=(%s) is not present in table \"%s\".",
3658 key_names.data, key_values.data,
3659 RelationGetRelationName(pk_rel)) :
3660 errdetail("Key is not present in table \"%s\".",
3661 RelationGetRelationName(pk_rel)),
3663 else if (is_restrict)
3664 ereport(ERROR,
3666 errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
3668 NameStr(riinfo->conname),
3670 has_perm ?
3671 errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
3672 key_names.data, key_values.data,
3674 errdetail("Key is referenced from table \"%s\".",
3677 else
3678 ereport(ERROR,
3680 errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
3682 NameStr(riinfo->conname),
3684 has_perm ?
3685 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3686 key_names.data, key_values.data,
3688 errdetail("Key is still referenced from table \"%s\".",
3691}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:262
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition aclchk.c:3911
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition fmgr.c:1764
long val
Definition informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3102
FormData_pg_attribute * Form_pg_attribute
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:178

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

Referenced by ri_FastPathBatchFlush(), ri_FastPathCheck(), 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 843 of file ri_triggers.c.

844{
847 Relation pk_rel;
851
853 trigdata->tg_relation, true);
854
855 /*
856 * Get the relation descriptors of the FK and PK tables and the old tuple.
857 *
858 * fk_rel is opened in RowShareLock mode since that's what our eventual
859 * SELECT FOR KEY SHARE will get on it.
860 */
861 fk_rel = table_open(riinfo->fk_relid, RowShareLock);
862 pk_rel = trigdata->tg_relation;
863 oldslot = trigdata->tg_trigslot;
864
865 /*
866 * If another PK row now exists providing the old key values, we should
867 * not do anything. However, this check should only be made in the NO
868 * ACTION case; in RESTRICT cases we don't wish to allow another row to be
869 * substituted.
870 *
871 * If the foreign key has PERIOD, we incorporate looking for replacement
872 * rows in the main SQL query below, so we needn't do it here.
873 */
874 if (is_no_action && !riinfo->hasperiod &&
876 {
878 return PointerGetDatum(NULL);
879 }
880
881 SPI_connect();
882
883 /*
884 * Fetch or prepare a saved plan for the restrict lookup (it's the same
885 * query for delete and update cases)
886 */
888
889 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
890 {
896 char paramname[16];
897 const char *querysep;
899 const char *fk_only;
900
901 /* ----------
902 * The query string built is
903 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
904 * FOR KEY SHARE OF x
905 * The type id's for the $ parameters are those of the
906 * corresponding PK attributes.
907 * ----------
908 */
910 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
911 "" : "ONLY ";
913 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
915 querysep = "WHERE";
916 for (int i = 0; i < riinfo->nkeys; i++)
917 {
918 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
919 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
920
922 RIAttName(fk_rel, riinfo->fk_attnums[i]));
923 sprintf(paramname, "$%d", i + 1);
926 riinfo->pf_eq_oprs[i],
928 querysep = "AND";
930 }
931
932 /*----------
933 * For temporal foreign keys, a reference could still be valid if the
934 * referenced range didn't change too much. Also if a referencing
935 * range extends past the current PK row, we don't want to check that
936 * part: some other PK row should fulfill it. We only want to check
937 * the part matching the PK record we've changed. Therefore to find
938 * invalid records we do this:
939 *
940 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
941 * -- begin temporal
942 * AND $n && x.fkperiod
943 * AND NOT coalesce((x.fkperiod * $n) <@
944 * (SELECT range_agg(r)
945 * FROM (SELECT y.pkperiod r
946 * FROM [ONLY] <pktable> y
947 * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
948 * FOR KEY SHARE OF y) y2), false)
949 * -- end temporal
950 * FOR KEY SHARE OF x
951 *
952 * We need the coalesce in case the first subquery returns no rows.
953 * We need the second subquery because FOR KEY SHARE doesn't support
954 * aggregate queries.
955 */
956 if (riinfo->hasperiod && is_no_action)
957 {
958 Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
959 Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
962 char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
963 "" : "ONLY ";
964
965 quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
966 sprintf(paramname, "$%d", riinfo->nkeys);
967
968 appendStringInfoString(&querybuf, " AND NOT coalesce(");
969
970 /* Intersect the fk with the old pk range */
975 riinfo->period_intersect_oper,
978
979 /* Find the remaining history */
981 appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
982
983 quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
985 appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
987
988 /* Restrict pk rows to what matches */
989 querysep = "WHERE";
990 for (int i = 0; i < riinfo->nkeys; i++)
991 {
992 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
993
995 RIAttName(pk_rel, riinfo->pk_attnums[i]));
996 sprintf(paramname, "$%d", i + 1);
999 riinfo->pp_eq_oprs[i],
1000 attname, pk_type);
1001 querysep = "AND";
1002 queryoids[i] = pk_type;
1003 }
1004 appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
1005
1008 riinfo->agged_period_contained_by_oper,
1010 /* end of coalesce: */
1011 appendStringInfoString(&querybuf, ", false)");
1012 }
1013
1014 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
1015
1016 /* Prepare and save the plan */
1017 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1018 &qkey, fk_rel, pk_rel);
1019 }
1020
1021 /*
1022 * We have a plan now. Run it to check for existing references.
1023 */
1025 fk_rel, pk_rel,
1026 oldslot, NULL,
1027 !is_no_action,
1028 true, /* must detect new rows */
1030
1031 if (SPI_finish() != SPI_OK_FINISH)
1032 elog(ERROR, "SPI_finish failed");
1033
1035
1036 return PointerGetDatum(NULL);
1037}
#define RI_PLAN_RESTRICT
Definition ri_triggers.c:83
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
#define RI_PLAN_NO_ACTION
Definition ri_triggers.c:81

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, 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_NO_ACTION, RI_PLAN_RESTRICT, ri_PlanCheck(), RIAttName, RIAttType, RowShareLock, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_OK_SELECT, sprintf, table_close(), table_open(), TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigslot.

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

◆ ri_set()

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

Definition at line 1326 of file ri_triggers.c.

1327{
1330 Relation pk_rel;
1334 int32 queryno;
1335
1337 trigdata->tg_relation, true);
1338
1339 /*
1340 * Get the relation descriptors of the FK and PK tables and the old tuple.
1341 *
1342 * fk_rel is opened in RowExclusiveLock mode since that's what our
1343 * eventual UPDATE will get on it.
1344 */
1346 pk_rel = trigdata->tg_relation;
1347 oldslot = trigdata->tg_trigslot;
1348
1349 SPI_connect();
1350
1351 /*
1352 * Fetch or prepare a saved plan for the trigger.
1353 */
1354 switch (tgkind)
1355 {
1356 case RI_TRIGTYPE_UPDATE:
1360 break;
1361 case RI_TRIGTYPE_DELETE:
1365 break;
1366 default:
1367 elog(ERROR, "invalid tgkind passed to ri_set");
1368 }
1369
1371
1372 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1373 {
1377 char paramname[16];
1378 const char *querysep;
1379 const char *qualsep;
1381 const char *fk_only;
1382 int num_cols_to_set;
1383 const int16 *set_cols;
1384
1385 switch (tgkind)
1386 {
1387 case RI_TRIGTYPE_UPDATE:
1388 num_cols_to_set = riinfo->nkeys;
1389 set_cols = riinfo->fk_attnums;
1390 break;
1391 case RI_TRIGTYPE_DELETE:
1392
1393 /*
1394 * If confdelsetcols are present, then we only update the
1395 * columns specified in that array, otherwise we update all
1396 * the referencing columns.
1397 */
1398 if (riinfo->ndelsetcols != 0)
1399 {
1400 num_cols_to_set = riinfo->ndelsetcols;
1401 set_cols = riinfo->confdelsetcols;
1402 }
1403 else
1404 {
1405 num_cols_to_set = riinfo->nkeys;
1406 set_cols = riinfo->fk_attnums;
1407 }
1408 break;
1409 default:
1410 elog(ERROR, "invalid tgkind passed to ri_set");
1411 }
1412
1413 /* ----------
1414 * The query string built is
1415 * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1416 * WHERE $1 = fkatt1 [AND ...]
1417 * The type id's for the $ parameters are those of the
1418 * corresponding PK attributes.
1419 * ----------
1420 */
1422 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1423 "" : "ONLY ";
1425 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1427
1428 /*
1429 * Add assignment clauses
1430 */
1431 querysep = "";
1432 for (int i = 0; i < num_cols_to_set; i++)
1433 {
1436 "%s %s = %s",
1438 is_set_null ? "NULL" : "DEFAULT");
1439 querysep = ",";
1440 }
1441
1442 /*
1443 * Add WHERE clause
1444 */
1445 qualsep = "WHERE";
1446 for (int i = 0; i < riinfo->nkeys; i++)
1447 {
1448 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1449 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1450
1452 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1453
1454 sprintf(paramname, "$%d", i + 1);
1457 riinfo->pf_eq_oprs[i],
1458 attname, fk_type);
1459 qualsep = "AND";
1460 queryoids[i] = pk_type;
1461 }
1462
1463 /* Prepare and save the plan */
1464 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1465 &qkey, fk_rel, pk_rel);
1466 }
1467
1468 /*
1469 * We have a plan now. Run it to update the existing references.
1470 */
1472 fk_rel, pk_rel,
1473 oldslot, NULL,
1474 false,
1475 true, /* must detect new rows */
1477
1478 if (SPI_finish() != SPI_OK_FINISH)
1479 elog(ERROR, "SPI_finish failed");
1480
1482
1483 if (is_set_null)
1484 return PointerGetDatum(NULL);
1485 else
1486 {
1487 /*
1488 * If we just deleted or updated the PK row whose key was equal to the
1489 * FK columns' default values, and a referencing row exists in the FK
1490 * table, we would have updated that row to the same values it already
1491 * had --- and RI_FKey_fk_upd_check_required would hence believe no
1492 * check is necessary. So we need to do another lookup now and in
1493 * case a reference still exists, abort the operation. That is
1494 * already implemented in the NO ACTION trigger, so just run it. (This
1495 * recheck is only needed in the SET DEFAULT case, since CASCADE would
1496 * remove such rows in case of a DELETE operation or would change the
1497 * FK key values in case of an UPDATE, while SET NULL is certain to
1498 * result in rows that satisfy the FK constraint.)
1499 */
1500 return ri_restrict(trigdata, true);
1501 }
1502}
int32_t int32
Definition c.h:620
#define RI_PLAN_SETNULL_ONUPDATE
Definition ri_triggers.c:85
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition ri_triggers.c:86
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition ri_triggers.c:87
#define RI_PLAN_SETNULL_ONDELETE
Definition ri_triggers.c:84

References appendStringInfo(), attname, elog, ERROR, fb(), i, initStringInfo(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, PointerGetDatum, quoteOneName(), quoteRelationName(), 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 259 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 260 of file ri_triggers.c.

Referenced by InvalidateConstraintCacheCallBack(), and ri_LoadConstraintInfo().

◆ ri_fastpath_cache

◆ ri_fastpath_callback_registered

bool ri_fastpath_callback_registered = false
static

◆ ri_fastpath_xact_callback_registered

bool ri_fastpath_xact_callback_registered = false
static

Definition at line 4193 of file ri_triggers.c.

Referenced by ri_FastPathGetEntry().

◆ ri_query_cache

HTAB* ri_query_cache = NULL
static

Definition at line 258 of file ri_triggers.c.

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