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