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