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