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