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

Generated by: LCOV version 1.11