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-2022, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  * src/backend/catalog/dependency.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/genam.h"
18 #include "access/htup_details.h"
19 #include "access/table.h"
20 #include "access/xact.h"
21 #include "catalog/catalog.h"
22 #include "catalog/dependency.h"
23 #include "catalog/heap.h"
24 #include "catalog/index.h"
25 #include "catalog/objectaccess.h"
26 #include "catalog/pg_am.h"
27 #include "catalog/pg_amop.h"
28 #include "catalog/pg_amproc.h"
29 #include "catalog/pg_attrdef.h"
30 #include "catalog/pg_authid.h"
31 #include "catalog/pg_cast.h"
32 #include "catalog/pg_collation.h"
33 #include "catalog/pg_constraint.h"
34 #include "catalog/pg_conversion.h"
35 #include "catalog/pg_database.h"
36 #include "catalog/pg_default_acl.h"
37 #include "catalog/pg_depend.h"
39 #include "catalog/pg_extension.h"
42 #include "catalog/pg_init_privs.h"
43 #include "catalog/pg_language.h"
44 #include "catalog/pg_largeobject.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_opclass.h"
47 #include "catalog/pg_operator.h"
48 #include "catalog/pg_opfamily.h"
49 #include "catalog/pg_policy.h"
50 #include "catalog/pg_proc.h"
51 #include "catalog/pg_publication.h"
54 #include "catalog/pg_rewrite.h"
57 #include "catalog/pg_tablespace.h"
58 #include "catalog/pg_transform.h"
59 #include "catalog/pg_trigger.h"
60 #include "catalog/pg_ts_config.h"
61 #include "catalog/pg_ts_dict.h"
62 #include "catalog/pg_ts_parser.h"
63 #include "catalog/pg_ts_template.h"
64 #include "catalog/pg_type.h"
66 #include "commands/comment.h"
67 #include "commands/defrem.h"
68 #include "commands/event_trigger.h"
69 #include "commands/extension.h"
70 #include "commands/policy.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/acl.h"
81 #include "utils/fmgroids.h"
82 #include "utils/guc.h"
83 #include "utils/lsyscache.h"
84 #include "utils/syscache.h"
85 
86 
87 /*
88  * Deletion processing requires additional state for each ObjectAddress that
89  * it's planning to delete. For simplicity and code-sharing we make the
90  * ObjectAddresses code support arrays with or without this extra state.
91  */
92 typedef struct
93 {
94  int flags; /* bitmask, see bit definitions below */
95  ObjectAddress dependee; /* object whose deletion forced this one */
97 
98 /* ObjectAddressExtra flag bits */
99 #define DEPFLAG_ORIGINAL 0x0001 /* an original deletion target */
100 #define DEPFLAG_NORMAL 0x0002 /* reached via normal dependency */
101 #define DEPFLAG_AUTO 0x0004 /* reached via auto dependency */
102 #define DEPFLAG_INTERNAL 0x0008 /* reached via internal dependency */
103 #define DEPFLAG_PARTITION 0x0010 /* reached via partition dependency */
104 #define DEPFLAG_EXTENSION 0x0020 /* reached via extension dependency */
105 #define DEPFLAG_REVERSE 0x0040 /* reverse internal/extension link */
106 #define DEPFLAG_IS_PART 0x0080 /* has a partition dependency */
107 #define DEPFLAG_SUBOBJECT 0x0100 /* subobject of another deletable object */
108 
109 
110 /* expansible list of ObjectAddresses */
112 {
113  ObjectAddress *refs; /* => palloc'd array */
114  ObjectAddressExtra *extras; /* => palloc'd array, or NULL if not used */
115  int numrefs; /* current number of references */
116  int maxrefs; /* current size of palloc'd array(s) */
117 };
118 
119 /* typedef ObjectAddresses appears in dependency.h */
120 
121 /* threaded list of ObjectAddresses, for recursion detection */
122 typedef struct ObjectAddressStack
123 {
124  const ObjectAddress *object; /* object being visited */
125  int flags; /* its current flag bits */
126  struct ObjectAddressStack *next; /* next outer stack level */
128 
129 /* temporary storage in findDependentObjects */
130 typedef struct
131 {
132  ObjectAddress obj; /* object to be deleted --- MUST BE FIRST */
133  int subflags; /* flags to pass down when recursing to obj */
135 
136 /* for find_expr_references_walker */
137 typedef struct
138 {
139  ObjectAddresses *addrs; /* addresses being accumulated */
140  List *rtables; /* list of rangetables to resolve Vars */
142 
143 /*
144  * This constant table maps ObjectClasses to the corresponding catalog OIDs.
145  * See also getObjectClass().
146  */
147 static const Oid object_classes[] = {
148  RelationRelationId, /* OCLASS_CLASS */
149  ProcedureRelationId, /* OCLASS_PROC */
150  TypeRelationId, /* OCLASS_TYPE */
151  CastRelationId, /* OCLASS_CAST */
152  CollationRelationId, /* OCLASS_COLLATION */
153  ConstraintRelationId, /* OCLASS_CONSTRAINT */
154  ConversionRelationId, /* OCLASS_CONVERSION */
155  AttrDefaultRelationId, /* OCLASS_DEFAULT */
156  LanguageRelationId, /* OCLASS_LANGUAGE */
157  LargeObjectRelationId, /* OCLASS_LARGEOBJECT */
158  OperatorRelationId, /* OCLASS_OPERATOR */
159  OperatorClassRelationId, /* OCLASS_OPCLASS */
160  OperatorFamilyRelationId, /* OCLASS_OPFAMILY */
161  AccessMethodRelationId, /* OCLASS_AM */
162  AccessMethodOperatorRelationId, /* OCLASS_AMOP */
163  AccessMethodProcedureRelationId, /* OCLASS_AMPROC */
164  RewriteRelationId, /* OCLASS_REWRITE */
165  TriggerRelationId, /* OCLASS_TRIGGER */
166  NamespaceRelationId, /* OCLASS_SCHEMA */
167  StatisticExtRelationId, /* OCLASS_STATISTIC_EXT */
168  TSParserRelationId, /* OCLASS_TSPARSER */
169  TSDictionaryRelationId, /* OCLASS_TSDICT */
170  TSTemplateRelationId, /* OCLASS_TSTEMPLATE */
171  TSConfigRelationId, /* OCLASS_TSCONFIG */
172  AuthIdRelationId, /* OCLASS_ROLE */
173  DatabaseRelationId, /* OCLASS_DATABASE */
174  TableSpaceRelationId, /* OCLASS_TBLSPACE */
175  ForeignDataWrapperRelationId, /* OCLASS_FDW */
176  ForeignServerRelationId, /* OCLASS_FOREIGN_SERVER */
177  UserMappingRelationId, /* OCLASS_USER_MAPPING */
178  DefaultAclRelationId, /* OCLASS_DEFACL */
179  ExtensionRelationId, /* OCLASS_EXTENSION */
180  EventTriggerRelationId, /* OCLASS_EVENT_TRIGGER */
181  PolicyRelationId, /* OCLASS_POLICY */
182  PublicationNamespaceRelationId, /* OCLASS_PUBLICATION_NAMESPACE */
183  PublicationRelationId, /* OCLASS_PUBLICATION */
184  PublicationRelRelationId, /* OCLASS_PUBLICATION_REL */
185  SubscriptionRelationId, /* OCLASS_SUBSCRIPTION */
186  TransformRelationId /* OCLASS_TRANSFORM */
187 };
188 
189 
190 static void findDependentObjects(const ObjectAddress *object,
191  int objflags,
192  int flags,
193  ObjectAddressStack *stack,
194  ObjectAddresses *targetObjects,
195  const ObjectAddresses *pendingObjects,
196  Relation *depRel);
197 static void reportDependentObjects(const ObjectAddresses *targetObjects,
198  DropBehavior behavior,
199  int flags,
200  const ObjectAddress *origObject);
201 static void deleteOneObject(const ObjectAddress *object,
202  Relation *depRel, int32 flags);
203 static void doDeletion(const ObjectAddress *object, int flags);
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 
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  * If the target object is pinned, we can just error out immediately; it
528  * won't have any objects recorded as depending on it.
529  */
531  ereport(ERROR,
532  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
533  errmsg("cannot drop %s because it is required by the database system",
534  getObjectDescription(object, false))));
535 
536  /*
537  * The target object might be internally dependent on some other object
538  * (its "owner"), and/or be a member of an extension (also considered its
539  * owner). If so, and if we aren't recursing from the owning object, we
540  * have to transform this deletion request into a deletion request of the
541  * owning object. (We'll eventually recurse back to this object, but the
542  * owning object has to be visited first so it will be deleted after.) The
543  * way to find out about this is to scan the pg_depend entries that show
544  * what this object depends on.
545  */
546  ScanKeyInit(&key[0],
547  Anum_pg_depend_classid,
548  BTEqualStrategyNumber, F_OIDEQ,
550  ScanKeyInit(&key[1],
551  Anum_pg_depend_objid,
552  BTEqualStrategyNumber, F_OIDEQ,
554  if (object->objectSubId != 0)
555  {
556  /* Consider only dependencies of this sub-object */
557  ScanKeyInit(&key[2],
558  Anum_pg_depend_objsubid,
559  BTEqualStrategyNumber, F_INT4EQ,
561  nkeys = 3;
562  }
563  else
564  {
565  /* Consider dependencies of this object and any sub-objects it has */
566  nkeys = 2;
567  }
568 
569  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
570  NULL, nkeys, key);
571 
572  /* initialize variables that loop may fill */
573  memset(&owningObject, 0, sizeof(owningObject));
574  memset(&partitionObject, 0, sizeof(partitionObject));
575 
576  while (HeapTupleIsValid(tup = systable_getnext(scan)))
577  {
578  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
579 
580  otherObject.classId = foundDep->refclassid;
581  otherObject.objectId = foundDep->refobjid;
582  otherObject.objectSubId = foundDep->refobjsubid;
583 
584  /*
585  * When scanning dependencies of a whole object, we may find rows
586  * linking sub-objects of the object to the object itself. (Normally,
587  * such a dependency is implicit, but we must make explicit ones in
588  * some cases involving partitioning.) We must ignore such rows to
589  * avoid infinite recursion.
590  */
591  if (otherObject.classId == object->classId &&
592  otherObject.objectId == object->objectId &&
593  object->objectSubId == 0)
594  continue;
595 
596  switch (foundDep->deptype)
597  {
598  case DEPENDENCY_NORMAL:
599  case DEPENDENCY_AUTO:
601  /* no problem */
602  break;
603 
605 
606  /*
607  * If told to, ignore EXTENSION dependencies altogether. This
608  * flag is normally used to prevent dropping extensions during
609  * temporary-object cleanup, even if a temp object was created
610  * during an extension script.
611  */
613  break;
614 
615  /*
616  * If the other object is the extension currently being
617  * created/altered, ignore this dependency and continue with
618  * the deletion. This allows dropping of an extension's
619  * objects within the extension's scripts, as well as corner
620  * cases such as dropping a transient object created within
621  * such a script.
622  */
623  if (creating_extension &&
624  otherObject.classId == ExtensionRelationId &&
625  otherObject.objectId == CurrentExtensionObject)
626  break;
627 
628  /* Otherwise, treat this like an internal dependency */
629  /* FALL THRU */
630 
631  case DEPENDENCY_INTERNAL:
632 
633  /*
634  * This object is part of the internal implementation of
635  * another object, or is part of the extension that is the
636  * other object. We have three cases:
637  *
638  * 1. At the outermost recursion level, we must disallow the
639  * DROP. However, if the owning object is listed in
640  * pendingObjects, just release the caller's lock and return;
641  * we'll eventually complete the DROP when we reach that entry
642  * in the pending list.
643  *
644  * Note: the above statement is true only if this pg_depend
645  * entry still exists by then; in principle, therefore, we
646  * could miss deleting an item the user told us to delete.
647  * However, no inconsistency can result: since we're at outer
648  * level, there is no object depending on this one.
649  */
650  if (stack == NULL)
651  {
652  if (pendingObjects &&
653  object_address_present(&otherObject, pendingObjects))
654  {
655  systable_endscan(scan);
656  /* need to release caller's lock; see notes below */
657  ReleaseDeletionLock(object);
658  return;
659  }
660 
661  /*
662  * We postpone actually issuing the error message until
663  * after this loop, so that we can make the behavior
664  * independent of the ordering of pg_depend entries, at
665  * least if there's not more than one INTERNAL and one
666  * EXTENSION dependency. (If there's more, we'll complain
667  * about a random one of them.) Prefer to complain about
668  * EXTENSION, since that's generally a more important
669  * dependency.
670  */
671  if (!OidIsValid(owningObject.classId) ||
672  foundDep->deptype == DEPENDENCY_EXTENSION)
673  owningObject = otherObject;
674  break;
675  }
676 
677  /*
678  * 2. When recursing from the other end of this dependency,
679  * it's okay to continue with the deletion. This holds when
680  * recursing from a whole object that includes the nominal
681  * other end as a component, too. Since there can be more
682  * than one "owning" object, we have to allow matches that are
683  * more than one level down in the stack.
684  */
685  if (stack_address_present_add_flags(&otherObject, 0, stack))
686  break;
687 
688  /*
689  * 3. Not all the owning objects have been visited, so
690  * transform this deletion request into a delete of this
691  * owning object.
692  *
693  * First, release caller's lock on this object and get
694  * deletion lock on the owning object. (We must release
695  * caller's lock to avoid deadlock against a concurrent
696  * deletion of the owning object.)
697  */
698  ReleaseDeletionLock(object);
699  AcquireDeletionLock(&otherObject, 0);
700 
701  /*
702  * The owning object might have been deleted while we waited
703  * to lock it; if so, neither it nor the current object are
704  * interesting anymore. We test this by checking the
705  * pg_depend entry (see notes below).
706  */
707  if (!systable_recheck_tuple(scan, tup))
708  {
709  systable_endscan(scan);
710  ReleaseDeletionLock(&otherObject);
711  return;
712  }
713 
714  /*
715  * One way or the other, we're done with the scan; might as
716  * well close it down before recursing, to reduce peak
717  * resource consumption.
718  */
719  systable_endscan(scan);
720 
721  /*
722  * Okay, recurse to the owning object instead of proceeding.
723  *
724  * We do not need to stack the current object; we want the
725  * traversal order to be as if the original reference had
726  * linked to the owning object instead of this one.
727  *
728  * The dependency type is a "reverse" dependency: we need to
729  * delete the owning object if this one is to be deleted, but
730  * this linkage is never a reason for an automatic deletion.
731  */
732  findDependentObjects(&otherObject,
734  flags,
735  stack,
736  targetObjects,
737  pendingObjects,
738  depRel);
739 
740  /*
741  * The current target object should have been added to
742  * targetObjects while processing the owning object; but it
743  * probably got only the flag bits associated with the
744  * dependency we're looking at. We need to add the objflags
745  * that were passed to this recursion level, too, else we may
746  * get a bogus failure in reportDependentObjects (if, for
747  * example, we were called due to a partition dependency).
748  *
749  * If somehow the current object didn't get scheduled for
750  * deletion, bleat. (That would imply that somebody deleted
751  * this dependency record before the recursion got to it.)
752  * Another idea would be to reacquire lock on the current
753  * object and resume trying to delete it, but it seems not
754  * worth dealing with the race conditions inherent in that.
755  */
756  if (!object_address_present_add_flags(object, objflags,
757  targetObjects))
758  elog(ERROR, "deletion of owning object %s failed to delete %s",
759  getObjectDescription(&otherObject, false),
760  getObjectDescription(object, false));
761 
762  /* And we're done here. */
763  return;
764 
766 
767  /*
768  * Remember that this object has a partition-type dependency.
769  * After the dependency scan, we'll complain if we didn't find
770  * a reason to delete one of its partition dependencies.
771  */
772  objflags |= DEPFLAG_IS_PART;
773 
774  /*
775  * Also remember the primary partition owner, for error
776  * messages. If there are multiple primary owners (which
777  * there should not be), we'll report a random one of them.
778  */
779  partitionObject = otherObject;
780  break;
781 
783 
784  /*
785  * Only use secondary partition owners in error messages if we
786  * find no primary owner (which probably shouldn't happen).
787  */
788  if (!(objflags & DEPFLAG_IS_PART))
789  partitionObject = otherObject;
790 
791  /*
792  * Remember that this object has a partition-type dependency.
793  * After the dependency scan, we'll complain if we didn't find
794  * a reason to delete one of its partition dependencies.
795  */
796  objflags |= DEPFLAG_IS_PART;
797  break;
798 
799  default:
800  elog(ERROR, "unrecognized dependency type '%c' for %s",
801  foundDep->deptype, getObjectDescription(object, false));
802  break;
803  }
804  }
805 
806  systable_endscan(scan);
807 
808  /*
809  * If we found an INTERNAL or EXTENSION dependency when we're at outer
810  * level, complain about it now. If we also found a PARTITION dependency,
811  * we prefer to report the PARTITION dependency. This is arbitrary but
812  * seems to be more useful in practice.
813  */
814  if (OidIsValid(owningObject.classId))
815  {
816  char *otherObjDesc;
817 
818  if (OidIsValid(partitionObject.classId))
819  otherObjDesc = getObjectDescription(&partitionObject, false);
820  else
821  otherObjDesc = getObjectDescription(&owningObject, false);
822 
823  ereport(ERROR,
824  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
825  errmsg("cannot drop %s because %s requires it",
826  getObjectDescription(object, false), otherObjDesc),
827  errhint("You can drop %s instead.", otherObjDesc)));
828  }
829 
830  /*
831  * Next, identify all objects that directly depend on the current object.
832  * To ensure predictable deletion order, we collect them up in
833  * dependentObjects and sort the list before actually recursing. (The
834  * deletion order would be valid in any case, but doing this ensures
835  * consistent output from DROP CASCADE commands, which is helpful for
836  * regression testing.)
837  */
838  maxDependentObjects = 128; /* arbitrary initial allocation */
839  dependentObjects = (ObjectAddressAndFlags *)
840  palloc(maxDependentObjects * sizeof(ObjectAddressAndFlags));
841  numDependentObjects = 0;
842 
843  ScanKeyInit(&key[0],
844  Anum_pg_depend_refclassid,
845  BTEqualStrategyNumber, F_OIDEQ,
847  ScanKeyInit(&key[1],
848  Anum_pg_depend_refobjid,
849  BTEqualStrategyNumber, F_OIDEQ,
851  if (object->objectSubId != 0)
852  {
853  ScanKeyInit(&key[2],
854  Anum_pg_depend_refobjsubid,
855  BTEqualStrategyNumber, F_INT4EQ,
857  nkeys = 3;
858  }
859  else
860  nkeys = 2;
861 
862  scan = systable_beginscan(*depRel, DependReferenceIndexId, true,
863  NULL, nkeys, key);
864 
865  while (HeapTupleIsValid(tup = systable_getnext(scan)))
866  {
867  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
868  int subflags;
869 
870  otherObject.classId = foundDep->classid;
871  otherObject.objectId = foundDep->objid;
872  otherObject.objectSubId = foundDep->objsubid;
873 
874  /*
875  * If what we found is a sub-object of the current object, just ignore
876  * it. (Normally, such a dependency is implicit, but we must make
877  * explicit ones in some cases involving partitioning.)
878  */
879  if (otherObject.classId == object->classId &&
880  otherObject.objectId == object->objectId &&
881  object->objectSubId == 0)
882  continue;
883 
884  /*
885  * Must lock the dependent object before recursing to it.
886  */
887  AcquireDeletionLock(&otherObject, 0);
888 
889  /*
890  * The dependent object might have been deleted while we waited to
891  * lock it; if so, we don't need to do anything more with it. We can
892  * test this cheaply and independently of the object's type by seeing
893  * if the pg_depend tuple we are looking at is still live. (If the
894  * object got deleted, the tuple would have been deleted too.)
895  */
896  if (!systable_recheck_tuple(scan, tup))
897  {
898  /* release the now-useless lock */
899  ReleaseDeletionLock(&otherObject);
900  /* and continue scanning for dependencies */
901  continue;
902  }
903 
904  /*
905  * We do need to delete it, so identify objflags to be passed down,
906  * which depend on the dependency type.
907  */
908  switch (foundDep->deptype)
909  {
910  case DEPENDENCY_NORMAL:
911  subflags = DEPFLAG_NORMAL;
912  break;
913  case DEPENDENCY_AUTO:
915  subflags = DEPFLAG_AUTO;
916  break;
917  case DEPENDENCY_INTERNAL:
918  subflags = DEPFLAG_INTERNAL;
919  break;
922  subflags = DEPFLAG_PARTITION;
923  break;
925  subflags = DEPFLAG_EXTENSION;
926  break;
927  default:
928  elog(ERROR, "unrecognized dependency type '%c' for %s",
929  foundDep->deptype, getObjectDescription(object, false));
930  subflags = 0; /* keep compiler quiet */
931  break;
932  }
933 
934  /* And add it to the pending-objects list */
935  if (numDependentObjects >= maxDependentObjects)
936  {
937  /* enlarge array if needed */
938  maxDependentObjects *= 2;
939  dependentObjects = (ObjectAddressAndFlags *)
940  repalloc(dependentObjects,
941  maxDependentObjects * sizeof(ObjectAddressAndFlags));
942  }
943 
944  dependentObjects[numDependentObjects].obj = otherObject;
945  dependentObjects[numDependentObjects].subflags = subflags;
946  numDependentObjects++;
947  }
948 
949  systable_endscan(scan);
950 
951  /*
952  * Now we can sort the dependent objects into a stable visitation order.
953  * It's safe to use object_address_comparator here since the obj field is
954  * first within ObjectAddressAndFlags.
955  */
956  if (numDependentObjects > 1)
957  qsort((void *) dependentObjects, numDependentObjects,
958  sizeof(ObjectAddressAndFlags),
960 
961  /*
962  * Now recurse to the dependent objects. We must visit them first since
963  * they have to be deleted before the current object.
964  */
965  mystack.object = object; /* set up a new stack level */
966  mystack.flags = objflags;
967  mystack.next = stack;
968 
969  for (int i = 0; i < numDependentObjects; i++)
970  {
971  ObjectAddressAndFlags *depObj = dependentObjects + i;
972 
973  findDependentObjects(&depObj->obj,
974  depObj->subflags,
975  flags,
976  &mystack,
977  targetObjects,
978  pendingObjects,
979  depRel);
980  }
981 
982  pfree(dependentObjects);
983 
984  /*
985  * Finally, we can add the target object to targetObjects. Be careful to
986  * include any flags that were passed back down to us from inner recursion
987  * levels. Record the "dependee" as being either the most important
988  * partition owner if there is one, else the object we recursed from, if
989  * any. (The logic in reportDependentObjects() is such that it can only
990  * need one of those objects.)
991  */
992  extra.flags = mystack.flags;
993  if (extra.flags & DEPFLAG_IS_PART)
994  extra.dependee = partitionObject;
995  else if (stack)
996  extra.dependee = *stack->object;
997  else
998  memset(&extra.dependee, 0, sizeof(extra.dependee));
999  add_exact_object_address_extra(object, &extra, targetObjects);
1000 }
1001 
1002 /*
1003  * reportDependentObjects - report about dependencies, and fail if RESTRICT
1004  *
1005  * Tell the user about dependent objects that we are going to delete
1006  * (or would need to delete, but are prevented by RESTRICT mode);
1007  * then error out if there are any and it's not CASCADE mode.
1008  *
1009  * targetObjects: list of objects that are scheduled to be deleted
1010  * behavior: RESTRICT or CASCADE
1011  * flags: other flags for the deletion operation
1012  * origObject: base object of deletion, or NULL if not available
1013  * (the latter case occurs in DROP OWNED)
1014  */
1015 static void
1017  DropBehavior behavior,
1018  int flags,
1019  const ObjectAddress *origObject)
1020 {
1021  int msglevel = (flags & PERFORM_DELETION_QUIETLY) ? DEBUG2 : NOTICE;
1022  bool ok = true;
1023  StringInfoData clientdetail;
1024  StringInfoData logdetail;
1025  int numReportedClient = 0;
1026  int numNotReportedClient = 0;
1027  int i;
1028 
1029  /*
1030  * If we need to delete any partition-dependent objects, make sure that
1031  * we're deleting at least one of their partition dependencies, too. That
1032  * can be detected by checking that we reached them by a PARTITION
1033  * dependency at some point.
1034  *
1035  * We just report the first such object, as in most cases the only way to
1036  * trigger this complaint is to explicitly try to delete one partition of
1037  * a partitioned object.
1038  */
1039  for (i = 0; i < targetObjects->numrefs; i++)
1040  {
1041  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1042 
1043  if ((extra->flags & DEPFLAG_IS_PART) &&
1044  !(extra->flags & DEPFLAG_PARTITION))
1045  {
1046  const ObjectAddress *object = &targetObjects->refs[i];
1047  char *otherObjDesc = getObjectDescription(&extra->dependee,
1048  false);
1049 
1050  ereport(ERROR,
1051  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1052  errmsg("cannot drop %s because %s requires it",
1053  getObjectDescription(object, false), otherObjDesc),
1054  errhint("You can drop %s instead.", otherObjDesc)));
1055  }
1056  }
1057 
1058  /*
1059  * If no error is to be thrown, and the msglevel is too low to be shown to
1060  * either client or server log, there's no need to do any of the rest of
1061  * the work.
1062  */
1063  if (behavior == DROP_CASCADE &&
1064  !message_level_is_interesting(msglevel))
1065  return;
1066 
1067  /*
1068  * We limit the number of dependencies reported to the client to
1069  * MAX_REPORTED_DEPS, since client software may not deal well with
1070  * enormous error strings. The server log always gets a full report.
1071  */
1072 #define MAX_REPORTED_DEPS 100
1073 
1074  initStringInfo(&clientdetail);
1075  initStringInfo(&logdetail);
1076 
1077  /*
1078  * We process the list back to front (ie, in dependency order not deletion
1079  * order), since this makes for a more understandable display.
1080  */
1081  for (i = targetObjects->numrefs - 1; i >= 0; i--)
1082  {
1083  const ObjectAddress *obj = &targetObjects->refs[i];
1084  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1085  char *objDesc;
1086 
1087  /* Ignore the original deletion target(s) */
1088  if (extra->flags & DEPFLAG_ORIGINAL)
1089  continue;
1090 
1091  /* Also ignore sub-objects; we'll report the whole object elsewhere */
1092  if (extra->flags & DEPFLAG_SUBOBJECT)
1093  continue;
1094 
1095  objDesc = getObjectDescription(obj, false);
1096 
1097  /* An object being dropped concurrently doesn't need to be reported */
1098  if (objDesc == NULL)
1099  continue;
1100 
1101  /*
1102  * If, at any stage of the recursive search, we reached the object via
1103  * an AUTO, INTERNAL, PARTITION, or EXTENSION dependency, then it's
1104  * okay to delete it even in RESTRICT mode.
1105  */
1106  if (extra->flags & (DEPFLAG_AUTO |
1110  {
1111  /*
1112  * auto-cascades are reported at DEBUG2, not msglevel. We don't
1113  * try to combine them with the regular message because the
1114  * results are too confusing when client_min_messages and
1115  * log_min_messages are different.
1116  */
1117  ereport(DEBUG2,
1118  (errmsg_internal("drop auto-cascades to %s",
1119  objDesc)));
1120  }
1121  else if (behavior == DROP_RESTRICT)
1122  {
1123  char *otherDesc = getObjectDescription(&extra->dependee,
1124  false);
1125 
1126  if (otherDesc)
1127  {
1128  if (numReportedClient < MAX_REPORTED_DEPS)
1129  {
1130  /* separate entries with a newline */
1131  if (clientdetail.len != 0)
1132  appendStringInfoChar(&clientdetail, '\n');
1133  appendStringInfo(&clientdetail, _("%s depends on %s"),
1134  objDesc, otherDesc);
1135  numReportedClient++;
1136  }
1137  else
1138  numNotReportedClient++;
1139  /* separate entries with a newline */
1140  if (logdetail.len != 0)
1141  appendStringInfoChar(&logdetail, '\n');
1142  appendStringInfo(&logdetail, _("%s depends on %s"),
1143  objDesc, otherDesc);
1144  pfree(otherDesc);
1145  }
1146  else
1147  numNotReportedClient++;
1148  ok = false;
1149  }
1150  else
1151  {
1152  if (numReportedClient < MAX_REPORTED_DEPS)
1153  {
1154  /* separate entries with a newline */
1155  if (clientdetail.len != 0)
1156  appendStringInfoChar(&clientdetail, '\n');
1157  appendStringInfo(&clientdetail, _("drop cascades to %s"),
1158  objDesc);
1159  numReportedClient++;
1160  }
1161  else
1162  numNotReportedClient++;
1163  /* separate entries with a newline */
1164  if (logdetail.len != 0)
1165  appendStringInfoChar(&logdetail, '\n');
1166  appendStringInfo(&logdetail, _("drop cascades to %s"),
1167  objDesc);
1168  }
1169 
1170  pfree(objDesc);
1171  }
1172 
1173  if (numNotReportedClient > 0)
1174  appendStringInfo(&clientdetail, ngettext("\nand %d other object "
1175  "(see server log for list)",
1176  "\nand %d other objects "
1177  "(see server log for list)",
1178  numNotReportedClient),
1179  numNotReportedClient);
1180 
1181  if (!ok)
1182  {
1183  if (origObject)
1184  ereport(ERROR,
1185  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1186  errmsg("cannot drop %s because other objects depend on it",
1187  getObjectDescription(origObject, false)),
1188  errdetail("%s", clientdetail.data),
1189  errdetail_log("%s", logdetail.data),
1190  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1191  else
1192  ereport(ERROR,
1193  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1194  errmsg("cannot drop desired object(s) because other objects depend on them"),
1195  errdetail("%s", clientdetail.data),
1196  errdetail_log("%s", logdetail.data),
1197  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1198  }
1199  else if (numReportedClient > 1)
1200  {
1201  ereport(msglevel,
1202  /* translator: %d always has a value larger than 1 */
1203  (errmsg_plural("drop cascades to %d other object",
1204  "drop cascades to %d other objects",
1205  numReportedClient + numNotReportedClient,
1206  numReportedClient + numNotReportedClient),
1207  errdetail("%s", clientdetail.data),
1208  errdetail_log("%s", logdetail.data)));
1209  }
1210  else if (numReportedClient == 1)
1211  {
1212  /* we just use the single item as-is */
1213  ereport(msglevel,
1214  (errmsg_internal("%s", clientdetail.data)));
1215  }
1216 
1217  pfree(clientdetail.data);
1218  pfree(logdetail.data);
1219 }
1220 
1221 /*
1222  * Drop an object by OID. Works for most catalogs, if no special processing
1223  * is needed.
1224  */
1225 static void
1227 {
1228  int cacheId;
1229  Relation rel;
1230  HeapTuple tup;
1231 
1233 
1235 
1236  /*
1237  * Use the system cache for the oid column, if one exists.
1238  */
1239  if (cacheId >= 0)
1240  {
1241  tup = SearchSysCache1(cacheId, ObjectIdGetDatum(object->objectId));
1242  if (!HeapTupleIsValid(tup))
1243  elog(ERROR, "cache lookup failed for %s %u",
1245 
1246  CatalogTupleDelete(rel, &tup->t_self);
1247 
1248  ReleaseSysCache(tup);
1249  }
1250  else
1251  {
1252  ScanKeyData skey[1];
1253  SysScanDesc scan;
1254 
1255  ScanKeyInit(&skey[0],
1257  BTEqualStrategyNumber, F_OIDEQ,
1259 
1261  NULL, 1, skey);
1262 
1263  /* we expect exactly one match */
1264  tup = systable_getnext(scan);
1265  if (!HeapTupleIsValid(tup))
1266  elog(ERROR, "could not find tuple for %s %u",
1268 
1269  CatalogTupleDelete(rel, &tup->t_self);
1270 
1271  systable_endscan(scan);
1272  }
1273 
1275 }
1276 
1277 /*
1278  * deleteOneObject: delete a single object for performDeletion.
1279  *
1280  * *depRel is the already-open pg_depend relation.
1281  */
1282 static void
1283 deleteOneObject(const ObjectAddress *object, Relation *depRel, int flags)
1284 {
1285  ScanKeyData key[3];
1286  int nkeys;
1287  SysScanDesc scan;
1288  HeapTuple tup;
1289 
1290  /* DROP hook of the objects being removed */
1293 
1294  /*
1295  * Close depRel if we are doing a drop concurrently. The object deletion
1296  * subroutine will commit the current transaction, so we can't keep the
1297  * relation open across doDeletion().
1298  */
1300  table_close(*depRel, RowExclusiveLock);
1301 
1302  /*
1303  * Delete the object itself, in an object-type-dependent way.
1304  *
1305  * We used to do this after removing the outgoing dependency links, but it
1306  * seems just as reasonable to do it beforehand. In the concurrent case
1307  * we *must* do it in this order, because we can't make any transactional
1308  * updates before calling doDeletion() --- they'd get committed right
1309  * away, which is not cool if the deletion then fails.
1310  */
1311  doDeletion(object, flags);
1312 
1313  /*
1314  * Reopen depRel if we closed it above
1315  */
1317  *depRel = table_open(DependRelationId, RowExclusiveLock);
1318 
1319  /*
1320  * Now remove any pg_depend records that link from this object to others.
1321  * (Any records linking to this object should be gone already.)
1322  *
1323  * When dropping a whole object (subId = 0), remove all pg_depend records
1324  * for its sub-objects too.
1325  */
1326  ScanKeyInit(&key[0],
1327  Anum_pg_depend_classid,
1328  BTEqualStrategyNumber, F_OIDEQ,
1330  ScanKeyInit(&key[1],
1331  Anum_pg_depend_objid,
1332  BTEqualStrategyNumber, F_OIDEQ,
1334  if (object->objectSubId != 0)
1335  {
1336  ScanKeyInit(&key[2],
1337  Anum_pg_depend_objsubid,
1338  BTEqualStrategyNumber, F_INT4EQ,
1340  nkeys = 3;
1341  }
1342  else
1343  nkeys = 2;
1344 
1345  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1346  NULL, nkeys, key);
1347 
1348  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1349  {
1350  CatalogTupleDelete(*depRel, &tup->t_self);
1351  }
1352 
1353  systable_endscan(scan);
1354 
1355  /*
1356  * Delete shared dependency references related to this object. Again, if
1357  * subId = 0, remove records for sub-objects too.
1358  */
1360  object->objectSubId);
1361 
1362 
1363  /*
1364  * Delete any comments, security labels, or initial privileges associated
1365  * with this object. (This is a convenient place to do these things,
1366  * rather than having every object type know to do it.)
1367  */
1369  DeleteSecurityLabel(object);
1370  DeleteInitPrivs(object);
1371 
1372  /*
1373  * CommandCounterIncrement here to ensure that preceding changes are all
1374  * visible to the next deletion step.
1375  */
1377 
1378  /*
1379  * And we're done!
1380  */
1381 }
1382 
1383 /*
1384  * doDeletion: actually delete a single object
1385  */
1386 static void
1387 doDeletion(const ObjectAddress *object, int flags)
1388 {
1389  switch (getObjectClass(object))
1390  {
1391  case OCLASS_CLASS:
1392  {
1393  char relKind = get_rel_relkind(object->objectId);
1394 
1395  if (relKind == RELKIND_INDEX ||
1396  relKind == RELKIND_PARTITIONED_INDEX)
1397  {
1398  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1399  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1400 
1401  Assert(object->objectSubId == 0);
1402  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1403  }
1404  else
1405  {
1406  if (object->objectSubId != 0)
1408  object->objectSubId);
1409  else
1411  }
1412 
1413  /*
1414  * for a sequence, in addition to dropping the heap, also
1415  * delete pg_sequence tuple
1416  */
1417  if (relKind == RELKIND_SEQUENCE)
1419  break;
1420  }
1421 
1422  case OCLASS_PROC:
1424  break;
1425 
1426  case OCLASS_TYPE:
1428  break;
1429 
1430  case OCLASS_CONSTRAINT:
1432  break;
1433 
1434  case OCLASS_DEFAULT:
1436  break;
1437 
1438  case OCLASS_LARGEOBJECT:
1440  break;
1441 
1442  case OCLASS_OPERATOR:
1444  break;
1445 
1446  case OCLASS_REWRITE:
1448  break;
1449 
1450  case OCLASS_TRIGGER:
1452  break;
1453 
1454  case OCLASS_STATISTIC_EXT:
1456  break;
1457 
1458  case OCLASS_TSCONFIG:
1460  break;
1461 
1462  case OCLASS_EXTENSION:
1464  break;
1465 
1466  case OCLASS_POLICY:
1468  break;
1469 
1472  break;
1473 
1476  break;
1477 
1478  case OCLASS_PUBLICATION:
1480  break;
1481 
1482  case OCLASS_CAST:
1483  case OCLASS_COLLATION:
1484  case OCLASS_CONVERSION:
1485  case OCLASS_LANGUAGE:
1486  case OCLASS_OPCLASS:
1487  case OCLASS_OPFAMILY:
1488  case OCLASS_AM:
1489  case OCLASS_AMOP:
1490  case OCLASS_AMPROC:
1491  case OCLASS_SCHEMA:
1492  case OCLASS_TSPARSER:
1493  case OCLASS_TSDICT:
1494  case OCLASS_TSTEMPLATE:
1495  case OCLASS_FDW:
1496  case OCLASS_FOREIGN_SERVER:
1497  case OCLASS_USER_MAPPING:
1498  case OCLASS_DEFACL:
1499  case OCLASS_EVENT_TRIGGER:
1500  case OCLASS_TRANSFORM:
1501  DropObjectById(object);
1502  break;
1503 
1504  /*
1505  * These global object types are not supported here.
1506  */
1507  case OCLASS_ROLE:
1508  case OCLASS_DATABASE:
1509  case OCLASS_TBLSPACE:
1510  case OCLASS_SUBSCRIPTION:
1511  elog(ERROR, "global objects cannot be deleted by doDeletion");
1512  break;
1513 
1514  /*
1515  * There's intentionally no default: case here; we want the
1516  * compiler to warn if a new OCLASS hasn't been handled above.
1517  */
1518  }
1519 }
1520 
1521 /*
1522  * AcquireDeletionLock - acquire a suitable lock for deleting an object
1523  *
1524  * Accepts the same flags as performDeletion (though currently only
1525  * PERFORM_DELETION_CONCURRENTLY does anything).
1526  *
1527  * We use LockRelation for relations, LockDatabaseObject for everything
1528  * else. Shared-across-databases objects are not currently supported
1529  * because no caller cares, but could be modified to use LockSharedObject.
1530  */
1531 void
1533 {
1534  if (object->classId == RelationRelationId)
1535  {
1536  /*
1537  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1538  * the index for the moment. index_drop() will promote the lock once
1539  * it's safe to do so. In all other cases we need full exclusive
1540  * lock.
1541  */
1544  else
1546  }
1547  else
1548  {
1549  /* assume we should lock the whole object not a sub-object */
1552  }
1553 }
1554 
1555 /*
1556  * ReleaseDeletionLock - release an object deletion lock
1557  *
1558  * Companion to AcquireDeletionLock.
1559  */
1560 void
1562 {
1563  if (object->classId == RelationRelationId)
1565  else
1566  /* assume we should lock the whole object not a sub-object */
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, SubscriptingRef))
1948  {
1949  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1950 
1951  /*
1952  * The refexpr should provide adequate dependency on refcontainertype,
1953  * and that type in turn depends on refelemtype. However, a custom
1954  * subscripting handler might set refrestype to something different
1955  * from either of those, in which case we'd better record it.
1956  */
1957  if (sbsref->refrestype != sbsref->refcontainertype &&
1958  sbsref->refrestype != sbsref->refelemtype)
1960  context->addrs);
1961  /* fall through to examine arguments */
1962  }
1963  else if (IsA(node, SubPlan))
1964  {
1965  /* Extra work needed here if we ever need this case */
1966  elog(ERROR, "already-planned subqueries not supported");
1967  }
1968  else if (IsA(node, FieldSelect))
1969  {
1970  FieldSelect *fselect = (FieldSelect *) node;
1971  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1972  Oid reltype = get_typ_typrelid(argtype);
1973 
1974  /*
1975  * We need a dependency on the specific column named in FieldSelect,
1976  * assuming we can identify the pg_class OID for it. (Probably we
1977  * always can at the moment, but in future it might be possible for
1978  * argtype to be RECORDOID.) If we can make a column dependency then
1979  * we shouldn't need a dependency on the column's type; but if we
1980  * can't, make a dependency on the type, as it might not appear
1981  * anywhere else in the expression.
1982  */
1983  if (OidIsValid(reltype))
1984  add_object_address(OCLASS_CLASS, reltype, fselect->fieldnum,
1985  context->addrs);
1986  else
1988  context->addrs);
1989  /* the collation might not be referenced anywhere else, either */
1990  if (OidIsValid(fselect->resultcollid) &&
1991  fselect->resultcollid != DEFAULT_COLLATION_OID)
1993  context->addrs);
1994  }
1995  else if (IsA(node, FieldStore))
1996  {
1997  FieldStore *fstore = (FieldStore *) node;
1998  Oid reltype = get_typ_typrelid(fstore->resulttype);
1999 
2000  /* similar considerations to FieldSelect, but multiple column(s) */
2001  if (OidIsValid(reltype))
2002  {
2003  ListCell *l;
2004 
2005  foreach(l, fstore->fieldnums)
2007  context->addrs);
2008  }
2009  else
2011  context->addrs);
2012  }
2013  else if (IsA(node, RelabelType))
2014  {
2015  RelabelType *relab = (RelabelType *) node;
2016 
2017  /* since there is no function dependency, need to depend on type */
2019  context->addrs);
2020  /* the collation might not be referenced anywhere else, either */
2021  if (OidIsValid(relab->resultcollid) &&
2022  relab->resultcollid != DEFAULT_COLLATION_OID)
2024  context->addrs);
2025  }
2026  else if (IsA(node, CoerceViaIO))
2027  {
2028  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2029 
2030  /* since there is no exposed function, need to depend on type */
2032  context->addrs);
2033  /* the collation might not be referenced anywhere else, either */
2034  if (OidIsValid(iocoerce->resultcollid) &&
2035  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2037  context->addrs);
2038  }
2039  else if (IsA(node, ArrayCoerceExpr))
2040  {
2041  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2042 
2043  /* as above, depend on type */
2045  context->addrs);
2046  /* the collation might not be referenced anywhere else, either */
2047  if (OidIsValid(acoerce->resultcollid) &&
2048  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2050  context->addrs);
2051  /* fall through to examine arguments */
2052  }
2053  else if (IsA(node, ConvertRowtypeExpr))
2054  {
2055  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2056 
2057  /* since there is no function dependency, need to depend on type */
2059  context->addrs);
2060  }
2061  else if (IsA(node, CollateExpr))
2062  {
2063  CollateExpr *coll = (CollateExpr *) node;
2064 
2066  context->addrs);
2067  }
2068  else if (IsA(node, RowExpr))
2069  {
2070  RowExpr *rowexpr = (RowExpr *) node;
2071 
2073  context->addrs);
2074  }
2075  else if (IsA(node, RowCompareExpr))
2076  {
2077  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2078  ListCell *l;
2079 
2080  foreach(l, rcexpr->opnos)
2081  {
2083  context->addrs);
2084  }
2085  foreach(l, rcexpr->opfamilies)
2086  {
2088  context->addrs);
2089  }
2090  /* fall through to examine arguments */
2091  }
2092  else if (IsA(node, CoerceToDomain))
2093  {
2094  CoerceToDomain *cd = (CoerceToDomain *) node;
2095 
2097  context->addrs);
2098  }
2099  else if (IsA(node, NextValueExpr))
2100  {
2101  NextValueExpr *nve = (NextValueExpr *) node;
2102 
2104  context->addrs);
2105  }
2106  else if (IsA(node, OnConflictExpr))
2107  {
2108  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2109 
2110  if (OidIsValid(onconflict->constraint))
2112  context->addrs);
2113  /* fall through to examine arguments */
2114  }
2115  else if (IsA(node, SortGroupClause))
2116  {
2117  SortGroupClause *sgc = (SortGroupClause *) node;
2118 
2120  context->addrs);
2121  if (OidIsValid(sgc->sortop))
2123  context->addrs);
2124  return false;
2125  }
2126  else if (IsA(node, WindowClause))
2127  {
2128  WindowClause *wc = (WindowClause *) node;
2129 
2130  if (OidIsValid(wc->startInRangeFunc))
2132  context->addrs);
2133  if (OidIsValid(wc->endInRangeFunc))
2135  context->addrs);
2136  if (OidIsValid(wc->inRangeColl) &&
2137  wc->inRangeColl != DEFAULT_COLLATION_OID)
2139  context->addrs);
2140  /* fall through to examine substructure */
2141  }
2142  else if (IsA(node, CTECycleClause))
2143  {
2144  CTECycleClause *cc = (CTECycleClause *) node;
2145 
2146  if (OidIsValid(cc->cycle_mark_type))
2148  context->addrs);
2151  context->addrs);
2152  if (OidIsValid(cc->cycle_mark_neop))
2154  context->addrs);
2155  /* fall through to examine substructure */
2156  }
2157  else if (IsA(node, Query))
2158  {
2159  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2160  Query *query = (Query *) node;
2161  ListCell *lc;
2162  bool result;
2163 
2164  /*
2165  * Add whole-relation refs for each plain relation mentioned in the
2166  * subquery's rtable, and ensure we add refs for any type-coercion
2167  * functions used in join alias lists.
2168  *
2169  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2170  * RTEs, subqueries, etc, so no need to do that here. But we must
2171  * tell it not to visit join alias lists, or we'll add refs for join
2172  * input columns whether or not they are actually used in our query.
2173  *
2174  * Note: we don't need to worry about collations mentioned in
2175  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2176  * collations referenced in other parts of the Query. We do have to
2177  * worry about collations mentioned in RTE_FUNCTION, but we take care
2178  * of those when we recurse to the RangeTblFunction node(s).
2179  */
2180  foreach(lc, query->rtable)
2181  {
2182  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2183 
2184  switch (rte->rtekind)
2185  {
2186  case RTE_RELATION:
2188  context->addrs);
2189  break;
2190  case RTE_JOIN:
2191 
2192  /*
2193  * Examine joinaliasvars entries only for merged JOIN
2194  * USING columns. Only those entries could contain
2195  * type-coercion functions. Also, their join input
2196  * columns must be referenced in the join quals, so this
2197  * won't accidentally add refs to otherwise-unused join
2198  * input columns. (We want to ref the type coercion
2199  * functions even if the merged column isn't explicitly
2200  * used anywhere, to protect possible expansion of the
2201  * join RTE as a whole-row var, and because it seems like
2202  * a bad idea to allow dropping a function that's present
2203  * in our query tree, whether or not it could get called.)
2204  */
2205  context->rtables = lcons(query->rtable, context->rtables);
2206  for (int i = 0; i < rte->joinmergedcols; i++)
2207  {
2208  Node *aliasvar = list_nth(rte->joinaliasvars, i);
2209 
2210  if (!IsA(aliasvar, Var))
2211  find_expr_references_walker(aliasvar, context);
2212  }
2213  context->rtables = list_delete_first(context->rtables);
2214  break;
2215  default:
2216  break;
2217  }
2218  }
2219 
2220  /*
2221  * If the query is an INSERT or UPDATE, we should create a dependency
2222  * on each target column, to prevent the specific target column from
2223  * being dropped. Although we will visit the TargetEntry nodes again
2224  * during query_tree_walker, we won't have enough context to do this
2225  * conveniently, so do it here.
2226  */
2227  if (query->commandType == CMD_INSERT ||
2228  query->commandType == CMD_UPDATE)
2229  {
2230  RangeTblEntry *rte;
2231 
2232  if (query->resultRelation <= 0 ||
2233  query->resultRelation > list_length(query->rtable))
2234  elog(ERROR, "invalid resultRelation %d",
2235  query->resultRelation);
2236  rte = rt_fetch(query->resultRelation, query->rtable);
2237  if (rte->rtekind == RTE_RELATION)
2238  {
2239  foreach(lc, query->targetList)
2240  {
2241  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2242 
2243  if (tle->resjunk)
2244  continue; /* ignore junk tlist items */
2246  context->addrs);
2247  }
2248  }
2249  }
2250 
2251  /*
2252  * Add dependencies on constraints listed in query's constraintDeps
2253  */
2254  foreach(lc, query->constraintDeps)
2255  {
2257  context->addrs);
2258  }
2259 
2260  /* Examine substructure of query */
2261  context->rtables = lcons(query->rtable, context->rtables);
2262  result = query_tree_walker(query,
2264  (void *) context,
2267  context->rtables = list_delete_first(context->rtables);
2268  return result;
2269  }
2270  else if (IsA(node, SetOperationStmt))
2271  {
2272  SetOperationStmt *setop = (SetOperationStmt *) node;
2273 
2274  /* we need to look at the groupClauses for operator references */
2275  find_expr_references_walker((Node *) setop->groupClauses, context);
2276  /* fall through to examine child nodes */
2277  }
2278  else if (IsA(node, RangeTblFunction))
2279  {
2280  RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2281  ListCell *ct;
2282 
2283  /*
2284  * Add refs for any datatypes and collations used in a column
2285  * definition list for a RECORD function. (For other cases, it should
2286  * be enough to depend on the function itself.)
2287  */
2288  foreach(ct, rtfunc->funccoltypes)
2289  {
2291  context->addrs);
2292  }
2293  foreach(ct, rtfunc->funccolcollations)
2294  {
2295  Oid collid = lfirst_oid(ct);
2296 
2297  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2299  context->addrs);
2300  }
2301  }
2302  else if (IsA(node, TableFunc))
2303  {
2304  TableFunc *tf = (TableFunc *) node;
2305  ListCell *ct;
2306 
2307  /*
2308  * Add refs for the datatypes and collations used in the TableFunc.
2309  */
2310  foreach(ct, tf->coltypes)
2311  {
2313  context->addrs);
2314  }
2315  foreach(ct, tf->colcollations)
2316  {
2317  Oid collid = lfirst_oid(ct);
2318 
2319  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2321  context->addrs);
2322  }
2323  }
2324  else if (IsA(node, TableSampleClause))
2325  {
2326  TableSampleClause *tsc = (TableSampleClause *) node;
2327 
2329  context->addrs);
2330  /* fall through to examine arguments */
2331  }
2332 
2334  (void *) context);
2335 }
2336 
2337 /*
2338  * Given an array of dependency references, eliminate any duplicates.
2339  */
2340 static void
2342 {
2343  ObjectAddress *priorobj;
2344  int oldref,
2345  newrefs;
2346 
2347  /*
2348  * We can't sort if the array has "extra" data, because there's no way to
2349  * keep it in sync. Fortunately that combination of features is not
2350  * needed.
2351  */
2352  Assert(!addrs->extras);
2353 
2354  if (addrs->numrefs <= 1)
2355  return; /* nothing to do */
2356 
2357  /* Sort the refs so that duplicates are adjacent */
2358  qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2360 
2361  /* Remove dups */
2362  priorobj = addrs->refs;
2363  newrefs = 1;
2364  for (oldref = 1; oldref < addrs->numrefs; oldref++)
2365  {
2366  ObjectAddress *thisobj = addrs->refs + oldref;
2367 
2368  if (priorobj->classId == thisobj->classId &&
2369  priorobj->objectId == thisobj->objectId)
2370  {
2371  if (priorobj->objectSubId == thisobj->objectSubId)
2372  continue; /* identical, so drop thisobj */
2373 
2374  /*
2375  * If we have a whole-object reference and a reference to a part
2376  * of the same object, we don't need the whole-object reference
2377  * (for example, we don't need to reference both table foo and
2378  * column foo.bar). The whole-object reference will always appear
2379  * first in the sorted list.
2380  */
2381  if (priorobj->objectSubId == 0)
2382  {
2383  /* replace whole ref with partial */
2384  priorobj->objectSubId = thisobj->objectSubId;
2385  continue;
2386  }
2387  }
2388  /* Not identical, so add thisobj to output set */
2389  priorobj++;
2390  *priorobj = *thisobj;
2391  newrefs++;
2392  }
2393 
2394  addrs->numrefs = newrefs;
2395 }
2396 
2397 /*
2398  * qsort comparator for ObjectAddress items
2399  */
2400 static int
2401 object_address_comparator(const void *a, const void *b)
2402 {
2403  const ObjectAddress *obja = (const ObjectAddress *) a;
2404  const ObjectAddress *objb = (const ObjectAddress *) b;
2405 
2406  /*
2407  * Primary sort key is OID descending. Most of the time, this will result
2408  * in putting newer objects before older ones, which is likely to be the
2409  * right order to delete in.
2410  */
2411  if (obja->objectId > objb->objectId)
2412  return -1;
2413  if (obja->objectId < objb->objectId)
2414  return 1;
2415 
2416  /*
2417  * Next sort on catalog ID, in case identical OIDs appear in different
2418  * catalogs. Sort direction is pretty arbitrary here.
2419  */
2420  if (obja->classId < objb->classId)
2421  return -1;
2422  if (obja->classId > objb->classId)
2423  return 1;
2424 
2425  /*
2426  * Last, sort on object subId.
2427  *
2428  * We sort the subId as an unsigned int so that 0 (the whole object) will
2429  * come first. This is essential for eliminate_duplicate_dependencies,
2430  * and is also the best order for findDependentObjects.
2431  */
2432  if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2433  return -1;
2434  if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2435  return 1;
2436  return 0;
2437 }
2438 
2439 /*
2440  * Routines for handling an expansible array of ObjectAddress items.
2441  *
2442  * new_object_addresses: create a new ObjectAddresses array.
2443  */
2446 {
2447  ObjectAddresses *addrs;
2448 
2449  addrs = palloc(sizeof(ObjectAddresses));
2450 
2451  addrs->numrefs = 0;
2452  addrs->maxrefs = 32;
2453  addrs->refs = (ObjectAddress *)
2454  palloc(addrs->maxrefs * sizeof(ObjectAddress));
2455  addrs->extras = NULL; /* until/unless needed */
2456 
2457  return addrs;
2458 }
2459 
2460 /*
2461  * Add an entry to an ObjectAddresses array.
2462  *
2463  * It is convenient to specify the class by ObjectClass rather than directly
2464  * by catalog OID.
2465  */
2466 static void
2467 add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
2468  ObjectAddresses *addrs)
2469 {
2470  ObjectAddress *item;
2471 
2472  /*
2473  * Make sure object_classes is kept up to date with the ObjectClass enum.
2474  */
2476  "object_classes[] must cover all ObjectClasses");
2477 
2478  /* enlarge array if needed */
2479  if (addrs->numrefs >= addrs->maxrefs)
2480  {
2481  addrs->maxrefs *= 2;
2482  addrs->refs = (ObjectAddress *)
2483  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2484  Assert(!addrs->extras);
2485  }
2486  /* record this item */
2487  item = addrs->refs + addrs->numrefs;
2488  item->classId = object_classes[oclass];
2489  item->objectId = objectId;
2490  item->objectSubId = subId;
2491  addrs->numrefs++;
2492 }
2493 
2494 /*
2495  * Add an entry to an ObjectAddresses array.
2496  *
2497  * As above, but specify entry exactly.
2498  */
2499 void
2501  ObjectAddresses *addrs)
2502 {
2503  ObjectAddress *item;
2504 
2505  /* enlarge array if needed */
2506  if (addrs->numrefs >= addrs->maxrefs)
2507  {
2508  addrs->maxrefs *= 2;
2509  addrs->refs = (ObjectAddress *)
2510  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2511  Assert(!addrs->extras);
2512  }
2513  /* record this item */
2514  item = addrs->refs + addrs->numrefs;
2515  *item = *object;
2516  addrs->numrefs++;
2517 }
2518 
2519 /*
2520  * Add an entry to an ObjectAddresses array.
2521  *
2522  * As above, but specify entry exactly and provide some "extra" data too.
2523  */
2524 static void
2526  const ObjectAddressExtra *extra,
2527  ObjectAddresses *addrs)
2528 {
2529  ObjectAddress *item;
2530  ObjectAddressExtra *itemextra;
2531 
2532  /* allocate extra space if first time */
2533  if (!addrs->extras)
2534  addrs->extras = (ObjectAddressExtra *)
2535  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2536 
2537  /* enlarge array if needed */
2538  if (addrs->numrefs >= addrs->maxrefs)
2539  {
2540  addrs->maxrefs *= 2;
2541  addrs->refs = (ObjectAddress *)
2542  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2543  addrs->extras = (ObjectAddressExtra *)
2544  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2545  }
2546  /* record this item */
2547  item = addrs->refs + addrs->numrefs;
2548  *item = *object;
2549  itemextra = addrs->extras + addrs->numrefs;
2550  *itemextra = *extra;
2551  addrs->numrefs++;
2552 }
2553 
2554 /*
2555  * Test whether an object is present in an ObjectAddresses array.
2556  *
2557  * We return "true" if object is a subobject of something in the array, too.
2558  */
2559 bool
2561  const ObjectAddresses *addrs)
2562 {
2563  int i;
2564 
2565  for (i = addrs->numrefs - 1; i >= 0; i--)
2566  {
2567  const ObjectAddress *thisobj = addrs->refs + i;
2568 
2569  if (object->classId == thisobj->classId &&
2570  object->objectId == thisobj->objectId)
2571  {
2572  if (object->objectSubId == thisobj->objectSubId ||
2573  thisobj->objectSubId == 0)
2574  return true;
2575  }
2576  }
2577 
2578  return false;
2579 }
2580 
2581 /*
2582  * As above, except that if the object is present then also OR the given
2583  * flags into its associated extra data (which must exist).
2584  */
2585 static bool
2587  int flags,
2588  ObjectAddresses *addrs)
2589 {
2590  bool result = false;
2591  int i;
2592 
2593  for (i = addrs->numrefs - 1; i >= 0; i--)
2594  {
2595  ObjectAddress *thisobj = addrs->refs + i;
2596 
2597  if (object->classId == thisobj->classId &&
2598  object->objectId == thisobj->objectId)
2599  {
2600  if (object->objectSubId == thisobj->objectSubId)
2601  {
2602  ObjectAddressExtra *thisextra = addrs->extras + i;
2603 
2604  thisextra->flags |= flags;
2605  result = true;
2606  }
2607  else if (thisobj->objectSubId == 0)
2608  {
2609  /*
2610  * We get here if we find a need to delete a column after
2611  * having already decided to drop its whole table. Obviously
2612  * we no longer need to drop the subobject, so report that we
2613  * found the subobject in the array. But don't plaster its
2614  * flags on the whole object.
2615  */
2616  result = true;
2617  }
2618  else if (object->objectSubId == 0)
2619  {
2620  /*
2621  * We get here if we find a need to delete a whole table after
2622  * having already decided to drop one of its columns. We
2623  * can't report that the whole object is in the array, but we
2624  * should mark the subobject with the whole object's flags.
2625  *
2626  * It might seem attractive to physically delete the column's
2627  * array entry, or at least mark it as no longer needing
2628  * separate deletion. But that could lead to, e.g., dropping
2629  * the column's datatype before we drop the table, which does
2630  * not seem like a good idea. This is a very rare situation
2631  * in practice, so we just take the hit of doing a separate
2632  * DROP COLUMN action even though we know we're gonna delete
2633  * the table later.
2634  *
2635  * What we can do, though, is mark this as a subobject so that
2636  * we don't report it separately, which is confusing because
2637  * it's unpredictable whether it happens or not. But do so
2638  * only if flags != 0 (flags == 0 is a read-only probe).
2639  *
2640  * Because there could be other subobjects of this object in
2641  * the array, this case means we always have to loop through
2642  * the whole array; we cannot exit early on a match.
2643  */
2644  ObjectAddressExtra *thisextra = addrs->extras + i;
2645 
2646  if (flags)
2647  thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2648  }
2649  }
2650  }
2651 
2652  return result;
2653 }
2654 
2655 /*
2656  * Similar to above, except we search an ObjectAddressStack.
2657  */
2658 static bool
2660  int flags,
2661  ObjectAddressStack *stack)
2662 {
2663  bool result = false;
2664  ObjectAddressStack *stackptr;
2665 
2666  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2667  {
2668  const ObjectAddress *thisobj = stackptr->object;
2669 
2670  if (object->classId == thisobj->classId &&
2671  object->objectId == thisobj->objectId)
2672  {
2673  if (object->objectSubId == thisobj->objectSubId)
2674  {
2675  stackptr->flags |= flags;
2676  result = true;
2677  }
2678  else if (thisobj->objectSubId == 0)
2679  {
2680  /*
2681  * We're visiting a column with whole table already on stack.
2682  * As in object_address_present_add_flags(), we can skip
2683  * further processing of the subobject, but we don't want to
2684  * propagate flags for the subobject to the whole object.
2685  */
2686  result = true;
2687  }
2688  else if (object->objectSubId == 0)
2689  {
2690  /*
2691  * We're visiting a table with column already on stack. As in
2692  * object_address_present_add_flags(), we should propagate
2693  * flags for the whole object to each of its subobjects.
2694  */
2695  if (flags)
2696  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2697  }
2698  }
2699  }
2700 
2701  return result;
2702 }
2703 
2704 /*
2705  * Record multiple dependencies from an ObjectAddresses array, after first
2706  * removing any duplicates.
2707  */
2708 void
2710  ObjectAddresses *referenced,
2711  DependencyType behavior)
2712 {
2714  recordMultipleDependencies(depender,
2715  referenced->refs, referenced->numrefs,
2716  behavior);
2717 }
2718 
2719 /*
2720  * Sort the items in an ObjectAddresses array.
2721  *
2722  * The major sort key is OID-descending, so that newer objects will be listed
2723  * first in most cases. This is primarily useful for ensuring stable outputs
2724  * from regression tests; it's not recommended if the order of the objects is
2725  * determined by user input, such as the order of targets in a DROP command.
2726  */
2727 void
2729 {
2730  if (addrs->numrefs > 1)
2731  qsort((void *) addrs->refs, addrs->numrefs,
2732  sizeof(ObjectAddress),
2734 }
2735 
2736 /*
2737  * Clean up when done with an ObjectAddresses array.
2738  */
2739 void
2741 {
2742  pfree(addrs->refs);
2743  if (addrs->extras)
2744  pfree(addrs->extras);
2745  pfree(addrs);
2746 }
2747 
2748 /*
2749  * Determine the class of a given object identified by objectAddress.
2750  *
2751  * This function is essentially the reverse mapping for the object_classes[]
2752  * table. We implement it as a function because the OIDs aren't consecutive.
2753  */
2756 {
2757  /* only pg_class entries can have nonzero objectSubId */
2758  if (object->classId != RelationRelationId &&
2759  object->objectSubId != 0)
2760  elog(ERROR, "invalid non-zero objectSubId for object class %u",
2761  object->classId);
2762 
2763  switch (object->classId)
2764  {
2765  case RelationRelationId:
2766  /* caller must check objectSubId */
2767  return OCLASS_CLASS;
2768 
2769  case ProcedureRelationId:
2770  return OCLASS_PROC;
2771 
2772  case TypeRelationId:
2773  return OCLASS_TYPE;
2774 
2775  case CastRelationId:
2776  return OCLASS_CAST;
2777 
2778  case CollationRelationId:
2779  return OCLASS_COLLATION;
2780 
2781  case ConstraintRelationId:
2782  return OCLASS_CONSTRAINT;
2783 
2784  case ConversionRelationId:
2785  return OCLASS_CONVERSION;
2786 
2787  case AttrDefaultRelationId:
2788  return OCLASS_DEFAULT;
2789 
2790  case LanguageRelationId:
2791  return OCLASS_LANGUAGE;
2792 
2793  case LargeObjectRelationId:
2794  return OCLASS_LARGEOBJECT;
2795 
2796  case OperatorRelationId:
2797  return OCLASS_OPERATOR;
2798 
2799  case OperatorClassRelationId:
2800  return OCLASS_OPCLASS;
2801 
2802  case OperatorFamilyRelationId:
2803  return OCLASS_OPFAMILY;
2804 
2805  case AccessMethodRelationId:
2806  return OCLASS_AM;
2807 
2808  case AccessMethodOperatorRelationId:
2809  return OCLASS_AMOP;
2810 
2811  case AccessMethodProcedureRelationId:
2812  return OCLASS_AMPROC;
2813 
2814  case RewriteRelationId:
2815  return OCLASS_REWRITE;
2816 
2817  case TriggerRelationId:
2818  return OCLASS_TRIGGER;
2819 
2820  case NamespaceRelationId:
2821  return OCLASS_SCHEMA;
2822 
2823  case StatisticExtRelationId:
2824  return OCLASS_STATISTIC_EXT;
2825 
2826  case TSParserRelationId:
2827  return OCLASS_TSPARSER;
2828 
2829  case TSDictionaryRelationId:
2830  return OCLASS_TSDICT;
2831 
2832  case TSTemplateRelationId:
2833  return OCLASS_TSTEMPLATE;
2834 
2835  case TSConfigRelationId:
2836  return OCLASS_TSCONFIG;
2837 
2838  case AuthIdRelationId:
2839  return OCLASS_ROLE;
2840 
2841  case DatabaseRelationId:
2842  return OCLASS_DATABASE;
2843 
2844  case TableSpaceRelationId:
2845  return OCLASS_TBLSPACE;
2846 
2847  case ForeignDataWrapperRelationId:
2848  return OCLASS_FDW;
2849 
2850  case ForeignServerRelationId:
2851  return OCLASS_FOREIGN_SERVER;
2852 
2853  case UserMappingRelationId:
2854  return OCLASS_USER_MAPPING;
2855 
2856  case DefaultAclRelationId:
2857  return OCLASS_DEFACL;
2858 
2859  case ExtensionRelationId:
2860  return OCLASS_EXTENSION;
2861 
2862  case EventTriggerRelationId:
2863  return OCLASS_EVENT_TRIGGER;
2864 
2865  case PolicyRelationId:
2866  return OCLASS_POLICY;
2867 
2868  case PublicationNamespaceRelationId:
2870 
2871  case PublicationRelationId:
2872  return OCLASS_PUBLICATION;
2873 
2874  case PublicationRelRelationId:
2875  return OCLASS_PUBLICATION_REL;
2876 
2877  case SubscriptionRelationId:
2878  return OCLASS_SUBSCRIPTION;
2879 
2880  case TransformRelationId:
2881  return OCLASS_TRANSFORM;
2882  }
2883 
2884  /* shouldn't get here */
2885  elog(ERROR, "unrecognized object class: %u", object->classId);
2886  return OCLASS_CLASS; /* keep compiler quiet */
2887 }
2888 
2889 /*
2890  * delete initial ACL for extension objects
2891  */
2892 static void
2894 {
2895  Relation relation;
2896  ScanKeyData key[3];
2897  SysScanDesc scan;
2898  HeapTuple oldtuple;
2899 
2900  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2901 
2902  ScanKeyInit(&key[0],
2903  Anum_pg_init_privs_objoid,
2904  BTEqualStrategyNumber, F_OIDEQ,
2906  ScanKeyInit(&key[1],
2907  Anum_pg_init_privs_classoid,
2908  BTEqualStrategyNumber, F_OIDEQ,
2910  ScanKeyInit(&key[2],
2911  Anum_pg_init_privs_objsubid,
2912  BTEqualStrategyNumber, F_INT4EQ,
2914 
2915  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
2916  NULL, 3, key);
2917 
2918  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
2919  CatalogTupleDelete(relation, &oldtuple->t_self);
2920 
2921  systable_endscan(scan);
2922 
2923  table_close(relation, RowExclusiveLock);
2924 }
#define InvalidAttrNumber
Definition: attnum.h:23
signed int int32
Definition: c.h:429
#define ngettext(s, p, n)
Definition: c.h:1179
#define lengthof(array)
Definition: c.h:734
#define MemSet(start, val, len)
Definition: c.h:1008
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define OidIsValid(objectId)
Definition: c.h:710
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:307
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:326
static bool object_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddresses *addrs)
Definition: dependency.c:2586
#define DEPFLAG_PARTITION
Definition: dependency.c:103
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:374
struct ObjectAddressStack ObjectAddressStack
static void add_exact_object_address_extra(const ObjectAddress *object, const ObjectAddressExtra *extra, ObjectAddresses *addrs)
Definition: dependency.c:2525
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2709
static void DropObjectById(const ObjectAddress *object)
Definition: dependency.c:1226
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2401
void sort_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2728
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1387
static bool stack_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddressStack *stack)
Definition: dependency.c:2659
#define DEPFLAG_IS_PART
Definition: dependency.c:106
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1732
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2341
void AcquireDeletionLock(const ObjectAddress *object, int flags)
Definition: dependency.c:1532
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2755
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:315
static void deleteOneObject(const ObjectAddress *object, Relation *depRel, int32 flags)
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2893
#define MAX_REPORTED_DEPS
#define DEPFLAG_ORIGINAL
Definition: dependency.c:99
static const Oid object_classes[]
Definition: dependency.c:147
static void reportDependentObjects(const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
Definition: dependency.c:1016
void ReleaseDeletionLock(const ObjectAddress *object)
Definition: dependency.c:1561
#define DEPFLAG_AUTO
Definition: dependency.c:101
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
Definition: dependency.c:1629
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1586
static void findDependentObjects(const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
Definition: dependency.c:474
#define DEPFLAG_REVERSE
Definition: dependency.c:105
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2560
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2445
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2500
#define DEPFLAG_NORMAL
Definition: dependency.c:100
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:107
#define DEPFLAG_EXTENSION
Definition: dependency.c:104
#define DEPFLAG_INTERNAL
Definition: dependency.c:102
static void deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel, int flags)
Definition: dependency.c:227
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2467
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2740
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:138
DependencyType
Definition: dependency.h:32
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_AUTO_EXTENSION
Definition: dependency.h:39
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
@ DEPENDENCY_EXTENSION
Definition: dependency.h:38
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:139
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
#define PERFORM_DELETION_SKIP_ORIGINAL
Definition: dependency.h:137
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134
#define LAST_OCLASS
Definition: dependency.h:131
ObjectClass
Definition: dependency.h:89
@ OCLASS_OPERATOR
Definition: dependency.h:100
@ OCLASS_LARGEOBJECT
Definition: dependency.h:99
@ OCLASS_FDW
Definition: dependency.h:117
@ OCLASS_OPFAMILY
Definition: dependency.h:102
@ OCLASS_DEFACL
Definition: dependency.h:120
@ OCLASS_TSPARSER
Definition: dependency.h:110
@ OCLASS_TRIGGER
Definition: dependency.h:107
@ OCLASS_DEFAULT
Definition: dependency.h:97
@ OCLASS_TSTEMPLATE
Definition: dependency.h:112
@ OCLASS_AMPROC
Definition: dependency.h:105
@ OCLASS_TBLSPACE
Definition: dependency.h:116
@ OCLASS_TSCONFIG
Definition: dependency.h:113
@ OCLASS_TYPE
Definition: dependency.h:92
@ OCLASS_LANGUAGE
Definition: dependency.h:98
@ OCLASS_CAST
Definition: dependency.h:93
@ OCLASS_SUBSCRIPTION
Definition: dependency.h:127
@ OCLASS_PUBLICATION_NAMESPACE
Definition: dependency.h:125
@ OCLASS_EXTENSION
Definition: dependency.h:121
@ OCLASS_COLLATION
Definition: dependency.h:94
@ OCLASS_FOREIGN_SERVER
Definition: dependency.h:118
@ OCLASS_REWRITE
Definition: dependency.h:106
@ OCLASS_STATISTIC_EXT
Definition: dependency.h:109
@ OCLASS_PROC
Definition: dependency.h:91
@ OCLASS_OPCLASS
Definition: dependency.h:101
@ OCLASS_CONVERSION
Definition: dependency.h:96
@ OCLASS_DATABASE
Definition: dependency.h:115
@ OCLASS_SCHEMA
Definition: dependency.h:108
@ OCLASS_EVENT_TRIGGER
Definition: dependency.h:122
@ OCLASS_CLASS
Definition: dependency.h:90
@ OCLASS_TRANSFORM
Definition: dependency.h:128
@ OCLASS_ROLE
Definition: dependency.h:114
@ OCLASS_CONSTRAINT
Definition: dependency.h:95
@ OCLASS_POLICY
Definition: dependency.h:123
@ OCLASS_USER_MAPPING
Definition: dependency.h:119
@ OCLASS_PUBLICATION_REL
Definition: dependency.h:126
@ OCLASS_AM
Definition: dependency.h:103
@ OCLASS_TSDICT
Definition: dependency.h:111
@ OCLASS_PUBLICATION
Definition: dependency.h:124
@ OCLASS_AMOP
Definition: dependency.h:104
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1014
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
bool message_level_is_interesting(int elevel)
Definition: elog.c:265
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
int errdetail_log(const char *fmt,...)
Definition: elog.c:1085
#define _(x)
Definition: elog.c:89
#define DEBUG2
Definition: elog.h:23
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define NOTICE
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:143
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
bool trackDroppedObjectsNeeded(void)
bool EventTriggerSupportsObjectClass(ObjectClass objclass)
bool creating_extension
Definition: extension.c:71
Oid CurrentExtensionObject
Definition: extension.c:72
void RemoveExtensionById(Oid extId)
Definition: extension.c:1878
void RemoveFunctionById(Oid funcOid)
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
bool systable_recheck_tuple(SysScanDesc sysscan, HeapTuple tup)
Definition: genam.c:564
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1654
void RemoveAttrDefaultById(Oid attrdefId)
Definition: heap.c:1822
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1895
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2122
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_delete_first(List *list)
Definition: list.c:902
List * lcons(void *datum, List *list)
Definition: list.c:474
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:977
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:998
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define RowExclusiveLock
Definition: lockdefs.h:38
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2678
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2468
void pfree(void *pointer)
Definition: mcxt.c:1169
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
void * palloc(Size size)
Definition: mcxt.c:1062
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2375
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
#define QTW_EXAMINE_SORTGROUP
Definition: nodeFuncs.h:28
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
@ CMD_INSERT
Definition: nodes.h:688
@ CMD_UPDATE
Definition: nodes.h:687
@ T_RangeTblEntry
Definition: nodes.h:462
#define InvokeObjectDropHookArg(classId, objectId, subId, dropflags)
Definition: objectaccess.h:162
AttrNumber get_object_attnum_oid(Oid class_id)
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
int get_object_catcache_oid(Oid class_id)
Oid get_object_oid_index(Oid class_id)
const char * get_object_class_descr(Oid class_id)
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:364
@ RTE_JOIN
Definition: parsenodes.h:992
@ RTE_RELATION
Definition: parsenodes.h:990
DropBehavior
Definition: parsenodes.h:1860
@ DROP_CASCADE
Definition: parsenodes.h:1862
@ DROP_RESTRICT
Definition: parsenodes.h:1861
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
void RemoveConstraintById(Oid conId)
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:56
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void LargeObjectDrop(Oid loid)
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define lfirst_int(lc)
Definition: pg_list.h:170
#define list_make1(x1)
Definition: pg_list.h:206
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define lfirst_oid(lc)
Definition: pg_list.h:171
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1001
void RemovePolicyById(Oid policy_id)
Definition: policy.c:335
#define qsort(a, b, c, d)
Definition: port.h:495
#define DatumGetObjectId(X)
Definition: postgres.h:544
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define Int32GetDatum(X)
Definition: postgres.h:523
unsigned int Oid
Definition: postgres_ext.h:31
void RemovePublicationSchemaById(Oid psoid)
void RemovePublicationById(Oid pubid)
void RemovePublicationRelById(Oid proid)
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:39
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:522
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:526
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:728
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Oid aggfnoid
Definition: primnodes.h:323
Oid cycle_mark_collation
Definition: parsenodes.h:1505
Oid resultcollid
Definition: primnodes.h:883
Oid resulttype
Definition: primnodes.h:881
Oid constcollid
Definition: primnodes.h:217
Oid consttype
Definition: primnodes.h:215
Datum constvalue
Definition: primnodes.h:219
bool constisnull
Definition: primnodes.h:220
AttrNumber fieldnum
Definition: primnodes.h:809
Oid resulttype
Definition: primnodes.h:810
Oid resultcollid
Definition: primnodes.h:813
Expr * arg
Definition: primnodes.h:808
Oid resulttype
Definition: primnodes.h:840
List * fieldnums
Definition: primnodes.h:839
Oid funcid
Definition: primnodes.h:495
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:51
Definition: nodes.h:540
ObjectAddress obj
Definition: dependency.c:132
ObjectAddress dependee
Definition: dependency.c:95
const ObjectAddress * object
Definition: dependency.c:124
struct ObjectAddressStack * next
Definition: dependency.c:126
ObjectAddressExtra * extras
Definition: dependency.c:114
ObjectAddress * refs
Definition: dependency.c:113
Oid opno
Definition: primnodes.h:542
Oid paramtype
Definition: primnodes.h:269
Oid paramcollid
Definition: primnodes.h:271
List * constraintDeps
Definition: parsenodes.h:179
List * rtable
Definition: parsenodes.h:146
int resultRelation
Definition: parsenodes.h:129
CmdType commandType
Definition: parsenodes.h:119
List * targetList
Definition: parsenodes.h:149
NodeTag type
Definition: parsenodes.h:1005
List * joinaliasvars
Definition: parsenodes.h:1082
RTEKind rtekind
Definition: parsenodes.h:1007
List * funccolcollations
Definition: parsenodes.h:1192
Oid resultcollid
Definition: primnodes.h:863
Oid resulttype
Definition: primnodes.h:861
List * opfamilies
Definition: primnodes.h:1118
Oid row_typeid
Definition: primnodes.h:1069
Oid refcontainertype
Definition: primnodes.h:439
List * coltypes
Definition: primnodes.h:90
List * colcollations
Definition: primnodes.h:92
AttrNumber resno
Definition: primnodes.h:1456
bool resjunk
Definition: primnodes.h:1462
Definition: primnodes.h:187
AttrNumber varattno
Definition: primnodes.h:191
int varno
Definition: primnodes.h:189
Index varlevelsup
Definition: primnodes.h:196
Oid endInRangeFunc
Definition: parsenodes.h:1397
Oid startInRangeFunc
Definition: parsenodes.h:1396
Oid winfnoid
Definition: primnodes.h:386
ObjectAddresses * addrs
Definition: dependency.c:139
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1150
@ TSDICTOID
Definition: syscache.h:106
@ TYPEOID
Definition: syscache.h:112
@ OPEROID
Definition: syscache.h:72
@ PROCOID
Definition: syscache.h:77
@ RELOID
Definition: syscache.h:87
@ TSCONFIGOID
Definition: syscache.h:104
@ NAMESPACEOID
Definition: syscache.h:70
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:186
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1332
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1061
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:653
void CommandCounterIncrement(void)
Definition: xact.c:1073