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