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