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