LCOV - code coverage report
Current view: top level - src/backend/catalog - dependency.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 724 807 89.7 %
Date: 2019-06-19 14:06:47 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13