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 
1264  /*
1265  * AfterTriggerSaveEvent() handles things such that this function is never
1266  * called for partitioned tables.
1267  */
1268  Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1269 
1270  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1271 
1272  ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1273 
1274  /*
1275  * If all new key values are NULL, the row satisfies the constraint, so no
1276  * check is needed.
1277  */
1278  if (ri_nullcheck == RI_KEYS_ALL_NULL)
1279  return false;
1280 
1281  /*
1282  * If some new key values are NULL, the behavior depends on the match
1283  * type.
1284  */
1285  else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1286  {
1287  switch (riinfo->confmatchtype)
1288  {
1289  case FKCONSTR_MATCH_SIMPLE:
1290 
1291  /*
1292  * If any new key value is NULL, the row must satisfy the
1293  * constraint, so no check is needed.
1294  */
1295  return false;
1296 
1298 
1299  /*
1300  * Don't know, must run full check.
1301  */
1302  break;
1303 
1304  case FKCONSTR_MATCH_FULL:
1305 
1306  /*
1307  * If some new key values are NULL, the row fails the
1308  * constraint. We must not throw error here, because the row
1309  * might get invalidated before the constraint is to be
1310  * checked, but we should queue the event to apply the check
1311  * later.
1312  */
1313  return true;
1314  }
1315  }
1316 
1317  /*
1318  * Continues here for no new key values are NULL, or we couldn't decide
1319  * yet.
1320  */
1321 
1322  /*
1323  * If the original row was inserted by our own transaction, we must fire
1324  * the trigger whether or not the keys are equal. This is because our
1325  * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1326  * not do anything; so we had better do the UPDATE check. (We could skip
1327  * this if we knew the INSERT trigger already fired, but there is no easy
1328  * way to know that.)
1329  */
1330  if (slot_is_current_xact_tuple(oldslot))
1331  return true;
1332 
1333  /* If all old and new key values are equal, no check is needed */
1334  if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1335  return false;
1336 
1337  /* Else we need to fire the trigger. */
1338  return true;
1339 }
1340 
1341 /*
1342  * RI_Initial_Check -
1343  *
1344  * Check an entire table for non-matching values using a single query.
1345  * This is not a trigger procedure, but is called during ALTER TABLE
1346  * ADD FOREIGN KEY to validate the initial table contents.
1347  *
1348  * We expect that the caller has made provision to prevent any problems
1349  * caused by concurrent actions. This could be either by locking rel and
1350  * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
1351  * that triggers implementing the checks are already active.
1352  * Hence, we do not need to lock individual rows for the check.
1353  *
1354  * If the check fails because the current user doesn't have permissions
1355  * to read both tables, return false to let our caller know that they will
1356  * need to do something else to check the constraint.
1357  */
1358 bool
1359 RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
1360 {
1361  const RI_ConstraintInfo *riinfo;
1362  StringInfoData querybuf;
1363  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1364  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1365  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1366  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1367  RangeTblEntry *rte;
1368  RTEPermissionInfo *pk_perminfo;
1369  RTEPermissionInfo *fk_perminfo;
1370  List *rtes = NIL;
1371  List *perminfos = NIL;
1372  const char *sep;
1373  const char *fk_only;
1374  const char *pk_only;
1375  int save_nestlevel;
1376  char workmembuf[32];
1377  int spi_result;
1378  SPIPlanPtr qplan;
1379 
1380  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1381 
1382  /*
1383  * Check to make sure current user has enough permissions to do the test
1384  * query. (If not, caller can fall back to the trigger method, which
1385  * works because it changes user IDs on the fly.)
1386  *
1387  * XXX are there any other show-stopper conditions to check?
1388  */
1389  pk_perminfo = makeNode(RTEPermissionInfo);
1390  pk_perminfo->relid = RelationGetRelid(pk_rel);
1391  pk_perminfo->requiredPerms = ACL_SELECT;
1392  perminfos = lappend(perminfos, pk_perminfo);
1393  rte = makeNode(RangeTblEntry);
1394  rte->rtekind = RTE_RELATION;
1395  rte->relid = RelationGetRelid(pk_rel);
1396  rte->relkind = pk_rel->rd_rel->relkind;
1397  rte->rellockmode = AccessShareLock;
1398  rte->perminfoindex = list_length(perminfos);
1399  rtes = lappend(rtes, rte);
1400 
1401  fk_perminfo = makeNode(RTEPermissionInfo);
1402  fk_perminfo->relid = RelationGetRelid(fk_rel);
1403  fk_perminfo->requiredPerms = ACL_SELECT;
1404  perminfos = lappend(perminfos, fk_perminfo);
1405  rte = makeNode(RangeTblEntry);
1406  rte->rtekind = RTE_RELATION;
1407  rte->relid = RelationGetRelid(fk_rel);
1408  rte->relkind = fk_rel->rd_rel->relkind;
1409  rte->rellockmode = AccessShareLock;
1410  rte->perminfoindex = list_length(perminfos);
1411  rtes = lappend(rtes, rte);
1412 
1413  for (int i = 0; i < riinfo->nkeys; i++)
1414  {
1415  int attno;
1416 
1417  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1418  pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1419 
1420  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1421  fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1422  }
1423 
1424  if (!ExecCheckPermissions(rtes, perminfos, false))
1425  return false;
1426 
1427  /*
1428  * Also punt if RLS is enabled on either table unless this role has the
1429  * bypassrls right or is the table owner of the table(s) involved which
1430  * have RLS enabled.
1431  */
1433  ((pk_rel->rd_rel->relrowsecurity &&
1434  !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1435  GetUserId())) ||
1436  (fk_rel->rd_rel->relrowsecurity &&
1437  !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1438  GetUserId()))))
1439  return false;
1440 
1441  /*----------
1442  * The query string built is:
1443  * SELECT fk.keycols FROM [ONLY] relname fk
1444  * LEFT OUTER JOIN [ONLY] pkrelname pk
1445  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1446  * WHERE pk.pkkeycol1 IS NULL AND
1447  * For MATCH SIMPLE:
1448  * (fk.keycol1 IS NOT NULL [AND ...])
1449  * For MATCH FULL:
1450  * (fk.keycol1 IS NOT NULL [OR ...])
1451  *
1452  * We attach COLLATE clauses to the operators when comparing columns
1453  * that have different collations.
1454  *----------
1455  */
1456  initStringInfo(&querybuf);
1457  appendStringInfoString(&querybuf, "SELECT ");
1458  sep = "";
1459  for (int i = 0; i < riinfo->nkeys; i++)
1460  {
1461  quoteOneName(fkattname,
1462  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1463  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1464  sep = ", ";
1465  }
1466 
1467  quoteRelationName(pkrelname, pk_rel);
1468  quoteRelationName(fkrelname, fk_rel);
1469  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1470  "" : "ONLY ";
1471  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1472  "" : "ONLY ";
1473  appendStringInfo(&querybuf,
1474  " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1475  fk_only, fkrelname, pk_only, pkrelname);
1476 
1477  strcpy(pkattname, "pk.");
1478  strcpy(fkattname, "fk.");
1479  sep = "(";
1480  for (int i = 0; i < riinfo->nkeys; i++)
1481  {
1482  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1483  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1484  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1485  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1486 
1487  quoteOneName(pkattname + 3,
1488  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1489  quoteOneName(fkattname + 3,
1490  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1491  ri_GenerateQual(&querybuf, sep,
1492  pkattname, pk_type,
1493  riinfo->pf_eq_oprs[i],
1494  fkattname, fk_type);
1495  if (pk_coll != fk_coll)
1496  ri_GenerateQualCollation(&querybuf, pk_coll);
1497  sep = "AND";
1498  }
1499 
1500  /*
1501  * It's sufficient to test any one pk attribute for null to detect a join
1502  * failure.
1503  */
1504  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1505  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1506 
1507  sep = "";
1508  for (int i = 0; i < riinfo->nkeys; i++)
1509  {
1510  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1511  appendStringInfo(&querybuf,
1512  "%sfk.%s IS NOT NULL",
1513  sep, fkattname);
1514  switch (riinfo->confmatchtype)
1515  {
1516  case FKCONSTR_MATCH_SIMPLE:
1517  sep = " AND ";
1518  break;
1519  case FKCONSTR_MATCH_FULL:
1520  sep = " OR ";
1521  break;
1522  }
1523  }
1524  appendStringInfoChar(&querybuf, ')');
1525 
1526  /*
1527  * Temporarily increase work_mem so that the check query can be executed
1528  * more efficiently. It seems okay to do this because the query is simple
1529  * enough to not use a multiple of work_mem, and one typically would not
1530  * have many large foreign-key validations happening concurrently. So
1531  * this seems to meet the criteria for being considered a "maintenance"
1532  * operation, and accordingly we use maintenance_work_mem. However, we
1533  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1534  * let that get applied to the maintenance_work_mem value.
1535  *
1536  * We use the equivalent of a function SET option to allow the setting to
1537  * persist for exactly the duration of the check query. guc.c also takes
1538  * care of undoing the setting on error.
1539  */
1540  save_nestlevel = NewGUCNestLevel();
1541 
1542  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1543  (void) set_config_option("work_mem", workmembuf,
1545  GUC_ACTION_SAVE, true, 0, false);
1546  (void) set_config_option("hash_mem_multiplier", "1",
1548  GUC_ACTION_SAVE, true, 0, false);
1549 
1550  if (SPI_connect() != SPI_OK_CONNECT)
1551  elog(ERROR, "SPI_connect failed");
1552 
1553  /*
1554  * Generate the plan. We don't need to cache it, and there are no
1555  * arguments to the plan.
1556  */
1557  qplan = SPI_prepare(querybuf.data, 0, NULL);
1558 
1559  if (qplan == NULL)
1560  elog(ERROR, "SPI_prepare returned %s for %s",
1562 
1563  /*
1564  * Run the plan. For safety we force a current snapshot to be used. (In
1565  * transaction-snapshot mode, this arguably violates transaction isolation
1566  * rules, but we really haven't got much choice.) We don't need to
1567  * register the snapshot, because SPI_execute_snapshot will see to it. We
1568  * need at most one tuple returned, so pass limit = 1.
1569  */
1570  spi_result = SPI_execute_snapshot(qplan,
1571  NULL, NULL,
1574  true, false, 1);
1575 
1576  /* Check result */
1577  if (spi_result != SPI_OK_SELECT)
1578  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1579 
1580  /* Did we find a tuple violating the constraint? */
1581  if (SPI_processed > 0)
1582  {
1583  TupleTableSlot *slot;
1584  HeapTuple tuple = SPI_tuptable->vals[0];
1585  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1586  RI_ConstraintInfo fake_riinfo;
1587 
1588  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1589 
1590  heap_deform_tuple(tuple, tupdesc,
1591  slot->tts_values, slot->tts_isnull);
1592  ExecStoreVirtualTuple(slot);
1593 
1594  /*
1595  * The columns to look at in the result tuple are 1..N, not whatever
1596  * they are in the fk_rel. Hack up riinfo so that the subroutines
1597  * called here will behave properly.
1598  *
1599  * In addition to this, we have to pass the correct tupdesc to
1600  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1601  * or fk_rel's tupdesc.
1602  */
1603  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1604  for (int i = 0; i < fake_riinfo.nkeys; i++)
1605  fake_riinfo.fk_attnums[i] = i + 1;
1606 
1607  /*
1608  * If it's MATCH FULL, and there are any nulls in the FK keys,
1609  * complain about that rather than the lack of a match. MATCH FULL
1610  * disallows partially-null FK rows.
1611  */
1612  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1613  ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1614  ereport(ERROR,
1615  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1616  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1617  RelationGetRelationName(fk_rel),
1618  NameStr(fake_riinfo.conname)),
1619  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1620  errtableconstraint(fk_rel,
1621  NameStr(fake_riinfo.conname))));
1622 
1623  /*
1624  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1625  * query, which isn't true, but will cause it to use
1626  * fake_riinfo.fk_attnums as we need.
1627  */
1628  ri_ReportViolation(&fake_riinfo,
1629  pk_rel, fk_rel,
1630  slot, tupdesc,
1631  RI_PLAN_CHECK_LOOKUPPK, false);
1632 
1634  }
1635 
1636  if (SPI_finish() != SPI_OK_FINISH)
1637  elog(ERROR, "SPI_finish failed");
1638 
1639  /*
1640  * Restore work_mem and hash_mem_multiplier.
1641  */
1642  AtEOXact_GUC(true, save_nestlevel);
1643 
1644  return true;
1645 }
1646 
1647 /*
1648  * RI_PartitionRemove_Check -
1649  *
1650  * Verify no referencing values exist, when a partition is detached on
1651  * the referenced side of a foreign key constraint.
1652  */
1653 void
1655 {
1656  const RI_ConstraintInfo *riinfo;
1657  StringInfoData querybuf;
1658  char *constraintDef;
1659  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1660  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1661  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1662  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1663  const char *sep;
1664  const char *fk_only;
1665  int save_nestlevel;
1666  char workmembuf[32];
1667  int spi_result;
1668  SPIPlanPtr qplan;
1669  int i;
1670 
1671  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1672 
1673  /*
1674  * We don't check permissions before displaying the error message, on the
1675  * assumption that the user detaching the partition must have enough
1676  * privileges to examine the table contents anyhow.
1677  */
1678 
1679  /*----------
1680  * The query string built is:
1681  * SELECT fk.keycols FROM [ONLY] relname fk
1682  * JOIN pkrelname pk
1683  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1684  * WHERE (<partition constraint>) AND
1685  * For MATCH SIMPLE:
1686  * (fk.keycol1 IS NOT NULL [AND ...])
1687  * For MATCH FULL:
1688  * (fk.keycol1 IS NOT NULL [OR ...])
1689  *
1690  * We attach COLLATE clauses to the operators when comparing columns
1691  * that have different collations.
1692  *----------
1693  */
1694  initStringInfo(&querybuf);
1695  appendStringInfoString(&querybuf, "SELECT ");
1696  sep = "";
1697  for (i = 0; i < riinfo->nkeys; i++)
1698  {
1699  quoteOneName(fkattname,
1700  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1701  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1702  sep = ", ";
1703  }
1704 
1705  quoteRelationName(pkrelname, pk_rel);
1706  quoteRelationName(fkrelname, fk_rel);
1707  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1708  "" : "ONLY ";
1709  appendStringInfo(&querybuf,
1710  " FROM %s%s fk JOIN %s pk ON",
1711  fk_only, fkrelname, pkrelname);
1712  strcpy(pkattname, "pk.");
1713  strcpy(fkattname, "fk.");
1714  sep = "(";
1715  for (i = 0; i < riinfo->nkeys; i++)
1716  {
1717  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1718  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1719  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1720  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1721 
1722  quoteOneName(pkattname + 3,
1723  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1724  quoteOneName(fkattname + 3,
1725  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1726  ri_GenerateQual(&querybuf, sep,
1727  pkattname, pk_type,
1728  riinfo->pf_eq_oprs[i],
1729  fkattname, fk_type);
1730  if (pk_coll != fk_coll)
1731  ri_GenerateQualCollation(&querybuf, pk_coll);
1732  sep = "AND";
1733  }
1734 
1735  /*
1736  * Start the WHERE clause with the partition constraint (except if this is
1737  * the default partition and there's no other partition, because the
1738  * partition constraint is the empty string in that case.)
1739  */
1740  constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1741  if (constraintDef && constraintDef[0] != '\0')
1742  appendStringInfo(&querybuf, ") WHERE %s AND (",
1743  constraintDef);
1744  else
1745  appendStringInfoString(&querybuf, ") WHERE (");
1746 
1747  sep = "";
1748  for (i = 0; i < riinfo->nkeys; i++)
1749  {
1750  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1751  appendStringInfo(&querybuf,
1752  "%sfk.%s IS NOT NULL",
1753  sep, fkattname);
1754  switch (riinfo->confmatchtype)
1755  {
1756  case FKCONSTR_MATCH_SIMPLE:
1757  sep = " AND ";
1758  break;
1759  case FKCONSTR_MATCH_FULL:
1760  sep = " OR ";
1761  break;
1762  }
1763  }
1764  appendStringInfoChar(&querybuf, ')');
1765 
1766  /*
1767  * Temporarily increase work_mem so that the check query can be executed
1768  * more efficiently. It seems okay to do this because the query is simple
1769  * enough to not use a multiple of work_mem, and one typically would not
1770  * have many large foreign-key validations happening concurrently. So
1771  * this seems to meet the criteria for being considered a "maintenance"
1772  * operation, and accordingly we use maintenance_work_mem. However, we
1773  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1774  * let that get applied to the maintenance_work_mem value.
1775  *
1776  * We use the equivalent of a function SET option to allow the setting to
1777  * persist for exactly the duration of the check query. guc.c also takes
1778  * care of undoing the setting on error.
1779  */
1780  save_nestlevel = NewGUCNestLevel();
1781 
1782  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1783  (void) set_config_option("work_mem", workmembuf,
1785  GUC_ACTION_SAVE, true, 0, false);
1786  (void) set_config_option("hash_mem_multiplier", "1",
1788  GUC_ACTION_SAVE, true, 0, false);
1789 
1790  if (SPI_connect() != SPI_OK_CONNECT)
1791  elog(ERROR, "SPI_connect failed");
1792 
1793  /*
1794  * Generate the plan. We don't need to cache it, and there are no
1795  * arguments to the plan.
1796  */
1797  qplan = SPI_prepare(querybuf.data, 0, NULL);
1798 
1799  if (qplan == NULL)
1800  elog(ERROR, "SPI_prepare returned %s for %s",
1802 
1803  /*
1804  * Run the plan. For safety we force a current snapshot to be used. (In
1805  * transaction-snapshot mode, this arguably violates transaction isolation
1806  * rules, but we really haven't got much choice.) We don't need to
1807  * register the snapshot, because SPI_execute_snapshot will see to it. We
1808  * need at most one tuple returned, so pass limit = 1.
1809  */
1810  spi_result = SPI_execute_snapshot(qplan,
1811  NULL, NULL,
1814  true, false, 1);
1815 
1816  /* Check result */
1817  if (spi_result != SPI_OK_SELECT)
1818  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1819 
1820  /* Did we find a tuple that would violate the constraint? */
1821  if (SPI_processed > 0)
1822  {
1823  TupleTableSlot *slot;
1824  HeapTuple tuple = SPI_tuptable->vals[0];
1825  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1826  RI_ConstraintInfo fake_riinfo;
1827 
1828  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1829 
1830  heap_deform_tuple(tuple, tupdesc,
1831  slot->tts_values, slot->tts_isnull);
1832  ExecStoreVirtualTuple(slot);
1833 
1834  /*
1835  * The columns to look at in the result tuple are 1..N, not whatever
1836  * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1837  * will behave properly.
1838  *
1839  * In addition to this, we have to pass the correct tupdesc to
1840  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1841  * or fk_rel's tupdesc.
1842  */
1843  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1844  for (i = 0; i < fake_riinfo.nkeys; i++)
1845  fake_riinfo.pk_attnums[i] = i + 1;
1846 
1847  ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
1848  slot, tupdesc, 0, true);
1849  }
1850 
1851  if (SPI_finish() != SPI_OK_FINISH)
1852  elog(ERROR, "SPI_finish failed");
1853 
1854  /*
1855  * Restore work_mem and hash_mem_multiplier.
1856  */
1857  AtEOXact_GUC(true, save_nestlevel);
1858 }
1859 
1860 
1861 /* ----------
1862  * Local functions below
1863  * ----------
1864  */
1865 
1866 
1867 /*
1868  * quoteOneName --- safely quote a single SQL name
1869  *
1870  * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
1871  */
1872 static void
1873 quoteOneName(char *buffer, const char *name)
1874 {
1875  /* Rather than trying to be smart, just always quote it. */
1876  *buffer++ = '"';
1877  while (*name)
1878  {
1879  if (*name == '"')
1880  *buffer++ = '"';
1881  *buffer++ = *name++;
1882  }
1883  *buffer++ = '"';
1884  *buffer = '\0';
1885 }
1886 
1887 /*
1888  * quoteRelationName --- safely quote a fully qualified relation name
1889  *
1890  * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
1891  */
1892 static void
1893 quoteRelationName(char *buffer, Relation rel)
1894 {
1896  buffer += strlen(buffer);
1897  *buffer++ = '.';
1898  quoteOneName(buffer, RelationGetRelationName(rel));
1899 }
1900 
1901 /*
1902  * ri_GenerateQual --- generate a WHERE clause equating two variables
1903  *
1904  * This basically appends " sep leftop op rightop" to buf, adding casts
1905  * and schema qualification as needed to ensure that the parser will select
1906  * the operator we specify. leftop and rightop should be parenthesized
1907  * if they aren't variables or parameters.
1908  */
1909 static void
1911  const char *sep,
1912  const char *leftop, Oid leftoptype,
1913  Oid opoid,
1914  const char *rightop, Oid rightoptype)
1915 {
1916  appendStringInfo(buf, " %s ", sep);
1917  generate_operator_clause(buf, leftop, leftoptype, opoid,
1918  rightop, rightoptype);
1919 }
1920 
1921 /*
1922  * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
1923  *
1924  * At present, we intentionally do not use this function for RI queries that
1925  * compare a variable to a $n parameter. Since parameter symbols always have
1926  * default collation, the effect will be to use the variable's collation.
1927  * Now that is only strictly correct when testing the referenced column, since
1928  * the SQL standard specifies that RI comparisons should use the referenced
1929  * column's collation. However, so long as all collations have the same
1930  * notion of equality (which they do, because texteq reduces to bitwise
1931  * equality), there's no visible semantic impact from using the referencing
1932  * column's collation when testing it, and this is a good thing to do because
1933  * it lets us use a normal index on the referencing column. However, we do
1934  * have to use this function when directly comparing the referencing and
1935  * referenced columns, if they are of different collations; else the parser
1936  * will fail to resolve the collation to use.
1937  */
1938 static void
1940 {
1941  HeapTuple tp;
1942  Form_pg_collation colltup;
1943  char *collname;
1944  char onename[MAX_QUOTED_NAME_LEN];
1945 
1946  /* Nothing to do if it's a noncollatable data type */
1947  if (!OidIsValid(collation))
1948  return;
1949 
1950  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1951  if (!HeapTupleIsValid(tp))
1952  elog(ERROR, "cache lookup failed for collation %u", collation);
1953  colltup = (Form_pg_collation) GETSTRUCT(tp);
1954  collname = NameStr(colltup->collname);
1955 
1956  /*
1957  * We qualify the name always, for simplicity and to ensure the query is
1958  * not search-path-dependent.
1959  */
1960  quoteOneName(onename, get_namespace_name(colltup->collnamespace));
1961  appendStringInfo(buf, " COLLATE %s", onename);
1962  quoteOneName(onename, collname);
1963  appendStringInfo(buf, ".%s", onename);
1964 
1965  ReleaseSysCache(tp);
1966 }
1967 
1968 /* ----------
1969  * ri_BuildQueryKey -
1970  *
1971  * Construct a hashtable key for a prepared SPI plan of an FK constraint.
1972  *
1973  * key: output argument, *key is filled in based on the other arguments
1974  * riinfo: info derived from pg_constraint entry
1975  * constr_queryno: an internal number identifying the query type
1976  * (see RI_PLAN_XXX constants at head of file)
1977  * ----------
1978  */
1979 static void
1981  int32 constr_queryno)
1982 {
1983  /*
1984  * Inherited constraints with a common ancestor can share ri_query_cache
1985  * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
1986  * Except in that case, the query processes the other table involved in
1987  * the FK constraint (i.e., not the table on which the trigger has been
1988  * fired), and so it will be the same for all members of the inheritance
1989  * tree. So we may use the root constraint's OID in the hash key, rather
1990  * than the constraint's own OID. This avoids creating duplicate SPI
1991  * plans, saving lots of work and memory when there are many partitions
1992  * with similar FK constraints.
1993  *
1994  * (Note that we must still have a separate RI_ConstraintInfo for each
1995  * constraint, because partitions can have different column orders,
1996  * resulting in different pk_attnums[] or fk_attnums[] array contents.)
1997  *
1998  * We assume struct RI_QueryKey contains no padding bytes, else we'd need
1999  * to use memset to clear them.
2000  */
2001  if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2002  key->constr_id = riinfo->constraint_root_id;
2003  else
2004  key->constr_id = riinfo->constraint_id;
2005  key->constr_queryno = constr_queryno;
2006 }
2007 
2008 /*
2009  * Check that RI trigger function was called in expected context
2010  */
2011 static void
2012 ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
2013 {
2014  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2015 
2016  if (!CALLED_AS_TRIGGER(fcinfo))
2017  ereport(ERROR,
2018  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2019  errmsg("function \"%s\" was not called by trigger manager", funcname)));
2020 
2021  /*
2022  * Check proper event
2023  */
2024  if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2025  !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2026  ereport(ERROR,
2027  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2028  errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2029 
2030  switch (tgkind)
2031  {
2032  case RI_TRIGTYPE_INSERT:
2033  if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2034  ereport(ERROR,
2035  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2036  errmsg("function \"%s\" must be fired for INSERT", funcname)));
2037  break;
2038  case RI_TRIGTYPE_UPDATE:
2039  if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2040  ereport(ERROR,
2041  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2042  errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2043  break;
2044  case RI_TRIGTYPE_DELETE:
2045  if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2046  ereport(ERROR,
2047  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2048  errmsg("function \"%s\" must be fired for DELETE", funcname)));
2049  break;
2050  }
2051 }
2052 
2053 
2054 /*
2055  * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
2056  */
2057 static const RI_ConstraintInfo *
2058 ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
2059 {
2060  Oid constraintOid = trigger->tgconstraint;
2061  const RI_ConstraintInfo *riinfo;
2062 
2063  /*
2064  * Check that the FK constraint's OID is available; it might not be if
2065  * we've been invoked via an ordinary trigger or an old-style "constraint
2066  * trigger".
2067  */
2068  if (!OidIsValid(constraintOid))
2069  ereport(ERROR,
2070  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2071  errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2072  trigger->tgname, RelationGetRelationName(trig_rel)),
2073  errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2074 
2075  /* Find or create a hashtable entry for the constraint */
2076  riinfo = ri_LoadConstraintInfo(constraintOid);
2077 
2078  /* Do some easy cross-checks against the trigger call data */
2079  if (rel_is_pk)
2080  {
2081  if (riinfo->fk_relid != trigger->tgconstrrelid ||
2082  riinfo->pk_relid != RelationGetRelid(trig_rel))
2083  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2084  trigger->tgname, RelationGetRelationName(trig_rel));
2085  }
2086  else
2087  {
2088  if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2089  riinfo->pk_relid != trigger->tgconstrrelid)
2090  elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2091  trigger->tgname, RelationGetRelationName(trig_rel));
2092  }
2093 
2094  if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2097  elog(ERROR, "unrecognized confmatchtype: %d",
2098  riinfo->confmatchtype);
2099 
2100  if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2101  ereport(ERROR,
2102  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2103  errmsg("MATCH PARTIAL not yet implemented")));
2104 
2105  return riinfo;
2106 }
2107 
2108 /*
2109  * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
2110  */
2111 static const RI_ConstraintInfo *
2113 {
2114  RI_ConstraintInfo *riinfo;
2115  bool found;
2116  HeapTuple tup;
2117  Form_pg_constraint conForm;
2118 
2119  /*
2120  * On the first call initialize the hashtable
2121  */
2122  if (!ri_constraint_cache)
2124 
2125  /*
2126  * Find or create a hash entry. If we find a valid one, just return it.
2127  */
2129  &constraintOid,
2130  HASH_ENTER, &found);
2131  if (!found)
2132  riinfo->valid = false;
2133  else if (riinfo->valid)
2134  return riinfo;
2135 
2136  /*
2137  * Fetch the pg_constraint row so we can fill in the entry.
2138  */
2139  tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2140  if (!HeapTupleIsValid(tup)) /* should not happen */
2141  elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2142  conForm = (Form_pg_constraint) GETSTRUCT(tup);
2143 
2144  if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2145  elog(ERROR, "constraint %u is not a foreign key constraint",
2146  constraintOid);
2147 
2148  /* And extract data */
2149  Assert(riinfo->constraint_id == constraintOid);
2150  if (OidIsValid(conForm->conparentid))
2151  riinfo->constraint_root_id =
2152  get_ri_constraint_root(conForm->conparentid);
2153  else
2154  riinfo->constraint_root_id = constraintOid;
2155  riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2156  ObjectIdGetDatum(constraintOid));
2157  riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2159  memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2160  riinfo->pk_relid = conForm->confrelid;
2161  riinfo->fk_relid = conForm->conrelid;
2162  riinfo->confupdtype = conForm->confupdtype;
2163  riinfo->confdeltype = conForm->confdeltype;
2164  riinfo->confmatchtype = conForm->confmatchtype;
2165 
2167  &riinfo->nkeys,
2168  riinfo->fk_attnums,
2169  riinfo->pk_attnums,
2170  riinfo->pf_eq_oprs,
2171  riinfo->pp_eq_oprs,
2172  riinfo->ff_eq_oprs,
2173  &riinfo->ndelsetcols,
2174  riinfo->confdelsetcols);
2175 
2176  ReleaseSysCache(tup);
2177 
2178  /*
2179  * For efficient processing of invalidation messages below, we keep a
2180  * doubly-linked count list of all currently valid entries.
2181  */
2183 
2184  riinfo->valid = true;
2185 
2186  return riinfo;
2187 }
2188 
2189 /*
2190  * get_ri_constraint_root
2191  * Returns the OID of the constraint's root parent
2192  */
2193 static Oid
2195 {
2196  for (;;)
2197  {
2198  HeapTuple tuple;
2199  Oid constrParentOid;
2200 
2201  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2202  if (!HeapTupleIsValid(tuple))
2203  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2204  constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2205  ReleaseSysCache(tuple);
2206  if (!OidIsValid(constrParentOid))
2207  break; /* we reached the root constraint */
2208  constrOid = constrParentOid;
2209  }
2210  return constrOid;
2211 }
2212 
2213 /*
2214  * Callback for pg_constraint inval events
2215  *
2216  * While most syscache callbacks just flush all their entries, pg_constraint
2217  * gets enough update traffic that it's probably worth being smarter.
2218  * Invalidate any ri_constraint_cache entry associated with the syscache
2219  * entry with the specified hash value, or all entries if hashvalue == 0.
2220  *
2221  * Note: at the time a cache invalidation message is processed there may be
2222  * active references to the cache. Because of this we never remove entries
2223  * from the cache, but only mark them invalid, which is harmless to active
2224  * uses. (Any query using an entry should hold a lock sufficient to keep that
2225  * data from changing under it --- but we may get cache flushes anyway.)
2226  */
2227 static void
2229 {
2230  dlist_mutable_iter iter;
2231 
2232  Assert(ri_constraint_cache != NULL);
2233 
2234  /*
2235  * If the list of currently valid entries gets excessively large, we mark
2236  * them all invalid so we can empty the list. This arrangement avoids
2237  * O(N^2) behavior in situations where a session touches many foreign keys
2238  * and also does many ALTER TABLEs, such as a restore from pg_dump.
2239  */
2241  hashvalue = 0; /* pretend it's a cache reset */
2242 
2244  {
2246  valid_link, iter.cur);
2247 
2248  /*
2249  * We must invalidate not only entries directly matching the given
2250  * hash value, but also child entries, in case the invalidation
2251  * affects a root constraint.
2252  */
2253  if (hashvalue == 0 ||
2254  riinfo->oidHashValue == hashvalue ||
2255  riinfo->rootHashValue == hashvalue)
2256  {
2257  riinfo->valid = false;
2258  /* Remove invalidated entries from the list, too */
2260  }
2261  }
2262 }
2263 
2264 
2265 /*
2266  * Prepare execution plan for a query to enforce an RI restriction
2267  */
2268 static SPIPlanPtr
2269 ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes,
2270  RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
2271 {
2272  SPIPlanPtr qplan;
2273  Relation query_rel;
2274  Oid save_userid;
2275  int save_sec_context;
2276 
2277  /*
2278  * Use the query type code to determine whether the query is run against
2279  * the PK or FK table; we'll do the check as that table's owner
2280  */
2281  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2282  query_rel = pk_rel;
2283  else
2284  query_rel = fk_rel;
2285 
2286  /* Switch to proper UID to perform check as */
2287  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2288  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2289  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2291 
2292  /* Create the plan */
2293  qplan = SPI_prepare(querystr, nargs, argtypes);
2294 
2295  if (qplan == NULL)
2296  elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2297 
2298  /* Restore UID and security context */
2299  SetUserIdAndSecContext(save_userid, save_sec_context);
2300 
2301  /* Save the plan */
2302  SPI_keepplan(qplan);
2303  ri_HashPreparedPlan(qkey, qplan);
2304 
2305  return qplan;
2306 }
2307 
2308 /*
2309  * Perform a query to enforce an RI restriction
2310  */
2311 static bool
2313  RI_QueryKey *qkey, SPIPlanPtr qplan,
2314  Relation fk_rel, Relation pk_rel,
2315  TupleTableSlot *oldslot, TupleTableSlot *newslot,
2316  bool detectNewRows, int expect_OK)
2317 {
2318  Relation query_rel,
2319  source_rel;
2320  bool source_is_pk;
2321  Snapshot test_snapshot;
2322  Snapshot crosscheck_snapshot;
2323  int limit;
2324  int spi_result;
2325  Oid save_userid;
2326  int save_sec_context;
2327  Datum vals[RI_MAX_NUMKEYS * 2];
2328  char nulls[RI_MAX_NUMKEYS * 2];
2329 
2330  /*
2331  * Use the query type code to determine whether the query is run against
2332  * the PK or FK table; we'll do the check as that table's owner
2333  */
2334  if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2335  query_rel = pk_rel;
2336  else
2337  query_rel = fk_rel;
2338 
2339  /*
2340  * The values for the query are taken from the table on which the trigger
2341  * is called - it is normally the other one with respect to query_rel. An
2342  * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2343  * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2344  * need some less klugy way to determine this.
2345  */
2347  {
2348  source_rel = fk_rel;
2349  source_is_pk = false;
2350  }
2351  else
2352  {
2353  source_rel = pk_rel;
2354  source_is_pk = true;
2355  }
2356 
2357  /* Extract the parameters to be passed into the query */
2358  if (newslot)
2359  {
2360  ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2361  vals, nulls);
2362  if (oldslot)
2363  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2364  vals + riinfo->nkeys, nulls + riinfo->nkeys);
2365  }
2366  else
2367  {
2368  ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2369  vals, nulls);
2370  }
2371 
2372  /*
2373  * In READ COMMITTED mode, we just need to use an up-to-date regular
2374  * snapshot, and we will see all rows that could be interesting. But in
2375  * transaction-snapshot mode, we can't change the transaction snapshot. If
2376  * the caller passes detectNewRows == false then it's okay to do the query
2377  * with the transaction snapshot; otherwise we use a current snapshot, and
2378  * tell the executor to error out if it finds any rows under the current
2379  * snapshot that wouldn't be visible per the transaction snapshot. Note
2380  * that SPI_execute_snapshot will register the snapshots, so we don't need
2381  * to bother here.
2382  */
2383  if (IsolationUsesXactSnapshot() && detectNewRows)
2384  {
2385  CommandCounterIncrement(); /* be sure all my own work is visible */
2386  test_snapshot = GetLatestSnapshot();
2387  crosscheck_snapshot = GetTransactionSnapshot();
2388  }
2389  else
2390  {
2391  /* the default SPI behavior is okay */
2392  test_snapshot = InvalidSnapshot;
2393  crosscheck_snapshot = InvalidSnapshot;
2394  }
2395 
2396  /*
2397  * If this is a select query (e.g., for a 'no action' or 'restrict'
2398  * trigger), we only need to see if there is a single row in the table,
2399  * matching the key. Otherwise, limit = 0 - because we want the query to
2400  * affect ALL the matching rows.
2401  */
2402  limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2403 
2404  /* Switch to proper UID to perform check as */
2405  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2406  SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2407  save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2409 
2410  /* Finally we can run the query. */
2411  spi_result = SPI_execute_snapshot(qplan,
2412  vals, nulls,
2413  test_snapshot, crosscheck_snapshot,
2414  false, false, limit);
2415 
2416  /* Restore UID and security context */
2417  SetUserIdAndSecContext(save_userid, save_sec_context);
2418 
2419  /* Check result */
2420  if (spi_result < 0)
2421  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2422 
2423  if (expect_OK >= 0 && spi_result != expect_OK)
2424  ereport(ERROR,
2425  (errcode(ERRCODE_INTERNAL_ERROR),
2426  errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2427  RelationGetRelationName(pk_rel),
2428  NameStr(riinfo->conname),
2429  RelationGetRelationName(fk_rel)),
2430  errhint("This is most likely due to a rule having rewritten the query.")));
2431 
2432  /* XXX wouldn't it be clearer to do this part at the caller? */
2434  expect_OK == SPI_OK_SELECT &&
2436  ri_ReportViolation(riinfo,
2437  pk_rel, fk_rel,
2438  newslot ? newslot : oldslot,
2439  NULL,
2440  qkey->constr_queryno, false);
2441 
2442  return SPI_processed != 0;
2443 }
2444 
2445 /*
2446  * Extract fields from a tuple into Datum/nulls arrays
2447  */
2448 static void
2450  const RI_ConstraintInfo *riinfo, bool rel_is_pk,
2451  Datum *vals, char *nulls)
2452 {
2453  const int16 *attnums;
2454  bool isnull;
2455 
2456  if (rel_is_pk)
2457  attnums = riinfo->pk_attnums;
2458  else
2459  attnums = riinfo->fk_attnums;
2460 
2461  for (int i = 0; i < riinfo->nkeys; i++)
2462  {
2463  vals[i] = slot_getattr(slot, attnums[i], &isnull);
2464  nulls[i] = isnull ? 'n' : ' ';
2465  }
2466 }
2467 
2468 /*
2469  * Produce an error report
2470  *
2471  * If the failed constraint was on insert/update to the FK table,
2472  * we want the key names and values extracted from there, and the error
2473  * message to look like 'key blah is not present in PK'.
2474  * Otherwise, the attr names and values come from the PK table and the
2475  * message looks like 'key blah is still referenced from FK'.
2476  */
2477 static void
2479  Relation pk_rel, Relation fk_rel,
2480  TupleTableSlot *violatorslot, TupleDesc tupdesc,
2481  int queryno, bool partgone)
2482 {
2483  StringInfoData key_names;
2484  StringInfoData key_values;
2485  bool onfk;
2486  const int16 *attnums;
2487  Oid rel_oid;
2488  AclResult aclresult;
2489  bool has_perm = true;
2490 
2491  /*
2492  * Determine which relation to complain about. If tupdesc wasn't passed
2493  * by caller, assume the violator tuple came from there.
2494  */
2495  onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
2496  if (onfk)
2497  {
2498  attnums = riinfo->fk_attnums;
2499  rel_oid = fk_rel->rd_id;
2500  if (tupdesc == NULL)
2501  tupdesc = fk_rel->rd_att;
2502  }
2503  else
2504  {
2505  attnums = riinfo->pk_attnums;
2506  rel_oid = pk_rel->rd_id;
2507  if (tupdesc == NULL)
2508  tupdesc = pk_rel->rd_att;
2509  }
2510 
2511  /*
2512  * Check permissions- if the user does not have access to view the data in
2513  * any of the key columns then we don't include the errdetail() below.
2514  *
2515  * Check if RLS is enabled on the relation first. If so, we don't return
2516  * any specifics to avoid leaking data.
2517  *
2518  * Check table-level permissions next and, failing that, column-level
2519  * privileges.
2520  *
2521  * When a partition at the referenced side is being detached/dropped, we
2522  * needn't check, since the user must be the table owner anyway.
2523  */
2524  if (partgone)
2525  has_perm = true;
2526  else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
2527  {
2528  aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
2529  if (aclresult != ACLCHECK_OK)
2530  {
2531  /* Try for column-level permissions */
2532  for (int idx = 0; idx < riinfo->nkeys; idx++)
2533  {
2534  aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
2535  GetUserId(),
2536  ACL_SELECT);
2537 
2538  /* No access to the key */
2539  if (aclresult != ACLCHECK_OK)
2540  {
2541  has_perm = false;
2542  break;
2543  }
2544  }
2545  }
2546  }
2547  else
2548  has_perm = false;
2549 
2550  if (has_perm)
2551  {
2552  /* Get printable versions of the keys involved */
2553  initStringInfo(&key_names);
2554  initStringInfo(&key_values);
2555  for (int idx = 0; idx < riinfo->nkeys; idx++)
2556  {
2557  int fnum = attnums[idx];
2558  Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
2559  char *name,
2560  *val;
2561  Datum datum;
2562  bool isnull;
2563 
2564  name = NameStr(att->attname);
2565 
2566  datum = slot_getattr(violatorslot, fnum, &isnull);
2567  if (!isnull)
2568  {
2569  Oid foutoid;
2570  bool typisvarlena;
2571 
2572  getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
2573  val = OidOutputFunctionCall(foutoid, datum);
2574  }
2575  else
2576  val = "null";
2577 
2578  if (idx > 0)
2579  {
2580  appendStringInfoString(&key_names, ", ");
2581  appendStringInfoString(&key_values, ", ");
2582  }
2583  appendStringInfoString(&key_names, name);
2584  appendStringInfoString(&key_values, val);
2585  }
2586  }
2587 
2588  if (partgone)
2589  ereport(ERROR,
2590  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2591  errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
2592  RelationGetRelationName(pk_rel),
2593  NameStr(riinfo->conname)),
2594  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2595  key_names.data, key_values.data,
2596  RelationGetRelationName(fk_rel)),
2597  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2598  else if (onfk)
2599  ereport(ERROR,
2600  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2601  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
2602  RelationGetRelationName(fk_rel),
2603  NameStr(riinfo->conname)),
2604  has_perm ?
2605  errdetail("Key (%s)=(%s) is not present in table \"%s\".",
2606  key_names.data, key_values.data,
2607  RelationGetRelationName(pk_rel)) :
2608  errdetail("Key is not present in table \"%s\".",
2609  RelationGetRelationName(pk_rel)),
2610  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2611  else
2612  ereport(ERROR,
2613  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
2614  errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
2615  RelationGetRelationName(pk_rel),
2616  NameStr(riinfo->conname),
2617  RelationGetRelationName(fk_rel)),
2618  has_perm ?
2619  errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
2620  key_names.data, key_values.data,
2621  RelationGetRelationName(fk_rel)) :
2622  errdetail("Key is still referenced from table \"%s\".",
2623  RelationGetRelationName(fk_rel)),
2624  errtableconstraint(fk_rel, NameStr(riinfo->conname))));
2625 }
2626 
2627 
2628 /*
2629  * ri_NullCheck -
2630  *
2631  * Determine the NULL state of all key values in a tuple
2632  *
2633  * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
2634  */
2635 static int
2637  TupleTableSlot *slot,
2638  const RI_ConstraintInfo *riinfo, bool rel_is_pk)
2639 {
2640  const int16 *attnums;
2641  bool allnull = true;
2642  bool nonenull = true;
2643 
2644  if (rel_is_pk)
2645  attnums = riinfo->pk_attnums;
2646  else
2647  attnums = riinfo->fk_attnums;
2648 
2649  for (int i = 0; i < riinfo->nkeys; i++)
2650  {
2651  if (slot_attisnull(slot, attnums[i]))
2652  nonenull = false;
2653  else
2654  allnull = false;
2655  }
2656 
2657  if (allnull)
2658  return RI_KEYS_ALL_NULL;
2659 
2660  if (nonenull)
2661  return RI_KEYS_NONE_NULL;
2662 
2663  return RI_KEYS_SOME_NULL;
2664 }
2665 
2666 
2667 /*
2668  * ri_InitHashTables -
2669  *
2670  * Initialize our internal hash tables.
2671  */
2672 static void
2674 {
2675  HASHCTL ctl;
2676 
2677  ctl.keysize = sizeof(Oid);
2678  ctl.entrysize = sizeof(RI_ConstraintInfo);
2679  ri_constraint_cache = hash_create("RI constraint cache",
2681  &ctl, HASH_ELEM | HASH_BLOBS);
2682 
2683  /* Arrange to flush cache on pg_constraint changes */
2686  (Datum) 0);
2687 
2688  ctl.keysize = sizeof(RI_QueryKey);
2689  ctl.entrysize = sizeof(RI_QueryHashEntry);
2690  ri_query_cache = hash_create("RI query cache",
2692  &ctl, HASH_ELEM | HASH_BLOBS);
2693 
2694  ctl.keysize = sizeof(RI_CompareKey);
2695  ctl.entrysize = sizeof(RI_CompareHashEntry);
2696  ri_compare_cache = hash_create("RI compare cache",
2698  &ctl, HASH_ELEM | HASH_BLOBS);
2699 }
2700 
2701 
2702 /*
2703  * ri_FetchPreparedPlan -
2704  *
2705  * Lookup for a query key in our private hash table of prepared
2706  * and saved SPI execution plans. Return the plan if found or NULL.
2707  */
2708 static SPIPlanPtr
2710 {
2711  RI_QueryHashEntry *entry;
2712  SPIPlanPtr plan;
2713 
2714  /*
2715  * On the first call initialize the hashtable
2716  */
2717  if (!ri_query_cache)
2719 
2720  /*
2721  * Lookup for the key
2722  */
2724  key,
2725  HASH_FIND, NULL);
2726  if (entry == NULL)
2727  return NULL;
2728 
2729  /*
2730  * Check whether the plan is still valid. If it isn't, we don't want to
2731  * simply rely on plancache.c to regenerate it; rather we should start
2732  * from scratch and rebuild the query text too. This is to cover cases
2733  * such as table/column renames. We depend on the plancache machinery to
2734  * detect possible invalidations, though.
2735  *
2736  * CAUTION: this check is only trustworthy if the caller has already
2737  * locked both FK and PK rels.
2738  */
2739  plan = entry->plan;
2740  if (plan && SPI_plan_is_valid(plan))
2741  return plan;
2742 
2743  /*
2744  * Otherwise we might as well flush the cached plan now, to free a little
2745  * memory space before we make a new one.
2746  */
2747  entry->plan = NULL;
2748  if (plan)
2749  SPI_freeplan(plan);
2750 
2751  return NULL;
2752 }
2753 
2754 
2755 /*
2756  * ri_HashPreparedPlan -
2757  *
2758  * Add another plan to our private SPI query plan hashtable.
2759  */
2760 static void
2762 {
2763  RI_QueryHashEntry *entry;
2764  bool found;
2765 
2766  /*
2767  * On the first call initialize the hashtable
2768  */
2769  if (!ri_query_cache)
2771 
2772  /*
2773  * Add the new plan. We might be overwriting an entry previously found
2774  * invalid by ri_FetchPreparedPlan.
2775  */
2777  key,
2778  HASH_ENTER, &found);
2779  Assert(!found || entry->plan == NULL);
2780  entry->plan = plan;
2781 }
2782 
2783 
2784 /*
2785  * ri_KeysEqual -
2786  *
2787  * Check if all key values in OLD and NEW are equal.
2788  *
2789  * Note: at some point we might wish to redefine this as checking for
2790  * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
2791  * considered equal. Currently there is no need since all callers have
2792  * previously found at least one of the rows to contain no nulls.
2793  */
2794 static bool
2796  const RI_ConstraintInfo *riinfo, bool rel_is_pk)
2797 {
2798  const int16 *attnums;
2799 
2800  if (rel_is_pk)
2801  attnums = riinfo->pk_attnums;
2802  else
2803  attnums = riinfo->fk_attnums;
2804 
2805  /* XXX: could be worthwhile to fetch all necessary attrs at once */
2806  for (int i = 0; i < riinfo->nkeys; i++)
2807  {
2808  Datum oldvalue;
2809  Datum newvalue;
2810  bool isnull;
2811 
2812  /*
2813  * Get one attribute's oldvalue. If it is NULL - they're not equal.
2814  */
2815  oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
2816  if (isnull)
2817  return false;
2818 
2819  /*
2820  * Get one attribute's newvalue. If it is NULL - they're not equal.
2821  */
2822  newvalue = slot_getattr(newslot, attnums[i], &isnull);
2823  if (isnull)
2824  return false;
2825 
2826  if (rel_is_pk)
2827  {
2828  /*
2829  * If we are looking at the PK table, then do a bytewise
2830  * comparison. We must propagate PK changes if the value is
2831  * changed to one that "looks" different but would compare as
2832  * equal using the equality operator. This only makes a
2833  * difference for ON UPDATE CASCADE, but for consistency we treat
2834  * all changes to the PK the same.
2835  */
2836  Form_pg_attribute att = TupleDescAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
2837 
2838  if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
2839  return false;
2840  }
2841  else
2842  {
2843  /*
2844  * For the FK table, compare with the appropriate equality
2845  * operator. Changes that compare equal will still satisfy the
2846  * constraint after the update.
2847  */
2848  if (!ri_AttributesEqual(riinfo->ff_eq_oprs[i], RIAttType(rel, attnums[i]),
2849  oldvalue, newvalue))
2850  return false;
2851  }
2852  }
2853 
2854  return true;
2855 }
2856 
2857 
2858 /*
2859  * ri_AttributesEqual -
2860  *
2861  * Call the appropriate equality comparison operator for two values.
2862  *
2863  * NB: we have already checked that neither value is null.
2864  */
2865 static bool
2866 ri_AttributesEqual(Oid eq_opr, Oid typeid,
2867  Datum oldvalue, Datum newvalue)
2868 {
2869  RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
2870 
2871  /* Do we need to cast the values? */
2872  if (OidIsValid(entry->cast_func_finfo.fn_oid))
2873  {
2874  oldvalue = FunctionCall3(&entry->cast_func_finfo,
2875  oldvalue,
2876  Int32GetDatum(-1), /* typmod */
2877  BoolGetDatum(false)); /* implicit coercion */
2878  newvalue = FunctionCall3(&entry->cast_func_finfo,
2879  newvalue,
2880  Int32GetDatum(-1), /* typmod */
2881  BoolGetDatum(false)); /* implicit coercion */
2882  }
2883 
2884  /*
2885  * Apply the comparison operator.
2886  *
2887  * Note: This function is part of a call stack that determines whether an
2888  * update to a row is significant enough that it needs checking or action
2889  * on the other side of a foreign-key constraint. Therefore, the
2890  * comparison here would need to be done with the collation of the *other*
2891  * table. For simplicity (e.g., we might not even have the other table
2892  * open), we'll just use the default collation here, which could lead to
2893  * some false negatives. All this would break if we ever allow
2894  * database-wide collations to be nondeterministic.
2895  */
2897  DEFAULT_COLLATION_OID,
2898  oldvalue, newvalue));
2899 }
2900 
2901 /*
2902  * ri_HashCompareOp -
2903  *
2904  * See if we know how to compare two values, and create a new hash entry
2905  * if not.
2906  */
2907 static RI_CompareHashEntry *
2908 ri_HashCompareOp(Oid eq_opr, Oid typeid)
2909 {
2911  RI_CompareHashEntry *entry;
2912  bool found;
2913 
2914  /*
2915  * On the first call initialize the hashtable
2916  */
2917  if (!ri_compare_cache)
2919 
2920  /*
2921  * Find or create a hash entry. Note we're assuming RI_CompareKey
2922  * contains no struct padding.
2923  */
2924  key.eq_opr = eq_opr;
2925  key.typeid = typeid;
2927  &key,
2928  HASH_ENTER, &found);
2929  if (!found)
2930  entry->valid = false;
2931 
2932  /*
2933  * If not already initialized, do so. Since we'll keep this hash entry
2934  * for the life of the backend, put any subsidiary info for the function
2935  * cache structs into TopMemoryContext.
2936  */
2937  if (!entry->valid)
2938  {
2939  Oid lefttype,
2940  righttype,
2941  castfunc;
2942  CoercionPathType pathtype;
2943 
2944  /* We always need to know how to call the equality operator */
2945  fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
2947 
2948  /*
2949  * If we chose to use a cast from FK to PK type, we may have to apply
2950  * the cast function to get to the operator's input type.
2951  *
2952  * XXX eventually it would be good to support array-coercion cases
2953  * here and in ri_AttributesEqual(). At the moment there is no point
2954  * because cases involving nonidentical array types will be rejected
2955  * at constraint creation time.
2956  *
2957  * XXX perhaps also consider supporting CoerceViaIO? No need at the
2958  * moment since that will never be generated for implicit coercions.
2959  */
2960  op_input_types(eq_opr, &lefttype, &righttype);
2961  Assert(lefttype == righttype);
2962  if (typeid == lefttype)
2963  castfunc = InvalidOid; /* simplest case */
2964  else
2965  {
2966  pathtype = find_coercion_pathway(lefttype, typeid,
2968  &castfunc);
2969  if (pathtype != COERCION_PATH_FUNC &&
2970  pathtype != COERCION_PATH_RELABELTYPE)
2971  {
2972  /*
2973  * The declared input type of the eq_opr might be a
2974  * polymorphic type such as ANYARRAY or ANYENUM, or other
2975  * special cases such as RECORD; find_coercion_pathway
2976  * currently doesn't subsume these special cases.
2977  */
2978  if (!IsBinaryCoercible(typeid, lefttype))
2979  elog(ERROR, "no conversion function from %s to %s",
2980  format_type_be(typeid),
2981  format_type_be(lefttype));
2982  }
2983  }
2984  if (OidIsValid(castfunc))
2985  fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
2987  else
2989  entry->valid = true;
2990  }
2991 
2992  return entry;
2993 }
2994 
2995 
2996 /*
2997  * Given a trigger function OID, determine whether it is an RI trigger,
2998  * and if so whether it is attached to PK or FK relation.
2999  */
3000 int
3002 {
3003  switch (tgfoid)
3004  {
3005  case F_RI_FKEY_CASCADE_DEL:
3006  case F_RI_FKEY_CASCADE_UPD:
3007  case F_RI_FKEY_RESTRICT_DEL:
3008  case F_RI_FKEY_RESTRICT_UPD:
3009  case F_RI_FKEY_SETNULL_DEL:
3010  case F_RI_FKEY_SETNULL_UPD:
3011  case F_RI_FKEY_SETDEFAULT_DEL:
3012  case F_RI_FKEY_SETDEFAULT_UPD:
3013  case F_RI_FKEY_NOACTION_DEL:
3014  case F_RI_FKEY_NOACTION_UPD:
3015  return RI_TRIGGER_PK;
3016 
3017  case F_RI_FKEY_CHECK_INS:
3018  case F_RI_FKEY_CHECK_UPD:
3019  return RI_TRIGGER_FK;
3020  }
3021 
3022  return RI_TRIGGER_NONE;
3023 }
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:4242
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3920
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4091
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define NameStr(name)
Definition: c.h:746
unsigned int uint32
Definition: c.h:506
signed short int16
Definition: c.h:493
signed int int32
Definition: c.h:494
#define Assert(condition)
Definition: c.h:858
#define pg_attribute_noreturn()
Definition: c.h:217
#define OidIsValid(objectId)
Definition: c.h:775
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:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#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:84
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1639
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1325
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:131
int NewGUCNestLevel(void)
Definition: guc.c:2234
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2261
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:3340
@ 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:670
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
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:3366
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:1054
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1358
MemoryContext TopMemoryContext
Definition: mcxt.c:149
#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:2731
@ RTE_RELATION
Definition: parsenodes.h:1028
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2730
#define ACL_SELECT
Definition: parsenodes.h:77
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2729
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 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:714
tree ctl
Definition: radixtree.h:1853
#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:6006
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:2112
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:2312
static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
Definition: ri_triggers.c:2761
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1873
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:1939
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:2478
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:2228
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:2866
Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS)
Definition: ri_triggers.c:551
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1893
static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2636
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:1910
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:2795
struct RI_CompareHashEntry RI_CompareHashEntry
static RI_CompareHashEntry * ri_HashCompareOp(Oid eq_opr, Oid typeid)
Definition: ri_triggers.c:2908
#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:2194
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:2058
static void ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo, int32 constr_queryno)
Definition: ri_triggers.c:1980
#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:1359
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:1654
static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, Oid *argtypes, RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:2269
#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:2012
#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:3001
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:2673
static void ri_ExtractValues(Relation rel, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk, Datum *vals, char *nulls)
Definition: ri_triggers.c:2449
#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:2709
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:2112
void generate_operator_clause(StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ruleutils.c:13004
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
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:1297
AclMode requiredPerms
Definition: parsenodes.h:1295
RTEKind rtekind
Definition: parsenodes.h:1057
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:741
#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:1335
#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_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395
static bool slot_is_current_xact_tuple(TupleTableSlot *slot)
Definition: tuptable.h:445
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:381
const char * name
void CommandCounterIncrement(void)
Definition: xact.c:1098
#define IsolationUsesXactSnapshot()
Definition: xact.h:51