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