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