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