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

Generated by: LCOV version 1.16