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