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