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