LCOV - code coverage report
Current view: top level - src/backend/catalog - pg_shdepend.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 336 417 80.6 %
Date: 2019-11-22 07:06:56 Functions: 19 19 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_shdepend.c
       4             :  *    routines to support manipulation of the pg_shdepend relation
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/catalog/pg_shdepend.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/indexing.h"
      24             : #include "catalog/pg_authid.h"
      25             : #include "catalog/pg_collation.h"
      26             : #include "catalog/pg_conversion.h"
      27             : #include "catalog/pg_database.h"
      28             : #include "catalog/pg_default_acl.h"
      29             : #include "catalog/pg_event_trigger.h"
      30             : #include "catalog/pg_extension.h"
      31             : #include "catalog/pg_foreign_data_wrapper.h"
      32             : #include "catalog/pg_foreign_server.h"
      33             : #include "catalog/pg_language.h"
      34             : #include "catalog/pg_largeobject.h"
      35             : #include "catalog/pg_largeobject_metadata.h"
      36             : #include "catalog/pg_namespace.h"
      37             : #include "catalog/pg_opclass.h"
      38             : #include "catalog/pg_operator.h"
      39             : #include "catalog/pg_opfamily.h"
      40             : #include "catalog/pg_proc.h"
      41             : #include "catalog/pg_shdepend.h"
      42             : #include "catalog/pg_statistic_ext.h"
      43             : #include "catalog/pg_subscription.h"
      44             : #include "catalog/pg_tablespace.h"
      45             : #include "catalog/pg_ts_config.h"
      46             : #include "catalog/pg_ts_dict.h"
      47             : #include "catalog/pg_type.h"
      48             : #include "catalog/pg_user_mapping.h"
      49             : #include "commands/alter.h"
      50             : #include "commands/collationcmds.h"
      51             : #include "commands/conversioncmds.h"
      52             : #include "commands/dbcommands.h"
      53             : #include "commands/defrem.h"
      54             : #include "commands/event_trigger.h"
      55             : #include "commands/extension.h"
      56             : #include "commands/policy.h"
      57             : #include "commands/proclang.h"
      58             : #include "commands/publicationcmds.h"
      59             : #include "commands/schemacmds.h"
      60             : #include "commands/subscriptioncmds.h"
      61             : #include "commands/tablecmds.h"
      62             : #include "commands/typecmds.h"
      63             : #include "miscadmin.h"
      64             : #include "storage/lmgr.h"
      65             : #include "utils/acl.h"
      66             : #include "utils/fmgroids.h"
      67             : #include "utils/syscache.h"
      68             : 
      69             : typedef enum
      70             : {
      71             :     LOCAL_OBJECT,
      72             :     SHARED_OBJECT,
      73             :     REMOTE_OBJECT
      74             : } SharedDependencyObjectType;
      75             : 
      76             : typedef struct
      77             : {
      78             :     ObjectAddress object;
      79             :     char        deptype;
      80             :     SharedDependencyObjectType objtype;
      81             : } ShDependObjectInfo;
      82             : 
      83             : static void getOidListDiff(Oid *list1, int *nlist1, Oid *list2, int *nlist2);
      84             : static Oid  classIdGetDbId(Oid classId);
      85             : static void shdepChangeDep(Relation sdepRel,
      86             :                            Oid classid, Oid objid, int32 objsubid,
      87             :                            Oid refclassid, Oid refobjid,
      88             :                            SharedDependencyType deptype);
      89             : static void shdepAddDependency(Relation sdepRel,
      90             :                                Oid classId, Oid objectId, int32 objsubId,
      91             :                                Oid refclassId, Oid refobjId,
      92             :                                SharedDependencyType deptype);
      93             : static void shdepDropDependency(Relation sdepRel,
      94             :                                 Oid classId, Oid objectId, int32 objsubId,
      95             :                                 bool drop_subobjects,
      96             :                                 Oid refclassId, Oid refobjId,
      97             :                                 SharedDependencyType deptype);
      98             : static void storeObjectDescription(StringInfo descs,
      99             :                                    SharedDependencyObjectType type,
     100             :                                    ObjectAddress *object,
     101             :                                    SharedDependencyType deptype,
     102             :                                    int count);
     103             : static bool isSharedObjectPinned(Oid classId, Oid objectId, Relation sdepRel);
     104             : 
     105             : 
     106             : /*
     107             :  * recordSharedDependencyOn
     108             :  *
     109             :  * Record a dependency between 2 objects via their respective ObjectAddresses.
     110             :  * The first argument is the dependent object, the second the one it
     111             :  * references (which must be a shared object).
     112             :  *
     113             :  * This locks the referenced object and makes sure it still exists.
     114             :  * Then it creates an entry in pg_shdepend.  The lock is kept until
     115             :  * the end of the transaction.
     116             :  *
     117             :  * Dependencies on pinned objects are not recorded.
     118             :  */
     119             : void
     120      125078 : recordSharedDependencyOn(ObjectAddress *depender,
     121             :                          ObjectAddress *referenced,
     122             :                          SharedDependencyType deptype)
     123             : {
     124             :     Relation    sdepRel;
     125             : 
     126             :     /*
     127             :      * Objects in pg_shdepend can't have SubIds.
     128             :      */
     129             :     Assert(depender->objectSubId == 0);
     130             :     Assert(referenced->objectSubId == 0);
     131             : 
     132             :     /*
     133             :      * During bootstrap, do nothing since pg_shdepend may not exist yet.
     134             :      * initdb will fill in appropriate pg_shdepend entries after bootstrap.
     135             :      */
     136      125078 :     if (IsBootstrapProcessingMode())
     137           0 :         return;
     138             : 
     139      125078 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     140             : 
     141             :     /* If the referenced object is pinned, do nothing. */
     142      125078 :     if (!isSharedObjectPinned(referenced->classId, referenced->objectId,
     143             :                               sdepRel))
     144             :     {
     145        1642 :         shdepAddDependency(sdepRel, depender->classId, depender->objectId,
     146             :                            depender->objectSubId,
     147             :                            referenced->classId, referenced->objectId,
     148             :                            deptype);
     149             :     }
     150             : 
     151      125078 :     table_close(sdepRel, RowExclusiveLock);
     152             : }
     153             : 
     154             : /*
     155             :  * recordDependencyOnOwner
     156             :  *
     157             :  * A convenient wrapper of recordSharedDependencyOn -- register the specified
     158             :  * user as owner of the given object.
     159             :  *
     160             :  * Note: it's the caller's responsibility to ensure that there isn't an owner
     161             :  * entry for the object already.
     162             :  */
     163             : void
     164      124982 : recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
     165             : {
     166             :     ObjectAddress myself,
     167             :                 referenced;
     168             : 
     169      124982 :     myself.classId = classId;
     170      124982 :     myself.objectId = objectId;
     171      124982 :     myself.objectSubId = 0;
     172             : 
     173      124982 :     referenced.classId = AuthIdRelationId;
     174      124982 :     referenced.objectId = owner;
     175      124982 :     referenced.objectSubId = 0;
     176             : 
     177      124982 :     recordSharedDependencyOn(&myself, &referenced, SHARED_DEPENDENCY_OWNER);
     178      124982 : }
     179             : 
     180             : /*
     181             :  * shdepChangeDep
     182             :  *
     183             :  * Update shared dependency records to account for an updated referenced
     184             :  * object.  This is an internal workhorse for operations such as changing
     185             :  * an object's owner.
     186             :  *
     187             :  * There must be no more than one existing entry for the given dependent
     188             :  * object and dependency type!  So in practice this can only be used for
     189             :  * updating SHARED_DEPENDENCY_OWNER entries, which should have that property.
     190             :  *
     191             :  * If there is no previous entry, we assume it was referencing a PINned
     192             :  * object, so we create a new entry.  If the new referenced object is
     193             :  * PINned, we don't create an entry (and drop the old one, if any).
     194             :  *
     195             :  * sdepRel must be the pg_shdepend relation, already opened and suitably
     196             :  * locked.
     197             :  */
     198             : static void
     199         332 : shdepChangeDep(Relation sdepRel,
     200             :                Oid classid, Oid objid, int32 objsubid,
     201             :                Oid refclassid, Oid refobjid,
     202             :                SharedDependencyType deptype)
     203             : {
     204         332 :     Oid         dbid = classIdGetDbId(classid);
     205         332 :     HeapTuple   oldtup = NULL;
     206             :     HeapTuple   scantup;
     207             :     ScanKeyData key[4];
     208             :     SysScanDesc scan;
     209             : 
     210             :     /*
     211             :      * Make sure the new referenced object doesn't go away while we record the
     212             :      * dependency.
     213             :      */
     214         332 :     shdepLockAndCheckObject(refclassid, refobjid);
     215             : 
     216             :     /*
     217             :      * Look for a previous entry
     218             :      */
     219         332 :     ScanKeyInit(&key[0],
     220             :                 Anum_pg_shdepend_dbid,
     221             :                 BTEqualStrategyNumber, F_OIDEQ,
     222             :                 ObjectIdGetDatum(dbid));
     223         332 :     ScanKeyInit(&key[1],
     224             :                 Anum_pg_shdepend_classid,
     225             :                 BTEqualStrategyNumber, F_OIDEQ,
     226             :                 ObjectIdGetDatum(classid));
     227         332 :     ScanKeyInit(&key[2],
     228             :                 Anum_pg_shdepend_objid,
     229             :                 BTEqualStrategyNumber, F_OIDEQ,
     230             :                 ObjectIdGetDatum(objid));
     231         332 :     ScanKeyInit(&key[3],
     232             :                 Anum_pg_shdepend_objsubid,
     233             :                 BTEqualStrategyNumber, F_INT4EQ,
     234             :                 Int32GetDatum(objsubid));
     235             : 
     236         332 :     scan = systable_beginscan(sdepRel, SharedDependDependerIndexId, true,
     237             :                               NULL, 4, key);
     238             : 
     239         868 :     while ((scantup = systable_getnext(scan)) != NULL)
     240             :     {
     241             :         /* Ignore if not of the target dependency type */
     242         204 :         if (((Form_pg_shdepend) GETSTRUCT(scantup))->deptype != deptype)
     243          14 :             continue;
     244             :         /* Caller screwed up if multiple matches */
     245         190 :         if (oldtup)
     246           0 :             elog(ERROR,
     247             :                  "multiple pg_shdepend entries for object %u/%u/%d deptype %c",
     248             :                  classid, objid, objsubid, deptype);
     249         190 :         oldtup = heap_copytuple(scantup);
     250             :     }
     251             : 
     252         332 :     systable_endscan(scan);
     253             : 
     254         332 :     if (isSharedObjectPinned(refclassid, refobjid, sdepRel))
     255             :     {
     256             :         /* No new entry needed, so just delete existing entry if any */
     257          16 :         if (oldtup)
     258          16 :             CatalogTupleDelete(sdepRel, &oldtup->t_self);
     259             :     }
     260         316 :     else if (oldtup)
     261             :     {
     262             :         /* Need to update existing entry */
     263         174 :         Form_pg_shdepend shForm = (Form_pg_shdepend) GETSTRUCT(oldtup);
     264             : 
     265             :         /* Since oldtup is a copy, we can just modify it in-memory */
     266         174 :         shForm->refclassid = refclassid;
     267         174 :         shForm->refobjid = refobjid;
     268             : 
     269         174 :         CatalogTupleUpdate(sdepRel, &oldtup->t_self, oldtup);
     270             :     }
     271             :     else
     272             :     {
     273             :         /* Need to insert new entry */
     274             :         Datum       values[Natts_pg_shdepend];
     275             :         bool        nulls[Natts_pg_shdepend];
     276             : 
     277         142 :         memset(nulls, false, sizeof(nulls));
     278             : 
     279         142 :         values[Anum_pg_shdepend_dbid - 1] = ObjectIdGetDatum(dbid);
     280         142 :         values[Anum_pg_shdepend_classid - 1] = ObjectIdGetDatum(classid);
     281         142 :         values[Anum_pg_shdepend_objid - 1] = ObjectIdGetDatum(objid);
     282         142 :         values[Anum_pg_shdepend_objsubid - 1] = Int32GetDatum(objsubid);
     283             : 
     284         142 :         values[Anum_pg_shdepend_refclassid - 1] = ObjectIdGetDatum(refclassid);
     285         142 :         values[Anum_pg_shdepend_refobjid - 1] = ObjectIdGetDatum(refobjid);
     286         142 :         values[Anum_pg_shdepend_deptype - 1] = CharGetDatum(deptype);
     287             : 
     288             :         /*
     289             :          * we are reusing oldtup just to avoid declaring a new variable, but
     290             :          * it's certainly a new tuple
     291             :          */
     292         142 :         oldtup = heap_form_tuple(RelationGetDescr(sdepRel), values, nulls);
     293         142 :         CatalogTupleInsert(sdepRel, oldtup);
     294             :     }
     295             : 
     296         332 :     if (oldtup)
     297         332 :         heap_freetuple(oldtup);
     298         332 : }
     299             : 
     300             : /*
     301             :  * changeDependencyOnOwner
     302             :  *
     303             :  * Update the shared dependencies to account for the new owner.
     304             :  *
     305             :  * Note: we don't need an objsubid argument because only whole objects
     306             :  * have owners.
     307             :  */
     308             : void
     309         332 : changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
     310             : {
     311             :     Relation    sdepRel;
     312             : 
     313         332 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     314             : 
     315             :     /* Adjust the SHARED_DEPENDENCY_OWNER entry */
     316         332 :     shdepChangeDep(sdepRel,
     317             :                    classId, objectId, 0,
     318             :                    AuthIdRelationId, newOwnerId,
     319             :                    SHARED_DEPENDENCY_OWNER);
     320             : 
     321             :     /*----------
     322             :      * There should never be a SHARED_DEPENDENCY_ACL entry for the owner,
     323             :      * so get rid of it if there is one.  This can happen if the new owner
     324             :      * was previously granted some rights to the object.
     325             :      *
     326             :      * This step is analogous to aclnewowner's removal of duplicate entries
     327             :      * in the ACL.  We have to do it to handle this scenario:
     328             :      *      A grants some rights on an object to B
     329             :      *      ALTER OWNER changes the object's owner to B
     330             :      *      ALTER OWNER changes the object's owner to C
     331             :      * The third step would remove all mention of B from the object's ACL,
     332             :      * but we'd still have a SHARED_DEPENDENCY_ACL for B if we did not do
     333             :      * things this way.
     334             :      *
     335             :      * The rule against having a SHARED_DEPENDENCY_ACL entry for the owner
     336             :      * allows us to fix things up in just this one place, without having
     337             :      * to make the various ALTER OWNER routines each know about it.
     338             :      *----------
     339             :      */
     340         332 :     shdepDropDependency(sdepRel, classId, objectId, 0, true,
     341             :                         AuthIdRelationId, newOwnerId,
     342             :                         SHARED_DEPENDENCY_ACL);
     343             : 
     344         332 :     table_close(sdepRel, RowExclusiveLock);
     345         332 : }
     346             : 
     347             : /*
     348             :  * getOidListDiff
     349             :  *      Helper for updateAclDependencies.
     350             :  *
     351             :  * Takes two Oid arrays and removes elements that are common to both arrays,
     352             :  * leaving just those that are in one input but not the other.
     353             :  * We assume both arrays have been sorted and de-duped.
     354             :  */
     355             : static void
     356       41500 : getOidListDiff(Oid *list1, int *nlist1, Oid *list2, int *nlist2)
     357             : {
     358             :     int         in1,
     359             :                 in2,
     360             :                 out1,
     361             :                 out2;
     362             : 
     363       41500 :     in1 = in2 = out1 = out2 = 0;
     364       86050 :     while (in1 < *nlist1 && in2 < *nlist2)
     365             :     {
     366        3050 :         if (list1[in1] == list2[in2])
     367             :         {
     368             :             /* skip over duplicates */
     369        3006 :             in1++;
     370        3006 :             in2++;
     371             :         }
     372          44 :         else if (list1[in1] < list2[in2])
     373             :         {
     374             :             /* list1[in1] is not in list2 */
     375          18 :             list1[out1++] = list1[in1++];
     376             :         }
     377             :         else
     378             :         {
     379             :             /* list2[in2] is not in list1 */
     380          26 :             list2[out2++] = list2[in2++];
     381             :         }
     382             :     }
     383             : 
     384             :     /* any remaining list1 entries are not in list2 */
     385       83226 :     while (in1 < *nlist1)
     386             :     {
     387         226 :         list1[out1++] = list1[in1++];
     388             :     }
     389             : 
     390             :     /* any remaining list2 entries are not in list1 */
     391      124312 :     while (in2 < *nlist2)
     392             :     {
     393       41312 :         list2[out2++] = list2[in2++];
     394             :     }
     395             : 
     396       41500 :     *nlist1 = out1;
     397       41500 :     *nlist2 = out2;
     398       41500 : }
     399             : 
     400             : /*
     401             :  * updateAclDependencies
     402             :  *      Update the pg_shdepend info for an object's ACL during GRANT/REVOKE.
     403             :  *
     404             :  * classId, objectId, objsubId: identify the object whose ACL this is
     405             :  * ownerId: role owning the object
     406             :  * noldmembers, oldmembers: array of roleids appearing in old ACL
     407             :  * nnewmembers, newmembers: array of roleids appearing in new ACL
     408             :  *
     409             :  * We calculate the differences between the new and old lists of roles,
     410             :  * and then insert or delete from pg_shdepend as appropriate.
     411             :  *
     412             :  * Note that we can't just insert all referenced roles blindly during GRANT,
     413             :  * because we would end up with duplicate registered dependencies.  We could
     414             :  * check for existence of the tuples before inserting, but that seems to be
     415             :  * more expensive than what we are doing here.  Likewise we can't just delete
     416             :  * blindly during REVOKE, because the user may still have other privileges.
     417             :  * It is also possible that REVOKE actually adds dependencies, due to
     418             :  * instantiation of a formerly implicit default ACL (although at present,
     419             :  * all such dependencies should be for the owning role, which we ignore here).
     420             :  *
     421             :  * NOTE: Both input arrays must be sorted and de-duped.  (Typically they
     422             :  * are extracted from an ACL array by aclmembers(), which takes care of
     423             :  * both requirements.)  The arrays are pfreed before return.
     424             :  */
     425             : void
     426       41500 : updateAclDependencies(Oid classId, Oid objectId, int32 objsubId,
     427             :                       Oid ownerId,
     428             :                       int noldmembers, Oid *oldmembers,
     429             :                       int nnewmembers, Oid *newmembers)
     430             : {
     431             :     Relation    sdepRel;
     432             :     int         i;
     433             : 
     434             :     /*
     435             :      * Remove entries that are common to both lists; those represent existing
     436             :      * dependencies we don't need to change.
     437             :      *
     438             :      * OK to overwrite the inputs since we'll pfree them anyway.
     439             :      */
     440       41500 :     getOidListDiff(oldmembers, &noldmembers, newmembers, &nnewmembers);
     441             : 
     442       41500 :     if (noldmembers > 0 || nnewmembers > 0)
     443             :     {
     444       40922 :         sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     445             : 
     446             :         /* Add new dependencies that weren't already present */
     447       82260 :         for (i = 0; i < nnewmembers; i++)
     448             :         {
     449       41338 :             Oid         roleid = newmembers[i];
     450             : 
     451             :             /*
     452             :              * Skip the owner: he has an OWNER shdep entry instead. (This is
     453             :              * not just a space optimization; it makes ALTER OWNER easier. See
     454             :              * notes in changeDependencyOnOwner.)
     455             :              */
     456       41338 :             if (roleid == ownerId)
     457       38804 :                 continue;
     458             : 
     459             :             /* Skip pinned roles; they don't need dependency entries */
     460        2534 :             if (isSharedObjectPinned(AuthIdRelationId, roleid, sdepRel))
     461        1646 :                 continue;
     462             : 
     463         888 :             shdepAddDependency(sdepRel, classId, objectId, objsubId,
     464             :                                AuthIdRelationId, roleid,
     465             :                                SHARED_DEPENDENCY_ACL);
     466             :         }
     467             : 
     468             :         /* Drop no-longer-used old dependencies */
     469       41166 :         for (i = 0; i < noldmembers; i++)
     470             :         {
     471         244 :             Oid         roleid = oldmembers[i];
     472             : 
     473             :             /* Skip the owner, same as above */
     474         244 :             if (roleid == ownerId)
     475          30 :                 continue;
     476             : 
     477             :             /* Skip pinned roles */
     478         214 :             if (isSharedObjectPinned(AuthIdRelationId, roleid, sdepRel))
     479           4 :                 continue;
     480             : 
     481         210 :             shdepDropDependency(sdepRel, classId, objectId, objsubId,
     482             :                                 false,  /* exact match on objsubId */
     483             :                                 AuthIdRelationId, roleid,
     484             :                                 SHARED_DEPENDENCY_ACL);
     485             :         }
     486             : 
     487       40922 :         table_close(sdepRel, RowExclusiveLock);
     488             :     }
     489             : 
     490       41500 :     if (oldmembers)
     491        2656 :         pfree(oldmembers);
     492       41500 :     if (newmembers)
     493       41430 :         pfree(newmembers);
     494       41500 : }
     495             : 
     496             : /*
     497             :  * A struct to keep track of dependencies found in other databases.
     498             :  */
     499             : typedef struct
     500             : {
     501             :     Oid         dbOid;
     502             :     int         count;
     503             : } remoteDep;
     504             : 
     505             : /*
     506             :  * qsort comparator for ShDependObjectInfo items
     507             :  */
     508             : static int
     509          76 : shared_dependency_comparator(const void *a, const void *b)
     510             : {
     511          76 :     const ShDependObjectInfo *obja = (const ShDependObjectInfo *) a;
     512          76 :     const ShDependObjectInfo *objb = (const ShDependObjectInfo *) b;
     513             : 
     514             :     /*
     515             :      * Primary sort key is OID ascending.
     516             :      */
     517          76 :     if (obja->object.objectId < objb->object.objectId)
     518          52 :         return -1;
     519          24 :     if (obja->object.objectId > objb->object.objectId)
     520          24 :         return 1;
     521             : 
     522             :     /*
     523             :      * Next sort on catalog ID, in case identical OIDs appear in different
     524             :      * catalogs.  Sort direction is pretty arbitrary here.
     525             :      */
     526           0 :     if (obja->object.classId < objb->object.classId)
     527           0 :         return -1;
     528           0 :     if (obja->object.classId > objb->object.classId)
     529           0 :         return 1;
     530             : 
     531             :     /*
     532             :      * Sort on object subId.
     533             :      *
     534             :      * We sort the subId as an unsigned int so that 0 (the whole object) will
     535             :      * come first.
     536             :      */
     537           0 :     if ((unsigned int) obja->object.objectSubId < (unsigned int) objb->object.objectSubId)
     538           0 :         return -1;
     539           0 :     if ((unsigned int) obja->object.objectSubId > (unsigned int) objb->object.objectSubId)
     540           0 :         return 1;
     541             : 
     542             :     /*
     543             :      * Last, sort on deptype, in case the same object has multiple dependency
     544             :      * types.  (Note that there's no need to consider objtype, as that's
     545             :      * determined by the catalog OID.)
     546             :      */
     547           0 :     if (obja->deptype < objb->deptype)
     548           0 :         return -1;
     549           0 :     if (obja->deptype > objb->deptype)
     550           0 :         return 1;
     551             : 
     552           0 :     return 0;
     553             : }
     554             : 
     555             : /*
     556             :  * checkSharedDependencies
     557             :  *
     558             :  * Check whether there are shared dependency entries for a given shared
     559             :  * object; return true if so.
     560             :  *
     561             :  * In addition, return a string containing a newline-separated list of object
     562             :  * descriptions that depend on the shared object, or NULL if none is found.
     563             :  * We actually return two such strings; the "detail" result is suitable for
     564             :  * returning to the client as an errdetail() string, and is limited in size.
     565             :  * The "detail_log" string is potentially much longer, and should be emitted
     566             :  * to the server log only.
     567             :  *
     568             :  * We can find three different kinds of dependencies: dependencies on objects
     569             :  * of the current database; dependencies on shared objects; and dependencies
     570             :  * on objects local to other databases.  We can (and do) provide descriptions
     571             :  * of the two former kinds of objects, but we can't do that for "remote"
     572             :  * objects, so we just provide a count of them.
     573             :  *
     574             :  * If we find a SHARED_DEPENDENCY_PIN entry, we can error out early.
     575             :  */
     576             : bool
     577         632 : checkSharedDependencies(Oid classId, Oid objectId,
     578             :                         char **detail_msg, char **detail_log_msg)
     579             : {
     580             :     Relation    sdepRel;
     581             :     ScanKeyData key[2];
     582             :     SysScanDesc scan;
     583             :     HeapTuple   tup;
     584         632 :     int         numReportedDeps = 0;
     585         632 :     int         numNotReportedDeps = 0;
     586         632 :     int         numNotReportedDbs = 0;
     587         632 :     List       *remDeps = NIL;
     588             :     ListCell   *cell;
     589             :     ObjectAddress object;
     590             :     ShDependObjectInfo *objects;
     591             :     int         numobjects;
     592             :     int         allocedobjects;
     593             :     StringInfoData descs;
     594             :     StringInfoData alldescs;
     595             : 
     596             :     /*
     597             :      * We limit the number of dependencies reported to the client to
     598             :      * MAX_REPORTED_DEPS, since client software may not deal well with
     599             :      * enormous error strings.  The server log always gets a full report.
     600             :      *
     601             :      * For stability of regression test results, we sort local and shared
     602             :      * objects by OID before reporting them.  We don't worry about the order
     603             :      * in which other databases are reported, though.
     604             :      */
     605             : #define MAX_REPORTED_DEPS 100
     606             : 
     607         632 :     allocedobjects = 128;       /* arbitrary initial array size */
     608         632 :     objects = (ShDependObjectInfo *)
     609         632 :         palloc(allocedobjects * sizeof(ShDependObjectInfo));
     610         632 :     numobjects = 0;
     611         632 :     initStringInfo(&descs);
     612         632 :     initStringInfo(&alldescs);
     613             : 
     614         632 :     sdepRel = table_open(SharedDependRelationId, AccessShareLock);
     615             : 
     616         632 :     ScanKeyInit(&key[0],
     617             :                 Anum_pg_shdepend_refclassid,
     618             :                 BTEqualStrategyNumber, F_OIDEQ,
     619             :                 ObjectIdGetDatum(classId));
     620         632 :     ScanKeyInit(&key[1],
     621             :                 Anum_pg_shdepend_refobjid,
     622             :                 BTEqualStrategyNumber, F_OIDEQ,
     623             :                 ObjectIdGetDatum(objectId));
     624             : 
     625         632 :     scan = systable_beginscan(sdepRel, SharedDependReferenceIndexId, true,
     626             :                               NULL, 2, key);
     627             : 
     628        1388 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     629             :     {
     630         124 :         Form_pg_shdepend sdepForm = (Form_pg_shdepend) GETSTRUCT(tup);
     631             : 
     632             :         /* This case can be dispatched quickly */
     633         124 :         if (sdepForm->deptype == SHARED_DEPENDENCY_PIN)
     634             :         {
     635           0 :             object.classId = classId;
     636           0 :             object.objectId = objectId;
     637           0 :             object.objectSubId = 0;
     638           0 :             ereport(ERROR,
     639             :                     (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
     640             :                      errmsg("cannot drop %s because it is required by the database system",
     641             :                             getObjectDescription(&object))));
     642             :         }
     643             : 
     644         124 :         object.classId = sdepForm->classid;
     645         124 :         object.objectId = sdepForm->objid;
     646         124 :         object.objectSubId = sdepForm->objsubid;
     647             : 
     648             :         /*
     649             :          * If it's a dependency local to this database or it's a shared
     650             :          * object, add it to the objects array.
     651             :          *
     652             :          * If it's a remote dependency, keep track of it so we can report the
     653             :          * number of them later.
     654             :          */
     655         128 :         if (sdepForm->dbid == MyDatabaseId ||
     656           4 :             sdepForm->dbid == InvalidOid)
     657             :         {
     658         124 :             if (numobjects >= allocedobjects)
     659             :             {
     660           0 :                 allocedobjects *= 2;
     661           0 :                 objects = (ShDependObjectInfo *)
     662           0 :                     repalloc(objects,
     663             :                              allocedobjects * sizeof(ShDependObjectInfo));
     664             :             }
     665         124 :             objects[numobjects].object = object;
     666         124 :             objects[numobjects].deptype = sdepForm->deptype;
     667         248 :             objects[numobjects].objtype = (sdepForm->dbid == MyDatabaseId) ?
     668         124 :                 LOCAL_OBJECT : SHARED_OBJECT;
     669         124 :             numobjects++;
     670             :         }
     671             :         else
     672             :         {
     673             :             /* It's not local nor shared, so it must be remote. */
     674             :             remoteDep  *dep;
     675           0 :             bool        stored = false;
     676             : 
     677             :             /*
     678             :              * XXX this info is kept on a simple List.  Maybe it's not good
     679             :              * for performance, but using a hash table seems needlessly
     680             :              * complex.  The expected number of databases is not high anyway,
     681             :              * I suppose.
     682             :              */
     683           0 :             foreach(cell, remDeps)
     684             :             {
     685           0 :                 dep = lfirst(cell);
     686           0 :                 if (dep->dbOid == sdepForm->dbid)
     687             :                 {
     688           0 :                     dep->count++;
     689           0 :                     stored = true;
     690           0 :                     break;
     691             :                 }
     692             :             }
     693           0 :             if (!stored)
     694             :             {
     695           0 :                 dep = (remoteDep *) palloc(sizeof(remoteDep));
     696           0 :                 dep->dbOid = sdepForm->dbid;
     697           0 :                 dep->count = 1;
     698           0 :                 remDeps = lappend(remDeps, dep);
     699             :             }
     700             :         }
     701             :     }
     702             : 
     703         632 :     systable_endscan(scan);
     704             : 
     705         632 :     table_close(sdepRel, AccessShareLock);
     706             : 
     707             :     /*
     708             :      * Sort and report local and shared objects.
     709             :      */
     710         632 :     if (numobjects > 1)
     711          28 :         qsort((void *) objects, numobjects,
     712             :               sizeof(ShDependObjectInfo), shared_dependency_comparator);
     713             : 
     714         756 :     for (int i = 0; i < numobjects; i++)
     715             :     {
     716         124 :         if (numReportedDeps < MAX_REPORTED_DEPS)
     717             :         {
     718         124 :             numReportedDeps++;
     719         372 :             storeObjectDescription(&descs,
     720         124 :                                    objects[i].objtype,
     721         124 :                                    &objects[i].object,
     722         124 :                                    objects[i].deptype,
     723             :                                    0);
     724             :         }
     725             :         else
     726           0 :             numNotReportedDeps++;
     727         372 :         storeObjectDescription(&alldescs,
     728         124 :                                objects[i].objtype,
     729         124 :                                &objects[i].object,
     730         124 :                                objects[i].deptype,
     731             :                                0);
     732             :     }
     733             : 
     734             :     /*
     735             :      * Summarize dependencies in remote databases.
     736             :      */
     737         632 :     foreach(cell, remDeps)
     738             :     {
     739           0 :         remoteDep  *dep = lfirst(cell);
     740             : 
     741           0 :         object.classId = DatabaseRelationId;
     742           0 :         object.objectId = dep->dbOid;
     743           0 :         object.objectSubId = 0;
     744             : 
     745           0 :         if (numReportedDeps < MAX_REPORTED_DEPS)
     746             :         {
     747           0 :             numReportedDeps++;
     748           0 :             storeObjectDescription(&descs, REMOTE_OBJECT, &object,
     749             :                                    SHARED_DEPENDENCY_INVALID, dep->count);
     750             :         }
     751             :         else
     752           0 :             numNotReportedDbs++;
     753           0 :         storeObjectDescription(&alldescs, REMOTE_OBJECT, &object,
     754             :                                SHARED_DEPENDENCY_INVALID, dep->count);
     755             :     }
     756             : 
     757         632 :     pfree(objects);
     758         632 :     list_free_deep(remDeps);
     759             : 
     760         632 :     if (descs.len == 0)
     761             :     {
     762         576 :         pfree(descs.data);
     763         576 :         pfree(alldescs.data);
     764         576 :         *detail_msg = *detail_log_msg = NULL;
     765         576 :         return false;
     766             :     }
     767             : 
     768          56 :     if (numNotReportedDeps > 0)
     769           0 :         appendStringInfo(&descs, ngettext("\nand %d other object "
     770             :                                           "(see server log for list)",
     771             :                                           "\nand %d other objects "
     772             :                                           "(see server log for list)",
     773             :                                           numNotReportedDeps),
     774             :                          numNotReportedDeps);
     775          56 :     if (numNotReportedDbs > 0)
     776           0 :         appendStringInfo(&descs, ngettext("\nand objects in %d other database "
     777             :                                           "(see server log for list)",
     778             :                                           "\nand objects in %d other databases "
     779             :                                           "(see server log for list)",
     780             :                                           numNotReportedDbs),
     781             :                          numNotReportedDbs);
     782             : 
     783          56 :     *detail_msg = descs.data;
     784          56 :     *detail_log_msg = alldescs.data;
     785          56 :     return true;
     786             : }
     787             : 
     788             : /*
     789             :  * copyTemplateDependencies
     790             :  *
     791             :  * Routine to create the initial shared dependencies of a new database.
     792             :  * We simply copy the dependencies from the template database.
     793             :  */
     794             : void
     795         884 : copyTemplateDependencies(Oid templateDbId, Oid newDbId)
     796             : {
     797             :     Relation    sdepRel;
     798             :     TupleDesc   sdepDesc;
     799             :     ScanKeyData key[1];
     800             :     SysScanDesc scan;
     801             :     HeapTuple   tup;
     802             :     CatalogIndexState indstate;
     803             :     Datum       values[Natts_pg_shdepend];
     804             :     bool        nulls[Natts_pg_shdepend];
     805             :     bool        replace[Natts_pg_shdepend];
     806             : 
     807         884 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     808         884 :     sdepDesc = RelationGetDescr(sdepRel);
     809             : 
     810         884 :     indstate = CatalogOpenIndexes(sdepRel);
     811             : 
     812             :     /* Scan all entries with dbid = templateDbId */
     813         884 :     ScanKeyInit(&key[0],
     814             :                 Anum_pg_shdepend_dbid,
     815             :                 BTEqualStrategyNumber, F_OIDEQ,
     816             :                 ObjectIdGetDatum(templateDbId));
     817             : 
     818         884 :     scan = systable_beginscan(sdepRel, SharedDependDependerIndexId, true,
     819             :                               NULL, 1, key);
     820             : 
     821             :     /* Set up to copy the tuples except for inserting newDbId */
     822         884 :     memset(values, 0, sizeof(values));
     823         884 :     memset(nulls, false, sizeof(nulls));
     824         884 :     memset(replace, false, sizeof(replace));
     825             : 
     826         884 :     replace[Anum_pg_shdepend_dbid - 1] = true;
     827         884 :     values[Anum_pg_shdepend_dbid - 1] = ObjectIdGetDatum(newDbId);
     828             : 
     829             :     /*
     830             :      * Copy the entries of the original database, changing the database Id to
     831             :      * that of the new database.  Note that because we are not copying rows
     832             :      * with dbId == 0 (ie, rows describing dependent shared objects) we won't
     833             :      * copy the ownership dependency of the template database itself; this is
     834             :      * what we want.
     835             :      */
     836        1768 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     837             :     {
     838             :         HeapTuple   newtup;
     839             : 
     840           0 :         newtup = heap_modify_tuple(tup, sdepDesc, values, nulls, replace);
     841           0 :         CatalogTupleInsertWithInfo(sdepRel, newtup, indstate);
     842             : 
     843           0 :         heap_freetuple(newtup);
     844             :     }
     845             : 
     846         884 :     systable_endscan(scan);
     847             : 
     848         884 :     CatalogCloseIndexes(indstate);
     849         884 :     table_close(sdepRel, RowExclusiveLock);
     850         884 : }
     851             : 
     852             : /*
     853             :  * dropDatabaseDependencies
     854             :  *
     855             :  * Delete pg_shdepend entries corresponding to a database that's being
     856             :  * dropped.
     857             :  */
     858             : void
     859          18 : dropDatabaseDependencies(Oid databaseId)
     860             : {
     861             :     Relation    sdepRel;
     862             :     ScanKeyData key[1];
     863             :     SysScanDesc scan;
     864             :     HeapTuple   tup;
     865             : 
     866          18 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     867             : 
     868             :     /*
     869             :      * First, delete all the entries that have the database Oid in the dbid
     870             :      * field.
     871             :      */
     872          18 :     ScanKeyInit(&key[0],
     873             :                 Anum_pg_shdepend_dbid,
     874             :                 BTEqualStrategyNumber, F_OIDEQ,
     875             :                 ObjectIdGetDatum(databaseId));
     876             :     /* We leave the other index fields unspecified */
     877             : 
     878          18 :     scan = systable_beginscan(sdepRel, SharedDependDependerIndexId, true,
     879             :                               NULL, 1, key);
     880             : 
     881          36 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     882             :     {
     883           0 :         CatalogTupleDelete(sdepRel, &tup->t_self);
     884             :     }
     885             : 
     886          18 :     systable_endscan(scan);
     887             : 
     888             :     /* Now delete all entries corresponding to the database itself */
     889          18 :     shdepDropDependency(sdepRel, DatabaseRelationId, databaseId, 0, true,
     890             :                         InvalidOid, InvalidOid,
     891             :                         SHARED_DEPENDENCY_INVALID);
     892             : 
     893          18 :     table_close(sdepRel, RowExclusiveLock);
     894          18 : }
     895             : 
     896             : /*
     897             :  * deleteSharedDependencyRecordsFor
     898             :  *
     899             :  * Delete all pg_shdepend entries corresponding to an object that's being
     900             :  * dropped or modified.  The object is assumed to be either a shared object
     901             :  * or local to the current database (the classId tells us which).
     902             :  *
     903             :  * If objectSubId is zero, we are deleting a whole object, so get rid of
     904             :  * pg_shdepend entries for subobjects as well.
     905             :  */
     906             : void
     907      122422 : deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
     908             : {
     909             :     Relation    sdepRel;
     910             : 
     911      122422 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
     912             : 
     913      122422 :     shdepDropDependency(sdepRel, classId, objectId, objectSubId,
     914             :                         (objectSubId == 0),
     915             :                         InvalidOid, InvalidOid,
     916             :                         SHARED_DEPENDENCY_INVALID);
     917             : 
     918      122422 :     table_close(sdepRel, RowExclusiveLock);
     919      122422 : }
     920             : 
     921             : /*
     922             :  * shdepAddDependency
     923             :  *      Internal workhorse for inserting into pg_shdepend
     924             :  *
     925             :  * sdepRel must be the pg_shdepend relation, already opened and suitably
     926             :  * locked.
     927             :  */
     928             : static void
     929        2530 : shdepAddDependency(Relation sdepRel,
     930             :                    Oid classId, Oid objectId, int32 objsubId,
     931             :                    Oid refclassId, Oid refobjId,
     932             :                    SharedDependencyType deptype)
     933             : {
     934             :     HeapTuple   tup;
     935             :     Datum       values[Natts_pg_shdepend];
     936             :     bool        nulls[Natts_pg_shdepend];
     937             : 
     938             :     /*
     939             :      * Make sure the object doesn't go away while we record the dependency on
     940             :      * it.  DROP routines should lock the object exclusively before they check
     941             :      * shared dependencies.
     942             :      */
     943        2530 :     shdepLockAndCheckObject(refclassId, refobjId);
     944             : 
     945        2530 :     memset(nulls, false, sizeof(nulls));
     946             : 
     947             :     /*
     948             :      * Form the new tuple and record the dependency.
     949             :      */
     950        2530 :     values[Anum_pg_shdepend_dbid - 1] = ObjectIdGetDatum(classIdGetDbId(classId));
     951        2530 :     values[Anum_pg_shdepend_classid - 1] = ObjectIdGetDatum(classId);
     952        2530 :     values[Anum_pg_shdepend_objid - 1] = ObjectIdGetDatum(objectId);
     953        2530 :     values[Anum_pg_shdepend_objsubid - 1] = Int32GetDatum(objsubId);
     954             : 
     955        2530 :     values[Anum_pg_shdepend_refclassid - 1] = ObjectIdGetDatum(refclassId);
     956        2530 :     values[Anum_pg_shdepend_refobjid - 1] = ObjectIdGetDatum(refobjId);
     957        2530 :     values[Anum_pg_shdepend_deptype - 1] = CharGetDatum(deptype);
     958             : 
     959        2530 :     tup = heap_form_tuple(sdepRel->rd_att, values, nulls);
     960             : 
     961        2530 :     CatalogTupleInsert(sdepRel, tup);
     962             : 
     963             :     /* clean up */
     964        2530 :     heap_freetuple(tup);
     965        2530 : }
     966             : 
     967             : /*
     968             :  * shdepDropDependency
     969             :  *      Internal workhorse for deleting entries from pg_shdepend.
     970             :  *
     971             :  * We drop entries having the following properties:
     972             :  *  dependent object is the one identified by classId/objectId/objsubId
     973             :  *  if refclassId isn't InvalidOid, it must match the entry's refclassid
     974             :  *  if refobjId isn't InvalidOid, it must match the entry's refobjid
     975             :  *  if deptype isn't SHARED_DEPENDENCY_INVALID, it must match entry's deptype
     976             :  *
     977             :  * If drop_subobjects is true, we ignore objsubId and consider all entries
     978             :  * matching classId/objectId.
     979             :  *
     980             :  * sdepRel must be the pg_shdepend relation, already opened and suitably
     981             :  * locked.
     982             :  */
     983             : static void
     984      122982 : shdepDropDependency(Relation sdepRel,
     985             :                     Oid classId, Oid objectId, int32 objsubId,
     986             :                     bool drop_subobjects,
     987             :                     Oid refclassId, Oid refobjId,
     988             :                     SharedDependencyType deptype)
     989             : {
     990             :     ScanKeyData key[4];
     991             :     int         nkeys;
     992             :     SysScanDesc scan;
     993             :     HeapTuple   tup;
     994             : 
     995             :     /* Scan for entries matching the dependent object */
     996      122982 :     ScanKeyInit(&key[0],
     997             :                 Anum_pg_shdepend_dbid,
     998             :                 BTEqualStrategyNumber, F_OIDEQ,
     999      122982 :                 ObjectIdGetDatum(classIdGetDbId(classId)));
    1000      122982 :     ScanKeyInit(&key[1],
    1001             :                 Anum_pg_shdepend_classid,
    1002             :                 BTEqualStrategyNumber, F_OIDEQ,
    1003             :                 ObjectIdGetDatum(classId));
    1004      122982 :     ScanKeyInit(&key[2],
    1005             :                 Anum_pg_shdepend_objid,
    1006             :                 BTEqualStrategyNumber, F_OIDEQ,
    1007             :                 ObjectIdGetDatum(objectId));
    1008      122982 :     if (drop_subobjects)
    1009      121514 :         nkeys = 3;
    1010             :     else
    1011             :     {
    1012        1468 :         ScanKeyInit(&key[3],
    1013             :                     Anum_pg_shdepend_objsubid,
    1014             :                     BTEqualStrategyNumber, F_INT4EQ,
    1015             :                     Int32GetDatum(objsubId));
    1016        1468 :         nkeys = 4;
    1017             :     }
    1018             : 
    1019      122982 :     scan = systable_beginscan(sdepRel, SharedDependDependerIndexId, true,
    1020             :                               NULL, nkeys, key);
    1021             : 
    1022      248704 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
    1023             :     {
    1024        2740 :         Form_pg_shdepend shdepForm = (Form_pg_shdepend) GETSTRUCT(tup);
    1025             : 
    1026             :         /* Filter entries according to additional parameters */
    1027        2740 :         if (OidIsValid(refclassId) && shdepForm->refclassid != refclassId)
    1028           0 :             continue;
    1029        2740 :         if (OidIsValid(refobjId) && shdepForm->refobjid != refobjId)
    1030         326 :             continue;
    1031        2630 :         if (deptype != SHARED_DEPENDENCY_INVALID &&
    1032         216 :             shdepForm->deptype != deptype)
    1033           0 :             continue;
    1034             : 
    1035             :         /* OK, delete it */
    1036        2414 :         CatalogTupleDelete(sdepRel, &tup->t_self);
    1037             :     }
    1038             : 
    1039      122982 :     systable_endscan(scan);
    1040      122982 : }
    1041             : 
    1042             : /*
    1043             :  * classIdGetDbId
    1044             :  *
    1045             :  * Get the database Id that should be used in pg_shdepend, given the OID
    1046             :  * of the catalog containing the object.  For shared objects, it's 0
    1047             :  * (InvalidOid); for all other objects, it's the current database Id.
    1048             :  */
    1049             : static Oid
    1050      125844 : classIdGetDbId(Oid classId)
    1051             : {
    1052             :     Oid         dbId;
    1053             : 
    1054      125844 :     if (IsSharedRelation(classId))
    1055         178 :         dbId = InvalidOid;
    1056             :     else
    1057      125666 :         dbId = MyDatabaseId;
    1058             : 
    1059      125844 :     return dbId;
    1060             : }
    1061             : 
    1062             : /*
    1063             :  * shdepLockAndCheckObject
    1064             :  *
    1065             :  * Lock the object that we are about to record a dependency on.
    1066             :  * After it's locked, verify that it hasn't been dropped while we
    1067             :  * weren't looking.  If the object has been dropped, this function
    1068             :  * does not return!
    1069             :  */
    1070             : void
    1071        3732 : shdepLockAndCheckObject(Oid classId, Oid objectId)
    1072             : {
    1073             :     /* AccessShareLock should be OK, since we are not modifying the object */
    1074        3732 :     LockSharedObject(classId, objectId, 0, AccessShareLock);
    1075             : 
    1076        3732 :     switch (classId)
    1077             :     {
    1078             :         case AuthIdRelationId:
    1079        2904 :             if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(objectId)))
    1080           0 :                 ereport(ERROR,
    1081             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    1082             :                          errmsg("role %u was concurrently dropped",
    1083             :                                 objectId)));
    1084        2904 :             break;
    1085             : 
    1086             :             /*
    1087             :              * Currently, this routine need not support any other shared
    1088             :              * object types besides roles.  If we wanted to record explicit
    1089             :              * dependencies on databases or tablespaces, we'd need code along
    1090             :              * these lines:
    1091             :              */
    1092             : #ifdef NOT_USED
    1093             :         case TableSpaceRelationId:
    1094             :             {
    1095             :                 /* For lack of a syscache on pg_tablespace, do this: */
    1096             :                 char       *tablespace = get_tablespace_name(objectId);
    1097             : 
    1098             :                 if (tablespace == NULL)
    1099             :                     ereport(ERROR,
    1100             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
    1101             :                              errmsg("tablespace %u was concurrently dropped",
    1102             :                                     objectId)));
    1103             :                 pfree(tablespace);
    1104             :                 break;
    1105             :             }
    1106             : #endif
    1107             : 
    1108             :         case DatabaseRelationId:
    1109             :             {
    1110             :                 /* For lack of a syscache on pg_database, do this: */
    1111         828 :                 char       *database = get_database_name(objectId);
    1112             : 
    1113         828 :                 if (database == NULL)
    1114           0 :                     ereport(ERROR,
    1115             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
    1116             :                              errmsg("database %u was concurrently dropped",
    1117             :                                     objectId)));
    1118         828 :                 pfree(database);
    1119         828 :                 break;
    1120             :             }
    1121             : 
    1122             : 
    1123             :         default:
    1124           0 :             elog(ERROR, "unrecognized shared classId: %u", classId);
    1125             :     }
    1126        3732 : }
    1127             : 
    1128             : 
    1129             : /*
    1130             :  * storeObjectDescription
    1131             :  *      Append the description of a dependent object to "descs"
    1132             :  *
    1133             :  * While searching for dependencies of a shared object, we stash the
    1134             :  * descriptions of dependent objects we find in a single string, which we
    1135             :  * later pass to ereport() in the DETAIL field when somebody attempts to
    1136             :  * drop a referenced shared object.
    1137             :  *
    1138             :  * When type is LOCAL_OBJECT or SHARED_OBJECT, we expect object to be the
    1139             :  * dependent object, deptype is the dependency type, and count is not used.
    1140             :  * When type is REMOTE_OBJECT, we expect object to be the database object,
    1141             :  * and count to be nonzero; deptype is not used in this case.
    1142             :  */
    1143             : static void
    1144         248 : storeObjectDescription(StringInfo descs,
    1145             :                        SharedDependencyObjectType type,
    1146             :                        ObjectAddress *object,
    1147             :                        SharedDependencyType deptype,
    1148             :                        int count)
    1149             : {
    1150         248 :     char       *objdesc = getObjectDescription(object);
    1151             : 
    1152             :     /* separate entries with a newline */
    1153         248 :     if (descs->len != 0)
    1154         136 :         appendStringInfoChar(descs, '\n');
    1155             : 
    1156         248 :     switch (type)
    1157             :     {
    1158             :         case LOCAL_OBJECT:
    1159             :         case SHARED_OBJECT:
    1160         248 :             if (deptype == SHARED_DEPENDENCY_OWNER)
    1161         144 :                 appendStringInfo(descs, _("owner of %s"), objdesc);
    1162         104 :             else if (deptype == SHARED_DEPENDENCY_ACL)
    1163          88 :                 appendStringInfo(descs, _("privileges for %s"), objdesc);
    1164          16 :             else if (deptype == SHARED_DEPENDENCY_POLICY)
    1165          16 :                 appendStringInfo(descs, _("target of %s"), objdesc);
    1166             :             else
    1167           0 :                 elog(ERROR, "unrecognized dependency type: %d",
    1168             :                      (int) deptype);
    1169         248 :             break;
    1170             : 
    1171             :         case REMOTE_OBJECT:
    1172             :             /* translator: %s will always be "database %s" */
    1173           0 :             appendStringInfo(descs, ngettext("%d object in %s",
    1174             :                                              "%d objects in %s",
    1175             :                                              count),
    1176             :                              count, objdesc);
    1177           0 :             break;
    1178             : 
    1179             :         default:
    1180           0 :             elog(ERROR, "unrecognized object type: %d", type);
    1181             :     }
    1182             : 
    1183         248 :     pfree(objdesc);
    1184         248 : }
    1185             : 
    1186             : 
    1187             : /*
    1188             :  * isSharedObjectPinned
    1189             :  *      Return whether a given shared object has a SHARED_DEPENDENCY_PIN entry.
    1190             :  *
    1191             :  * sdepRel must be the pg_shdepend relation, already opened and suitably
    1192             :  * locked.
    1193             :  */
    1194             : static bool
    1195      128240 : isSharedObjectPinned(Oid classId, Oid objectId, Relation sdepRel)
    1196             : {
    1197      128240 :     bool        result = false;
    1198             :     ScanKeyData key[2];
    1199             :     SysScanDesc scan;
    1200             :     HeapTuple   tup;
    1201             : 
    1202      128240 :     ScanKeyInit(&key[0],
    1203             :                 Anum_pg_shdepend_refclassid,
    1204             :                 BTEqualStrategyNumber, F_OIDEQ,
    1205             :                 ObjectIdGetDatum(classId));
    1206      128240 :     ScanKeyInit(&key[1],
    1207             :                 Anum_pg_shdepend_refobjid,
    1208             :                 BTEqualStrategyNumber, F_OIDEQ,
    1209             :                 ObjectIdGetDatum(objectId));
    1210             : 
    1211      128240 :     scan = systable_beginscan(sdepRel, SharedDependReferenceIndexId, true,
    1212             :                               NULL, 2, key);
    1213             : 
    1214             :     /*
    1215             :      * Since we won't generate additional pg_shdepend entries for pinned
    1216             :      * objects, there can be at most one entry referencing a pinned object.
    1217             :      * Hence, it's sufficient to look at the first returned tuple; we don't
    1218             :      * need to loop.
    1219             :      */
    1220      128240 :     tup = systable_getnext(scan);
    1221      128240 :     if (HeapTupleIsValid(tup))
    1222             :     {
    1223      127694 :         Form_pg_shdepend shdepForm = (Form_pg_shdepend) GETSTRUCT(tup);
    1224             : 
    1225      127694 :         if (shdepForm->deptype == SHARED_DEPENDENCY_PIN)
    1226      125102 :             result = true;
    1227             :     }
    1228             : 
    1229      128240 :     systable_endscan(scan);
    1230             : 
    1231      128240 :     return result;
    1232             : }
    1233             : 
    1234             : /*
    1235             :  * shdepDropOwned
    1236             :  *
    1237             :  * Drop the objects owned by any one of the given RoleIds.  If a role has
    1238             :  * access to an object, the grant will be removed as well (but the object
    1239             :  * will not, of course).
    1240             :  *
    1241             :  * We can revoke grants immediately while doing the scan, but drops are
    1242             :  * saved up and done all at once with performMultipleDeletions.  This
    1243             :  * is necessary so that we don't get failures from trying to delete
    1244             :  * interdependent objects in the wrong order.
    1245             :  */
    1246             : void
    1247          60 : shdepDropOwned(List *roleids, DropBehavior behavior)
    1248             : {
    1249             :     Relation    sdepRel;
    1250             :     ListCell   *cell;
    1251             :     ObjectAddresses *deleteobjs;
    1252             : 
    1253          60 :     deleteobjs = new_object_addresses();
    1254             : 
    1255             :     /*
    1256             :      * We don't need this strong a lock here, but we'll call routines that
    1257             :      * acquire RowExclusiveLock.  Better get that right now to avoid potential
    1258             :      * deadlock failures.
    1259             :      */
    1260          60 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
    1261             : 
    1262             :     /*
    1263             :      * For each role, find the dependent objects and drop them using the
    1264             :      * regular (non-shared) dependency management.
    1265             :      */
    1266         134 :     foreach(cell, roleids)
    1267             :     {
    1268          74 :         Oid         roleid = lfirst_oid(cell);
    1269             :         ScanKeyData key[2];
    1270             :         SysScanDesc scan;
    1271             :         HeapTuple   tuple;
    1272             : 
    1273             :         /* Doesn't work for pinned objects */
    1274          74 :         if (isSharedObjectPinned(AuthIdRelationId, roleid, sdepRel))
    1275             :         {
    1276             :             ObjectAddress obj;
    1277             : 
    1278           0 :             obj.classId = AuthIdRelationId;
    1279           0 :             obj.objectId = roleid;
    1280           0 :             obj.objectSubId = 0;
    1281             : 
    1282           0 :             ereport(ERROR,
    1283             :                     (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
    1284             :                      errmsg("cannot drop objects owned by %s because they are "
    1285             :                             "required by the database system",
    1286             :                             getObjectDescription(&obj))));
    1287             :         }
    1288             : 
    1289          74 :         ScanKeyInit(&key[0],
    1290             :                     Anum_pg_shdepend_refclassid,
    1291             :                     BTEqualStrategyNumber, F_OIDEQ,
    1292             :                     ObjectIdGetDatum(AuthIdRelationId));
    1293          74 :         ScanKeyInit(&key[1],
    1294             :                     Anum_pg_shdepend_refobjid,
    1295             :                     BTEqualStrategyNumber, F_OIDEQ,
    1296             :                     ObjectIdGetDatum(roleid));
    1297             : 
    1298          74 :         scan = systable_beginscan(sdepRel, SharedDependReferenceIndexId, true,
    1299             :                                   NULL, 2, key);
    1300             : 
    1301         394 :         while ((tuple = systable_getnext(scan)) != NULL)
    1302             :         {
    1303         246 :             Form_pg_shdepend sdepForm = (Form_pg_shdepend) GETSTRUCT(tuple);
    1304             :             ObjectAddress obj;
    1305             : 
    1306             :             /*
    1307             :              * We only operate on shared objects and objects in the current
    1308             :              * database
    1309             :              */
    1310         250 :             if (sdepForm->dbid != MyDatabaseId &&
    1311           4 :                 sdepForm->dbid != InvalidOid)
    1312           0 :                 continue;
    1313             : 
    1314         246 :             switch (sdepForm->deptype)
    1315             :             {
    1316             :                     /* Shouldn't happen */
    1317             :                 case SHARED_DEPENDENCY_PIN:
    1318             :                 case SHARED_DEPENDENCY_INVALID:
    1319           0 :                     elog(ERROR, "unexpected dependency type");
    1320             :                     break;
    1321             :                 case SHARED_DEPENDENCY_ACL:
    1322          32 :                     RemoveRoleFromObjectACL(roleid,
    1323             :                                             sdepForm->classid,
    1324             :                                             sdepForm->objid);
    1325          32 :                     break;
    1326             :                 case SHARED_DEPENDENCY_POLICY:
    1327             :                     /* If unable to remove role from policy, remove policy. */
    1328          12 :                     if (!RemoveRoleFromObjectPolicy(roleid,
    1329             :                                                     sdepForm->classid,
    1330             :                                                     sdepForm->objid))
    1331             :                     {
    1332           4 :                         obj.classId = sdepForm->classid;
    1333           4 :                         obj.objectId = sdepForm->objid;
    1334           4 :                         obj.objectSubId = sdepForm->objsubid;
    1335           4 :                         add_exact_object_address(&obj, deleteobjs);
    1336             :                     }
    1337          12 :                     break;
    1338             :                 case SHARED_DEPENDENCY_OWNER:
    1339             :                     /* If a local object, save it for deletion below */
    1340         202 :                     if (sdepForm->dbid == MyDatabaseId)
    1341             :                     {
    1342         202 :                         obj.classId = sdepForm->classid;
    1343         202 :                         obj.objectId = sdepForm->objid;
    1344         202 :                         obj.objectSubId = sdepForm->objsubid;
    1345         202 :                         add_exact_object_address(&obj, deleteobjs);
    1346             :                     }
    1347         202 :                     break;
    1348             :             }
    1349             :         }
    1350             : 
    1351          74 :         systable_endscan(scan);
    1352             :     }
    1353             : 
    1354             :     /*
    1355             :      * For stability of deletion-report ordering, sort the objects into
    1356             :      * approximate reverse creation order before deletion.  (This might also
    1357             :      * make the deletion go a bit faster, since there's less chance of having
    1358             :      * to rearrange the objects due to dependencies.)
    1359             :      */
    1360          60 :     sort_object_addresses(deleteobjs);
    1361             : 
    1362             :     /* the dependency mechanism does the actual work */
    1363          60 :     performMultipleDeletions(deleteobjs, behavior, 0);
    1364             : 
    1365          56 :     table_close(sdepRel, RowExclusiveLock);
    1366             : 
    1367          56 :     free_object_addresses(deleteobjs);
    1368          56 : }
    1369             : 
    1370             : /*
    1371             :  * shdepReassignOwned
    1372             :  *
    1373             :  * Change the owner of objects owned by any of the roles in roleids to
    1374             :  * newrole.  Grants are not touched.
    1375             :  */
    1376             : void
    1377           8 : shdepReassignOwned(List *roleids, Oid newrole)
    1378             : {
    1379             :     Relation    sdepRel;
    1380             :     ListCell   *cell;
    1381             : 
    1382             :     /*
    1383             :      * We don't need this strong a lock here, but we'll call routines that
    1384             :      * acquire RowExclusiveLock.  Better get that right now to avoid potential
    1385             :      * deadlock problems.
    1386             :      */
    1387           8 :     sdepRel = table_open(SharedDependRelationId, RowExclusiveLock);
    1388             : 
    1389          16 :     foreach(cell, roleids)
    1390             :     {
    1391             :         SysScanDesc scan;
    1392             :         ScanKeyData key[2];
    1393             :         HeapTuple   tuple;
    1394           8 :         Oid         roleid = lfirst_oid(cell);
    1395             : 
    1396             :         /* Refuse to work on pinned roles */
    1397           8 :         if (isSharedObjectPinned(AuthIdRelationId, roleid, sdepRel))
    1398             :         {
    1399             :             ObjectAddress obj;
    1400             : 
    1401           0 :             obj.classId = AuthIdRelationId;
    1402           0 :             obj.objectId = roleid;
    1403           0 :             obj.objectSubId = 0;
    1404             : 
    1405           0 :             ereport(ERROR,
    1406             :                     (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
    1407             :                      errmsg("cannot reassign ownership of objects owned by %s because they are required by the database system",
    1408             :                             getObjectDescription(&obj))));
    1409             : 
    1410             :             /*
    1411             :              * There's no need to tell the whole truth, which is that we
    1412             :              * didn't track these dependencies at all ...
    1413             :              */
    1414             :         }
    1415             : 
    1416           8 :         ScanKeyInit(&key[0],
    1417             :                     Anum_pg_shdepend_refclassid,
    1418             :                     BTEqualStrategyNumber, F_OIDEQ,
    1419             :                     ObjectIdGetDatum(AuthIdRelationId));
    1420           8 :         ScanKeyInit(&key[1],
    1421             :                     Anum_pg_shdepend_refobjid,
    1422             :                     BTEqualStrategyNumber, F_OIDEQ,
    1423             :                     ObjectIdGetDatum(roleid));
    1424             : 
    1425           8 :         scan = systable_beginscan(sdepRel, SharedDependReferenceIndexId, true,
    1426             :                                   NULL, 2, key);
    1427             : 
    1428          88 :         while ((tuple = systable_getnext(scan)) != NULL)
    1429             :         {
    1430          72 :             Form_pg_shdepend sdepForm = (Form_pg_shdepend) GETSTRUCT(tuple);
    1431             : 
    1432             :             /*
    1433             :              * We only operate on shared objects and objects in the current
    1434             :              * database
    1435             :              */
    1436          76 :             if (sdepForm->dbid != MyDatabaseId &&
    1437           4 :                 sdepForm->dbid != InvalidOid)
    1438           0 :                 continue;
    1439             : 
    1440             :             /* Unexpected because we checked for pins above */
    1441          72 :             if (sdepForm->deptype == SHARED_DEPENDENCY_PIN)
    1442           0 :                 elog(ERROR, "unexpected shared pin");
    1443             : 
    1444             :             /* We leave non-owner dependencies alone */
    1445          72 :             if (sdepForm->deptype != SHARED_DEPENDENCY_OWNER)
    1446          16 :                 continue;
    1447             : 
    1448             :             /* Issue the appropriate ALTER OWNER call */
    1449          56 :             switch (sdepForm->classid)
    1450             :             {
    1451             :                 case TypeRelationId:
    1452          12 :                     AlterTypeOwner_oid(sdepForm->objid, newrole, true);
    1453          12 :                     break;
    1454             : 
    1455             :                 case NamespaceRelationId:
    1456           4 :                     AlterSchemaOwner_oid(sdepForm->objid, newrole);
    1457           4 :                     break;
    1458             : 
    1459             :                 case RelationRelationId:
    1460             : 
    1461             :                     /*
    1462             :                      * Pass recursing = true so that we don't fail on indexes,
    1463             :                      * owned sequences, etc when we happen to visit them
    1464             :                      * before their parent table.
    1465             :                      */
    1466          16 :                     ATExecChangeOwner(sdepForm->objid, newrole, true, AccessExclusiveLock);
    1467          16 :                     break;
    1468             : 
    1469             :                 case DefaultAclRelationId:
    1470             : 
    1471             :                     /*
    1472             :                      * Ignore default ACLs; they should be handled by DROP
    1473             :                      * OWNED, not REASSIGN OWNED.
    1474             :                      */
    1475           4 :                     break;
    1476             : 
    1477             :                 case UserMappingRelationId:
    1478             :                     /* ditto */
    1479           8 :                     break;
    1480             : 
    1481             :                 case ForeignServerRelationId:
    1482           8 :                     AlterForeignServerOwner_oid(sdepForm->objid, newrole);
    1483           8 :                     break;
    1484             : 
    1485             :                 case ForeignDataWrapperRelationId:
    1486           0 :                     AlterForeignDataWrapperOwner_oid(sdepForm->objid, newrole);
    1487           0 :                     break;
    1488             : 
    1489             :                 case EventTriggerRelationId:
    1490           0 :                     AlterEventTriggerOwner_oid(sdepForm->objid, newrole);
    1491           0 :                     break;
    1492             : 
    1493             :                 case PublicationRelationId:
    1494           0 :                     AlterPublicationOwner_oid(sdepForm->objid, newrole);
    1495           0 :                     break;
    1496             : 
    1497             :                 case SubscriptionRelationId:
    1498           0 :                     AlterSubscriptionOwner_oid(sdepForm->objid, newrole);
    1499           0 :                     break;
    1500             : 
    1501             :                     /* Generic alter owner cases */
    1502             :                 case CollationRelationId:
    1503             :                 case ConversionRelationId:
    1504             :                 case OperatorRelationId:
    1505             :                 case ProcedureRelationId:
    1506             :                 case LanguageRelationId:
    1507             :                 case LargeObjectRelationId:
    1508             :                 case OperatorFamilyRelationId:
    1509             :                 case OperatorClassRelationId:
    1510             :                 case ExtensionRelationId:
    1511             :                 case StatisticExtRelationId:
    1512             :                 case TableSpaceRelationId:
    1513             :                 case DatabaseRelationId:
    1514             :                 case TSConfigRelationId:
    1515             :                 case TSDictionaryRelationId:
    1516             :                     {
    1517           4 :                         Oid         classId = sdepForm->classid;
    1518             :                         Relation    catalog;
    1519             : 
    1520           4 :                         if (classId == LargeObjectRelationId)
    1521           0 :                             classId = LargeObjectMetadataRelationId;
    1522             : 
    1523           4 :                         catalog = table_open(classId, RowExclusiveLock);
    1524             : 
    1525           4 :                         AlterObjectOwner_internal(catalog, sdepForm->objid,
    1526             :                                                   newrole);
    1527             : 
    1528           4 :                         table_close(catalog, NoLock);
    1529             :                     }
    1530           4 :                     break;
    1531             : 
    1532             :                 default:
    1533           0 :                     elog(ERROR, "unexpected classid %u", sdepForm->classid);
    1534             :                     break;
    1535             :             }
    1536             :             /* Make sure the next iteration will see my changes */
    1537          56 :             CommandCounterIncrement();
    1538             :         }
    1539             : 
    1540           8 :         systable_endscan(scan);
    1541             :     }
    1542             : 
    1543           8 :     table_close(sdepRel, RowExclusiveLock);
    1544           8 : }

Generated by: LCOV version 1.13