Branch data 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/genam.h"
27 : : #include "access/htup_details.h"
28 : : #include "access/skey.h"
29 : : #include "access/sysattr.h"
30 : : #include "access/table.h"
31 : : #include "access/tableam.h"
32 : : #include "access/xact.h"
33 : : #include "catalog/index.h"
34 : : #include "catalog/namespace.h"
35 : : #include "catalog/objectaccess.h"
36 : : #include "catalog/pg_am_d.h"
37 : : #include "catalog/pg_collation.h"
38 : : #include "catalog/pg_constraint.h"
39 : : #include "catalog/pg_index.h"
40 : : #include "catalog/pg_namespace.h"
41 : : #include "catalog/pg_proc.h"
42 : : #include "commands/trigger.h"
43 : : #include "executor/executor.h"
44 : : #include "executor/spi.h"
45 : : #include "lib/ilist.h"
46 : : #include "miscadmin.h"
47 : : #include "parser/parse_coerce.h"
48 : : #include "parser/parse_relation.h"
49 : : #include "tcop/utility.h"
50 : : #include "utils/acl.h"
51 : : #include "utils/builtins.h"
52 : : #include "utils/datum.h"
53 : : #include "utils/fmgroids.h"
54 : : #include "utils/guc.h"
55 : : #include "utils/hsearch.h"
56 : : #include "utils/injection_point.h"
57 : : #include "utils/inval.h"
58 : : #include "utils/lsyscache.h"
59 : : #include "utils/memutils.h"
60 : : #include "utils/rel.h"
61 : : #include "utils/rls.h"
62 : : #include "utils/ruleutils.h"
63 : : #include "utils/snapmgr.h"
64 : : #include "utils/syscache.h"
65 : :
66 : : /*
67 : : * Local definitions
68 : : */
69 : :
70 : : #define RI_MAX_NUMKEYS INDEX_MAX_KEYS
71 : :
72 : : #define RI_INIT_CONSTRAINTHASHSIZE 64
73 : : #define RI_INIT_QUERYHASHSIZE (RI_INIT_CONSTRAINTHASHSIZE * 4)
74 : :
75 : : #define RI_KEYS_ALL_NULL 0
76 : : #define RI_KEYS_SOME_NULL 1
77 : : #define RI_KEYS_NONE_NULL 2
78 : :
79 : : /* RI query type codes */
80 : : /* these queries are executed against the PK (referenced) table: */
81 : : #define RI_PLAN_CHECK_LOOKUPPK 1
82 : : #define RI_PLAN_CHECK_LOOKUPPK_FROM_PK 2
83 : : #define RI_PLAN_LAST_ON_PK RI_PLAN_CHECK_LOOKUPPK_FROM_PK
84 : : /* these queries are executed against the FK (referencing) table: */
85 : : #define RI_PLAN_CASCADE_ONDELETE 3
86 : : #define RI_PLAN_CASCADE_ONUPDATE 4
87 : : #define RI_PLAN_NO_ACTION 5
88 : : /* For RESTRICT, the same plan can be used for both ON DELETE and ON UPDATE triggers. */
89 : : #define RI_PLAN_RESTRICT 6
90 : : #define RI_PLAN_SETNULL_ONDELETE 7
91 : : #define RI_PLAN_SETNULL_ONUPDATE 8
92 : : #define RI_PLAN_SETDEFAULT_ONDELETE 9
93 : : #define RI_PLAN_SETDEFAULT_ONUPDATE 10
94 : :
95 : : #define MAX_QUOTED_NAME_LEN (NAMEDATALEN*2+3)
96 : : #define MAX_QUOTED_REL_NAME_LEN (MAX_QUOTED_NAME_LEN*2)
97 : :
98 : : #define RIAttName(rel, attnum) NameStr(*attnumAttName(rel, attnum))
99 : : #define RIAttType(rel, attnum) attnumTypeId(rel, attnum)
100 : : #define RIAttCollation(rel, attnum) attnumCollationId(rel, attnum)
101 : :
102 : : #define RI_TRIGTYPE_INSERT 1
103 : : #define RI_TRIGTYPE_UPDATE 2
104 : : #define RI_TRIGTYPE_DELETE 3
105 : :
106 : : typedef struct FastPathMeta FastPathMeta;
107 : :
108 : : /* Eligibility checks that require the referenced table and index to be open. */
109 : : typedef enum RI_FastPathState
110 : : {
111 : : RI_FASTPATH_UNKNOWN,
112 : : RI_FASTPATH_USABLE,
113 : : RI_FASTPATH_UNUSABLE
114 : : } RI_FastPathState;
115 : :
116 : : /*
117 : : * RI_ConstraintInfo
118 : : *
119 : : * Information extracted from an FK pg_constraint entry. This is cached in
120 : : * ri_constraint_cache.
121 : : *
122 : : * Note that pf/pp/ff_eq_oprs may hold the overlaps operator instead of equals
123 : : * for the PERIOD part of a temporal foreign key.
124 : : */
125 : : typedef struct RI_ConstraintInfo
126 : : {
127 : : Oid constraint_id; /* OID of pg_constraint entry (hash key) */
128 : : bool valid; /* successfully initialized? */
129 : : Oid constraint_root_id; /* OID of topmost ancestor constraint;
130 : : * same as constraint_id if not inherited */
131 : : uint32 oidHashValue; /* hash value of constraint_id */
132 : : uint32 rootHashValue; /* hash value of constraint_root_id */
133 : : NameData conname; /* name of the FK constraint */
134 : : Oid pk_relid; /* referenced relation */
135 : : Oid fk_relid; /* referencing relation */
136 : : char confupdtype; /* foreign key's ON UPDATE action */
137 : : char confdeltype; /* foreign key's ON DELETE action */
138 : : int ndelsetcols; /* number of columns referenced in ON DELETE
139 : : * SET clause */
140 : : int16 confdelsetcols[RI_MAX_NUMKEYS]; /* attnums of cols to set on
141 : : * delete */
142 : : char confmatchtype; /* foreign key's match type */
143 : : bool hasperiod; /* if the foreign key uses PERIOD */
144 : : int nkeys; /* number of key columns */
145 : : int16 pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
146 : : int16 fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
147 : : Oid pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
148 : : Oid pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
149 : : Oid ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
150 : : Oid period_contained_by_oper; /* anyrange <@ anyrange (or
151 : : * multiranges) */
152 : : Oid agged_period_contained_by_oper; /* fkattr <@ range_agg(pkattr) */
153 : : Oid period_intersect_oper; /* anyrange * anyrange (or
154 : : * multiranges) */
155 : : dlist_node valid_link; /* Link in list of valid entries */
156 : :
157 : : Oid conindid;
158 : : bool pk_is_partitioned;
159 : : RI_FastPathState fastpath_state; /* populated lazily under lock */
160 : :
161 : : FastPathMeta *fpmeta;
162 : : } RI_ConstraintInfo;
163 : :
164 : : typedef struct RI_CompareHashEntry RI_CompareHashEntry;
165 : :
166 : : /* Fast-path metadata for RI checks on foreign key referencing tables */
167 : : typedef struct FastPathMeta
168 : : {
169 : : FmgrInfo eq_opr_finfo[RI_MAX_NUMKEYS];
170 : : FmgrInfo cast_func_finfo[RI_MAX_NUMKEYS];
171 : : RegProcedure regops[RI_MAX_NUMKEYS];
172 : : Oid subtypes[RI_MAX_NUMKEYS];
173 : : int strats[RI_MAX_NUMKEYS];
174 : : AttrNumber index_attnos[RI_MAX_NUMKEYS]; /* index column positions */
175 : :
176 : : /*
177 : : * fn_mcxt for the cached FmgrInfos above. Cast and equality functions
178 : : * (e.g. record_eq()) use fn_mcxt as scratch space, caching state there
179 : : * and keeping a pointer to it in FmgrInfo.fn_extra. Give them a context
180 : : * of their own, created with this struct and destroyed with it in
181 : : * AtEOXact_RI().
182 : : *
183 : : * Note this context must not be reset while the FmgrInfos remain in use,
184 : : * since that would free the state fn_extra still points at.
185 : : */
186 : : MemoryContext scratch_cxt;
187 : :
188 : : /* Link in ri_fpmeta_dead_list while awaiting deferred release */
189 : : struct FastPathMeta *next_dead;
190 : : } FastPathMeta;
191 : :
192 : : /*
193 : : * RI_QueryKey
194 : : *
195 : : * The key identifying a prepared SPI plan in our query hashtable
196 : : */
197 : : typedef struct RI_QueryKey
198 : : {
199 : : Oid constr_id; /* OID of pg_constraint entry */
200 : : int32 constr_queryno; /* query type ID, see RI_PLAN_XXX above */
201 : : } RI_QueryKey;
202 : :
203 : : /*
204 : : * RI_QueryHashEntry
205 : : */
206 : : typedef struct RI_QueryHashEntry
207 : : {
208 : : RI_QueryKey key;
209 : : SPIPlanPtr plan;
210 : : } RI_QueryHashEntry;
211 : :
212 : : /*
213 : : * RI_CompareKey
214 : : *
215 : : * The key identifying an entry showing how to compare two values
216 : : */
217 : : typedef struct RI_CompareKey
218 : : {
219 : : Oid eq_opr; /* the equality operator to apply */
220 : : Oid typeid; /* the data type to apply it to */
221 : : } RI_CompareKey;
222 : :
223 : : /*
224 : : * RI_CompareHashEntry
225 : : */
226 : : typedef struct RI_CompareHashEntry
227 : : {
228 : : RI_CompareKey key;
229 : : bool valid; /* successfully initialized? */
230 : : FmgrInfo eq_opr_finfo; /* call info for equality fn */
231 : : FmgrInfo cast_func_finfo; /* in case we must coerce input */
232 : : } RI_CompareHashEntry;
233 : :
234 : : /*
235 : : * Local data
236 : : */
237 : : static HTAB *ri_constraint_cache = NULL;
238 : : static HTAB *ri_query_cache = NULL;
239 : : static HTAB *ri_compare_cache = NULL;
240 : : static dclist_head ri_constraint_cache_valid_list;
241 : :
242 : : /*
243 : : * FastPathMeta objects detached from their cache entry by invalidation, but
244 : : * possibly still referenced by an RI check further up the stack. Released
245 : : * by AtEOXact_RI(), where no such reference can exist. See
246 : : * InvalidateConstraintCacheCallBack().
247 : : */
248 : : static FastPathMeta *ri_fpmeta_dead_list = NULL;
249 : :
250 : : /*
251 : : * Local function prototypes
252 : : */
253 : : static bool ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
254 : : TupleTableSlot *oldslot,
255 : : const RI_ConstraintInfo *riinfo);
256 : : static Datum ri_restrict(TriggerData *trigdata, bool is_no_action);
257 : : static Datum ri_set(TriggerData *trigdata, bool is_set_null, int tgkind);
258 : : static void quoteOneName(char *buffer, const char *name);
259 : : static void quoteRelationName(char *buffer, Relation rel);
260 : : static void ri_GenerateQual(StringInfo buf,
261 : : const char *sep,
262 : : const char *leftop, Oid leftoptype,
263 : : Oid opoid,
264 : : const char *rightop, Oid rightoptype);
265 : : static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
266 : : static int ri_NullCheck(TupleDesc tupDesc, TupleTableSlot *slot,
267 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk);
268 : : static void ri_BuildQueryKey(RI_QueryKey *key,
269 : : const RI_ConstraintInfo *riinfo,
270 : : int32 constr_queryno);
271 : : static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
272 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk);
273 : : static bool ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
274 : : Datum lhs, Datum rhs);
275 : :
276 : : static void ri_InitHashTables(void);
277 : : static void InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid,
278 : : uint32 hashvalue);
279 : : static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key);
280 : : static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan);
281 : : static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
282 : :
283 : : static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
284 : : int tgkind);
285 : : static RI_ConstraintInfo *ri_FetchConstraintInfo(Trigger *trigger,
286 : : Relation trig_rel, bool rel_is_pk);
287 : : static RI_ConstraintInfo *ri_LoadConstraintInfo(Oid constraintOid);
288 : : static Oid get_ri_constraint_root(Oid constrOid);
289 : : static SPIPlanPtr ri_PlanCheck(const char *querystr, int nargs, const Oid *argtypes,
290 : : RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel);
291 : : static bool ri_PerformCheck(const RI_ConstraintInfo *riinfo,
292 : : RI_QueryKey *qkey, SPIPlanPtr qplan,
293 : : Relation fk_rel, Relation pk_rel,
294 : : TupleTableSlot *oldslot, TupleTableSlot *newslot,
295 : : bool is_restrict,
296 : : bool detectNewRows, int expect_OK);
297 : : static bool ri_FastPathCheck(RI_ConstraintInfo *riinfo,
298 : : Relation fk_rel, TupleTableSlot *newslot);
299 : : static bool ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel,
300 : : IndexScanDesc scandesc, TupleTableSlot *slot,
301 : : Snapshot snapshot, const RI_ConstraintInfo *riinfo,
302 : : ScanKeyData *skey, int nkeys);
303 : : static bool ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap,
304 : : bool *concurrently_updated);
305 : : static bool ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo);
306 : : static bool ri_check_fastpath_index(RI_ConstraintInfo *riinfo,
307 : : Relation pk_rel, Relation idx_rel);
308 : : static void ri_CheckPermissions(const RI_ConstraintInfo *riinfo,
309 : : Relation query_rel);
310 : : static bool recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys,
311 : : int nkeys, TupleTableSlot *new_slot);
312 : : static void ri_CheckFunctionPermissions(const RI_ConstraintInfo *riinfo,
313 : : const FastPathMeta *fpmeta);
314 : : static void build_index_scankeys(const RI_ConstraintInfo *riinfo,
315 : : FastPathMeta *fpmeta,
316 : : Relation idx_rel, Datum *pk_vals,
317 : : char *pk_nulls, ScanKey skeys);
318 : : static void ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo,
319 : : Relation fk_rel, Relation idx_rel);
320 : : static void ri_ExtractValues(Relation rel, TupleTableSlot *slot,
321 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk,
322 : : Datum *vals, char *nulls);
323 : : pg_noreturn static void ri_ReportViolation(const RI_ConstraintInfo *riinfo,
324 : : Relation pk_rel, Relation fk_rel,
325 : : TupleTableSlot *violatorslot, TupleDesc tupdesc,
326 : : int queryno, bool is_restrict, bool partgone);
327 : :
328 : :
329 : : /*
330 : : * RI_FKey_check -
331 : : *
332 : : * Check foreign key existence (combined for INSERT and UPDATE).
333 : : */
334 : : static Datum
335 : 605726 : RI_FKey_check(TriggerData *trigdata)
336 : : {
337 : : RI_ConstraintInfo *riinfo;
338 : : Relation fk_rel;
339 : : Relation pk_rel;
340 : : TupleTableSlot *newslot;
341 : : RI_QueryKey qkey;
342 : : SPIPlanPtr qplan;
343 : :
344 : 605726 : riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
345 : : trigdata->tg_relation, false);
346 : :
347 [ + + ]: 605726 : if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
348 : 296 : newslot = trigdata->tg_newslot;
349 : : else
350 : 605430 : newslot = trigdata->tg_trigslot;
351 : :
352 : : /*
353 : : * We should not even consider checking the row if it is no longer valid,
354 : : * since it was either deleted (so the deferred check should be skipped)
355 : : * or updated (in which case only the latest version of the row should be
356 : : * checked). Test its liveness according to SnapshotSelf. We need pin
357 : : * and lock on the buffer to call HeapTupleSatisfiesVisibility. Caller
358 : : * should be holding pin, but not lock.
359 : : */
360 [ + + ]: 605726 : if (!table_tuple_satisfies_snapshot(trigdata->tg_relation, newslot, SnapshotSelf))
361 : 40 : return PointerGetDatum(NULL);
362 : :
363 : 605686 : fk_rel = trigdata->tg_relation;
364 : :
365 [ + + + - ]: 605686 : switch (ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false))
366 : : {
367 : 102 : case RI_KEYS_ALL_NULL:
368 : :
369 : : /*
370 : : * No further check needed - an all-NULL key passes every type of
371 : : * foreign key constraint.
372 : : */
373 : 102 : return PointerGetDatum(NULL);
374 : :
375 : 104 : case RI_KEYS_SOME_NULL:
376 : :
377 : : /*
378 : : * This is the only case that differs between the three kinds of
379 : : * MATCH.
380 : : */
381 [ + + - ]: 104 : switch (riinfo->confmatchtype)
382 : : {
383 : 24 : case FKCONSTR_MATCH_FULL:
384 : :
385 : : /*
386 : : * Not allowed - MATCH FULL says either all or none of the
387 : : * attributes can be NULLs
388 : : */
389 [ + - ]: 24 : ereport(ERROR,
390 : : (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
391 : : errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
392 : : RelationGetRelationName(fk_rel),
393 : : NameStr(riinfo->conname)),
394 : : errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
395 : : errtableconstraint(fk_rel,
396 : : NameStr(riinfo->conname))));
397 : : return PointerGetDatum(NULL);
398 : :
399 : 80 : case FKCONSTR_MATCH_SIMPLE:
400 : :
401 : : /*
402 : : * MATCH SIMPLE - if ANY column is null, the key passes
403 : : * the constraint.
404 : : */
405 : 80 : return PointerGetDatum(NULL);
406 : :
407 : : #ifdef NOT_USED
408 : : case FKCONSTR_MATCH_PARTIAL:
409 : :
410 : : /*
411 : : * MATCH PARTIAL - all non-null columns must match. (not
412 : : * implemented, can be done by modifying the query below
413 : : * to only include non-null columns, or by writing a
414 : : * special version here)
415 : : */
416 : : break;
417 : : #endif
418 : : }
419 : :
420 : : case RI_KEYS_NONE_NULL:
421 : :
422 : : /*
423 : : * Have a full qualified key - continue below for all three kinds
424 : : * of MATCH.
425 : : */
426 : 605480 : break;
427 : : }
428 : :
429 : : /*
430 : : * Fast path: probe the PK unique index directly, bypassing SPI.
431 : : *
432 : : * For non-partitioned, non-temporal FKs, we can skip the SPI machinery
433 : : * (plan cache, executor setup, etc.) and do a direct index scan + tuple
434 : : * lock. This is semantically equivalent to the SPI path below but avoids
435 : : * the per-row executor overhead.
436 : : *
437 : : * ri_FastPathCheck() reports the violation itself if no matching PK row
438 : : * is found. It returns false if the index checks made after opening the
439 : : * relations require a SPI fallback.
440 : : */
441 [ + + + + ]: 1209850 : if (ri_fastpath_is_applicable(riinfo) &&
442 : 604722 : ri_FastPathCheck(riinfo, fk_rel, newslot))
443 : 604346 : return PointerGetDatum(NULL);
444 : :
445 : 782 : SPI_connect();
446 : :
447 : : /*
448 : : * pk_rel is opened in RowShareLock mode since that's what our eventual
449 : : * SELECT FOR KEY SHARE will get on it.
450 : : */
451 : 782 : pk_rel = table_open(riinfo->pk_relid, RowShareLock);
452 : :
453 : : /* Fetch or prepare a saved plan for the real check */
454 : 782 : ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK);
455 : :
456 [ + + ]: 782 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
457 : : {
458 : : StringInfoData querybuf;
459 : : char pkrelname[MAX_QUOTED_REL_NAME_LEN];
460 : : char attname[MAX_QUOTED_NAME_LEN];
461 : : char paramname[16];
462 : : const char *querysep;
463 : : Oid queryoids[RI_MAX_NUMKEYS];
464 : : const char *pk_only;
465 : :
466 : : /* ----------
467 : : * The query string built is
468 : : * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
469 : : * FOR KEY SHARE OF x
470 : : * The type id's for the $ parameters are those of the
471 : : * corresponding FK attributes.
472 : : *
473 : : * But for temporal FKs we need to make sure
474 : : * the FK's range is completely covered.
475 : : * So we use this query instead:
476 : : * SELECT 1
477 : : * FROM (
478 : : * SELECT pkperiodatt AS r
479 : : * FROM [ONLY] pktable x
480 : : * WHERE pkatt1 = $1 [AND ...]
481 : : * AND pkperiodatt && $n
482 : : * FOR KEY SHARE OF x
483 : : * ) x1
484 : : * HAVING $n <@ range_agg(x1.r)
485 : : * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
486 : : * we can make this a bit simpler.
487 : : * ----------
488 : : */
489 : 386 : initStringInfo(&querybuf);
490 : 772 : pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
491 [ + + ]: 386 : "" : "ONLY ";
492 : 386 : quoteRelationName(pkrelname, pk_rel);
493 [ + + ]: 386 : if (riinfo->hasperiod)
494 : : {
495 : 67 : quoteOneName(attname,
496 : 67 : RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
497 : :
498 : 67 : appendStringInfo(&querybuf,
499 : : "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
500 : : attname, pk_only, pkrelname);
501 : : }
502 : : else
503 : : {
504 : 319 : appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
505 : : pk_only, pkrelname);
506 : : }
507 : 386 : querysep = "WHERE";
508 [ + + ]: 863 : for (int i = 0; i < riinfo->nkeys; i++)
509 : : {
510 : 477 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
511 : 477 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
512 : :
513 : 477 : quoteOneName(attname,
514 : 477 : RIAttName(pk_rel, riinfo->pk_attnums[i]));
515 : 477 : sprintf(paramname, "$%d", i + 1);
516 : 477 : ri_GenerateQual(&querybuf, querysep,
517 : : attname, pk_type,
518 : : riinfo->pf_eq_oprs[i],
519 : : paramname, fk_type);
520 : 477 : querysep = "AND";
521 : 477 : queryoids[i] = fk_type;
522 : : }
523 : 386 : appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
524 [ + + ]: 386 : if (riinfo->hasperiod)
525 : : {
526 : 67 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
527 : :
528 : 67 : appendStringInfoString(&querybuf, ") x1 HAVING ");
529 : 67 : sprintf(paramname, "$%d", riinfo->nkeys);
530 : 67 : ri_GenerateQual(&querybuf, "",
531 : : paramname, fk_type,
532 : : riinfo->agged_period_contained_by_oper,
533 : : "pg_catalog.range_agg", ANYMULTIRANGEOID);
534 : 67 : appendStringInfoString(&querybuf, "(x1.r)");
535 : : }
536 : :
537 : : /* Prepare and save the plan */
538 : 386 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
539 : : &qkey, fk_rel, pk_rel);
540 : : }
541 : :
542 : : /*
543 : : * Now check that foreign key exists in PK table
544 : : *
545 : : * XXX detectNewRows must be true when a partitioned table is on the
546 : : * referenced side. The reason is that our snapshot must be fresh in
547 : : * order for the hack in find_inheritance_children() to work.
548 : : */
549 : 782 : ri_PerformCheck(riinfo, &qkey, qplan,
550 : : fk_rel, pk_rel,
551 : : NULL, newslot,
552 : : false,
553 : 782 : pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE,
554 : : SPI_OK_SELECT);
555 : :
556 [ - + ]: 622 : if (SPI_finish() != SPI_OK_FINISH)
557 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
558 : :
559 : 622 : table_close(pk_rel, RowShareLock);
560 : :
561 : 622 : return PointerGetDatum(NULL);
562 : : }
563 : :
564 : :
565 : : /*
566 : : * RI_FKey_check_ins -
567 : : *
568 : : * Check foreign key existence at insert event on FK table.
569 : : */
570 : : Datum
571 : 605430 : RI_FKey_check_ins(PG_FUNCTION_ARGS)
572 : : {
573 : : /* Check that this is a valid trigger call on the right time and event. */
574 : 605430 : ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);
575 : :
576 : : /* Share code with UPDATE case. */
577 : 605430 : return RI_FKey_check((TriggerData *) fcinfo->context);
578 : : }
579 : :
580 : :
581 : : /*
582 : : * RI_FKey_check_upd -
583 : : *
584 : : * Check foreign key existence at update event on FK table.
585 : : */
586 : : Datum
587 : 296 : RI_FKey_check_upd(PG_FUNCTION_ARGS)
588 : : {
589 : : /* Check that this is a valid trigger call on the right time and event. */
590 : 296 : ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);
591 : :
592 : : /* Share code with INSERT case. */
593 : 296 : return RI_FKey_check((TriggerData *) fcinfo->context);
594 : : }
595 : :
596 : :
597 : : /*
598 : : * ri_Check_Pk_Match
599 : : *
600 : : * Check to see if another PK row has been created that provides the same
601 : : * key values as the "oldslot" that's been modified or deleted in our trigger
602 : : * event. Returns true if a match is found in the PK table.
603 : : *
604 : : * We assume the caller checked that the oldslot contains no NULL key values,
605 : : * since otherwise a match is impossible.
606 : : */
607 : : static bool
608 : 530 : ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
609 : : TupleTableSlot *oldslot,
610 : : const RI_ConstraintInfo *riinfo)
611 : : {
612 : : SPIPlanPtr qplan;
613 : : RI_QueryKey qkey;
614 : : bool result;
615 : :
616 : : /* Only called for non-null rows */
617 : : Assert(ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) == RI_KEYS_NONE_NULL);
618 : :
619 : 530 : SPI_connect();
620 : :
621 : : /*
622 : : * Fetch or prepare a saved plan for checking PK table with values coming
623 : : * from a PK row
624 : : */
625 : 530 : ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CHECK_LOOKUPPK_FROM_PK);
626 : :
627 [ + + ]: 530 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
628 : : {
629 : : StringInfoData querybuf;
630 : : char pkrelname[MAX_QUOTED_REL_NAME_LEN];
631 : : char attname[MAX_QUOTED_NAME_LEN];
632 : : char paramname[16];
633 : : const char *querysep;
634 : : const char *pk_only;
635 : : Oid queryoids[RI_MAX_NUMKEYS];
636 : :
637 : : /* ----------
638 : : * The query string built is
639 : : * SELECT 1 FROM [ONLY] <pktable> x WHERE pkatt1 = $1 [AND ...]
640 : : * FOR KEY SHARE OF x
641 : : * The type id's for the $ parameters are those of the
642 : : * PK attributes themselves.
643 : : *
644 : : * But for temporal FKs we need to make sure
645 : : * the old PK's range is completely covered.
646 : : * So we use this query instead:
647 : : * SELECT 1
648 : : * FROM (
649 : : * SELECT pkperiodatt AS r
650 : : * FROM [ONLY] pktable x
651 : : * WHERE pkatt1 = $1 [AND ...]
652 : : * AND pkperiodatt && $n
653 : : * FOR KEY SHARE OF x
654 : : * ) x1
655 : : * HAVING $n <@ range_agg(x1.r)
656 : : * Note if FOR KEY SHARE ever allows GROUP BY and HAVING
657 : : * we can make this a bit simpler.
658 : : * ----------
659 : : */
660 : 257 : initStringInfo(&querybuf);
661 : 514 : pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
662 [ + + ]: 257 : "" : "ONLY ";
663 : 257 : quoteRelationName(pkrelname, pk_rel);
664 [ - + ]: 257 : if (riinfo->hasperiod)
665 : : {
666 : 0 : quoteOneName(attname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
667 : :
668 : 0 : appendStringInfo(&querybuf,
669 : : "SELECT 1 FROM (SELECT %s AS r FROM %s%s x",
670 : : attname, pk_only, pkrelname);
671 : : }
672 : : else
673 : : {
674 : 257 : appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
675 : : pk_only, pkrelname);
676 : : }
677 : 257 : querysep = "WHERE";
678 [ + + ]: 602 : for (int i = 0; i < riinfo->nkeys; i++)
679 : : {
680 : 345 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
681 : :
682 : 345 : quoteOneName(attname,
683 : 345 : RIAttName(pk_rel, riinfo->pk_attnums[i]));
684 : 345 : sprintf(paramname, "$%d", i + 1);
685 : 345 : ri_GenerateQual(&querybuf, querysep,
686 : : attname, pk_type,
687 : 345 : riinfo->pp_eq_oprs[i],
688 : : paramname, pk_type);
689 : 345 : querysep = "AND";
690 : 345 : queryoids[i] = pk_type;
691 : : }
692 : 257 : appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
693 [ - + ]: 257 : if (riinfo->hasperiod)
694 : : {
695 : 0 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
696 : :
697 : 0 : appendStringInfoString(&querybuf, ") x1 HAVING ");
698 : 0 : sprintf(paramname, "$%d", riinfo->nkeys);
699 : 0 : ri_GenerateQual(&querybuf, "",
700 : : paramname, fk_type,
701 : 0 : riinfo->agged_period_contained_by_oper,
702 : : "pg_catalog.range_agg", ANYMULTIRANGEOID);
703 : 0 : appendStringInfoString(&querybuf, "(x1.r)");
704 : : }
705 : :
706 : : /* Prepare and save the plan */
707 : 257 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
708 : : &qkey, fk_rel, pk_rel);
709 : : }
710 : :
711 : : /*
712 : : * We have a plan now. Run it.
713 : : */
714 : 530 : result = ri_PerformCheck(riinfo, &qkey, qplan,
715 : : fk_rel, pk_rel,
716 : : oldslot, NULL,
717 : : false,
718 : : true, /* treat like update */
719 : : SPI_OK_SELECT);
720 : :
721 [ - + ]: 530 : if (SPI_finish() != SPI_OK_FINISH)
722 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
723 : :
724 : 530 : return result;
725 : : }
726 : :
727 : :
728 : : /*
729 : : * RI_FKey_noaction_del -
730 : : *
731 : : * Give an error and roll back the current transaction if the
732 : : * delete has resulted in a violation of the given referential
733 : : * integrity constraint.
734 : : */
735 : : Datum
736 : 301 : RI_FKey_noaction_del(PG_FUNCTION_ARGS)
737 : : {
738 : : /* Check that this is a valid trigger call on the right time and event. */
739 : 301 : ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);
740 : :
741 : : /* Share code with RESTRICT/UPDATE cases. */
742 : 301 : return ri_restrict((TriggerData *) fcinfo->context, true);
743 : : }
744 : :
745 : : /*
746 : : * RI_FKey_restrict_del -
747 : : *
748 : : * Restrict delete from PK table to rows unreferenced by foreign key.
749 : : *
750 : : * The SQL standard intends that this referential action occur exactly when
751 : : * the delete is performed, rather than after. This appears to be
752 : : * the only difference between "NO ACTION" and "RESTRICT". In Postgres
753 : : * we still implement this as an AFTER trigger, but it's non-deferrable.
754 : : */
755 : : Datum
756 : 8 : RI_FKey_restrict_del(PG_FUNCTION_ARGS)
757 : : {
758 : : /* Check that this is a valid trigger call on the right time and event. */
759 : 8 : ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);
760 : :
761 : : /* Share code with NO ACTION/UPDATE cases. */
762 : 8 : return ri_restrict((TriggerData *) fcinfo->context, false);
763 : : }
764 : :
765 : : /*
766 : : * RI_FKey_noaction_upd -
767 : : *
768 : : * Give an error and roll back the current transaction if the
769 : : * update has resulted in a violation of the given referential
770 : : * integrity constraint.
771 : : */
772 : : Datum
773 : 351 : RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
774 : : {
775 : : /* Check that this is a valid trigger call on the right time and event. */
776 : 351 : ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);
777 : :
778 : : /* Share code with RESTRICT/DELETE cases. */
779 : 351 : return ri_restrict((TriggerData *) fcinfo->context, true);
780 : : }
781 : :
782 : : /*
783 : : * RI_FKey_restrict_upd -
784 : : *
785 : : * Restrict update of PK to rows unreferenced by foreign key.
786 : : *
787 : : * The SQL standard intends that this referential action occur exactly when
788 : : * the update is performed, rather than after. This appears to be
789 : : * the only difference between "NO ACTION" and "RESTRICT". In Postgres
790 : : * we still implement this as an AFTER trigger, but it's non-deferrable.
791 : : */
792 : : Datum
793 : 20 : RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
794 : : {
795 : : /* Check that this is a valid trigger call on the right time and event. */
796 : 20 : ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);
797 : :
798 : : /* Share code with NO ACTION/DELETE cases. */
799 : 20 : return ri_restrict((TriggerData *) fcinfo->context, false);
800 : : }
801 : :
802 : : /*
803 : : * ri_restrict -
804 : : *
805 : : * Common code for ON DELETE RESTRICT, ON DELETE NO ACTION,
806 : : * ON UPDATE RESTRICT, and ON UPDATE NO ACTION.
807 : : */
808 : : static Datum
809 : 768 : ri_restrict(TriggerData *trigdata, bool is_no_action)
810 : : {
811 : : const RI_ConstraintInfo *riinfo;
812 : : Relation fk_rel;
813 : : Relation pk_rel;
814 : : TupleTableSlot *oldslot;
815 : : RI_QueryKey qkey;
816 : : SPIPlanPtr qplan;
817 : :
818 : 768 : riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
819 : : trigdata->tg_relation, true);
820 : :
821 : : /*
822 : : * Get the relation descriptors of the FK and PK tables and the old tuple.
823 : : *
824 : : * fk_rel is opened in RowShareLock mode since that's what our eventual
825 : : * SELECT FOR KEY SHARE will get on it.
826 : : */
827 : 768 : fk_rel = table_open(riinfo->fk_relid, RowShareLock);
828 : 768 : pk_rel = trigdata->tg_relation;
829 : 768 : oldslot = trigdata->tg_trigslot;
830 : :
831 : : /*
832 : : * If another PK row now exists providing the old key values, we should
833 : : * not do anything. However, this check should only be made in the NO
834 : : * ACTION case; in RESTRICT cases we don't wish to allow another row to be
835 : : * substituted.
836 : : *
837 : : * If the foreign key has PERIOD, we incorporate looking for replacement
838 : : * rows in the main SQL query below, so we needn't do it here.
839 : : */
840 [ + + + + : 1298 : if (is_no_action && !riinfo->hasperiod &&
+ + ]
841 : 530 : ri_Check_Pk_Match(pk_rel, fk_rel, oldslot, riinfo))
842 : : {
843 : 38 : table_close(fk_rel, RowShareLock);
844 : 38 : return PointerGetDatum(NULL);
845 : : }
846 : :
847 : 730 : SPI_connect();
848 : :
849 : : /*
850 : : * Fetch or prepare a saved plan for the restrict lookup (it's the same
851 : : * query for delete and update cases)
852 : : */
853 [ + + ]: 730 : ri_BuildQueryKey(&qkey, riinfo, is_no_action ? RI_PLAN_NO_ACTION : RI_PLAN_RESTRICT);
854 : :
855 [ + + ]: 730 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
856 : : {
857 : : StringInfoData querybuf;
858 : : char pkrelname[MAX_QUOTED_REL_NAME_LEN];
859 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
860 : : char attname[MAX_QUOTED_NAME_LEN];
861 : : char periodattname[MAX_QUOTED_NAME_LEN];
862 : : char paramname[16];
863 : : const char *querysep;
864 : : Oid queryoids[RI_MAX_NUMKEYS];
865 : : const char *fk_only;
866 : :
867 : : /* ----------
868 : : * The query string built is
869 : : * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = fkatt1 [AND ...]
870 : : * FOR KEY SHARE OF x
871 : : * The type id's for the $ parameters are those of the
872 : : * corresponding PK attributes.
873 : : * ----------
874 : : */
875 : 315 : initStringInfo(&querybuf);
876 : 630 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
877 [ + + ]: 315 : "" : "ONLY ";
878 : 315 : quoteRelationName(fkrelname, fk_rel);
879 : 315 : appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
880 : : fk_only, fkrelname);
881 : 315 : querysep = "WHERE";
882 [ + + ]: 802 : for (int i = 0; i < riinfo->nkeys; i++)
883 : : {
884 : 487 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
885 : 487 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
886 : :
887 : 487 : quoteOneName(attname,
888 : 487 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
889 : 487 : sprintf(paramname, "$%d", i + 1);
890 : 487 : ri_GenerateQual(&querybuf, querysep,
891 : : paramname, pk_type,
892 : 487 : riinfo->pf_eq_oprs[i],
893 : : attname, fk_type);
894 : 487 : querysep = "AND";
895 : 487 : queryoids[i] = pk_type;
896 : : }
897 : :
898 : : /*----------
899 : : * For temporal foreign keys, a reference could still be valid if the
900 : : * referenced range didn't change too much. Also if a referencing
901 : : * range extends past the current PK row, we don't want to check that
902 : : * part: some other PK row should fulfill it. We only want to check
903 : : * the part matching the PK record we've changed. Therefore to find
904 : : * invalid records we do this:
905 : : *
906 : : * SELECT 1 FROM [ONLY] <fktable> x WHERE $1 = x.fkatt1 [AND ...]
907 : : * -- begin temporal
908 : : * AND $n && x.fkperiod
909 : : * AND NOT coalesce((x.fkperiod * $n) <@
910 : : * (SELECT range_agg(r)
911 : : * FROM (SELECT y.pkperiod r
912 : : * FROM [ONLY] <pktable> y
913 : : * WHERE $1 = y.pkatt1 [AND ...] AND $n && y.pkperiod
914 : : * FOR KEY SHARE OF y) y2), false)
915 : : * -- end temporal
916 : : * FOR KEY SHARE OF x
917 : : *
918 : : * We need the coalesce in case the first subquery returns no rows.
919 : : * We need the second subquery because FOR KEY SHARE doesn't support
920 : : * aggregate queries.
921 : : */
922 [ + + + - ]: 315 : if (riinfo->hasperiod && is_no_action)
923 : : {
924 : 86 : Oid pk_period_type = RIAttType(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]);
925 : 86 : Oid fk_period_type = RIAttType(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]);
926 : : StringInfoData intersectbuf;
927 : : StringInfoData replacementsbuf;
928 : 172 : char *pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
929 [ - + ]: 86 : "" : "ONLY ";
930 : :
931 : 86 : quoteOneName(attname, RIAttName(fk_rel, riinfo->fk_attnums[riinfo->nkeys - 1]));
932 : 86 : sprintf(paramname, "$%d", riinfo->nkeys);
933 : :
934 : 86 : appendStringInfoString(&querybuf, " AND NOT coalesce(");
935 : :
936 : : /* Intersect the fk with the old pk range */
937 : 86 : initStringInfo(&intersectbuf);
938 : 86 : appendStringInfoChar(&intersectbuf, '(');
939 : 86 : ri_GenerateQual(&intersectbuf, "",
940 : : attname, fk_period_type,
941 : 86 : riinfo->period_intersect_oper,
942 : : paramname, pk_period_type);
943 : 86 : appendStringInfoChar(&intersectbuf, ')');
944 : :
945 : : /* Find the remaining history */
946 : 86 : initStringInfo(&replacementsbuf);
947 : 86 : appendStringInfoString(&replacementsbuf, "(SELECT pg_catalog.range_agg(r) FROM ");
948 : :
949 : 86 : quoteOneName(periodattname, RIAttName(pk_rel, riinfo->pk_attnums[riinfo->nkeys - 1]));
950 : 86 : quoteRelationName(pkrelname, pk_rel);
951 : 86 : appendStringInfo(&replacementsbuf, "(SELECT y.%s r FROM %s%s y",
952 : : periodattname, pk_only, pkrelname);
953 : :
954 : : /* Restrict pk rows to what matches */
955 : 86 : querysep = "WHERE";
956 [ + + ]: 258 : for (int i = 0; i < riinfo->nkeys; i++)
957 : : {
958 : 172 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
959 : :
960 : 172 : quoteOneName(attname,
961 : 172 : RIAttName(pk_rel, riinfo->pk_attnums[i]));
962 : 172 : sprintf(paramname, "$%d", i + 1);
963 : 172 : ri_GenerateQual(&replacementsbuf, querysep,
964 : : paramname, pk_type,
965 : 172 : riinfo->pp_eq_oprs[i],
966 : : attname, pk_type);
967 : 172 : querysep = "AND";
968 : 172 : queryoids[i] = pk_type;
969 : : }
970 : 86 : appendStringInfoString(&replacementsbuf, " FOR KEY SHARE OF y) y2)");
971 : :
972 : 86 : ri_GenerateQual(&querybuf, "",
973 : 86 : intersectbuf.data, fk_period_type,
974 : 86 : riinfo->agged_period_contained_by_oper,
975 : 86 : replacementsbuf.data, ANYMULTIRANGEOID);
976 : : /* end of coalesce: */
977 : 86 : appendStringInfoString(&querybuf, ", false)");
978 : : }
979 : :
980 : 315 : appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
981 : :
982 : : /* Prepare and save the plan */
983 : 315 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
984 : : &qkey, fk_rel, pk_rel);
985 : : }
986 : :
987 : : /*
988 : : * We have a plan now. Run it to check for existing references.
989 : : */
990 : 730 : ri_PerformCheck(riinfo, &qkey, qplan,
991 : : fk_rel, pk_rel,
992 : : oldslot, NULL,
993 : : !is_no_action,
994 : : true, /* must detect new rows */
995 : 730 : SPI_OK_SELECT);
996 : :
997 [ - + ]: 416 : if (SPI_finish() != SPI_OK_FINISH)
998 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
999 : :
1000 : 416 : table_close(fk_rel, RowShareLock);
1001 : :
1002 : 416 : return PointerGetDatum(NULL);
1003 : : }
1004 : :
1005 : :
1006 : : /*
1007 : : * RI_FKey_cascade_del -
1008 : : *
1009 : : * Cascaded delete foreign key references at delete event on PK table.
1010 : : */
1011 : : Datum
1012 : 98 : RI_FKey_cascade_del(PG_FUNCTION_ARGS)
1013 : : {
1014 : 98 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
1015 : : const RI_ConstraintInfo *riinfo;
1016 : : Relation fk_rel;
1017 : : Relation pk_rel;
1018 : : TupleTableSlot *oldslot;
1019 : : RI_QueryKey qkey;
1020 : : SPIPlanPtr qplan;
1021 : :
1022 : : /* Check that this is a valid trigger call on the right time and event. */
1023 : 98 : ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);
1024 : :
1025 : 98 : riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1026 : : trigdata->tg_relation, true);
1027 : :
1028 : : /*
1029 : : * Get the relation descriptors of the FK and PK tables and the old tuple.
1030 : : *
1031 : : * fk_rel is opened in RowExclusiveLock mode since that's what our
1032 : : * eventual DELETE will get on it.
1033 : : */
1034 : 98 : fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1035 : 98 : pk_rel = trigdata->tg_relation;
1036 : 98 : oldslot = trigdata->tg_trigslot;
1037 : :
1038 : 98 : SPI_connect();
1039 : :
1040 : : /* Fetch or prepare a saved plan for the cascaded delete */
1041 : 98 : ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONDELETE);
1042 : :
1043 [ + + ]: 98 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1044 : : {
1045 : : StringInfoData querybuf;
1046 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1047 : : char attname[MAX_QUOTED_NAME_LEN];
1048 : : char paramname[16];
1049 : : const char *querysep;
1050 : : Oid queryoids[RI_MAX_NUMKEYS];
1051 : : const char *fk_only;
1052 : :
1053 : : /* ----------
1054 : : * The query string built is
1055 : : * DELETE FROM [ONLY] <fktable> WHERE $1 = fkatt1 [AND ...]
1056 : : * The type id's for the $ parameters are those of the
1057 : : * corresponding PK attributes.
1058 : : * ----------
1059 : : */
1060 : 58 : initStringInfo(&querybuf);
1061 : 116 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1062 [ + + ]: 58 : "" : "ONLY ";
1063 : 58 : quoteRelationName(fkrelname, fk_rel);
1064 : 58 : appendStringInfo(&querybuf, "DELETE FROM %s%s",
1065 : : fk_only, fkrelname);
1066 : 58 : querysep = "WHERE";
1067 [ + + ]: 128 : for (int i = 0; i < riinfo->nkeys; i++)
1068 : : {
1069 : 70 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1070 : 70 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1071 : :
1072 : 70 : quoteOneName(attname,
1073 : 70 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1074 : 70 : sprintf(paramname, "$%d", i + 1);
1075 : 70 : ri_GenerateQual(&querybuf, querysep,
1076 : : paramname, pk_type,
1077 : 70 : riinfo->pf_eq_oprs[i],
1078 : : attname, fk_type);
1079 : 70 : querysep = "AND";
1080 : 70 : queryoids[i] = pk_type;
1081 : : }
1082 : :
1083 : : /* Prepare and save the plan */
1084 : 58 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1085 : : &qkey, fk_rel, pk_rel);
1086 : : }
1087 : :
1088 : : /*
1089 : : * We have a plan now. Build up the arguments from the key values in the
1090 : : * deleted PK tuple and delete the referencing rows
1091 : : */
1092 : 98 : ri_PerformCheck(riinfo, &qkey, qplan,
1093 : : fk_rel, pk_rel,
1094 : : oldslot, NULL,
1095 : : false,
1096 : : true, /* must detect new rows */
1097 : : SPI_OK_DELETE);
1098 : :
1099 [ - + ]: 97 : if (SPI_finish() != SPI_OK_FINISH)
1100 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
1101 : :
1102 : 97 : table_close(fk_rel, RowExclusiveLock);
1103 : :
1104 : 97 : return PointerGetDatum(NULL);
1105 : : }
1106 : :
1107 : :
1108 : : /*
1109 : : * RI_FKey_cascade_upd -
1110 : : *
1111 : : * Cascaded update foreign key references at update event on PK table.
1112 : : */
1113 : : Datum
1114 : 144 : RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
1115 : : {
1116 : 144 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
1117 : : const RI_ConstraintInfo *riinfo;
1118 : : Relation fk_rel;
1119 : : Relation pk_rel;
1120 : : TupleTableSlot *newslot;
1121 : : TupleTableSlot *oldslot;
1122 : : RI_QueryKey qkey;
1123 : : SPIPlanPtr qplan;
1124 : :
1125 : : /* Check that this is a valid trigger call on the right time and event. */
1126 : 144 : ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);
1127 : :
1128 : 144 : riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1129 : : trigdata->tg_relation, true);
1130 : :
1131 : : /*
1132 : : * Get the relation descriptors of the FK and PK tables and the new and
1133 : : * old tuple.
1134 : : *
1135 : : * fk_rel is opened in RowExclusiveLock mode since that's what our
1136 : : * eventual UPDATE will get on it.
1137 : : */
1138 : 144 : fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1139 : 144 : pk_rel = trigdata->tg_relation;
1140 : 144 : newslot = trigdata->tg_newslot;
1141 : 144 : oldslot = trigdata->tg_trigslot;
1142 : :
1143 : 144 : SPI_connect();
1144 : :
1145 : : /* Fetch or prepare a saved plan for the cascaded update */
1146 : 144 : ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_ONUPDATE);
1147 : :
1148 [ + + ]: 144 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1149 : : {
1150 : : StringInfoData querybuf;
1151 : : StringInfoData qualbuf;
1152 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1153 : : char attname[MAX_QUOTED_NAME_LEN];
1154 : : char paramname[16];
1155 : : const char *querysep;
1156 : : const char *qualsep;
1157 : : Oid queryoids[RI_MAX_NUMKEYS * 2];
1158 : : const char *fk_only;
1159 : :
1160 : : /* ----------
1161 : : * The query string built is
1162 : : * UPDATE [ONLY] <fktable> SET fkatt1 = $1 [, ...]
1163 : : * WHERE $n = fkatt1 [AND ...]
1164 : : * The type id's for the $ parameters are those of the
1165 : : * corresponding PK attributes. Note that we are assuming
1166 : : * there is an assignment cast from the PK to the FK type;
1167 : : * else the parser will fail.
1168 : : * ----------
1169 : : */
1170 : 84 : initStringInfo(&querybuf);
1171 : 84 : initStringInfo(&qualbuf);
1172 : 168 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1173 [ + + ]: 84 : "" : "ONLY ";
1174 : 84 : quoteRelationName(fkrelname, fk_rel);
1175 : 84 : appendStringInfo(&querybuf, "UPDATE %s%s SET",
1176 : : fk_only, fkrelname);
1177 : 84 : querysep = "";
1178 : 84 : qualsep = "WHERE";
1179 [ + + ]: 184 : for (int i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
1180 : : {
1181 : 100 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1182 : 100 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1183 : :
1184 : 100 : quoteOneName(attname,
1185 : 100 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1186 : 100 : appendStringInfo(&querybuf,
1187 : : "%s %s = $%d",
1188 : : querysep, attname, i + 1);
1189 : 100 : sprintf(paramname, "$%d", j + 1);
1190 : 100 : ri_GenerateQual(&qualbuf, qualsep,
1191 : : paramname, pk_type,
1192 : 100 : riinfo->pf_eq_oprs[i],
1193 : : attname, fk_type);
1194 : 100 : querysep = ",";
1195 : 100 : qualsep = "AND";
1196 : 100 : queryoids[i] = pk_type;
1197 : 100 : queryoids[j] = pk_type;
1198 : : }
1199 : 84 : appendBinaryStringInfo(&querybuf, qualbuf.data, qualbuf.len);
1200 : :
1201 : : /* Prepare and save the plan */
1202 : 84 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
1203 : : &qkey, fk_rel, pk_rel);
1204 : : }
1205 : :
1206 : : /*
1207 : : * We have a plan now. Run it to update the existing references.
1208 : : */
1209 : 144 : ri_PerformCheck(riinfo, &qkey, qplan,
1210 : : fk_rel, pk_rel,
1211 : : oldslot, newslot,
1212 : : false,
1213 : : true, /* must detect new rows */
1214 : : SPI_OK_UPDATE);
1215 : :
1216 [ - + ]: 144 : if (SPI_finish() != SPI_OK_FINISH)
1217 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
1218 : :
1219 : 144 : table_close(fk_rel, RowExclusiveLock);
1220 : :
1221 : 144 : return PointerGetDatum(NULL);
1222 : : }
1223 : :
1224 : :
1225 : : /*
1226 : : * RI_FKey_setnull_del -
1227 : : *
1228 : : * Set foreign key references to NULL values at delete event on PK table.
1229 : : */
1230 : : Datum
1231 : 65 : RI_FKey_setnull_del(PG_FUNCTION_ARGS)
1232 : : {
1233 : : /* Check that this is a valid trigger call on the right time and event. */
1234 : 65 : ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);
1235 : :
1236 : : /* Share code with UPDATE case */
1237 : 65 : return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_DELETE);
1238 : : }
1239 : :
1240 : : /*
1241 : : * RI_FKey_setnull_upd -
1242 : : *
1243 : : * Set foreign key references to NULL at update event on PK table.
1244 : : */
1245 : : Datum
1246 : 20 : RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
1247 : : {
1248 : : /* Check that this is a valid trigger call on the right time and event. */
1249 : 20 : ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);
1250 : :
1251 : : /* Share code with DELETE case */
1252 : 20 : return ri_set((TriggerData *) fcinfo->context, true, RI_TRIGTYPE_UPDATE);
1253 : : }
1254 : :
1255 : : /*
1256 : : * RI_FKey_setdefault_del -
1257 : : *
1258 : : * Set foreign key references to defaults at delete event on PK table.
1259 : : */
1260 : : Datum
1261 : 56 : RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
1262 : : {
1263 : : /* Check that this is a valid trigger call on the right time and event. */
1264 : 56 : ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);
1265 : :
1266 : : /* Share code with UPDATE case */
1267 : 56 : return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_DELETE);
1268 : : }
1269 : :
1270 : : /*
1271 : : * RI_FKey_setdefault_upd -
1272 : : *
1273 : : * Set foreign key references to defaults at update event on PK table.
1274 : : */
1275 : : Datum
1276 : 32 : RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
1277 : : {
1278 : : /* Check that this is a valid trigger call on the right time and event. */
1279 : 32 : ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);
1280 : :
1281 : : /* Share code with DELETE case */
1282 : 32 : return ri_set((TriggerData *) fcinfo->context, false, RI_TRIGTYPE_UPDATE);
1283 : : }
1284 : :
1285 : : /*
1286 : : * ri_set -
1287 : : *
1288 : : * Common code for ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE SET
1289 : : * NULL, and ON UPDATE SET DEFAULT.
1290 : : */
1291 : : static Datum
1292 : 173 : ri_set(TriggerData *trigdata, bool is_set_null, int tgkind)
1293 : : {
1294 : : const RI_ConstraintInfo *riinfo;
1295 : : Relation fk_rel;
1296 : : Relation pk_rel;
1297 : : TupleTableSlot *oldslot;
1298 : : RI_QueryKey qkey;
1299 : : SPIPlanPtr qplan;
1300 : : int32 queryno;
1301 : :
1302 : 173 : riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
1303 : : trigdata->tg_relation, true);
1304 : :
1305 : : /*
1306 : : * Get the relation descriptors of the FK and PK tables and the old tuple.
1307 : : *
1308 : : * fk_rel is opened in RowExclusiveLock mode since that's what our
1309 : : * eventual UPDATE will get on it.
1310 : : */
1311 : 173 : fk_rel = table_open(riinfo->fk_relid, RowExclusiveLock);
1312 : 173 : pk_rel = trigdata->tg_relation;
1313 : 173 : oldslot = trigdata->tg_trigslot;
1314 : :
1315 : 173 : SPI_connect();
1316 : :
1317 : : /*
1318 : : * Fetch or prepare a saved plan for the trigger.
1319 : : */
1320 [ + + - ]: 173 : switch (tgkind)
1321 : : {
1322 : 52 : case RI_TRIGTYPE_UPDATE:
1323 : 52 : queryno = is_set_null
1324 : : ? RI_PLAN_SETNULL_ONUPDATE
1325 [ + + ]: 52 : : RI_PLAN_SETDEFAULT_ONUPDATE;
1326 : 52 : break;
1327 : 121 : case RI_TRIGTYPE_DELETE:
1328 : 121 : queryno = is_set_null
1329 : : ? RI_PLAN_SETNULL_ONDELETE
1330 [ + + ]: 121 : : RI_PLAN_SETDEFAULT_ONDELETE;
1331 : 121 : break;
1332 : 0 : default:
1333 [ # # ]: 0 : elog(ERROR, "invalid tgkind passed to ri_set");
1334 : : }
1335 : :
1336 : 173 : ri_BuildQueryKey(&qkey, riinfo, queryno);
1337 : :
1338 [ + + ]: 173 : if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
1339 : : {
1340 : : StringInfoData querybuf;
1341 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1342 : : char attname[MAX_QUOTED_NAME_LEN];
1343 : : char paramname[16];
1344 : : const char *querysep;
1345 : : const char *qualsep;
1346 : : Oid queryoids[RI_MAX_NUMKEYS];
1347 : : const char *fk_only;
1348 : : int num_cols_to_set;
1349 : : const int16 *set_cols;
1350 : :
1351 [ + + - ]: 101 : switch (tgkind)
1352 : : {
1353 : 32 : case RI_TRIGTYPE_UPDATE:
1354 : 32 : num_cols_to_set = riinfo->nkeys;
1355 : 32 : set_cols = riinfo->fk_attnums;
1356 : 32 : break;
1357 : 69 : case RI_TRIGTYPE_DELETE:
1358 : :
1359 : : /*
1360 : : * If confdelsetcols are present, then we only update the
1361 : : * columns specified in that array, otherwise we update all
1362 : : * the referencing columns.
1363 : : */
1364 [ + + ]: 69 : if (riinfo->ndelsetcols != 0)
1365 : : {
1366 : 16 : num_cols_to_set = riinfo->ndelsetcols;
1367 : 16 : set_cols = riinfo->confdelsetcols;
1368 : : }
1369 : : else
1370 : : {
1371 : 53 : num_cols_to_set = riinfo->nkeys;
1372 : 53 : set_cols = riinfo->fk_attnums;
1373 : : }
1374 : 69 : break;
1375 : 0 : default:
1376 [ # # ]: 0 : elog(ERROR, "invalid tgkind passed to ri_set");
1377 : : }
1378 : :
1379 : : /* ----------
1380 : : * The query string built is
1381 : : * UPDATE [ONLY] <fktable> SET fkatt1 = {NULL|DEFAULT} [, ...]
1382 : : * WHERE $1 = fkatt1 [AND ...]
1383 : : * The type id's for the $ parameters are those of the
1384 : : * corresponding PK attributes.
1385 : : * ----------
1386 : : */
1387 : 101 : initStringInfo(&querybuf);
1388 : 202 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1389 [ + + ]: 101 : "" : "ONLY ";
1390 : 101 : quoteRelationName(fkrelname, fk_rel);
1391 : 101 : appendStringInfo(&querybuf, "UPDATE %s%s SET",
1392 : : fk_only, fkrelname);
1393 : :
1394 : : /*
1395 : : * Add assignment clauses
1396 : : */
1397 : 101 : querysep = "";
1398 [ + + ]: 267 : for (int i = 0; i < num_cols_to_set; i++)
1399 : : {
1400 : 166 : quoteOneName(attname, RIAttName(fk_rel, set_cols[i]));
1401 [ + + ]: 166 : appendStringInfo(&querybuf,
1402 : : "%s %s = %s",
1403 : : querysep, attname,
1404 : : is_set_null ? "NULL" : "DEFAULT");
1405 : 166 : querysep = ",";
1406 : : }
1407 : :
1408 : : /*
1409 : : * Add WHERE clause
1410 : : */
1411 : 101 : qualsep = "WHERE";
1412 [ + + ]: 283 : for (int i = 0; i < riinfo->nkeys; i++)
1413 : : {
1414 : 182 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1415 : 182 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1416 : :
1417 : 182 : quoteOneName(attname,
1418 : 182 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1419 : :
1420 : 182 : sprintf(paramname, "$%d", i + 1);
1421 : 182 : ri_GenerateQual(&querybuf, qualsep,
1422 : : paramname, pk_type,
1423 : 182 : riinfo->pf_eq_oprs[i],
1424 : : attname, fk_type);
1425 : 182 : qualsep = "AND";
1426 : 182 : queryoids[i] = pk_type;
1427 : : }
1428 : :
1429 : : /* Prepare and save the plan */
1430 : 101 : qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
1431 : : &qkey, fk_rel, pk_rel);
1432 : : }
1433 : :
1434 : : /*
1435 : : * We have a plan now. Run it to update the existing references.
1436 : : */
1437 : 173 : ri_PerformCheck(riinfo, &qkey, qplan,
1438 : : fk_rel, pk_rel,
1439 : : oldslot, NULL,
1440 : : false,
1441 : : true, /* must detect new rows */
1442 : : SPI_OK_UPDATE);
1443 : :
1444 [ - + ]: 172 : if (SPI_finish() != SPI_OK_FINISH)
1445 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
1446 : :
1447 : 172 : table_close(fk_rel, RowExclusiveLock);
1448 : :
1449 [ + + ]: 172 : if (is_set_null)
1450 : 84 : return PointerGetDatum(NULL);
1451 : : else
1452 : : {
1453 : : /*
1454 : : * If we just deleted or updated the PK row whose key was equal to the
1455 : : * FK columns' default values, and a referencing row exists in the FK
1456 : : * table, we would have updated that row to the same values it already
1457 : : * had --- and RI_FKey_fk_upd_check_required would hence believe no
1458 : : * check is necessary. So we need to do another lookup now and in
1459 : : * case a reference still exists, abort the operation. That is
1460 : : * already implemented in the NO ACTION trigger, so just run it. (This
1461 : : * recheck is only needed in the SET DEFAULT case, since CASCADE would
1462 : : * remove such rows in case of a DELETE operation or would change the
1463 : : * FK key values in case of an UPDATE, while SET NULL is certain to
1464 : : * result in rows that satisfy the FK constraint.)
1465 : : */
1466 : 88 : return ri_restrict(trigdata, true);
1467 : : }
1468 : : }
1469 : :
1470 : :
1471 : : /*
1472 : : * RI_FKey_pk_upd_check_required -
1473 : : *
1474 : : * Check if we really need to fire the RI trigger for an update or delete to a PK
1475 : : * relation. This is called by the AFTER trigger queue manager to see if
1476 : : * it can skip queuing an instance of an RI trigger. Returns true if the
1477 : : * trigger must be fired, false if we can prove the constraint will still
1478 : : * be satisfied.
1479 : : *
1480 : : * newslot will be NULL if this is called for a delete.
1481 : : */
1482 : : bool
1483 : 1520 : RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel,
1484 : : TupleTableSlot *oldslot, TupleTableSlot *newslot)
1485 : : {
1486 : : const RI_ConstraintInfo *riinfo;
1487 : :
1488 : 1520 : riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1489 : :
1490 : : /*
1491 : : * If any old key value is NULL, the row could not have been referenced by
1492 : : * an FK row, so no check is needed.
1493 : : */
1494 [ + + ]: 1520 : if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1495 : 4 : return false;
1496 : :
1497 : : /* If all old and new key values are equal, no check is needed */
1498 [ + + + + ]: 1516 : if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1499 : 292 : return false;
1500 : :
1501 : : /* Else we need to fire the trigger. */
1502 : 1224 : return true;
1503 : : }
1504 : :
1505 : : /*
1506 : : * RI_FKey_fk_upd_check_required -
1507 : : *
1508 : : * Check if we really need to fire the RI trigger for an update to an FK
1509 : : * relation. This is called by the AFTER trigger queue manager to see if
1510 : : * it can skip queuing an instance of an RI trigger. Returns true if the
1511 : : * trigger must be fired, false if we can prove the constraint will still
1512 : : * be satisfied.
1513 : : */
1514 : : bool
1515 : 670 : RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel,
1516 : : TupleTableSlot *oldslot, TupleTableSlot *newslot)
1517 : : {
1518 : : const RI_ConstraintInfo *riinfo;
1519 : : int ri_nullcheck;
1520 : :
1521 : : /*
1522 : : * AfterTriggerSaveEvent() handles things such that this function is never
1523 : : * called for partitioned tables.
1524 : : */
1525 : : Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1526 : :
1527 : 670 : riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1528 : :
1529 : 670 : ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1530 : :
1531 : : /*
1532 : : * If all new key values are NULL, the row satisfies the constraint, so no
1533 : : * check is needed.
1534 : : */
1535 [ + + ]: 670 : if (ri_nullcheck == RI_KEYS_ALL_NULL)
1536 : 84 : return false;
1537 : :
1538 : : /*
1539 : : * If some new key values are NULL, the behavior depends on the match
1540 : : * type.
1541 : : */
1542 [ + + ]: 586 : else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1543 : : {
1544 [ + - + - ]: 20 : switch (riinfo->confmatchtype)
1545 : : {
1546 : 16 : case FKCONSTR_MATCH_SIMPLE:
1547 : :
1548 : : /*
1549 : : * If any new key value is NULL, the row must satisfy the
1550 : : * constraint, so no check is needed.
1551 : : */
1552 : 16 : return false;
1553 : :
1554 : 0 : case FKCONSTR_MATCH_PARTIAL:
1555 : :
1556 : : /*
1557 : : * Don't know, must run full check.
1558 : : */
1559 : 0 : break;
1560 : :
1561 : 4 : case FKCONSTR_MATCH_FULL:
1562 : :
1563 : : /*
1564 : : * If some new key values are NULL, the row fails the
1565 : : * constraint. We must not throw error here, because the row
1566 : : * might get invalidated before the constraint is to be
1567 : : * checked, but we should queue the event to apply the check
1568 : : * later.
1569 : : */
1570 : 4 : return true;
1571 : : }
1572 : : }
1573 : :
1574 : : /*
1575 : : * Continues here for no new key values are NULL, or we couldn't decide
1576 : : * yet.
1577 : : */
1578 : :
1579 : : /*
1580 : : * If the original row was inserted by our own transaction, we must fire
1581 : : * the trigger whether or not the keys are equal. This is because our
1582 : : * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1583 : : * not do anything; so we had better do the UPDATE check. (We could skip
1584 : : * this if we knew the INSERT trigger already fired, but there is no easy
1585 : : * way to know that.)
1586 : : */
1587 [ + + ]: 566 : if (slot_is_current_xact_tuple(oldslot))
1588 : 77 : return true;
1589 : :
1590 : : /* If all old and new key values are equal, no check is needed */
1591 [ + + ]: 489 : if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1592 : 262 : return false;
1593 : :
1594 : : /* Else we need to fire the trigger. */
1595 : 227 : return true;
1596 : : }
1597 : :
1598 : : /*
1599 : : * RI_Initial_Check -
1600 : : *
1601 : : * Check an entire table for non-matching values using a single query.
1602 : : * This is not a trigger procedure, but is called during ALTER TABLE
1603 : : * ADD FOREIGN KEY to validate the initial table contents.
1604 : : *
1605 : : * We expect that the caller has made provision to prevent any problems
1606 : : * caused by concurrent actions. This could be either by locking rel and
1607 : : * pkrel at ShareRowExclusiveLock or higher, or by otherwise ensuring
1608 : : * that triggers implementing the checks are already active.
1609 : : * Hence, we do not need to lock individual rows for the check.
1610 : : *
1611 : : * If the check fails because the current user doesn't have permissions
1612 : : * to read both tables, return false to let our caller know that they will
1613 : : * need to do something else to check the constraint.
1614 : : */
1615 : : bool
1616 : 776 : RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
1617 : : {
1618 : : const RI_ConstraintInfo *riinfo;
1619 : : StringInfoData querybuf;
1620 : : char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1621 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1622 : : char pkattname[MAX_QUOTED_NAME_LEN + 3];
1623 : : char fkattname[MAX_QUOTED_NAME_LEN + 3];
1624 : : RangeTblEntry *rte;
1625 : : RTEPermissionInfo *pk_perminfo;
1626 : : RTEPermissionInfo *fk_perminfo;
1627 : 776 : List *rtes = NIL;
1628 : 776 : List *perminfos = NIL;
1629 : : const char *sep;
1630 : : const char *fk_only;
1631 : : const char *pk_only;
1632 : : int save_nestlevel;
1633 : : char workmembuf[32];
1634 : : int spi_result;
1635 : : SPIPlanPtr qplan;
1636 : :
1637 : 776 : riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1638 : :
1639 : : /*
1640 : : * Check to make sure current user has enough permissions to do the test
1641 : : * query. (If not, caller can fall back to the trigger method, which
1642 : : * works because it changes user IDs on the fly.)
1643 : : *
1644 : : * XXX are there any other show-stopper conditions to check?
1645 : : */
1646 : 776 : pk_perminfo = makeNode(RTEPermissionInfo);
1647 : 776 : pk_perminfo->relid = RelationGetRelid(pk_rel);
1648 : 776 : pk_perminfo->requiredPerms = ACL_SELECT;
1649 : 776 : perminfos = lappend(perminfos, pk_perminfo);
1650 : 776 : rte = makeNode(RangeTblEntry);
1651 : 776 : rte->rtekind = RTE_RELATION;
1652 : 776 : rte->relid = RelationGetRelid(pk_rel);
1653 : 776 : rte->relkind = pk_rel->rd_rel->relkind;
1654 : 776 : rte->rellockmode = AccessShareLock;
1655 : 776 : rte->perminfoindex = list_length(perminfos);
1656 : 776 : rtes = lappend(rtes, rte);
1657 : :
1658 : 776 : fk_perminfo = makeNode(RTEPermissionInfo);
1659 : 776 : fk_perminfo->relid = RelationGetRelid(fk_rel);
1660 : 776 : fk_perminfo->requiredPerms = ACL_SELECT;
1661 : 776 : perminfos = lappend(perminfos, fk_perminfo);
1662 : 776 : rte = makeNode(RangeTblEntry);
1663 : 776 : rte->rtekind = RTE_RELATION;
1664 : 776 : rte->relid = RelationGetRelid(fk_rel);
1665 : 776 : rte->relkind = fk_rel->rd_rel->relkind;
1666 : 776 : rte->rellockmode = AccessShareLock;
1667 : 776 : rte->perminfoindex = list_length(perminfos);
1668 : 776 : rtes = lappend(rtes, rte);
1669 : :
1670 [ + + ]: 1837 : for (int i = 0; i < riinfo->nkeys; i++)
1671 : : {
1672 : : int attno;
1673 : :
1674 : 1061 : attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1675 : 1061 : pk_perminfo->selectedCols = bms_add_member(pk_perminfo->selectedCols, attno);
1676 : :
1677 : 1061 : attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1678 : 1061 : fk_perminfo->selectedCols = bms_add_member(fk_perminfo->selectedCols, attno);
1679 : : }
1680 : :
1681 [ + + ]: 776 : if (!ExecCheckPermissions(rtes, perminfos, false))
1682 : 41 : return false;
1683 : :
1684 : : /*
1685 : : * Also punt if RLS is enabled on either table unless this role has the
1686 : : * bypassrls right or is the table owner of the table(s) involved which
1687 : : * have RLS enabled.
1688 : : */
1689 [ + + ]: 735 : if (!has_bypassrls_privilege(GetUserId()) &&
1690 [ + - ]: 8 : ((pk_rel->rd_rel->relrowsecurity &&
1691 [ - + ]: 8 : !object_ownercheck(RelationRelationId, RelationGetRelid(pk_rel),
1692 : 0 : GetUserId())) ||
1693 [ # # ]: 0 : (fk_rel->rd_rel->relrowsecurity &&
1694 [ # # ]: 0 : !object_ownercheck(RelationRelationId, RelationGetRelid(fk_rel),
1695 : : GetUserId()))))
1696 : 8 : return false;
1697 : :
1698 : : /*----------
1699 : : * The query string built is:
1700 : : * SELECT fk.keycols FROM [ONLY] relname fk
1701 : : * LEFT OUTER JOIN [ONLY] pkrelname pk
1702 : : * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1703 : : * WHERE pk.pkkeycol1 IS NULL AND
1704 : : * For MATCH SIMPLE:
1705 : : * (fk.keycol1 IS NOT NULL [AND ...])
1706 : : * For MATCH FULL:
1707 : : * (fk.keycol1 IS NOT NULL [OR ...])
1708 : : *
1709 : : * We attach COLLATE clauses to the operators when comparing columns
1710 : : * that have different collations.
1711 : : *----------
1712 : : */
1713 : 727 : initStringInfo(&querybuf);
1714 : 727 : appendStringInfoString(&querybuf, "SELECT ");
1715 : 727 : sep = "";
1716 [ + + ]: 1715 : for (int i = 0; i < riinfo->nkeys; i++)
1717 : : {
1718 : 988 : quoteOneName(fkattname,
1719 : 988 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1720 : 988 : appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1721 : 988 : sep = ", ";
1722 : : }
1723 : :
1724 : 727 : quoteRelationName(pkrelname, pk_rel);
1725 : 727 : quoteRelationName(fkrelname, fk_rel);
1726 : 1454 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1727 [ - + ]: 727 : "" : "ONLY ";
1728 : 1454 : pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1729 [ + + ]: 727 : "" : "ONLY ";
1730 : 727 : appendStringInfo(&querybuf,
1731 : : " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1732 : : fk_only, fkrelname, pk_only, pkrelname);
1733 : :
1734 : 727 : strcpy(pkattname, "pk.");
1735 : 727 : strcpy(fkattname, "fk.");
1736 : 727 : sep = "(";
1737 [ + + ]: 1715 : for (int i = 0; i < riinfo->nkeys; i++)
1738 : : {
1739 : 988 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1740 : 988 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1741 : 988 : Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1742 : 988 : Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1743 : :
1744 : 988 : quoteOneName(pkattname + 3,
1745 : 988 : RIAttName(pk_rel, riinfo->pk_attnums[i]));
1746 : 988 : quoteOneName(fkattname + 3,
1747 : 988 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1748 : 988 : ri_GenerateQual(&querybuf, sep,
1749 : : pkattname, pk_type,
1750 : 988 : riinfo->pf_eq_oprs[i],
1751 : : fkattname, fk_type);
1752 [ + + ]: 988 : if (pk_coll != fk_coll)
1753 : 8 : ri_GenerateQualCollation(&querybuf, pk_coll);
1754 : 988 : sep = "AND";
1755 : : }
1756 : :
1757 : : /*
1758 : : * It's sufficient to test any one pk attribute for null to detect a join
1759 : : * failure.
1760 : : */
1761 : 727 : quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1762 : 727 : appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1763 : :
1764 : 727 : sep = "";
1765 [ + + ]: 1715 : for (int i = 0; i < riinfo->nkeys; i++)
1766 : : {
1767 : 988 : quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1768 : 988 : appendStringInfo(&querybuf,
1769 : : "%sfk.%s IS NOT NULL",
1770 : : sep, fkattname);
1771 [ + + - ]: 988 : switch (riinfo->confmatchtype)
1772 : : {
1773 : 914 : case FKCONSTR_MATCH_SIMPLE:
1774 : 914 : sep = " AND ";
1775 : 914 : break;
1776 : 74 : case FKCONSTR_MATCH_FULL:
1777 : 74 : sep = " OR ";
1778 : 74 : break;
1779 : : }
1780 : : }
1781 : 727 : appendStringInfoChar(&querybuf, ')');
1782 : :
1783 : : /*
1784 : : * Temporarily increase work_mem so that the check query can be executed
1785 : : * more efficiently. It seems okay to do this because the query is simple
1786 : : * enough to not use a multiple of work_mem, and one typically would not
1787 : : * have many large foreign-key validations happening concurrently. So
1788 : : * this seems to meet the criteria for being considered a "maintenance"
1789 : : * operation, and accordingly we use maintenance_work_mem. However, we
1790 : : * must also set hash_mem_multiplier to 1, since it is surely not okay to
1791 : : * let that get applied to the maintenance_work_mem value.
1792 : : *
1793 : : * We use the equivalent of a function SET option to allow the setting to
1794 : : * persist for exactly the duration of the check query. guc.c also takes
1795 : : * care of undoing the setting on error.
1796 : : */
1797 : 727 : save_nestlevel = NewGUCNestLevel();
1798 : :
1799 : 727 : snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1800 : 727 : (void) set_config_option("work_mem", workmembuf,
1801 : : PGC_USERSET, PGC_S_SESSION,
1802 : : GUC_ACTION_SAVE, true, 0, false);
1803 : 727 : (void) set_config_option("hash_mem_multiplier", "1",
1804 : : PGC_USERSET, PGC_S_SESSION,
1805 : : GUC_ACTION_SAVE, true, 0, false);
1806 : :
1807 : 727 : SPI_connect();
1808 : :
1809 : : /*
1810 : : * Generate the plan. We don't need to cache it, and there are no
1811 : : * arguments to the plan.
1812 : : */
1813 : 727 : qplan = SPI_prepare(querybuf.data, 0, NULL);
1814 : :
1815 [ - + ]: 727 : if (qplan == NULL)
1816 [ # # ]: 0 : elog(ERROR, "SPI_prepare returned %s for %s",
1817 : : SPI_result_code_string(SPI_result), querybuf.data);
1818 : :
1819 : : /*
1820 : : * Run the plan. For safety we force a current snapshot to be used. (In
1821 : : * transaction-snapshot mode, this arguably violates transaction isolation
1822 : : * rules, but we really haven't got much choice.) We don't need to
1823 : : * register the snapshot, because SPI_execute_snapshot will see to it. We
1824 : : * need at most one tuple returned, so pass limit = 1.
1825 : : */
1826 : 727 : spi_result = SPI_execute_snapshot(qplan,
1827 : : NULL, NULL,
1828 : : GetLatestSnapshot(),
1829 : : InvalidSnapshot,
1830 : : true, false, 1);
1831 : :
1832 : : /* Check result */
1833 [ - + ]: 727 : if (spi_result != SPI_OK_SELECT)
1834 [ # # ]: 0 : elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1835 : :
1836 : : /* Did we find a tuple violating the constraint? */
1837 [ + + ]: 727 : if (SPI_processed > 0)
1838 : : {
1839 : : TupleTableSlot *slot;
1840 : 47 : HeapTuple tuple = SPI_tuptable->vals[0];
1841 : 47 : TupleDesc tupdesc = SPI_tuptable->tupdesc;
1842 : : RI_ConstraintInfo fake_riinfo;
1843 : :
1844 : 47 : slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1845 : :
1846 : 47 : heap_deform_tuple(tuple, tupdesc,
1847 : : slot->tts_values, slot->tts_isnull);
1848 : 47 : ExecStoreVirtualTuple(slot);
1849 : :
1850 : : /*
1851 : : * The columns to look at in the result tuple are 1..N, not whatever
1852 : : * they are in the fk_rel. Hack up riinfo so that the subroutines
1853 : : * called here will behave properly.
1854 : : *
1855 : : * In addition to this, we have to pass the correct tupdesc to
1856 : : * ri_ReportViolation, overriding its normal habit of using the pk_rel
1857 : : * or fk_rel's tupdesc.
1858 : : */
1859 : 47 : memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1860 [ + + ]: 110 : for (int i = 0; i < fake_riinfo.nkeys; i++)
1861 : 63 : fake_riinfo.fk_attnums[i] = i + 1;
1862 : :
1863 : : /*
1864 : : * If it's MATCH FULL, and there are any nulls in the FK keys,
1865 : : * complain about that rather than the lack of a match. MATCH FULL
1866 : : * disallows partially-null FK rows.
1867 : : */
1868 [ + + + + ]: 67 : if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1869 : 20 : ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1870 [ + - ]: 8 : ereport(ERROR,
1871 : : (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1872 : : errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1873 : : RelationGetRelationName(fk_rel),
1874 : : NameStr(fake_riinfo.conname)),
1875 : : errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1876 : : errtableconstraint(fk_rel,
1877 : : NameStr(fake_riinfo.conname))));
1878 : :
1879 : : /*
1880 : : * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1881 : : * query, which isn't true, but will cause it to use
1882 : : * fake_riinfo.fk_attnums as we need.
1883 : : */
1884 : 39 : ri_ReportViolation(&fake_riinfo,
1885 : : pk_rel, fk_rel,
1886 : : slot, tupdesc,
1887 : : RI_PLAN_CHECK_LOOKUPPK, false, false);
1888 : :
1889 : : ExecDropSingleTupleTableSlot(slot);
1890 : : }
1891 : :
1892 [ - + ]: 680 : if (SPI_finish() != SPI_OK_FINISH)
1893 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
1894 : :
1895 : : /*
1896 : : * Restore work_mem and hash_mem_multiplier.
1897 : : */
1898 : 680 : AtEOXact_GUC(true, save_nestlevel);
1899 : :
1900 : 680 : return true;
1901 : : }
1902 : :
1903 : : /*
1904 : : * RI_PartitionRemove_Check -
1905 : : *
1906 : : * Verify no referencing values exist, when a partition is detached on
1907 : : * the referenced side of a foreign key constraint.
1908 : : */
1909 : : void
1910 : 65 : RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
1911 : : {
1912 : : const RI_ConstraintInfo *riinfo;
1913 : : StringInfoData querybuf;
1914 : : char *constraintDef;
1915 : : char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1916 : : char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1917 : : char pkattname[MAX_QUOTED_NAME_LEN + 3];
1918 : : char fkattname[MAX_QUOTED_NAME_LEN + 3];
1919 : : const char *sep;
1920 : : const char *fk_only;
1921 : : int save_nestlevel;
1922 : : char workmembuf[32];
1923 : : int spi_result;
1924 : : SPIPlanPtr qplan;
1925 : : int i;
1926 : :
1927 : 65 : riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1928 : :
1929 : : /*
1930 : : * We don't check permissions before displaying the error message, on the
1931 : : * assumption that the user detaching the partition must have enough
1932 : : * privileges to examine the table contents anyhow.
1933 : : */
1934 : :
1935 : : /*----------
1936 : : * The query string built is:
1937 : : * SELECT fk.keycols FROM [ONLY] relname fk
1938 : : * JOIN pkrelname pk
1939 : : * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1940 : : * WHERE (<partition constraint>) AND
1941 : : * For MATCH SIMPLE:
1942 : : * (fk.keycol1 IS NOT NULL [AND ...])
1943 : : * For MATCH FULL:
1944 : : * (fk.keycol1 IS NOT NULL [OR ...])
1945 : : *
1946 : : * We attach COLLATE clauses to the operators when comparing columns
1947 : : * that have different collations.
1948 : : *----------
1949 : : */
1950 : 65 : initStringInfo(&querybuf);
1951 : 65 : appendStringInfoString(&querybuf, "SELECT ");
1952 : 65 : sep = "";
1953 [ + + ]: 130 : for (i = 0; i < riinfo->nkeys; i++)
1954 : : {
1955 : 65 : quoteOneName(fkattname,
1956 : 65 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1957 : 65 : appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1958 : 65 : sep = ", ";
1959 : : }
1960 : :
1961 : 65 : quoteRelationName(pkrelname, pk_rel);
1962 : 65 : quoteRelationName(fkrelname, fk_rel);
1963 : 130 : fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1964 [ + + ]: 65 : "" : "ONLY ";
1965 : 65 : appendStringInfo(&querybuf,
1966 : : " FROM %s%s fk JOIN %s pk ON",
1967 : : fk_only, fkrelname, pkrelname);
1968 : 65 : strcpy(pkattname, "pk.");
1969 : 65 : strcpy(fkattname, "fk.");
1970 : 65 : sep = "(";
1971 [ + + ]: 130 : for (i = 0; i < riinfo->nkeys; i++)
1972 : : {
1973 : 65 : Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1974 : 65 : Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1975 : 65 : Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1976 : 65 : Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1977 : :
1978 : 65 : quoteOneName(pkattname + 3,
1979 : 65 : RIAttName(pk_rel, riinfo->pk_attnums[i]));
1980 : 65 : quoteOneName(fkattname + 3,
1981 : 65 : RIAttName(fk_rel, riinfo->fk_attnums[i]));
1982 : 65 : ri_GenerateQual(&querybuf, sep,
1983 : : pkattname, pk_type,
1984 : 65 : riinfo->pf_eq_oprs[i],
1985 : : fkattname, fk_type);
1986 [ - + ]: 65 : if (pk_coll != fk_coll)
1987 : 0 : ri_GenerateQualCollation(&querybuf, pk_coll);
1988 : 65 : sep = "AND";
1989 : : }
1990 : :
1991 : : /*
1992 : : * Start the WHERE clause with the partition constraint (except if this is
1993 : : * the default partition and there's no other partition, because the
1994 : : * partition constraint is the empty string in that case.)
1995 : : */
1996 : 65 : constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1997 [ + - + - ]: 65 : if (constraintDef && constraintDef[0] != '\0')
1998 : 65 : appendStringInfo(&querybuf, ") WHERE %s AND (",
1999 : : constraintDef);
2000 : : else
2001 : 0 : appendStringInfoString(&querybuf, ") WHERE (");
2002 : :
2003 : 65 : sep = "";
2004 [ + + ]: 130 : for (i = 0; i < riinfo->nkeys; i++)
2005 : : {
2006 : 65 : quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
2007 : 65 : appendStringInfo(&querybuf,
2008 : : "%sfk.%s IS NOT NULL",
2009 : : sep, fkattname);
2010 [ + - - ]: 65 : switch (riinfo->confmatchtype)
2011 : : {
2012 : 65 : case FKCONSTR_MATCH_SIMPLE:
2013 : 65 : sep = " AND ";
2014 : 65 : break;
2015 : 0 : case FKCONSTR_MATCH_FULL:
2016 : 0 : sep = " OR ";
2017 : 0 : break;
2018 : : }
2019 : : }
2020 : 65 : appendStringInfoChar(&querybuf, ')');
2021 : :
2022 : : /*
2023 : : * Temporarily increase work_mem so that the check query can be executed
2024 : : * more efficiently. It seems okay to do this because the query is simple
2025 : : * enough to not use a multiple of work_mem, and one typically would not
2026 : : * have many large foreign-key validations happening concurrently. So
2027 : : * this seems to meet the criteria for being considered a "maintenance"
2028 : : * operation, and accordingly we use maintenance_work_mem. However, we
2029 : : * must also set hash_mem_multiplier to 1, since it is surely not okay to
2030 : : * let that get applied to the maintenance_work_mem value.
2031 : : *
2032 : : * We use the equivalent of a function SET option to allow the setting to
2033 : : * persist for exactly the duration of the check query. guc.c also takes
2034 : : * care of undoing the setting on error.
2035 : : */
2036 : 65 : save_nestlevel = NewGUCNestLevel();
2037 : :
2038 : 65 : snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
2039 : 65 : (void) set_config_option("work_mem", workmembuf,
2040 : : PGC_USERSET, PGC_S_SESSION,
2041 : : GUC_ACTION_SAVE, true, 0, false);
2042 : 65 : (void) set_config_option("hash_mem_multiplier", "1",
2043 : : PGC_USERSET, PGC_S_SESSION,
2044 : : GUC_ACTION_SAVE, true, 0, false);
2045 : :
2046 : 65 : SPI_connect();
2047 : :
2048 : : /*
2049 : : * Generate the plan. We don't need to cache it, and there are no
2050 : : * arguments to the plan.
2051 : : */
2052 : 65 : qplan = SPI_prepare(querybuf.data, 0, NULL);
2053 : :
2054 [ - + ]: 65 : if (qplan == NULL)
2055 [ # # ]: 0 : elog(ERROR, "SPI_prepare returned %s for %s",
2056 : : SPI_result_code_string(SPI_result), querybuf.data);
2057 : :
2058 : : /*
2059 : : * Run the plan. For safety we force a current snapshot to be used. (In
2060 : : * transaction-snapshot mode, this arguably violates transaction isolation
2061 : : * rules, but we really haven't got much choice.) We don't need to
2062 : : * register the snapshot, because SPI_execute_snapshot will see to it. We
2063 : : * need at most one tuple returned, so pass limit = 1.
2064 : : */
2065 : 65 : spi_result = SPI_execute_snapshot(qplan,
2066 : : NULL, NULL,
2067 : : GetLatestSnapshot(),
2068 : : InvalidSnapshot,
2069 : : true, false, 1);
2070 : :
2071 : : /* Check result */
2072 [ - + ]: 65 : if (spi_result != SPI_OK_SELECT)
2073 [ # # ]: 0 : elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2074 : :
2075 : : /* Did we find a tuple that would violate the constraint? */
2076 [ + + ]: 65 : if (SPI_processed > 0)
2077 : : {
2078 : : TupleTableSlot *slot;
2079 : 22 : HeapTuple tuple = SPI_tuptable->vals[0];
2080 : 22 : TupleDesc tupdesc = SPI_tuptable->tupdesc;
2081 : : RI_ConstraintInfo fake_riinfo;
2082 : :
2083 : 22 : slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
2084 : :
2085 : 22 : heap_deform_tuple(tuple, tupdesc,
2086 : : slot->tts_values, slot->tts_isnull);
2087 : 22 : ExecStoreVirtualTuple(slot);
2088 : :
2089 : : /*
2090 : : * The columns to look at in the result tuple are 1..N, not whatever
2091 : : * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
2092 : : * will behave properly.
2093 : : *
2094 : : * In addition to this, we have to pass the correct tupdesc to
2095 : : * ri_ReportViolation, overriding its normal habit of using the pk_rel
2096 : : * or fk_rel's tupdesc.
2097 : : */
2098 : 22 : memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
2099 [ + + ]: 44 : for (i = 0; i < fake_riinfo.nkeys; i++)
2100 : 22 : fake_riinfo.pk_attnums[i] = i + 1;
2101 : :
2102 : 22 : ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
2103 : : slot, tupdesc, 0, false, true);
2104 : : }
2105 : :
2106 [ - + ]: 43 : if (SPI_finish() != SPI_OK_FINISH)
2107 [ # # ]: 0 : elog(ERROR, "SPI_finish failed");
2108 : :
2109 : : /*
2110 : : * Restore work_mem and hash_mem_multiplier.
2111 : : */
2112 : 43 : AtEOXact_GUC(true, save_nestlevel);
2113 : 43 : }
2114 : :
2115 : :
2116 : : /* ----------
2117 : : * Local functions below
2118 : : * ----------
2119 : : */
2120 : :
2121 : :
2122 : : /*
2123 : : * quoteOneName --- safely quote a single SQL name
2124 : : *
2125 : : * buffer must be MAX_QUOTED_NAME_LEN long (includes room for \0)
2126 : : */
2127 : : static void
2128 : 12935 : quoteOneName(char *buffer, const char *name)
2129 : : {
2130 : : /* Rather than trying to be smart, just always quote it. */
2131 : 12935 : *buffer++ = '"';
2132 [ + + ]: 79090 : while (*name)
2133 : : {
2134 [ - + ]: 66155 : if (*name == '"')
2135 : 0 : *buffer++ = '"';
2136 : 66155 : *buffer++ = *name++;
2137 : : }
2138 : 12935 : *buffer++ = '"';
2139 : 12935 : *buffer = '\0';
2140 : 12935 : }
2141 : :
2142 : : /*
2143 : : * quoteRelationName --- safely quote a fully qualified relation name
2144 : : *
2145 : : * buffer must be MAX_QUOTED_REL_NAME_LEN long (includes room for \0)
2146 : : */
2147 : : static void
2148 : 2871 : quoteRelationName(char *buffer, Relation rel)
2149 : : {
2150 : 2871 : quoteOneName(buffer, get_namespace_name(RelationGetNamespace(rel)));
2151 : 2871 : buffer += strlen(buffer);
2152 : 2871 : *buffer++ = '.';
2153 : 2871 : quoteOneName(buffer, RelationGetRelationName(rel));
2154 : 2871 : }
2155 : :
2156 : : /*
2157 : : * ri_GenerateQual --- generate a WHERE clause equating two variables
2158 : : *
2159 : : * This basically appends " sep leftop op rightop" to buf, adding casts
2160 : : * and schema qualification as needed to ensure that the parser will select
2161 : : * the operator we specify. leftop and rightop should be parenthesized
2162 : : * if they aren't variables or parameters.
2163 : : */
2164 : : static void
2165 : 3125 : ri_GenerateQual(StringInfo buf,
2166 : : const char *sep,
2167 : : const char *leftop, Oid leftoptype,
2168 : : Oid opoid,
2169 : : const char *rightop, Oid rightoptype)
2170 : : {
2171 : 3125 : appendStringInfo(buf, " %s ", sep);
2172 : 3125 : generate_operator_clause(buf, leftop, leftoptype, opoid,
2173 : : rightop, rightoptype);
2174 : 3125 : }
2175 : :
2176 : : /*
2177 : : * ri_GenerateQualCollation --- add a COLLATE spec to a WHERE clause
2178 : : *
2179 : : * We only have to use this function when directly comparing the referencing
2180 : : * and referenced columns, if they are of different collations; else the
2181 : : * parser will fail to resolve the collation to use. We don't need to use
2182 : : * this function for RI queries that compare a variable to a $n parameter.
2183 : : * Since parameter symbols always have default collation, the effect will be
2184 : : * to use the variable's collation.
2185 : : *
2186 : : * Note that we require that the collations of the referencing and the
2187 : : * referenced column have the same notion of equality: Either they have to
2188 : : * both be deterministic or else they both have to be the same. (See also
2189 : : * ATAddForeignKeyConstraint().)
2190 : : */
2191 : : static void
2192 : 8 : ri_GenerateQualCollation(StringInfo buf, Oid collation)
2193 : : {
2194 : : HeapTuple tp;
2195 : : Form_pg_collation colltup;
2196 : : char *collname;
2197 : : char onename[MAX_QUOTED_NAME_LEN];
2198 : :
2199 : : /* Nothing to do if it's a noncollatable data type */
2200 [ - + ]: 8 : if (!OidIsValid(collation))
2201 : 0 : return;
2202 : :
2203 : 8 : tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2204 [ - + ]: 8 : if (!HeapTupleIsValid(tp))
2205 [ # # ]: 0 : elog(ERROR, "cache lookup failed for collation %u", collation);
2206 : 8 : colltup = (Form_pg_collation) GETSTRUCT(tp);
2207 : 8 : collname = NameStr(colltup->collname);
2208 : :
2209 : : /*
2210 : : * We qualify the name always, for simplicity and to ensure the query is
2211 : : * not search-path-dependent.
2212 : : */
2213 : 8 : quoteOneName(onename, get_namespace_name(colltup->collnamespace));
2214 : 8 : appendStringInfo(buf, " COLLATE %s", onename);
2215 : 8 : quoteOneName(onename, collname);
2216 : 8 : appendStringInfo(buf, ".%s", onename);
2217 : :
2218 : 8 : ReleaseSysCache(tp);
2219 : : }
2220 : :
2221 : : /* ----------
2222 : : * ri_BuildQueryKey -
2223 : : *
2224 : : * Construct a hashtable key for a prepared SPI plan of an FK constraint.
2225 : : *
2226 : : * key: output argument, *key is filled in based on the other arguments
2227 : : * riinfo: info derived from pg_constraint entry
2228 : : * constr_queryno: an internal number identifying the query type
2229 : : * (see RI_PLAN_XXX constants at head of file)
2230 : : * ----------
2231 : : */
2232 : : static void
2233 : 2457 : ri_BuildQueryKey(RI_QueryKey *key, const RI_ConstraintInfo *riinfo,
2234 : : int32 constr_queryno)
2235 : : {
2236 : : /*
2237 : : * Inherited constraints with a common ancestor can share ri_query_cache
2238 : : * entries for all query types except RI_PLAN_CHECK_LOOKUPPK_FROM_PK.
2239 : : * Except in that case, the query processes the other table involved in
2240 : : * the FK constraint (i.e., not the table on which the trigger has been
2241 : : * fired), and so it will be the same for all members of the inheritance
2242 : : * tree. So we may use the root constraint's OID in the hash key, rather
2243 : : * than the constraint's own OID. This avoids creating duplicate SPI
2244 : : * plans, saving lots of work and memory when there are many partitions
2245 : : * with similar FK constraints.
2246 : : *
2247 : : * (Note that we must still have a separate RI_ConstraintInfo for each
2248 : : * constraint, because partitions can have different column orders,
2249 : : * resulting in different pk_attnums[] or fk_attnums[] array contents.)
2250 : : *
2251 : : * We assume struct RI_QueryKey contains no padding bytes, else we'd need
2252 : : * to use memset to clear them.
2253 : : */
2254 [ + + ]: 2457 : if (constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK)
2255 : 1927 : key->constr_id = riinfo->constraint_root_id;
2256 : : else
2257 : 530 : key->constr_id = riinfo->constraint_id;
2258 : 2457 : key->constr_queryno = constr_queryno;
2259 : 2457 : }
2260 : :
2261 : : /*
2262 : : * Check that RI trigger function was called in expected context
2263 : : */
2264 : : static void
2265 : 606821 : ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname, int tgkind)
2266 : : {
2267 : 606821 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
2268 : :
2269 [ + - - + ]: 606821 : if (!CALLED_AS_TRIGGER(fcinfo))
2270 [ # # ]: 0 : ereport(ERROR,
2271 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2272 : : errmsg("function \"%s\" was not called by trigger manager", funcname)));
2273 : :
2274 : : /*
2275 : : * Check proper event
2276 : : */
2277 [ + - ]: 606821 : if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
2278 [ - + ]: 606821 : !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2279 [ # # ]: 0 : ereport(ERROR,
2280 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2281 : : errmsg("function \"%s\" must be fired AFTER ROW", funcname)));
2282 : :
2283 [ + + + - ]: 606821 : switch (tgkind)
2284 : : {
2285 : 605430 : case RI_TRIGTYPE_INSERT:
2286 [ - + ]: 605430 : if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2287 [ # # ]: 0 : ereport(ERROR,
2288 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2289 : : errmsg("function \"%s\" must be fired for INSERT", funcname)));
2290 : 605430 : break;
2291 : 863 : case RI_TRIGTYPE_UPDATE:
2292 [ - + ]: 863 : if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2293 [ # # ]: 0 : ereport(ERROR,
2294 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2295 : : errmsg("function \"%s\" must be fired for UPDATE", funcname)));
2296 : 863 : break;
2297 : 528 : case RI_TRIGTYPE_DELETE:
2298 [ - + ]: 528 : if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2299 [ # # ]: 0 : ereport(ERROR,
2300 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2301 : : errmsg("function \"%s\" must be fired for DELETE", funcname)));
2302 : 528 : break;
2303 : : }
2304 : 606821 : }
2305 : :
2306 : :
2307 : : /*
2308 : : * Fetch the RI_ConstraintInfo struct for the trigger's FK constraint.
2309 : : */
2310 : : static RI_ConstraintInfo *
2311 : 609940 : ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
2312 : : {
2313 : 609940 : Oid constraintOid = trigger->tgconstraint;
2314 : : RI_ConstraintInfo *riinfo;
2315 : :
2316 : : /*
2317 : : * Check that the FK constraint's OID is available; it might not be if
2318 : : * we've been invoked via an ordinary trigger or an old-style "constraint
2319 : : * trigger".
2320 : : */
2321 [ - + ]: 609940 : if (!OidIsValid(constraintOid))
2322 [ # # ]: 0 : ereport(ERROR,
2323 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2324 : : errmsg("no pg_constraint entry for trigger \"%s\" on table \"%s\"",
2325 : : trigger->tgname, RelationGetRelationName(trig_rel)),
2326 : : errhint("Remove this referential integrity trigger and its mates, then do ALTER TABLE ADD CONSTRAINT.")));
2327 : :
2328 : : /* Find or create a hashtable entry for the constraint */
2329 : 609940 : riinfo = ri_LoadConstraintInfo(constraintOid);
2330 : :
2331 : : /* Do some easy cross-checks against the trigger call data */
2332 [ + + ]: 609940 : if (rel_is_pk)
2333 : : {
2334 [ + - ]: 2703 : if (riinfo->fk_relid != trigger->tgconstrrelid ||
2335 [ - + ]: 2703 : riinfo->pk_relid != RelationGetRelid(trig_rel))
2336 [ # # ]: 0 : elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2337 : : trigger->tgname, RelationGetRelationName(trig_rel));
2338 : : }
2339 : : else
2340 : : {
2341 [ + - ]: 607237 : if (riinfo->fk_relid != RelationGetRelid(trig_rel) ||
2342 [ - + ]: 607237 : riinfo->pk_relid != trigger->tgconstrrelid)
2343 [ # # ]: 0 : elog(ERROR, "wrong pg_constraint entry for trigger \"%s\" on table \"%s\"",
2344 : : trigger->tgname, RelationGetRelationName(trig_rel));
2345 : : }
2346 : :
2347 [ + + ]: 609940 : if (riinfo->confmatchtype != FKCONSTR_MATCH_FULL &&
2348 [ + - ]: 609627 : riinfo->confmatchtype != FKCONSTR_MATCH_PARTIAL &&
2349 [ - + ]: 609627 : riinfo->confmatchtype != FKCONSTR_MATCH_SIMPLE)
2350 [ # # ]: 0 : elog(ERROR, "unrecognized confmatchtype: %d",
2351 : : riinfo->confmatchtype);
2352 : :
2353 [ - + ]: 609940 : if (riinfo->confmatchtype == FKCONSTR_MATCH_PARTIAL)
2354 [ # # ]: 0 : ereport(ERROR,
2355 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2356 : : errmsg("MATCH PARTIAL not yet implemented")));
2357 : :
2358 : 609940 : return riinfo;
2359 : : }
2360 : :
2361 : : /*
2362 : : * Fetch or create the RI_ConstraintInfo struct for an FK constraint.
2363 : : */
2364 : : static RI_ConstraintInfo *
2365 : 1215647 : ri_LoadConstraintInfo(Oid constraintOid)
2366 : : {
2367 : : RI_ConstraintInfo *riinfo;
2368 : : bool found;
2369 : : HeapTuple tup;
2370 : : Form_pg_constraint conForm;
2371 : :
2372 : : /*
2373 : : * On the first call initialize the hashtable
2374 : : */
2375 [ + + ]: 1215647 : if (!ri_constraint_cache)
2376 : 258 : ri_InitHashTables();
2377 : :
2378 : : /*
2379 : : * Find or create a hash entry. If we find a valid one, just return it.
2380 : : */
2381 : 1215647 : riinfo = (RI_ConstraintInfo *) hash_search(ri_constraint_cache,
2382 : : &constraintOid,
2383 : : HASH_ENTER, &found);
2384 [ + + ]: 1215647 : if (!found)
2385 : 2500 : riinfo->valid = false;
2386 [ + + ]: 1213147 : else if (riinfo->valid)
2387 : 1212858 : return riinfo;
2388 : :
2389 : : /*
2390 : : * Fetch the pg_constraint row so we can fill in the entry.
2391 : : */
2392 : 2789 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
2393 [ - + ]: 2789 : if (!HeapTupleIsValid(tup)) /* should not happen */
2394 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constraintOid);
2395 : 2789 : conForm = (Form_pg_constraint) GETSTRUCT(tup);
2396 : :
2397 [ - + ]: 2789 : if (conForm->contype != CONSTRAINT_FOREIGN) /* should not happen */
2398 [ # # ]: 0 : elog(ERROR, "constraint %u is not a foreign key constraint",
2399 : : constraintOid);
2400 : :
2401 : : /* And extract data */
2402 : : Assert(riinfo->constraint_id == constraintOid);
2403 [ + + ]: 2789 : if (OidIsValid(conForm->conparentid))
2404 : 940 : riinfo->constraint_root_id =
2405 : 940 : get_ri_constraint_root(conForm->conparentid);
2406 : : else
2407 : 1849 : riinfo->constraint_root_id = constraintOid;
2408 : 2789 : riinfo->oidHashValue = GetSysCacheHashValue1(CONSTROID,
2409 : : ObjectIdGetDatum(constraintOid));
2410 : 2789 : riinfo->rootHashValue = GetSysCacheHashValue1(CONSTROID,
2411 : : ObjectIdGetDatum(riinfo->constraint_root_id));
2412 : 2789 : memcpy(&riinfo->conname, &conForm->conname, sizeof(NameData));
2413 : 2789 : riinfo->pk_relid = conForm->confrelid;
2414 : 2789 : riinfo->fk_relid = conForm->conrelid;
2415 : 2789 : riinfo->confupdtype = conForm->confupdtype;
2416 : 2789 : riinfo->confdeltype = conForm->confdeltype;
2417 : 2789 : riinfo->confmatchtype = conForm->confmatchtype;
2418 : 2789 : riinfo->hasperiod = conForm->conperiod;
2419 : :
2420 : 2789 : DeconstructFkConstraintRow(tup,
2421 : : &riinfo->nkeys,
2422 : 2789 : riinfo->fk_attnums,
2423 : 2789 : riinfo->pk_attnums,
2424 : 2789 : riinfo->pf_eq_oprs,
2425 : 2789 : riinfo->pp_eq_oprs,
2426 : 2789 : riinfo->ff_eq_oprs,
2427 : : &riinfo->ndelsetcols,
2428 : 2789 : riinfo->confdelsetcols);
2429 : :
2430 : : /*
2431 : : * For temporal FKs, get the operators and functions we need. We ask the
2432 : : * opclass of the PK element for these. This all gets cached (as does the
2433 : : * generated plan), so there's no performance issue.
2434 : : */
2435 [ + + ]: 2789 : if (riinfo->hasperiod)
2436 : : {
2437 : 137 : Oid opclass = get_index_column_opclass(conForm->conindid, riinfo->nkeys);
2438 : :
2439 : 137 : FindFKPeriodOpers(opclass,
2440 : : &riinfo->period_contained_by_oper,
2441 : : &riinfo->agged_period_contained_by_oper,
2442 : : &riinfo->period_intersect_oper);
2443 : : }
2444 : :
2445 : : /* Metadata used by fast path. */
2446 : 2789 : riinfo->conindid = conForm->conindid;
2447 : 2789 : riinfo->pk_is_partitioned =
2448 : 2789 : (get_rel_relkind(riinfo->pk_relid) == RELKIND_PARTITIONED_TABLE);
2449 : 2789 : riinfo->fastpath_state = RI_FASTPATH_UNKNOWN;
2450 : :
2451 : 2789 : ReleaseSysCache(tup);
2452 : :
2453 : : /*
2454 : : * For efficient processing of invalidation messages below, we keep a
2455 : : * doubly-linked count list of all currently valid entries.
2456 : : */
2457 : 2789 : dclist_push_tail(&ri_constraint_cache_valid_list, &riinfo->valid_link);
2458 : :
2459 : 2789 : riinfo->valid = true;
2460 : :
2461 : 2789 : riinfo->fpmeta = NULL;
2462 : :
2463 : 2789 : return riinfo;
2464 : : }
2465 : :
2466 : : /*
2467 : : * get_ri_constraint_root
2468 : : * Returns the OID of the constraint's root parent
2469 : : */
2470 : : static Oid
2471 : 940 : get_ri_constraint_root(Oid constrOid)
2472 : : {
2473 : : for (;;)
2474 : 232 : {
2475 : : HeapTuple tuple;
2476 : : Oid constrParentOid;
2477 : :
2478 : 1172 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
2479 [ - + ]: 1172 : if (!HeapTupleIsValid(tuple))
2480 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
2481 : 1172 : constrParentOid = ((Form_pg_constraint) GETSTRUCT(tuple))->conparentid;
2482 : 1172 : ReleaseSysCache(tuple);
2483 [ + + ]: 1172 : if (!OidIsValid(constrParentOid))
2484 : 940 : break; /* we reached the root constraint */
2485 : 232 : constrOid = constrParentOid;
2486 : : }
2487 : 940 : return constrOid;
2488 : : }
2489 : :
2490 : : /*
2491 : : * Callback for pg_constraint and pg_amop inval events
2492 : : *
2493 : : * While most syscache callbacks just flush all their entries, pg_constraint
2494 : : * gets enough update traffic that it's probably worth being smarter.
2495 : : * Invalidate any ri_constraint_cache entry associated with the syscache
2496 : : * entry with the specified hash value, or all entries if hashvalue == 0.
2497 : : *
2498 : : * Note: at the time a cache invalidation message is processed there may be
2499 : : * active references to the cache. Because of this we never remove entries
2500 : : * from the cache, but only mark them invalid, which is harmless to active
2501 : : * uses. (Any query using an entry should hold a lock sufficient to keep that
2502 : : * data from changing under it --- but we may get cache flushes anyway.)
2503 : : *
2504 : : * The fast-path metadata hanging off an entry is subject to the same rule.
2505 : : * We unlink it so that the next check rebuilds it, but the object itself is
2506 : : * only queued here and is actually released by AtEOXact_RI().
2507 : : */
2508 : : static void
2509 : 53838 : InvalidateConstraintCacheCallBack(Datum arg, SysCacheIdentifier cacheid,
2510 : : uint32 hashvalue)
2511 : : {
2512 : : dlist_mutable_iter iter;
2513 : :
2514 : : Assert(ri_constraint_cache != NULL);
2515 : :
2516 : : /*
2517 : : * pg_amop changes can affect any constraint's fast-path metadata, and
2518 : : * this pg_amop hashvalue can't be matched against the pg_constraint-keyed
2519 : : * cache entries, so flush them all via the match-everything path below as
2520 : : * the large-list reset below does. Being selective would mean mapping
2521 : : * the change back to the affected constraints, not worth it for DDL this
2522 : : * rare.
2523 : : */
2524 [ + + ]: 53838 : if (cacheid == AMOPOPID)
2525 : 397 : hashvalue = 0;
2526 : :
2527 : : /*
2528 : : * If the list of currently valid entries gets excessively large, we mark
2529 : : * them all invalid so we can empty the list. This arrangement avoids
2530 : : * O(N^2) behavior in situations where a session touches many foreign keys
2531 : : * and also does many ALTER TABLEs, such as a restore from pg_dump.
2532 : : */
2533 [ - + ]: 53838 : if (dclist_count(&ri_constraint_cache_valid_list) > 1000)
2534 : 0 : hashvalue = 0; /* pretend it's a cache reset */
2535 : :
2536 [ + + + + ]: 216768 : dclist_foreach_modify(iter, &ri_constraint_cache_valid_list)
2537 : : {
2538 : 162930 : RI_ConstraintInfo *riinfo = dclist_container(RI_ConstraintInfo,
2539 : : valid_link, iter.cur);
2540 : :
2541 : : /*
2542 : : * We must invalidate not only entries directly matching the given
2543 : : * hash value, but also child entries, in case the invalidation
2544 : : * affects a root constraint.
2545 : : */
2546 [ + + ]: 162930 : if (hashvalue == 0 ||
2547 [ + + ]: 162790 : riinfo->oidHashValue == hashvalue ||
2548 [ + + ]: 161002 : riinfo->rootHashValue == hashvalue)
2549 : : {
2550 : 2144 : riinfo->valid = false;
2551 : :
2552 : : /*
2553 : : * Detach any fast-path metadata so that the next check
2554 : : * repopulates it, but do not free it here. ri_FastPathCheck()
2555 : : * copies riinfo->fpmeta into a local (and takes FmgrInfo pointers
2556 : : * into it) and then runs index scans, tuple locking, and
2557 : : * user-supplied cast and equality functions, all of which can
2558 : : * accept invalidation messages and reach this callback. Freeing
2559 : : * now would leave those callers reading freed memory. Queue it
2560 : : * instead; AtEOXact_RI() releases it once no RI check can be
2561 : : * running.
2562 : : */
2563 [ + + ]: 2144 : if (riinfo->fpmeta)
2564 : : {
2565 : 715 : riinfo->fpmeta->next_dead = ri_fpmeta_dead_list;
2566 : 715 : ri_fpmeta_dead_list = riinfo->fpmeta;
2567 : 715 : riinfo->fpmeta = NULL;
2568 : : }
2569 : :
2570 : : /* Remove invalidated entries from the list, too */
2571 : 2144 : dclist_delete_from(&ri_constraint_cache_valid_list, iter.cur);
2572 : : }
2573 : : }
2574 : 53838 : }
2575 : :
2576 : :
2577 : : /*
2578 : : * Prepare execution plan for a query to enforce an RI restriction
2579 : : */
2580 : : static SPIPlanPtr
2581 : 1201 : ri_PlanCheck(const char *querystr, int nargs, const Oid *argtypes,
2582 : : RI_QueryKey *qkey, Relation fk_rel, Relation pk_rel)
2583 : : {
2584 : : SPIPlanPtr qplan;
2585 : : Relation query_rel;
2586 : : Oid save_userid;
2587 : : int save_sec_context;
2588 : :
2589 : : /*
2590 : : * Use the query type code to determine whether the query is run against
2591 : : * the PK or FK table; we'll do the check as that table's owner
2592 : : */
2593 [ + + ]: 1201 : if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2594 : 643 : query_rel = pk_rel;
2595 : : else
2596 : 558 : query_rel = fk_rel;
2597 : :
2598 : : /* Switch to proper UID to perform check as */
2599 : 1201 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
2600 : 1201 : SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2601 : : save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2602 : : SECURITY_NOFORCE_RLS);
2603 : :
2604 : : /* Create the plan */
2605 : 1201 : qplan = SPI_prepare(querystr, nargs, argtypes);
2606 : :
2607 [ - + ]: 1201 : if (qplan == NULL)
2608 [ # # ]: 0 : elog(ERROR, "SPI_prepare returned %s for %s", SPI_result_code_string(SPI_result), querystr);
2609 : :
2610 : : /* Restore UID and security context */
2611 : 1201 : SetUserIdAndSecContext(save_userid, save_sec_context);
2612 : :
2613 : : /* Save the plan */
2614 : 1201 : SPI_keepplan(qplan);
2615 : 1201 : ri_HashPreparedPlan(qkey, qplan);
2616 : :
2617 : 1201 : return qplan;
2618 : : }
2619 : :
2620 : : /*
2621 : : * Perform a query to enforce an RI restriction
2622 : : */
2623 : : static bool
2624 : 2457 : ri_PerformCheck(const RI_ConstraintInfo *riinfo,
2625 : : RI_QueryKey *qkey, SPIPlanPtr qplan,
2626 : : Relation fk_rel, Relation pk_rel,
2627 : : TupleTableSlot *oldslot, TupleTableSlot *newslot,
2628 : : bool is_restrict,
2629 : : bool detectNewRows, int expect_OK)
2630 : : {
2631 : : Relation query_rel,
2632 : : source_rel;
2633 : : bool source_is_pk;
2634 : : Snapshot test_snapshot;
2635 : : Snapshot crosscheck_snapshot;
2636 : : int limit;
2637 : : int spi_result;
2638 : : Oid save_userid;
2639 : : int save_sec_context;
2640 : : Datum vals[RI_MAX_NUMKEYS * 2];
2641 : : char nulls[RI_MAX_NUMKEYS * 2];
2642 : :
2643 : : /*
2644 : : * Use the query type code to determine whether the query is run against
2645 : : * the PK or FK table; we'll do the check as that table's owner
2646 : : */
2647 [ + + ]: 2457 : if (qkey->constr_queryno <= RI_PLAN_LAST_ON_PK)
2648 : 1312 : query_rel = pk_rel;
2649 : : else
2650 : 1145 : query_rel = fk_rel;
2651 : :
2652 : : /*
2653 : : * The values for the query are taken from the table on which the trigger
2654 : : * is called - it is normally the other one with respect to query_rel. An
2655 : : * exception is ri_Check_Pk_Match(), which uses the PK table for both (and
2656 : : * sets queryno to RI_PLAN_CHECK_LOOKUPPK_FROM_PK). We might eventually
2657 : : * need some less klugy way to determine this.
2658 : : */
2659 [ + + ]: 2457 : if (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK)
2660 : : {
2661 : 782 : source_rel = fk_rel;
2662 : 782 : source_is_pk = false;
2663 : : }
2664 : : else
2665 : : {
2666 : 1675 : source_rel = pk_rel;
2667 : 1675 : source_is_pk = true;
2668 : : }
2669 : :
2670 : : /* Extract the parameters to be passed into the query */
2671 [ + + ]: 2457 : if (newslot)
2672 : : {
2673 : 926 : ri_ExtractValues(source_rel, newslot, riinfo, source_is_pk,
2674 : : vals, nulls);
2675 [ + + ]: 926 : if (oldslot)
2676 : 144 : ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2677 : 144 : vals + riinfo->nkeys, nulls + riinfo->nkeys);
2678 : : }
2679 : : else
2680 : : {
2681 : 1531 : ri_ExtractValues(source_rel, oldslot, riinfo, source_is_pk,
2682 : : vals, nulls);
2683 : : }
2684 : :
2685 : : /*
2686 : : * In READ COMMITTED mode, we just need to use an up-to-date regular
2687 : : * snapshot, and we will see all rows that could be interesting. But in
2688 : : * transaction-snapshot mode, we can't change the transaction snapshot. If
2689 : : * the caller passes detectNewRows == false then it's okay to do the query
2690 : : * with the transaction snapshot; otherwise we use a current snapshot, and
2691 : : * tell the executor to error out if it finds any rows under the current
2692 : : * snapshot that wouldn't be visible per the transaction snapshot. Note
2693 : : * that SPI_execute_snapshot will register the snapshots, so we don't need
2694 : : * to bother here.
2695 : : */
2696 [ + + + + ]: 2457 : if (IsolationUsesXactSnapshot() && detectNewRows)
2697 : : {
2698 : 36 : CommandCounterIncrement(); /* be sure all my own work is visible */
2699 : 36 : test_snapshot = GetLatestSnapshot();
2700 : 36 : crosscheck_snapshot = GetTransactionSnapshot();
2701 : : }
2702 : : else
2703 : : {
2704 : : /* the default SPI behavior is okay */
2705 : 2421 : test_snapshot = InvalidSnapshot;
2706 : 2421 : crosscheck_snapshot = InvalidSnapshot;
2707 : : }
2708 : :
2709 : : /*
2710 : : * If this is a select query (e.g., for a 'no action' or 'restrict'
2711 : : * trigger), we only need to see if there is a single row in the table,
2712 : : * matching the key. Otherwise, limit = 0 - because we want the query to
2713 : : * affect ALL the matching rows.
2714 : : */
2715 : 2457 : limit = (expect_OK == SPI_OK_SELECT) ? 1 : 0;
2716 : :
2717 : : /* Switch to proper UID to perform check as */
2718 : 2457 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
2719 : 2457 : SetUserIdAndSecContext(RelationGetForm(query_rel)->relowner,
2720 : : save_sec_context | SECURITY_LOCAL_USERID_CHANGE |
2721 : : SECURITY_NOFORCE_RLS);
2722 : :
2723 : : /*
2724 : : * Finally we can run the query.
2725 : : *
2726 : : * Set fire_triggers to false to ensure that AFTER triggers are queued in
2727 : : * the outer query's after-trigger context and fire after all RI updates
2728 : : * on the same row are complete, rather than immediately.
2729 : : */
2730 : 2457 : spi_result = SPI_execute_snapshot(qplan,
2731 : : vals, nulls,
2732 : : test_snapshot, crosscheck_snapshot,
2733 : : false, false, limit);
2734 : :
2735 : : /* Restore UID and security context */
2736 : 2439 : SetUserIdAndSecContext(save_userid, save_sec_context);
2737 : :
2738 : : /* Check result */
2739 [ - + ]: 2439 : if (spi_result < 0)
2740 [ # # ]: 0 : elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
2741 : :
2742 [ + - - + ]: 2439 : if (expect_OK >= 0 && spi_result != expect_OK)
2743 [ # # ]: 0 : ereport(ERROR,
2744 : : (errcode(ERRCODE_INTERNAL_ERROR),
2745 : : errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result",
2746 : : RelationGetRelationName(pk_rel),
2747 : : NameStr(riinfo->conname),
2748 : : RelationGetRelationName(fk_rel)),
2749 : : errhint("This is most likely due to a rule having rewritten the query.")));
2750 : :
2751 : : /* XXX wouldn't it be clearer to do this part at the caller? */
2752 [ + + + + ]: 2439 : if (qkey->constr_queryno != RI_PLAN_CHECK_LOOKUPPK_FROM_PK &&
2753 : 1496 : expect_OK == SPI_OK_SELECT &&
2754 [ + + ]: 1496 : (SPI_processed == 0) == (qkey->constr_queryno == RI_PLAN_CHECK_LOOKUPPK))
2755 [ + + ]: 458 : ri_ReportViolation(riinfo,
2756 : : pk_rel, fk_rel,
2757 : : newslot ? newslot : oldslot,
2758 : : NULL,
2759 : : qkey->constr_queryno, is_restrict, false);
2760 : :
2761 : 1981 : return SPI_processed != 0;
2762 : : }
2763 : :
2764 : : /*
2765 : : * ri_FastPathCheck
2766 : : * Perform per row FK existence check via direct index probe,
2767 : : * bypassing SPI.
2768 : : *
2769 : : * Return false if the index is unsuitable, so the caller can use SPI.
2770 : : * Otherwise, report any violation via ri_ReportViolation(), or return true
2771 : : * after a successful check.
2772 : : */
2773 : : static bool
2774 : 604722 : ri_FastPathCheck(RI_ConstraintInfo *riinfo,
2775 : : Relation fk_rel, TupleTableSlot *newslot)
2776 : : {
2777 : : Relation pk_rel;
2778 : : Relation idx_rel;
2779 : : IndexScanDesc scandesc;
2780 : : TupleTableSlot *slot;
2781 : : Datum pk_vals[INDEX_MAX_KEYS];
2782 : : char pk_nulls[INDEX_MAX_KEYS];
2783 : : ScanKeyData skey[INDEX_MAX_KEYS];
2784 : 604722 : bool found = false;
2785 : : Oid saved_userid;
2786 : : int saved_sec_context;
2787 : : Snapshot snapshot;
2788 : : FastPathMeta *fpmeta;
2789 : :
2790 : 604722 : INJECTION_POINT("ri-before-pk-lock", NULL);
2791 : :
2792 : 604722 : pk_rel = table_open(riinfo->pk_relid, RowShareLock);
2793 : :
2794 : : /*
2795 : : * The row lock taken below is refused in a read-only transaction unless
2796 : : * the referenced table is temporary, as ExecCheckXactReadOnly() refuses
2797 : : * the SPI path's SELECT ... FOR KEY SHARE.
2798 : : */
2799 [ + + + + ]: 604722 : if (XactReadOnly && !isTempNamespace(RelationGetNamespace(pk_rel)))
2800 : 4 : PreventCommandIfReadOnly("SELECT FOR KEY SHARE");
2801 : :
2802 : : /*
2803 : : * Advance the command counter so the check sees the effects of prior
2804 : : * triggers in this statement, as SPI does when executing the query issued
2805 : : * by ri_PerformCheck(). Do this after locking the referenced relation
2806 : : * and before reloading the constraint information, so local invalidations
2807 : : * are processed under the lock.
2808 : : */
2809 : 604718 : CommandCounterIncrement();
2810 : :
2811 : : /* Re-read the constraint under that lock. */
2812 : 604718 : riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2813 : :
2814 : 604718 : idx_rel = index_open(riinfo->conindid, AccessShareLock);
2815 : :
2816 [ + + ]: 604718 : if (!ri_check_fastpath_index(riinfo, pk_rel, idx_rel))
2817 : : {
2818 : 24 : index_close(idx_rel, NoLock);
2819 : 24 : table_close(pk_rel, NoLock);
2820 : 24 : return false;
2821 : : }
2822 : :
2823 : : /*
2824 : : * Only now take the snapshot the scan will use. Acquiring it before
2825 : : * table_open() would let an unbounded amount of time pass while we wait
2826 : : * for the lock, during which another transaction can commit the very row
2827 : : * we are about to look for. The scan would not see it and the check
2828 : : * would report a violation for a key that exists.
2829 : : *
2830 : : * The SPI path does not have this problem: for this check it passes
2831 : : * InvalidSnapshot, so SPI takes the snapshot after the
2832 : : * referenced-relation lock has been acquired.
2833 : : *
2834 : : * Make this snapshot active too, as SPI does. STABLE cast and equality
2835 : : * functions use the active snapshot, so leaving the outer query's
2836 : : * snapshot active could hide changes made by earlier triggers even though
2837 : : * the index scan can see them.
2838 : : */
2839 : 604694 : snapshot = RegisterSnapshot(GetTransactionSnapshot());
2840 : 604694 : PushActiveSnapshot(snapshot);
2841 : :
2842 : 604694 : slot = table_slot_create(pk_rel, NULL);
2843 : :
2844 : 604694 : GetUserIdAndSecContext(&saved_userid, &saved_sec_context);
2845 : 604694 : SetUserIdAndSecContext(RelationGetForm(pk_rel)->relowner,
2846 : : saved_sec_context |
2847 : : SECURITY_LOCAL_USERID_CHANGE |
2848 : : SECURITY_NOFORCE_RLS);
2849 : 604694 : ri_CheckPermissions(riinfo, pk_rel);
2850 : :
2851 : : /*
2852 : : * Begin the scan under the switched user id, so that any access method
2853 : : * code invoked by index_beginscan() runs as the PK relation's owner. For
2854 : : * btree this has no functional consequence, but it keeps the ordering
2855 : : * correct for out-of-tree access methods.
2856 : : */
2857 : 604670 : scandesc = index_beginscan(pk_rel, idx_rel, false,
2858 : : snapshot, NULL,
2859 : : riinfo->nkeys, 0,
2860 : : SO_NONE);
2861 : :
2862 [ + + ]: 604670 : if (riinfo->fpmeta == NULL)
2863 : : {
2864 : : /* Reload to ensure it's valid. */
2865 : 989 : riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
2866 : 989 : ri_populate_fastpath_metadata(riinfo, fk_rel, idx_rel);
2867 : : }
2868 : :
2869 : : /*
2870 : : * Use our own pointer to the metadata from here on. The permission
2871 : : * checks below look up catalog entries and so can process invalidation
2872 : : * messages, which detach riinfo->fpmeta (see
2873 : : * InvalidateConstraintCacheCallBack()); the detached object stays valid
2874 : : * until AtEOXact_RI().
2875 : : */
2876 : 604670 : fpmeta = riinfo->fpmeta;
2877 : : Assert(fpmeta);
2878 : 604670 : ri_CheckFunctionPermissions(riinfo, fpmeta);
2879 : 604662 : ri_ExtractValues(fk_rel, newslot, riinfo, false, pk_vals, pk_nulls);
2880 : 604662 : build_index_scankeys(riinfo, fpmeta, idx_rel, pk_vals, pk_nulls, skey);
2881 : 604662 : found = ri_FastPathProbeOne(pk_rel, idx_rel, scandesc, slot,
2882 : : snapshot, riinfo, skey, riinfo->nkeys);
2883 : 604655 : SetUserIdAndSecContext(saved_userid, saved_sec_context);
2884 : 604655 : index_endscan(scandesc);
2885 : 604655 : ExecDropSingleTupleTableSlot(slot);
2886 : 604655 : UnregisterSnapshot(snapshot);
2887 : 604655 : PopActiveSnapshot();
2888 : :
2889 [ + + ]: 604655 : if (!found)
2890 : 309 : ri_ReportViolation(riinfo, pk_rel, fk_rel,
2891 : : newslot, NULL,
2892 : : RI_PLAN_CHECK_LOOKUPPK, false, false);
2893 : :
2894 : 604346 : index_close(idx_rel, NoLock);
2895 : 604346 : table_close(pk_rel, NoLock);
2896 : 604346 : return true;
2897 : : }
2898 : :
2899 : : /*
2900 : : * ri_FastPathProbeOne
2901 : : * Probe the PK index for one set of scan keys, lock the matching
2902 : : * tuple
2903 : : *
2904 : : * Returns true if a matching PK row was found, locked, and (if
2905 : : * applicable) visible to the transaction snapshot.
2906 : : */
2907 : : static bool
2908 : 604662 : ri_FastPathProbeOne(Relation pk_rel, Relation idx_rel,
2909 : : IndexScanDesc scandesc, TupleTableSlot *slot,
2910 : : Snapshot snapshot, const RI_ConstraintInfo *riinfo,
2911 : : ScanKeyData *skey, int nkeys)
2912 : : {
2913 : 604662 : bool found = false;
2914 : :
2915 : 604662 : index_rescan(scandesc, skey, nkeys, NULL, 0);
2916 : :
2917 [ + + ]: 604662 : if (table_index_getnext_slot(scandesc, ForwardScanDirection, slot))
2918 : : {
2919 : : bool concurrently_updated;
2920 : :
2921 [ + + ]: 604362 : if (ri_LockPKTuple(pk_rel, slot, snapshot,
2922 : : &concurrently_updated))
2923 : : {
2924 [ + + ]: 604350 : if (concurrently_updated)
2925 : 7 : found = recheck_matched_pk_tuple(idx_rel, skey, nkeys, slot);
2926 : : else
2927 : 604343 : found = true;
2928 : : }
2929 : : }
2930 : :
2931 : 604655 : return found;
2932 : : }
2933 : :
2934 : : /*
2935 : : * ri_LockPKTuple
2936 : : * Lock a PK tuple found by the fast-path index scan.
2937 : : *
2938 : : * Calls table_tuple_lock() directly with handling specific to RI checks.
2939 : : * Returns true if the tuple was successfully locked.
2940 : : *
2941 : : * Sets *concurrently_updated to true if the locked tuple was reached
2942 : : * by following an update chain (tmfd.traversed), indicating the caller
2943 : : * should recheck the key.
2944 : : */
2945 : : static bool
2946 : 604362 : ri_LockPKTuple(Relation pk_rel, TupleTableSlot *slot, Snapshot snap,
2947 : : bool *concurrently_updated)
2948 : : {
2949 : : TM_FailureData tmfd;
2950 : : TM_Result result;
2951 : 604362 : int lockflags = TUPLE_LOCK_FLAG_LOCK_UPDATE_IN_PROGRESS;
2952 : :
2953 : 604362 : *concurrently_updated = false;
2954 : :
2955 [ + + ]: 604362 : if (!IsolationUsesXactSnapshot())
2956 : 604340 : lockflags |= TUPLE_LOCK_FLAG_FIND_LAST_VERSION;
2957 : :
2958 : : /*
2959 : : * Lock as of the command ID the scan's snapshot was taken with, as
2960 : : * ExecLockRows() uses the es_output_cid fixed when its query started.
2961 : : * User code run during the scan, such as an equality function, may have
2962 : : * advanced the current command ID since; with that, a row it updated
2963 : : * would look updated by an earlier command (TM_Invisible) rather than by
2964 : : * this one (TM_SelfModified).
2965 : : */
2966 : 604362 : result = table_tuple_lock(pk_rel, &slot->tts_tid, snap,
2967 : : slot, snap->curcid,
2968 : : LockTupleKeyShare, LockWaitBlock,
2969 : : lockflags, &tmfd);
2970 : :
2971 [ + + + + : 604359 : switch (result)
- - ]
2972 : : {
2973 : 604350 : case TM_Ok:
2974 [ + + ]: 604350 : if (tmfd.traversed)
2975 : 7 : *concurrently_updated = true;
2976 : 604350 : return true;
2977 : :
2978 : 4 : case TM_Deleted:
2979 [ + + ]: 4 : if (IsolationUsesXactSnapshot())
2980 [ + - ]: 3 : ereport(ERROR,
2981 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2982 : : errmsg("could not serialize access due to concurrent delete")));
2983 : 1 : return false;
2984 : :
2985 : 1 : case TM_Updated:
2986 [ + - ]: 1 : if (IsolationUsesXactSnapshot())
2987 [ + - ]: 1 : ereport(ERROR,
2988 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2989 : : errmsg("could not serialize access due to concurrent update")));
2990 : :
2991 : : /*
2992 : : * In READ COMMITTED, FIND_LAST_VERSION should have chased the
2993 : : * chain rather than returning TM_Updated. As in ExecLockRows(),
2994 : : * treat this as an unexpected result.
2995 : : */
2996 [ # # ]: 0 : elog(ERROR, "unexpected table_tuple_lock status: %u", result);
2997 : : break;
2998 : :
2999 : 4 : case TM_SelfModified:
3000 : :
3001 : : /*
3002 : : * As in ExecLockRows(), ignore a tuple updated or deleted by the
3003 : : * current command or a later command in this transaction.
3004 : : */
3005 : 4 : return false;
3006 : :
3007 : 0 : case TM_Invisible:
3008 [ # # ]: 0 : elog(ERROR, "attempted to lock invisible tuple");
3009 : : break;
3010 : :
3011 : 0 : default:
3012 [ # # ]: 0 : elog(ERROR, "unrecognized table_tuple_lock status: %u", result);
3013 : : break;
3014 : : }
3015 : :
3016 : : return false; /* keep compiler quiet */
3017 : : }
3018 : :
3019 : : /*
3020 : : * Apply the checks that do not require opening the referenced index. An
3021 : : * unknown state still needs ri_check_fastpath_index() before using it.
3022 : : */
3023 : : static bool
3024 : 605480 : ri_fastpath_is_applicable(const RI_ConstraintInfo *riinfo)
3025 : : {
3026 : : /*
3027 : : * Partitioned referenced tables are skipped for simplicity, since they
3028 : : * require routing the probe through the correct partition using
3029 : : * PartitionDirectory.
3030 : : */
3031 [ + + ]: 605480 : if (riinfo->pk_is_partitioned)
3032 : 587 : return false;
3033 : :
3034 : : /*
3035 : : * Temporal foreign keys use range overlap and containment semantics (&&,
3036 : : * <@, range_agg()) that inherently involve aggregation and multiple-row
3037 : : * reasoning, so they stay on the SPI path.
3038 : : */
3039 [ + + ]: 604893 : if (riinfo->hasperiod)
3040 : 151 : return false;
3041 : :
3042 : 604742 : return riinfo->fastpath_state != RI_FASTPATH_UNUSABLE;
3043 : : }
3044 : :
3045 : : /*
3046 : : * Check index-dependent eligibility lazily, like fast-path scan metadata.
3047 : : * Cache both success and failure until the constraint information is reloaded.
3048 : : *
3049 : : * The caller has locked the referenced table, reloaded conindid, and opened
3050 : : * the index. Looking up index properties in ri_LoadConstraintInfo() would
3051 : : * race with REINDEX CONCURRENTLY dropping an index read before that lock.
3052 : : * The index-property checks use the held relation descriptors.
3053 : : */
3054 : : static bool
3055 : 604718 : ri_check_fastpath_index(RI_ConstraintInfo *riinfo,
3056 : : Relation pk_rel, Relation idx_rel)
3057 : : {
3058 : : /* Opening the index can have processed further invalidations. */
3059 [ - + ]: 604718 : if (!riinfo->valid)
3060 : 0 : riinfo = ri_LoadConstraintInfo(riinfo->constraint_id);
3061 : :
3062 [ + + ]: 604718 : if (riinfo->fastpath_state != RI_FASTPATH_UNKNOWN)
3063 : 603697 : return riinfo->fastpath_state == RI_FASTPATH_USABLE;
3064 : :
3065 : : /*
3066 : : * The fast path probes the referenced index directly. A foreign key's
3067 : : * referenced index need not be a primary key; transformFkeyCheckAttrs()
3068 : : * accepts any unique index, so an out-of-tree amcanunique access method
3069 : : * could reach here. Restrict the fast path to btree; other access
3070 : : * methods fall back to SPI.
3071 : : */
3072 [ - + ]: 1021 : if (idx_rel->rd_rel->relam != BTREE_AM_OID)
3073 : : {
3074 : 0 : riinfo->fastpath_state = RI_FASTPATH_UNUSABLE;
3075 : 0 : return false;
3076 : : }
3077 : :
3078 : : /*
3079 : : * Leave comparisons with a different index and referenced-column
3080 : : * collation to SPI. Map index keys to table attributes because the FK
3081 : : * columns need not be listed in index order. Ignore INCLUDE columns.
3082 : : */
3083 [ + + ]: 2198 : for (int i = 0; i < idx_rel->rd_index->indnkeyatts; i++)
3084 : : {
3085 : 1193 : AttrNumber attnum = idx_rel->rd_index->indkey.values[i];
3086 : :
3087 [ + + ]: 1193 : if (idx_rel->rd_indcollation[i] != RIAttCollation(pk_rel, attnum))
3088 : : {
3089 : 16 : riinfo->fastpath_state = RI_FASTPATH_UNUSABLE;
3090 : 16 : return false;
3091 : : }
3092 : : }
3093 : :
3094 : : /*
3095 : : * The equality operator stored in pg_constraint must still be an equality
3096 : : * member of the index opfamily. When it is not, the direct fast-path
3097 : : * probe errors, so mark the fast path unusable and fall back to SPI,
3098 : : * which uses the same operator in a query where the planner simply
3099 : : * declines the index.
3100 : : */
3101 [ + + ]: 2174 : for (int i = 0; i < riinfo->nkeys; i++)
3102 : : {
3103 : : int idx_col;
3104 : :
3105 [ + - ]: 1374 : for (idx_col = 0; idx_col < idx_rel->rd_index->indnkeyatts; idx_col++)
3106 : : {
3107 : 1374 : if (idx_rel->rd_index->indkey.values[idx_col] ==
3108 [ + + ]: 1374 : riinfo->pk_attnums[i])
3109 : 1177 : break;
3110 : : }
3111 : : Assert(idx_col < idx_rel->rd_index->indnkeyatts);
3112 : :
3113 [ + + ]: 1177 : if (get_op_opfamily_strategy(riinfo->pf_eq_oprs[i],
3114 : 1177 : idx_rel->rd_opfamily[idx_col]) != BTEqualStrategyNumber)
3115 : : {
3116 : 8 : riinfo->fastpath_state = RI_FASTPATH_UNUSABLE;
3117 : 8 : return false;
3118 : : }
3119 : : }
3120 : :
3121 : 997 : riinfo->fastpath_state = RI_FASTPATH_USABLE;
3122 : 997 : return true;
3123 : : }
3124 : :
3125 : : /*
3126 : : * ri_CheckPermissions
3127 : : * Check permissions for the SELECT ... FOR KEY SHARE used by the SPI
3128 : : * path, as the referenced table's owner.
3129 : : *
3130 : : * Go through ExecCheckPermissions() with a manufactured range table so that
3131 : : * ExecutorCheckPerms_hook gets control, as it does for the query the SPI
3132 : : * path executes.
3133 : : */
3134 : : static void
3135 : 604694 : ri_CheckPermissions(const RI_ConstraintInfo *riinfo, Relation query_rel)
3136 : : {
3137 : : AclResult aclresult;
3138 : 604694 : AclMode requiredPerms = ACL_SELECT | ACL_SELECT_FOR_UPDATE;
3139 : : RangeTblEntry *rte;
3140 : : RTEPermissionInfo *perminfo;
3141 : :
3142 : : /* USAGE on schema. */
3143 : 604694 : aclresult = object_aclcheck(NamespaceRelationId,
3144 : 604694 : RelationGetNamespace(query_rel),
3145 : : GetUserId(), ACL_USAGE);
3146 [ - + ]: 604694 : if (aclresult != ACLCHECK_OK)
3147 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
3148 : 0 : get_namespace_name(RelationGetNamespace(query_rel)));
3149 : :
3150 : : /*
3151 : : * SELECT is needed only on the referenced key columns. FOR KEY SHARE
3152 : : * also needs UPDATE privilege, which may be granted on any column; leave
3153 : : * updatedCols empty as the SPI query does.
3154 : : */
3155 : 604694 : perminfo = makeNode(RTEPermissionInfo);
3156 : 604694 : perminfo->relid = RelationGetRelid(query_rel);
3157 : 604694 : perminfo->requiredPerms = requiredPerms;
3158 [ + + ]: 1210288 : for (int i = 0; i < riinfo->nkeys; i++)
3159 : : {
3160 : 605594 : int attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
3161 : :
3162 : 605594 : perminfo->selectedCols = bms_add_member(perminfo->selectedCols, attno);
3163 : : }
3164 : :
3165 : 604694 : rte = makeNode(RangeTblEntry);
3166 : 604694 : rte->rtekind = RTE_RELATION;
3167 : 604694 : rte->relid = RelationGetRelid(query_rel);
3168 : 604694 : rte->relkind = query_rel->rd_rel->relkind;
3169 : 604694 : rte->rellockmode = RowShareLock;
3170 : 604694 : rte->perminfoindex = 1;
3171 : :
3172 : 604694 : (void) ExecCheckPermissions(list_make1(rte), list_make1(perminfo), true);
3173 : 604670 : }
3174 : :
3175 : : /*
3176 : : * recheck_matched_pk_tuple
3177 : : * After following an update chain (tmfd.traversed), verify that
3178 : : * the locked PK tuple still matches the original search keys.
3179 : : *
3180 : : * A non-key update (e.g. changing a non-PK column) creates a new tuple version
3181 : : * that we've now locked, but the key is unchanged -- that's fine. A key
3182 : : * update means the value we were looking for is gone, so we should treat it as
3183 : : * not found.
3184 : : */
3185 : : static bool
3186 : 7 : recheck_matched_pk_tuple(Relation idxrel, ScanKeyData *skeys, int nkeys,
3187 : : TupleTableSlot *new_slot)
3188 : : {
3189 : : /*
3190 : : * TODO: BuildIndexInfo does a syscache lookup + palloc on every call.
3191 : : * This only fires on the concurrent-update path (tmfd.traversed), which
3192 : : * should be rare, so the cost is acceptable for now. If profiling shows
3193 : : * otherwise, cache the IndexInfo in FastPathMeta.
3194 : : */
3195 : 7 : IndexInfo *indexInfo = BuildIndexInfo(idxrel);
3196 : : Datum values[INDEX_MAX_KEYS];
3197 : : bool isnull[INDEX_MAX_KEYS];
3198 : 7 : bool matched = true;
3199 : :
3200 : : /* PK indexes never have these. */
3201 : : Assert(indexInfo->ii_Expressions == NIL &&
3202 : : indexInfo->ii_ExclusionOps == NULL);
3203 : :
3204 : : /* Form the index values and isnull flags given the table tuple. */
3205 : : Assert(nkeys == indexInfo->ii_NumIndexKeyAttrs);
3206 : 7 : FormIndexDatum(indexInfo, new_slot, NULL, values, isnull);
3207 [ + + ]: 10 : for (int i = 0; i < nkeys; i++)
3208 : : {
3209 : 7 : ScanKeyData *skey = &skeys[i];
3210 : :
3211 : : /*
3212 : : * A foreign key may reference a nullable unique column, so the
3213 : : * version we chased the update chain to may have a NULL in a key
3214 : : * column. A NULL never equals the value we searched for, so treat it
3215 : : * as no match, as the SPI path's requalification would.
3216 : : */
3217 [ + + ]: 7 : if (isnull[i] ||
3218 [ + + ]: 5 : !DatumGetBool(FunctionCall2Coll(&skey->sk_func,
3219 : : skey->sk_collation,
3220 : : values[i],
3221 : : skey->sk_argument)))
3222 : : {
3223 : 4 : matched = false;
3224 : 4 : break;
3225 : : }
3226 : : }
3227 : :
3228 : 7 : return matched;
3229 : : }
3230 : :
3231 : : /*
3232 : : * ri_CheckFunctionPermissions
3233 : : * Check EXECUTE privilege on the functions the fast path invokes on the
3234 : : * FK values, as the referenced table's owner.
3235 : : *
3236 : : * This parallels the checks ExecInitFunc() performs when the SPI path
3237 : : * initializes its generated query, where the equality operator's function
3238 : : * appears in the WHERE clause and the cast function, if any, in the cast
3239 : : * applied to the parameter. Call with the user id already switched to the
3240 : : * referenced table's owner.
3241 : : */
3242 : : static void
3243 : 604670 : ri_CheckFunctionPermissions(const RI_ConstraintInfo *riinfo,
3244 : : const FastPathMeta *fpmeta)
3245 : : {
3246 [ + + ]: 1210224 : for (int i = 0; i < riinfo->nkeys; i++)
3247 : : {
3248 : 605562 : Oid funcs[2] = {fpmeta->regops[i], fpmeta->cast_func_finfo[i].fn_oid};
3249 : :
3250 [ + + ]: 1816674 : for (int j = 0; j < lengthof(funcs); j++)
3251 : : {
3252 : : AclResult aclresult;
3253 : :
3254 [ + + ]: 1211120 : if (!OidIsValid(funcs[j]))
3255 : 605494 : continue;
3256 : 605626 : aclresult = object_aclcheck(ProcedureRelationId, funcs[j],
3257 : : GetUserId(), ACL_EXECUTE);
3258 [ + + ]: 605626 : if (aclresult != ACLCHECK_OK)
3259 : 8 : aclcheck_error(aclresult, OBJECT_FUNCTION,
3260 : 8 : get_func_name(funcs[j]));
3261 [ - + ]: 605618 : InvokeFunctionExecuteHook(funcs[j]);
3262 : : }
3263 : : }
3264 : 604662 : }
3265 : :
3266 : : /*
3267 : : * build_index_scankeys
3268 : : * Build ScanKeys for a direct index probe of the PK's unique index.
3269 : : *
3270 : : * Uses cached compare entries, operator procedures, and strategy numbers
3271 : : * from ri_populate_fastpath_metadata() rather than looking them up on
3272 : : * each invocation. Casts FK values to the operator's expected input
3273 : : * type if needed.
3274 : : */
3275 : : static void
3276 : 604662 : build_index_scankeys(const RI_ConstraintInfo *riinfo,
3277 : : FastPathMeta *fpmeta,
3278 : : Relation idx_rel, Datum *pk_vals,
3279 : : char *pk_nulls, ScanKey skeys)
3280 : : {
3281 : : Assert(fpmeta);
3282 : :
3283 : : /*
3284 : : * May need to cast each of the individual values of the foreign key to
3285 : : * the corresponding PK column's type if the equality operator demands it.
3286 : : */
3287 [ + + ]: 1210216 : for (int i = 0; i < riinfo->nkeys; i++)
3288 : : {
3289 [ + - ]: 605554 : if (pk_nulls[i] != 'n' &&
3290 [ + + ]: 605554 : OidIsValid(fpmeta->cast_func_finfo[i].fn_oid))
3291 : 60 : pk_vals[i] = FunctionCall3(&fpmeta->cast_func_finfo[i],
3292 : : pk_vals[i],
3293 : : Int32GetDatum(-1), /* typmod */
3294 : : BoolGetDatum(false)); /* implicit coercion */
3295 : : }
3296 : :
3297 : : /*
3298 : : * Set up ScanKeys for the index scan. This is essentially how
3299 : : * ExecIndexBuildScanKeys() sets them up. Use the cached index_attnos and
3300 : : * the corresponding collation since FK columns may be in a different
3301 : : * order than PK index columns. Place each scan key at the array position
3302 : : * corresponding to its index column, since btree requires keys to be
3303 : : * ordered by attribute number.
3304 : : */
3305 [ + + ]: 1210216 : for (int i = 0; i < riinfo->nkeys; i++)
3306 : : {
3307 : 605554 : AttrNumber pkattrno = fpmeta->index_attnos[i];
3308 : 605554 : int skey_pos = pkattrno - 1; /* 0-based array position */
3309 : :
3310 : 605554 : ScanKeyEntryInitialize(&skeys[skey_pos], 0, pkattrno,
3311 : 605554 : fpmeta->strats[i], fpmeta->subtypes[i],
3312 : 605554 : idx_rel->rd_indcollation[skey_pos], fpmeta->regops[i],
3313 : 605554 : pk_vals[i]);
3314 : : }
3315 : 604662 : }
3316 : :
3317 : : /*
3318 : : * ri_populate_fastpath_metadata
3319 : : * Cache per-key metadata needed by build_index_scankeys().
3320 : : *
3321 : : * Looks up the compare hash entry, operator procedure OID, and index
3322 : : * strategy/subtype for each key column. Called lazily on first use
3323 : : * and persists for the lifetime of the RI_ConstraintInfo entry.
3324 : : */
3325 : : static void
3326 : 989 : ri_populate_fastpath_metadata(RI_ConstraintInfo *riinfo,
3327 : : Relation fk_rel, Relation idx_rel)
3328 : : {
3329 : : FastPathMeta *fpmeta;
3330 : 989 : MemoryContext oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3331 : :
3332 : : Assert(riinfo != NULL && riinfo->valid);
3333 : : Assert(riinfo->fpmeta == NULL);
3334 : :
3335 : 989 : fpmeta = palloc_object(FastPathMeta);
3336 : 989 : fpmeta->next_dead = NULL;
3337 : :
3338 : : /* Scratch context for the cached FmgrInfos' fn_mcxt; see FastPathMeta. */
3339 : 989 : fpmeta->scratch_cxt = AllocSetContextCreate(TopMemoryContext,
3340 : : "RI fast-path finfo scratch",
3341 : : ALLOCSET_SMALL_SIZES);
3342 [ + + ]: 2142 : for (int i = 0; i < riinfo->nkeys; i++)
3343 : : {
3344 : 1153 : Oid eq_opr = riinfo->pf_eq_oprs[i];
3345 : 1153 : Oid typeid = RIAttType(fk_rel, riinfo->fk_attnums[i]);
3346 : : Oid lefttype;
3347 : 1153 : RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3348 : : int idx_col;
3349 : :
3350 : : /*
3351 : : * Find the index column position for this constraint key. The FK
3352 : : * constraint may reference columns in a different order than they
3353 : : * appear in the PK index, so we must map pk_attnums[i] to the
3354 : : * corresponding index column position.
3355 : : */
3356 [ + - ]: 1342 : for (idx_col = 0; idx_col < riinfo->nkeys; idx_col++)
3357 : : {
3358 [ + + ]: 1342 : if (idx_rel->rd_index->indkey.values[idx_col] == riinfo->pk_attnums[i])
3359 : 1153 : break;
3360 : : }
3361 : : Assert(idx_col < riinfo->nkeys);
3362 : :
3363 : : /* 1-based attribute number */
3364 : 1153 : fpmeta->index_attnos[i] = idx_col + 1;
3365 : :
3366 : 1153 : fmgr_info_copy(&fpmeta->cast_func_finfo[i], &entry->cast_func_finfo,
3367 : : fpmeta->scratch_cxt);
3368 : 1153 : fmgr_info_copy(&fpmeta->eq_opr_finfo[i], &entry->eq_opr_finfo,
3369 : : fpmeta->scratch_cxt);
3370 : 1153 : fpmeta->regops[i] = get_opcode(eq_opr);
3371 : :
3372 : 1153 : get_op_opfamily_properties(eq_opr,
3373 : 1153 : idx_rel->rd_opfamily[idx_col],
3374 : : false,
3375 : : &fpmeta->strats[i],
3376 : : &lefttype,
3377 : : &fpmeta->subtypes[i]);
3378 : : }
3379 : :
3380 : 989 : riinfo->fpmeta = fpmeta;
3381 : 989 : MemoryContextSwitchTo(oldcxt);
3382 : 989 : }
3383 : :
3384 : : /*
3385 : : * Extract fields from a tuple into Datum/nulls arrays
3386 : : */
3387 : : static void
3388 : 607263 : ri_ExtractValues(Relation rel, TupleTableSlot *slot,
3389 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk,
3390 : : Datum *vals, char *nulls)
3391 : : {
3392 : : const int16 *attnums;
3393 : : bool isnull;
3394 : :
3395 [ + + ]: 607263 : if (rel_is_pk)
3396 : 1819 : attnums = riinfo->pk_attnums;
3397 : : else
3398 : 605444 : attnums = riinfo->fk_attnums;
3399 : :
3400 [ + + ]: 1216539 : for (int i = 0; i < riinfo->nkeys; i++)
3401 : : {
3402 : 609276 : vals[i] = slot_getattr(slot, attnums[i], &isnull);
3403 [ - + ]: 609276 : nulls[i] = isnull ? 'n' : ' ';
3404 : : }
3405 : 607263 : }
3406 : :
3407 : : /*
3408 : : * Produce an error report
3409 : : *
3410 : : * If the failed constraint was on insert/update to the FK table,
3411 : : * we want the key names and values extracted from there, and the error
3412 : : * message to look like 'key blah is not present in PK'.
3413 : : * Otherwise, the attr names and values come from the PK table and the
3414 : : * message looks like 'key blah is still referenced from FK'.
3415 : : */
3416 : : static void
3417 : 828 : ri_ReportViolation(const RI_ConstraintInfo *riinfo,
3418 : : Relation pk_rel, Relation fk_rel,
3419 : : TupleTableSlot *violatorslot, TupleDesc tupdesc,
3420 : : int queryno, bool is_restrict, bool partgone)
3421 : : {
3422 : : StringInfoData key_names;
3423 : : StringInfoData key_values;
3424 : : bool onfk;
3425 : : const int16 *attnums;
3426 : : Oid rel_oid;
3427 : : AclResult aclresult;
3428 : 828 : bool has_perm = true;
3429 : :
3430 : : /*
3431 : : * Determine which relation to complain about. If tupdesc wasn't passed
3432 : : * by caller, assume the violator tuple came from there.
3433 : : */
3434 : 828 : onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);
3435 [ + + ]: 828 : if (onfk)
3436 : : {
3437 : 492 : attnums = riinfo->fk_attnums;
3438 : 492 : rel_oid = fk_rel->rd_id;
3439 [ + + ]: 492 : if (tupdesc == NULL)
3440 : 453 : tupdesc = fk_rel->rd_att;
3441 : : }
3442 : : else
3443 : : {
3444 : 336 : attnums = riinfo->pk_attnums;
3445 : 336 : rel_oid = pk_rel->rd_id;
3446 [ + + ]: 336 : if (tupdesc == NULL)
3447 : 314 : tupdesc = pk_rel->rd_att;
3448 : : }
3449 : :
3450 : : /*
3451 : : * Check permissions- if the user does not have access to view the data in
3452 : : * any of the key columns then we don't include the errdetail() below.
3453 : : *
3454 : : * Check if RLS is enabled on the relation first. If so, we don't return
3455 : : * any specifics to avoid leaking data.
3456 : : *
3457 : : * Check table-level permissions next and, failing that, column-level
3458 : : * privileges.
3459 : : *
3460 : : * When a partition at the referenced side is being detached/dropped, we
3461 : : * needn't check, since the user must be the table owner anyway.
3462 : : */
3463 [ + + ]: 828 : if (partgone)
3464 : 22 : has_perm = true;
3465 [ + + ]: 806 : else if (check_enable_rls(rel_oid, InvalidOid, true) != RLS_ENABLED)
3466 : : {
3467 : 802 : aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
3468 [ - + ]: 802 : if (aclresult != ACLCHECK_OK)
3469 : : {
3470 : : /* Try for column-level permissions */
3471 [ # # ]: 0 : for (int idx = 0; idx < riinfo->nkeys; idx++)
3472 : : {
3473 : 0 : aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
3474 : : GetUserId(),
3475 : : ACL_SELECT);
3476 : :
3477 : : /* No access to the key */
3478 [ # # ]: 0 : if (aclresult != ACLCHECK_OK)
3479 : : {
3480 : 0 : has_perm = false;
3481 : 0 : break;
3482 : : }
3483 : : }
3484 : : }
3485 : : }
3486 : : else
3487 : 4 : has_perm = false;
3488 : :
3489 [ + + ]: 828 : if (has_perm)
3490 : : {
3491 : : /* Get printable versions of the keys involved */
3492 : 824 : initStringInfo(&key_names);
3493 : 824 : initStringInfo(&key_values);
3494 [ + + ]: 2023 : for (int idx = 0; idx < riinfo->nkeys; idx++)
3495 : : {
3496 : 1199 : int fnum = attnums[idx];
3497 : 1199 : Form_pg_attribute att = TupleDescAttr(tupdesc, fnum - 1);
3498 : : char *name,
3499 : : *val;
3500 : : Datum datum;
3501 : : bool isnull;
3502 : :
3503 : 1199 : name = NameStr(att->attname);
3504 : :
3505 : 1199 : datum = slot_getattr(violatorslot, fnum, &isnull);
3506 [ + - ]: 1199 : if (!isnull)
3507 : : {
3508 : : Oid foutoid;
3509 : : bool typisvarlena;
3510 : :
3511 : 1199 : getTypeOutputInfo(att->atttypid, &foutoid, &typisvarlena);
3512 : 1199 : val = OidOutputFunctionCall(foutoid, datum);
3513 : : }
3514 : : else
3515 : 0 : val = "null";
3516 : :
3517 [ + + ]: 1199 : if (idx > 0)
3518 : : {
3519 : 375 : appendStringInfoString(&key_names, ", ");
3520 : 375 : appendStringInfoString(&key_values, ", ");
3521 : : }
3522 : 1199 : appendStringInfoString(&key_names, name);
3523 : 1199 : appendStringInfoString(&key_values, val);
3524 : : }
3525 : : }
3526 : :
3527 [ + + ]: 828 : if (partgone)
3528 [ + - ]: 22 : ereport(ERROR,
3529 : : (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3530 : : errmsg("removing partition \"%s\" violates foreign key constraint \"%s\"",
3531 : : RelationGetRelationName(pk_rel),
3532 : : NameStr(riinfo->conname)),
3533 : : errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3534 : : key_names.data, key_values.data,
3535 : : RelationGetRelationName(fk_rel)),
3536 : : errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3537 [ + + ]: 806 : else if (onfk)
3538 [ + - + - ]: 492 : ereport(ERROR,
3539 : : (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3540 : : errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
3541 : : RelationGetRelationName(fk_rel),
3542 : : NameStr(riinfo->conname)),
3543 : : has_perm ?
3544 : : errdetail("Key (%s)=(%s) is not present in table \"%s\".",
3545 : : key_names.data, key_values.data,
3546 : : RelationGetRelationName(pk_rel)) :
3547 : : errdetail("Key is not present in table \"%s\".",
3548 : : RelationGetRelationName(pk_rel)),
3549 : : errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3550 [ + + ]: 314 : else if (is_restrict)
3551 [ + - + - ]: 20 : ereport(ERROR,
3552 : : (errcode(ERRCODE_RESTRICT_VIOLATION),
3553 : : errmsg("update or delete on table \"%s\" violates RESTRICT setting of foreign key constraint \"%s\" on table \"%s\"",
3554 : : RelationGetRelationName(pk_rel),
3555 : : NameStr(riinfo->conname),
3556 : : RelationGetRelationName(fk_rel)),
3557 : : has_perm ?
3558 : : errdetail("Key (%s)=(%s) is referenced from table \"%s\".",
3559 : : key_names.data, key_values.data,
3560 : : RelationGetRelationName(fk_rel)) :
3561 : : errdetail("Key is referenced from table \"%s\".",
3562 : : RelationGetRelationName(fk_rel)),
3563 : : errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3564 : : else
3565 [ + - + + ]: 294 : ereport(ERROR,
3566 : : (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
3567 : : errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"",
3568 : : RelationGetRelationName(pk_rel),
3569 : : NameStr(riinfo->conname),
3570 : : RelationGetRelationName(fk_rel)),
3571 : : has_perm ?
3572 : : errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
3573 : : key_names.data, key_values.data,
3574 : : RelationGetRelationName(fk_rel)) :
3575 : : errdetail("Key is still referenced from table \"%s\".",
3576 : : RelationGetRelationName(fk_rel)),
3577 : : errtableconstraint(fk_rel, NameStr(riinfo->conname))));
3578 : : }
3579 : :
3580 : :
3581 : : /*
3582 : : * ri_NullCheck -
3583 : : *
3584 : : * Determine the NULL state of all key values in a tuple
3585 : : *
3586 : : * Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
3587 : : */
3588 : : static int
3589 : 607896 : ri_NullCheck(TupleDesc tupDesc,
3590 : : TupleTableSlot *slot,
3591 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk)
3592 : : {
3593 : : const int16 *attnums;
3594 : 607896 : bool allnull = true;
3595 : 607896 : bool nonenull = true;
3596 : :
3597 [ + + ]: 607896 : if (rel_is_pk)
3598 : 1520 : attnums = riinfo->pk_attnums;
3599 : : else
3600 : 606376 : attnums = riinfo->fk_attnums;
3601 : :
3602 [ + + ]: 1217905 : for (int i = 0; i < riinfo->nkeys; i++)
3603 : : {
3604 [ + + ]: 610009 : if (slot_attisnull(slot, attnums[i]))
3605 : 370 : nonenull = false;
3606 : : else
3607 : 609639 : allnull = false;
3608 : : }
3609 : :
3610 [ + + ]: 607896 : if (allnull)
3611 : 186 : return RI_KEYS_ALL_NULL;
3612 : :
3613 [ + + ]: 607710 : if (nonenull)
3614 : 607574 : return RI_KEYS_NONE_NULL;
3615 : :
3616 : 136 : return RI_KEYS_SOME_NULL;
3617 : : }
3618 : :
3619 : :
3620 : : /*
3621 : : * ri_InitHashTables -
3622 : : *
3623 : : * Initialize our internal hash tables.
3624 : : */
3625 : : static void
3626 : 258 : ri_InitHashTables(void)
3627 : : {
3628 : : HASHCTL ctl;
3629 : :
3630 : 258 : ctl.keysize = sizeof(Oid);
3631 : 258 : ctl.entrysize = sizeof(RI_ConstraintInfo);
3632 : 258 : ri_constraint_cache = hash_create("RI constraint cache",
3633 : : RI_INIT_CONSTRAINTHASHSIZE,
3634 : : &ctl, HASH_ELEM | HASH_BLOBS);
3635 : :
3636 : : /* Arrange to flush cache on pg_constraint or pg_amop changes */
3637 : 258 : CacheRegisterSyscacheCallback(CONSTROID,
3638 : : InvalidateConstraintCacheCallBack,
3639 : : (Datum) 0);
3640 : 258 : CacheRegisterSyscacheCallback(AMOPOPID,
3641 : : InvalidateConstraintCacheCallBack,
3642 : : (Datum) 0);
3643 : :
3644 : 258 : ctl.keysize = sizeof(RI_QueryKey);
3645 : 258 : ctl.entrysize = sizeof(RI_QueryHashEntry);
3646 : 258 : ri_query_cache = hash_create("RI query cache",
3647 : : RI_INIT_QUERYHASHSIZE,
3648 : : &ctl, HASH_ELEM | HASH_BLOBS);
3649 : :
3650 : 258 : ctl.keysize = sizeof(RI_CompareKey);
3651 : 258 : ctl.entrysize = sizeof(RI_CompareHashEntry);
3652 : 258 : ri_compare_cache = hash_create("RI compare cache",
3653 : : RI_INIT_QUERYHASHSIZE,
3654 : : &ctl, HASH_ELEM | HASH_BLOBS);
3655 : 258 : }
3656 : :
3657 : :
3658 : : /*
3659 : : * ri_FetchPreparedPlan -
3660 : : *
3661 : : * Lookup for a query key in our private hash table of prepared
3662 : : * and saved SPI execution plans. Return the plan if found or NULL.
3663 : : */
3664 : : static SPIPlanPtr
3665 : 2457 : ri_FetchPreparedPlan(RI_QueryKey *key)
3666 : : {
3667 : : RI_QueryHashEntry *entry;
3668 : : SPIPlanPtr plan;
3669 : :
3670 : : /*
3671 : : * On the first call initialize the hashtable
3672 : : */
3673 [ - + ]: 2457 : if (!ri_query_cache)
3674 : 0 : ri_InitHashTables();
3675 : :
3676 : : /*
3677 : : * Lookup for the key
3678 : : */
3679 : 2457 : entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
3680 : : key,
3681 : : HASH_FIND, NULL);
3682 [ + + ]: 2457 : if (entry == NULL)
3683 : 1050 : return NULL;
3684 : :
3685 : : /*
3686 : : * Check whether the plan is still valid. If it isn't, we don't want to
3687 : : * simply rely on plancache.c to regenerate it; rather we should start
3688 : : * from scratch and rebuild the query text too. This is to cover cases
3689 : : * such as table/column renames. We depend on the plancache machinery to
3690 : : * detect possible invalidations, though.
3691 : : *
3692 : : * CAUTION: this check is only trustworthy if the caller has already
3693 : : * locked both FK and PK rels.
3694 : : */
3695 : 1407 : plan = entry->plan;
3696 [ + - + + ]: 1407 : if (plan && SPI_plan_is_valid(plan))
3697 : 1256 : return plan;
3698 : :
3699 : : /*
3700 : : * Otherwise we might as well flush the cached plan now, to free a little
3701 : : * memory space before we make a new one.
3702 : : */
3703 : 151 : entry->plan = NULL;
3704 [ + - ]: 151 : if (plan)
3705 : 151 : SPI_freeplan(plan);
3706 : :
3707 : 151 : return NULL;
3708 : : }
3709 : :
3710 : :
3711 : : /*
3712 : : * ri_HashPreparedPlan -
3713 : : *
3714 : : * Add another plan to our private SPI query plan hashtable.
3715 : : */
3716 : : static void
3717 : 1201 : ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
3718 : : {
3719 : : RI_QueryHashEntry *entry;
3720 : : bool found;
3721 : :
3722 : : /*
3723 : : * On the first call initialize the hashtable
3724 : : */
3725 [ - + ]: 1201 : if (!ri_query_cache)
3726 : 0 : ri_InitHashTables();
3727 : :
3728 : : /*
3729 : : * Add the new plan. We might be overwriting an entry previously found
3730 : : * invalid by ri_FetchPreparedPlan.
3731 : : */
3732 : 1201 : entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
3733 : : key,
3734 : : HASH_ENTER, &found);
3735 : : Assert(!found || entry->plan == NULL);
3736 : 1201 : entry->plan = plan;
3737 : 1201 : }
3738 : :
3739 : :
3740 : : /*
3741 : : * ri_KeysEqual -
3742 : : *
3743 : : * Check if all key values in OLD and NEW are "equivalent":
3744 : : * For normal FKs we check for equality.
3745 : : * For temporal FKs we check that the PK side is a superset of its old value,
3746 : : * or the FK side is a subset of its old value.
3747 : : *
3748 : : * Note: at some point we might wish to redefine this as checking for
3749 : : * "IS NOT DISTINCT" rather than "=", that is, allow two nulls to be
3750 : : * considered equal. Currently there is no need since all callers have
3751 : : * previously found at least one of the rows to contain no nulls.
3752 : : */
3753 : : static bool
3754 : 1424 : ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot,
3755 : : const RI_ConstraintInfo *riinfo, bool rel_is_pk)
3756 : : {
3757 : : const int16 *attnums;
3758 : :
3759 [ + + ]: 1424 : if (rel_is_pk)
3760 : 935 : attnums = riinfo->pk_attnums;
3761 : : else
3762 : 489 : attnums = riinfo->fk_attnums;
3763 : :
3764 : : /* XXX: could be worthwhile to fetch all necessary attrs at once */
3765 [ + + ]: 2202 : for (int i = 0; i < riinfo->nkeys; i++)
3766 : : {
3767 : : Datum oldvalue;
3768 : : Datum newvalue;
3769 : : bool isnull;
3770 : :
3771 : : /*
3772 : : * Get one attribute's oldvalue. If it is NULL - they're not equal.
3773 : : */
3774 : 1648 : oldvalue = slot_getattr(oldslot, attnums[i], &isnull);
3775 [ + + ]: 1648 : if (isnull)
3776 : 870 : return false;
3777 : :
3778 : : /*
3779 : : * Get one attribute's newvalue. If it is NULL - they're not equal.
3780 : : */
3781 : 1630 : newvalue = slot_getattr(newslot, attnums[i], &isnull);
3782 [ + + ]: 1630 : if (isnull)
3783 : 2 : return false;
3784 : :
3785 [ + + ]: 1628 : if (rel_is_pk)
3786 : : {
3787 : : /*
3788 : : * If we are looking at the PK table, then do a bytewise
3789 : : * comparison. We must propagate PK changes if the value is
3790 : : * changed to one that "looks" different but would compare as
3791 : : * equal using the equality operator. This only makes a
3792 : : * difference for ON UPDATE CASCADE, but for consistency we treat
3793 : : * all changes to the PK the same.
3794 : : */
3795 : 1101 : CompactAttribute *att = TupleDescCompactAttr(oldslot->tts_tupleDescriptor, attnums[i] - 1);
3796 : :
3797 [ + + ]: 1101 : if (!datum_image_eq(oldvalue, newvalue, att->attbyval, att->attlen))
3798 : 641 : return false;
3799 : : }
3800 : : else
3801 : : {
3802 : : Oid eq_opr;
3803 : :
3804 : : /*
3805 : : * When comparing the PERIOD columns we can skip the check
3806 : : * whenever the referencing column stayed equal or shrank, so test
3807 : : * with the contained-by operator instead.
3808 : : */
3809 [ + + + + ]: 527 : if (riinfo->hasperiod && i == riinfo->nkeys - 1)
3810 : 32 : eq_opr = riinfo->period_contained_by_oper;
3811 : : else
3812 : 495 : eq_opr = riinfo->ff_eq_oprs[i];
3813 : :
3814 : : /*
3815 : : * For the FK table, compare with the appropriate equality
3816 : : * operator. Changes that compare equal will still satisfy the
3817 : : * constraint after the update.
3818 : : */
3819 [ + + ]: 527 : if (!ri_CompareWithCast(eq_opr, RIAttType(rel, attnums[i]), RIAttCollation(rel, attnums[i]),
3820 : : newvalue, oldvalue))
3821 : 209 : return false;
3822 : : }
3823 : : }
3824 : :
3825 : 554 : return true;
3826 : : }
3827 : :
3828 : :
3829 : : /*
3830 : : * ri_CompareWithCast -
3831 : : *
3832 : : * Call the appropriate comparison operator for two values.
3833 : : * Normally this is equality, but for the PERIOD part of foreign keys
3834 : : * it is ContainedBy, so the order of lhs vs rhs is significant.
3835 : : * See below for how the collation is applied.
3836 : : *
3837 : : * NB: we have already checked that neither value is null.
3838 : : */
3839 : : static bool
3840 : 527 : ri_CompareWithCast(Oid eq_opr, Oid typeid, Oid collid,
3841 : : Datum lhs, Datum rhs)
3842 : : {
3843 : 527 : RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
3844 : :
3845 : : /* Do we need to cast the values? */
3846 [ + + ]: 527 : if (OidIsValid(entry->cast_func_finfo.fn_oid))
3847 : : {
3848 : 8 : lhs = FunctionCall3(&entry->cast_func_finfo,
3849 : : lhs,
3850 : : Int32GetDatum(-1), /* typmod */
3851 : : BoolGetDatum(false)); /* implicit coercion */
3852 : 8 : rhs = FunctionCall3(&entry->cast_func_finfo,
3853 : : rhs,
3854 : : Int32GetDatum(-1), /* typmod */
3855 : : BoolGetDatum(false)); /* implicit coercion */
3856 : : }
3857 : :
3858 : : /*
3859 : : * Apply the comparison operator.
3860 : : *
3861 : : * Note: This function is part of a call stack that determines whether an
3862 : : * update to a row is significant enough that it needs checking or action
3863 : : * on the other side of a foreign-key constraint. Therefore, the
3864 : : * comparison here would need to be done with the collation of the *other*
3865 : : * table. For simplicity (e.g., we might not even have the other table
3866 : : * open), we'll use our own collation. This is fine because we require
3867 : : * that both collations have the same notion of equality (either they are
3868 : : * both deterministic or else they are both the same).
3869 : : *
3870 : : * With range/multirangetypes, the collation of the base type is stored as
3871 : : * part of the rangetype (pg_range.rngcollation), and always used, so
3872 : : * there is no danger of inconsistency even using a non-equals operator.
3873 : : * But if we support arbitrary types with PERIOD, we should perhaps just
3874 : : * always force a re-check.
3875 : : */
3876 : 527 : return DatumGetBool(FunctionCall2Coll(&entry->eq_opr_finfo, collid, lhs, rhs));
3877 : : }
3878 : :
3879 : : /*
3880 : : * ri_HashCompareOp -
3881 : : *
3882 : : * Look up or create a cache entry for the given equality operator and
3883 : : * the caller's value type (typeid). The entry holds the operator's
3884 : : * FmgrInfo and, if typeid doesn't match what the operator expects as
3885 : : * its right-hand input, a cast function to coerce the value before
3886 : : * comparison.
3887 : : */
3888 : : static RI_CompareHashEntry *
3889 : 1680 : ri_HashCompareOp(Oid eq_opr, Oid typeid)
3890 : : {
3891 : : RI_CompareKey key;
3892 : : RI_CompareHashEntry *entry;
3893 : : bool found;
3894 : :
3895 : : /*
3896 : : * On the first call initialize the hashtable
3897 : : */
3898 [ - + ]: 1680 : if (!ri_compare_cache)
3899 : 0 : ri_InitHashTables();
3900 : :
3901 : : /*
3902 : : * Find or create a hash entry. Note we're assuming RI_CompareKey
3903 : : * contains no struct padding.
3904 : : */
3905 : 1680 : key.eq_opr = eq_opr;
3906 : 1680 : key.typeid = typeid;
3907 : 1680 : entry = (RI_CompareHashEntry *) hash_search(ri_compare_cache,
3908 : : &key,
3909 : : HASH_ENTER, &found);
3910 [ + + ]: 1680 : if (!found)
3911 : 293 : entry->valid = false;
3912 : :
3913 : : /*
3914 : : * If not already initialized, do so. Since we'll keep this hash entry
3915 : : * for the life of the backend, put any subsidiary info for the function
3916 : : * cache structs into TopMemoryContext.
3917 : : */
3918 [ + + ]: 1680 : if (!entry->valid)
3919 : : {
3920 : : Oid lefttype,
3921 : : righttype,
3922 : : castfunc;
3923 : : CoercionPathType pathtype;
3924 : :
3925 : : /* We always need to know how to call the equality operator */
3926 : 293 : fmgr_info_cxt(get_opcode(eq_opr), &entry->eq_opr_finfo,
3927 : : TopMemoryContext);
3928 : :
3929 : : /*
3930 : : * If we chose to use a cast from FK to PK type, we may have to apply
3931 : : * the cast function to get to the operator's input type.
3932 : : *
3933 : : * XXX eventually it would be good to support array-coercion cases
3934 : : * here and in ri_CompareWithCast(). At the moment there is no point
3935 : : * because cases involving nonidentical array types will be rejected
3936 : : * at constraint creation time.
3937 : : *
3938 : : * XXX perhaps also consider supporting CoerceViaIO? No need at the
3939 : : * moment since that will never be generated for implicit coercions.
3940 : : */
3941 : 293 : op_input_types(eq_opr, &lefttype, &righttype);
3942 : :
3943 : : /*
3944 : : * pf_eq_oprs (used by the fast path) can be cross-type when the FK
3945 : : * and PK columns differ in type, e.g. int48eq for int4 PK / int8 FK.
3946 : : * If the FK column's type, or the base type of a domain over it,
3947 : : * already matches what the operator expects as its right-hand input,
3948 : : * no cast is needed.
3949 : : */
3950 [ + + ]: 293 : if (getBaseType(typeid) == righttype)
3951 : 245 : castfunc = InvalidOid; /* simplest case */
3952 : : else
3953 : : {
3954 : 48 : pathtype = find_coercion_pathway(lefttype, typeid,
3955 : : COERCION_IMPLICIT,
3956 : : &castfunc);
3957 [ + + + - ]: 48 : if (pathtype != COERCION_PATH_FUNC &&
3958 : : pathtype != COERCION_PATH_RELABELTYPE)
3959 : : {
3960 : : /*
3961 : : * The declared input type of the eq_opr might be a
3962 : : * polymorphic type such as ANYARRAY or ANYENUM, or other
3963 : : * special cases such as RECORD; find_coercion_pathway
3964 : : * currently doesn't subsume these special cases.
3965 : : */
3966 [ - + ]: 16 : if (!IsBinaryCoercible(typeid, lefttype))
3967 [ # # ]: 0 : elog(ERROR, "no conversion function from %s to %s",
3968 : : format_type_be(typeid),
3969 : : format_type_be(lefttype));
3970 : : }
3971 : : }
3972 [ + + ]: 293 : if (OidIsValid(castfunc))
3973 : 32 : fmgr_info_cxt(castfunc, &entry->cast_func_finfo,
3974 : : TopMemoryContext);
3975 : : else
3976 : 261 : entry->cast_func_finfo.fn_oid = InvalidOid;
3977 : 293 : entry->valid = true;
3978 : : }
3979 : :
3980 : 1680 : return entry;
3981 : : }
3982 : :
3983 : :
3984 : : /*
3985 : : * Given a trigger function OID, determine whether it is an RI trigger,
3986 : : * and if so whether it is attached to PK or FK relation.
3987 : : */
3988 : : int
3989 : 5570 : RI_FKey_trigger_type(Oid tgfoid)
3990 : : {
3991 [ + + + ]: 5570 : switch (tgfoid)
3992 : : {
3993 : 1972 : case F_RI_FKEY_CASCADE_DEL:
3994 : : case F_RI_FKEY_CASCADE_UPD:
3995 : : case F_RI_FKEY_RESTRICT_DEL:
3996 : : case F_RI_FKEY_RESTRICT_UPD:
3997 : : case F_RI_FKEY_SETNULL_DEL:
3998 : : case F_RI_FKEY_SETNULL_UPD:
3999 : : case F_RI_FKEY_SETDEFAULT_DEL:
4000 : : case F_RI_FKEY_SETDEFAULT_UPD:
4001 : : case F_RI_FKEY_NOACTION_DEL:
4002 : : case F_RI_FKEY_NOACTION_UPD:
4003 : 1972 : return RI_TRIGGER_PK;
4004 : :
4005 : 1765 : case F_RI_FKEY_CHECK_INS:
4006 : : case F_RI_FKEY_CHECK_UPD:
4007 : 1765 : return RI_TRIGGER_FK;
4008 : : }
4009 : :
4010 : 1833 : return RI_TRIGGER_NONE;
4011 : : }
4012 : :
4013 : : /*
4014 : : * AtEOXact_RI
4015 : : * End-of-transaction cleanup for referential integrity.
4016 : : *
4017 : : * Currently this only releases fast-path metadata detached during the
4018 : : * transaction. InvalidateConstraintCacheCallBack() cannot free a
4019 : : * FastPathMeta when it detaches one, because an RI check further up the
4020 : : * stack may still hold a pointer into it. It queues them on
4021 : : * ri_fpmeta_dead_list instead, and we release them here, where no such
4022 : : * reference can exist. isCommit is accepted for consistency with the
4023 : : * other AtEOXact_* routines but is not used: the release is the same on
4024 : : * the commit and the abort path.
4025 : : *
4026 : : * There is no AtEOSubXact_RI() counterpart. Nothing here is scoped to a
4027 : : * subtransaction: a detached FastPathMeta stays reachable from the dead
4028 : : * list whichever subtransaction detached it, and a check holding a pointer
4029 : : * into one may be running at an outer level, so releasing at subtransaction
4030 : : * end would be unsafe as well as unnecessary.
4031 : : */
4032 : : void
4033 : 642888 : AtEOXact_RI(bool isCommit)
4034 : : {
4035 [ + + ]: 643603 : while (ri_fpmeta_dead_list != NULL)
4036 : : {
4037 : 715 : FastPathMeta *dead = ri_fpmeta_dead_list;
4038 : :
4039 : 715 : ri_fpmeta_dead_list = dead->next_dead;
4040 : 715 : MemoryContextDelete(dead->scratch_cxt);
4041 : 715 : pfree(dead);
4042 : : }
4043 : 642888 : }
|