Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
ri_triggers.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * ri_triggers.c
4 *
5 * Generic trigger procedures for referential integrity constraint
6 * checks.
7 *
8 * Note about memory management: the private hashtables kept here live
9 * across query and transaction boundaries, in fact they live as long as
10 * the backend does. This works because the hashtable structures
11 * themselves are allocated by dynahash.c in its permanent DynaHashCxt,
12 * and the SPI plans they point to are saved using SPI_keepplan().
13 * There is not currently any provision for throwing away a no-longer-needed
14 * plan --- consider improving this someday.
15 *
16 *
17 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
18 *
19 * src/backend/utils/adt/ri_triggers.c
20 *
21 *-------------------------------------------------------------------------
22 */
23
24#include "postgres.h"
25
26#include "access/htup_details.h"
27#include "access/sysattr.h"
28#include "access/table.h"
29#include "access/tableam.h"
30#include "access/xact.h"
33#include "commands/trigger.h"
34#include "executor/executor.h"
35#include "executor/spi.h"
36#include "lib/ilist.h"
37#include "miscadmin.h"
38#include "parser/parse_coerce.h"
40#include "utils/acl.h"
41#include "utils/builtins.h"
42#include "utils/datum.h"
43#include "utils/fmgroids.h"
44#include "utils/guc.h"
45#include "utils/inval.h"
46#include "utils/lsyscache.h"
47#include "utils/memutils.h"
48#include "utils/rel.h"
49#include "utils/rls.h"
50#include "utils/ruleutils.h"
51#include "utils/snapmgr.h"
52#include "utils/syscache.h"
53
54/*
55 * Local definitions
56 */
57
58#define RI_MAX_NUMKEYS INDEX_MAX_KEYS
59
60#define RI_INIT_CONSTRAINTHASHSIZE 64
61#define RI_INIT_QUERYHASHSIZE (RI_INIT_CONSTRAINTHASHSIZE * 4)
62
63#define RI_KEYS_ALL_NULL 0
64#define RI_KEYS_SOME_NULL 1
65#define RI_KEYS_NONE_NULL 2
66
67/* RI query type codes */
68/* these queries are executed against the PK (referenced) table: */
69#define RI_PLAN_CHECK_LOOKUPPK 1
70#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK 2
71#define RI_PLAN_LAST_ON_PK RI_PLAN_CHECK_LOOKUPPK_FROM_PK
72/* these queries are executed against the FK (referencing) table: */
73#define RI_PLAN_CASCADE_ONDELETE 3
74#define RI_PLAN_CASCADE_ONUPDATE 4
75#define RI_PLAN_NO_ACTION 5
76/* For RESTRICT, the same plan can be used for both ON DELETE and ON UPDATE triggers. */
77#define RI_PLAN_RESTRICT 6
78#define RI_PLAN_SETNULL_ONDELETE 7
79#define RI_PLAN_SETNULL_ONUPDATE 8
80#define RI_PLAN_SETDEFAULT_ONDELETE 9
81#define RI_PLAN_SETDEFAULT_ONUPDATE 10
82
83#define MAX_QUOTED_NAME_LEN (NAMEDATALEN*2+3)
84#define MAX_QUOTED_REL_NAME_LEN (MAX_QUOTED_NAME_LEN*2)
85
86#define RIAttName(rel, attnum) NameStr(*attnumAttName(rel, attnum))
87#define RIAttType(rel, attnum) attnumTypeId(rel, attnum)
88#define RIAttCollation(rel, attnum) attnumCollationId(rel, attnum)
89
90#define RI_TRIGTYPE_INSERT 1
91#define RI_TRIGTYPE_UPDATE 2
92#define RI_TRIGTYPE_DELETE 3
93
94
95/*
96 * RI_ConstraintInfo
97 *
98 * Information extracted from an FK pg_constraint entry. This is cached in
99 * ri_constraint_cache.
100 *
101 * Note that pf/pp/ff_eq_oprs may hold the overlaps operator instead of equals
102 * for the PERIOD part of a temporal foreign key.
103 */
104typedef struct RI_ConstraintInfo
105{
106 Oid constraint_id; /* OID of pg_constraint entry (hash key) */
107 bool valid; /* successfully initialized? */
108 Oid constraint_root_id; /* OID of topmost ancestor constraint;
109 * same as constraint_id if not inherited */
110 uint32 oidHashValue; /* hash value of constraint_id */
111 uint32 rootHashValue; /* hash value of constraint_root_id */
112 NameData conname; /* name of the FK constraint */
113 Oid pk_relid; /* referenced relation */
114 Oid fk_relid; /* referencing relation */
115 char confupdtype; /* foreign key's ON UPDATE action */
116 char confdeltype; /* foreign key's ON DELETE action */
117 int ndelsetcols; /* number of columns referenced in ON DELETE
118 * SET clause */
119 int16 confdelsetcols[RI_MAX_NUMKEYS]; /* attnums of cols to set on
120 * delete */
121 char confmatchtype; /* foreign key's match type */
122 bool hasperiod; /* if the foreign key uses PERIOD */
123 int nkeys; /* number of key columns */
124 int16 pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
125 int16 fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
126 Oid pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
127 Oid pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
128 Oid ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
129 Oid period_contained_by_oper; /* anyrange <@ anyrange */
130 Oid agged_period_contained_by_oper; /* fkattr <@ range_agg(pkattr) */
131 Oid period_intersect_oper; /* anyrange * anyrange */
132 dlist_node valid_link; /* Link in list of valid entries */
134
135/*
136 * RI_QueryKey
137 *
138 * The key identifying a prepared SPI plan in our query hashtable
139 */
140typedef struct RI_QueryKey
141{
142 Oid constr_id; /* OID of pg_constraint entry */
143 int32 constr_queryno; /* query type ID, see RI_PLAN_XXX above */
145
146/*
147 * RI_QueryHashEntry
148 */
149typedef struct RI_QueryHashEntry
150{
154
155/*
156 * RI_CompareKey
157 *
158 * The key identifying an entry showing how to compare two values
159 */
160typedef struct RI_CompareKey
161{
162 Oid eq_opr; /* the equality operator to apply */
163 Oid typeid; /* the data type to apply it to */
165
166/*
167 * RI_CompareHashEntry
168 */
170{
172 bool valid; /* successfully initialized? */
173 FmgrInfo eq_opr_finfo; /* call info for equality fn */
174 FmgrInfo cast_func_finfo; /* in case we must coerce input */
176
177
178/*
179 * Local data
180 */
182static HTAB *ri_query_cache = NULL;
183static HTAB *ri_compare_cache = NULL;
185
186
187/*
188 * Local function prototypes
189 */
190static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
191 TupleTableSlot *oldslot,
192 const RI_ConstraintInfo *riinfo);
193static Datum ri_restrict(TriggerData *trigdata, bool is_no_action);
194static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind);
195static void quoteOneName(char *buffer, const char *name);
196static void quoteRelationName(char *buffer, Relation rel);
197static void ri_GenerateQual(StringInfo buf,
198 const char *sep,
199 const char *leftop, Oid leftoptype,
200 Oid opoid,
201 const char *rightop, Oid rightoptype);
202static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
203static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot,
204 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
205static void ri_BuildQueryKey(RI_QueryKey *key,
206 const RI_ConstraintInfo *riinfo,
207 int32 constr_queryno);
208static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
209 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
210static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
211 Datum lhs, Datum rhs);
212
213static void ri_InitHashTables(void);
214static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue);
217static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
218
219static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
220 int tgkind);
222 Relation trig_rel, bool rel_is_pk);
223static const RI_ConstraintInfo *ri_LoadConstraintInfo(Oid constraintOid);
224static Oid get_ri_constraint_root(Oid constrOid);
225static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
226 RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel);
227static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo,
228 RI_QueryKey *qkey, SPIPlanPtr qplan,
229 Relation fk_rel, Relation pk_rel,
230 TupleTableSlot *oldslot, TupleTableSlot *newslot,
231 bool is_restrict,
232 bool detectNewRows, int expect_OK);
233static void ri_ExtractValues(Relation rel, TupleTableSlot *slot,
234 const RI_ConstraintInfo *riinfo, bool rel_is_pk,
235 Datum *vals, char *nulls);
236pg_noreturn static void ri_ReportViolation(const RI_ConstraintInfo *riinfo,
237 Relation pk_rel, Relation fk_rel,
238 TupleTableSlot *violatorslot, TupleDesc tupdesc,
239 int queryno, bool is_restrict, bool partgone);
240
241
242/*
243 * RI_FKey_check -
244 *
245 * Check foreign key existence (combined for INSERT and UPDATE).
246 */
247static Datum
249{
250 const RI_ConstraintInfo *riinfo;
251 Relation fk_rel;
252 Relation pk_rel;
253 TupleTableSlot *newslot;
254 RI_QueryKey qkey;
255 SPIPlanPtr qplan;
256
257 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
258 trigdata->tg_relation, false);
259
260 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
261 newslot = trigdata->tg_newslot;
262 else
263 newslot = trigdata->tg_trigslot;
264
265 /*
266 * We should not even consider checking the row if it is no longer valid,
267 * since it was either deleted (so the deferred check should be skipped)
268 * or updated (in which case only the latest version of the row should be
269 * checked). Test its liveness according to SnapshotSelf. We need pin
270 * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
271 * should be holding pin, but not lock.
272 */
274 return PointerGetDatum(NULL);
275
276 /*
277 * Get the relation descriptors of the FK and PK tables.
278 *
279 * pk_rel is opened in RowShareLock mode since that's what our eventual
280 * SELECT FOR KEY SHARE will get on it.
281 */
282 fk_rel = trigdata->tg_relation;
283 pk_rel = table_open(riinfo->pk_relid, RowShareLock);
284
285 switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
286 {
287 case RI_KEYS_ALL_NULL:
288
289 /*
290 * No further check needed - an all-NULL key passes every type of
291 * foreign key constraint.
292 */
293 table_close(pk_rel, RowShareLock);
294 return PointerGetDatum(NULL);
295
297
298 /*
299 * This is the only case that differs between the three kinds of
300 * MATCH.
301 */
302 switch (riinfo->confmatchtype)
303 {
305
306 /*
307 * Not allowed - MATCH FULL says either all or none of the
308 * attributes can be NULLs
309 */
311 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
312 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
314 NameStr(riinfo->conname)),
315 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
316 errtableconstraint(fk_rel,
317 NameStr(riinfo->conname))));
318 table_close(pk_rel, RowShareLock);
319 return PointerGetDatum(NULL);
320
322
323 /*
324 * MATCH SIMPLE - if ANY column is null, the key passes
325 * the constraint.
326 */
327 table_close(pk_rel, RowShareLock);
328 return PointerGetDatum(NULL);
329
330#ifdef NOT_USED
332
333 /*
334 * MATCH PARTIAL - all non-null columns must match. (not
335 * implemented, can be done by modifying the query below
336 * to only include non-null columns, or by writing a
337 * special version here)
338 */
339 break;
340#endif
341 }
342
344
345 /*
346 * Have a full qualified key - continue below for all three kinds
347 * of MATCH.
348 */
349 break;
350 }
351
352 SPI_connect();
353
354 /* Fetch or prepare a saved plan for the real check */
356
357 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
358 {
359 StringInfoData querybuf;
360 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
362 char paramname[16];
363 const char *querysep;
364 Oid queryoids[RI_MAX_NUMKEYS];
365 const char *pk_only;
366
367 /* ----------
368 * The query string built is
369 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
370 * FOR KEY SHARE OF x
371 * The type id's for the $ parameters are those of the
372 * corresponding FK attributes.
373 *
374 * But for temporal FKs we need to make sure
375 * the FK's range is completely covered.
376 * So we use this query instead:
377 * SELECT 1
378 * FROM (
379 * SELECT pkperiodatt AS r
380 * FROM [ONLY] pktable x
381 * WHERE pkatt1 = $1 [AND ...]
382 * AND pkperiodatt && $n
383 * FOR KEY SHARE OF x
384 * ) x1
385 * HAVING $n <@ range_agg(x1.r)
386 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
387 * we can make this a bit simpler.
388 * ----------
389 */
390 initStringInfo(&querybuf);
391 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
392 "" : "ONLY ";
393 quoteRelationName(pkrelname, pk_rel);
394 if (riinfo->hasperiod)
395 {
397 RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
398
399 appendStringInfo(&querybuf,
400 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
401 attname, pk_only, pkrelname);
402 }
403 else
404 {
405 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
406 pk_only, pkrelname);
407 }
408 querysep = "WHERE";
409 for (int i = 0; i < riinfo->nkeys; i++)
410 {
411 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
412 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
413
415 RIAttName(pk_rel, riinfo->pk_attnums[i]));
416 sprintf(paramname, "$%d", i + 1);
417 ri_GenerateQual(&querybuf, querysep,
418 attname, pk_type,
419 riinfo->pf_eq_oprs[i],
420 paramname, fk_type);
421 querysep = "AND";
422 queryoids[i] = fk_type;
423 }
424 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
425 if (riinfo->hasperiod)
426 {
427 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
428
429 appendStringInfoString(&querybuf, ") x1 HAVING ");
430 sprintf(paramname, "$%d", riinfo->nkeys);
431 ri_GenerateQual(&querybuf, "",
432 paramname, fk_type,
434 "pg_catalog.range_agg", ANYMULTIRANGEOID);
435 appendStringInfoString(&querybuf, "(x1.r)");
436 }
437
438 /* Prepare and save the plan */
439 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
440 &qkey, fk_rel, pk_rel);
441 }
442
443 /*
444 * Now check that foreign key exists in PK table
445 *
446 * XXX detectNewRows must be true when a partitioned table is on the
447 * referenced side. The reason is that our snapshot must be fresh in
448 * order for the hack in find_inheritance_children() to work.
449 */
450 ri_PerformCheck(riinfo, &qkey, qplan,
451 fk_rel, pk_rel,
452 NULL, newslot,
453 false,
454 pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
456
457 if (SPI_finish() != SPI_OK_FINISH)
458 elog(ERROR, "SPI_finish failed");
459
460 table_close(pk_rel, RowShareLock);
461
462 return PointerGetDatum(NULL);
463}
464
465
466/*
467 * RI_FKey_check_ins -
468 *
469 * Check foreign key existence at insert event on FK table.
470 */
471Datum
473{
474 /* Check that this is a valid trigger call on the right time and event. */
475 ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
476
477 /* Share code with UPDATE case. */
478 return RI_FKey_check((TriggerData *) fcinfo->context);
479}
480
481
482/*
483 * RI_FKey_check_upd -
484 *
485 * Check foreign key existence at update event on FK table.
486 */
487Datum
489{
490 /* Check that this is a valid trigger call on the right time and event. */
491 ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
492
493 /* Share code with INSERT case. */
494 return RI_FKey_check((TriggerData *) fcinfo->context);
495}
496
497
498/*
499 * ri_Check_Pk_Match
500 *
501 * Check to see if another PK row has been created that provides the same
502 * key values as the "oldslot" that's been modified or deleted in our trigger
503 * event. Returns true if a match is found in the PK table.
504 *
505 * We assume the caller checked that the oldslot contains no NULL key values,
506 * since otherwise a match is impossible.
507 */
508static bool
510 TupleTableSlot *oldslot,
511 const RI_ConstraintInfo *riinfo)
512{
513 SPIPlanPtr qplan;
514 RI_QueryKey qkey;
515 bool result;
516
517 /* Only called for non-null rows */
518 Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
519
520 SPI_connect();
521
522 /*
523 * Fetch or prepare a saved plan for checking PK table with values coming
524 * from a PK row
525 */
527
528 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
529 {
530 StringInfoData querybuf;
531 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
533 char paramname[16];
534 const char *querysep;
535 const char *pk_only;
536 Oid queryoids[RI_MAX_NUMKEYS];
537
538 /* ----------
539 * The query string built is
540 * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
541 * FOR KEY SHARE OF x
542 * The type id's for the $ parameters are those of the
543 * PK attributes themselves.
544 *
545 * But for temporal FKs we need to make sure
546 * the old PK's range is completely covered.
547 * So we use this query instead:
548 * SELECT 1
549 * FROM (
550 * SELECT pkperiodatt AS r
551 * FROM [ONLY] pktable x
552 * WHERE pkatt1 = $1 [AND ...]
553 * AND pkperiodatt && $n
554 * FOR KEY SHARE OF x
555 * ) x1
556 * HAVING $n <@ range_agg(x1.r)
557 * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
558 * we can make this a bit simpler.
559 * ----------
560 */
561 initStringInfo(&querybuf);
562 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
563 "" : "ONLY ";
564 quoteRelationName(pkrelname, pk_rel);
565 if (riinfo->hasperiod)
566 {
567 quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
568
569 appendStringInfo(&querybuf,
570 "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
571 attname, pk_only, pkrelname);
572 }
573 else
574 {
575 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
576 pk_only, pkrelname);
577 }
578 querysep = "WHERE";
579 for (int i = 0; i < riinfo->nkeys; i++)
580 {
581 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
582
584 RIAttName(pk_rel, riinfo->pk_attnums[i]));
585 sprintf(paramname, "$%d", i + 1);
586 ri_GenerateQual(&querybuf, querysep,
587 attname, pk_type,
588 riinfo->pp_eq_oprs[i],
589 paramname, pk_type);
590 querysep = "AND";
591 queryoids[i] = pk_type;
592 }
593 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
594 if (riinfo->hasperiod)
595 {
596 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
597
598 appendStringInfoString(&querybuf, ") x1 HAVING ");
599 sprintf(paramname, "$%d", riinfo->nkeys);
600 ri_GenerateQual(&querybuf, "",
601 paramname, fk_type,
603 "pg_catalog.range_agg", ANYMULTIRANGEOID);
604 appendStringInfoString(&querybuf, "(x1.r)");
605 }
606
607 /* Prepare and save the plan */
608 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
609 &qkey, fk_rel, pk_rel);
610 }
611
612 /*
613 * We have a plan now. Run it.
614 */
615 result = ri_PerformCheck(riinfo, &qkey, qplan,
616 fk_rel, pk_rel,
617 oldslot, NULL,
618 false,
619 true, /* treat like update */
621
622 if (SPI_finish() != SPI_OK_FINISH)
623 elog(ERROR, "SPI_finish failed");
624
625 return result;
626}
627
628
629/*
630 * RI_FKey_noaction_del -
631 *
632 * Give an error and roll back the current transaction if the
633 * delete has resulted in a violation of the given referential
634 * integrity constraint.
635 */
636Datum
638{
639 /* Check that this is a valid trigger call on the right time and event. */
640 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
641
642 /* Share code with RESTRICT/UPDATE cases. */
643 return ri_restrict((TriggerData *) fcinfo->context, true);
644}
645
646/*
647 * RI_FKey_restrict_del -
648 *
649 * Restrict delete from PK table to rows unreferenced by foreign key.
650 *
651 * The SQL standard intends that this referential action occur exactly when
652 * the delete is performed, rather than after. This appears to be
653 * the only difference between "NO ACTION" and "RESTRICT". In Postgres
654 * we still implement this as an AFTER trigger, but it's non-deferrable.
655 */
656Datum
658{
659 /* Check that this is a valid trigger call on the right time and event. */
660 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
661
662 /* Share code with NO ACTION/UPDATE cases. */
663 return ri_restrict((TriggerData *) fcinfo->context, false);
664}
665
666/*
667 * RI_FKey_noaction_upd -
668 *
669 * Give an error and roll back the current transaction if the
670 * update has resulted in a violation of the given referential
671 * integrity constraint.
672 */
673Datum
675{
676 /* Check that this is a valid trigger call on the right time and event. */
677 ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
678
679 /* Share code with RESTRICT/DELETE cases. */
680 return ri_restrict((TriggerData *) fcinfo->context, true);
681}
682
683/*
684 * RI_FKey_restrict_upd -
685 *
686 * Restrict update of PK to rows unreferenced by foreign key.
687 *
688 * The SQL standard intends that this referential action occur exactly when
689 * the update is performed, rather than after. This appears to be
690 * the only difference between "NO ACTION" and "RESTRICT". In Postgres
691 * we still implement this as an AFTER trigger, but it's non-deferrable.
692 */
693Datum
695{
696 /* Check that this is a valid trigger call on the right time and event. */
697 ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
698
699 /* Share code with NO ACTION/DELETE cases. */
700 return ri_restrict((TriggerData *) fcinfo->context, false);
701}
702
703/*
704 * ri_restrict -
705 *
706 * Common code for ON DELETE RESTRICT, ON DELETE NO ACTION,
707 * ON UPDATE RESTRICT, and ON UPDATE NO ACTION.
708 */
709static Datum
710ri_restrict(TriggerData *trigdata, bool is_no_action)
711{
712 const RI_ConstraintInfo *riinfo;
713 Relation fk_rel;
714 Relation pk_rel;
715 TupleTableSlot *oldslot;
716 RI_QueryKey qkey;
717 SPIPlanPtr qplan;
718
719 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
720 trigdata->tg_relation, true);
721
722 /*
723 * Get the relation descriptors of the FK and PK tables and the old tuple.
724 *
725 * fk_rel is opened in RowShareLock mode since that's what our eventual
726 * SELECT FOR KEY SHARE will get on it.
727 */
728 fk_rel = table_open(riinfo->fk_relid, RowShareLock);
729 pk_rel = trigdata->tg_relation;
730 oldslot = trigdata->tg_trigslot;
731
732 /*
733 * If another PK row now exists providing the old key values, we should
734 * not do anything. However, this check should only be made in the NO
735 * ACTION case; in RESTRICT cases we don't wish to allow another row to be
736 * substituted.
737 *
738 * If the foreign key has PERIOD, we incorporate looking for replacement
739 * rows in the main SQL query below, so we needn't do it here.
740 */
741 if (is_no_action && !riinfo->hasperiod &&
742 ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
743 {
744 table_close(fk_rel, RowShareLock);
745 return PointerGetDatum(NULL);
746 }
747
748 SPI_connect();
749
750 /*
751 * Fetch or prepare a saved plan for the restrict lookup (it's the same
752 * query for delete and update cases)
753 */
754 ri_BuildQueryKey(&qkey, riinfo, is_no_action ? RI_PLAN_NO_ACTION : RI_PLAN_RESTRICT);
755
756 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
757 {
758 StringInfoData querybuf;
759 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
760 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
762 char periodattname[MAX_QUOTED_NAME_LEN];
763 char paramname[16];
764 const char *querysep;
765 Oid queryoids[RI_MAX_NUMKEYS];
766 const char *fk_only;
767
768 /* ----------
769 * The query string built is
770 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
771 * FOR KEY SHARE OF x
772 * The type id's for the $ parameters are those of the
773 * corresponding PK attributes.
774 * ----------
775 */
776 initStringInfo(&querybuf);
777 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
778 "" : "ONLY ";
779 quoteRelationName(fkrelname, fk_rel);
780 appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
781 fk_only, fkrelname);
782 querysep = "WHERE";
783 for (int i = 0; i < riinfo->nkeys; i++)
784 {
785 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
786 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
787
789 RIAttName(fk_rel, riinfo->fk_attnums[i]));
790 sprintf(paramname, "$%d", i + 1);
791 ri_GenerateQual(&querybuf, querysep,
792 paramname, pk_type,
793 riinfo->pf_eq_oprs[i],
794 attname, fk_type);
795 querysep = "AND";
796 queryoids[i] = pk_type;
797 }
798
799 /*----------
800 * For temporal foreign keys, a reference could still be valid if the
801 * referenced range didn't change too much. Also if a referencing
802 * range extends past the current PK row, we don't want to check that
803 * part: some other PK row should fulfill it. We only want to check
804 * the part matching the PK record we've changed. Therefore to find
805 * invalid records we do this:
806 *
807 * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
808 * -- begin temporal
809 * AND $n && x.fkperiod
810 * AND NOT coalesce((x.fkperiod * $n) <@
811 * (SELECT range_agg(r)
812 * FROM (SELECT y.pkperiod r
813 * FROM [ONLY] <pktable> y
814 * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
815 * FOR KEY SHARE OF y) y2), false)
816 * -- end temporal
817 * FOR KEY SHARE OF x
818 *
819 * We need the coalesce in case the first subquery returns no rows.
820 * We need the second subquery because FOR KEY SHARE doesn't support
821 * aggregate queries.
822 */
823 if (riinfo->hasperiod && is_no_action)
824 {
825 Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
826 Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
827 StringInfoData intersectbuf;
828 StringInfoData replacementsbuf;
829 char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
830 "" : "ONLY ";
831
832 quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
833 sprintf(paramname, "$%d", riinfo->nkeys);
834
835 appendStringInfoString(&querybuf, " AND NOT coalesce(");
836
837 /* Intersect the fk with the old pk range */
838 initStringInfo(&intersectbuf);
839 appendStringInfoChar(&intersectbuf, '(');
840 ri_GenerateQual(&intersectbuf, "",
841 attname, fk_period_type,
842 riinfo->period_intersect_oper,
843 paramname, pk_period_type);
844 appendStringInfoChar(&intersectbuf, ')');
845
846 /* Find the remaining history */
847 initStringInfo(&replacementsbuf);
848 appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
849
850 quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
851 quoteRelationName(pkrelname, pk_rel);
852 appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
853 periodattname, pk_only, pkrelname);
854
855 /* Restrict pk rows to what matches */
856 querysep = "WHERE";
857 for (int i = 0; i < riinfo->nkeys; i++)
858 {
859 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
860
862 RIAttName(pk_rel, riinfo->pk_attnums[i]));
863 sprintf(paramname, "$%d", i + 1);
864 ri_GenerateQual(&replacementsbuf, querysep,
865 paramname, pk_type,
866 riinfo->pp_eq_oprs[i],
867 attname, pk_type);
868 querysep = "AND";
869 queryoids[i] = pk_type;
870 }
871 appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
872
873 ri_GenerateQual(&querybuf, "",
874 intersectbuf.data, fk_period_type,
876 replacementsbuf.data, ANYMULTIRANGEOID);
877 /* end of coalesce: */
878 appendStringInfoString(&querybuf, ", false)");
879 }
880
881 appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
882
883 /* Prepare and save the plan */
884 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
885 &qkey, fk_rel, pk_rel);
886 }
887
888 /*
889 * We have a plan now. Run it to check for existing references.
890 */
891 ri_PerformCheck(riinfo, &qkey, qplan,
892 fk_rel, pk_rel,
893 oldslot, NULL,
894 !is_no_action,
895 true, /* must detect new rows */
897
898 if (SPI_finish() != SPI_OK_FINISH)
899 elog(ERROR, "SPI_finish failed");
900
901 table_close(fk_rel, RowShareLock);
902
903 return PointerGetDatum(NULL);
904}
905
906
907/*
908 * RI_FKey_cascade_del -
909 *
910 * Cascaded delete foreign key references at delete event on PK table.
911 */
912Datum
914{
915 TriggerData *trigdata = (TriggerData *) fcinfo->context;
916 const RI_ConstraintInfo *riinfo;
917 Relation fk_rel;
918 Relation pk_rel;
919 TupleTableSlot *oldslot;
920 RI_QueryKey qkey;
921 SPIPlanPtr qplan;
922
923 /* Check that this is a valid trigger call on the right time and event. */
924 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
925
926 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
927 trigdata->tg_relation, true);
928
929 /*
930 * Get the relation descriptors of the FK and PK tables and the old tuple.
931 *
932 * fk_rel is opened in RowExclusiveLock mode since that's what our
933 * eventual DELETE will get on it.
934 */
935 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
936 pk_rel = trigdata->tg_relation;
937 oldslot = trigdata->tg_trigslot;
938
939 SPI_connect();
940
941 /* Fetch or prepare a saved plan for the cascaded delete */
943
944 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
945 {
946 StringInfoData querybuf;
947 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
949 char paramname[16];
950 const char *querysep;
951 Oid queryoids[RI_MAX_NUMKEYS];
952 const char *fk_only;
953
954 /* ----------
955 * The query string built is
956 * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
957 * The type id's for the $ parameters are those of the
958 * corresponding PK attributes.
959 * ----------
960 */
961 initStringInfo(&querybuf);
962 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
963 "" : "ONLY ";
964 quoteRelationName(fkrelname, fk_rel);
965 appendStringInfo(&querybuf, "DELETE FROM %s%s",
966 fk_only, fkrelname);
967 querysep = "WHERE";
968 for (int i = 0; i < riinfo->nkeys; i++)
969 {
970 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
971 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
972
974 RIAttName(fk_rel, riinfo->fk_attnums[i]));
975 sprintf(paramname, "$%d", i + 1);
976 ri_GenerateQual(&querybuf, querysep,
977 paramname, pk_type,
978 riinfo->pf_eq_oprs[i],
979 attname, fk_type);
980 querysep = "AND";
981 queryoids[i] = pk_type;
982 }
983
984 /* Prepare and save the plan */
985 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
986 &qkey, fk_rel, pk_rel);
987 }
988
989 /*
990 * We have a plan now. Build up the arguments from the key values in the
991 * deleted PK tuple and delete the referencing rows
992 */
993 ri_PerformCheck(riinfo, &qkey, qplan,
994 fk_rel, pk_rel,
995 oldslot, NULL,
996 false,
997 true, /* must detect new rows */
999
1000 if (SPI_finish() != SPI_OK_FINISH)
1001 elog(ERROR, "SPI_finish failed");
1002
1004
1005 return PointerGetDatum(NULL);
1006}
1007
1008
1009/*
1010 * RI_FKey_cascade_upd -
1011 *
1012 * Cascaded update foreign key references at update event on PK table.
1013 */
1014Datum
1016{
1017 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1018 const RI_ConstraintInfo *riinfo;
1019 Relation fk_rel;
1020 Relation pk_rel;
1021 TupleTableSlot *newslot;
1022 TupleTableSlot *oldslot;
1023 RI_QueryKey qkey;
1024 SPIPlanPtr qplan;
1025
1026 /* Check that this is a valid trigger call on the right time and event. */
1027 ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1028
1029 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1030 trigdata->tg_relation, true);
1031
1032 /*
1033 * Get the relation descriptors of the FK and PK tables and the new and
1034 * old tuple.
1035 *
1036 * fk_rel is opened in RowExclusiveLock mode since that's what our
1037 * eventual UPDATE will get on it.
1038 */
1039 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1040 pk_rel = trigdata->tg_relation;
1041 newslot = trigdata->tg_newslot;
1042 oldslot = trigdata->tg_trigslot;
1043
1044 SPI_connect();
1045
1046 /* Fetch or prepare a saved plan for the cascaded update */
1048
1049 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1050 {
1051 StringInfoData querybuf;
1052 StringInfoData qualbuf;
1053 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1055 char paramname[16];
1056 const char *querysep;
1057 const char *qualsep;
1058 Oid queryoids[RI_MAX_NUMKEYS * 2];
1059 const char *fk_only;
1060
1061 /* ----------
1062 * The query string built is
1063 * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1064 * WHERE $n = fkatt1 [AND ...]
1065 * The type id's for the $ parameters are those of the
1066 * corresponding PK attributes. Note that we are assuming
1067 * there is an assignment cast from the PK to the FK type;
1068 * else the parser will fail.
1069 * ----------
1070 */
1071 initStringInfo(&querybuf);
1072 initStringInfo(&qualbuf);
1073 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1074 "" : "ONLY ";
1075 quoteRelationName(fkrelname, fk_rel);
1076 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1077 fk_only, fkrelname);
1078 querysep = "";
1079 qualsep = "WHERE";
1080 for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1081 {
1082 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1083 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1084
1086 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1087 appendStringInfo(&querybuf,
1088 "%s %s = $%d",
1089 querysep, attname, i + 1);
1090 sprintf(paramname, "$%d", j + 1);
1091 ri_GenerateQual(&qualbuf, qualsep,
1092 paramname, pk_type,
1093 riinfo->pf_eq_oprs[i],
1094 attname, fk_type);
1095 querysep = ",";
1096 qualsep = "AND";
1097 queryoids[i] = pk_type;
1098 queryoids[j] = pk_type;
1099 }
1100 appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
1101
1102 /* Prepare and save the plan */
1103 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1104 &qkey, fk_rel, pk_rel);
1105 }
1106
1107 /*
1108 * We have a plan now. Run it to update the existing references.
1109 */
1110 ri_PerformCheck(riinfo, &qkey, qplan,
1111 fk_rel, pk_rel,
1112 oldslot, newslot,
1113 false,
1114 true, /* must detect new rows */
1116
1117 if (SPI_finish() != SPI_OK_FINISH)
1118 elog(ERROR, "SPI_finish failed");
1119
1121
1122 return PointerGetDatum(NULL);
1123}
1124
1125
1126/*
1127 * RI_FKey_setnull_del -
1128 *
1129 * Set foreign key references to NULL values at delete event on PK table.
1130 */
1131Datum
1133{
1134 /* Check that this is a valid trigger call on the right time and event. */
1135 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1136
1137 /* Share code with UPDATE case */
1138 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1139}
1140
1141/*
1142 * RI_FKey_setnull_upd -
1143 *
1144 * Set foreign key references to NULL at update event on PK table.
1145 */
1146Datum
1148{
1149 /* Check that this is a valid trigger call on the right time and event. */
1150 ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1151
1152 /* Share code with DELETE case */
1153 return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1154}
1155
1156/*
1157 * RI_FKey_setdefault_del -
1158 *
1159 * Set foreign key references to defaults at delete event on PK table.
1160 */
1161Datum
1163{
1164 /* Check that this is a valid trigger call on the right time and event. */
1165 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1166
1167 /* Share code with UPDATE case */
1168 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1169}
1170
1171/*
1172 * RI_FKey_setdefault_upd -
1173 *
1174 * Set foreign key references to defaults at update event on PK table.
1175 */
1176Datum
1178{
1179 /* Check that this is a valid trigger call on the right time and event. */
1180 ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1181
1182 /* Share code with DELETE case */
1183 return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1184}
1185
1186/*
1187 * ri_set -
1188 *
1189 * Common code for ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE SET
1190 * NULL, and ON UPDATE SET DEFAULT.
1191 */
1192static Datum
1193ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
1194{
1195 const RI_ConstraintInfo *riinfo;
1196 Relation fk_rel;
1197 Relation pk_rel;
1198 TupleTableSlot *oldslot;
1199 RI_QueryKey qkey;
1200 SPIPlanPtr qplan;
1201 int32 queryno;
1202
1203 riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1204 trigdata->tg_relation, true);
1205
1206 /*
1207 * Get the relation descriptors of the FK and PK tables and the old tuple.
1208 *
1209 * fk_rel is opened in RowExclusiveLock mode since that's what our
1210 * eventual UPDATE will get on it.
1211 */
1212 fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1213 pk_rel = trigdata->tg_relation;
1214 oldslot = trigdata->tg_trigslot;
1215
1216 SPI_connect();
1217
1218 /*
1219 * Fetch or prepare a saved plan for the trigger.
1220 */
1221 switch (tgkind)
1222 {
1223 case RI_TRIGTYPE_UPDATE:
1224 queryno = is_set_null
1227 break;
1228 case RI_TRIGTYPE_DELETE:
1229 queryno = is_set_null
1232 break;
1233 default:
1234 elog(ERROR, "invalid tgkind passed to ri_set");
1235 }
1236
1237 ri_BuildQueryKey(&qkey, riinfo, queryno);
1238
1239 if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1240 {
1241 StringInfoData querybuf;
1242 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1244 char paramname[16];
1245 const char *querysep;
1246 const char *qualsep;
1247 Oid queryoids[RI_MAX_NUMKEYS];
1248 const char *fk_only;
1249 int num_cols_to_set;
1250 const int16 *set_cols;
1251
1252 switch (tgkind)
1253 {
1254 case RI_TRIGTYPE_UPDATE:
1255 num_cols_to_set = riinfo->nkeys;
1256 set_cols = riinfo->fk_attnums;
1257 break;
1258 case RI_TRIGTYPE_DELETE:
1259
1260 /*
1261 * If confdelsetcols are present, then we only update the
1262 * columns specified in that array, otherwise we update all
1263 * the referencing columns.
1264 */
1265 if (riinfo->ndelsetcols != 0)
1266 {
1267 num_cols_to_set = riinfo->ndelsetcols;
1268 set_cols = riinfo->confdelsetcols;
1269 }
1270 else
1271 {
1272 num_cols_to_set = riinfo->nkeys;
1273 set_cols = riinfo->fk_attnums;
1274 }
1275 break;
1276 default:
1277 elog(ERROR, "invalid tgkind passed to ri_set");
1278 }
1279
1280 /* ----------
1281 * The query string built is
1282 * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1283 * WHERE $1 = fkatt1 [AND ...]
1284 * The type id's for the $ parameters are those of the
1285 * corresponding PK attributes.
1286 * ----------
1287 */
1288 initStringInfo(&querybuf);
1289 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1290 "" : "ONLY ";
1291 quoteRelationName(fkrelname, fk_rel);
1292 appendStringInfo(&querybuf, "UPDATE %s%s SET",
1293 fk_only, fkrelname);
1294
1295 /*
1296 * Add assignment clauses
1297 */
1298 querysep = "";
1299 for (int i = 0; i < num_cols_to_set; i++)
1300 {
1301 quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
1302 appendStringInfo(&querybuf,
1303 "%s %s = %s",
1304 querysep, attname,
1305 is_set_null ? "NULL" : "DEFAULT");
1306 querysep = ",";
1307 }
1308
1309 /*
1310 * Add WHERE clause
1311 */
1312 qualsep = "WHERE";
1313 for (int i = 0; i < riinfo->nkeys; i++)
1314 {
1315 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1316 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1317
1319 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1320
1321 sprintf(paramname, "$%d", i + 1);
1322 ri_GenerateQual(&querybuf, qualsep,
1323 paramname, pk_type,
1324 riinfo->pf_eq_oprs[i],
1325 attname, fk_type);
1326 qualsep = "AND";
1327 queryoids[i] = pk_type;
1328 }
1329
1330 /* Prepare and save the plan */
1331 qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1332 &qkey, fk_rel, pk_rel);
1333 }
1334
1335 /*
1336 * We have a plan now. Run it to update the existing references.
1337 */
1338 ri_PerformCheck(riinfo, &qkey, qplan,
1339 fk_rel, pk_rel,
1340 oldslot, NULL,
1341 false,
1342 true, /* must detect new rows */
1344
1345 if (SPI_finish() != SPI_OK_FINISH)
1346 elog(ERROR, "SPI_finish failed");
1347
1349
1350 if (is_set_null)
1351 return PointerGetDatum(NULL);
1352 else
1353 {
1354 /*
1355 * If we just deleted or updated the PK row whose key was equal to the
1356 * FK columns' default values, and a referencing row exists in the FK
1357 * table, we would have updated that row to the same values it already
1358 * had --- and RI_FKey_fk_upd_check_required would hence believe no
1359 * check is necessary. So we need to do another lookup now and in
1360 * case a reference still exists, abort the operation. That is
1361 * already implemented in the NO ACTION trigger, so just run it. (This
1362 * recheck is only needed in the SET DEFAULT case, since CASCADE would
1363 * remove such rows in case of a DELETE operation or would change the
1364 * FK key values in case of an UPDATE, while SET NULL is certain to
1365 * result in rows that satisfy the FK constraint.)
1366 */
1367 return ri_restrict(trigdata, true);
1368 }
1369}
1370
1371
1372/*
1373 * RI_FKey_pk_upd_check_required -
1374 *
1375 * Check if we really need to fire the RI trigger for an update or delete to a PK
1376 * relation. This is called by the AFTER trigger queue manager to see if
1377 * it can skip queuing an instance of an RI trigger. Returns true if the
1378 * trigger must be fired, false if we can prove the constraint will still
1379 * be satisfied.
1380 *
1381 * newslot will be NULL if this is called for a delete.
1382 */
1383bool
1385 TupleTableSlot *oldslot, TupleTableSlot *newslot)
1386{
1387 const RI_ConstraintInfo *riinfo;
1388
1389 riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1390
1391 /*
1392 * If any old key value is NULL, the row could not have been referenced by
1393 * an FK row, so no check is needed.
1394 */
1395 if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1396 return false;
1397
1398 /* If all old and new key values are equal, no check is needed */
1399 if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1400 return false;
1401
1402 /* Else we need to fire the trigger. */
1403 return true;
1404}
1405
1406/*
1407 * RI_FKey_fk_upd_check_required -
1408 *
1409 * Check if we really need to fire the RI trigger for an update to an FK
1410 * relation. This is called by the AFTER trigger queue manager to see if
1411 * it can skip queuing an instance of an RI trigger. Returns true if the
1412 * trigger must be fired, false if we can prove the constraint will still
1413 * be satisfied.
1414 */
1415bool
1417 TupleTableSlot *oldslot, TupleTableSlot *newslot)
1418{
1419 const RI_ConstraintInfo *riinfo;
1420 int ri_nullcheck;
1421
1422 /*
1423 * AfterTriggerSaveEvent() handles things such that this function is never
1424 * called for partitioned tables.
1425 */
1426 Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1427
1428 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1429
1430 ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1431
1432 /*
1433 * If all new key values are NULL, the row satisfies the constraint, so no
1434 * check is needed.
1435 */
1436 if (ri_nullcheck == RI_KEYS_ALL_NULL)
1437 return false;
1438
1439 /*
1440 * If some new key values are NULL, the behavior depends on the match
1441 * type.
1442 */
1443 else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1444 {
1445 switch (riinfo->confmatchtype)
1446 {
1448
1449 /*
1450 * If any new key value is NULL, the row must satisfy the
1451 * constraint, so no check is needed.
1452 */
1453 return false;
1454
1456
1457 /*
1458 * Don't know, must run full check.
1459 */
1460 break;
1461
1463
1464 /*
1465 * If some new key values are NULL, the row fails the
1466 * constraint. We must not throw error here, because the row
1467 * might get invalidated before the constraint is to be
1468 * checked, but we should queue the event to apply the check
1469 * later.
1470 */
1471 return true;
1472 }
1473 }
1474
1475 /*
1476 * Continues here for no new key values are NULL, or we couldn't decide
1477 * yet.
1478 */
1479
1480 /*
1481 * If the original row was inserted by our own transaction, we must fire
1482 * the trigger whether or not the keys are equal. This is because our
1483 * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1484 * not do anything; so we had better do the UPDATE check. (We could skip
1485 * this if we knew the INSERT trigger already fired, but there is no easy
1486 * way to know that.)
1487 */
1488 if (slot_is_current_xact_tuple(oldslot))
1489 return true;
1490
1491 /* If all old and new key values are equal, no check is needed */
1492 if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1493 return false;
1494
1495 /* Else we need to fire the trigger. */
1496 return true;
1497}
1498
1499/*
1500 * RI_Initial_Check -
1501 *
1502 * Check an entire table for non-matching values using a single query.
1503 * This is not a trigger procedure, but is called during ALTER TABLE
1504 * ADD FOREIGN KEY to validate the initial table contents.
1505 *
1506 * We expect that the caller has made provision to prevent any problems
1507 * caused by concurrent actions. This could be either by locking rel and
1508 * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
1509 * that triggers implementing the checks are already active.
1510 * Hence, we do not need to lock individual rows for the check.
1511 *
1512 * If the check fails because the current user doesn't have permissions
1513 * to read both tables, return false to let our caller know that they will
1514 * need to do something else to check the constraint.
1515 */
1516bool
1518{
1519 const RI_ConstraintInfo *riinfo;
1520 StringInfoData querybuf;
1521 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1522 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1523 char pkattname[MAX_QUOTED_NAME_LEN + 3];
1524 char fkattname[MAX_QUOTED_NAME_LEN + 3];
1525 RangeTblEntry *rte;
1526 RTEPermissionInfo *pk_perminfo;
1527 RTEPermissionInfo *fk_perminfo;
1528 List *rtes = NIL;
1529 List *perminfos = NIL;
1530 const char *sep;
1531 const char *fk_only;
1532 const char *pk_only;
1533 int save_nestlevel;
1534 char workmembuf[32];
1535 int spi_result;
1536 SPIPlanPtr qplan;
1537
1538 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1539
1540 /*
1541 * Check to make sure current user has enough permissions to do the test
1542 * query. (If not, caller can fall back to the trigger method, which
1543 * works because it changes user IDs on the fly.)
1544 *
1545 * XXX are there any other show-stopper conditions to check?
1546 */
1547 pk_perminfo = makeNode(RTEPermissionInfo);
1548 pk_perminfo->relid = RelationGetRelid(pk_rel);
1549 pk_perminfo->requiredPerms = ACL_SELECT;
1550 perminfos = lappend(perminfos, pk_perminfo);
1551 rte = makeNode(RangeTblEntry);
1552 rte->rtekind = RTE_RELATION;
1553 rte->relid = RelationGetRelid(pk_rel);
1554 rte->relkind = pk_rel->rd_rel->relkind;
1555 rte->rellockmode = AccessShareLock;
1556 rte->perminfoindex = list_length(perminfos);
1557 rtes = lappend(rtes, rte);
1558
1559 fk_perminfo = makeNode(RTEPermissionInfo);
1560 fk_perminfo->relid = RelationGetRelid(fk_rel);
1561 fk_perminfo->requiredPerms = ACL_SELECT;
1562 perminfos = lappend(perminfos, fk_perminfo);
1563 rte = makeNode(RangeTblEntry);
1564 rte->rtekind = RTE_RELATION;
1565 rte->relid = RelationGetRelid(fk_rel);
1566 rte->relkind = fk_rel->rd_rel->relkind;
1567 rte->rellockmode = AccessShareLock;
1568 rte->perminfoindex = list_length(perminfos);
1569 rtes = lappend(rtes, rte);
1570
1571 for (int i = 0; i < riinfo->nkeys; i++)
1572 {
1573 int attno;
1574
1576 pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1577
1579 fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1580 }
1581
1582 if (!ExecCheckPermissions(rtes, perminfos, false))
1583 return false;
1584
1585 /*
1586 * Also punt if RLS is enabled on either table unless this role has the
1587 * bypassrls right or is the table owner of the table(s) involved which
1588 * have RLS enabled.
1589 */
1591 ((pk_rel->rd_rel->relrowsecurity &&
1592 !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1593 GetUserId())) ||
1594 (fk_rel->rd_rel->relrowsecurity &&
1595 !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1596 GetUserId()))))
1597 return false;
1598
1599 /*----------
1600 * The query string built is:
1601 * SELECT fk.keycols FROM [ONLY] relname fk
1602 * LEFT OUTER JOIN [ONLY] pkrelname pk
1603 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1604 * WHERE pk.pkkeycol1 IS NULL AND
1605 * For MATCH SIMPLE:
1606 * (fk.keycol1 IS NOT NULL [AND ...])
1607 * For MATCH FULL:
1608 * (fk.keycol1 IS NOT NULL [OR ...])
1609 *
1610 * We attach COLLATE clauses to the operators when comparing columns
1611 * that have different collations.
1612 *----------
1613 */
1614 initStringInfo(&querybuf);
1615 appendStringInfoString(&querybuf, "SELECT ");
1616 sep = "";
1617 for (int i = 0; i < riinfo->nkeys; i++)
1618 {
1619 quoteOneName(fkattname,
1620 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1621 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1622 sep = ", ";
1623 }
1624
1625 quoteRelationName(pkrelname, pk_rel);
1626 quoteRelationName(fkrelname, fk_rel);
1627 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1628 "" : "ONLY ";
1629 pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1630 "" : "ONLY ";
1631 appendStringInfo(&querybuf,
1632 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1633 fk_only, fkrelname, pk_only, pkrelname);
1634
1635 strcpy(pkattname, "pk.");
1636 strcpy(fkattname, "fk.");
1637 sep = "(";
1638 for (int i = 0; i < riinfo->nkeys; i++)
1639 {
1640 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1641 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1642 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1643 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1644
1645 quoteOneName(pkattname + 3,
1646 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1647 quoteOneName(fkattname + 3,
1648 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1649 ri_GenerateQual(&querybuf, sep,
1650 pkattname, pk_type,
1651 riinfo->pf_eq_oprs[i],
1652 fkattname, fk_type);
1653 if (pk_coll != fk_coll)
1654 ri_GenerateQualCollation(&querybuf, pk_coll);
1655 sep = "AND";
1656 }
1657
1658 /*
1659 * It's sufficient to test any one pk attribute for null to detect a join
1660 * failure.
1661 */
1662 quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1663 appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1664
1665 sep = "";
1666 for (int i = 0; i < riinfo->nkeys; i++)
1667 {
1668 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1669 appendStringInfo(&querybuf,
1670 "%sfk.%s IS NOT NULL",
1671 sep, fkattname);
1672 switch (riinfo->confmatchtype)
1673 {
1675 sep = " AND ";
1676 break;
1678 sep = " OR ";
1679 break;
1680 }
1681 }
1682 appendStringInfoChar(&querybuf, ')');
1683
1684 /*
1685 * Temporarily increase work_mem so that the check query can be executed
1686 * more efficiently. It seems okay to do this because the query is simple
1687 * enough to not use a multiple of work_mem, and one typically would not
1688 * have many large foreign-key validations happening concurrently. So
1689 * this seems to meet the criteria for being considered a "maintenance"
1690 * operation, and accordingly we use maintenance_work_mem. However, we
1691 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1692 * let that get applied to the maintenance_work_mem value.
1693 *
1694 * We use the equivalent of a function SET option to allow the setting to
1695 * persist for exactly the duration of the check query. guc.c also takes
1696 * care of undoing the setting on error.
1697 */
1698 save_nestlevel = NewGUCNestLevel();
1699
1700 snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1701 (void) set_config_option("work_mem", workmembuf,
1703 GUC_ACTION_SAVE, true, 0, false);
1704 (void) set_config_option("hash_mem_multiplier", "1",
1706 GUC_ACTION_SAVE, true, 0, false);
1707
1708 SPI_connect();
1709
1710 /*
1711 * Generate the plan. We don't need to cache it, and there are no
1712 * arguments to the plan.
1713 */
1714 qplan = SPI_prepare(querybuf.data, 0, NULL);
1715
1716 if (qplan == NULL)
1717 elog(ERROR, "SPI_prepare returned %s for %s",
1719
1720 /*
1721 * Run the plan. For safety we force a current snapshot to be used. (In
1722 * transaction-snapshot mode, this arguably violates transaction isolation
1723 * rules, but we really haven't got much choice.) We don't need to
1724 * register the snapshot, because SPI_execute_snapshot will see to it. We
1725 * need at most one tuple returned, so pass limit = 1.
1726 */
1727 spi_result = SPI_execute_snapshot(qplan,
1728 NULL, NULL,
1731 true, false, 1);
1732
1733 /* Check result */
1734 if (spi_result != SPI_OK_SELECT)
1735 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1736
1737 /* Did we find a tuple violating the constraint? */
1738 if (SPI_processed > 0)
1739 {
1740 TupleTableSlot *slot;
1741 HeapTuple tuple = SPI_tuptable->vals[0];
1742 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1743 RI_ConstraintInfo fake_riinfo;
1744
1745 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1746
1747 heap_deform_tuple(tuple, tupdesc,
1748 slot->tts_values, slot->tts_isnull);
1750
1751 /*
1752 * The columns to look at in the result tuple are 1..N, not whatever
1753 * they are in the fk_rel. Hack up riinfo so that the subroutines
1754 * called here will behave properly.
1755 *
1756 * In addition to this, we have to pass the correct tupdesc to
1757 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1758 * or fk_rel's tupdesc.
1759 */
1760 memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1761 for (int i = 0; i < fake_riinfo.nkeys; i++)
1762 fake_riinfo.fk_attnums[i] = i + 1;
1763
1764 /*
1765 * If it's MATCH FULL, and there are any nulls in the FK keys,
1766 * complain about that rather than the lack of a match. MATCH FULL
1767 * disallows partially-null FK rows.
1768 */
1769 if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1770 ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1771 ereport(ERROR,
1772 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1773 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1775 NameStr(fake_riinfo.conname)),
1776 errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1777 errtableconstraint(fk_rel,
1778 NameStr(fake_riinfo.conname))));
1779
1780 /*
1781 * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1782 * query, which isn't true, but will cause it to use
1783 * fake_riinfo.fk_attnums as we need.
1784 */
1785 ri_ReportViolation(&fake_riinfo,
1786 pk_rel, fk_rel,
1787 slot, tupdesc,
1788 RI_PLAN_CHECK_LOOKUPPK, false, false);
1789
1791 }
1792
1793 if (SPI_finish() != SPI_OK_FINISH)
1794 elog(ERROR, "SPI_finish failed");
1795
1796 /*
1797 * Restore work_mem and hash_mem_multiplier.
1798 */
1799 AtEOXact_GUC(true, save_nestlevel);
1800
1801 return true;
1802}
1803
1804/*
1805 * RI_PartitionRemove_Check -
1806 *
1807 * Verify no referencing values exist, when a partition is detached on
1808 * the referenced side of a foreign key constraint.
1809 */
1810void
1812{
1813 const RI_ConstraintInfo *riinfo;
1814 StringInfoData querybuf;
1815 char *constraintDef;
1816 char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1817 char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1818 char pkattname[MAX_QUOTED_NAME_LEN + 3];
1819 char fkattname[MAX_QUOTED_NAME_LEN + 3];
1820 const char *sep;
1821 const char *fk_only;
1822 int save_nestlevel;
1823 char workmembuf[32];
1824 int spi_result;
1825 SPIPlanPtr qplan;
1826 int i;
1827
1828 riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1829
1830 /*
1831 * We don't check permissions before displaying the error message, on the
1832 * assumption that the user detaching the partition must have enough
1833 * privileges to examine the table contents anyhow.
1834 */
1835
1836 /*----------
1837 * The query string built is:
1838 * SELECT fk.keycols FROM [ONLY] relname fk
1839 * JOIN pkrelname pk
1840 * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1841 * WHERE (<partition constraint>) AND
1842 * For MATCH SIMPLE:
1843 * (fk.keycol1 IS NOT NULL [AND ...])
1844 * For MATCH FULL:
1845 * (fk.keycol1 IS NOT NULL [OR ...])
1846 *
1847 * We attach COLLATE clauses to the operators when comparing columns
1848 * that have different collations.
1849 *----------
1850 */
1851 initStringInfo(&querybuf);
1852 appendStringInfoString(&querybuf, "SELECT ");
1853 sep = "";
1854 for (i = 0; i < riinfo->nkeys; i++)
1855 {
1856 quoteOneName(fkattname,
1857 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1858 appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1859 sep = ", ";
1860 }
1861
1862 quoteRelationName(pkrelname, pk_rel);
1863 quoteRelationName(fkrelname, fk_rel);
1864 fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1865 "" : "ONLY ";
1866 appendStringInfo(&querybuf,
1867 " FROM %s%s fk JOIN %s pk ON",
1868 fk_only, fkrelname, pkrelname);
1869 strcpy(pkattname, "pk.");
1870 strcpy(fkattname, "fk.");
1871 sep = "(";
1872 for (i = 0; i < riinfo->nkeys; i++)
1873 {
1874 Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1875 Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1876 Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1877 Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1878
1879 quoteOneName(pkattname + 3,
1880 RIAttName(pk_rel, riinfo->pk_attnums[i]));
1881 quoteOneName(fkattname + 3,
1882 RIAttName(fk_rel, riinfo->fk_attnums[i]));
1883 ri_GenerateQual(&querybuf, sep,
1884 pkattname, pk_type,
1885 riinfo->pf_eq_oprs[i],
1886 fkattname, fk_type);
1887 if (pk_coll != fk_coll)
1888 ri_GenerateQualCollation(&querybuf, pk_coll);
1889 sep = "AND";
1890 }
1891
1892 /*
1893 * Start the WHERE clause with the partition constraint (except if this is
1894 * the default partition and there's no other partition, because the
1895 * partition constraint is the empty string in that case.)
1896 */
1897 constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1898 if (constraintDef && constraintDef[0] != '\0')
1899 appendStringInfo(&querybuf, ") WHERE %s AND (",
1900 constraintDef);
1901 else
1902 appendStringInfoString(&querybuf, ") WHERE (");
1903
1904 sep = "";
1905 for (i = 0; i < riinfo->nkeys; i++)
1906 {
1907 quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1908 appendStringInfo(&querybuf,
1909 "%sfk.%s IS NOT NULL",
1910 sep, fkattname);
1911 switch (riinfo->confmatchtype)
1912 {
1914 sep = " AND ";
1915 break;
1917 sep = " OR ";
1918 break;
1919 }
1920 }
1921 appendStringInfoChar(&querybuf, ')');
1922
1923 /*
1924 * Temporarily increase work_mem so that the check query can be executed
1925 * more efficiently. It seems okay to do this because the query is simple
1926 * enough to not use a multiple of work_mem, and one typically would not
1927 * have many large foreign-key validations happening concurrently. So
1928 * this seems to meet the criteria for being considered a "maintenance"
1929 * operation, and accordingly we use maintenance_work_mem. However, we
1930 * must also set hash_mem_multiplier to 1, since it is surely not okay to
1931 * let that get applied to the maintenance_work_mem value.
1932 *
1933 * We use the equivalent of a function SET option to allow the setting to
1934 * persist for exactly the duration of the check query. guc.c also takes
1935 * care of undoing the setting on error.
1936 */
1937 save_nestlevel = NewGUCNestLevel();
1938
1939 snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1940 (void) set_config_option("work_mem", workmembuf,
1942 GUC_ACTION_SAVE, true, 0, false);
1943 (void) set_config_option("hash_mem_multiplier", "1",
1945 GUC_ACTION_SAVE, true, 0, false);
1946
1947 SPI_connect();
1948
1949 /*
1950 * Generate the plan. We don't need to cache it, and there are no
1951 * arguments to the plan.
1952 */
1953 qplan = SPI_prepare(querybuf.data, 0, NULL);
1954
1955 if (qplan == NULL)
1956 elog(ERROR, "SPI_prepare returned %s for %s",
1958
1959 /*
1960 * Run the plan. For safety we force a current snapshot to be used. (In
1961 * transaction-snapshot mode, this arguably violates transaction isolation
1962 * rules, but we really haven't got much choice.) We don't need to
1963 * register the snapshot, because SPI_execute_snapshot will see to it. We
1964 * need at most one tuple returned, so pass limit = 1.
1965 */
1966 spi_result = SPI_execute_snapshot(qplan,
1967 NULL, NULL,
1970 true, false, 1);
1971
1972 /* Check result */
1973 if (spi_result != SPI_OK_SELECT)
1974 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1975
1976 /* Did we find a tuple that would violate the constraint? */
1977 if (SPI_processed > 0)
1978 {
1979 TupleTableSlot *slot;
1980 HeapTuple tuple = SPI_tuptable->vals[0];
1981 TupleDesc tupdesc = SPI_tuptable->tupdesc;
1982 RI_ConstraintInfo fake_riinfo;
1983
1984 slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1985
1986 heap_deform_tuple(tuple, tupdesc,
1987 slot->tts_values, slot->tts_isnull);
1989
1990 /*
1991 * The columns to look at in the result tuple are 1..N, not whatever
1992 * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1993 * will behave properly.
1994 *
1995 * In addition to this, we have to pass the correct tupdesc to
1996 * ri_ReportViolation, overriding its normal habit of using the pk_rel
1997 * or fk_rel's tupdesc.
1998 */
1999 memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
2000 for (i = 0; i < fake_riinfo.nkeys; i++)
2001 fake_riinfo.pk_attnums[i] = i + 1;
2002
2003 ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
2004 slot, tupdesc, 0, false, true);
2005 }
2006
2007 if (SPI_finish() != SPI_OK_FINISH)
2008 elog(ERROR, "SPI_finish failed");
2009
2010 /*
2011 * Restore work_mem and hash_mem_multiplier.
2012 */
2013 AtEOXact_GUC(true, save_nestlevel);
2014}
2015
2016
2017/* ----------
2018 * Local functions below
2019 * ----------
2020 */
2021
2022
2023/*
2024 * quoteOneName --- safely quote a single SQL name
2025 *
2026 * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
2027 */
2028static void
2029quoteOneName(char *buffer, const char *name)
2030{
2031 /* Rather than trying to be smart, just always quote it. */
2032 *buffer++ = '"';
2033 while (*name)
2034 {
2035 if (*name == '"')
2036 *buffer++ = '"';
2037 *buffer++ = *name++;
2038 }
2039 *buffer++ = '"';
2040 *buffer = '\0';
2041}
2042
2043/*
2044 * quoteRelationName --- safely quote a fully qualified relation name
2045 *
2046 * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
2047 */
2048static void
2049quoteRelationName(char *buffer, Relation rel)
2050{
2052 buffer += strlen(buffer);
2053 *buffer++ = '.';
2055}
2056
2057/*
2058 * ri_GenerateQual --- generate a WHERE clause equating two variables
2059 *
2060 * This basically appends " sep leftop op rightop" to buf, adding casts
2061 * and schema qualification as needed to ensure that the parser will select
2062 * the operator we specify. leftop and rightop should be parenthesized
2063 * if they aren't variables or parameters.
2064 */
2065static void
2067 const char *sep,
2068 const char *leftop, Oid leftoptype,
2069 Oid opoid,
2070 const char *rightop, Oid rightoptype)
2071{
2072 appendStringInfo(buf, " %s ", sep);
2073 generate_operator_clause(buf, leftop, leftoptype, opoid,
2074 rightop, rightoptype);
2075}
2076
2077/*
2078 * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
2079 *
2080 * We only have to use this function when directly comparing the referencing
2081 * and referenced columns, if they are of different collations; else the
2082 * parser will fail to resolve the collation to use. We don't need to use
2083 * this function for RI queries that compare a variable to a $n parameter.
2084 * Since parameter symbols always have default collation, the effect will be
2085 * to use the variable's collation.
2086 *
2087 * Note that we require that the collations of the referencing and the
2088 * referenced column have the same notion of equality: Either they have to
2089 * both be deterministic or else they both have to be the same. (See also
2090 * ATAddForeignKeyConstraint().)
2091 */
2092static void
2094{
2095 HeapTuple tp;
2096 Form_pg_collation colltup;
2097 char *collname;
2098 char onename[MAX_QUOTED_NAME_LEN];
2099
2100 /* Nothing to do if it's a noncollatable data type */
2101 if (!OidIsValid(collation))
2102 return;
2103
2104 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2105 if (!HeapTupleIsValid(tp))
2106 elog(ERROR, "cache lookup failed for collation %u", collation);
2107 colltup = (Form_pg_collation) GETSTRUCT(tp);
2108 collname = NameStr(colltup->collname);
2109
2110 /*
2111 * We qualify the name always, for simplicity and to ensure the query is
2112 * not search-path-dependent.
2113 */
2114 quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2115 appendStringInfo(buf, " COLLATE %s", onename);
2116 quoteOneName(onename, collname);
2117 appendStringInfo(buf, ".%s", onename);
2118
2119 ReleaseSysCache(tp);
2120}
2121
2122/* ----------
2123 * ri_BuildQueryKey -
2124 *
2125 * Construct a hashtable key for a prepared SPI plan of an FK constraint.
2126 *
2127 * key: output argument, *key is filled in based on the other arguments
2128 * riinfo: info derived from pg_constraint entry
2129 * constr_queryno: an internal number identifying the query type
2130 * (see RI_PLAN_XXX constants at head of file)
2131 * ----------
2132 */
2133static void
2135 int32 constr_queryno)
2136{
2137 /*
2138 * Inherited constraints with a common ancestor can share ri_query_cache
2139 * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2140 * Except in that case, the query processes the other table involved in
2141 * the FK constraint (i.e., not the table on which the trigger has been
2142 * fired), and so it will be the same for all members of the inheritance
2143 * tree. So we may use the root constraint's OID in the hash key, rather
2144 * than the constraint's own OID. This avoids creating duplicate SPI
2145 * plans, saving lots of work and memory when there are many partitions
2146 * with similar FK constraints.
2147 *
2148 * (Note that we must still have a separate RI_ConstraintInfo for each
2149 * constraint, because partitions can have different column orders,
2150 * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2151 *
2152 * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2153 * to use memset to clear them.
2154 */
2155 if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2156 key->constr_id = riinfo->constraint_root_id;
2157 else
2158 key->constr_id = riinfo->constraint_id;
2159 key->constr_queryno = constr_queryno;
2160}
2161
2162/*
2163 * Check that RI trigger function was called in expected context
2164 */
2165static void
2166ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
2167{
2168 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2169
2170 if (!CALLED_AS_TRIGGER(fcinfo))
2171 ereport(ERROR,
2172 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2173 errmsg("function \"%s\" was not called by trigger manager", funcname)));
2174
2175 /*
2176 * Check proper event
2177 */
2178 if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2179 !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2180 ereport(ERROR,
2181 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2182 errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2183
2184 switch (tgkind)
2185 {
2186 case RI_TRIGTYPE_INSERT:
2187 if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2188 ereport(ERROR,
2189 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2190 errmsg("function \"%s\" must be fired for INSERT", funcname)));
2191 break;
2192 case RI_TRIGTYPE_UPDATE:
2193 if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2194 ereport(ERROR,
2195 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2196 errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2197 break;
2198 case RI_TRIGTYPE_DELETE:
2199 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2200 ereport(ERROR,
2201 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2202 errmsg("function \"%s\" must be fired for DELETE", funcname)));
2203 break;
2204 }
2205}
2206
2207
2208/*
2209 * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
2210 */
2211static const RI_ConstraintInfo *
2212ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
2213{
2214 Oid constraintOid = trigger->tgconstraint;
2215 const RI_ConstraintInfo *riinfo;
2216
2217 /*
2218 * Check that the FK constraint's OID is available; it might not be if
2219 * we've been invoked via an ordinary trigger or an old-style "constraint
2220 * trigger".
2221 */
2222 if (!OidIsValid(constraintOid))
2223 ereport(ERROR,
2224 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2225 errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2226 trigger->tgname, RelationGetRelationName(trig_rel)),
2227 errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2228
2229 /* Find or create a hashtable entry for the constraint */
2230 riinfo = ri_LoadConstraintInfo(constraintOid);
2231
2232 /* Do some easy cross-checks against the trigger call data */
2233 if (rel_is_pk)
2234 {
2235 if (riinfo->fk_relid != trigger->tgconstrrelid ||
2236 riinfo->pk_relid != RelationGetRelid(trig_rel))
2237 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2238 trigger->tgname, RelationGetRelationName(trig_rel));
2239 }
2240 else
2241 {
2242 if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2243 riinfo->pk_relid != trigger->tgconstrrelid)
2244 elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2245 trigger->tgname, RelationGetRelationName(trig_rel));
2246 }
2247
2248 if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2251 elog(ERROR, "unrecognized confmatchtype: %d",
2252 riinfo->confmatchtype);
2253
2255 ereport(ERROR,
2256 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2257 errmsg("MATCH PARTIAL not yet implemented")));
2258
2259 return riinfo;
2260}
2261
2262/*
2263 * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
2264 */
2265static const RI_ConstraintInfo *
2267{
2268 RI_ConstraintInfo *riinfo;
2269 bool found;
2270 HeapTuple tup;
2271 Form_pg_constraint conForm;
2272
2273 /*
2274 * On the first call initialize the hashtable
2275 */
2278
2279 /*
2280 * Find or create a hash entry. If we find a valid one, just return it.
2281 */
2283 &constraintOid,
2284 HASH_ENTER, &found);
2285 if (!found)
2286 riinfo->valid = false;
2287 else if (riinfo->valid)
2288 return riinfo;
2289
2290 /*
2291 * Fetch the pg_constraint row so we can fill in the entry.
2292 */
2293 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2294 if (!HeapTupleIsValid(tup)) /* should not happen */
2295 elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2296 conForm = (Form_pg_constraint) GETSTRUCT(tup);
2297
2298 if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2299 elog(ERROR, "constraint %u is not a foreign key constraint",
2300 constraintOid);
2301
2302 /* And extract data */
2303 Assert(riinfo->constraint_id == constraintOid);
2304 if (OidIsValid(conForm->conparentid))
2305 riinfo->constraint_root_id =
2306 get_ri_constraint_root(conForm->conparentid);
2307 else
2308 riinfo->constraint_root_id = constraintOid;
2309 riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2310 ObjectIdGetDatum(constraintOid));
2311 riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2313 memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2314 riinfo->pk_relid = conForm->confrelid;
2315 riinfo->fk_relid = conForm->conrelid;
2316 riinfo->confupdtype = conForm->confupdtype;
2317 riinfo->confdeltype = conForm->confdeltype;
2318 riinfo->confmatchtype = conForm->confmatchtype;
2319 riinfo->hasperiod = conForm->conperiod;
2320
2322 &riinfo->nkeys,
2323 riinfo->fk_attnums,
2324 riinfo->pk_attnums,
2325 riinfo->pf_eq_oprs,
2326 riinfo->pp_eq_oprs,
2327 riinfo->ff_eq_oprs,
2328 &riinfo->ndelsetcols,
2329 riinfo->confdelsetcols);
2330
2331 /*
2332 * For temporal FKs, get the operators and functions we need. We ask the
2333 * opclass of the PK element for these. This all gets cached (as does the
2334 * generated plan), so there's no performance issue.
2335 */
2336 if (riinfo->hasperiod)
2337 {
2338 Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2339
2340 FindFKPeriodOpers(opclass,
2341 &riinfo->period_contained_by_oper,
2343 &riinfo->period_intersect_oper);
2344 }
2345
2346 ReleaseSysCache(tup);
2347
2348 /*
2349 * For efficient processing of invalidation messages below, we keep a
2350 * doubly-linked count list of all currently valid entries.
2351 */
2353
2354 riinfo->valid = true;
2355
2356 return riinfo;
2357}
2358
2359/*
2360 * get_ri_constraint_root
2361 * Returns the OID of the constraint's root parent
2362 */
2363static Oid
2365{
2366 for (;;)
2367 {
2368 HeapTuple tuple;
2369 Oid constrParentOid;
2370
2371 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2372 if (!HeapTupleIsValid(tuple))
2373 elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2374 constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2375 ReleaseSysCache(tuple);
2376 if (!OidIsValid(constrParentOid))
2377 break; /* we reached the root constraint */
2378 constrOid = constrParentOid;
2379 }
2380 return constrOid;
2381}
2382
2383/*
2384 * Callback for pg_constraint inval events
2385 *
2386 * While most syscache callbacks just flush all their entries, pg_constraint
2387 * gets enough update traffic that it's probably worth being smarter.
2388 * Invalidate any ri_constraint_cache entry associated with the syscache
2389 * entry with the specified hash value, or all entries if hashvalue == 0.
2390 *
2391 * Note: at the time a cache invalidation message is processed there may be
2392 * active references to the cache. Because of this we never remove entries
2393 * from the cache, but only mark them invalid, which is harmless to active
2394 * uses. (Any query using an entry should hold a lock sufficient to keep that
2395 * data from changing under it --- but we may get cache flushes anyway.)
2396 */
2397static void
2399{
2400 dlist_mutable_iter iter;
2401
2402 Assert(ri_constraint_cache != NULL);
2403
2404 /*
2405 * If the list of currently valid entries gets excessively large, we mark
2406 * them all invalid so we can empty the list. This arrangement avoids
2407 * O(N^2) behavior in situations where a session touches many foreign keys
2408 * and also does many ALTER TABLEs, such as a restore from pg_dump.
2409 */
2411 hashvalue = 0; /* pretend it's a cache reset */
2412
2414 {
2416 valid_link, iter.cur);
2417
2418 /*
2419 * We must invalidate not only entries directly matching the given
2420 * hash value, but also child entries, in case the invalidation
2421 * affects a root constraint.
2422 */
2423 if (hashvalue == 0 ||
2424 riinfo->oidHashValue == hashvalue ||
2425 riinfo->rootHashValue == hashvalue)
2426 {
2427 riinfo->valid = false;
2428 /* Remove invalidated entries from the list, too */
2430 }
2431 }
2432}
2433
2434
2435/*
2436 * Prepare execution plan for a query to enforce an RI restriction
2437 */
2438static SPIPlanPtr
2439ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
2440 RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
2441{
2442 SPIPlanPtr qplan;
2443 Relation query_rel;
2444 Oid save_userid;
2445 int save_sec_context;
2446
2447 /*
2448 * Use the query type code to determine whether the query is run against
2449 * the PK or FK table; we'll do the check as that table's owner
2450 */
2452 query_rel = pk_rel;
2453 else
2454 query_rel = fk_rel;
2455
2456 /* Switch to proper UID to perform check as */
2457 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2458 SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2459 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2461
2462 /* Create the plan */
2463 qplan = SPI_prepare(querystr, nargs, argtypes);
2464
2465 if (qplan == NULL)
2466 elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2467
2468 /* Restore UID and security context */
2469 SetUserIdAndSecContext(save_userid, save_sec_context);
2470
2471 /* Save the plan */
2472 SPI_keepplan(qplan);
2473 ri_HashPreparedPlan(qkey, qplan);
2474
2475 return qplan;
2476}
2477
2478/*
2479 * Perform a query to enforce an RI restriction
2480 */
2481static bool
2483 RI_QueryKey *qkey, SPIPlanPtr qplan,
2484 Relation fk_rel, Relation pk_rel,
2485 TupleTableSlot *oldslot, TupleTableSlot *newslot,
2486 bool is_restrict,
2487 bool detectNewRows, int expect_OK)
2488{
2489 Relation query_rel,
2490 source_rel;
2491 bool source_is_pk;
2492 Snapshot test_snapshot;
2493 Snapshot crosscheck_snapshot;
2494 int limit;
2495 int spi_result;
2496 Oid save_userid;
2497 int save_sec_context;
2498 Datum vals[RI_MAX_NUMKEYS * 2];
2499 char nulls[RI_MAX_NUMKEYS * 2];
2500
2501 /*
2502 * Use the query type code to determine whether the query is run against
2503 * the PK or FK table; we'll do the check as that table's owner
2504 */
2506 query_rel = pk_rel;
2507 else
2508 query_rel = fk_rel;
2509
2510 /*
2511 * The values for the query are taken from the table on which the trigger
2512 * is called - it is normally the other one with respect to query_rel. An
2513 * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2514 * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2515 * need some less klugy way to determine this.
2516 */
2518 {
2519 source_rel = fk_rel;
2520 source_is_pk = false;
2521 }
2522 else
2523 {
2524 source_rel = pk_rel;
2525 source_is_pk = true;
2526 }
2527
2528 /* Extract the parameters to be passed into the query */
2529 if (newslot)
2530 {
2531 ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2532 vals, nulls);
2533 if (oldslot)
2534 ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2535 vals + riinfo->nkeys, nulls + riinfo->nkeys);
2536 }
2537 else
2538 {
2539 ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2540 vals, nulls);
2541 }
2542
2543 /*
2544 * In READ COMMITTED mode, we just need to use an up-to-date regular
2545 * snapshot, and we will see all rows that could be interesting. But in
2546 * transaction-snapshot mode, we can't change the transaction snapshot. If
2547 * the caller passes detectNewRows == false then it's okay to do the query
2548 * with the transaction snapshot; otherwise we use a current snapshot, and
2549 * tell the executor to error out if it finds any rows under the current
2550 * snapshot that wouldn't be visible per the transaction snapshot. Note
2551 * that SPI_execute_snapshot will register the snapshots, so we don't need
2552 * to bother here.
2553 */
2554 if (IsolationUsesXactSnapshot() && detectNewRows)
2555 {
2556 CommandCounterIncrement(); /* be sure all my own work is visible */
2557 test_snapshot = GetLatestSnapshot();
2558 crosscheck_snapshot = GetTransactionSnapshot();
2559 }
2560 else
2561 {
2562 /* the default SPI behavior is okay */
2563 test_snapshot = InvalidSnapshot;
2564 crosscheck_snapshot = InvalidSnapshot;
2565 }
2566
2567 /*
2568 * If this is a select query (e.g., for a 'no action' or 'restrict'
2569 * trigger), we only need to see if there is a single row in the table,
2570 * matching the key. Otherwise, limit = 0 - because we want the query to
2571 * affect ALL the matching rows.
2572 */
2573 limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2574
2575 /* Switch to proper UID to perform check as */
2576 GetUserIdAndSecContext(&save_userid, &save_sec_context);
2577 SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2578 save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2580
2581 /* Finally we can run the query. */
2582 spi_result = SPI_execute_snapshot(qplan,
2583 vals, nulls,
2584 test_snapshot, crosscheck_snapshot,
2585 false, false, limit);
2586
2587 /* Restore UID and security context */
2588 SetUserIdAndSecContext(save_userid, save_sec_context);
2589
2590 /* Check result */
2591 if (spi_result < 0)
2592 elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2593
2594 if (expect_OK >= 0 && spi_result != expect_OK)
2595 ereport(ERROR,
2596 (errcode(ERRCODE_INTERNAL_ERROR),
2597 errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2599 NameStr(riinfo->conname),
2600 RelationGetRelationName(fk_rel)),
2601 errhint("This is most likely due to a rule having rewritten the query.")));
2602
2603 /* XXX wouldn't it be clearer to do this part at the caller? */
2605 expect_OK == SPI_OK_SELECT &&
2607 ri_ReportViolation(riinfo,
2608 pk_rel, fk_rel,
2609 newslot ? newslot : oldslot,
2610 NULL,
2611 qkey->constr_queryno, is_restrict, false);
2612
2613 return SPI_processed != 0;
2614}
2615
2616/*
2617 * Extract fields from a tuple into Datum/nulls arrays
2618 */
2619static void
2621 const RI_ConstraintInfo *riinfo, bool rel_is_pk,
2622 Datum *vals, char *nulls)
2623{
2624 const int16 *attnums;
2625 bool isnull;
2626
2627 if (rel_is_pk)
2628 attnums = riinfo->pk_attnums;
2629 else
2630 attnums = riinfo->fk_attnums;
2631
2632 for (int i = 0; i < riinfo->nkeys; i++)
2633 {
2634 vals[i] = slot_getattr(slot, attnums[i], &isnull);
2635 nulls[i] = isnull ? 'n' : ' ';
2636 }
2637}
2638
2639/*
2640 * Produce an error report
2641 *
2642 * If the failed constraint was on insert/update to the FK table,
2643 * we want the key names and values extracted from there, and the error
2644 * message to look like 'key blah is not present in PK'.
2645 * Otherwise, the attr names and values come from the PK table and the
2646 * message looks like 'key blah is still referenced from FK'.
2647 */
2648static void
2650 Relation pk_rel, Relation fk_rel,
2651 TupleTableSlot *violatorslot, TupleDesc tupdesc,
2652 int queryno, bool is_restrict, bool partgone)
2653{
2654 StringInfoData key_names;
2655 StringInfoData key_values;
2656 bool onfk;
2657 const int16 *attnums;
2658 Oid rel_oid;
2659 AclResult aclresult;
2660 bool has_perm = true;
2661
2662 /*
2663 * Determine which relation to complain about. If tupdesc wasn't passed
2664 * by caller, assume the violator tuple came from there.
2665 */
2666 onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2667 if (onfk)
2668 {
2669 attnums = riinfo->fk_attnums;
2670 rel_oid = fk_rel->rd_id;
2671 if (tupdesc == NULL)
2672 tupdesc = fk_rel->rd_att;
2673 }
2674 else
2675 {
2676 attnums = riinfo->pk_attnums;
2677 rel_oid = pk_rel->rd_id;
2678 if (tupdesc == NULL)
2679 tupdesc = pk_rel->rd_att;
2680 }
2681
2682 /*
2683 * Check permissions- if the user does not have access to view the data in
2684 * any of the key columns then we don't include the errdetail() below.
2685 *
2686 * Check if RLS is enabled on the relation first. If so, we don't return
2687 * any specifics to avoid leaking data.
2688 *
2689 * Check table-level permissions next and, failing that, column-level
2690 * privileges.
2691 *
2692 * When a partition at the referenced side is being detached/dropped, we
2693 * needn't check, since the user must be the table owner anyway.
2694 */
2695 if (partgone)
2696 has_perm = true;
2697 else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2698 {
2699 aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2700 if (aclresult != ACLCHECK_OK)
2701 {
2702 /* Try for column-level permissions */
2703 for (int idx = 0; idx < riinfo->nkeys; idx++)
2704 {
2705 aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2706 GetUserId(),
2707 ACL_SELECT);
2708
2709 /* No access to the key */
2710 if (aclresult != ACLCHECK_OK)
2711 {
2712 has_perm = false;
2713 break;
2714 }
2715 }
2716 }
2717 }
2718 else
2719 has_perm = false;
2720
2721 if (has_perm)
2722 {
2723 /* Get printable versions of the keys involved */
2724 initStringInfo(&key_names);
2725 initStringInfo(&key_values);
2726 for (int idx = 0; idx < riinfo->nkeys; idx++)
2727 {
2728 int fnum = attnums[idx];
2729 Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2730 char *name,
2731 *val;
2732 Datum datum;
2733 bool isnull;
2734
2735 name = NameStr(att->attname);
2736
2737 datum = slot_getattr(violatorslot, fnum, &isnull);
2738 if (!isnull)
2739 {
2740 Oid foutoid;
2741 bool typisvarlena;
2742
2743 getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2744 val = OidOutputFunctionCall(foutoid, datum);
2745 }
2746 else
2747 val = "null";
2748
2749 if (idx > 0)
2750 {
2751 appendStringInfoString(&key_names, ", ");
2752 appendStringInfoString(&key_values, ", ");
2753 }
2754 appendStringInfoString(&key_names, name);
2755 appendStringInfoString(&key_values, val);
2756 }
2757 }
2758
2759 if (partgone)
2760 ereport(ERROR,
2761 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2762 errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2764 NameStr(riinfo->conname)),
2765 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2766 key_names.data, key_values.data,
2767 RelationGetRelationName(fk_rel)),
2768 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2769 else if (onfk)
2770 ereport(ERROR,
2771 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2772 errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2774 NameStr(riinfo->conname)),
2775 has_perm ?
2776 errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2777 key_names.data, key_values.data,
2778 RelationGetRelationName(pk_rel)) :
2779 errdetail("Key is not present in table \"%s\".",
2780 RelationGetRelationName(pk_rel)),
2781 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2782 else if (is_restrict)
2783 ereport(ERROR,
2784 (errcode(ERRCODE_RESTRICT_VIOLATION),
2785 errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
2787 NameStr(riinfo->conname),
2788 RelationGetRelationName(fk_rel)),
2789 has_perm ?
2790 errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
2791 key_names.data, key_values.data,
2792 RelationGetRelationName(fk_rel)) :
2793 errdetail("Key is referenced from table \"%s\".",
2794 RelationGetRelationName(fk_rel)),
2795 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2796 else
2797 ereport(ERROR,
2798 (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2799 errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2801 NameStr(riinfo->conname),
2802 RelationGetRelationName(fk_rel)),
2803 has_perm ?
2804 errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2805 key_names.data, key_values.data,
2806 RelationGetRelationName(fk_rel)) :
2807 errdetail("Key is still referenced from table \"%s\".",
2808 RelationGetRelationName(fk_rel)),
2809 errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2810}
2811
2812
2813/*
2814 * ri_NullCheck -
2815 *
2816 * Determine the NULL state of all key values in a tuple
2817 *
2818 * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
2819 */
2820static int
2822 TupleTableSlot *slot,
2823 const RI_ConstraintInfo *riinfo, bool rel_is_pk)
2824{
2825 const int16 *attnums;
2826 bool allnull = true;
2827 bool nonenull = true;
2828
2829 if (rel_is_pk)
2830 attnums = riinfo->pk_attnums;
2831 else
2832 attnums = riinfo->fk_attnums;
2833
2834 for (int i = 0; i < riinfo->nkeys; i++)
2835 {
2836 if (slot_attisnull(slot, attnums[i]))
2837 nonenull = false;
2838 else
2839 allnull = false;
2840 }
2841
2842 if (allnull)
2843 return RI_KEYS_ALL_NULL;
2844
2845 if (nonenull)
2846 return RI_KEYS_NONE_NULL;
2847
2848 return RI_KEYS_SOME_NULL;
2849}
2850
2851
2852/*
2853 * ri_InitHashTables -
2854 *
2855 * Initialize our internal hash tables.
2856 */
2857static void
2859{
2860 HASHCTL ctl;
2861
2862 ctl.keysize = sizeof(Oid);
2863 ctl.entrysize = sizeof(RI_ConstraintInfo);
2864 ri_constraint_cache = hash_create("RI constraint cache",
2867
2868 /* Arrange to flush cache on pg_constraint changes */
2871 (Datum) 0);
2872
2873 ctl.keysize = sizeof(RI_QueryKey);
2874 ctl.entrysize = sizeof(RI_QueryHashEntry);
2875 ri_query_cache = hash_create("RI query cache",
2878
2879 ctl.keysize = sizeof(RI_CompareKey);
2880 ctl.entrysize = sizeof(RI_CompareHashEntry);
2881 ri_compare_cache = hash_create("RI compare cache",
2884}
2885
2886
2887/*
2888 * ri_FetchPreparedPlan -
2889 *
2890 * Lookup for a query key in our private hash table of prepared
2891 * and saved SPI execution plans. Return the plan if found or NULL.
2892 */
2893static SPIPlanPtr
2895{
2896 RI_QueryHashEntry *entry;
2898
2899 /*
2900 * On the first call initialize the hashtable
2901 */
2902 if (!ri_query_cache)
2904
2905 /*
2906 * Lookup for the key
2907 */
2909 key,
2910 HASH_FIND, NULL);
2911 if (entry == NULL)
2912 return NULL;
2913
2914 /*
2915 * Check whether the plan is still valid. If it isn't, we don't want to
2916 * simply rely on plancache.c to regenerate it; rather we should start
2917 * from scratch and rebuild the query text too. This is to cover cases
2918 * such as table/column renames. We depend on the plancache machinery to
2919 * detect possible invalidations, though.
2920 *
2921 * CAUTION: this check is only trustworthy if the caller has already
2922 * locked both FK and PK rels.
2923 */
2924 plan = entry->plan;
2925 if (plan && SPI_plan_is_valid(plan))
2926 return plan;
2927
2928 /*
2929 * Otherwise we might as well flush the cached plan now, to free a little
2930 * memory space before we make a new one.
2931 */
2932 entry->plan = NULL;
2933 if (plan)
2935
2936 return NULL;
2937}
2938
2939
2940/*
2941 * ri_HashPreparedPlan -
2942 *
2943 * Add another plan to our private SPI query plan hashtable.
2944 */
2945static void
2947{
2948 RI_QueryHashEntry *entry;
2949 bool found;
2950
2951 /*
2952 * On the first call initialize the hashtable
2953 */
2954 if (!ri_query_cache)
2956
2957 /*
2958 * Add the new plan. We might be overwriting an entry previously found
2959 * invalid by ri_FetchPreparedPlan.
2960 */
2962 key,
2963 HASH_ENTER, &found);
2964 Assert(!found || entry->plan == NULL);
2965 entry->plan = plan;
2966}
2967
2968
2969/*
2970 * ri_KeysEqual -
2971 *
2972 * Check if all key values in OLD and NEW are "equivalent":
2973 * For normal FKs we check for equality.
2974 * For temporal FKs we check that the PK side is a superset of its old value,
2975 * or the FK side is a subset of its old value.
2976 *
2977 * Note: at some point we might wish to redefine this as checking for
2978 * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
2979 * considered equal. Currently there is no need since all callers have
2980 * previously found at least one of the rows to contain no nulls.
2981 */
2982static bool
2984 const RI_ConstraintInfo *riinfo, bool rel_is_pk)
2985{
2986 const int16 *attnums;
2987
2988 if (rel_is_pk)
2989 attnums = riinfo->pk_attnums;
2990 else
2991 attnums = riinfo->fk_attnums;
2992
2993 /* XXX: could be worthwhile to fetch all necessary attrs at once */
2994 for (int i = 0; i < riinfo->nkeys; i++)
2995 {
2996 Datum oldvalue;
2997 Datum newvalue;
2998 bool isnull;
2999
3000 /*
3001 * Get one attribute's oldvalue. If it is NULL - they're not equal.
3002 */
3003 oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3004 if (isnull)
3005 return false;
3006
3007 /*
3008 * Get one attribute's newvalue. If it is NULL - they're not equal.
3009 */
3010 newvalue = slot_getattr(newslot, attnums[i], &isnull);
3011 if (isnull)
3012 return false;
3013
3014 if (rel_is_pk)
3015 {
3016 /*
3017 * If we are looking at the PK table, then do a bytewise
3018 * comparison. We must propagate PK changes if the value is
3019 * changed to one that "looks" different but would compare as
3020 * equal using the equality operator. This only makes a
3021 * difference for ON UPDATE CASCADE, but for consistency we treat
3022 * all changes to the PK the same.
3023 */
3024 CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3025
3026 if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3027 return false;
3028 }
3029 else
3030 {
3031 Oid eq_opr;
3032
3033 /*
3034 * When comparing the PERIOD columns we can skip the check
3035 * whenever the referencing column stayed equal or shrank, so test
3036 * with the contained-by operator instead.
3037 */
3038 if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3039 eq_opr = riinfo->period_contained_by_oper;
3040 else
3041 eq_opr = riinfo->ff_eq_oprs[i];
3042
3043 /*
3044 * For the FK table, compare with the appropriate equality
3045 * operator. Changes that compare equal will still satisfy the
3046 * constraint after the update.
3047 */
3048 if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3049 newvalue, oldvalue))
3050 return false;
3051 }
3052 }
3053
3054 return true;
3055}
3056
3057
3058/*
3059 * ri_CompareWithCast -
3060 *
3061 * Call the appropriate comparison operator for two values.
3062 * Normally this is equality, but for the PERIOD part of foreign keys
3063 * it is ContainedBy, so the order of lhs vs rhs is significant.
3064 * See below for how the collation is applied.
3065 *
3066 * NB: we have already checked that neither value is null.
3067 */
3068static bool
3070 Datum lhs, Datum rhs)
3071{
3072 RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3073
3074 /* Do we need to cast the values? */
3075 if (OidIsValid(entry->cast_func_finfo.fn_oid))
3076 {
3077 lhs = FunctionCall3(&entry->cast_func_finfo,
3078 lhs,
3079 Int32GetDatum(-1), /* typmod */
3080 BoolGetDatum(false)); /* implicit coercion */
3081 rhs = FunctionCall3(&entry->cast_func_finfo,
3082 rhs,
3083 Int32GetDatum(-1), /* typmod */
3084 BoolGetDatum(false)); /* implicit coercion */
3085 }
3086
3087 /*
3088 * Apply the comparison operator.
3089 *
3090 * Note: This function is part of a call stack that determines whether an
3091 * update to a row is significant enough that it needs checking or action
3092 * on the other side of a foreign-key constraint. Therefore, the
3093 * comparison here would need to be done with the collation of the *other*
3094 * table. For simplicity (e.g., we might not even have the other table
3095 * open), we'll use our own collation. This is fine because we require
3096 * that both collations have the same notion of equality (either they are
3097 * both deterministic or else they are both the same).
3098 *
3099 * With range/multirangetypes, the collation of the base type is stored as
3100 * part of the rangetype (pg_range.rngcollation), and always used, so
3101 * there is no danger of inconsistency even using a non-equals operator.
3102 * But if we support arbitrary types with PERIOD, we should perhaps just
3103 * always force a re-check.
3104 */
3105 return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
3106}
3107
3108/*
3109 * ri_HashCompareOp -
3110 *
3111 * See if we know how to compare two values, and create a new hash entry
3112 * if not.
3113 */
3114static RI_CompareHashEntry *
3115ri_HashCompareOp(Oid eq_opr, Oid typeid)
3116{
3118 RI_CompareHashEntry *entry;
3119 bool found;
3120
3121 /*
3122 * On the first call initialize the hashtable
3123 */
3124 if (!ri_compare_cache)
3126
3127 /*
3128 * Find or create a hash entry. Note we're assuming RI_CompareKey
3129 * contains no struct padding.
3130 */
3131 key.eq_opr = eq_opr;
3132 key.typeid = typeid;
3134 &key,
3135 HASH_ENTER, &found);
3136 if (!found)
3137 entry->valid = false;
3138
3139 /*
3140 * If not already initialized, do so. Since we'll keep this hash entry
3141 * for the life of the backend, put any subsidiary info for the function
3142 * cache structs into TopMemoryContext.
3143 */
3144 if (!entry->valid)
3145 {
3146 Oid lefttype,
3147 righttype,
3148 castfunc;
3149 CoercionPathType pathtype;
3150
3151 /* We always need to know how to call the equality operator */
3152 fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3154
3155 /*
3156 * If we chose to use a cast from FK to PK type, we may have to apply
3157 * the cast function to get to the operator's input type.
3158 *
3159 * XXX eventually it would be good to support array-coercion cases
3160 * here and in ri_CompareWithCast(). At the moment there is no point
3161 * because cases involving nonidentical array types will be rejected
3162 * at constraint creation time.
3163 *
3164 * XXX perhaps also consider supporting CoerceViaIO? No need at the
3165 * moment since that will never be generated for implicit coercions.
3166 */
3167 op_input_types(eq_opr, &lefttype, &righttype);
3168 Assert(lefttype == righttype);
3169 if (typeid == lefttype)
3170 castfunc = InvalidOid; /* simplest case */
3171 else
3172 {
3173 pathtype = find_coercion_pathway(lefttype, typeid,
3175 &castfunc);
3176 if (pathtype != COERCION_PATH_FUNC &&
3177 pathtype != COERCION_PATH_RELABELTYPE)
3178 {
3179 /*
3180 * The declared input type of the eq_opr might be a
3181 * polymorphic type such as ANYARRAY or ANYENUM, or other
3182 * special cases such as RECORD; find_coercion_pathway
3183 * currently doesn't subsume these special cases.
3184 */
3185 if (!IsBinaryCoercible(typeid, lefttype))
3186 elog(ERROR, "no conversion function from %s to %s",
3187 format_type_be(typeid),
3188 format_type_be(lefttype));
3189 }
3190 }
3191 if (OidIsValid(castfunc))
3192 fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3194 else
3196 entry->valid = true;
3197 }
3198
3199 return entry;
3200}
3201
3202
3203/*
3204 * Given a trigger function OID, determine whether it is an RI trigger,
3205 * and if so whether it is attached to PK or FK relation.
3206 */
3207int
3209{
3210 switch (tgfoid)
3211 {
3212 case F_RI_FKEY_CASCADE_DEL:
3213 case F_RI_FKEY_CASCADE_UPD:
3214 case F_RI_FKEY_RESTRICT_DEL:
3215 case F_RI_FKEY_RESTRICT_UPD:
3216 case F_RI_FKEY_SETNULL_DEL:
3217 case F_RI_FKEY_SETNULL_UPD:
3218 case F_RI_FKEY_SETDEFAULT_DEL:
3219 case F_RI_FKEY_SETDEFAULT_UPD:
3220 case F_RI_FKEY_NOACTION_DEL:
3221 case F_RI_FKEY_NOACTION_UPD:
3222 return RI_TRIGGER_PK;
3223
3224 case F_RI_FKEY_CHECK_INS:
3225 case F_RI_FKEY_CHECK_UPD:
3226 return RI_TRIGGER_FK;
3227 }
3228
3229 return RI_TRIGGER_NONE;
3230}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:4186
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3866
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4088
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4037
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define NameStr(name)
Definition: c.h:752
#define pg_noreturn
Definition: c.h:164
int16_t int16
Definition: c.h:534
int32_t int32
Definition: c.h:535
uint32_t uint32
Definition: c.h:539
#define OidIsValid(objectId)
Definition: c.h:775
Oid collid
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
int errdetail(const char *fmt,...)
Definition: elog.c:1207
int errhint(const char *fmt,...)
Definition: elog.c:1321
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:582
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1427
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1443
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1741
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1762
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
#define FunctionCall3(flinfo, arg1, arg2, arg3)
Definition: fmgr.h:704
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int maintenance_work_mem
Definition: globals.c:133
int NewGUCNestLevel(void)
Definition: guc.c:2240
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2267
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:3347
@ GUC_ACTION_SAVE
Definition: guc.h:205
@ PGC_S_SESSION
Definition: guc.h:126
@ PGC_USERSET
Definition: guc.h:79
Assert(PointerIsAligned(start, uint64))
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1346
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
#define dclist_container(type, membername, ptr)
Definition: ilist.h:947
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition: ilist.h:709
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
#define funcname
Definition: indent_codes.h:69
long val
Definition: informix.c:689
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1812
int j
Definition: isn.c:78
int i
Definition: isn.c:77
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
List * lappend(List *list, void *datum)
Definition: list.c:339
#define AccessShareLock
Definition: lockdefs.h:36
#define RowShareLock
Definition: lockdefs.h:37
#define RowExclusiveLock
Definition: lockdefs.h:38
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3074
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1452
Oid get_index_column_opclass(Oid index_oid, int attno)
Definition: lsyscache.c:3679
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1525
MemoryContext TopMemoryContext
Definition: mcxt.c:166
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:319
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:317
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:612
Oid GetUserId(void)
Definition: miscinit.c:469
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:619
#define makeNode(_type_)
Definition: nodes.h:161
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType
Definition: parse_coerce.h:25
@ COERCION_PATH_FUNC
Definition: parse_coerce.h:27
@ COERCION_PATH_RELABELTYPE
Definition: parse_coerce.h:28
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2825
@ RTE_RELATION
Definition: parsenodes.h:1041
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2824
#define ACL_SELECT
Definition: parsenodes.h:77
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2823
NameData attname
Definition: pg_attribute.h:41
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
void * arg
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58
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)
FormData_pg_constraint * Form_pg_constraint
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define plan(x)
Definition: pg_regress.c:161
static char * buf
Definition: pg_test_fsync.c:72
#define sprintf
Definition: port.h:241
#define snprintf
Definition: port.h:239
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
uint64_t Datum
Definition: postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
@ COERCION_IMPLICIT
Definition: primnodes.h:733
tree ctl
Definition: radixtree.h:1838
#define RelationGetForm(relation)
Definition: rel.h:508
#define RelationGetRelid(relation)
Definition: rel.h:514
#define RelationGetDescr(relation)
Definition: rel.h:540
#define RelationGetRelationName(relation)
Definition: rel.h:548
#define RelationGetNamespace(relation)
Definition: rel.h:555
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6103
static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
Definition: ri_triggers.c:1193
static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo, RI_QueryKey *qkey, SPIPlanPtr qplan, Relation fk_rel, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, bool is_restrict, bool detectNewRows, int expect_OK)
Definition: ri_triggers.c:2482
#define RI_TRIGTYPE_INSERT
Definition: ri_triggers.c:90
struct RI_ConstraintInfo RI_ConstraintInfo
static const RI_ConstraintInfo * ri_LoadConstraintInfo(Oid constraintOid)
Definition: ri_triggers.c:2266
static Datum RI_FKey_check(TriggerData *trigdata)
Definition: ri_triggers.c:248
#define RI_PLAN_SETNULL_ONUPDATE
Definition: ri_triggers.c:79
#define RI_PLAN_CASCADE_ONUPDATE
Definition: ri_triggers.c:74
#define RI_TRIGTYPE_DELETE
Definition: ri_triggers.c:92
Datum RI_FKey_setnull_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:1132
static pg_noreturn void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool is_restrict, bool partgone)
Definition: ri_triggers.c:2649
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2946
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:2029
bool RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: ri_triggers.c:1384
#define RI_PLAN_LAST_ON_PK
Definition: ri_triggers.c:71
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:87
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:2093
Datum RI_FKey_cascade_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:913
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:64
Datum RI_FKey_check_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:488
static HTAB * ri_query_cache
Definition: ri_triggers.c:182
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:84
Datum RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:694
static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: ri_triggers.c:2398
static Datum ri_restrict(TriggerData *trigdata, bool is_no_action)
Definition: ri_triggers.c:710
Datum RI_FKey_restrict_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:657
#define RI_PLAN_RESTRICT
Definition: ri_triggers.c:77
Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:637
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:2049
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2821
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ri_triggers.c:2066
struct RI_QueryKey RI_QueryKey
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2983
struct RI_CompareHashEntry RI_CompareHashEntry
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:3115
#define RI_PLAN_CHECK_LOOKUPPK_FROM_PK
Definition: ri_triggers.c:70
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:88
static dclist_head ri_constraint_cache_valid_list
Definition: ri_triggers.c:184
static Oid get_ri_constraint_root(Oid constrOid)
Definition: ri_triggers.c:2364
Datum RI_FKey_check_ins(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:472
struct RI_QueryHashEntry RI_QueryHashEntry
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:63
static HTAB * ri_compare_cache
Definition: ri_triggers.c:183
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:65
#define RI_INIT_QUERYHASHSIZE
Definition: ri_triggers.c:61
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2212
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:2134
#define RI_PLAN_CASCADE_ONDELETE
Definition: ri_triggers.c:73
Datum RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:1147
#define RI_PLAN_SETDEFAULT_ONDELETE
Definition: ri_triggers.c:80
Datum RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:1162
#define RI_PLAN_SETDEFAULT_ONUPDATE
Definition: ri_triggers.c:81
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:69
static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid, Datum lhs, Datum rhs)
Definition: ri_triggers.c:3069
#define RI_PLAN_SETNULL_ONDELETE
Definition: ri_triggers.c:78
#define RI_INIT_CONSTRAINTHASHSIZE
Definition: ri_triggers.c:60
bool RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1517
static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel, TupleTableSlot *oldslot, const RI_ConstraintInfo *riinfo)
Definition: ri_triggers.c:509
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1811
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2439
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:83
static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
Definition: ri_triggers.c:2166
#define RI_TRIGTYPE_UPDATE
Definition: ri_triggers.c:91
bool RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: ri_triggers.c:1416
int RI_FKey_trigger_type(Oid tgfoid)
Definition: ri_triggers.c:3208
Datum RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:1015
Datum RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:674
static void ri_InitHashTables(void)
Definition: ri_triggers.c:2858
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2620
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:86
#define RI_MAX_NUMKEYS
Definition: ri_triggers.c:58
static HTAB * ri_constraint_cache
Definition: ri_triggers.c:181
static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key)
Definition: ri_triggers.c:2894
struct RI_CompareKey RI_CompareKey
Datum RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:1177
#define RI_PLAN_NO_ACTION
Definition: ri_triggers.c:75
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2127
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13440
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:271
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:353
#define SnapshotSelf
Definition: snapmgr.h:32
#define InvalidSnapshot
Definition: snapshot.h:119
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1948
uint64 SPI_processed
Definition: spi.c:44
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:1025
const char * SPI_result_code_string(int code)
Definition: spi.c:1972
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_connect(void)
Definition: spi.c:94
int SPI_execute_snapshot(SPIPlanPtr plan, Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition: spi.c:773
int SPI_result
Definition: spi.c:46
int SPI_finish(void)
Definition: spi.c:182
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:860
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:976
#define SPI_OK_UPDATE
Definition: spi.h:90
#define SPI_OK_DELETE
Definition: spi.h:89
#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 appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:281
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
int16 attlen
Definition: tupdesc.h:71
Definition: fmgr.h:57
Oid fn_oid
Definition: fmgr.h:59
Definition: dynahash.c:222
Definition: pg_list.h:54
RI_CompareKey key
Definition: ri_triggers.c:171
FmgrInfo cast_func_finfo
Definition: ri_triggers.c:174
dlist_node valid_link
Definition: ri_triggers.c:132
int16 pk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:124
Oid agged_period_contained_by_oper
Definition: ri_triggers.c:130
int16 fk_attnums[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:125
Oid pp_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:127
Oid pf_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:126
Oid period_contained_by_oper
Definition: ri_triggers.c:129
int16 confdelsetcols[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:119
Oid ff_eq_oprs[RI_MAX_NUMKEYS]
Definition: ri_triggers.c:128
SPIPlanPtr plan
Definition: ri_triggers.c:152
RI_QueryKey key
Definition: ri_triggers.c:151
int32 constr_queryno
Definition: ri_triggers.c:143
Bitmapset * selectedCols
Definition: parsenodes.h:1322
AclMode requiredPerms
Definition: parsenodes.h:1320
RTEKind rtekind
Definition: parsenodes.h:1076
TupleDesc rd_att
Definition: rel.h:112
Oid rd_id
Definition: rel.h:113
Form_pg_class rd_rel
Definition: rel.h:111
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
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
Oid tgconstraint
Definition: reltrigger.h:35
Oid tgconstrrelid
Definition: reltrigger.h:33
char * tgname
Definition: reltrigger.h:27
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
dlist_node * cur
Definition: ilist.h:200
Definition: c.h:747
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:118
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static bool table_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot, Snapshot snapshot)
Definition: tableam.h:1300
#define RI_TRIGGER_FK
Definition: trigger.h:285
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:113
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:26
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:122
#define RI_TRIGGER_NONE
Definition: trigger.h:286
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:131
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:110
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:116
#define RI_TRIGGER_PK
Definition: trigger.h:284
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:399
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition: tuptable.h:449
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:385
const char * name
void CommandCounterIncrement(void)
Definition: xact.c:1100
#define IsolationUsesXactSnapshot()
Definition: xact.h:52