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

Generated by: LCOV version 1.14