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