Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * dependency.c
4 : : * Routines to support inter-object dependencies.
5 : : *
6 : : *
7 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 : : * Portions Copyright (c) 1994, Regents of the University of California
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/catalog/dependency.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/genam.h"
18 : : #include "access/htup_details.h"
19 : : #include "access/table.h"
20 : : #include "access/xact.h"
21 : : #include "catalog/catalog.h"
22 : : #include "catalog/dependency.h"
23 : : #include "catalog/heap.h"
24 : : #include "catalog/index.h"
25 : : #include "catalog/namespace.h"
26 : : #include "catalog/objectaccess.h"
27 : : #include "catalog/pg_am.h"
28 : : #include "catalog/pg_amop.h"
29 : : #include "catalog/pg_amproc.h"
30 : : #include "catalog/pg_attrdef.h"
31 : : #include "catalog/pg_authid.h"
32 : : #include "catalog/pg_auth_members.h"
33 : : #include "catalog/pg_cast.h"
34 : : #include "catalog/pg_collation.h"
35 : : #include "catalog/pg_constraint.h"
36 : : #include "catalog/pg_conversion.h"
37 : : #include "catalog/pg_database.h"
38 : : #include "catalog/pg_default_acl.h"
39 : : #include "catalog/pg_depend.h"
40 : : #include "catalog/pg_event_trigger.h"
41 : : #include "catalog/pg_extension.h"
42 : : #include "catalog/pg_foreign_data_wrapper.h"
43 : : #include "catalog/pg_foreign_server.h"
44 : : #include "catalog/pg_init_privs.h"
45 : : #include "catalog/pg_language.h"
46 : : #include "catalog/pg_largeobject.h"
47 : : #include "catalog/pg_namespace.h"
48 : : #include "catalog/pg_opclass.h"
49 : : #include "catalog/pg_operator.h"
50 : : #include "catalog/pg_opfamily.h"
51 : : #include "catalog/pg_parameter_acl.h"
52 : : #include "catalog/pg_policy.h"
53 : : #include "catalog/pg_proc.h"
54 : : #include "catalog/pg_publication.h"
55 : : #include "catalog/pg_publication_namespace.h"
56 : : #include "catalog/pg_publication_rel.h"
57 : : #include "catalog/pg_rewrite.h"
58 : : #include "catalog/pg_statistic_ext.h"
59 : : #include "catalog/pg_subscription.h"
60 : : #include "catalog/pg_tablespace.h"
61 : : #include "catalog/pg_transform.h"
62 : : #include "catalog/pg_trigger.h"
63 : : #include "catalog/pg_ts_config.h"
64 : : #include "catalog/pg_ts_dict.h"
65 : : #include "catalog/pg_ts_parser.h"
66 : : #include "catalog/pg_ts_template.h"
67 : : #include "catalog/pg_type.h"
68 : : #include "catalog/pg_user_mapping.h"
69 : : #include "commands/comment.h"
70 : : #include "commands/defrem.h"
71 : : #include "commands/event_trigger.h"
72 : : #include "commands/extension.h"
73 : : #include "commands/policy.h"
74 : : #include "commands/publicationcmds.h"
75 : : #include "commands/seclabel.h"
76 : : #include "commands/sequence.h"
77 : : #include "commands/trigger.h"
78 : : #include "commands/typecmds.h"
79 : : #include "funcapi.h"
80 : : #include "miscadmin.h"
81 : : #include "nodes/nodeFuncs.h"
82 : : #include "parser/parsetree.h"
83 : : #include "rewrite/rewriteRemove.h"
84 : : #include "storage/lmgr.h"
85 : : #include "utils/fmgroids.h"
86 : : #include "utils/lsyscache.h"
87 : : #include "utils/syscache.h"
88 : :
89 : :
90 : : /*
91 : : * Deletion processing requires additional state for each ObjectAddress that
92 : : * it's planning to delete. For simplicity and code-sharing we make the
93 : : * ObjectAddresses code support arrays with or without this extra state.
94 : : */
95 : : typedef struct
96 : : {
97 : : int flags; /* bitmask, see bit definitions below */
98 : : ObjectAddress dependee; /* object whose deletion forced this one */
99 : : } ObjectAddressExtra;
100 : :
101 : : /* ObjectAddressExtra flag bits */
102 : : #define DEPFLAG_ORIGINAL 0x0001 /* an original deletion target */
103 : : #define DEPFLAG_NORMAL 0x0002 /* reached via normal dependency */
104 : : #define DEPFLAG_AUTO 0x0004 /* reached via auto dependency */
105 : : #define DEPFLAG_INTERNAL 0x0008 /* reached via internal dependency */
106 : : #define DEPFLAG_PARTITION 0x0010 /* reached via partition dependency */
107 : : #define DEPFLAG_EXTENSION 0x0020 /* reached via extension dependency */
108 : : #define DEPFLAG_REVERSE 0x0040 /* reverse internal/extension link */
109 : : #define DEPFLAG_IS_PART 0x0080 /* has a partition dependency */
110 : : #define DEPFLAG_SUBOBJECT 0x0100 /* subobject of another deletable object */
111 : :
112 : :
113 : : /* expansible list of ObjectAddresses */
114 : : struct ObjectAddresses
115 : : {
116 : : ObjectAddress *refs; /* => palloc'd array */
117 : : ObjectAddressExtra *extras; /* => palloc'd array, or NULL if not used */
118 : : int numrefs; /* current number of references */
119 : : int maxrefs; /* current size of palloc'd array(s) */
120 : : };
121 : :
122 : : /* typedef ObjectAddresses appears in dependency.h */
123 : :
124 : : /* threaded list of ObjectAddresses, for recursion detection */
125 : : typedef struct ObjectAddressStack
126 : : {
127 : : const ObjectAddress *object; /* object being visited */
128 : : int flags; /* its current flag bits */
129 : : struct ObjectAddressStack *next; /* next outer stack level */
130 : : } ObjectAddressStack;
131 : :
132 : : /* temporary storage in findDependentObjects */
133 : : typedef struct
134 : : {
135 : : ObjectAddress obj; /* object to be deleted --- MUST BE FIRST */
136 : : int subflags; /* flags to pass down when recursing to obj */
137 : : } ObjectAddressAndFlags;
138 : :
139 : : /* for find_expr_references_walker */
140 : : typedef struct
141 : : {
142 : : ObjectAddresses *addrs; /* addresses being accumulated */
143 : : List *rtables; /* list of rangetables to resolve Vars */
144 : : } find_expr_references_context;
145 : :
146 : :
147 : : static void findDependentObjects(const ObjectAddress *object,
148 : : int objflags,
149 : : int flags,
150 : : ObjectAddressStack *stack,
151 : : ObjectAddresses *targetObjects,
152 : : const ObjectAddresses *pendingObjects,
153 : : Relation *depRel);
154 : : static void reportDependentObjects(const ObjectAddresses *targetObjects,
155 : : DropBehavior behavior,
156 : : int flags,
157 : : const ObjectAddress *origObject);
158 : : static void deleteOneObject(const ObjectAddress *object,
159 : : Relation *depRel, int32 flags);
160 : : static void doDeletion(const ObjectAddress *object, int flags);
161 : : static void add_target_column_dependencies(List *targetList, Oid relid,
162 : : find_expr_references_context *context);
163 : : static bool find_expr_references_walker(Node *node,
164 : : find_expr_references_context *context);
165 : : static void process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum,
166 : : find_expr_references_context *context);
167 : : static void eliminate_duplicate_dependencies(ObjectAddresses *addrs);
168 : : static int object_address_comparator(const void *a, const void *b);
169 : : static void add_object_address(Oid classId, Oid objectId, int32 subId,
170 : : ObjectAddresses *addrs);
171 : : static void add_exact_object_address_extra(const ObjectAddress *object,
172 : : const ObjectAddressExtra *extra,
173 : : ObjectAddresses *addrs);
174 : : static bool object_address_present_add_flags(const ObjectAddress *object,
175 : : int flags,
176 : : ObjectAddresses *addrs);
177 : : static bool stack_address_present_add_flags(const ObjectAddress *object,
178 : : int flags,
179 : : ObjectAddressStack *stack);
180 : : static void DeleteInitPrivs(const ObjectAddress *object);
181 : :
182 : :
183 : : /*
184 : : * Go through the objects given running the final actions on them, and execute
185 : : * the actual deletion.
186 : : */
187 : : static void
188 : 24156 : deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel,
189 : : int flags)
190 : : {
191 : : int i;
192 : :
193 : : /*
194 : : * Keep track of objects for event triggers, if necessary.
195 : : */
196 [ + + + + ]: 24156 : if (trackDroppedObjectsNeeded() && !(flags & PERFORM_DELETION_INTERNAL))
197 : : {
198 [ + + ]: 3139 : for (i = 0; i < targetObjects->numrefs; i++)
199 : : {
200 : 2652 : const ObjectAddress *thisobj = &targetObjects->refs[i];
201 : 2652 : const ObjectAddressExtra *extra = &targetObjects->extras[i];
202 : 2652 : bool original = false;
203 : 2652 : bool normal = false;
204 : :
205 [ + + ]: 2652 : if (extra->flags & DEPFLAG_ORIGINAL)
206 : 542 : original = true;
207 [ + + ]: 2652 : if (extra->flags & DEPFLAG_NORMAL)
208 : 236 : normal = true;
209 [ - + ]: 2652 : if (extra->flags & DEPFLAG_REVERSE)
210 : 0 : normal = true;
211 : :
212 [ + + ]: 2652 : if (EventTriggerSupportsObject(thisobj))
213 : : {
214 : 2578 : EventTriggerSQLDropAddObject(thisobj, original, normal);
215 : : }
216 : : }
217 : : }
218 : :
219 : : /*
220 : : * Delete all the objects in the proper order, except that if told to, we
221 : : * should skip the original object(s).
222 : : */
223 [ + + ]: 178350 : for (i = 0; i < targetObjects->numrefs; i++)
224 : : {
225 : 154208 : ObjectAddress *thisobj = targetObjects->refs + i;
226 : 154208 : ObjectAddressExtra *thisextra = targetObjects->extras + i;
227 : :
228 [ + + ]: 154208 : if ((flags & PERFORM_DELETION_SKIP_ORIGINAL) &&
229 [ + + ]: 6683 : (thisextra->flags & DEPFLAG_ORIGINAL))
230 : 597 : continue;
231 : :
232 : 153611 : deleteOneObject(thisobj, depRel, flags);
233 : : }
234 : 24142 : }
235 : :
236 : : /*
237 : : * performDeletion: attempt to drop the specified object. If CASCADE
238 : : * behavior is specified, also drop any dependent objects (recursively).
239 : : * If RESTRICT behavior is specified, error out if there are any dependent
240 : : * objects, except for those that should be implicitly dropped anyway
241 : : * according to the dependency type.
242 : : *
243 : : * This is the outer control routine for all forms of DROP that drop objects
244 : : * that can participate in dependencies. Note that performMultipleDeletions
245 : : * is a variant on the same theme; if you change anything here you'll likely
246 : : * need to fix that too.
247 : : *
248 : : * Bits in the flags argument can include:
249 : : *
250 : : * PERFORM_DELETION_INTERNAL: indicates that the drop operation is not the
251 : : * direct result of a user-initiated action. For example, when a temporary
252 : : * schema is cleaned out so that a new backend can use it, or when a column
253 : : * default is dropped as an intermediate step while adding a new one, that's
254 : : * an internal operation. On the other hand, when we drop something because
255 : : * the user issued a DROP statement against it, that's not internal. Currently
256 : : * this suppresses calling event triggers and making some permissions checks.
257 : : *
258 : : * PERFORM_DELETION_CONCURRENTLY: perform the drop concurrently. This does
259 : : * not currently work for anything except dropping indexes; don't set it for
260 : : * other object types or you may get strange results.
261 : : *
262 : : * PERFORM_DELETION_QUIETLY: reduce message level from NOTICE to DEBUG2.
263 : : *
264 : : * PERFORM_DELETION_SKIP_ORIGINAL: do not delete the specified object(s),
265 : : * but only what depends on it/them.
266 : : *
267 : : * PERFORM_DELETION_SKIP_EXTENSIONS: do not delete extensions, even when
268 : : * deleting objects that are part of an extension. This should generally
269 : : * be used only when dropping temporary objects.
270 : : *
271 : : * PERFORM_DELETION_CONCURRENT_LOCK: perform the drop normally but with a lock
272 : : * as if it were concurrent. This is used by REINDEX CONCURRENTLY.
273 : : *
274 : : */
275 : : void
276 : 4541 : performDeletion(const ObjectAddress *object,
277 : : DropBehavior behavior, int flags)
278 : : {
279 : : Relation depRel;
280 : : ObjectAddresses *targetObjects;
281 : :
282 : : /*
283 : : * We save some cycles by opening pg_depend just once and passing the
284 : : * Relation pointer down to all the recursive deletion steps.
285 : : */
286 : 4541 : depRel = table_open(DependRelationId, RowExclusiveLock);
287 : :
288 : : /*
289 : : * Acquire deletion lock on the target object. (Ideally the caller has
290 : : * done this already, but many places are sloppy about it.)
291 : : */
292 : 4541 : AcquireDeletionLock(object, 0);
293 : :
294 : : /*
295 : : * Construct a list of objects to delete (ie, the given object plus
296 : : * everything directly or indirectly dependent on it).
297 : : */
298 : 4541 : targetObjects = new_object_addresses();
299 : :
300 : 4541 : findDependentObjects(object,
301 : : DEPFLAG_ORIGINAL,
302 : : flags,
303 : : NULL, /* empty stack */
304 : : targetObjects,
305 : : NULL, /* no pendingObjects */
306 : : &depRel);
307 : :
308 : : /*
309 : : * Check if deletion is allowed, and report about cascaded deletes.
310 : : */
311 : 4541 : reportDependentObjects(targetObjects,
312 : : behavior,
313 : : flags,
314 : : object);
315 : :
316 : : /* do the deed */
317 : 4517 : deleteObjectsInList(targetObjects, &depRel, flags);
318 : :
319 : : /* And clean up */
320 : 4516 : free_object_addresses(targetObjects);
321 : :
322 : 4516 : table_close(depRel, RowExclusiveLock);
323 : 4516 : }
324 : :
325 : : /*
326 : : * performMultipleDeletions: Similar to performDeletion, but act on multiple
327 : : * objects at once.
328 : : *
329 : : * The main difference from issuing multiple performDeletion calls is that the
330 : : * list of objects that would be implicitly dropped, for each object to be
331 : : * dropped, is the union of the implicit-object list for all objects. This
332 : : * makes each check be more relaxed.
333 : : */
334 : : void
335 : 21999 : performMultipleDeletions(const ObjectAddresses *objects,
336 : : DropBehavior behavior, int flags)
337 : : {
338 : : Relation depRel;
339 : : ObjectAddresses *targetObjects;
340 : : int i;
341 : :
342 : : /* No work if no objects... */
343 [ + + ]: 21999 : if (objects->numrefs <= 0)
344 : 2087 : return;
345 : :
346 : : /*
347 : : * We save some cycles by opening pg_depend just once and passing the
348 : : * Relation pointer down to all the recursive deletion steps.
349 : : */
350 : 19912 : depRel = table_open(DependRelationId, RowExclusiveLock);
351 : :
352 : : /*
353 : : * Construct a list of objects to delete (ie, the given objects plus
354 : : * everything directly or indirectly dependent on them). Note that
355 : : * because we pass the whole objects list as pendingObjects context, we
356 : : * won't get a failure from trying to delete an object that is internally
357 : : * dependent on another one in the list; we'll just skip that object and
358 : : * delete it when we reach its owner.
359 : : */
360 : 19912 : targetObjects = new_object_addresses();
361 : :
362 [ + + ]: 43818 : for (i = 0; i < objects->numrefs; i++)
363 : : {
364 : 23937 : const ObjectAddress *thisobj = objects->refs + i;
365 : :
366 : : /*
367 : : * Acquire deletion lock on each target object. (Ideally the caller
368 : : * has done this already, but many places are sloppy about it.)
369 : : */
370 : 23937 : AcquireDeletionLock(thisobj, flags);
371 : :
372 : 23937 : findDependentObjects(thisobj,
373 : : DEPFLAG_ORIGINAL,
374 : : flags,
375 : : NULL, /* empty stack */
376 : : targetObjects,
377 : : objects,
378 : : &depRel);
379 : : }
380 : :
381 : : /*
382 : : * Check if deletion is allowed, and report about cascaded deletes.
383 : : *
384 : : * If there's exactly one object being deleted, report it the same way as
385 : : * in performDeletion(), else we have to be vaguer.
386 : : */
387 : 19881 : reportDependentObjects(targetObjects,
388 : : behavior,
389 : : flags,
390 [ + + ]: 19881 : (objects->numrefs == 1 ? objects->refs : NULL));
391 : :
392 : : /* do the deed */
393 : 19639 : deleteObjectsInList(targetObjects, &depRel, flags);
394 : :
395 : : /* And clean up */
396 : 19626 : free_object_addresses(targetObjects);
397 : :
398 : 19626 : table_close(depRel, RowExclusiveLock);
399 : : }
400 : :
401 : : /*
402 : : * findDependentObjects - find all objects that depend on 'object'
403 : : *
404 : : * For every object that depends on the starting object, acquire a deletion
405 : : * lock on the object, add it to targetObjects (if not already there),
406 : : * and recursively find objects that depend on it. An object's dependencies
407 : : * will be placed into targetObjects before the object itself; this means
408 : : * that the finished list's order represents a safe deletion order.
409 : : *
410 : : * The caller must already have a deletion lock on 'object' itself,
411 : : * but must not have added it to targetObjects. (Note: there are corner
412 : : * cases where we won't add the object either, and will also release the
413 : : * caller-taken lock. This is a bit ugly, but the API is set up this way
414 : : * to allow easy rechecking of an object's liveness after we lock it. See
415 : : * notes within the function.)
416 : : *
417 : : * When dropping a whole object (subId = 0), we find dependencies for
418 : : * its sub-objects too.
419 : : *
420 : : * object: the object to add to targetObjects and find dependencies on
421 : : * objflags: flags to be ORed into the object's targetObjects entry
422 : : * flags: PERFORM_DELETION_xxx flags for the deletion operation as a whole
423 : : * stack: list of objects being visited in current recursion; topmost item
424 : : * is the object that we recursed from (NULL for external callers)
425 : : * targetObjects: list of objects that are scheduled to be deleted
426 : : * pendingObjects: list of other objects slated for destruction, but
427 : : * not necessarily in targetObjects yet (can be NULL if none)
428 : : * *depRel: already opened pg_depend relation
429 : : *
430 : : * Note: objflags describes the reason for visiting this particular object
431 : : * at this time, and is not passed down when recursing. The flags argument
432 : : * is passed down, since it describes what we're doing overall.
433 : : */
434 : : static void
435 : 191151 : findDependentObjects(const ObjectAddress *object,
436 : : int objflags,
437 : : int flags,
438 : : ObjectAddressStack *stack,
439 : : ObjectAddresses *targetObjects,
440 : : const ObjectAddresses *pendingObjects,
441 : : Relation *depRel)
442 : : {
443 : : ScanKeyData key[3];
444 : : int nkeys;
445 : : SysScanDesc scan;
446 : : HeapTuple tup;
447 : : ObjectAddress otherObject;
448 : : ObjectAddress owningObject;
449 : : ObjectAddress partitionObject;
450 : : ObjectAddressAndFlags *dependentObjects;
451 : : int numDependentObjects;
452 : : int maxDependentObjects;
453 : : ObjectAddressStack mystack;
454 : : ObjectAddressExtra extra;
455 : :
456 : : /*
457 : : * If the target object is already being visited in an outer recursion
458 : : * level, just report the current objflags back to that level and exit.
459 : : * This is needed to avoid infinite recursion in the face of circular
460 : : * dependencies.
461 : : *
462 : : * The stack check alone would result in dependency loops being broken at
463 : : * an arbitrary point, ie, the first member object of the loop to be
464 : : * visited is the last one to be deleted. This is obviously unworkable.
465 : : * However, the check for internal dependency below guarantees that we
466 : : * will not break a loop at an internal dependency: if we enter the loop
467 : : * at an "owned" object we will switch and start at the "owning" object
468 : : * instead. We could probably hack something up to avoid breaking at an
469 : : * auto dependency, too, if we had to. However there are no known cases
470 : : * where that would be necessary.
471 : : */
472 [ + + ]: 191151 : if (stack_address_present_add_flags(object, objflags, stack))
473 : 34114 : return;
474 : :
475 : : /*
476 : : * since this function recurses, it could be driven to stack overflow,
477 : : * because of the deep dependency tree, not only due to dependency loops.
478 : : */
479 : 190929 : check_stack_depth();
480 : :
481 : : /*
482 : : * It's also possible that the target object has already been completely
483 : : * processed and put into targetObjects. If so, again we just add the
484 : : * specified objflags to its entry and return.
485 : : *
486 : : * (Note: in these early-exit cases we could release the caller-taken
487 : : * lock, since the object is presumably now locked multiple times; but it
488 : : * seems not worth the cycles.)
489 : : */
490 [ + + ]: 190929 : if (object_address_present_add_flags(object, objflags, targetObjects))
491 : 32662 : return;
492 : :
493 : : /*
494 : : * If the target object is pinned, we can just error out immediately; it
495 : : * won't have any objects recorded as depending on it.
496 : : */
497 [ + + ]: 158267 : if (IsPinnedObject(object->classId, object->objectId))
498 [ + - ]: 1 : ereport(ERROR,
499 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
500 : : errmsg("cannot drop %s because it is required by the database system",
501 : : getObjectDescription(object, false))));
502 : :
503 : : /*
504 : : * The target object might be internally dependent on some other object
505 : : * (its "owner"), and/or be a member of an extension (also considered its
506 : : * owner). If so, and if we aren't recursing from the owning object, we
507 : : * have to transform this deletion request into a deletion request of the
508 : : * owning object. (We'll eventually recurse back to this object, but the
509 : : * owning object has to be visited first so it will be deleted after.) The
510 : : * way to find out about this is to scan the pg_depend entries that show
511 : : * what this object depends on.
512 : : */
513 : 158266 : ScanKeyInit(&key[0],
514 : : Anum_pg_depend_classid,
515 : : BTEqualStrategyNumber, F_OIDEQ,
516 : 158266 : ObjectIdGetDatum(object->classId));
517 : 158266 : ScanKeyInit(&key[1],
518 : : Anum_pg_depend_objid,
519 : : BTEqualStrategyNumber, F_OIDEQ,
520 : 158266 : ObjectIdGetDatum(object->objectId));
521 [ + + ]: 158266 : if (object->objectSubId != 0)
522 : : {
523 : : /* Consider only dependencies of this sub-object */
524 : 1574 : ScanKeyInit(&key[2],
525 : : Anum_pg_depend_objsubid,
526 : : BTEqualStrategyNumber, F_INT4EQ,
527 : 1574 : Int32GetDatum(object->objectSubId));
528 : 1574 : nkeys = 3;
529 : : }
530 : : else
531 : : {
532 : : /* Consider dependencies of this object and any sub-objects it has */
533 : 156692 : nkeys = 2;
534 : : }
535 : :
536 : 158266 : scan = systable_beginscan(*depRel, DependDependerIndexId, true,
537 : : NULL, nkeys, key);
538 : :
539 : : /* initialize variables that loop may fill */
540 : 158266 : memset(&owningObject, 0, sizeof(owningObject));
541 : 158266 : memset(&partitionObject, 0, sizeof(partitionObject));
542 : :
543 [ + + ]: 376611 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
544 : : {
545 : 219575 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
546 : :
547 : 219575 : otherObject.classId = foundDep->refclassid;
548 : 219575 : otherObject.objectId = foundDep->refobjid;
549 : 219575 : otherObject.objectSubId = foundDep->refobjsubid;
550 : :
551 : : /*
552 : : * When scanning dependencies of a whole object, we may find rows
553 : : * linking sub-objects of the object to the object itself. (Normally,
554 : : * such a dependency is implicit, but we must make explicit ones in
555 : : * some cases involving partitioning.) We must ignore such rows to
556 : : * avoid infinite recursion.
557 : : */
558 [ + + ]: 219575 : if (otherObject.classId == object->classId &&
559 [ + + ]: 73333 : otherObject.objectId == object->objectId &&
560 [ + + ]: 3100 : object->objectSubId == 0)
561 : 3084 : continue;
562 : :
563 [ + + + + : 216491 : switch (foundDep->deptype)
+ - ]
564 : : {
565 : 124721 : case DEPENDENCY_NORMAL:
566 : : case DEPENDENCY_AUTO:
567 : : case DEPENDENCY_AUTO_EXTENSION:
568 : : /* no problem */
569 : 124721 : break;
570 : :
571 : 3213 : case DEPENDENCY_EXTENSION:
572 : :
573 : : /*
574 : : * If told to, ignore EXTENSION dependencies altogether. This
575 : : * flag is normally used to prevent dropping extensions during
576 : : * temporary-object cleanup, even if a temp object was created
577 : : * during an extension script.
578 : : */
579 [ + + ]: 3213 : if (flags & PERFORM_DELETION_SKIP_EXTENSIONS)
580 : 4 : break;
581 : :
582 : : /*
583 : : * If the other object is the extension currently being
584 : : * created/altered, ignore this dependency and continue with
585 : : * the deletion. This allows dropping of an extension's
586 : : * objects within the extension's scripts, as well as corner
587 : : * cases such as dropping a transient object created within
588 : : * such a script.
589 : : */
590 [ + + ]: 3209 : if (creating_extension &&
591 [ + - ]: 201 : otherObject.classId == ExtensionRelationId &&
592 [ + - ]: 201 : otherObject.objectId == CurrentExtensionObject)
593 : 201 : break;
594 : :
595 : : /* Otherwise, treat this like an internal dependency */
596 : : pg_fallthrough;
597 : :
598 : : case DEPENDENCY_INTERNAL:
599 : :
600 : : /*
601 : : * This object is part of the internal implementation of
602 : : * another object, or is part of the extension that is the
603 : : * other object. We have three cases:
604 : : *
605 : : * 1. At the outermost recursion level, we must disallow the
606 : : * DROP. However, if the owning object is listed in
607 : : * pendingObjects, just release the caller's lock and return;
608 : : * we'll eventually complete the DROP when we reach that entry
609 : : * in the pending list.
610 : : *
611 : : * Note: the above statement is true only if this pg_depend
612 : : * entry still exists by then; in principle, therefore, we
613 : : * could miss deleting an item the user told us to delete.
614 : : * However, no inconsistency can result: since we're at outer
615 : : * level, there is no object depending on this one.
616 : : */
617 [ + + ]: 84891 : if (stack == NULL)
618 : : {
619 [ + - - + ]: 52 : if (pendingObjects &&
620 : 26 : object_address_present(&otherObject, pendingObjects))
621 : : {
622 : 0 : systable_endscan(scan);
623 : : /* need to release caller's lock; see notes below */
624 : 0 : ReleaseDeletionLock(object);
625 : 0 : return;
626 : : }
627 : :
628 : : /*
629 : : * We postpone actually issuing the error message until
630 : : * after this loop, so that we can make the behavior
631 : : * independent of the ordering of pg_depend entries, at
632 : : * least if there's not more than one INTERNAL and one
633 : : * EXTENSION dependency. (If there's more, we'll complain
634 : : * about a random one of them.) Prefer to complain about
635 : : * EXTENSION, since that's generally a more important
636 : : * dependency.
637 : : */
638 [ - + ]: 26 : if (!OidIsValid(owningObject.classId) ||
639 [ # # ]: 0 : foundDep->deptype == DEPENDENCY_EXTENSION)
640 : 26 : owningObject = otherObject;
641 : 26 : break;
642 : : }
643 : :
644 : : /*
645 : : * 2. When recursing from the other end of this dependency,
646 : : * it's okay to continue with the deletion. This holds when
647 : : * recursing from a whole object that includes the nominal
648 : : * other end as a component, too. Since there can be more
649 : : * than one "owning" object, we have to allow matches that are
650 : : * more than one level down in the stack.
651 : : */
652 [ + + ]: 84865 : if (stack_address_present_add_flags(&otherObject, 0, stack))
653 : 83635 : break;
654 : :
655 : : /*
656 : : * 3. Not all the owning objects have been visited, so
657 : : * transform this deletion request into a delete of this
658 : : * owning object.
659 : : *
660 : : * First, release caller's lock on this object and get
661 : : * deletion lock on the owning object. (We must release
662 : : * caller's lock to avoid deadlock against a concurrent
663 : : * deletion of the owning object.)
664 : : */
665 : 1230 : ReleaseDeletionLock(object);
666 : 1230 : AcquireDeletionLock(&otherObject, 0);
667 : :
668 : : /*
669 : : * The owning object might have been deleted while we waited
670 : : * to lock it; if so, neither it nor the current object are
671 : : * interesting anymore. We test this by checking the
672 : : * pg_depend entry (see notes below).
673 : : */
674 [ - + ]: 1230 : if (!systable_recheck_tuple(scan, tup))
675 : : {
676 : 0 : systable_endscan(scan);
677 : 0 : ReleaseDeletionLock(&otherObject);
678 : 0 : return;
679 : : }
680 : :
681 : : /*
682 : : * One way or the other, we're done with the scan; might as
683 : : * well close it down before recursing, to reduce peak
684 : : * resource consumption.
685 : : */
686 : 1230 : systable_endscan(scan);
687 : :
688 : : /*
689 : : * Okay, recurse to the owning object instead of proceeding.
690 : : *
691 : : * We do not need to stack the current object; we want the
692 : : * traversal order to be as if the original reference had
693 : : * linked to the owning object instead of this one.
694 : : *
695 : : * The dependency type is a "reverse" dependency: we need to
696 : : * delete the owning object if this one is to be deleted, but
697 : : * this linkage is never a reason for an automatic deletion.
698 : : */
699 : 1230 : findDependentObjects(&otherObject,
700 : : DEPFLAG_REVERSE,
701 : : flags,
702 : : stack,
703 : : targetObjects,
704 : : pendingObjects,
705 : : depRel);
706 : :
707 : : /*
708 : : * The current target object should have been added to
709 : : * targetObjects while processing the owning object; but it
710 : : * probably got only the flag bits associated with the
711 : : * dependency we're looking at. We need to add the objflags
712 : : * that were passed to this recursion level, too, else we may
713 : : * get a bogus failure in reportDependentObjects (if, for
714 : : * example, we were called due to a partition dependency).
715 : : *
716 : : * If somehow the current object didn't get scheduled for
717 : : * deletion, bleat. (That would imply that somebody deleted
718 : : * this dependency record before the recursion got to it.)
719 : : * Another idea would be to reacquire lock on the current
720 : : * object and resume trying to delete it, but it seems not
721 : : * worth dealing with the race conditions inherent in that.
722 : : */
723 [ - + ]: 1230 : if (!object_address_present_add_flags(object, objflags,
724 : : targetObjects))
725 [ # # ]: 0 : elog(ERROR, "deletion of owning object %s failed to delete %s",
726 : : getObjectDescription(&otherObject, false),
727 : : getObjectDescription(object, false));
728 : :
729 : : /* And we're done here. */
730 : 1230 : return;
731 : :
732 : 3337 : case DEPENDENCY_PARTITION_PRI:
733 : :
734 : : /*
735 : : * Remember that this object has a partition-type dependency.
736 : : * After the dependency scan, we'll complain if we didn't find
737 : : * a reason to delete one of its partition dependencies.
738 : : */
739 : 3337 : objflags |= DEPFLAG_IS_PART;
740 : :
741 : : /*
742 : : * Also remember the primary partition owner, for error
743 : : * messages. If there are multiple primary owners (which
744 : : * there should not be), we'll report a random one of them.
745 : : */
746 : 3337 : partitionObject = otherObject;
747 : 3337 : break;
748 : :
749 : 3337 : case DEPENDENCY_PARTITION_SEC:
750 : :
751 : : /*
752 : : * Only use secondary partition owners in error messages if we
753 : : * find no primary owner (which probably shouldn't happen).
754 : : */
755 [ - + ]: 3337 : if (!(objflags & DEPFLAG_IS_PART))
756 : 0 : partitionObject = otherObject;
757 : :
758 : : /*
759 : : * Remember that this object has a partition-type dependency.
760 : : * After the dependency scan, we'll complain if we didn't find
761 : : * a reason to delete one of its partition dependencies.
762 : : */
763 : 3337 : objflags |= DEPFLAG_IS_PART;
764 : 3337 : break;
765 : :
766 : 0 : default:
767 [ # # ]: 0 : elog(ERROR, "unrecognized dependency type '%c' for %s",
768 : : foundDep->deptype, getObjectDescription(object, false));
769 : : break;
770 : : }
771 : : }
772 : :
773 : 157036 : systable_endscan(scan);
774 : :
775 : : /*
776 : : * If we found an INTERNAL or EXTENSION dependency when we're at outer
777 : : * level, complain about it now. If we also found a PARTITION dependency,
778 : : * we prefer to report the PARTITION dependency. This is arbitrary but
779 : : * seems to be more useful in practice.
780 : : */
781 [ + + ]: 157036 : if (OidIsValid(owningObject.classId))
782 : : {
783 : : char *otherObjDesc;
784 : :
785 [ + + ]: 26 : if (OidIsValid(partitionObject.classId))
786 : 8 : otherObjDesc = getObjectDescription(&partitionObject, false);
787 : : else
788 : 18 : otherObjDesc = getObjectDescription(&owningObject, false);
789 : :
790 [ + - ]: 26 : ereport(ERROR,
791 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
792 : : errmsg("cannot drop %s because %s requires it",
793 : : getObjectDescription(object, false), otherObjDesc),
794 : : errhint("You can drop %s instead.", otherObjDesc)));
795 : : }
796 : :
797 : : /*
798 : : * Next, identify all objects that directly depend on the current object.
799 : : * To ensure predictable deletion order, we collect them up in
800 : : * dependentObjects and sort the list before actually recursing. (The
801 : : * deletion order would be valid in any case, but doing this ensures
802 : : * consistent output from DROP CASCADE commands, which is helpful for
803 : : * regression testing.)
804 : : */
805 : 157010 : maxDependentObjects = 128; /* arbitrary initial allocation */
806 : 157010 : dependentObjects = palloc_array(ObjectAddressAndFlags, maxDependentObjects);
807 : 157010 : numDependentObjects = 0;
808 : :
809 : 157010 : ScanKeyInit(&key[0],
810 : : Anum_pg_depend_refclassid,
811 : : BTEqualStrategyNumber, F_OIDEQ,
812 : 157010 : ObjectIdGetDatum(object->classId));
813 : 157010 : ScanKeyInit(&key[1],
814 : : Anum_pg_depend_refobjid,
815 : : BTEqualStrategyNumber, F_OIDEQ,
816 : 157010 : ObjectIdGetDatum(object->objectId));
817 [ + + ]: 157010 : if (object->objectSubId != 0)
818 : : {
819 : 1558 : ScanKeyInit(&key[2],
820 : : Anum_pg_depend_refobjsubid,
821 : : BTEqualStrategyNumber, F_INT4EQ,
822 : 1558 : Int32GetDatum(object->objectSubId));
823 : 1558 : nkeys = 3;
824 : : }
825 : : else
826 : 155452 : nkeys = 2;
827 : :
828 : 157010 : scan = systable_beginscan(*depRel, DependReferenceIndexId, true,
829 : : NULL, nkeys, key);
830 : :
831 [ + + ]: 321541 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
832 : : {
833 : 164535 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
834 : : int subflags;
835 : :
836 : 164535 : otherObject.classId = foundDep->classid;
837 : 164535 : otherObject.objectId = foundDep->objid;
838 : 164535 : otherObject.objectSubId = foundDep->objsubid;
839 : :
840 : : /*
841 : : * If what we found is a sub-object of the current object, just ignore
842 : : * it. (Normally, such a dependency is implicit, but we must make
843 : : * explicit ones in some cases involving partitioning.)
844 : : */
845 [ + + ]: 164535 : if (otherObject.classId == object->classId &&
846 [ + + ]: 70187 : otherObject.objectId == object->objectId &&
847 [ + - ]: 3084 : object->objectSubId == 0)
848 : 3084 : continue;
849 : :
850 : : /*
851 : : * Must lock the dependent object before recursing to it.
852 : : */
853 : 161451 : AcquireDeletionLock(&otherObject, 0);
854 : :
855 : : /*
856 : : * The dependent object might have been deleted while we waited to
857 : : * lock it; if so, we don't need to do anything more with it. We can
858 : : * test this cheaply and independently of the object's type by seeing
859 : : * if the pg_depend tuple we are looking at is still live. (If the
860 : : * object got deleted, the tuple would have been deleted too.)
861 : : */
862 [ - + ]: 161451 : if (!systable_recheck_tuple(scan, tup))
863 : : {
864 : : /* release the now-useless lock */
865 : 0 : ReleaseDeletionLock(&otherObject);
866 : : /* and continue scanning for dependencies */
867 : 0 : continue;
868 : : }
869 : :
870 : : /*
871 : : * Check that the dependent object is not in a shared catalog, which
872 : : * is not supported by doDeletion().
873 : : */
874 [ + + ]: 161451 : if (IsSharedRelation(otherObject.classId))
875 : : {
876 : 4 : char *otherObjDesc = getObjectDescription(&otherObject,
877 : : false);
878 : :
879 [ + - ]: 4 : ereport(ERROR,
880 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
881 : : errmsg("cannot drop %s because %s depends on it",
882 : : getObjectDescription(object, false), otherObjDesc),
883 : : errhint("Drop %s first.", otherObjDesc)));
884 : : }
885 : :
886 : : /*
887 : : * We do need to delete it, so identify objflags to be passed down,
888 : : * which depend on the dependency type.
889 : : */
890 [ + + + + : 161447 : switch (foundDep->deptype)
+ - ]
891 : : {
892 : 21845 : case DEPENDENCY_NORMAL:
893 : 21845 : subflags = DEPFLAG_NORMAL;
894 : 21845 : break;
895 : 49911 : case DEPENDENCY_AUTO:
896 : : case DEPENDENCY_AUTO_EXTENSION:
897 : 49911 : subflags = DEPFLAG_AUTO;
898 : 49911 : break;
899 : 80632 : case DEPENDENCY_INTERNAL:
900 : 80632 : subflags = DEPFLAG_INTERNAL;
901 : 80632 : break;
902 : 6099 : case DEPENDENCY_PARTITION_PRI:
903 : : case DEPENDENCY_PARTITION_SEC:
904 : 6099 : subflags = DEPFLAG_PARTITION;
905 : 6099 : break;
906 : 2960 : case DEPENDENCY_EXTENSION:
907 : 2960 : subflags = DEPFLAG_EXTENSION;
908 : 2960 : break;
909 : 0 : default:
910 [ # # ]: 0 : elog(ERROR, "unrecognized dependency type '%c' for %s",
911 : : foundDep->deptype, getObjectDescription(object, false));
912 : : subflags = 0; /* keep compiler quiet */
913 : : break;
914 : : }
915 : :
916 : : /* And add it to the pending-objects list */
917 [ + + ]: 161447 : if (numDependentObjects >= maxDependentObjects)
918 : : {
919 : : /* enlarge array if needed */
920 : 24 : maxDependentObjects *= 2;
921 : 24 : dependentObjects = repalloc_array(dependentObjects,
922 : : ObjectAddressAndFlags,
923 : : maxDependentObjects);
924 : : }
925 : :
926 : 161447 : dependentObjects[numDependentObjects].obj = otherObject;
927 : 161447 : dependentObjects[numDependentObjects].subflags = subflags;
928 : 161447 : numDependentObjects++;
929 : : }
930 : :
931 : 157006 : systable_endscan(scan);
932 : :
933 : : /*
934 : : * Now we can sort the dependent objects into a stable visitation order.
935 : : * It's safe to use object_address_comparator here since the obj field is
936 : : * first within ObjectAddressAndFlags.
937 : : */
938 [ + + ]: 157006 : if (numDependentObjects > 1)
939 : 34294 : qsort(dependentObjects, numDependentObjects,
940 : : sizeof(ObjectAddressAndFlags),
941 : : object_address_comparator);
942 : :
943 : : /*
944 : : * Now recurse to the dependent objects. We must visit them first since
945 : : * they have to be deleted before the current object.
946 : : */
947 : 157006 : mystack.object = object; /* set up a new stack level */
948 : 157006 : mystack.flags = objflags;
949 : 157006 : mystack.next = stack;
950 : :
951 [ + + ]: 318449 : for (int i = 0; i < numDependentObjects; i++)
952 : : {
953 : 161443 : ObjectAddressAndFlags *depObj = dependentObjects + i;
954 : :
955 : 161443 : findDependentObjects(&depObj->obj,
956 : : depObj->subflags,
957 : : flags,
958 : : &mystack,
959 : : targetObjects,
960 : : pendingObjects,
961 : : depRel);
962 : : }
963 : :
964 : 157006 : pfree(dependentObjects);
965 : :
966 : : /*
967 : : * Finally, we can add the target object to targetObjects. Be careful to
968 : : * include any flags that were passed back down to us from inner recursion
969 : : * levels. Record the "dependee" as being either the most important
970 : : * partition owner if there is one, else the object we recursed from, if
971 : : * any. (The logic in reportDependentObjects() is such that it can only
972 : : * need one of those objects.)
973 : : */
974 : 157006 : extra.flags = mystack.flags;
975 [ + + ]: 157006 : if (extra.flags & DEPFLAG_IS_PART)
976 : 3329 : extra.dependee = partitionObject;
977 [ + + ]: 153677 : else if (stack)
978 : 125816 : extra.dependee = *stack->object;
979 : : else
980 : 27861 : memset(&extra.dependee, 0, sizeof(extra.dependee));
981 : 157006 : add_exact_object_address_extra(object, &extra, targetObjects);
982 : : }
983 : :
984 : : /*
985 : : * reportDependentObjects - report about dependencies, and fail if RESTRICT
986 : : *
987 : : * Tell the user about dependent objects that we are going to delete
988 : : * (or would need to delete, but are prevented by RESTRICT mode);
989 : : * then error out if there are any and it's not CASCADE mode.
990 : : *
991 : : * targetObjects: list of objects that are scheduled to be deleted
992 : : * behavior: RESTRICT or CASCADE
993 : : * flags: other flags for the deletion operation
994 : : * origObject: base object of deletion, or NULL if not available
995 : : * (the latter case occurs in DROP OWNED)
996 : : */
997 : : static void
998 : 24422 : reportDependentObjects(const ObjectAddresses *targetObjects,
999 : : DropBehavior behavior,
1000 : : int flags,
1001 : : const ObjectAddress *origObject)
1002 : : {
1003 [ + + ]: 24422 : int msglevel = (flags & PERFORM_DELETION_QUIETLY) ? DEBUG2 : NOTICE;
1004 : 24422 : bool ok = true;
1005 : : StringInfoData clientdetail;
1006 : : StringInfoData logdetail;
1007 : 24422 : int numReportedClient = 0;
1008 : 24422 : int numNotReportedClient = 0;
1009 : : int i;
1010 : :
1011 : : /*
1012 : : * If we need to delete any partition-dependent objects, make sure that
1013 : : * we're deleting at least one of their partition dependencies, too. That
1014 : : * can be detected by checking that we reached them by a PARTITION
1015 : : * dependency at some point.
1016 : : *
1017 : : * We just report the first such object, as in most cases the only way to
1018 : : * trigger this complaint is to explicitly try to delete one partition of
1019 : : * a partitioned object.
1020 : : */
1021 [ + + ]: 181408 : for (i = 0; i < targetObjects->numrefs; i++)
1022 : : {
1023 : 157006 : const ObjectAddressExtra *extra = &targetObjects->extras[i];
1024 : :
1025 [ + + ]: 157006 : if ((extra->flags & DEPFLAG_IS_PART) &&
1026 [ + + ]: 3329 : !(extra->flags & DEPFLAG_PARTITION))
1027 : : {
1028 : 20 : const ObjectAddress *object = &targetObjects->refs[i];
1029 : 20 : char *otherObjDesc = getObjectDescription(&extra->dependee,
1030 : : false);
1031 : :
1032 [ + - ]: 20 : ereport(ERROR,
1033 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1034 : : errmsg("cannot drop %s because %s requires it",
1035 : : getObjectDescription(object, false), otherObjDesc),
1036 : : errhint("You can drop %s instead.", otherObjDesc)));
1037 : : }
1038 : : }
1039 : :
1040 : : /*
1041 : : * If no error is to be thrown, and the msglevel is too low to be shown to
1042 : : * either client or server log, there's no need to do any of the rest of
1043 : : * the work.
1044 : : */
1045 [ + + ]: 24402 : if (behavior == DROP_CASCADE &&
1046 [ + + ]: 2340 : !message_level_is_interesting(msglevel))
1047 : 653 : return;
1048 : :
1049 : : /*
1050 : : * We limit the number of dependencies reported to the client to
1051 : : * MAX_REPORTED_DEPS, since client software may not deal well with
1052 : : * enormous error strings. The server log always gets a full report.
1053 : : */
1054 : : #define MAX_REPORTED_DEPS 100
1055 : :
1056 : 23749 : initStringInfo(&clientdetail);
1057 : 23749 : initStringInfo(&logdetail);
1058 : :
1059 : : /*
1060 : : * We process the list back to front (ie, in dependency order not deletion
1061 : : * order), since this makes for a more understandable display.
1062 : : */
1063 [ + + ]: 172147 : for (i = targetObjects->numrefs - 1; i >= 0; i--)
1064 : : {
1065 : 148398 : const ObjectAddress *obj = &targetObjects->refs[i];
1066 : 148398 : const ObjectAddressExtra *extra = &targetObjects->extras[i];
1067 : : char *objDesc;
1068 : :
1069 : : /* Ignore the original deletion target(s) */
1070 [ + + ]: 148398 : if (extra->flags & DEPFLAG_ORIGINAL)
1071 : 27790 : continue;
1072 : :
1073 : : /* Also ignore sub-objects; we'll report the whole object elsewhere */
1074 [ + + ]: 120608 : if (extra->flags & DEPFLAG_SUBOBJECT)
1075 : 24 : continue;
1076 : :
1077 : 120584 : objDesc = getObjectDescription(obj, false);
1078 : :
1079 : : /* An object being dropped concurrently doesn't need to be reported */
1080 [ - + ]: 120584 : if (objDesc == NULL)
1081 : 0 : continue;
1082 : :
1083 : : /*
1084 : : * If, at any stage of the recursive search, we reached the object via
1085 : : * an AUTO, INTERNAL, PARTITION, or EXTENSION dependency, then it's
1086 : : * okay to delete it even in RESTRICT mode.
1087 : : */
1088 [ + + ]: 120584 : if (extra->flags & (DEPFLAG_AUTO |
1089 : : DEPFLAG_INTERNAL |
1090 : : DEPFLAG_PARTITION |
1091 : : DEPFLAG_EXTENSION))
1092 : : {
1093 : : /*
1094 : : * auto-cascades are reported at DEBUG2, not msglevel. We don't
1095 : : * try to combine them with the regular message because the
1096 : : * results are too confusing when client_min_messages and
1097 : : * log_min_messages are different.
1098 : : */
1099 [ + + ]: 115036 : ereport(DEBUG2,
1100 : : (errmsg_internal("drop auto-cascades to %s",
1101 : : objDesc)));
1102 : : }
1103 [ + + ]: 5548 : else if (behavior == DROP_RESTRICT)
1104 : : {
1105 : 391 : char *otherDesc = getObjectDescription(&extra->dependee,
1106 : : false);
1107 : :
1108 [ + - ]: 391 : if (otherDesc)
1109 : : {
1110 [ + - ]: 391 : if (numReportedClient < MAX_REPORTED_DEPS)
1111 : : {
1112 : : /* separate entries with a newline */
1113 [ + + ]: 391 : if (clientdetail.len != 0)
1114 : 145 : appendStringInfoChar(&clientdetail, '\n');
1115 : 391 : appendStringInfo(&clientdetail, _("%s depends on %s"),
1116 : : objDesc, otherDesc);
1117 : 391 : numReportedClient++;
1118 : : }
1119 : : else
1120 : 0 : numNotReportedClient++;
1121 : : /* separate entries with a newline */
1122 [ + + ]: 391 : if (logdetail.len != 0)
1123 : 145 : appendStringInfoChar(&logdetail, '\n');
1124 : 391 : appendStringInfo(&logdetail, _("%s depends on %s"),
1125 : : objDesc, otherDesc);
1126 : 391 : pfree(otherDesc);
1127 : : }
1128 : : else
1129 : 0 : numNotReportedClient++;
1130 : 391 : ok = false;
1131 : : }
1132 : : else
1133 : : {
1134 [ + + ]: 5157 : if (numReportedClient < MAX_REPORTED_DEPS)
1135 : : {
1136 : : /* separate entries with a newline */
1137 [ + + ]: 4238 : if (clientdetail.len != 0)
1138 : 3221 : appendStringInfoChar(&clientdetail, '\n');
1139 : 4238 : appendStringInfo(&clientdetail, _("drop cascades to %s"),
1140 : : objDesc);
1141 : 4238 : numReportedClient++;
1142 : : }
1143 : : else
1144 : 919 : numNotReportedClient++;
1145 : : /* separate entries with a newline */
1146 [ + + ]: 5157 : if (logdetail.len != 0)
1147 : 4140 : appendStringInfoChar(&logdetail, '\n');
1148 : 5157 : appendStringInfo(&logdetail, _("drop cascades to %s"),
1149 : : objDesc);
1150 : : }
1151 : :
1152 : 120584 : pfree(objDesc);
1153 : : }
1154 : :
1155 [ + + ]: 23749 : if (numNotReportedClient > 0)
1156 : 10 : appendStringInfo(&clientdetail, ngettext("\nand %d other object "
1157 : : "(see server log for list)",
1158 : : "\nand %d other objects "
1159 : : "(see server log for list)",
1160 : : numNotReportedClient),
1161 : : numNotReportedClient);
1162 : :
1163 [ + + ]: 23749 : if (!ok)
1164 : : {
1165 [ + + ]: 246 : if (origObject)
1166 [ + - ]: 242 : ereport(ERROR,
1167 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1168 : : errmsg("cannot drop %s because other objects depend on it",
1169 : : getObjectDescription(origObject, false)),
1170 : : errdetail_internal("%s", clientdetail.data),
1171 : : errdetail_log("%s", logdetail.data),
1172 : : errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1173 : : else
1174 [ + - ]: 4 : ereport(ERROR,
1175 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1176 : : errmsg("cannot drop desired object(s) because other objects depend on them"),
1177 : : errdetail_internal("%s", clientdetail.data),
1178 : : errdetail_log("%s", logdetail.data),
1179 : : errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1180 : : }
1181 [ + + ]: 23503 : else if (numReportedClient > 1)
1182 : : {
1183 [ + - ]: 472 : ereport(msglevel,
1184 : : (errmsg_plural("drop cascades to %d other object",
1185 : : "drop cascades to %d other objects",
1186 : : numReportedClient + numNotReportedClient,
1187 : : numReportedClient + numNotReportedClient),
1188 : : errdetail_internal("%s", clientdetail.data),
1189 : : errdetail_log("%s", logdetail.data)));
1190 : : }
1191 [ + + ]: 23031 : else if (numReportedClient == 1)
1192 : : {
1193 : : /* we just use the single item as-is */
1194 [ + - ]: 545 : ereport(msglevel,
1195 : : (errmsg_internal("%s", clientdetail.data)));
1196 : : }
1197 : :
1198 : 23503 : pfree(clientdetail.data);
1199 : 23503 : pfree(logdetail.data);
1200 : : }
1201 : :
1202 : : /*
1203 : : * Drop an object by OID. Works for most catalogs, if no special processing
1204 : : * is needed.
1205 : : */
1206 : : static void
1207 : 3636 : DropObjectById(const ObjectAddress *object)
1208 : : {
1209 : : SysCacheIdentifier cacheId;
1210 : : Relation rel;
1211 : : HeapTuple tup;
1212 : :
1213 : 3636 : cacheId = get_object_catcache_oid(object->classId);
1214 : :
1215 : 3636 : rel = table_open(object->classId, RowExclusiveLock);
1216 : :
1217 : : /*
1218 : : * Use the system cache for the oid column, if one exists.
1219 : : */
1220 [ + + ]: 3636 : if (cacheId >= 0)
1221 : : {
1222 : 1419 : tup = SearchSysCache1(cacheId, ObjectIdGetDatum(object->objectId));
1223 [ - + ]: 1419 : if (!HeapTupleIsValid(tup))
1224 [ # # ]: 0 : elog(ERROR, "cache lookup failed for %s %u",
1225 : : get_object_class_descr(object->classId), object->objectId);
1226 : :
1227 : 1419 : CatalogTupleDelete(rel, &tup->t_self);
1228 : :
1229 : 1419 : ReleaseSysCache(tup);
1230 : : }
1231 : : else
1232 : : {
1233 : : ScanKeyData skey[1];
1234 : : SysScanDesc scan;
1235 : :
1236 : 2217 : ScanKeyInit(&skey[0],
1237 : 2217 : get_object_attnum_oid(object->classId),
1238 : : BTEqualStrategyNumber, F_OIDEQ,
1239 : 2217 : ObjectIdGetDatum(object->objectId));
1240 : :
1241 : 2217 : scan = systable_beginscan(rel, get_object_oid_index(object->classId), true,
1242 : : NULL, 1, skey);
1243 : :
1244 : : /* we expect exactly one match */
1245 : 2217 : tup = systable_getnext(scan);
1246 [ - + ]: 2217 : if (!HeapTupleIsValid(tup))
1247 [ # # ]: 0 : elog(ERROR, "could not find tuple for %s %u",
1248 : : get_object_class_descr(object->classId), object->objectId);
1249 : :
1250 : 2217 : CatalogTupleDelete(rel, &tup->t_self);
1251 : :
1252 : 2217 : systable_endscan(scan);
1253 : : }
1254 : :
1255 : 3636 : table_close(rel, RowExclusiveLock);
1256 : 3636 : }
1257 : :
1258 : : /*
1259 : : * deleteOneObject: delete a single object for performDeletion.
1260 : : *
1261 : : * *depRel is the already-open pg_depend relation.
1262 : : */
1263 : : static void
1264 : 153611 : deleteOneObject(const ObjectAddress *object, Relation *depRel, int flags)
1265 : : {
1266 : : ScanKeyData key[3];
1267 : : int nkeys;
1268 : : SysScanDesc scan;
1269 : : HeapTuple tup;
1270 : :
1271 : : /* DROP hook of the objects being removed */
1272 [ + + ]: 153611 : InvokeObjectDropHookArg(object->classId, object->objectId,
1273 : : object->objectSubId, flags);
1274 : :
1275 : : /*
1276 : : * Close depRel if we are doing a drop concurrently. The object deletion
1277 : : * subroutine will commit the current transaction, so we can't keep the
1278 : : * relation open across doDeletion().
1279 : : */
1280 [ + + ]: 153611 : if (flags & PERFORM_DELETION_CONCURRENTLY)
1281 : 82 : table_close(*depRel, RowExclusiveLock);
1282 : :
1283 : : /*
1284 : : * Delete the object itself, in an object-type-dependent way.
1285 : : *
1286 : : * We used to do this after removing the outgoing dependency links, but it
1287 : : * seems just as reasonable to do it beforehand. In the concurrent case
1288 : : * we *must* do it in this order, because we can't make any transactional
1289 : : * updates before calling doDeletion() --- they'd get committed right
1290 : : * away, which is not cool if the deletion then fails.
1291 : : */
1292 : 153611 : doDeletion(object, flags);
1293 : :
1294 : : /*
1295 : : * Reopen depRel if we closed it above
1296 : : */
1297 [ + + ]: 153597 : if (flags & PERFORM_DELETION_CONCURRENTLY)
1298 : 82 : *depRel = table_open(DependRelationId, RowExclusiveLock);
1299 : :
1300 : : /*
1301 : : * Now remove any pg_depend records that link from this object to others.
1302 : : * (Any records linking to this object should be gone already.)
1303 : : *
1304 : : * When dropping a whole object (subId = 0), remove all pg_depend records
1305 : : * for its sub-objects too.
1306 : : */
1307 : 153597 : ScanKeyInit(&key[0],
1308 : : Anum_pg_depend_classid,
1309 : : BTEqualStrategyNumber, F_OIDEQ,
1310 : 153597 : ObjectIdGetDatum(object->classId));
1311 : 153597 : ScanKeyInit(&key[1],
1312 : : Anum_pg_depend_objid,
1313 : : BTEqualStrategyNumber, F_OIDEQ,
1314 : 153597 : ObjectIdGetDatum(object->objectId));
1315 [ + + ]: 153597 : if (object->objectSubId != 0)
1316 : : {
1317 : 1475 : ScanKeyInit(&key[2],
1318 : : Anum_pg_depend_objsubid,
1319 : : BTEqualStrategyNumber, F_INT4EQ,
1320 : 1475 : Int32GetDatum(object->objectSubId));
1321 : 1475 : nkeys = 3;
1322 : : }
1323 : : else
1324 : 152122 : nkeys = 2;
1325 : :
1326 : 153597 : scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1327 : : NULL, nkeys, key);
1328 : :
1329 [ + + ]: 365471 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
1330 : : {
1331 : 211874 : CatalogTupleDelete(*depRel, &tup->t_self);
1332 : : }
1333 : :
1334 : 153597 : systable_endscan(scan);
1335 : :
1336 : : /*
1337 : : * Delete shared dependency references related to this object. Again, if
1338 : : * subId = 0, remove records for sub-objects too.
1339 : : */
1340 : 153597 : deleteSharedDependencyRecordsFor(object->classId, object->objectId,
1341 : 153597 : object->objectSubId);
1342 : :
1343 : :
1344 : : /*
1345 : : * Delete any comments, security labels, or initial privileges associated
1346 : : * with this object. (This is a convenient place to do these things,
1347 : : * rather than having every object type know to do it.) As above, all
1348 : : * these functions must remove records for sub-objects too if the subid is
1349 : : * zero.
1350 : : */
1351 : 153597 : DeleteComments(object->objectId, object->classId, object->objectSubId);
1352 : 153597 : DeleteSecurityLabel(object);
1353 : 153597 : DeleteInitPrivs(object);
1354 : :
1355 : : /*
1356 : : * CommandCounterIncrement here to ensure that preceding changes are all
1357 : : * visible to the next deletion step.
1358 : : */
1359 : 153597 : CommandCounterIncrement();
1360 : :
1361 : : /*
1362 : : * And we're done!
1363 : : */
1364 : 153597 : }
1365 : :
1366 : : /*
1367 : : * doDeletion: actually delete a single object
1368 : : */
1369 : : static void
1370 : 153611 : doDeletion(const ObjectAddress *object, int flags)
1371 : : {
1372 [ + + + + : 153611 : switch (object->classId)
+ + + + +
+ + + + +
+ + + -
- ]
1373 : : {
1374 : 52913 : case RelationRelationId:
1375 : : {
1376 : 52913 : char relKind = get_rel_relkind(object->objectId);
1377 : :
1378 [ + + + + ]: 52913 : if (relKind == RELKIND_INDEX ||
1379 : : relKind == RELKIND_PARTITIONED_INDEX)
1380 : 16656 : {
1381 : 16664 : bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1382 : 16664 : bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1383 : :
1384 : : Assert(object->objectSubId == 0);
1385 : 16664 : index_drop(object->objectId, concurrent, concurrent_lock_mode);
1386 : : }
1387 : : else
1388 : : {
1389 [ + + ]: 36249 : if (object->objectSubId != 0)
1390 : 1475 : RemoveAttributeById(object->objectId,
1391 : 1475 : object->objectSubId);
1392 : : else
1393 : 34774 : heap_drop_with_catalog(object->objectId);
1394 : : }
1395 : :
1396 : : /*
1397 : : * for a sequence, in addition to dropping the heap, also
1398 : : * delete pg_sequence tuple
1399 : : */
1400 [ + + ]: 52901 : if (relKind == RELKIND_SEQUENCE)
1401 : 689 : DeleteSequenceTuple(object->objectId);
1402 : 52901 : break;
1403 : : }
1404 : :
1405 : 5977 : case ProcedureRelationId:
1406 : 5977 : RemoveFunctionById(object->objectId);
1407 : 5977 : break;
1408 : :
1409 : 55537 : case TypeRelationId:
1410 : 55537 : RemoveTypeById(object->objectId);
1411 : 55537 : break;
1412 : :
1413 : 18269 : case ConstraintRelationId:
1414 : 18269 : RemoveConstraintById(object->objectId);
1415 : 18268 : break;
1416 : :
1417 : 2433 : case AttrDefaultRelationId:
1418 : 2433 : RemoveAttrDefaultById(object->objectId);
1419 : 2433 : break;
1420 : :
1421 : 61 : case LargeObjectRelationId:
1422 : 61 : LargeObjectDrop(object->objectId);
1423 : 61 : break;
1424 : :
1425 : 490 : case OperatorRelationId:
1426 : 490 : RemoveOperatorById(object->objectId);
1427 : 490 : break;
1428 : :
1429 : 2175 : case RewriteRelationId:
1430 : 2175 : RemoveRewriteRuleById(object->objectId);
1431 : 2174 : break;
1432 : :
1433 : 9712 : case TriggerRelationId:
1434 : 9712 : RemoveTriggerById(object->objectId);
1435 : 9712 : break;
1436 : :
1437 : 585 : case StatisticExtRelationId:
1438 : 585 : RemoveStatisticsById(object->objectId);
1439 : 585 : break;
1440 : :
1441 : 32 : case TSConfigRelationId:
1442 : 32 : RemoveTSConfigurationById(object->objectId);
1443 : 32 : break;
1444 : :
1445 : 125 : case ExtensionRelationId:
1446 : 125 : RemoveExtensionById(object->objectId);
1447 : 125 : break;
1448 : :
1449 : 466 : case PolicyRelationId:
1450 : 466 : RemovePolicyById(object->objectId);
1451 : 466 : break;
1452 : :
1453 : 132 : case PublicationNamespaceRelationId:
1454 : 132 : RemovePublicationSchemaById(object->objectId);
1455 : 132 : break;
1456 : :
1457 : 660 : case PublicationRelRelationId:
1458 : 660 : RemovePublicationRelById(object->objectId);
1459 : 660 : break;
1460 : :
1461 : 408 : case PublicationRelationId:
1462 : 408 : RemovePublicationById(object->objectId);
1463 : 408 : break;
1464 : :
1465 : 3636 : case CastRelationId:
1466 : : case CollationRelationId:
1467 : : case ConversionRelationId:
1468 : : case LanguageRelationId:
1469 : : case OperatorClassRelationId:
1470 : : case OperatorFamilyRelationId:
1471 : : case AccessMethodRelationId:
1472 : : case AccessMethodOperatorRelationId:
1473 : : case AccessMethodProcedureRelationId:
1474 : : case NamespaceRelationId:
1475 : : case TSParserRelationId:
1476 : : case TSDictionaryRelationId:
1477 : : case TSTemplateRelationId:
1478 : : case ForeignDataWrapperRelationId:
1479 : : case ForeignServerRelationId:
1480 : : case UserMappingRelationId:
1481 : : case DefaultAclRelationId:
1482 : : case EventTriggerRelationId:
1483 : : case TransformRelationId:
1484 : : case AuthMemRelationId:
1485 : 3636 : DropObjectById(object);
1486 : 3636 : break;
1487 : :
1488 : : /*
1489 : : * These global object types are not supported here.
1490 : : */
1491 : 0 : case AuthIdRelationId:
1492 : : case DatabaseRelationId:
1493 : : case TableSpaceRelationId:
1494 : : case SubscriptionRelationId:
1495 : : case ParameterAclRelationId:
1496 [ # # ]: 0 : elog(ERROR, "global objects cannot be deleted by doDeletion");
1497 : : break;
1498 : :
1499 : 0 : default:
1500 [ # # ]: 0 : elog(ERROR, "unsupported object class: %u", object->classId);
1501 : : }
1502 : 153597 : }
1503 : :
1504 : : /*
1505 : : * AcquireDeletionLock - acquire a suitable lock for deleting an object
1506 : : *
1507 : : * Accepts the same flags as performDeletion (though currently only
1508 : : * PERFORM_DELETION_CONCURRENTLY does anything).
1509 : : *
1510 : : * We use LockRelation for relations, and otherwise LockSharedObject or
1511 : : * LockDatabaseObject as appropriate for the object type.
1512 : : */
1513 : : void
1514 : 191426 : AcquireDeletionLock(const ObjectAddress *object, int flags)
1515 : : {
1516 [ + + ]: 191426 : if (object->classId == RelationRelationId)
1517 : : {
1518 : : /*
1519 : : * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1520 : : * the index for the moment. index_drop() will promote the lock once
1521 : : * it's safe to do so. In all other cases we need full exclusive
1522 : : * lock.
1523 : : */
1524 [ + + ]: 66710 : if (flags & PERFORM_DELETION_CONCURRENTLY)
1525 : 82 : LockRelationOid(object->objectId, ShareUpdateExclusiveLock);
1526 : : else
1527 : 66628 : LockRelationOid(object->objectId, AccessExclusiveLock);
1528 : : }
1529 [ + + ]: 124716 : else if (IsSharedRelation(object->classId))
1530 : 32 : LockSharedObject(object->classId, object->objectId, 0,
1531 : : AccessExclusiveLock);
1532 : : else
1533 : : {
1534 : : /* assume we should lock the whole object not a sub-object */
1535 : 124684 : LockDatabaseObject(object->classId, object->objectId, 0,
1536 : : AccessExclusiveLock);
1537 : : }
1538 : 191426 : }
1539 : :
1540 : : /*
1541 : : * ReleaseDeletionLock - release an object deletion lock
1542 : : *
1543 : : * Companion to AcquireDeletionLock.
1544 : : */
1545 : : void
1546 : 1231 : ReleaseDeletionLock(const ObjectAddress *object)
1547 : : {
1548 [ + + ]: 1231 : if (object->classId == RelationRelationId)
1549 : 37 : UnlockRelationOid(object->objectId, AccessExclusiveLock);
1550 [ + + ]: 1194 : else if (IsSharedRelation(object->classId))
1551 : 1 : UnlockSharedObject(object->classId, object->objectId, 0,
1552 : : AccessExclusiveLock);
1553 : : else
1554 : : /* assume we should lock the whole object not a sub-object */
1555 : 1193 : UnlockDatabaseObject(object->classId, object->objectId, 0,
1556 : : AccessExclusiveLock);
1557 : 1231 : }
1558 : :
1559 : : /*
1560 : : * recordDependencyOnExpr - find expression dependencies
1561 : : *
1562 : : * This is used to find the dependencies of rules, constraint expressions,
1563 : : * etc.
1564 : : *
1565 : : * Given an expression or query in node-tree form, find all the objects
1566 : : * it refers to (tables, columns, operators, functions, etc). Record
1567 : : * a dependency of the specified type from the given depender object
1568 : : * to each object mentioned in the expression.
1569 : : *
1570 : : * rtable is the rangetable to be used to interpret Vars with varlevelsup=0.
1571 : : * It can be NIL if no such variables are expected.
1572 : : */
1573 : : void
1574 : 13683 : recordDependencyOnExpr(const ObjectAddress *depender,
1575 : : Node *expr, List *rtable,
1576 : : DependencyType behavior)
1577 : : {
1578 : : ObjectAddresses *addrs;
1579 : :
1580 : 13683 : addrs = new_object_addresses();
1581 : :
1582 : : /* Collect all dependencies from the expression */
1583 : 13683 : collectDependenciesOfExpr(addrs, expr, rtable);
1584 : :
1585 : : /* Remove duplicates */
1586 : 13683 : eliminate_duplicate_dependencies(addrs);
1587 : :
1588 : : /* And record 'em */
1589 : 13683 : recordMultipleDependencies(depender,
1590 : 13683 : addrs->refs, addrs->numrefs,
1591 : : behavior);
1592 : :
1593 : 13683 : free_object_addresses(addrs);
1594 : 13683 : }
1595 : :
1596 : : /*
1597 : : * collectDependenciesOfExpr - collect expression dependencies
1598 : : *
1599 : : * This function analyzes an expression or query in node-tree form to
1600 : : * find all the objects it refers to (tables, columns, operators,
1601 : : * functions, etc.) and adds them to the provided ObjectAddresses
1602 : : * structure. Unlike recordDependencyOnExpr, this function does not
1603 : : * immediately record the dependencies, allowing the caller to add to,
1604 : : * filter, or modify the collected dependencies before recording them.
1605 : : *
1606 : : * rtable is the rangetable to be used to interpret Vars with varlevelsup=0.
1607 : : * It can be NIL if no such variables are expected.
1608 : : *
1609 : : * Note: the returned list may well contain duplicates. The caller should
1610 : : * de-duplicate before recording the dependencies. Within this file, callers
1611 : : * must call eliminate_duplicate_dependencies(). External callers typically
1612 : : * go through record_object_address_dependencies() which will see to that.
1613 : : * This choice allows collecting dependencies from multiple sources without
1614 : : * redundant de-duplication work.
1615 : : */
1616 : : void
1617 : 47203 : collectDependenciesOfExpr(ObjectAddresses *addrs,
1618 : : Node *expr, List *rtable)
1619 : : {
1620 : : find_expr_references_context context;
1621 : :
1622 : 47203 : context.addrs = addrs;
1623 : :
1624 : : /* Set up interpretation for Vars at varlevelsup = 0 */
1625 : 47203 : context.rtables = list_make1(rtable);
1626 : :
1627 : : /* Scan the expression tree for referenceable objects */
1628 : 47203 : find_expr_references_walker(expr, &context);
1629 : 47199 : }
1630 : :
1631 : : /*
1632 : : * recordDependencyOnSingleRelExpr - find expression dependencies
1633 : : *
1634 : : * As above, but only one relation is expected to be referenced (with
1635 : : * varno = 1 and varlevelsup = 0). Pass the relation OID instead of a
1636 : : * range table. An additional frammish is that dependencies on that
1637 : : * relation's component columns will be marked with 'self_behavior',
1638 : : * whereas 'behavior' is used for everything else; also, if 'reverse_self'
1639 : : * is true, those dependencies are reversed so that the columns are made
1640 : : * to depend on the table not vice versa.
1641 : : *
1642 : : * NOTE: the caller should ensure that a whole-table dependency on the
1643 : : * specified relation is created separately, if one is needed. In particular,
1644 : : * a whole-row Var "relation.*" will not cause this routine to emit any
1645 : : * dependency item. This is appropriate behavior for subexpressions of an
1646 : : * ordinary query, so other cases need to cope as necessary.
1647 : : */
1648 : : void
1649 : 7716 : recordDependencyOnSingleRelExpr(const ObjectAddress *depender,
1650 : : Node *expr, Oid relId,
1651 : : DependencyType behavior,
1652 : : DependencyType self_behavior,
1653 : : bool reverse_self)
1654 : : {
1655 : : find_expr_references_context context;
1656 : 7716 : RangeTblEntry rte = {0};
1657 : :
1658 [ - + ]: 7716 : if (expr == NULL)
1659 : 0 : return;
1660 : :
1661 : 7716 : context.addrs = new_object_addresses();
1662 : :
1663 : : /* We gin up a rather bogus rangetable list to handle Vars */
1664 : 7716 : rte.type = T_RangeTblEntry;
1665 : 7716 : rte.rtekind = RTE_RELATION;
1666 : 7716 : rte.relid = relId;
1667 : 7716 : rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1668 : 7716 : rte.rellockmode = AccessShareLock;
1669 : :
1670 : 7716 : context.rtables = list_make1(list_make1(&rte));
1671 : :
1672 : : /* Scan the expression tree for referenceable objects */
1673 : 7716 : find_expr_references_walker(expr, &context);
1674 : :
1675 : : /* Also add a dependency to the result type */
1676 [ + + ]: 7716 : if (IsA(expr, List))
1677 : : {
1678 : : ListCell *l;
1679 : :
1680 [ + - + + : 3281 : foreach(l, (List *) expr)
+ + ]
1681 : : {
1682 : 1733 : add_object_address(TypeRelationId, exprType(lfirst(l)), 0,
1683 : : context.addrs);
1684 : : }
1685 : : }
1686 : : else
1687 : 6168 : add_object_address(TypeRelationId, exprType(expr), 0,
1688 : : context.addrs);
1689 : :
1690 : : /* Remove any duplicates */
1691 : 7716 : eliminate_duplicate_dependencies(context.addrs);
1692 : :
1693 : : /* Separate self-dependencies if necessary */
1694 [ + + - + ]: 7716 : if ((behavior != self_behavior || reverse_self) &&
1695 [ + - ]: 1548 : context.addrs->numrefs > 0)
1696 : : {
1697 : : ObjectAddresses *self_addrs;
1698 : : ObjectAddress *outobj;
1699 : : int oldref,
1700 : : outrefs;
1701 : :
1702 : 1548 : self_addrs = new_object_addresses();
1703 : :
1704 : 1548 : outobj = context.addrs->refs;
1705 : 1548 : outrefs = 0;
1706 [ + + ]: 7566 : for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1707 : : {
1708 : 6018 : ObjectAddress *thisobj = context.addrs->refs + oldref;
1709 : :
1710 [ + + ]: 6018 : if (thisobj->classId == RelationRelationId &&
1711 [ + + ]: 1966 : thisobj->objectId == relId)
1712 : : {
1713 : : /* Move this ref into self_addrs */
1714 : 1874 : add_exact_object_address(thisobj, self_addrs);
1715 : : }
1716 : : else
1717 : : {
1718 : : /* Keep it in context.addrs */
1719 : 4144 : *outobj = *thisobj;
1720 : 4144 : outobj++;
1721 : 4144 : outrefs++;
1722 : : }
1723 : : }
1724 : 1548 : context.addrs->numrefs = outrefs;
1725 : :
1726 : : /* Record the self-dependencies with the appropriate direction */
1727 [ + + ]: 1548 : if (!reverse_self)
1728 : 1374 : recordMultipleDependencies(depender,
1729 : 1374 : self_addrs->refs, self_addrs->numrefs,
1730 : : self_behavior);
1731 : : else
1732 : : {
1733 : : /* Can't use recordMultipleDependencies, so do it the hard way */
1734 : : int selfref;
1735 : :
1736 [ + + ]: 397 : for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1737 : : {
1738 : 223 : ObjectAddress *thisobj = self_addrs->refs + selfref;
1739 : :
1740 : 223 : recordDependencyOn(thisobj, depender, self_behavior);
1741 : : }
1742 : : }
1743 : :
1744 : 1548 : free_object_addresses(self_addrs);
1745 : : }
1746 : :
1747 : : /* Record the external dependencies */
1748 : 7716 : recordMultipleDependencies(depender,
1749 : 7716 : context.addrs->refs, context.addrs->numrefs,
1750 : : behavior);
1751 : :
1752 : 7716 : free_object_addresses(context.addrs);
1753 : : }
1754 : :
1755 : : /*
1756 : : * We require USAGE on a type to store a dependency on it. This helper
1757 : : * function does the appropriate privilege checks.
1758 : : *
1759 : : * NB: Other objects have privileges of their own, but recording those
1760 : : * dependencies doesn't require holding them. For example, an expression may
1761 : : * reference a function for which the user lacks EXECUTE. Instead, EXECUTE is
1762 : : * checked when the function is executed.
1763 : : */
1764 : : static void
1765 : 24494 : check_usage_on_types(ObjectAddresses *addrs, Oid roleid)
1766 : : {
1767 [ + + ]: 239864 : for (int i = 0; i < addrs->numrefs; i++)
1768 : : {
1769 : 215422 : ObjectAddress *ref = &addrs->refs[i];
1770 : : AclResult aclresult;
1771 : :
1772 [ + + ]: 215422 : if (ref->classId != TypeRelationId)
1773 : 167208 : continue;
1774 : :
1775 : : /* we don't record dependencies on pinned types */
1776 [ + + ]: 48214 : if (IsPinnedObject(ref->classId, ref->objectId))
1777 : 40738 : continue;
1778 : :
1779 : 7476 : aclresult = object_aclcheck(ref->classId, ref->objectId,
1780 : : roleid, ACL_USAGE);
1781 [ + + ]: 7476 : if (aclresult != ACLCHECK_OK)
1782 : 52 : aclcheck_error_type(aclresult, ref->objectId);
1783 : : }
1784 : 24442 : }
1785 : :
1786 : : /*
1787 : : * CheckUsageOnTypesInExpr - require USAGE on all types named by an expression
1788 : : *
1789 : : * rtable is the rangetable for interpreting Vars (or NIL if none are
1790 : : * expected). roleid is the role whose USAGE is required.
1791 : : */
1792 : : void
1793 : 18137 : CheckUsageOnTypesInExpr(Node *expr, List *rtable, Oid roleid)
1794 : : {
1795 : 18137 : ObjectAddresses *addrs = new_object_addresses();
1796 : :
1797 : 18137 : collectDependenciesOfExpr(addrs, expr, rtable);
1798 : 18137 : eliminate_duplicate_dependencies(addrs);
1799 : 18137 : check_usage_on_types(addrs, roleid);
1800 : 18117 : free_object_addresses(addrs);
1801 : 18117 : }
1802 : :
1803 : : /*
1804 : : * CheckUsageOnTypesInSingleRelExpr - as above, for a single-rel expression
1805 : : *
1806 : : * Like recordDependencyOnSingleRelExpr(), this handles expressions whose Vars
1807 : : * all refer to one relation. roleid is the role whose USAGE is required.
1808 : : */
1809 : : void
1810 : 6365 : CheckUsageOnTypesInSingleRelExpr(Node *expr, Oid relId, Oid roleid)
1811 : : {
1812 : : find_expr_references_context context;
1813 : 6365 : RangeTblEntry rte = {0};
1814 : :
1815 [ - + ]: 6365 : if (expr == NULL)
1816 : 0 : return;
1817 : :
1818 : 6365 : context.addrs = new_object_addresses();
1819 : :
1820 : : /* We gin up a rather bogus rangetable list to handle Vars */
1821 : 6365 : rte.type = T_RangeTblEntry;
1822 : 6365 : rte.rtekind = RTE_RELATION;
1823 : 6365 : rte.relid = relId;
1824 : 6365 : rte.relkind = RELKIND_RELATION;
1825 : 6365 : rte.rellockmode = AccessShareLock;
1826 : 6365 : context.rtables = list_make1(list_make1(&rte));
1827 : :
1828 : 6365 : find_expr_references_walker(expr, &context);
1829 : :
1830 : : /* Also check USAGE on the result type */
1831 [ + + ]: 6357 : if (IsA(expr, List))
1832 : : {
1833 : : ListCell *l;
1834 : :
1835 [ + - + + : 2950 : foreach(l, (List *) expr)
+ + ]
1836 : : {
1837 : 1569 : add_object_address(TypeRelationId, exprType(lfirst(l)), 0,
1838 : : context.addrs);
1839 : : }
1840 : : }
1841 : : else
1842 : 4976 : add_object_address(TypeRelationId, exprType(expr), 0,
1843 : : context.addrs);
1844 : :
1845 : 6357 : eliminate_duplicate_dependencies(context.addrs);
1846 : 6357 : check_usage_on_types(context.addrs, roleid);
1847 : 6325 : free_object_addresses(context.addrs);
1848 : : }
1849 : :
1850 : : /*
1851 : : * CheckTypeDependencyInExpr - does 'expr' depend on the given type?
1852 : : */
1853 : : bool
1854 : 58 : CheckTypeDependencyInExpr(Node *expr, List *rtable, Oid typeId)
1855 : : {
1856 : 58 : ObjectAddresses *addrs = new_object_addresses();
1857 : : ObjectAddress typeAddr;
1858 : : bool result;
1859 : :
1860 : 58 : collectDependenciesOfExpr(addrs, expr, rtable);
1861 : :
1862 : 58 : ObjectAddressSet(typeAddr, TypeRelationId, typeId);
1863 : 58 : result = object_address_present(&typeAddr, addrs);
1864 : 58 : free_object_addresses(addrs);
1865 : :
1866 : 58 : return result;
1867 : : }
1868 : :
1869 : : /*
1870 : : * CheckTypeDependencyInSingleRelExpr - as above, for a single-rel expression
1871 : : */
1872 : : bool
1873 : 16 : CheckTypeDependencyInSingleRelExpr(Node *expr, Oid relId, Oid typeId)
1874 : : {
1875 : 16 : RangeTblEntry rte = {0};
1876 : :
1877 : : /* We gin up a rather bogus rangetable list to handle Vars */
1878 : 16 : rte.type = T_RangeTblEntry;
1879 : 16 : rte.rtekind = RTE_RELATION;
1880 : 16 : rte.relid = relId;
1881 : 16 : rte.relkind = RELKIND_RELATION;
1882 : 16 : rte.rellockmode = AccessShareLock;
1883 : :
1884 : 16 : return CheckTypeDependencyInExpr(expr, list_make1(&rte), typeId);
1885 : : }
1886 : :
1887 : : /*
1888 : : * Record dependencies on the target columns named in the target list of an
1889 : : * INSERT or UPDATE query, or of an INSERT or UPDATE action of a MERGE query.
1890 : : */
1891 : : static void
1892 : 1062 : add_target_column_dependencies(List *targetList, Oid relid,
1893 : : find_expr_references_context *context)
1894 : : {
1895 [ + + + + : 4218 : foreach_node(TargetEntry, tle, targetList)
+ + ]
1896 : : {
1897 [ + + ]: 2094 : if (tle->resjunk)
1898 : 8 : continue; /* ignore junk tlist items */
1899 : 2086 : add_object_address(RelationRelationId, relid, tle->resno,
1900 : : context->addrs);
1901 : : }
1902 : 1062 : }
1903 : :
1904 : : /*
1905 : : * Recursively search an expression tree for object references.
1906 : : *
1907 : : * Note: in many cases we do not need to create dependencies on the datatypes
1908 : : * involved in an expression, because we'll have an indirect dependency via
1909 : : * some other object. For instance Var nodes depend on a column which depends
1910 : : * on the datatype, and OpExpr nodes depend on the operator which depends on
1911 : : * the datatype. However we do need a type dependency if there is no such
1912 : : * indirect dependency, as for example in Const and CoerceToDomain nodes.
1913 : : *
1914 : : * Similarly, we don't need to create dependencies on collations except where
1915 : : * the collation is being freshly introduced to the expression.
1916 : : */
1917 : : static bool
1918 : 3729801 : find_expr_references_walker(Node *node,
1919 : : find_expr_references_context *context)
1920 : : {
1921 [ + + ]: 3729801 : if (node == NULL)
1922 : 1259764 : return false;
1923 [ + + ]: 2470037 : if (IsA(node, Var))
1924 : : {
1925 : 626384 : Var *var = (Var *) node;
1926 : : List *rtable;
1927 : : RangeTblEntry *rte;
1928 : :
1929 : : /* Find matching rtable entry, or complain if not found */
1930 [ - + ]: 626384 : if (var->varlevelsup >= list_length(context->rtables))
1931 [ # # ]: 0 : elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1932 : 626384 : rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1933 [ + - - + ]: 626384 : if (var->varno <= 0 || var->varno > list_length(rtable))
1934 [ # # ]: 0 : elog(ERROR, "invalid varno %d", var->varno);
1935 : 626384 : rte = rt_fetch(var->varno, rtable);
1936 : :
1937 : : /*
1938 : : * A whole-row Var references no specific columns, so adds no new
1939 : : * dependency. (We assume that there is a whole-table dependency
1940 : : * arising from each underlying rangetable entry. While we could
1941 : : * record such a dependency when finding a whole-row Var that
1942 : : * references a relation directly, it's quite unclear how to extend
1943 : : * that to whole-row Vars for JOINs, so it seems better to leave the
1944 : : * responsibility with the range table. Note that this poses some
1945 : : * risks for identifying dependencies of stand-alone expressions:
1946 : : * whole-table references may need to be created separately.)
1947 : : */
1948 [ + + ]: 626384 : if (var->varattno == InvalidAttrNumber)
1949 : 10436 : return false;
1950 [ + + ]: 615948 : if (rte->rtekind == RTE_RELATION)
1951 : : {
1952 : : /* If it's a plain relation, reference this column */
1953 : 431170 : add_object_address(RelationRelationId, rte->relid, var->varattno,
1954 : : context->addrs);
1955 : : }
1956 [ + + ]: 184778 : else if (rte->rtekind == RTE_FUNCTION)
1957 : : {
1958 : : /* Might need to add a dependency on a composite type's column */
1959 : : /* (done out of line, because it's a bit bulky) */
1960 : 95374 : process_function_rte_ref(rte, var->varattno, context);
1961 : : }
1962 : :
1963 : : /*
1964 : : * Vars referencing other RTE types require no additional work. In
1965 : : * particular, a join alias Var can be ignored, because it must
1966 : : * reference a merged USING column. The relevant join input columns
1967 : : * will also be referenced in the join qual, and any type coercion
1968 : : * functions involved in the alias expression will be dealt with when
1969 : : * we scan the RTE itself.
1970 : : */
1971 : 615948 : return false;
1972 : : }
1973 [ + + ]: 1843653 : else if (IsA(node, Const))
1974 : : {
1975 : 300155 : Const *con = (Const *) node;
1976 : : Oid objoid;
1977 : :
1978 : : /* A constant must depend on the constant's datatype */
1979 : 300155 : add_object_address(TypeRelationId, con->consttype, 0,
1980 : : context->addrs);
1981 : :
1982 : : /*
1983 : : * We must also depend on the constant's collation: it could be
1984 : : * different from the datatype's, if a CollateExpr was const-folded to
1985 : : * a simple constant. However we can save work in the most common
1986 : : * case where the collation is "default", since we know that's pinned.
1987 : : */
1988 [ + + ]: 300155 : if (OidIsValid(con->constcollid) &&
1989 [ + + ]: 120357 : con->constcollid != DEFAULT_COLLATION_OID)
1990 : 29031 : add_object_address(CollationRelationId, con->constcollid, 0,
1991 : : context->addrs);
1992 : :
1993 : : /*
1994 : : * If it's a regclass or similar literal referring to an existing
1995 : : * object, add a reference to that object. (Currently, only the
1996 : : * regclass and regconfig cases have any likely use, but we may as
1997 : : * well handle all the OID-alias datatypes consistently.)
1998 : : */
1999 [ + + ]: 300155 : if (!con->constisnull)
2000 : : {
2001 [ - - + - : 251125 : switch (con->consttype)
- - - + +
+ + ]
2002 : : {
2003 : 0 : case REGPROCOID:
2004 : : case REGPROCEDUREOID:
2005 : 0 : objoid = DatumGetObjectId(con->constvalue);
2006 [ # # ]: 0 : if (SearchSysCacheExists1(PROCOID,
2007 : : ObjectIdGetDatum(objoid)))
2008 : 0 : add_object_address(ProcedureRelationId, objoid, 0,
2009 : : context->addrs);
2010 : 0 : break;
2011 : 0 : case REGOPEROID:
2012 : : case REGOPERATOROID:
2013 : 0 : objoid = DatumGetObjectId(con->constvalue);
2014 [ # # ]: 0 : if (SearchSysCacheExists1(OPEROID,
2015 : : ObjectIdGetDatum(objoid)))
2016 : 0 : add_object_address(OperatorRelationId, objoid, 0,
2017 : : context->addrs);
2018 : 0 : break;
2019 : 7487 : case REGCLASSOID:
2020 : 7487 : objoid = DatumGetObjectId(con->constvalue);
2021 [ + - ]: 7487 : if (SearchSysCacheExists1(RELOID,
2022 : : ObjectIdGetDatum(objoid)))
2023 : 7487 : add_object_address(RelationRelationId, objoid, 0,
2024 : : context->addrs);
2025 : 7487 : break;
2026 : 0 : case REGTYPEOID:
2027 : 0 : objoid = DatumGetObjectId(con->constvalue);
2028 [ # # ]: 0 : if (SearchSysCacheExists1(TYPEOID,
2029 : : ObjectIdGetDatum(objoid)))
2030 : 0 : add_object_address(TypeRelationId, objoid, 0,
2031 : : context->addrs);
2032 : 0 : break;
2033 : 0 : case REGCOLLATIONOID:
2034 : 0 : objoid = DatumGetObjectId(con->constvalue);
2035 [ # # ]: 0 : if (SearchSysCacheExists1(COLLOID,
2036 : : ObjectIdGetDatum(objoid)))
2037 : 0 : add_object_address(CollationRelationId, objoid, 0,
2038 : : context->addrs);
2039 : 0 : break;
2040 : 0 : case REGCONFIGOID:
2041 : 0 : objoid = DatumGetObjectId(con->constvalue);
2042 [ # # ]: 0 : if (SearchSysCacheExists1(TSCONFIGOID,
2043 : : ObjectIdGetDatum(objoid)))
2044 : 0 : add_object_address(TSConfigRelationId, objoid, 0,
2045 : : context->addrs);
2046 : 0 : break;
2047 : 0 : case REGDICTIONARYOID:
2048 : 0 : objoid = DatumGetObjectId(con->constvalue);
2049 [ # # ]: 0 : if (SearchSysCacheExists1(TSDICTOID,
2050 : : ObjectIdGetDatum(objoid)))
2051 : 0 : add_object_address(TSDictionaryRelationId, objoid, 0,
2052 : : context->addrs);
2053 : 0 : break;
2054 : :
2055 : 244 : case REGNAMESPACEOID:
2056 : 244 : objoid = DatumGetObjectId(con->constvalue);
2057 [ + - ]: 244 : if (SearchSysCacheExists1(NAMESPACEOID,
2058 : : ObjectIdGetDatum(objoid)))
2059 : 244 : add_object_address(NamespaceRelationId, objoid, 0,
2060 : : context->addrs);
2061 : 244 : break;
2062 : :
2063 : : /*
2064 : : * Dependencies for regrole should be shared among all
2065 : : * databases, so explicitly inhibit to have dependencies.
2066 : : */
2067 : 4 : case REGROLEOID:
2068 [ + - ]: 4 : ereport(ERROR,
2069 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2070 : : errmsg("constant of the type %s cannot be used here",
2071 : : "regrole")));
2072 : : break;
2073 : :
2074 : : /*
2075 : : * Dependencies for regdatabase should be shared among all
2076 : : * databases, so explicitly inhibit to have dependencies.
2077 : : */
2078 : 4 : case REGDATABASEOID:
2079 [ + - ]: 4 : ereport(ERROR,
2080 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2081 : : errmsg("constant of the type %s cannot be used here",
2082 : : "regdatabase")));
2083 : : break;
2084 : : }
2085 : : }
2086 : 300147 : return false;
2087 : : }
2088 [ + + ]: 1543498 : else if (IsA(node, Param))
2089 : : {
2090 : 20822 : Param *param = (Param *) node;
2091 : :
2092 : : /* A parameter must depend on the parameter's datatype */
2093 : 20822 : add_object_address(TypeRelationId, param->paramtype, 0,
2094 : : context->addrs);
2095 : : /* and its collation, just as for Consts */
2096 [ + + ]: 20822 : if (OidIsValid(param->paramcollid) &&
2097 [ + + ]: 4424 : param->paramcollid != DEFAULT_COLLATION_OID)
2098 : 2714 : add_object_address(CollationRelationId, param->paramcollid, 0,
2099 : : context->addrs);
2100 : : }
2101 [ + + ]: 1522676 : else if (IsA(node, FuncExpr))
2102 : : {
2103 : 145435 : FuncExpr *funcexpr = (FuncExpr *) node;
2104 : :
2105 : 145435 : add_object_address(ProcedureRelationId, funcexpr->funcid, 0,
2106 : : context->addrs);
2107 : : /* fall through to examine arguments */
2108 : : }
2109 [ + + ]: 1377241 : else if (IsA(node, OpExpr))
2110 : : {
2111 : 171371 : OpExpr *opexpr = (OpExpr *) node;
2112 : :
2113 : 171371 : add_object_address(OperatorRelationId, opexpr->opno, 0,
2114 : : context->addrs);
2115 : : /* fall through to examine arguments */
2116 : : }
2117 [ + + ]: 1205870 : else if (IsA(node, DistinctExpr))
2118 : : {
2119 : 16 : DistinctExpr *distinctexpr = (DistinctExpr *) node;
2120 : :
2121 : 16 : add_object_address(OperatorRelationId, distinctexpr->opno, 0,
2122 : : context->addrs);
2123 : : /* fall through to examine arguments */
2124 : : }
2125 [ + + ]: 1205854 : else if (IsA(node, NullIfExpr))
2126 : : {
2127 : 785 : NullIfExpr *nullifexpr = (NullIfExpr *) node;
2128 : :
2129 : 785 : add_object_address(OperatorRelationId, nullifexpr->opno, 0,
2130 : : context->addrs);
2131 : : /* fall through to examine arguments */
2132 : : }
2133 [ + + ]: 1205069 : else if (IsA(node, ScalarArrayOpExpr))
2134 : : {
2135 : 12111 : ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
2136 : :
2137 : 12111 : add_object_address(OperatorRelationId, opexpr->opno, 0,
2138 : : context->addrs);
2139 : : /* fall through to examine arguments */
2140 : : }
2141 [ + + ]: 1192958 : else if (IsA(node, Aggref))
2142 : : {
2143 : 3388 : Aggref *aggref = (Aggref *) node;
2144 : :
2145 : 3388 : add_object_address(ProcedureRelationId, aggref->aggfnoid, 0,
2146 : : context->addrs);
2147 : : /* fall through to examine arguments */
2148 : : }
2149 [ + + ]: 1189570 : else if (IsA(node, WindowFunc))
2150 : : {
2151 : 297 : WindowFunc *wfunc = (WindowFunc *) node;
2152 : :
2153 : 297 : add_object_address(ProcedureRelationId, wfunc->winfnoid, 0,
2154 : : context->addrs);
2155 : : /* fall through to examine arguments */
2156 : : }
2157 [ + + ]: 1189273 : else if (IsA(node, SubscriptingRef))
2158 : : {
2159 : 5626 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
2160 : :
2161 : : /*
2162 : : * The refexpr should provide adequate dependency on refcontainertype,
2163 : : * and that type in turn depends on refelemtype. However, a custom
2164 : : * subscripting handler might set refrestype to something different
2165 : : * from either of those, in which case we'd better record it.
2166 : : */
2167 [ + + ]: 5626 : if (sbsref->refrestype != sbsref->refcontainertype &&
2168 [ - + ]: 5458 : sbsref->refrestype != sbsref->refelemtype)
2169 : 0 : add_object_address(TypeRelationId, sbsref->refrestype, 0,
2170 : : context->addrs);
2171 : : /* fall through to examine arguments */
2172 : : }
2173 [ - + ]: 1183647 : else if (IsA(node, SubPlan))
2174 : : {
2175 : : /* Extra work needed here if we ever need this case */
2176 [ # # ]: 0 : elog(ERROR, "already-planned subqueries not supported");
2177 : : }
2178 [ + + ]: 1183647 : else if (IsA(node, FieldSelect))
2179 : : {
2180 : 30620 : FieldSelect *fselect = (FieldSelect *) node;
2181 : 30620 : Oid argtype = getBaseType(exprType((Node *) fselect->arg));
2182 : 30620 : Oid reltype = get_typ_typrelid(argtype);
2183 : :
2184 : : /*
2185 : : * We need a dependency on the specific column named in FieldSelect,
2186 : : * assuming we can identify the pg_class OID for it. (Probably we
2187 : : * always can at the moment, but in future it might be possible for
2188 : : * argtype to be RECORDOID.) If we can make a column dependency then
2189 : : * we shouldn't need a dependency on the column's type; but if we
2190 : : * can't, make a dependency on the type, as it might not appear
2191 : : * anywhere else in the expression.
2192 : : */
2193 [ + + ]: 30620 : if (OidIsValid(reltype))
2194 : 19515 : add_object_address(RelationRelationId, reltype, fselect->fieldnum,
2195 : : context->addrs);
2196 : : else
2197 : 11105 : add_object_address(TypeRelationId, fselect->resulttype, 0,
2198 : : context->addrs);
2199 : : /* the collation might not be referenced anywhere else, either */
2200 [ + + ]: 30620 : if (OidIsValid(fselect->resultcollid) &&
2201 [ - + ]: 3119 : fselect->resultcollid != DEFAULT_COLLATION_OID)
2202 : 0 : add_object_address(CollationRelationId, fselect->resultcollid, 0,
2203 : : context->addrs);
2204 : : }
2205 [ + + ]: 1153027 : else if (IsA(node, FieldStore))
2206 : : {
2207 : 128 : FieldStore *fstore = (FieldStore *) node;
2208 : 128 : Oid reltype = get_typ_typrelid(fstore->resulttype);
2209 : :
2210 : : /* similar considerations to FieldSelect, but multiple column(s) */
2211 [ + - ]: 128 : if (OidIsValid(reltype))
2212 : : {
2213 : : ListCell *l;
2214 : :
2215 [ + - + + : 256 : foreach(l, fstore->fieldnums)
+ + ]
2216 : 128 : add_object_address(RelationRelationId, reltype, lfirst_int(l),
2217 : : context->addrs);
2218 : : }
2219 : : else
2220 : 0 : add_object_address(TypeRelationId, fstore->resulttype, 0,
2221 : : context->addrs);
2222 : : }
2223 [ + + ]: 1152899 : else if (IsA(node, RelabelType))
2224 : : {
2225 : 23251 : RelabelType *relab = (RelabelType *) node;
2226 : :
2227 : : /* since there is no function dependency, need to depend on type */
2228 : 23251 : add_object_address(TypeRelationId, relab->resulttype, 0,
2229 : : context->addrs);
2230 : : /* the collation might not be referenced anywhere else, either */
2231 [ + + ]: 23251 : if (OidIsValid(relab->resultcollid) &&
2232 [ + + ]: 5662 : relab->resultcollid != DEFAULT_COLLATION_OID)
2233 : 5133 : add_object_address(CollationRelationId, relab->resultcollid, 0,
2234 : : context->addrs);
2235 : : }
2236 [ + + ]: 1129648 : else if (IsA(node, CoerceViaIO))
2237 : : {
2238 : 4823 : CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2239 : :
2240 : : /* since there is no exposed function, need to depend on type */
2241 : 4823 : add_object_address(TypeRelationId, iocoerce->resulttype, 0,
2242 : : context->addrs);
2243 : : /* the collation might not be referenced anywhere else, either */
2244 [ + + ]: 4823 : if (OidIsValid(iocoerce->resultcollid) &&
2245 [ + + ]: 3573 : iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2246 : 1239 : add_object_address(CollationRelationId, iocoerce->resultcollid, 0,
2247 : : context->addrs);
2248 : : }
2249 [ + + ]: 1124825 : else if (IsA(node, ArrayCoerceExpr))
2250 : : {
2251 : 834 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2252 : :
2253 : : /* as above, depend on type */
2254 : 834 : add_object_address(TypeRelationId, acoerce->resulttype, 0,
2255 : : context->addrs);
2256 : : /* the collation might not be referenced anywhere else, either */
2257 [ + + ]: 834 : if (OidIsValid(acoerce->resultcollid) &&
2258 [ + + ]: 303 : acoerce->resultcollid != DEFAULT_COLLATION_OID)
2259 : 177 : add_object_address(CollationRelationId, acoerce->resultcollid, 0,
2260 : : context->addrs);
2261 : : /* fall through to examine arguments */
2262 : : }
2263 [ - + ]: 1123991 : else if (IsA(node, ConvertRowtypeExpr))
2264 : : {
2265 : 0 : ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2266 : :
2267 : : /* since there is no function dependency, need to depend on type */
2268 : 0 : add_object_address(TypeRelationId, cvt->resulttype, 0,
2269 : : context->addrs);
2270 : : }
2271 [ + + ]: 1123991 : else if (IsA(node, CollateExpr))
2272 : : {
2273 : 152 : CollateExpr *coll = (CollateExpr *) node;
2274 : :
2275 : 152 : add_object_address(CollationRelationId, coll->collOid, 0,
2276 : : context->addrs);
2277 : : }
2278 [ + + ]: 1123839 : else if (IsA(node, RowExpr))
2279 : : {
2280 : 304 : RowExpr *rowexpr = (RowExpr *) node;
2281 : :
2282 : 304 : add_object_address(TypeRelationId, rowexpr->row_typeid, 0,
2283 : : context->addrs);
2284 : : }
2285 [ + + ]: 1123535 : else if (IsA(node, RowCompareExpr))
2286 : : {
2287 : 28 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2288 : : ListCell *l;
2289 : :
2290 [ + - + + : 84 : foreach(l, rcexpr->opnos)
+ + ]
2291 : : {
2292 : 56 : add_object_address(OperatorRelationId, lfirst_oid(l), 0,
2293 : : context->addrs);
2294 : : }
2295 [ + - + + : 84 : foreach(l, rcexpr->opfamilies)
+ + ]
2296 : : {
2297 : 56 : add_object_address(OperatorFamilyRelationId, lfirst_oid(l), 0,
2298 : : context->addrs);
2299 : : }
2300 : : /* fall through to examine arguments */
2301 : : }
2302 [ + + ]: 1123507 : else if (IsA(node, CoerceToDomain))
2303 : : {
2304 : 111995 : CoerceToDomain *cd = (CoerceToDomain *) node;
2305 : :
2306 : 111995 : add_object_address(TypeRelationId, cd->resulttype, 0,
2307 : : context->addrs);
2308 : : }
2309 [ - + ]: 1011512 : else if (IsA(node, NextValueExpr))
2310 : : {
2311 : 0 : NextValueExpr *nve = (NextValueExpr *) node;
2312 : :
2313 : 0 : add_object_address(RelationRelationId, nve->seqid, 0,
2314 : : context->addrs);
2315 : : }
2316 [ + + ]: 1011512 : else if (IsA(node, OnConflictExpr))
2317 : : {
2318 : 32 : OnConflictExpr *onconflict = (OnConflictExpr *) node;
2319 : :
2320 [ - + ]: 32 : if (OidIsValid(onconflict->constraint))
2321 : 0 : add_object_address(ConstraintRelationId, onconflict->constraint, 0,
2322 : : context->addrs);
2323 : : /* fall through to examine arguments */
2324 : : }
2325 [ + + ]: 1011480 : else if (IsA(node, SortGroupClause))
2326 : : {
2327 : 23665 : SortGroupClause *sgc = (SortGroupClause *) node;
2328 : :
2329 : 23665 : add_object_address(OperatorRelationId, sgc->eqop, 0,
2330 : : context->addrs);
2331 [ + - ]: 23665 : if (OidIsValid(sgc->sortop))
2332 : 23665 : add_object_address(OperatorRelationId, sgc->sortop, 0,
2333 : : context->addrs);
2334 : 23665 : return false;
2335 : : }
2336 [ + + ]: 987815 : else if (IsA(node, WindowClause))
2337 : : {
2338 : 273 : WindowClause *wc = (WindowClause *) node;
2339 : :
2340 [ + + ]: 273 : if (OidIsValid(wc->startInRangeFunc))
2341 : 8 : add_object_address(ProcedureRelationId, wc->startInRangeFunc, 0,
2342 : : context->addrs);
2343 [ + + ]: 273 : if (OidIsValid(wc->endInRangeFunc))
2344 : 8 : add_object_address(ProcedureRelationId, wc->endInRangeFunc, 0,
2345 : : context->addrs);
2346 [ - + ]: 273 : if (OidIsValid(wc->inRangeColl) &&
2347 [ # # ]: 0 : wc->inRangeColl != DEFAULT_COLLATION_OID)
2348 : 0 : add_object_address(CollationRelationId, wc->inRangeColl, 0,
2349 : : context->addrs);
2350 : : /* fall through to examine substructure */
2351 : : }
2352 [ + + ]: 987542 : else if (IsA(node, CTECycleClause))
2353 : : {
2354 : 16 : CTECycleClause *cc = (CTECycleClause *) node;
2355 : :
2356 [ + - ]: 16 : if (OidIsValid(cc->cycle_mark_type))
2357 : 16 : add_object_address(TypeRelationId, cc->cycle_mark_type, 0,
2358 : : context->addrs);
2359 [ + + ]: 16 : if (OidIsValid(cc->cycle_mark_collation))
2360 : 8 : add_object_address(CollationRelationId, cc->cycle_mark_collation, 0,
2361 : : context->addrs);
2362 [ + - ]: 16 : if (OidIsValid(cc->cycle_mark_neop))
2363 : 16 : add_object_address(OperatorRelationId, cc->cycle_mark_neop, 0,
2364 : : context->addrs);
2365 : : /* fall through to examine substructure */
2366 : : }
2367 [ + + ]: 987526 : else if (IsA(node, Query))
2368 : : {
2369 : : /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2370 : 67309 : Query *query = (Query *) node;
2371 : : ListCell *lc;
2372 : : bool result;
2373 : :
2374 : : /*
2375 : : * Add whole-relation refs for each plain relation mentioned in the
2376 : : * subquery's rtable, and ensure we add refs for any type-coercion
2377 : : * functions used in join alias lists.
2378 : : *
2379 : : * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2380 : : * RTEs, subqueries, etc, so no need to do that here. But we must
2381 : : * tell it not to visit join alias lists, or we'll add refs for join
2382 : : * input columns whether or not they are actually used in our query.
2383 : : *
2384 : : * Note: we don't need to worry about collations mentioned in
2385 : : * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2386 : : * collations referenced in other parts of the Query. We do have to
2387 : : * worry about collations mentioned in RTE_FUNCTION, but we take care
2388 : : * of those when we recurse to the RangeTblFunction node(s).
2389 : : */
2390 [ + + + + : 217447 : foreach(lc, query->rtable)
+ + ]
2391 : : {
2392 : 150142 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2393 : :
2394 [ + + + + ]: 150142 : switch (rte->rtekind)
2395 : : {
2396 : 92413 : case RTE_RELATION:
2397 : 92413 : add_object_address(RelationRelationId, rte->relid, 0,
2398 : : context->addrs);
2399 : 92413 : break;
2400 : 27612 : case RTE_JOIN:
2401 : :
2402 : : /*
2403 : : * Examine joinaliasvars entries only for merged JOIN
2404 : : * USING columns. Only those entries could contain
2405 : : * type-coercion functions. Also, their join input
2406 : : * columns must be referenced in the join quals, so this
2407 : : * won't accidentally add refs to otherwise-unused join
2408 : : * input columns. (We want to ref the type coercion
2409 : : * functions even if the merged column isn't explicitly
2410 : : * used anywhere, to protect possible expansion of the
2411 : : * join RTE as a whole-row var, and because it seems like
2412 : : * a bad idea to allow dropping a function that's present
2413 : : * in our query tree, whether or not it could get called.)
2414 : : */
2415 : 27612 : context->rtables = lcons(query->rtable, context->rtables);
2416 [ + + ]: 28016 : for (int i = 0; i < rte->joinmergedcols; i++)
2417 : : {
2418 : 404 : Node *aliasvar = list_nth(rte->joinaliasvars, i);
2419 : :
2420 [ + + ]: 404 : if (!IsA(aliasvar, Var))
2421 : 104 : find_expr_references_walker(aliasvar, context);
2422 : : }
2423 : 27612 : context->rtables = list_delete_first(context->rtables);
2424 : 27612 : break;
2425 : 4 : case RTE_NAMEDTUPLESTORE:
2426 : :
2427 : : /*
2428 : : * Cataloged objects cannot depend on tuplestores, because
2429 : : * those have no cataloged representation. For now we can
2430 : : * call the tuplestore a "transition table" because that's
2431 : : * the only kind exposed to SQL, but someday we might have
2432 : : * to work harder.
2433 : : */
2434 [ + - ]: 4 : ereport(ERROR,
2435 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2436 : : errmsg("transition table \"%s\" cannot be referenced in a persistent object",
2437 : : rte->eref->aliasname)));
2438 : : break;
2439 : 30113 : default:
2440 : : /* Other RTE types can be ignored here */
2441 : 30113 : break;
2442 : : }
2443 : : }
2444 : :
2445 : : /*
2446 : : * If the query is an INSERT, UPDATE, or MERGE, we should create a
2447 : : * dependency on each target column, to prevent the specific target
2448 : : * column from being dropped. Although we will visit the TargetEntry
2449 : : * nodes again during query_tree_walker, we won't have enough context
2450 : : * to do this conveniently, so do it here. (For MERGE, the target
2451 : : * columns are those of its INSERT and UPDATE actions.)
2452 : : */
2453 [ + + ]: 67305 : if (query->commandType == CMD_INSERT ||
2454 [ + + ]: 66655 : query->commandType == CMD_UPDATE ||
2455 [ + + ]: 66355 : query->commandType == CMD_MERGE)
2456 : : {
2457 : : RangeTblEntry *rte;
2458 : :
2459 [ + - - + ]: 1964 : if (query->resultRelation <= 0 ||
2460 : 982 : query->resultRelation > list_length(query->rtable))
2461 [ # # ]: 0 : elog(ERROR, "invalid resultRelation %d",
2462 : : query->resultRelation);
2463 : 982 : rte = rt_fetch(query->resultRelation, query->rtable);
2464 [ + - ]: 982 : if (rte->rtekind == RTE_RELATION)
2465 : : {
2466 [ + + ]: 982 : if (query->commandType == CMD_MERGE)
2467 : : {
2468 [ + - + + : 200 : foreach_node(MergeAction, action, query->mergeActionList)
+ + ]
2469 : : {
2470 [ + + ]: 136 : if (action->commandType == CMD_INSERT ||
2471 [ + + ]: 72 : action->commandType == CMD_UPDATE)
2472 : 112 : add_target_column_dependencies(action->targetList,
2473 : : rte->relid,
2474 : : context);
2475 : : }
2476 : : }
2477 : : else
2478 : 950 : add_target_column_dependencies(query->targetList,
2479 : : rte->relid, context);
2480 : : }
2481 : : }
2482 : :
2483 : : /*
2484 : : * Add dependencies on constraints listed in query's constraintDeps
2485 : : */
2486 [ + + + + : 67430 : foreach(lc, query->constraintDeps)
+ + ]
2487 : : {
2488 : 125 : add_object_address(ConstraintRelationId, lfirst_oid(lc), 0,
2489 : : context->addrs);
2490 : : }
2491 : :
2492 : : /* Examine substructure of query */
2493 : 67305 : context->rtables = lcons(query->rtable, context->rtables);
2494 : 67305 : result = query_tree_walker(query,
2495 : : find_expr_references_walker,
2496 : : context,
2497 : : QTW_IGNORE_JOINALIASES |
2498 : : QTW_EXAMINE_SORTGROUP);
2499 : 67305 : context->rtables = list_delete_first(context->rtables);
2500 : 67305 : return result;
2501 : : }
2502 [ + + ]: 920217 : else if (IsA(node, SetOperationStmt))
2503 : : {
2504 : 7168 : SetOperationStmt *setop = (SetOperationStmt *) node;
2505 : :
2506 : : /* we need to look at the groupClauses for operator references */
2507 : 7168 : find_expr_references_walker((Node *) setop->groupClauses, context);
2508 : : /* fall through to examine child nodes */
2509 : : }
2510 [ + + ]: 913049 : else if (IsA(node, RangeTblFunction))
2511 : : {
2512 : 10819 : RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2513 : : ListCell *ct;
2514 : :
2515 : : /*
2516 : : * Add refs for any datatypes and collations used in a column
2517 : : * definition list for a RECORD function. (For other cases, it should
2518 : : * be enough to depend on the function itself.)
2519 : : */
2520 [ + + + + : 11023 : foreach(ct, rtfunc->funccoltypes)
+ + ]
2521 : : {
2522 : 204 : add_object_address(TypeRelationId, lfirst_oid(ct), 0,
2523 : : context->addrs);
2524 : : }
2525 [ + + + + : 11023 : foreach(ct, rtfunc->funccolcollations)
+ + ]
2526 : : {
2527 : 204 : Oid collid = lfirst_oid(ct);
2528 : :
2529 [ + + - + ]: 204 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2530 : 0 : add_object_address(CollationRelationId, collid, 0,
2531 : : context->addrs);
2532 : : }
2533 : : }
2534 [ + + ]: 902230 : else if (IsA(node, TableFunc))
2535 : : {
2536 : 210 : TableFunc *tf = (TableFunc *) node;
2537 : : ListCell *ct;
2538 : :
2539 : : /*
2540 : : * Add refs for the datatypes and collations used in the TableFunc.
2541 : : */
2542 [ + - + + : 1221 : foreach(ct, tf->coltypes)
+ + ]
2543 : : {
2544 : 1011 : add_object_address(TypeRelationId, lfirst_oid(ct), 0,
2545 : : context->addrs);
2546 : : }
2547 [ + - + + : 1221 : foreach(ct, tf->colcollations)
+ + ]
2548 : : {
2549 : 1011 : Oid collid = lfirst_oid(ct);
2550 : :
2551 [ + + - + ]: 1011 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2552 : 0 : add_object_address(CollationRelationId, collid, 0,
2553 : : context->addrs);
2554 : : }
2555 : : }
2556 [ + + ]: 902020 : else if (IsA(node, TableSampleClause))
2557 : : {
2558 : 36 : TableSampleClause *tsc = (TableSampleClause *) node;
2559 : :
2560 : 36 : add_object_address(ProcedureRelationId, tsc->tsmhandler, 0,
2561 : : context->addrs);
2562 : : /* fall through to examine arguments */
2563 : : }
2564 : :
2565 : 1452524 : return expression_tree_walker(node, find_expr_references_walker,
2566 : : context);
2567 : : }
2568 : :
2569 : : /*
2570 : : * find_expr_references_walker subroutine: handle a Var reference
2571 : : * to an RTE_FUNCTION RTE
2572 : : */
2573 : : static void
2574 : 95374 : process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum,
2575 : : find_expr_references_context *context)
2576 : : {
2577 : 95374 : int atts_done = 0;
2578 : : ListCell *lc;
2579 : :
2580 : : /*
2581 : : * Identify which RangeTblFunction produces this attnum, and see if it
2582 : : * returns a composite type. If so, we'd better make a dependency on the
2583 : : * referenced column of the composite type (or actually, of its associated
2584 : : * relation).
2585 : : */
2586 [ + - + + : 95706 : foreach(lc, rte->functions)
+ + ]
2587 : : {
2588 : 95550 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2589 : :
2590 [ + - ]: 95550 : if (attnum > atts_done &&
2591 [ + + ]: 95550 : attnum <= atts_done + rtfunc->funccolcount)
2592 : : {
2593 : : TupleDesc tupdesc;
2594 : :
2595 : : /* If it has a coldeflist, it certainly returns RECORD */
2596 [ + + ]: 95218 : if (rtfunc->funccolnames != NIL)
2597 : 204 : tupdesc = NULL; /* no need to work hard */
2598 : : else
2599 : 95014 : tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr, true);
2600 [ + + + + ]: 95218 : if (tupdesc && tupdesc->tdtypeid != RECORDOID)
2601 : : {
2602 : : /*
2603 : : * Named composite type, so individual columns could get
2604 : : * dropped. Make a dependency on this specific column.
2605 : : */
2606 : 1194 : Oid reltype = get_typ_typrelid(tupdesc->tdtypeid);
2607 : :
2608 : : Assert(attnum - atts_done <= tupdesc->natts);
2609 [ + - ]: 1194 : if (OidIsValid(reltype)) /* can this fail? */
2610 : 1194 : add_object_address(RelationRelationId, reltype,
2611 : : attnum - atts_done,
2612 : : context->addrs);
2613 : 95218 : return;
2614 : : }
2615 : : /* Nothing to do; function's result type is handled elsewhere */
2616 : 94024 : return;
2617 : : }
2618 : 332 : atts_done += rtfunc->funccolcount;
2619 : : }
2620 : :
2621 : : /* If we get here, must be looking for the ordinality column */
2622 [ + - + - ]: 156 : if (rte->funcordinality && attnum == atts_done + 1)
2623 : 156 : return;
2624 : :
2625 : : /* this probably can't happen ... */
2626 [ # # ]: 0 : ereport(ERROR,
2627 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2628 : : errmsg("column %d of relation \"%s\" does not exist",
2629 : : attnum, rte->eref->aliasname)));
2630 : : }
2631 : :
2632 : : /*
2633 : : * find_temp_object - search an array of dependency references for temp objects
2634 : : *
2635 : : * Scan an ObjectAddresses array for references to temporary objects (objects
2636 : : * in temporary namespaces), ignoring those in our own temp namespace if
2637 : : * local_temp_okay is true. If one is found, return true after storing its
2638 : : * address in *foundobj.
2639 : : *
2640 : : * Current callers only use this to deliver helpful notices, so reporting
2641 : : * one such object seems sufficient. We return the first one, which should
2642 : : * be a stable result for a given query since it depends only on the order
2643 : : * in which this module searches query trees. (However, it's important to
2644 : : * call this before de-duplicating the objects, else OID order would affect
2645 : : * the result.)
2646 : : */
2647 : : bool
2648 : 26471 : find_temp_object(const ObjectAddresses *addrs, bool local_temp_okay,
2649 : : ObjectAddress *foundobj)
2650 : : {
2651 [ + + ]: 571756 : for (int i = 0; i < addrs->numrefs; i++)
2652 : : {
2653 : 545408 : const ObjectAddress *thisobj = addrs->refs + i;
2654 : : Oid objnamespace;
2655 : :
2656 : : /*
2657 : : * Use get_object_namespace() to see if this object belongs to a
2658 : : * schema. If not, we can skip it.
2659 : : */
2660 : 545408 : objnamespace = get_object_namespace(thisobj);
2661 : :
2662 : : /*
2663 : : * If the object is in a temporary namespace, complain, except if
2664 : : * local_temp_okay and it's our own temp namespace.
2665 : : */
2666 [ + + + + ]: 545408 : if (OidIsValid(objnamespace) && isAnyTempNamespace(objnamespace) &&
2667 [ + + - + ]: 124 : !(local_temp_okay && isTempNamespace(objnamespace)))
2668 : : {
2669 : 123 : *foundobj = *thisobj;
2670 : 123 : return true;
2671 : : }
2672 : : }
2673 : 26348 : return false;
2674 : : }
2675 : :
2676 : : /*
2677 : : * query_uses_temp_object - convenience wrapper for find_temp_object
2678 : : *
2679 : : * If the Query includes any use of a temporary object, fill *temp_object
2680 : : * with the address of one such object and return true.
2681 : : */
2682 : : bool
2683 : 11365 : query_uses_temp_object(Query *query, ObjectAddress *temp_object)
2684 : : {
2685 : : bool result;
2686 : : ObjectAddresses *addrs;
2687 : :
2688 : 11365 : addrs = new_object_addresses();
2689 : :
2690 : : /* Collect all dependencies from the Query */
2691 : 11365 : collectDependenciesOfExpr(addrs, (Node *) query, NIL);
2692 : :
2693 : : /* Look for one that is temp */
2694 : 11361 : result = find_temp_object(addrs, false, temp_object);
2695 : :
2696 : 11361 : free_object_addresses(addrs);
2697 : :
2698 : 11361 : return result;
2699 : : }
2700 : :
2701 : : /*
2702 : : * Given an array of dependency references, eliminate any duplicates.
2703 : : */
2704 : : static void
2705 : 315304 : eliminate_duplicate_dependencies(ObjectAddresses *addrs)
2706 : : {
2707 : : ObjectAddress *priorobj;
2708 : : int oldref,
2709 : : newrefs;
2710 : :
2711 : : /*
2712 : : * We can't sort if the array has "extra" data, because there's no way to
2713 : : * keep it in sync. Fortunately that combination of features is not
2714 : : * needed.
2715 : : */
2716 : : Assert(!addrs->extras);
2717 : :
2718 [ + + ]: 315304 : if (addrs->numrefs <= 1)
2719 : 101063 : return; /* nothing to do */
2720 : :
2721 : : /* Sort the refs so that duplicates are adjacent */
2722 : 214241 : qsort(addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2723 : : object_address_comparator);
2724 : :
2725 : : /* Remove dups */
2726 : 214241 : priorobj = addrs->refs;
2727 : 214241 : newrefs = 1;
2728 [ + + ]: 1793398 : for (oldref = 1; oldref < addrs->numrefs; oldref++)
2729 : : {
2730 : 1579157 : ObjectAddress *thisobj = addrs->refs + oldref;
2731 : :
2732 [ + + ]: 1579157 : if (priorobj->classId == thisobj->classId &&
2733 [ + + ]: 1362935 : priorobj->objectId == thisobj->objectId)
2734 : : {
2735 [ + + ]: 848697 : if (priorobj->objectSubId == thisobj->objectSubId)
2736 : 647651 : continue; /* identical, so drop thisobj */
2737 : :
2738 : : /*
2739 : : * If we have a whole-object reference and a reference to a part
2740 : : * of the same object, we don't need the whole-object reference
2741 : : * (for example, we don't need to reference both table foo and
2742 : : * column foo.bar). The whole-object reference will always appear
2743 : : * first in the sorted list.
2744 : : */
2745 [ + + ]: 201046 : if (priorobj->objectSubId == 0)
2746 : : {
2747 : : /* replace whole ref with partial */
2748 : 47005 : priorobj->objectSubId = thisobj->objectSubId;
2749 : 47005 : continue;
2750 : : }
2751 : : }
2752 : : /* Not identical, so add thisobj to output set */
2753 : 884501 : priorobj++;
2754 : 884501 : *priorobj = *thisobj;
2755 : 884501 : newrefs++;
2756 : : }
2757 : :
2758 : 214241 : addrs->numrefs = newrefs;
2759 : : }
2760 : :
2761 : : /*
2762 : : * qsort comparator for ObjectAddress items
2763 : : */
2764 : : static int
2765 : 5883382 : object_address_comparator(const void *a, const void *b)
2766 : : {
2767 : 5883382 : const ObjectAddress *obja = (const ObjectAddress *) a;
2768 : 5883382 : const ObjectAddress *objb = (const ObjectAddress *) b;
2769 : :
2770 : : /*
2771 : : * Primary sort key is OID descending. Most of the time, this will result
2772 : : * in putting newer objects before older ones, which is likely to be the
2773 : : * right order to delete in.
2774 : : */
2775 [ + + ]: 5883382 : if (obja->objectId > objb->objectId)
2776 : 1530979 : return -1;
2777 [ + + ]: 4352403 : if (obja->objectId < objb->objectId)
2778 : 2781792 : return 1;
2779 : :
2780 : : /*
2781 : : * Next sort on catalog ID, in case identical OIDs appear in different
2782 : : * catalogs. Sort direction is pretty arbitrary here.
2783 : : */
2784 [ - + ]: 1570611 : if (obja->classId < objb->classId)
2785 : 0 : return -1;
2786 [ - + ]: 1570611 : if (obja->classId > objb->classId)
2787 : 0 : return 1;
2788 : :
2789 : : /*
2790 : : * Last, sort on object subId.
2791 : : *
2792 : : * We sort the subId as an unsigned int so that 0 (the whole object) will
2793 : : * come first. This is essential for eliminate_duplicate_dependencies,
2794 : : * and is also the best order for findDependentObjects.
2795 : : */
2796 [ + + ]: 1570611 : if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2797 : 390796 : return -1;
2798 [ + + ]: 1179815 : if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2799 : 381355 : return 1;
2800 : 798460 : return 0;
2801 : : }
2802 : :
2803 : : /*
2804 : : * Routines for handling an expansible array of ObjectAddress items.
2805 : : *
2806 : : * new_object_addresses: create a new ObjectAddresses array.
2807 : : */
2808 : : ObjectAddresses *
2809 : 375362 : new_object_addresses(void)
2810 : : {
2811 : : ObjectAddresses *addrs;
2812 : :
2813 : 375362 : addrs = palloc_object(ObjectAddresses);
2814 : :
2815 : 375362 : addrs->numrefs = 0;
2816 : 375362 : addrs->maxrefs = 32;
2817 : 375362 : addrs->refs = palloc_array(ObjectAddress, addrs->maxrefs);
2818 : 375362 : addrs->extras = NULL; /* until/unless needed */
2819 : :
2820 : 375362 : return addrs;
2821 : : }
2822 : :
2823 : : /*
2824 : : * Add an entry to an ObjectAddresses array.
2825 : : */
2826 : : static void
2827 : 1462695 : add_object_address(Oid classId, Oid objectId, int32 subId,
2828 : : ObjectAddresses *addrs)
2829 : : {
2830 : : ObjectAddress *item;
2831 : :
2832 : : /* enlarge array if needed */
2833 [ + + ]: 1462695 : if (addrs->numrefs >= addrs->maxrefs)
2834 : : {
2835 : 20377 : addrs->maxrefs *= 2;
2836 : 20377 : addrs->refs = repalloc_array(addrs->refs, ObjectAddress, addrs->maxrefs);
2837 : : Assert(!addrs->extras);
2838 : : }
2839 : : /* record this item */
2840 : 1462695 : item = addrs->refs + addrs->numrefs;
2841 : 1462695 : item->classId = classId;
2842 : 1462695 : item->objectId = objectId;
2843 : 1462695 : item->objectSubId = subId;
2844 : 1462695 : addrs->numrefs++;
2845 : 1462695 : }
2846 : :
2847 : : /*
2848 : : * Add an entry to an ObjectAddresses array.
2849 : : *
2850 : : * As above, but specify entry exactly.
2851 : : */
2852 : : void
2853 : 862573 : add_exact_object_address(const ObjectAddress *object,
2854 : : ObjectAddresses *addrs)
2855 : : {
2856 : : ObjectAddress *item;
2857 : :
2858 : : /* enlarge array if needed */
2859 [ + + ]: 862573 : if (addrs->numrefs >= addrs->maxrefs)
2860 : : {
2861 : 37 : addrs->maxrefs *= 2;
2862 : 37 : addrs->refs = repalloc_array(addrs->refs, ObjectAddress, addrs->maxrefs);
2863 : : Assert(!addrs->extras);
2864 : : }
2865 : : /* record this item */
2866 : 862573 : item = addrs->refs + addrs->numrefs;
2867 : 862573 : *item = *object;
2868 : 862573 : addrs->numrefs++;
2869 : 862573 : }
2870 : :
2871 : : /*
2872 : : * Add an entry to an ObjectAddresses array.
2873 : : *
2874 : : * As above, but specify entry exactly and provide some "extra" data too.
2875 : : */
2876 : : static void
2877 : 157006 : add_exact_object_address_extra(const ObjectAddress *object,
2878 : : const ObjectAddressExtra *extra,
2879 : : ObjectAddresses *addrs)
2880 : : {
2881 : : ObjectAddress *item;
2882 : : ObjectAddressExtra *itemextra;
2883 : :
2884 : : /* allocate extra space if first time */
2885 [ + + ]: 157006 : if (!addrs->extras)
2886 : 24422 : addrs->extras = palloc_array(ObjectAddressExtra, addrs->maxrefs);
2887 : :
2888 : : /* enlarge array if needed */
2889 [ + + ]: 157006 : if (addrs->numrefs >= addrs->maxrefs)
2890 : : {
2891 : 592 : addrs->maxrefs *= 2;
2892 : 592 : addrs->refs = repalloc_array(addrs->refs, ObjectAddress, addrs->maxrefs);
2893 : 592 : addrs->extras = repalloc_array(addrs->extras, ObjectAddressExtra, addrs->maxrefs);
2894 : : }
2895 : : /* record this item */
2896 : 157006 : item = addrs->refs + addrs->numrefs;
2897 : 157006 : *item = *object;
2898 : 157006 : itemextra = addrs->extras + addrs->numrefs;
2899 : 157006 : *itemextra = *extra;
2900 : 157006 : addrs->numrefs++;
2901 : 157006 : }
2902 : :
2903 : : /*
2904 : : * Test whether an object is present in an ObjectAddresses array.
2905 : : *
2906 : : * We return "true" if object is a subobject of something in the array, too.
2907 : : */
2908 : : bool
2909 : 477 : object_address_present(const ObjectAddress *object,
2910 : : const ObjectAddresses *addrs)
2911 : : {
2912 : : int i;
2913 : :
2914 [ + + ]: 1796 : for (i = addrs->numrefs - 1; i >= 0; i--)
2915 : : {
2916 : 1356 : const ObjectAddress *thisobj = addrs->refs + i;
2917 : :
2918 [ + + ]: 1356 : if (object->classId == thisobj->classId &&
2919 [ + + ]: 400 : object->objectId == thisobj->objectId)
2920 : : {
2921 [ - + ]: 37 : if (object->objectSubId == thisobj->objectSubId ||
2922 [ # # ]: 0 : thisobj->objectSubId == 0)
2923 : 37 : return true;
2924 : : }
2925 : : }
2926 : :
2927 : 440 : return false;
2928 : : }
2929 : :
2930 : : /*
2931 : : * As above, except that if the object is present then also OR the given
2932 : : * flags into its associated extra data (which must exist).
2933 : : */
2934 : : static bool
2935 : 192159 : object_address_present_add_flags(const ObjectAddress *object,
2936 : : int flags,
2937 : : ObjectAddresses *addrs)
2938 : : {
2939 : 192159 : bool result = false;
2940 : : int i;
2941 : :
2942 [ + + ]: 7039707 : for (i = addrs->numrefs - 1; i >= 0; i--)
2943 : : {
2944 : 6847548 : ObjectAddress *thisobj = addrs->refs + i;
2945 : :
2946 [ + + ]: 6847548 : if (object->classId == thisobj->classId &&
2947 [ + + ]: 2649718 : object->objectId == thisobj->objectId)
2948 : : {
2949 [ + + ]: 33956 : if (object->objectSubId == thisobj->objectSubId)
2950 : : {
2951 : 33579 : ObjectAddressExtra *thisextra = addrs->extras + i;
2952 : :
2953 : 33579 : thisextra->flags |= flags;
2954 : 33579 : result = true;
2955 : : }
2956 [ + + ]: 377 : else if (thisobj->objectSubId == 0)
2957 : : {
2958 : : /*
2959 : : * We get here if we find a need to delete a column after
2960 : : * having already decided to drop its whole table. Obviously
2961 : : * we no longer need to drop the subobject, so report that we
2962 : : * found the subobject in the array. But don't plaster its
2963 : : * flags on the whole object.
2964 : : */
2965 : 313 : result = true;
2966 : : }
2967 [ + + ]: 64 : else if (object->objectSubId == 0)
2968 : : {
2969 : : /*
2970 : : * We get here if we find a need to delete a whole table after
2971 : : * having already decided to drop one of its columns. We
2972 : : * can't report that the whole object is in the array, but we
2973 : : * should mark the subobject with the whole object's flags.
2974 : : *
2975 : : * It might seem attractive to physically delete the column's
2976 : : * array entry, or at least mark it as no longer needing
2977 : : * separate deletion. But that could lead to, e.g., dropping
2978 : : * the column's datatype before we drop the table, which does
2979 : : * not seem like a good idea. This is a very rare situation
2980 : : * in practice, so we just take the hit of doing a separate
2981 : : * DROP COLUMN action even though we know we're gonna delete
2982 : : * the table later.
2983 : : *
2984 : : * What we can do, though, is mark this as a subobject so that
2985 : : * we don't report it separately, which is confusing because
2986 : : * it's unpredictable whether it happens or not. But do so
2987 : : * only if flags != 0 (flags == 0 is a read-only probe).
2988 : : *
2989 : : * Because there could be other subobjects of this object in
2990 : : * the array, this case means we always have to loop through
2991 : : * the whole array; we cannot exit early on a match.
2992 : : */
2993 : 52 : ObjectAddressExtra *thisextra = addrs->extras + i;
2994 : :
2995 [ + - ]: 52 : if (flags)
2996 : 52 : thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2997 : : }
2998 : : }
2999 : : }
3000 : :
3001 : 192159 : return result;
3002 : : }
3003 : :
3004 : : /*
3005 : : * Similar to above, except we search an ObjectAddressStack.
3006 : : */
3007 : : static bool
3008 : 276016 : stack_address_present_add_flags(const ObjectAddress *object,
3009 : : int flags,
3010 : : ObjectAddressStack *stack)
3011 : : {
3012 : 276016 : bool result = false;
3013 : : ObjectAddressStack *stackptr;
3014 : :
3015 [ + + ]: 728624 : for (stackptr = stack; stackptr; stackptr = stackptr->next)
3016 : : {
3017 : 452608 : const ObjectAddress *thisobj = stackptr->object;
3018 : :
3019 [ + + ]: 452608 : if (object->classId == thisobj->classId &&
3020 [ + + ]: 201521 : object->objectId == thisobj->objectId)
3021 : : {
3022 [ + + ]: 83905 : if (object->objectSubId == thisobj->objectSubId)
3023 : : {
3024 : 83183 : stackptr->flags |= flags;
3025 : 83183 : result = true;
3026 : : }
3027 [ + + ]: 722 : else if (thisobj->objectSubId == 0)
3028 : : {
3029 : : /*
3030 : : * We're visiting a column with whole table already on stack.
3031 : : * As in object_address_present_add_flags(), we can skip
3032 : : * further processing of the subobject, but we don't want to
3033 : : * propagate flags for the subobject to the whole object.
3034 : : */
3035 : 674 : result = true;
3036 : : }
3037 [ - + ]: 48 : else if (object->objectSubId == 0)
3038 : : {
3039 : : /*
3040 : : * We're visiting a table with column already on stack. As in
3041 : : * object_address_present_add_flags(), we should propagate
3042 : : * flags for the whole object to each of its subobjects.
3043 : : */
3044 [ # # ]: 0 : if (flags)
3045 : 0 : stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
3046 : : }
3047 : : }
3048 : : }
3049 : :
3050 : 276016 : return result;
3051 : : }
3052 : :
3053 : : /*
3054 : : * Record multiple dependencies from an ObjectAddresses array, after first
3055 : : * removing any duplicates.
3056 : : */
3057 : : void
3058 : 269411 : record_object_address_dependencies(const ObjectAddress *depender,
3059 : : ObjectAddresses *referenced,
3060 : : DependencyType behavior)
3061 : : {
3062 : 269411 : eliminate_duplicate_dependencies(referenced);
3063 : 269411 : recordMultipleDependencies(depender,
3064 : 269411 : referenced->refs, referenced->numrefs,
3065 : : behavior);
3066 : 269406 : }
3067 : :
3068 : : /*
3069 : : * Sort the items in an ObjectAddresses array.
3070 : : *
3071 : : * The major sort key is OID-descending, so that newer objects will be listed
3072 : : * first in most cases. This is primarily useful for ensuring stable outputs
3073 : : * from regression tests; it's not recommended if the order of the objects is
3074 : : * determined by user input, such as the order of targets in a DROP command.
3075 : : */
3076 : : void
3077 : 101 : sort_object_addresses(ObjectAddresses *addrs)
3078 : : {
3079 [ + + ]: 101 : if (addrs->numrefs > 1)
3080 : 50 : qsort(addrs->refs, addrs->numrefs,
3081 : : sizeof(ObjectAddress),
3082 : : object_address_comparator);
3083 : 101 : }
3084 : :
3085 : : /*
3086 : : * Clean up when done with an ObjectAddresses array.
3087 : : */
3088 : : void
3089 : 373796 : free_object_addresses(ObjectAddresses *addrs)
3090 : : {
3091 : 373796 : pfree(addrs->refs);
3092 [ + + ]: 373796 : if (addrs->extras)
3093 : 24142 : pfree(addrs->extras);
3094 : 373796 : pfree(addrs);
3095 : 373796 : }
3096 : :
3097 : : /*
3098 : : * delete initial ACL for extension objects
3099 : : */
3100 : : static void
3101 : 153597 : DeleteInitPrivs(const ObjectAddress *object)
3102 : : {
3103 : : Relation relation;
3104 : : ScanKeyData key[3];
3105 : : int nkeys;
3106 : : SysScanDesc scan;
3107 : : HeapTuple oldtuple;
3108 : :
3109 : 153597 : relation = table_open(InitPrivsRelationId, RowExclusiveLock);
3110 : :
3111 : 153597 : ScanKeyInit(&key[0],
3112 : : Anum_pg_init_privs_objoid,
3113 : : BTEqualStrategyNumber, F_OIDEQ,
3114 : 153597 : ObjectIdGetDatum(object->objectId));
3115 : 153597 : ScanKeyInit(&key[1],
3116 : : Anum_pg_init_privs_classoid,
3117 : : BTEqualStrategyNumber, F_OIDEQ,
3118 : 153597 : ObjectIdGetDatum(object->classId));
3119 [ + + ]: 153597 : if (object->objectSubId != 0)
3120 : : {
3121 : 1475 : ScanKeyInit(&key[2],
3122 : : Anum_pg_init_privs_objsubid,
3123 : : BTEqualStrategyNumber, F_INT4EQ,
3124 : 1475 : Int32GetDatum(object->objectSubId));
3125 : 1475 : nkeys = 3;
3126 : : }
3127 : : else
3128 : 152122 : nkeys = 2;
3129 : :
3130 : 153597 : scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
3131 : : NULL, nkeys, key);
3132 : :
3133 [ + + ]: 153680 : while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
3134 : 83 : CatalogTupleDelete(relation, &oldtuple->t_self);
3135 : :
3136 : 153597 : systable_endscan(scan);
3137 : :
3138 : 153597 : table_close(relation, RowExclusiveLock);
3139 : 153597 : }
|