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