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