PostgreSQL Source Code  git master
dependency.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * dependency.c
4  * Routines to support inter-object dependencies.
5  *
6  *
7  * Portions Copyright (c) 1996-2020, 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"
38 #include "catalog/pg_extension.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"
52 #include "catalog/pg_rewrite.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"
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"
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 */
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 */
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 */
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 */
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 */
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 void AcquireDeletionLock(const ObjectAddress *object, int flags);
203 static void ReleaseDeletionLock(const ObjectAddress *object);
204 static bool find_expr_references_walker(Node *node,
207 static int object_address_comparator(const void *a, const void *b);
208 static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
209  ObjectAddresses *addrs);
210 static void add_exact_object_address_extra(const ObjectAddress *object,
211  const ObjectAddressExtra *extra,
212  ObjectAddresses *addrs);
213 static bool object_address_present_add_flags(const ObjectAddress *object,
214  int flags,
215  ObjectAddresses *addrs);
216 static bool stack_address_present_add_flags(const ObjectAddress *object,
217  int flags,
218  ObjectAddressStack *stack);
219 static void DeleteInitPrivs(const ObjectAddress *object);
220 
221 
222 /*
223  * Go through the objects given running the final actions on them, and execute
224  * the actual deletion.
225  */
226 static void
228  int flags)
229 {
230  int i;
231 
232  /*
233  * Keep track of objects for event triggers, if necessary.
234  */
236  {
237  for (i = 0; i < targetObjects->numrefs; i++)
238  {
239  const ObjectAddress *thisobj = &targetObjects->refs[i];
240  const ObjectAddressExtra *extra = &targetObjects->extras[i];
241  bool original = false;
242  bool normal = false;
243 
244  if (extra->flags & DEPFLAG_ORIGINAL)
245  original = true;
246  if (extra->flags & DEPFLAG_NORMAL)
247  normal = true;
248  if (extra->flags & DEPFLAG_REVERSE)
249  normal = true;
250 
252  {
253  EventTriggerSQLDropAddObject(thisobj, original, normal);
254  }
255  }
256  }
257 
258  /*
259  * Delete all the objects in the proper order, except that if told to, we
260  * should skip the original object(s).
261  */
262  for (i = 0; i < targetObjects->numrefs; i++)
263  {
264  ObjectAddress *thisobj = targetObjects->refs + i;
265  ObjectAddressExtra *thisextra = targetObjects->extras + i;
266 
267  if ((flags & PERFORM_DELETION_SKIP_ORIGINAL) &&
268  (thisextra->flags & DEPFLAG_ORIGINAL))
269  continue;
270 
271  deleteOneObject(thisobj, depRel, flags);
272  }
273 }
274 
275 /*
276  * performDeletion: attempt to drop the specified object. If CASCADE
277  * behavior is specified, also drop any dependent objects (recursively).
278  * If RESTRICT behavior is specified, error out if there are any dependent
279  * objects, except for those that should be implicitly dropped anyway
280  * according to the dependency type.
281  *
282  * This is the outer control routine for all forms of DROP that drop objects
283  * that can participate in dependencies. Note that performMultipleDeletions
284  * is a variant on the same theme; if you change anything here you'll likely
285  * need to fix that too.
286  *
287  * Bits in the flags argument can include:
288  *
289  * PERFORM_DELETION_INTERNAL: indicates that the drop operation is not the
290  * direct result of a user-initiated action. For example, when a temporary
291  * schema is cleaned out so that a new backend can use it, or when a column
292  * default is dropped as an intermediate step while adding a new one, that's
293  * an internal operation. On the other hand, when we drop something because
294  * the user issued a DROP statement against it, that's not internal. Currently
295  * this suppresses calling event triggers and making some permissions checks.
296  *
297  * PERFORM_DELETION_CONCURRENTLY: perform the drop concurrently. This does
298  * not currently work for anything except dropping indexes; don't set it for
299  * other object types or you may get strange results.
300  *
301  * PERFORM_DELETION_QUIETLY: reduce message level from NOTICE to DEBUG2.
302  *
303  * PERFORM_DELETION_SKIP_ORIGINAL: do not delete the specified object(s),
304  * but only what depends on it/them.
305  *
306  * PERFORM_DELETION_SKIP_EXTENSIONS: do not delete extensions, even when
307  * deleting objects that are part of an extension. This should generally
308  * be used only when dropping temporary objects.
309  *
310  * PERFORM_DELETION_CONCURRENT_LOCK: perform the drop normally but with a lock
311  * as if it were concurrent. This is used by REINDEX CONCURRENTLY.
312  *
313  */
314 void
316  DropBehavior behavior, int flags)
317 {
318  Relation depRel;
319  ObjectAddresses *targetObjects;
320 
321  /*
322  * We save some cycles by opening pg_depend just once and passing the
323  * Relation pointer down to all the recursive deletion steps.
324  */
325  depRel = table_open(DependRelationId, RowExclusiveLock);
326 
327  /*
328  * Acquire deletion lock on the target object. (Ideally the caller has
329  * done this already, but many places are sloppy about it.)
330  */
331  AcquireDeletionLock(object, 0);
332 
333  /*
334  * Construct a list of objects to delete (ie, the given object plus
335  * everything directly or indirectly dependent on it).
336  */
337  targetObjects = new_object_addresses();
338 
339  findDependentObjects(object,
341  flags,
342  NULL, /* empty stack */
343  targetObjects,
344  NULL, /* no pendingObjects */
345  &depRel);
346 
347  /*
348  * Check if deletion is allowed, and report about cascaded deletes.
349  */
350  reportDependentObjects(targetObjects,
351  behavior,
352  flags,
353  object);
354 
355  /* do the deed */
356  deleteObjectsInList(targetObjects, &depRel, flags);
357 
358  /* And clean up */
359  free_object_addresses(targetObjects);
360 
361  table_close(depRel, RowExclusiveLock);
362 }
363 
364 /*
365  * performMultipleDeletions: Similar to performDeletion, but act on multiple
366  * objects at once.
367  *
368  * The main difference from issuing multiple performDeletion calls is that the
369  * list of objects that would be implicitly dropped, for each object to be
370  * dropped, is the union of the implicit-object list for all objects. This
371  * makes each check be more relaxed.
372  */
373 void
375  DropBehavior behavior, int flags)
376 {
377  Relation depRel;
378  ObjectAddresses *targetObjects;
379  int i;
380 
381  /* No work if no objects... */
382  if (objects->numrefs <= 0)
383  return;
384 
385  /*
386  * We save some cycles by opening pg_depend just once and passing the
387  * Relation pointer down to all the recursive deletion steps.
388  */
389  depRel = table_open(DependRelationId, RowExclusiveLock);
390 
391  /*
392  * Construct a list of objects to delete (ie, the given objects plus
393  * everything directly or indirectly dependent on them). Note that
394  * because we pass the whole objects list as pendingObjects context, we
395  * won't get a failure from trying to delete an object that is internally
396  * dependent on another one in the list; we'll just skip that object and
397  * delete it when we reach its owner.
398  */
399  targetObjects = new_object_addresses();
400 
401  for (i = 0; i < objects->numrefs; i++)
402  {
403  const ObjectAddress *thisobj = objects->refs + i;
404 
405  /*
406  * Acquire deletion lock on each target object. (Ideally the caller
407  * has done this already, but many places are sloppy about it.)
408  */
409  AcquireDeletionLock(thisobj, flags);
410 
411  findDependentObjects(thisobj,
413  flags,
414  NULL, /* empty stack */
415  targetObjects,
416  objects,
417  &depRel);
418  }
419 
420  /*
421  * Check if deletion is allowed, and report about cascaded deletes.
422  *
423  * If there's exactly one object being deleted, report it the same way as
424  * in performDeletion(), else we have to be vaguer.
425  */
426  reportDependentObjects(targetObjects,
427  behavior,
428  flags,
429  (objects->numrefs == 1 ? objects->refs : NULL));
430 
431  /* do the deed */
432  deleteObjectsInList(targetObjects, &depRel, flags);
433 
434  /* And clean up */
435  free_object_addresses(targetObjects);
436 
437  table_close(depRel, RowExclusiveLock);
438 }
439 
440 /*
441  * findDependentObjects - find all objects that depend on 'object'
442  *
443  * For every object that depends on the starting object, acquire a deletion
444  * lock on the object, add it to targetObjects (if not already there),
445  * and recursively find objects that depend on it. An object's dependencies
446  * will be placed into targetObjects before the object itself; this means
447  * that the finished list's order represents a safe deletion order.
448  *
449  * The caller must already have a deletion lock on 'object' itself,
450  * but must not have added it to targetObjects. (Note: there are corner
451  * cases where we won't add the object either, and will also release the
452  * caller-taken lock. This is a bit ugly, but the API is set up this way
453  * to allow easy rechecking of an object's liveness after we lock it. See
454  * notes within the function.)
455  *
456  * When dropping a whole object (subId = 0), we find dependencies for
457  * its sub-objects too.
458  *
459  * object: the object to add to targetObjects and find dependencies on
460  * objflags: flags to be ORed into the object's targetObjects entry
461  * flags: PERFORM_DELETION_xxx flags for the deletion operation as a whole
462  * stack: list of objects being visited in current recursion; topmost item
463  * is the object that we recursed from (NULL for external callers)
464  * targetObjects: list of objects that are scheduled to be deleted
465  * pendingObjects: list of other objects slated for destruction, but
466  * not necessarily in targetObjects yet (can be NULL if none)
467  * *depRel: already opened pg_depend relation
468  *
469  * Note: objflags describes the reason for visiting this particular object
470  * at this time, and is not passed down when recursing. The flags argument
471  * is passed down, since it describes what we're doing overall.
472  */
473 static void
475  int objflags,
476  int flags,
477  ObjectAddressStack *stack,
478  ObjectAddresses *targetObjects,
479  const ObjectAddresses *pendingObjects,
480  Relation *depRel)
481 {
482  ScanKeyData key[3];
483  int nkeys;
484  SysScanDesc scan;
485  HeapTuple tup;
486  ObjectAddress otherObject;
487  ObjectAddress owningObject;
488  ObjectAddress partitionObject;
489  ObjectAddressAndFlags *dependentObjects;
490  int numDependentObjects;
491  int maxDependentObjects;
492  ObjectAddressStack mystack;
493  ObjectAddressExtra extra;
494 
495  /*
496  * If the target object is already being visited in an outer recursion
497  * level, just report the current objflags back to that level and exit.
498  * This is needed to avoid infinite recursion in the face of circular
499  * dependencies.
500  *
501  * The stack check alone would result in dependency loops being broken at
502  * an arbitrary point, ie, the first member object of the loop to be
503  * visited is the last one to be deleted. This is obviously unworkable.
504  * However, the check for internal dependency below guarantees that we
505  * will not break a loop at an internal dependency: if we enter the loop
506  * at an "owned" object we will switch and start at the "owning" object
507  * instead. We could probably hack something up to avoid breaking at an
508  * auto dependency, too, if we had to. However there are no known cases
509  * where that would be necessary.
510  */
511  if (stack_address_present_add_flags(object, objflags, stack))
512  return;
513 
514  /*
515  * It's also possible that the target object has already been completely
516  * processed and put into targetObjects. If so, again we just add the
517  * specified objflags to its entry and return.
518  *
519  * (Note: in these early-exit cases we could release the caller-taken
520  * lock, since the object is presumably now locked multiple times; but it
521  * seems not worth the cycles.)
522  */
523  if (object_address_present_add_flags(object, objflags, targetObjects))
524  return;
525 
526  /*
527  * The target object might be internally dependent on some other object
528  * (its "owner"), and/or be a member of an extension (also considered its
529  * owner). If so, and if we aren't recursing from the owning object, we
530  * have to transform this deletion request into a deletion request of the
531  * owning object. (We'll eventually recurse back to this object, but the
532  * owning object has to be visited first so it will be deleted after.) The
533  * way to find out about this is to scan the pg_depend entries that show
534  * what this object depends on.
535  */
536  ScanKeyInit(&key[0],
537  Anum_pg_depend_classid,
538  BTEqualStrategyNumber, F_OIDEQ,
539  ObjectIdGetDatum(object->classId));
540  ScanKeyInit(&key[1],
541  Anum_pg_depend_objid,
542  BTEqualStrategyNumber, F_OIDEQ,
543  ObjectIdGetDatum(object->objectId));
544  if (object->objectSubId != 0)
545  {
546  /* Consider only dependencies of this sub-object */
547  ScanKeyInit(&key[2],
548  Anum_pg_depend_objsubid,
549  BTEqualStrategyNumber, F_INT4EQ,
550  Int32GetDatum(object->objectSubId));
551  nkeys = 3;
552  }
553  else
554  {
555  /* Consider dependencies of this object and any sub-objects it has */
556  nkeys = 2;
557  }
558 
559  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
560  NULL, nkeys, key);
561 
562  /* initialize variables that loop may fill */
563  memset(&owningObject, 0, sizeof(owningObject));
564  memset(&partitionObject, 0, sizeof(partitionObject));
565 
566  while (HeapTupleIsValid(tup = systable_getnext(scan)))
567  {
568  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
569 
570  otherObject.classId = foundDep->refclassid;
571  otherObject.objectId = foundDep->refobjid;
572  otherObject.objectSubId = foundDep->refobjsubid;
573 
574  /*
575  * When scanning dependencies of a whole object, we may find rows
576  * linking sub-objects of the object to the object itself. (Normally,
577  * such a dependency is implicit, but we must make explicit ones in
578  * some cases involving partitioning.) We must ignore such rows to
579  * avoid infinite recursion.
580  */
581  if (otherObject.classId == object->classId &&
582  otherObject.objectId == object->objectId &&
583  object->objectSubId == 0)
584  continue;
585 
586  switch (foundDep->deptype)
587  {
588  case DEPENDENCY_NORMAL:
589  case DEPENDENCY_AUTO:
591  /* no problem */
592  break;
593 
595 
596  /*
597  * If told to, ignore EXTENSION dependencies altogether. This
598  * flag is normally used to prevent dropping extensions during
599  * temporary-object cleanup, even if a temp object was created
600  * during an extension script.
601  */
603  break;
604 
605  /*
606  * If the other object is the extension currently being
607  * created/altered, ignore this dependency and continue with
608  * the deletion. This allows dropping of an extension's
609  * objects within the extension's scripts, as well as corner
610  * cases such as dropping a transient object created within
611  * such a script.
612  */
613  if (creating_extension &&
614  otherObject.classId == ExtensionRelationId &&
615  otherObject.objectId == CurrentExtensionObject)
616  break;
617 
618  /* Otherwise, treat this like an internal dependency */
619  /* FALL THRU */
620 
621  case DEPENDENCY_INTERNAL:
622 
623  /*
624  * This object is part of the internal implementation of
625  * another object, or is part of the extension that is the
626  * other object. We have three cases:
627  *
628  * 1. At the outermost recursion level, we must disallow the
629  * DROP. However, if the owning object is listed in
630  * pendingObjects, just release the caller's lock and return;
631  * we'll eventually complete the DROP when we reach that entry
632  * in the pending list.
633  *
634  * Note: the above statement is true only if this pg_depend
635  * entry still exists by then; in principle, therefore, we
636  * could miss deleting an item the user told us to delete.
637  * However, no inconsistency can result: since we're at outer
638  * level, there is no object depending on this one.
639  */
640  if (stack == NULL)
641  {
642  if (pendingObjects &&
643  object_address_present(&otherObject, pendingObjects))
644  {
645  systable_endscan(scan);
646  /* need to release caller's lock; see notes below */
647  ReleaseDeletionLock(object);
648  return;
649  }
650 
651  /*
652  * We postpone actually issuing the error message until
653  * after this loop, so that we can make the behavior
654  * independent of the ordering of pg_depend entries, at
655  * least if there's not more than one INTERNAL and one
656  * EXTENSION dependency. (If there's more, we'll complain
657  * about a random one of them.) Prefer to complain about
658  * EXTENSION, since that's generally a more important
659  * dependency.
660  */
661  if (!OidIsValid(owningObject.classId) ||
662  foundDep->deptype == DEPENDENCY_EXTENSION)
663  owningObject = otherObject;
664  break;
665  }
666 
667  /*
668  * 2. When recursing from the other end of this dependency,
669  * it's okay to continue with the deletion. This holds when
670  * recursing from a whole object that includes the nominal
671  * other end as a component, too. Since there can be more
672  * than one "owning" object, we have to allow matches that are
673  * more than one level down in the stack.
674  */
675  if (stack_address_present_add_flags(&otherObject, 0, stack))
676  break;
677 
678  /*
679  * 3. Not all the owning objects have been visited, so
680  * transform this deletion request into a delete of this
681  * owning object.
682  *
683  * First, release caller's lock on this object and get
684  * deletion lock on the owning object. (We must release
685  * caller's lock to avoid deadlock against a concurrent
686  * deletion of the owning object.)
687  */
688  ReleaseDeletionLock(object);
689  AcquireDeletionLock(&otherObject, 0);
690 
691  /*
692  * The owning object might have been deleted while we waited
693  * to lock it; if so, neither it nor the current object are
694  * interesting anymore. We test this by checking the
695  * pg_depend entry (see notes below).
696  */
697  if (!systable_recheck_tuple(scan, tup))
698  {
699  systable_endscan(scan);
700  ReleaseDeletionLock(&otherObject);
701  return;
702  }
703 
704  /*
705  * One way or the other, we're done with the scan; might as
706  * well close it down before recursing, to reduce peak
707  * resource consumption.
708  */
709  systable_endscan(scan);
710 
711  /*
712  * Okay, recurse to the owning object instead of proceeding.
713  *
714  * We do not need to stack the current object; we want the
715  * traversal order to be as if the original reference had
716  * linked to the owning object instead of this one.
717  *
718  * The dependency type is a "reverse" dependency: we need to
719  * delete the owning object if this one is to be deleted, but
720  * this linkage is never a reason for an automatic deletion.
721  */
722  findDependentObjects(&otherObject,
724  flags,
725  stack,
726  targetObjects,
727  pendingObjects,
728  depRel);
729 
730  /*
731  * The current target object should have been added to
732  * targetObjects while processing the owning object; but it
733  * probably got only the flag bits associated with the
734  * dependency we're looking at. We need to add the objflags
735  * that were passed to this recursion level, too, else we may
736  * get a bogus failure in reportDependentObjects (if, for
737  * example, we were called due to a partition dependency).
738  *
739  * If somehow the current object didn't get scheduled for
740  * deletion, bleat. (That would imply that somebody deleted
741  * this dependency record before the recursion got to it.)
742  * Another idea would be to reacquire lock on the current
743  * object and resume trying to delete it, but it seems not
744  * worth dealing with the race conditions inherent in that.
745  */
746  if (!object_address_present_add_flags(object, objflags,
747  targetObjects))
748  elog(ERROR, "deletion of owning object %s failed to delete %s",
749  getObjectDescription(&otherObject),
750  getObjectDescription(object));
751 
752  /* And we're done here. */
753  return;
754 
756 
757  /*
758  * Remember that this object has a partition-type dependency.
759  * After the dependency scan, we'll complain if we didn't find
760  * a reason to delete one of its partition dependencies.
761  */
762  objflags |= DEPFLAG_IS_PART;
763 
764  /*
765  * Also remember the primary partition owner, for error
766  * messages. If there are multiple primary owners (which
767  * there should not be), we'll report a random one of them.
768  */
769  partitionObject = otherObject;
770  break;
771 
773 
774  /*
775  * Only use secondary partition owners in error messages if we
776  * find no primary owner (which probably shouldn't happen).
777  */
778  if (!(objflags & DEPFLAG_IS_PART))
779  partitionObject = otherObject;
780 
781  /*
782  * Remember that this object has a partition-type dependency.
783  * After the dependency scan, we'll complain if we didn't find
784  * a reason to delete one of its partition dependencies.
785  */
786  objflags |= DEPFLAG_IS_PART;
787  break;
788 
789  case DEPENDENCY_PIN:
790 
791  /*
792  * Should not happen; PIN dependencies should have zeroes in
793  * the depender fields...
794  */
795  elog(ERROR, "incorrect use of PIN dependency with %s",
796  getObjectDescription(object));
797  break;
798  default:
799  elog(ERROR, "unrecognized dependency type '%c' for %s",
800  foundDep->deptype, getObjectDescription(object));
801  break;
802  }
803  }
804 
805  systable_endscan(scan);
806 
807  /*
808  * If we found an INTERNAL or EXTENSION dependency when we're at outer
809  * level, complain about it now. If we also found a PARTITION dependency,
810  * we prefer to report the PARTITION dependency. This is arbitrary but
811  * seems to be more useful in practice.
812  */
813  if (OidIsValid(owningObject.classId))
814  {
815  char *otherObjDesc;
816 
817  if (OidIsValid(partitionObject.classId))
818  otherObjDesc = getObjectDescription(&partitionObject);
819  else
820  otherObjDesc = getObjectDescription(&owningObject);
821 
822  ereport(ERROR,
823  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
824  errmsg("cannot drop %s because %s requires it",
825  getObjectDescription(object), otherObjDesc),
826  errhint("You can drop %s instead.", otherObjDesc)));
827  }
828 
829  /*
830  * Next, identify all objects that directly depend on the current object.
831  * To ensure predictable deletion order, we collect them up in
832  * dependentObjects and sort the list before actually recursing. (The
833  * deletion order would be valid in any case, but doing this ensures
834  * consistent output from DROP CASCADE commands, which is helpful for
835  * regression testing.)
836  */
837  maxDependentObjects = 128; /* arbitrary initial allocation */
838  dependentObjects = (ObjectAddressAndFlags *)
839  palloc(maxDependentObjects * sizeof(ObjectAddressAndFlags));
840  numDependentObjects = 0;
841 
842  ScanKeyInit(&key[0],
843  Anum_pg_depend_refclassid,
844  BTEqualStrategyNumber, F_OIDEQ,
845  ObjectIdGetDatum(object->classId));
846  ScanKeyInit(&key[1],
847  Anum_pg_depend_refobjid,
848  BTEqualStrategyNumber, F_OIDEQ,
849  ObjectIdGetDatum(object->objectId));
850  if (object->objectSubId != 0)
851  {
852  ScanKeyInit(&key[2],
853  Anum_pg_depend_refobjsubid,
854  BTEqualStrategyNumber, F_INT4EQ,
855  Int32GetDatum(object->objectSubId));
856  nkeys = 3;
857  }
858  else
859  nkeys = 2;
860 
861  scan = systable_beginscan(*depRel, DependReferenceIndexId, true,
862  NULL, nkeys, key);
863 
864  while (HeapTupleIsValid(tup = systable_getnext(scan)))
865  {
866  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
867  int subflags;
868 
869  otherObject.classId = foundDep->classid;
870  otherObject.objectId = foundDep->objid;
871  otherObject.objectSubId = foundDep->objsubid;
872 
873  /*
874  * If what we found is a sub-object of the current object, just ignore
875  * it. (Normally, such a dependency is implicit, but we must make
876  * explicit ones in some cases involving partitioning.)
877  */
878  if (otherObject.classId == object->classId &&
879  otherObject.objectId == object->objectId &&
880  object->objectSubId == 0)
881  continue;
882 
883  /*
884  * Must lock the dependent object before recursing to it.
885  */
886  AcquireDeletionLock(&otherObject, 0);
887 
888  /*
889  * The dependent object might have been deleted while we waited to
890  * lock it; if so, we don't need to do anything more with it. We can
891  * test this cheaply and independently of the object's type by seeing
892  * if the pg_depend tuple we are looking at is still live. (If the
893  * object got deleted, the tuple would have been deleted too.)
894  */
895  if (!systable_recheck_tuple(scan, tup))
896  {
897  /* release the now-useless lock */
898  ReleaseDeletionLock(&otherObject);
899  /* and continue scanning for dependencies */
900  continue;
901  }
902 
903  /*
904  * We do need to delete it, so identify objflags to be passed down,
905  * which depend on the dependency type.
906  */
907  switch (foundDep->deptype)
908  {
909  case DEPENDENCY_NORMAL:
910  subflags = DEPFLAG_NORMAL;
911  break;
912  case DEPENDENCY_AUTO:
914  subflags = DEPFLAG_AUTO;
915  break;
916  case DEPENDENCY_INTERNAL:
917  subflags = DEPFLAG_INTERNAL;
918  break;
921  subflags = DEPFLAG_PARTITION;
922  break;
924  subflags = DEPFLAG_EXTENSION;
925  break;
926  case DEPENDENCY_PIN:
927 
928  /*
929  * For a PIN dependency we just ereport immediately; there
930  * won't be any others to report.
931  */
932  ereport(ERROR,
933  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
934  errmsg("cannot drop %s because it is required by the database system",
935  getObjectDescription(object))));
936  subflags = 0; /* keep compiler quiet */
937  break;
938  default:
939  elog(ERROR, "unrecognized dependency type '%c' for %s",
940  foundDep->deptype, getObjectDescription(object));
941  subflags = 0; /* keep compiler quiet */
942  break;
943  }
944 
945  /* And add it to the pending-objects list */
946  if (numDependentObjects >= maxDependentObjects)
947  {
948  /* enlarge array if needed */
949  maxDependentObjects *= 2;
950  dependentObjects = (ObjectAddressAndFlags *)
951  repalloc(dependentObjects,
952  maxDependentObjects * sizeof(ObjectAddressAndFlags));
953  }
954 
955  dependentObjects[numDependentObjects].obj = otherObject;
956  dependentObjects[numDependentObjects].subflags = subflags;
957  numDependentObjects++;
958  }
959 
960  systable_endscan(scan);
961 
962  /*
963  * Now we can sort the dependent objects into a stable visitation order.
964  * It's safe to use object_address_comparator here since the obj field is
965  * first within ObjectAddressAndFlags.
966  */
967  if (numDependentObjects > 1)
968  qsort((void *) dependentObjects, numDependentObjects,
969  sizeof(ObjectAddressAndFlags),
971 
972  /*
973  * Now recurse to the dependent objects. We must visit them first since
974  * they have to be deleted before the current object.
975  */
976  mystack.object = object; /* set up a new stack level */
977  mystack.flags = objflags;
978  mystack.next = stack;
979 
980  for (int i = 0; i < numDependentObjects; i++)
981  {
982  ObjectAddressAndFlags *depObj = dependentObjects + i;
983 
984  findDependentObjects(&depObj->obj,
985  depObj->subflags,
986  flags,
987  &mystack,
988  targetObjects,
989  pendingObjects,
990  depRel);
991  }
992 
993  pfree(dependentObjects);
994 
995  /*
996  * Finally, we can add the target object to targetObjects. Be careful to
997  * include any flags that were passed back down to us from inner recursion
998  * levels. Record the "dependee" as being either the most important
999  * partition owner if there is one, else the object we recursed from, if
1000  * any. (The logic in reportDependentObjects() is such that it can only
1001  * need one of those objects.)
1002  */
1003  extra.flags = mystack.flags;
1004  if (extra.flags & DEPFLAG_IS_PART)
1005  extra.dependee = partitionObject;
1006  else if (stack)
1007  extra.dependee = *stack->object;
1008  else
1009  memset(&extra.dependee, 0, sizeof(extra.dependee));
1010  add_exact_object_address_extra(object, &extra, targetObjects);
1011 }
1012 
1013 /*
1014  * reportDependentObjects - report about dependencies, and fail if RESTRICT
1015  *
1016  * Tell the user about dependent objects that we are going to delete
1017  * (or would need to delete, but are prevented by RESTRICT mode);
1018  * then error out if there are any and it's not CASCADE mode.
1019  *
1020  * targetObjects: list of objects that are scheduled to be deleted
1021  * behavior: RESTRICT or CASCADE
1022  * flags: other flags for the deletion operation
1023  * origObject: base object of deletion, or NULL if not available
1024  * (the latter case occurs in DROP OWNED)
1025  */
1026 static void
1028  DropBehavior behavior,
1029  int flags,
1030  const ObjectAddress *origObject)
1031 {
1032  int msglevel = (flags & PERFORM_DELETION_QUIETLY) ? DEBUG2 : NOTICE;
1033  bool ok = true;
1034  StringInfoData clientdetail;
1035  StringInfoData logdetail;
1036  int numReportedClient = 0;
1037  int numNotReportedClient = 0;
1038  int i;
1039 
1040  /*
1041  * If we need to delete any partition-dependent objects, make sure that
1042  * we're deleting at least one of their partition dependencies, too. That
1043  * can be detected by checking that we reached them by a PARTITION
1044  * dependency at some point.
1045  *
1046  * We just report the first such object, as in most cases the only way to
1047  * trigger this complaint is to explicitly try to delete one partition of
1048  * a partitioned object.
1049  */
1050  for (i = 0; i < targetObjects->numrefs; i++)
1051  {
1052  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1053 
1054  if ((extra->flags & DEPFLAG_IS_PART) &&
1055  !(extra->flags & DEPFLAG_PARTITION))
1056  {
1057  const ObjectAddress *object = &targetObjects->refs[i];
1058  char *otherObjDesc = getObjectDescription(&extra->dependee);
1059 
1060  ereport(ERROR,
1061  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1062  errmsg("cannot drop %s because %s requires it",
1063  getObjectDescription(object), otherObjDesc),
1064  errhint("You can drop %s instead.", otherObjDesc)));
1065  }
1066  }
1067 
1068  /*
1069  * If no error is to be thrown, and the msglevel is too low to be shown to
1070  * either client or server log, there's no need to do any of the rest of
1071  * the work.
1072  *
1073  * Note: this code doesn't know all there is to be known about elog
1074  * levels, but it works for NOTICE and DEBUG2, which are the only values
1075  * msglevel can currently have. We also assume we are running in a normal
1076  * operating environment.
1077  */
1078  if (behavior == DROP_CASCADE &&
1079  msglevel < client_min_messages &&
1080  (msglevel < log_min_messages || log_min_messages == LOG))
1081  return;
1082 
1083  /*
1084  * We limit the number of dependencies reported to the client to
1085  * MAX_REPORTED_DEPS, since client software may not deal well with
1086  * enormous error strings. The server log always gets a full report.
1087  */
1088 #define MAX_REPORTED_DEPS 100
1089 
1090  initStringInfo(&clientdetail);
1091  initStringInfo(&logdetail);
1092 
1093  /*
1094  * We process the list back to front (ie, in dependency order not deletion
1095  * order), since this makes for a more understandable display.
1096  */
1097  for (i = targetObjects->numrefs - 1; i >= 0; i--)
1098  {
1099  const ObjectAddress *obj = &targetObjects->refs[i];
1100  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1101  char *objDesc;
1102 
1103  /* Ignore the original deletion target(s) */
1104  if (extra->flags & DEPFLAG_ORIGINAL)
1105  continue;
1106 
1107  /* Also ignore sub-objects; we'll report the whole object elsewhere */
1108  if (extra->flags & DEPFLAG_SUBOBJECT)
1109  continue;
1110 
1111  objDesc = getObjectDescription(obj);
1112 
1113  /*
1114  * If, at any stage of the recursive search, we reached the object via
1115  * an AUTO, INTERNAL, PARTITION, or EXTENSION dependency, then it's
1116  * okay to delete it even in RESTRICT mode.
1117  */
1118  if (extra->flags & (DEPFLAG_AUTO |
1122  {
1123  /*
1124  * auto-cascades are reported at DEBUG2, not msglevel. We don't
1125  * try to combine them with the regular message because the
1126  * results are too confusing when client_min_messages and
1127  * log_min_messages are different.
1128  */
1129  ereport(DEBUG2,
1130  (errmsg("drop auto-cascades to %s",
1131  objDesc)));
1132  }
1133  else if (behavior == DROP_RESTRICT)
1134  {
1135  char *otherDesc = getObjectDescription(&extra->dependee);
1136 
1137  if (numReportedClient < MAX_REPORTED_DEPS)
1138  {
1139  /* separate entries with a newline */
1140  if (clientdetail.len != 0)
1141  appendStringInfoChar(&clientdetail, '\n');
1142  appendStringInfo(&clientdetail, _("%s depends on %s"),
1143  objDesc, otherDesc);
1144  numReportedClient++;
1145  }
1146  else
1147  numNotReportedClient++;
1148  /* separate entries with a newline */
1149  if (logdetail.len != 0)
1150  appendStringInfoChar(&logdetail, '\n');
1151  appendStringInfo(&logdetail, _("%s depends on %s"),
1152  objDesc, otherDesc);
1153  pfree(otherDesc);
1154  ok = false;
1155  }
1156  else
1157  {
1158  if (numReportedClient < MAX_REPORTED_DEPS)
1159  {
1160  /* separate entries with a newline */
1161  if (clientdetail.len != 0)
1162  appendStringInfoChar(&clientdetail, '\n');
1163  appendStringInfo(&clientdetail, _("drop cascades to %s"),
1164  objDesc);
1165  numReportedClient++;
1166  }
1167  else
1168  numNotReportedClient++;
1169  /* separate entries with a newline */
1170  if (logdetail.len != 0)
1171  appendStringInfoChar(&logdetail, '\n');
1172  appendStringInfo(&logdetail, _("drop cascades to %s"),
1173  objDesc);
1174  }
1175 
1176  pfree(objDesc);
1177  }
1178 
1179  if (numNotReportedClient > 0)
1180  appendStringInfo(&clientdetail, ngettext("\nand %d other object "
1181  "(see server log for list)",
1182  "\nand %d other objects "
1183  "(see server log for list)",
1184  numNotReportedClient),
1185  numNotReportedClient);
1186 
1187  if (!ok)
1188  {
1189  if (origObject)
1190  ereport(ERROR,
1191  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1192  errmsg("cannot drop %s because other objects depend on it",
1193  getObjectDescription(origObject)),
1194  errdetail("%s", clientdetail.data),
1195  errdetail_log("%s", logdetail.data),
1196  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1197  else
1198  ereport(ERROR,
1199  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1200  errmsg("cannot drop desired object(s) because other objects depend on them"),
1201  errdetail("%s", clientdetail.data),
1202  errdetail_log("%s", logdetail.data),
1203  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1204  }
1205  else if (numReportedClient > 1)
1206  {
1207  ereport(msglevel,
1208  /* translator: %d always has a value larger than 1 */
1209  (errmsg_plural("drop cascades to %d other object",
1210  "drop cascades to %d other objects",
1211  numReportedClient + numNotReportedClient,
1212  numReportedClient + numNotReportedClient),
1213  errdetail("%s", clientdetail.data),
1214  errdetail_log("%s", logdetail.data)));
1215  }
1216  else if (numReportedClient == 1)
1217  {
1218  /* we just use the single item as-is */
1219  ereport(msglevel,
1220  (errmsg_internal("%s", clientdetail.data)));
1221  }
1222 
1223  pfree(clientdetail.data);
1224  pfree(logdetail.data);
1225 }
1226 
1227 /*
1228  * deleteOneObject: delete a single object for performDeletion.
1229  *
1230  * *depRel is the already-open pg_depend relation.
1231  */
1232 static void
1233 deleteOneObject(const ObjectAddress *object, Relation *depRel, int flags)
1234 {
1235  ScanKeyData key[3];
1236  int nkeys;
1237  SysScanDesc scan;
1238  HeapTuple tup;
1239 
1240  /* DROP hook of the objects being removed */
1241  InvokeObjectDropHookArg(object->classId, object->objectId,
1242  object->objectSubId, flags);
1243 
1244  /*
1245  * Close depRel if we are doing a drop concurrently. The object deletion
1246  * subroutine will commit the current transaction, so we can't keep the
1247  * relation open across doDeletion().
1248  */
1249  if (flags & PERFORM_DELETION_CONCURRENTLY)
1250  table_close(*depRel, RowExclusiveLock);
1251 
1252  /*
1253  * Delete the object itself, in an object-type-dependent way.
1254  *
1255  * We used to do this after removing the outgoing dependency links, but it
1256  * seems just as reasonable to do it beforehand. In the concurrent case
1257  * we *must* do it in this order, because we can't make any transactional
1258  * updates before calling doDeletion() --- they'd get committed right
1259  * away, which is not cool if the deletion then fails.
1260  */
1261  doDeletion(object, flags);
1262 
1263  /*
1264  * Reopen depRel if we closed it above
1265  */
1266  if (flags & PERFORM_DELETION_CONCURRENTLY)
1267  *depRel = table_open(DependRelationId, RowExclusiveLock);
1268 
1269  /*
1270  * Now remove any pg_depend records that link from this object to others.
1271  * (Any records linking to this object should be gone already.)
1272  *
1273  * When dropping a whole object (subId = 0), remove all pg_depend records
1274  * for its sub-objects too.
1275  */
1276  ScanKeyInit(&key[0],
1277  Anum_pg_depend_classid,
1278  BTEqualStrategyNumber, F_OIDEQ,
1279  ObjectIdGetDatum(object->classId));
1280  ScanKeyInit(&key[1],
1281  Anum_pg_depend_objid,
1282  BTEqualStrategyNumber, F_OIDEQ,
1283  ObjectIdGetDatum(object->objectId));
1284  if (object->objectSubId != 0)
1285  {
1286  ScanKeyInit(&key[2],
1287  Anum_pg_depend_objsubid,
1288  BTEqualStrategyNumber, F_INT4EQ,
1289  Int32GetDatum(object->objectSubId));
1290  nkeys = 3;
1291  }
1292  else
1293  nkeys = 2;
1294 
1295  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1296  NULL, nkeys, key);
1297 
1298  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1299  {
1300  CatalogTupleDelete(*depRel, &tup->t_self);
1301  }
1302 
1303  systable_endscan(scan);
1304 
1305  /*
1306  * Delete shared dependency references related to this object. Again, if
1307  * subId = 0, remove records for sub-objects too.
1308  */
1310  object->objectSubId);
1311 
1312 
1313  /*
1314  * Delete any comments, security labels, or initial privileges associated
1315  * with this object. (This is a convenient place to do these things,
1316  * rather than having every object type know to do it.)
1317  */
1318  DeleteComments(object->objectId, object->classId, object->objectSubId);
1319  DeleteSecurityLabel(object);
1320  DeleteInitPrivs(object);
1321 
1322  /*
1323  * CommandCounterIncrement here to ensure that preceding changes are all
1324  * visible to the next deletion step.
1325  */
1327 
1328  /*
1329  * And we're done!
1330  */
1331 }
1332 
1333 /*
1334  * doDeletion: actually delete a single object
1335  */
1336 static void
1337 doDeletion(const ObjectAddress *object, int flags)
1338 {
1339  switch (getObjectClass(object))
1340  {
1341  case OCLASS_CLASS:
1342  {
1343  char relKind = get_rel_relkind(object->objectId);
1344 
1345  if (relKind == RELKIND_INDEX ||
1346  relKind == RELKIND_PARTITIONED_INDEX)
1347  {
1348  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1349  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1350 
1351  Assert(object->objectSubId == 0);
1352  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1353  }
1354  else
1355  {
1356  if (object->objectSubId != 0)
1357  RemoveAttributeById(object->objectId,
1358  object->objectSubId);
1359  else
1361  }
1362 
1363  /*
1364  * for a sequence, in addition to dropping the heap, also
1365  * delete pg_sequence tuple
1366  */
1367  if (relKind == RELKIND_SEQUENCE)
1368  DeleteSequenceTuple(object->objectId);
1369  break;
1370  }
1371 
1372  case OCLASS_PROC:
1373  RemoveFunctionById(object->objectId);
1374  break;
1375 
1376  case OCLASS_TYPE:
1377  RemoveTypeById(object->objectId);
1378  break;
1379 
1380  case OCLASS_CAST:
1381  DropCastById(object->objectId);
1382  break;
1383 
1384  case OCLASS_COLLATION:
1385  RemoveCollationById(object->objectId);
1386  break;
1387 
1388  case OCLASS_CONSTRAINT:
1389  RemoveConstraintById(object->objectId);
1390  break;
1391 
1392  case OCLASS_CONVERSION:
1393  RemoveConversionById(object->objectId);
1394  break;
1395 
1396  case OCLASS_DEFAULT:
1398  break;
1399 
1400  case OCLASS_LANGUAGE:
1402  break;
1403 
1404  case OCLASS_LARGEOBJECT:
1405  LargeObjectDrop(object->objectId);
1406  break;
1407 
1408  case OCLASS_OPERATOR:
1409  RemoveOperatorById(object->objectId);
1410  break;
1411 
1412  case OCLASS_OPCLASS:
1413  RemoveOpClassById(object->objectId);
1414  break;
1415 
1416  case OCLASS_OPFAMILY:
1417  RemoveOpFamilyById(object->objectId);
1418  break;
1419 
1420  case OCLASS_AM:
1422  break;
1423 
1424  case OCLASS_AMOP:
1425  RemoveAmOpEntryById(object->objectId);
1426  break;
1427 
1428  case OCLASS_AMPROC:
1430  break;
1431 
1432  case OCLASS_REWRITE:
1434  break;
1435 
1436  case OCLASS_TRIGGER:
1437  RemoveTriggerById(object->objectId);
1438  break;
1439 
1440  case OCLASS_SCHEMA:
1441  RemoveSchemaById(object->objectId);
1442  break;
1443 
1444  case OCLASS_STATISTIC_EXT:
1445  RemoveStatisticsById(object->objectId);
1446  break;
1447 
1448  case OCLASS_TSPARSER:
1449  RemoveTSParserById(object->objectId);
1450  break;
1451 
1452  case OCLASS_TSDICT:
1454  break;
1455 
1456  case OCLASS_TSTEMPLATE:
1457  RemoveTSTemplateById(object->objectId);
1458  break;
1459 
1460  case OCLASS_TSCONFIG:
1462  break;
1463 
1464  /*
1465  * OCLASS_ROLE, OCLASS_DATABASE, OCLASS_TBLSPACE intentionally not
1466  * handled here
1467  */
1468 
1469  case OCLASS_FDW:
1471  break;
1472 
1473  case OCLASS_FOREIGN_SERVER:
1475  break;
1476 
1477  case OCLASS_USER_MAPPING:
1479  break;
1480 
1481  case OCLASS_DEFACL:
1482  RemoveDefaultACLById(object->objectId);
1483  break;
1484 
1485  case OCLASS_EXTENSION:
1486  RemoveExtensionById(object->objectId);
1487  break;
1488 
1489  case OCLASS_EVENT_TRIGGER:
1491  break;
1492 
1493  case OCLASS_POLICY:
1494  RemovePolicyById(object->objectId);
1495  break;
1496 
1497  case OCLASS_PUBLICATION:
1499  break;
1500 
1503  break;
1504 
1505  case OCLASS_TRANSFORM:
1506  DropTransformById(object->objectId);
1507  break;
1508 
1509  /*
1510  * These global object types are not supported here.
1511  */
1512  case OCLASS_ROLE:
1513  case OCLASS_DATABASE:
1514  case OCLASS_TBLSPACE:
1515  case OCLASS_SUBSCRIPTION:
1516  elog(ERROR, "global objects cannot be deleted by doDeletion");
1517  break;
1518 
1519  /*
1520  * There's intentionally no default: case here; we want the
1521  * compiler to warn if a new OCLASS hasn't been handled above.
1522  */
1523  }
1524 }
1525 
1526 /*
1527  * AcquireDeletionLock - acquire a suitable lock for deleting an object
1528  *
1529  * We use LockRelation for relations, LockDatabaseObject for everything
1530  * else. Note that dependency.c is not concerned with deleting any kind of
1531  * shared-across-databases object, so we have no need for LockSharedObject.
1532  */
1533 static void
1535 {
1536  if (object->classId == RelationRelationId)
1537  {
1538  /*
1539  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1540  * the index for the moment. index_drop() will promote the lock once
1541  * it's safe to do so. In all other cases we need full exclusive
1542  * lock.
1543  */
1544  if (flags & PERFORM_DELETION_CONCURRENTLY)
1546  else
1548  }
1549  else
1550  {
1551  /* assume we should lock the whole object not a sub-object */
1552  LockDatabaseObject(object->classId, object->objectId, 0,
1554  }
1555 }
1556 
1557 /*
1558  * ReleaseDeletionLock - release an object deletion lock
1559  */
1560 static void
1562 {
1563  if (object->classId == RelationRelationId)
1565  else
1566  /* assume we should lock the whole object not a sub-object */
1567  UnlockDatabaseObject(object->classId, object->objectId, 0,
1569 }
1570 
1571 /*
1572  * recordDependencyOnExpr - find expression dependencies
1573  *
1574  * This is used to find the dependencies of rules, constraint expressions,
1575  * etc.
1576  *
1577  * Given an expression or query in node-tree form, find all the objects
1578  * it refers to (tables, columns, operators, functions, etc). Record
1579  * a dependency of the specified type from the given depender object
1580  * to each object mentioned in the expression.
1581  *
1582  * rtable is the rangetable to be used to interpret Vars with varlevelsup=0.
1583  * It can be NIL if no such variables are expected.
1584  */
1585 void
1587  Node *expr, List *rtable,
1588  DependencyType behavior)
1589 {
1591 
1592  context.addrs = new_object_addresses();
1593 
1594  /* Set up interpretation for Vars at varlevelsup = 0 */
1595  context.rtables = list_make1(rtable);
1596 
1597  /* Scan the expression tree for referenceable objects */
1598  find_expr_references_walker(expr, &context);
1599 
1600  /* Remove any duplicates */
1602 
1603  /* And record 'em */
1604  recordMultipleDependencies(depender,
1605  context.addrs->refs, context.addrs->numrefs,
1606  behavior);
1607 
1608  free_object_addresses(context.addrs);
1609 }
1610 
1611 /*
1612  * recordDependencyOnSingleRelExpr - find expression dependencies
1613  *
1614  * As above, but only one relation is expected to be referenced (with
1615  * varno = 1 and varlevelsup = 0). Pass the relation OID instead of a
1616  * range table. An additional frammish is that dependencies on that
1617  * relation's component columns will be marked with 'self_behavior',
1618  * whereas 'behavior' is used for everything else; also, if 'reverse_self'
1619  * is true, those dependencies are reversed so that the columns are made
1620  * to depend on the table not vice versa.
1621  *
1622  * NOTE: the caller should ensure that a whole-table dependency on the
1623  * specified relation is created separately, if one is needed. In particular,
1624  * a whole-row Var "relation.*" will not cause this routine to emit any
1625  * dependency item. This is appropriate behavior for subexpressions of an
1626  * ordinary query, so other cases need to cope as necessary.
1627  */
1628 void
1630  Node *expr, Oid relId,
1631  DependencyType behavior,
1632  DependencyType self_behavior,
1633  bool reverse_self)
1634 {
1636  RangeTblEntry rte;
1637 
1638  context.addrs = new_object_addresses();
1639 
1640  /* We gin up a rather bogus rangetable list to handle Vars */
1641  MemSet(&rte, 0, sizeof(rte));
1642  rte.type = T_RangeTblEntry;
1643  rte.rtekind = RTE_RELATION;
1644  rte.relid = relId;
1645  rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1647 
1648  context.rtables = list_make1(list_make1(&rte));
1649 
1650  /* Scan the expression tree for referenceable objects */
1651  find_expr_references_walker(expr, &context);
1652 
1653  /* Remove any duplicates */
1655 
1656  /* Separate self-dependencies if necessary */
1657  if ((behavior != self_behavior || reverse_self) &&
1658  context.addrs->numrefs > 0)
1659  {
1660  ObjectAddresses *self_addrs;
1661  ObjectAddress *outobj;
1662  int oldref,
1663  outrefs;
1664 
1665  self_addrs = new_object_addresses();
1666 
1667  outobj = context.addrs->refs;
1668  outrefs = 0;
1669  for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1670  {
1671  ObjectAddress *thisobj = context.addrs->refs + oldref;
1672 
1673  if (thisobj->classId == RelationRelationId &&
1674  thisobj->objectId == relId)
1675  {
1676  /* Move this ref into self_addrs */
1677  add_exact_object_address(thisobj, self_addrs);
1678  }
1679  else
1680  {
1681  /* Keep it in context.addrs */
1682  *outobj = *thisobj;
1683  outobj++;
1684  outrefs++;
1685  }
1686  }
1687  context.addrs->numrefs = outrefs;
1688 
1689  /* Record the self-dependencies with the appropriate direction */
1690  if (!reverse_self)
1691  recordMultipleDependencies(depender,
1692  self_addrs->refs, self_addrs->numrefs,
1693  self_behavior);
1694  else
1695  {
1696  /* Can't use recordMultipleDependencies, so do it the hard way */
1697  int selfref;
1698 
1699  for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1700  {
1701  ObjectAddress *thisobj = self_addrs->refs + selfref;
1702 
1703  recordDependencyOn(thisobj, depender, self_behavior);
1704  }
1705  }
1706 
1707  free_object_addresses(self_addrs);
1708  }
1709 
1710  /* Record the external dependencies */
1711  recordMultipleDependencies(depender,
1712  context.addrs->refs, context.addrs->numrefs,
1713  behavior);
1714 
1715  free_object_addresses(context.addrs);
1716 }
1717 
1718 /*
1719  * Recursively search an expression tree for object references.
1720  *
1721  * Note: in many cases we do not need to create dependencies on the datatypes
1722  * involved in an expression, because we'll have an indirect dependency via
1723  * some other object. For instance Var nodes depend on a column which depends
1724  * on the datatype, and OpExpr nodes depend on the operator which depends on
1725  * the datatype. However we do need a type dependency if there is no such
1726  * indirect dependency, as for example in Const and CoerceToDomain nodes.
1727  *
1728  * Similarly, we don't need to create dependencies on collations except where
1729  * the collation is being freshly introduced to the expression.
1730  */
1731 static bool
1734 {
1735  if (node == NULL)
1736  return false;
1737  if (IsA(node, Var))
1738  {
1739  Var *var = (Var *) node;
1740  List *rtable;
1741  RangeTblEntry *rte;
1742 
1743  /* Find matching rtable entry, or complain if not found */
1744  if (var->varlevelsup >= list_length(context->rtables))
1745  elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1746  rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1747  if (var->varno <= 0 || var->varno > list_length(rtable))
1748  elog(ERROR, "invalid varno %d", var->varno);
1749  rte = rt_fetch(var->varno, rtable);
1750 
1751  /*
1752  * A whole-row Var references no specific columns, so adds no new
1753  * dependency. (We assume that there is a whole-table dependency
1754  * arising from each underlying rangetable entry. While we could
1755  * record such a dependency when finding a whole-row Var that
1756  * references a relation directly, it's quite unclear how to extend
1757  * that to whole-row Vars for JOINs, so it seems better to leave the
1758  * responsibility with the range table. Note that this poses some
1759  * risks for identifying dependencies of stand-alone expressions:
1760  * whole-table references may need to be created separately.)
1761  */
1762  if (var->varattno == InvalidAttrNumber)
1763  return false;
1764  if (rte->rtekind == RTE_RELATION)
1765  {
1766  /* If it's a plain relation, reference this column */
1768  context->addrs);
1769  }
1770 
1771  /*
1772  * Vars referencing other RTE types require no additional work. In
1773  * particular, a join alias Var can be ignored, because it must
1774  * reference a merged USING column. The relevant join input columns
1775  * will also be referenced in the join qual, and any type coercion
1776  * functions involved in the alias expression will be dealt with when
1777  * we scan the RTE itself.
1778  */
1779  return false;
1780  }
1781  else if (IsA(node, Const))
1782  {
1783  Const *con = (Const *) node;
1784  Oid objoid;
1785 
1786  /* A constant must depend on the constant's datatype */
1788  context->addrs);
1789 
1790  /*
1791  * We must also depend on the constant's collation: it could be
1792  * different from the datatype's, if a CollateExpr was const-folded to
1793  * a simple constant. However we can save work in the most common
1794  * case where the collation is "default", since we know that's pinned.
1795  */
1796  if (OidIsValid(con->constcollid) &&
1797  con->constcollid != DEFAULT_COLLATION_OID)
1799  context->addrs);
1800 
1801  /*
1802  * If it's a regclass or similar literal referring to an existing
1803  * object, add a reference to that object. (Currently, only the
1804  * regclass and regconfig cases have any likely use, but we may as
1805  * well handle all the OID-alias datatypes consistently.)
1806  */
1807  if (!con->constisnull)
1808  {
1809  switch (con->consttype)
1810  {
1811  case REGPROCOID:
1812  case REGPROCEDUREOID:
1813  objoid = DatumGetObjectId(con->constvalue);
1815  ObjectIdGetDatum(objoid)))
1816  add_object_address(OCLASS_PROC, objoid, 0,
1817  context->addrs);
1818  break;
1819  case REGOPEROID:
1820  case REGOPERATOROID:
1821  objoid = DatumGetObjectId(con->constvalue);
1823  ObjectIdGetDatum(objoid)))
1825  context->addrs);
1826  break;
1827  case REGCLASSOID:
1828  objoid = DatumGetObjectId(con->constvalue);
1830  ObjectIdGetDatum(objoid)))
1831  add_object_address(OCLASS_CLASS, objoid, 0,
1832  context->addrs);
1833  break;
1834  case REGTYPEOID:
1835  objoid = DatumGetObjectId(con->constvalue);
1837  ObjectIdGetDatum(objoid)))
1838  add_object_address(OCLASS_TYPE, objoid, 0,
1839  context->addrs);
1840  break;
1841  case REGCONFIGOID:
1842  objoid = DatumGetObjectId(con->constvalue);
1844  ObjectIdGetDatum(objoid)))
1846  context->addrs);
1847  break;
1848  case REGDICTIONARYOID:
1849  objoid = DatumGetObjectId(con->constvalue);
1851  ObjectIdGetDatum(objoid)))
1852  add_object_address(OCLASS_TSDICT, objoid, 0,
1853  context->addrs);
1854  break;
1855 
1856  case REGNAMESPACEOID:
1857  objoid = DatumGetObjectId(con->constvalue);
1859  ObjectIdGetDatum(objoid)))
1860  add_object_address(OCLASS_SCHEMA, objoid, 0,
1861  context->addrs);
1862  break;
1863 
1864  /*
1865  * Dependencies for regrole should be shared among all
1866  * databases, so explicitly inhibit to have dependencies.
1867  */
1868  case REGROLEOID:
1869  ereport(ERROR,
1870  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1871  errmsg("constant of the type %s cannot be used here",
1872  "regrole")));
1873  break;
1874  }
1875  }
1876  return false;
1877  }
1878  else if (IsA(node, Param))
1879  {
1880  Param *param = (Param *) node;
1881 
1882  /* A parameter must depend on the parameter's datatype */
1884  context->addrs);
1885  /* and its collation, just as for Consts */
1886  if (OidIsValid(param->paramcollid) &&
1887  param->paramcollid != DEFAULT_COLLATION_OID)
1889  context->addrs);
1890  }
1891  else if (IsA(node, FuncExpr))
1892  {
1893  FuncExpr *funcexpr = (FuncExpr *) node;
1894 
1895  add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
1896  context->addrs);
1897  /* fall through to examine arguments */
1898  }
1899  else if (IsA(node, OpExpr))
1900  {
1901  OpExpr *opexpr = (OpExpr *) node;
1902 
1904  context->addrs);
1905  /* fall through to examine arguments */
1906  }
1907  else if (IsA(node, DistinctExpr))
1908  {
1909  DistinctExpr *distinctexpr = (DistinctExpr *) node;
1910 
1911  add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
1912  context->addrs);
1913  /* fall through to examine arguments */
1914  }
1915  else if (IsA(node, NullIfExpr))
1916  {
1917  NullIfExpr *nullifexpr = (NullIfExpr *) node;
1918 
1919  add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
1920  context->addrs);
1921  /* fall through to examine arguments */
1922  }
1923  else if (IsA(node, ScalarArrayOpExpr))
1924  {
1925  ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1926 
1928  context->addrs);
1929  /* fall through to examine arguments */
1930  }
1931  else if (IsA(node, Aggref))
1932  {
1933  Aggref *aggref = (Aggref *) node;
1934 
1936  context->addrs);
1937  /* fall through to examine arguments */
1938  }
1939  else if (IsA(node, WindowFunc))
1940  {
1941  WindowFunc *wfunc = (WindowFunc *) node;
1942 
1944  context->addrs);
1945  /* fall through to examine arguments */
1946  }
1947  else if (IsA(node, SubPlan))
1948  {
1949  /* Extra work needed here if we ever need this case */
1950  elog(ERROR, "already-planned subqueries not supported");
1951  }
1952  else if (IsA(node, FieldSelect))
1953  {
1954  FieldSelect *fselect = (FieldSelect *) node;
1955  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1956  Oid reltype = get_typ_typrelid(argtype);
1957 
1958  /*
1959  * We need a dependency on the specific column named in FieldSelect,
1960  * assuming we can identify the pg_class OID for it. (Probably we
1961  * always can at the moment, but in future it might be possible for
1962  * argtype to be RECORDOID.) If we can make a column dependency then
1963  * we shouldn't need a dependency on the column's type; but if we
1964  * can't, make a dependency on the type, as it might not appear
1965  * anywhere else in the expression.
1966  */
1967  if (OidIsValid(reltype))
1968  add_object_address(OCLASS_CLASS, reltype, fselect->fieldnum,
1969  context->addrs);
1970  else
1972  context->addrs);
1973  /* the collation might not be referenced anywhere else, either */
1974  if (OidIsValid(fselect->resultcollid) &&
1975  fselect->resultcollid != DEFAULT_COLLATION_OID)
1977  context->addrs);
1978  }
1979  else if (IsA(node, FieldStore))
1980  {
1981  FieldStore *fstore = (FieldStore *) node;
1982  Oid reltype = get_typ_typrelid(fstore->resulttype);
1983 
1984  /* similar considerations to FieldSelect, but multiple column(s) */
1985  if (OidIsValid(reltype))
1986  {
1987  ListCell *l;
1988 
1989  foreach(l, fstore->fieldnums)
1991  context->addrs);
1992  }
1993  else
1995  context->addrs);
1996  }
1997  else if (IsA(node, RelabelType))
1998  {
1999  RelabelType *relab = (RelabelType *) node;
2000 
2001  /* since there is no function dependency, need to depend on type */
2003  context->addrs);
2004  /* the collation might not be referenced anywhere else, either */
2005  if (OidIsValid(relab->resultcollid) &&
2006  relab->resultcollid != DEFAULT_COLLATION_OID)
2008  context->addrs);
2009  }
2010  else if (IsA(node, CoerceViaIO))
2011  {
2012  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2013 
2014  /* since there is no exposed function, need to depend on type */
2016  context->addrs);
2017  /* the collation might not be referenced anywhere else, either */
2018  if (OidIsValid(iocoerce->resultcollid) &&
2019  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2021  context->addrs);
2022  }
2023  else if (IsA(node, ArrayCoerceExpr))
2024  {
2025  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2026 
2027  /* as above, depend on type */
2029  context->addrs);
2030  /* the collation might not be referenced anywhere else, either */
2031  if (OidIsValid(acoerce->resultcollid) &&
2032  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2034  context->addrs);
2035  /* fall through to examine arguments */
2036  }
2037  else if (IsA(node, ConvertRowtypeExpr))
2038  {
2039  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2040 
2041  /* since there is no function dependency, need to depend on type */
2043  context->addrs);
2044  }
2045  else if (IsA(node, CollateExpr))
2046  {
2047  CollateExpr *coll = (CollateExpr *) node;
2048 
2050  context->addrs);
2051  }
2052  else if (IsA(node, RowExpr))
2053  {
2054  RowExpr *rowexpr = (RowExpr *) node;
2055 
2057  context->addrs);
2058  }
2059  else if (IsA(node, RowCompareExpr))
2060  {
2061  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2062  ListCell *l;
2063 
2064  foreach(l, rcexpr->opnos)
2065  {
2067  context->addrs);
2068  }
2069  foreach(l, rcexpr->opfamilies)
2070  {
2072  context->addrs);
2073  }
2074  /* fall through to examine arguments */
2075  }
2076  else if (IsA(node, CoerceToDomain))
2077  {
2078  CoerceToDomain *cd = (CoerceToDomain *) node;
2079 
2081  context->addrs);
2082  }
2083  else if (IsA(node, NextValueExpr))
2084  {
2085  NextValueExpr *nve = (NextValueExpr *) node;
2086 
2088  context->addrs);
2089  }
2090  else if (IsA(node, OnConflictExpr))
2091  {
2092  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2093 
2094  if (OidIsValid(onconflict->constraint))
2096  context->addrs);
2097  /* fall through to examine arguments */
2098  }
2099  else if (IsA(node, SortGroupClause))
2100  {
2101  SortGroupClause *sgc = (SortGroupClause *) node;
2102 
2104  context->addrs);
2105  if (OidIsValid(sgc->sortop))
2107  context->addrs);
2108  return false;
2109  }
2110  else if (IsA(node, WindowClause))
2111  {
2112  WindowClause *wc = (WindowClause *) node;
2113 
2114  if (OidIsValid(wc->startInRangeFunc))
2116  context->addrs);
2117  if (OidIsValid(wc->endInRangeFunc))
2119  context->addrs);
2120  if (OidIsValid(wc->inRangeColl) &&
2121  wc->inRangeColl != DEFAULT_COLLATION_OID)
2123  context->addrs);
2124  /* fall through to examine substructure */
2125  }
2126  else if (IsA(node, Query))
2127  {
2128  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2129  Query *query = (Query *) node;
2130  ListCell *lc;
2131  bool result;
2132 
2133  /*
2134  * Add whole-relation refs for each plain relation mentioned in the
2135  * subquery's rtable, and ensure we add refs for any type-coercion
2136  * functions used in join alias lists.
2137  *
2138  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2139  * RTEs, subqueries, etc, so no need to do that here. But we must
2140  * tell it not to visit join alias lists, or we'll add refs for join
2141  * input columns whether or not they are actually used in our query.
2142  *
2143  * Note: we don't need to worry about collations mentioned in
2144  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2145  * collations referenced in other parts of the Query. We do have to
2146  * worry about collations mentioned in RTE_FUNCTION, but we take care
2147  * of those when we recurse to the RangeTblFunction node(s).
2148  */
2149  foreach(lc, query->rtable)
2150  {
2151  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2152 
2153  switch (rte->rtekind)
2154  {
2155  case RTE_RELATION:
2157  context->addrs);
2158  break;
2159  case RTE_JOIN:
2160 
2161  /*
2162  * Examine joinaliasvars entries only for merged JOIN
2163  * USING columns. Only those entries could contain
2164  * type-coercion functions. Also, their join input
2165  * columns must be referenced in the join quals, so this
2166  * won't accidentally add refs to otherwise-unused join
2167  * input columns. (We want to ref the type coercion
2168  * functions even if the merged column isn't explicitly
2169  * used anywhere, to protect possible expansion of the
2170  * join RTE as a whole-row var, and because it seems like
2171  * a bad idea to allow dropping a function that's present
2172  * in our query tree, whether or not it could get called.)
2173  */
2174  context->rtables = lcons(query->rtable, context->rtables);
2175  for (int i = 0; i < rte->joinmergedcols; i++)
2176  {
2177  Node *aliasvar = list_nth(rte->joinaliasvars, i);
2178 
2179  if (!IsA(aliasvar, Var))
2180  find_expr_references_walker(aliasvar, context);
2181  }
2182  context->rtables = list_delete_first(context->rtables);
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 */
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  {
2226  context->addrs);
2227  }
2228 
2229  /* Examine substructure of query */
2230  context->rtables = lcons(query->rtable, context->rtables);
2231  result = query_tree_walker(query,
2233  (void *) context,
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  {
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)
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  {
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)
2290  context->addrs);
2291  }
2292  }
2293  else if (IsA(node, TableSampleClause))
2294  {
2295  TableSampleClause *tsc = (TableSampleClause *) node;
2296 
2298  context->addrs);
2299  /* fall through to examine arguments */
2300  }
2301 
2303  (void *) context);
2304 }
2305 
2306 /*
2307  * Given an array of dependency references, eliminate any duplicates.
2308  */
2309 static void
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),
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
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  */
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
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  */
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
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
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
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
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
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
2679  ObjectAddresses *referenced,
2680  DependencyType behavior)
2681 {
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
2698 {
2699  if (addrs->numrefs > 1)
2700  qsort((void *) addrs->refs, addrs->numrefs,
2701  sizeof(ObjectAddress),
2703 }
2704 
2705 /*
2706  * Clean up when done with an ObjectAddresses array.
2707  */
2708 void
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  */
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
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 }
Datum constvalue
Definition: primnodes.h:214
static void findDependentObjects(const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
Definition: dependency.c:474
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1491
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:106
Oid CurrentExtensionObject
Definition: extension.c:71
static void ReleaseDeletionLock(const ObjectAddress *object)
Definition: dependency.c:1561
DependencyType
Definition: dependency.h:31
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2370
#define DEPFLAG_PARTITION
Definition: dependency.c:102
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
List * joinaliasvars
Definition: parsenodes.h:1049
Index varlevelsup
Definition: primnodes.h:191
int errhint(const char *fmt,...)
Definition: elog.c:1069
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2006
static void add_exact_object_address_extra(const ObjectAddress *object, const ObjectAddressExtra *extra, ObjectAddresses *addrs)
Definition: dependency.c:2494
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1732
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:529
static void deleteOneObject(const ObjectAddress *object, Relation *depRel, int32 flags)
void RemoveOpClassById(Oid opclassOid)
Definition: opclasscmds.c:1622
Oid resulttype
Definition: primnodes.h:764
void DropTransformById(Oid transformOid)
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
bool trackDroppedObjectsNeeded(void)
void sort_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2697
void RemoveExtensionById(Oid extId)
Definition: extension.c:1851
ObjectAddresses * addrs
Definition: dependency.c:138
List * constraintDeps
Definition: parsenodes.h:168
void DropProceduralLanguageById(Oid langOid)
Definition: proclang.c:534
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
void RemoveForeignDataWrapperById(Oid fdwId)
Definition: foreigncmds.c:842
#define DatumGetObjectId(X)
Definition: postgres.h:500
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2678
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2529
#define DependReferenceIndexId
Definition: indexing.h:151
Oid resulttype
Definition: primnodes.h:835
#define QTW_EXAMINE_SORTGROUP
Definition: nodeFuncs.h:30
List * opfamilies
Definition: primnodes.h:1072
#define DependDependerIndexId
Definition: indexing.h:149
#define PERFORM_DELETION_SKIP_ORIGINAL
Definition: dependency.h:137
int resultRelation
Definition: parsenodes.h:122
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:446
#define LAST_OCLASS
Definition: dependency.h:131
Oid endInRangeFunc
Definition: parsenodes.h:1357
#define AccessShareLock
Definition: lockdefs.h:36
void RemoveSchemaById(Oid schemaOid)
Definition: schemacmds.c:217
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
#define MemSet(start, val, len)
Definition: c.h:962
AttrNumber varattno
Definition: primnodes.h:186
Expr * arg
Definition: primnodes.h:762
void RemovePublicationById(Oid pubid)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
void RemovePublicationRelById(Oid proid)
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2469
#define lengthof(array)
Definition: c.h:669
#define DEPFLAG_REVERSE
Definition: dependency.c:104
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2414
void RemoveAmProcEntryById(Oid entryOid)
Definition: opclasscmds.c:1670
#define LOG
Definition: elog.h:26
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2709
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
#define InitPrivsObjIndexId
Definition: indexing.h:176
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:690
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2724
#define OidIsValid(objectId)
Definition: c.h:645
void RemoveCollationById(Oid collationOid)
Definition: pg_collation.c:214
void RemoveUserMappingById(Oid umId)
Definition: foreigncmds.c:1439
struct ObjectAddressStack * next
Definition: dependency.c:125
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2310
void RemoveConversionById(Oid conversionOid)
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
void RemoveAccessMethodById(Oid amOid)
Definition: amcmds.c:119
char * getObjectDescription(const ObjectAddress *object)
List * colcollations
Definition: primnodes.h:92
signed int int32
Definition: c.h:347
List * targetList
Definition: parsenodes.h:140
bool systable_recheck_tuple(SysScanDesc sysscan, HeapTuple tup)
Definition: genam.c:497
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:339
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
#define list_make1(x1)
Definition: pg_list.h:227
ObjectAddress obj
Definition: dependency.c:131
Oid consttype
Definition: primnodes.h:210
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:849
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2499
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1414
void RemoveDefaultACLById(Oid defaclOid)
Definition: aclchk.c:1530
List * rtable
Definition: parsenodes.h:137
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define DEPFLAG_ORIGINAL
Definition: dependency.c:98
#define DEPFLAG_IS_PART
Definition: dependency.c:105
static const Oid object_classes[]
Definition: dependency.c:146
Oid paramcollid
Definition: primnodes.h:266
#define DEPFLAG_AUTO
Definition: dependency.c:100
#define lfirst_int(lc)
Definition: pg_list.h:191
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1131
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
ItemPointerData t_self
Definition: htup.h:65
const ObjectAddress * object
Definition: dependency.c:123
#define DEPFLAG_INTERNAL
Definition: dependency.c:101
Oid constcollid
Definition: primnodes.h:212
Oid resultcollid
Definition: primnodes.h:767
#define DEBUG2
Definition: elog.h:24
void RemoveOpFamilyById(Oid opfamilyOid)
Definition: opclasscmds.c:1603
void RemovePolicyById(Oid policy_id)
Definition: policy.c:354
static bool object_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddresses *addrs)
Definition: dependency.c:2555
struct ObjectAddressStack ObjectAddressStack
ObjectAddress * refs
Definition: dependency.c:112
ObjectClass
Definition: dependency.h:89
#define RowExclusiveLock
Definition: lockdefs.h:38
void RemoveTSParserById(Oid prsId)
Definition: tsearchcmds.c:295
int errdetail(const char *fmt,...)
Definition: elog.c:955
AttrNumber resno
Definition: primnodes.h:1408
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1586
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:961
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1610
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:315
void RemoveTSTemplateById(Oid tmplId)
Definition: tsearchcmds.c:824
static void reportDependentObjects(const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
Definition: dependency.c:1027
int errdetail_log(const char *fmt,...)
Definition: elog.c:1003
Oid resulttype
Definition: primnodes.h:794
Oid winfnoid
Definition: primnodes.h:373
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:526
void RemoveEventTriggerById(Oid trigOid)
void RemoveAttrDefaultById(Oid attrdefId)
Definition: heap.c:1778
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
void LargeObjectDrop(Oid loid)
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:907
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:982
bool EventTriggerSupportsObjectClass(ObjectClass objclass)
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Index varno
Definition: primnodes.h:184
#define ngettext(s, p, n)
Definition: c.h:1133
void RemoveAmOpEntryById(Oid entryOid)
Definition: opclasscmds.c:1641
DropBehavior
Definition: parsenodes.h:1761
static void AcquireDeletionLock(const ObjectAddress *object, int flags)
Definition: dependency.c:1534
void CommandCounterIncrement(void)
Definition: xact.c:1005
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:325
Oid resultcollid
Definition: primnodes.h:837
Oid resulttype
Definition: primnodes.h:815
List * coltypes
Definition: primnodes.h:90
int log_min_messages
Definition: guc.c:518
Oid resultcollid
Definition: primnodes.h:817
void RemoveForeignServerById(Oid srvId)
Definition: foreigncmds.c:1092
bool creating_extension
Definition: extension.c:70
Oid aggfnoid
Definition: primnodes.h:312
#define DEPFLAG_EXTENSION
Definition: dependency.c:103
#define NOTICE
Definition: elog.h:37
CmdType commandType
Definition: parsenodes.h:112
List * lcons(void *datum, List *list)
Definition: list.c:454
int errmsg_internal(const char *fmt,...)
Definition: elog.c:909
List * funccolcollations
Definition: parsenodes.h:1152
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:55
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
Definition: dependency.c:1629
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
Oid row_typeid
Definition: primnodes.h:1023
static int list_length(const List *l)
Definition: pg_list.h:169
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1337
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
#define InvalidAttrNumber
Definition: attnum.h:23
void RemoveFunctionById(Oid funcOid)
RTEKind rtekind
Definition: parsenodes.h:974
ObjectAddressExtra * extras
Definition: dependency.c:113
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define Int32GetDatum(X)
Definition: postgres.h:479
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define DEPFLAG_NORMAL
Definition: dependency.c:99
NodeTag type
Definition: parsenodes.h:972
List * fieldnums
Definition: primnodes.h:793
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:39
#define elog(elevel,...)
Definition: elog.h:228
int i
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:139
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2859
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
int client_min_messages
Definition: guc.c:519
static void deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel, int flags)
Definition: dependency.c:227
Oid opno
Definition: primnodes.h:516
void DropCastById(Oid castOid)
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
#define MAX_REPORTED_DEPS
#define qsort(a, b, c, d)
Definition: port.h:491
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
static bool stack_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddressStack *stack)
Definition: dependency.c:2628
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:138
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1851
Definition: pg_list.h:50
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2436
ObjectAddress dependee
Definition: dependency.c:94
Oid startInRangeFunc
Definition: parsenodes.h:1356
void RemoveConstraintById(Oid conId)
#define _(x)
Definition: elog.c:87
Oid paramtype
Definition: primnodes.h:264
#define InvokeObjectDropHookArg(classId, objectId, subId, dropflags)
Definition: objectaccess.h:162
bool constisnull
Definition: primnodes.h:215
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
List * list_delete_first(List *list)
Definition: list.c:861
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
void RemoveTSDictionaryById(Oid dictId)
Definition: tsearchcmds.c:508
AttrNumber fieldnum
Definition: primnodes.h:763