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