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