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