LCOV - code coverage report
Current view: top level - src/backend/commands - alter.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 317 349 90.8 %
Date: 2025-01-18 04:15:08 Functions: 10 10 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * alter.c
       4             :  *    Drivers for generic alter commands
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/commands/alter.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "access/htup_details.h"
      18             : #include "access/relation.h"
      19             : #include "access/table.h"
      20             : #include "catalog/dependency.h"
      21             : #include "catalog/indexing.h"
      22             : #include "catalog/namespace.h"
      23             : #include "catalog/objectaccess.h"
      24             : #include "catalog/pg_collation.h"
      25             : #include "catalog/pg_conversion.h"
      26             : #include "catalog/pg_database_d.h"
      27             : #include "catalog/pg_event_trigger.h"
      28             : #include "catalog/pg_foreign_data_wrapper.h"
      29             : #include "catalog/pg_foreign_server.h"
      30             : #include "catalog/pg_language.h"
      31             : #include "catalog/pg_largeobject.h"
      32             : #include "catalog/pg_largeobject_metadata.h"
      33             : #include "catalog/pg_namespace.h"
      34             : #include "catalog/pg_opclass.h"
      35             : #include "catalog/pg_operator.h"
      36             : #include "catalog/pg_opfamily.h"
      37             : #include "catalog/pg_proc.h"
      38             : #include "catalog/pg_statistic_ext.h"
      39             : #include "catalog/pg_subscription.h"
      40             : #include "catalog/pg_ts_config.h"
      41             : #include "catalog/pg_ts_dict.h"
      42             : #include "catalog/pg_ts_parser.h"
      43             : #include "catalog/pg_ts_template.h"
      44             : #include "commands/alter.h"
      45             : #include "commands/collationcmds.h"
      46             : #include "commands/dbcommands.h"
      47             : #include "commands/defrem.h"
      48             : #include "commands/event_trigger.h"
      49             : #include "commands/extension.h"
      50             : #include "commands/policy.h"
      51             : #include "commands/publicationcmds.h"
      52             : #include "commands/schemacmds.h"
      53             : #include "commands/subscriptioncmds.h"
      54             : #include "commands/tablecmds.h"
      55             : #include "commands/tablespace.h"
      56             : #include "commands/trigger.h"
      57             : #include "commands/typecmds.h"
      58             : #include "commands/user.h"
      59             : #include "miscadmin.h"
      60             : #include "replication/logicalworker.h"
      61             : #include "rewrite/rewriteDefine.h"
      62             : #include "storage/lmgr.h"
      63             : #include "utils/acl.h"
      64             : #include "utils/builtins.h"
      65             : #include "utils/lsyscache.h"
      66             : #include "utils/rel.h"
      67             : #include "utils/syscache.h"
      68             : 
      69             : static Oid  AlterObjectNamespace_internal(Relation rel, Oid objid, Oid nspOid);
      70             : 
      71             : /*
      72             :  * Raise an error to the effect that an object of the given name is already
      73             :  * present in the given namespace.
      74             :  */
      75             : static void
      76          24 : report_name_conflict(Oid classId, const char *name)
      77             : {
      78             :     char       *msgfmt;
      79             : 
      80          24 :     switch (classId)
      81             :     {
      82           6 :         case EventTriggerRelationId:
      83           6 :             msgfmt = gettext_noop("event trigger \"%s\" already exists");
      84           6 :             break;
      85           6 :         case ForeignDataWrapperRelationId:
      86           6 :             msgfmt = gettext_noop("foreign-data wrapper \"%s\" already exists");
      87           6 :             break;
      88           6 :         case ForeignServerRelationId:
      89           6 :             msgfmt = gettext_noop("server \"%s\" already exists");
      90           6 :             break;
      91           6 :         case LanguageRelationId:
      92           6 :             msgfmt = gettext_noop("language \"%s\" already exists");
      93           6 :             break;
      94           0 :         case PublicationRelationId:
      95           0 :             msgfmt = gettext_noop("publication \"%s\" already exists");
      96           0 :             break;
      97           0 :         case SubscriptionRelationId:
      98           0 :             msgfmt = gettext_noop("subscription \"%s\" already exists");
      99           0 :             break;
     100           0 :         default:
     101           0 :             elog(ERROR, "unsupported object class: %u", classId);
     102             :             break;
     103             :     }
     104             : 
     105          24 :     ereport(ERROR,
     106             :             (errcode(ERRCODE_DUPLICATE_OBJECT),
     107             :              errmsg(msgfmt, name)));
     108             : }
     109             : 
     110             : static void
     111          72 : report_namespace_conflict(Oid classId, const char *name, Oid nspOid)
     112             : {
     113             :     char       *msgfmt;
     114             : 
     115             :     Assert(OidIsValid(nspOid));
     116             : 
     117          72 :     switch (classId)
     118             :     {
     119          12 :         case ConversionRelationId:
     120             :             Assert(OidIsValid(nspOid));
     121          12 :             msgfmt = gettext_noop("conversion \"%s\" already exists in schema \"%s\"");
     122          12 :             break;
     123          12 :         case StatisticExtRelationId:
     124             :             Assert(OidIsValid(nspOid));
     125          12 :             msgfmt = gettext_noop("statistics object \"%s\" already exists in schema \"%s\"");
     126          12 :             break;
     127          12 :         case TSParserRelationId:
     128             :             Assert(OidIsValid(nspOid));
     129          12 :             msgfmt = gettext_noop("text search parser \"%s\" already exists in schema \"%s\"");
     130          12 :             break;
     131          12 :         case TSDictionaryRelationId:
     132             :             Assert(OidIsValid(nspOid));
     133          12 :             msgfmt = gettext_noop("text search dictionary \"%s\" already exists in schema \"%s\"");
     134          12 :             break;
     135          12 :         case TSTemplateRelationId:
     136             :             Assert(OidIsValid(nspOid));
     137          12 :             msgfmt = gettext_noop("text search template \"%s\" already exists in schema \"%s\"");
     138          12 :             break;
     139          12 :         case TSConfigRelationId:
     140             :             Assert(OidIsValid(nspOid));
     141          12 :             msgfmt = gettext_noop("text search configuration \"%s\" already exists in schema \"%s\"");
     142          12 :             break;
     143           0 :         default:
     144           0 :             elog(ERROR, "unsupported object class: %u", classId);
     145             :             break;
     146             :     }
     147             : 
     148          72 :     ereport(ERROR,
     149             :             (errcode(ERRCODE_DUPLICATE_OBJECT),
     150             :              errmsg(msgfmt, name, get_namespace_name(nspOid))));
     151             : }
     152             : 
     153             : /*
     154             :  * AlterObjectRename_internal
     155             :  *
     156             :  * Generic function to rename the given object, for simple cases (won't
     157             :  * work for tables, nor other cases where we need to do more than change
     158             :  * the name column of a single catalog entry).
     159             :  *
     160             :  * rel: catalog relation containing object (RowExclusiveLock'd by caller)
     161             :  * objectId: OID of object to be renamed
     162             :  * new_name: CString representation of new name
     163             :  */
     164             : static void
     165         404 : AlterObjectRename_internal(Relation rel, Oid objectId, const char *new_name)
     166             : {
     167         404 :     Oid         classId = RelationGetRelid(rel);
     168         404 :     int         oidCacheId = get_object_catcache_oid(classId);
     169         404 :     int         nameCacheId = get_object_catcache_name(classId);
     170         404 :     AttrNumber  Anum_name = get_object_attnum_name(classId);
     171         404 :     AttrNumber  Anum_namespace = get_object_attnum_namespace(classId);
     172         404 :     AttrNumber  Anum_owner = get_object_attnum_owner(classId);
     173             :     HeapTuple   oldtup;
     174             :     HeapTuple   newtup;
     175             :     Datum       datum;
     176             :     bool        isnull;
     177             :     Oid         namespaceId;
     178             :     Oid         ownerId;
     179             :     char       *old_name;
     180             :     AclResult   aclresult;
     181             :     Datum      *values;
     182             :     bool       *nulls;
     183             :     bool       *replaces;
     184             :     NameData    nameattrdata;
     185             : 
     186         404 :     oldtup = SearchSysCache1(oidCacheId, ObjectIdGetDatum(objectId));
     187         404 :     if (!HeapTupleIsValid(oldtup))
     188           0 :         elog(ERROR, "cache lookup failed for object %u of catalog \"%s\"",
     189             :              objectId, RelationGetRelationName(rel));
     190             : 
     191         404 :     datum = heap_getattr(oldtup, Anum_name,
     192             :                          RelationGetDescr(rel), &isnull);
     193             :     Assert(!isnull);
     194         404 :     old_name = NameStr(*(DatumGetName(datum)));
     195             : 
     196             :     /* Get OID of namespace */
     197         404 :     if (Anum_namespace > 0)
     198             :     {
     199         270 :         datum = heap_getattr(oldtup, Anum_namespace,
     200             :                              RelationGetDescr(rel), &isnull);
     201             :         Assert(!isnull);
     202         270 :         namespaceId = DatumGetObjectId(datum);
     203             :     }
     204             :     else
     205         134 :         namespaceId = InvalidOid;
     206             : 
     207             :     /* Permission checks ... superusers can always do it */
     208         404 :     if (!superuser())
     209             :     {
     210             :         /* Fail if object does not have an explicit owner */
     211         246 :         if (Anum_owner <= 0)
     212           0 :             ereport(ERROR,
     213             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     214             :                      errmsg("must be superuser to rename %s",
     215             :                             getObjectDescriptionOids(classId, objectId))));
     216             : 
     217             :         /* Otherwise, must be owner of the existing object */
     218         246 :         datum = heap_getattr(oldtup, Anum_owner,
     219             :                              RelationGetDescr(rel), &isnull);
     220             :         Assert(!isnull);
     221         246 :         ownerId = DatumGetObjectId(datum);
     222             : 
     223         246 :         if (!has_privs_of_role(GetUserId(), DatumGetObjectId(ownerId)))
     224          72 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_object_type(classId, objectId),
     225             :                            old_name);
     226             : 
     227             :         /* User must have CREATE privilege on the namespace */
     228         174 :         if (OidIsValid(namespaceId))
     229             :         {
     230         144 :             aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(),
     231             :                                         ACL_CREATE);
     232         144 :             if (aclresult != ACLCHECK_OK)
     233           0 :                 aclcheck_error(aclresult, OBJECT_SCHEMA,
     234           0 :                                get_namespace_name(namespaceId));
     235             :         }
     236             : 
     237         174 :         if (classId == SubscriptionRelationId)
     238             :         {
     239             :             Form_pg_subscription form;
     240             : 
     241             :             /* must have CREATE privilege on database */
     242          18 :             aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
     243             :                                         GetUserId(), ACL_CREATE);
     244          18 :             if (aclresult != ACLCHECK_OK)
     245           6 :                 aclcheck_error(aclresult, OBJECT_DATABASE,
     246           6 :                                get_database_name(MyDatabaseId));
     247             : 
     248             :             /*
     249             :              * Don't allow non-superuser modification of a subscription with
     250             :              * password_required=false.
     251             :              */
     252          12 :             form = (Form_pg_subscription) GETSTRUCT(oldtup);
     253          12 :             if (!form->subpasswordrequired && !superuser())
     254           0 :                 ereport(ERROR,
     255             :                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     256             :                          errmsg("password_required=false is superuser-only"),
     257             :                          errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
     258             :         }
     259             :     }
     260             : 
     261             :     /*
     262             :      * Check for duplicate name (more friendly than unique-index failure).
     263             :      * Since this is just a friendliness check, we can just skip it in cases
     264             :      * where there isn't suitable support.
     265             :      */
     266         326 :     if (classId == ProcedureRelationId)
     267             :     {
     268          72 :         Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(oldtup);
     269             : 
     270          72 :         IsThereFunctionInNamespace(new_name, proc->pronargs,
     271             :                                    &proc->proargtypes, proc->pronamespace);
     272             :     }
     273         254 :     else if (classId == CollationRelationId)
     274             :     {
     275          12 :         Form_pg_collation coll = (Form_pg_collation) GETSTRUCT(oldtup);
     276             : 
     277          12 :         IsThereCollationInNamespace(new_name, coll->collnamespace);
     278             :     }
     279         242 :     else if (classId == OperatorClassRelationId)
     280             :     {
     281          18 :         Form_pg_opclass opc = (Form_pg_opclass) GETSTRUCT(oldtup);
     282             : 
     283          18 :         IsThereOpClassInNamespace(new_name, opc->opcmethod,
     284             :                                   opc->opcnamespace);
     285             :     }
     286         224 :     else if (classId == OperatorFamilyRelationId)
     287             :     {
     288          18 :         Form_pg_opfamily opf = (Form_pg_opfamily) GETSTRUCT(oldtup);
     289             : 
     290          18 :         IsThereOpFamilyInNamespace(new_name, opf->opfmethod,
     291             :                                    opf->opfnamespace);
     292             :     }
     293         206 :     else if (classId == SubscriptionRelationId)
     294             :     {
     295          26 :         if (SearchSysCacheExists2(SUBSCRIPTIONNAME,
     296             :                                   ObjectIdGetDatum(MyDatabaseId),
     297             :                                   CStringGetDatum(new_name)))
     298           0 :             report_name_conflict(classId, new_name);
     299             : 
     300             :         /* Also enforce regression testing naming rules, if enabled */
     301             : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
     302             :         if (strncmp(new_name, "regress_", 8) != 0)
     303             :             elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
     304             : #endif
     305             : 
     306             :         /* Wake up related replication workers to handle this change quickly */
     307          26 :         LogicalRepWorkersWakeupAtCommit(objectId);
     308             :     }
     309         180 :     else if (nameCacheId >= 0)
     310             :     {
     311         180 :         if (OidIsValid(namespaceId))
     312             :         {
     313          96 :             if (SearchSysCacheExists2(nameCacheId,
     314             :                                       CStringGetDatum(new_name),
     315             :                                       ObjectIdGetDatum(namespaceId)))
     316          36 :                 report_namespace_conflict(classId, new_name, namespaceId);
     317             :         }
     318             :         else
     319             :         {
     320          84 :             if (SearchSysCacheExists1(nameCacheId,
     321             :                                       CStringGetDatum(new_name)))
     322          24 :                 report_name_conflict(classId, new_name);
     323             :         }
     324             :     }
     325             : 
     326             :     /* Build modified tuple */
     327         236 :     values = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(Datum));
     328         236 :     nulls = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(bool));
     329         236 :     replaces = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(bool));
     330         236 :     namestrcpy(&nameattrdata, new_name);
     331         236 :     values[Anum_name - 1] = NameGetDatum(&nameattrdata);
     332         236 :     replaces[Anum_name - 1] = true;
     333         236 :     newtup = heap_modify_tuple(oldtup, RelationGetDescr(rel),
     334             :                                values, nulls, replaces);
     335             : 
     336             :     /* Perform actual update */
     337         236 :     CatalogTupleUpdate(rel, &oldtup->t_self, newtup);
     338             : 
     339         236 :     InvokeObjectPostAlterHook(classId, objectId, 0);
     340             : 
     341             :     /* Release memory */
     342         236 :     pfree(values);
     343         236 :     pfree(nulls);
     344         236 :     pfree(replaces);
     345         236 :     heap_freetuple(newtup);
     346             : 
     347         236 :     ReleaseSysCache(oldtup);
     348         236 : }
     349             : 
     350             : /*
     351             :  * Executes an ALTER OBJECT / RENAME TO statement.  Based on the object
     352             :  * type, the function appropriate to that type is executed.
     353             :  *
     354             :  * Return value is the address of the renamed object.
     355             :  */
     356             : ObjectAddress
     357        1512 : ExecRenameStmt(RenameStmt *stmt)
     358             : {
     359        1512 :     switch (stmt->renameType)
     360             :     {
     361          84 :         case OBJECT_TABCONSTRAINT:
     362             :         case OBJECT_DOMCONSTRAINT:
     363          84 :             return RenameConstraint(stmt);
     364             : 
     365           6 :         case OBJECT_DATABASE:
     366           6 :             return RenameDatabase(stmt->subname, stmt->newname);
     367             : 
     368          30 :         case OBJECT_ROLE:
     369          30 :             return RenameRole(stmt->subname, stmt->newname);
     370             : 
     371          20 :         case OBJECT_SCHEMA:
     372          20 :             return RenameSchema(stmt->subname, stmt->newname);
     373             : 
     374           6 :         case OBJECT_TABLESPACE:
     375           6 :             return RenameTableSpace(stmt->subname, stmt->newname);
     376             : 
     377         510 :         case OBJECT_TABLE:
     378             :         case OBJECT_SEQUENCE:
     379             :         case OBJECT_VIEW:
     380             :         case OBJECT_MATVIEW:
     381             :         case OBJECT_INDEX:
     382             :         case OBJECT_FOREIGN_TABLE:
     383         510 :             return RenameRelation(stmt);
     384             : 
     385         316 :         case OBJECT_COLUMN:
     386             :         case OBJECT_ATTRIBUTE:
     387         316 :             return renameatt(stmt);
     388             : 
     389          34 :         case OBJECT_RULE:
     390          34 :             return RenameRewriteRule(stmt->relation, stmt->subname,
     391          34 :                                      stmt->newname);
     392             : 
     393          40 :         case OBJECT_TRIGGER:
     394          40 :             return renametrig(stmt);
     395             : 
     396          18 :         case OBJECT_POLICY:
     397          18 :             return rename_policy(stmt);
     398             : 
     399          32 :         case OBJECT_DOMAIN:
     400             :         case OBJECT_TYPE:
     401          32 :             return RenameType(stmt);
     402             : 
     403         416 :         case OBJECT_AGGREGATE:
     404             :         case OBJECT_COLLATION:
     405             :         case OBJECT_CONVERSION:
     406             :         case OBJECT_EVENT_TRIGGER:
     407             :         case OBJECT_FDW:
     408             :         case OBJECT_FOREIGN_SERVER:
     409             :         case OBJECT_FUNCTION:
     410             :         case OBJECT_OPCLASS:
     411             :         case OBJECT_OPFAMILY:
     412             :         case OBJECT_LANGUAGE:
     413             :         case OBJECT_PROCEDURE:
     414             :         case OBJECT_ROUTINE:
     415             :         case OBJECT_STATISTIC_EXT:
     416             :         case OBJECT_TSCONFIGURATION:
     417             :         case OBJECT_TSDICTIONARY:
     418             :         case OBJECT_TSPARSER:
     419             :         case OBJECT_TSTEMPLATE:
     420             :         case OBJECT_PUBLICATION:
     421             :         case OBJECT_SUBSCRIPTION:
     422             :             {
     423             :                 ObjectAddress address;
     424             :                 Relation    catalog;
     425             : 
     426         416 :                 address = get_object_address(stmt->renameType,
     427             :                                              stmt->object,
     428             :                                              NULL,
     429             :                                              AccessExclusiveLock, false);
     430             : 
     431         404 :                 catalog = table_open(address.classId, RowExclusiveLock);
     432         404 :                 AlterObjectRename_internal(catalog,
     433             :                                            address.objectId,
     434         404 :                                            stmt->newname);
     435         236 :                 table_close(catalog, RowExclusiveLock);
     436             : 
     437         236 :                 return address;
     438             :             }
     439             : 
     440           0 :         default:
     441           0 :             elog(ERROR, "unrecognized rename stmt type: %d",
     442             :                  (int) stmt->renameType);
     443             :             return InvalidObjectAddress;    /* keep compiler happy */
     444             :     }
     445             : }
     446             : 
     447             : /*
     448             :  * Executes an ALTER OBJECT / [NO] DEPENDS ON EXTENSION statement.
     449             :  *
     450             :  * Return value is the address of the altered object.  refAddress is an output
     451             :  * argument which, if not null, receives the address of the object that the
     452             :  * altered object now depends on.
     453             :  */
     454             : ObjectAddress
     455          46 : ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress)
     456             : {
     457             :     ObjectAddress address;
     458             :     ObjectAddress refAddr;
     459             :     Relation    rel;
     460             : 
     461             :     address =
     462          46 :         get_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object,
     463             :                               &rel, AccessExclusiveLock, false);
     464             : 
     465             :     /*
     466             :      * Verify that the user is entitled to run the command.
     467             :      *
     468             :      * We don't check any privileges on the extension, because that's not
     469             :      * needed.  The object owner is stipulating, by running this command, that
     470             :      * the extension owner can drop the object whenever they feel like it,
     471             :      * which is not considered a problem.
     472             :      */
     473          46 :     check_object_ownership(GetUserId(),
     474             :                            stmt->objectType, address, stmt->object, rel);
     475             : 
     476             :     /*
     477             :      * If a relation was involved, it would have been opened and locked. We
     478             :      * don't need the relation here, but we'll retain the lock until commit.
     479             :      */
     480          46 :     if (rel)
     481          34 :         table_close(rel, NoLock);
     482             : 
     483          46 :     refAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname,
     484             :                                  NULL, AccessExclusiveLock, false);
     485          46 :     if (refAddress)
     486          46 :         *refAddress = refAddr;
     487             : 
     488          46 :     if (stmt->remove)
     489             :     {
     490           8 :         deleteDependencyRecordsForSpecific(address.classId, address.objectId,
     491             :                                            DEPENDENCY_AUTO_EXTENSION,
     492             :                                            refAddr.classId, refAddr.objectId);
     493             :     }
     494             :     else
     495             :     {
     496             :         List       *currexts;
     497             : 
     498             :         /* Avoid duplicates */
     499          38 :         currexts = getAutoExtensionsOfObject(address.classId,
     500             :                                              address.objectId);
     501          38 :         if (!list_member_oid(currexts, refAddr.objectId))
     502          36 :             recordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION);
     503             :     }
     504             : 
     505          46 :     return address;
     506             : }
     507             : 
     508             : /*
     509             :  * Executes an ALTER OBJECT / SET SCHEMA statement.  Based on the object
     510             :  * type, the function appropriate to that type is executed.
     511             :  *
     512             :  * Return value is that of the altered object.
     513             :  *
     514             :  * oldSchemaAddr is an output argument which, if not NULL, is set to the object
     515             :  * address of the original schema.
     516             :  */
     517             : ObjectAddress
     518         398 : ExecAlterObjectSchemaStmt(AlterObjectSchemaStmt *stmt,
     519             :                           ObjectAddress *oldSchemaAddr)
     520             : {
     521             :     ObjectAddress address;
     522             :     Oid         oldNspOid;
     523             : 
     524         398 :     switch (stmt->objectType)
     525             :     {
     526          12 :         case OBJECT_EXTENSION:
     527          12 :             address = AlterExtensionNamespace(strVal(stmt->object), stmt->newschema,
     528             :                                               oldSchemaAddr ? &oldNspOid : NULL);
     529           8 :             break;
     530             : 
     531         104 :         case OBJECT_FOREIGN_TABLE:
     532             :         case OBJECT_SEQUENCE:
     533             :         case OBJECT_TABLE:
     534             :         case OBJECT_VIEW:
     535             :         case OBJECT_MATVIEW:
     536         104 :             address = AlterTableNamespace(stmt,
     537             :                                           oldSchemaAddr ? &oldNspOid : NULL);
     538          96 :             break;
     539             : 
     540          18 :         case OBJECT_DOMAIN:
     541             :         case OBJECT_TYPE:
     542          18 :             address = AlterTypeNamespace(castNode(List, stmt->object), stmt->newschema,
     543             :                                          stmt->objectType,
     544             :                                          oldSchemaAddr ? &oldNspOid : NULL);
     545          18 :             break;
     546             : 
     547             :             /* generic code path */
     548         264 :         case OBJECT_AGGREGATE:
     549             :         case OBJECT_COLLATION:
     550             :         case OBJECT_CONVERSION:
     551             :         case OBJECT_FUNCTION:
     552             :         case OBJECT_OPERATOR:
     553             :         case OBJECT_OPCLASS:
     554             :         case OBJECT_OPFAMILY:
     555             :         case OBJECT_PROCEDURE:
     556             :         case OBJECT_ROUTINE:
     557             :         case OBJECT_STATISTIC_EXT:
     558             :         case OBJECT_TSCONFIGURATION:
     559             :         case OBJECT_TSDICTIONARY:
     560             :         case OBJECT_TSPARSER:
     561             :         case OBJECT_TSTEMPLATE:
     562             :             {
     563             :                 Relation    catalog;
     564             :                 Oid         classId;
     565             :                 Oid         nspOid;
     566             : 
     567         264 :                 address = get_object_address(stmt->objectType,
     568             :                                              stmt->object,
     569             :                                              NULL,
     570             :                                              AccessExclusiveLock,
     571             :                                              false);
     572         258 :                 classId = address.classId;
     573         258 :                 catalog = table_open(classId, RowExclusiveLock);
     574         258 :                 nspOid = LookupCreationNamespace(stmt->newschema);
     575             : 
     576         258 :                 oldNspOid = AlterObjectNamespace_internal(catalog, address.objectId,
     577             :                                                           nspOid);
     578         144 :                 table_close(catalog, RowExclusiveLock);
     579             :             }
     580         144 :             break;
     581             : 
     582           0 :         default:
     583           0 :             elog(ERROR, "unrecognized AlterObjectSchemaStmt type: %d",
     584             :                  (int) stmt->objectType);
     585             :             return InvalidObjectAddress;    /* keep compiler happy */
     586             :     }
     587             : 
     588         266 :     if (oldSchemaAddr)
     589         266 :         ObjectAddressSet(*oldSchemaAddr, NamespaceRelationId, oldNspOid);
     590             : 
     591         266 :     return address;
     592             : }
     593             : 
     594             : /*
     595             :  * Change an object's namespace given its classOid and object Oid.
     596             :  *
     597             :  * Objects that don't have a namespace should be ignored, as should
     598             :  * dependent types such as array types.
     599             :  *
     600             :  * This function is currently used only by ALTER EXTENSION SET SCHEMA,
     601             :  * so it only needs to cover object kinds that can be members of an
     602             :  * extension, and it can silently ignore dependent types --- we assume
     603             :  * those will be moved when their parent object is moved.
     604             :  *
     605             :  * Returns the OID of the object's previous namespace, or InvalidOid if
     606             :  * object doesn't have a schema or was ignored due to being a dependent type.
     607             :  */
     608             : Oid
     609          42 : AlterObjectNamespace_oid(Oid classId, Oid objid, Oid nspOid,
     610             :                          ObjectAddresses *objsMoved)
     611             : {
     612          42 :     Oid         oldNspOid = InvalidOid;
     613             : 
     614          42 :     switch (classId)
     615             :     {
     616           2 :         case RelationRelationId:
     617             :             {
     618             :                 Relation    rel;
     619             : 
     620           2 :                 rel = relation_open(objid, AccessExclusiveLock);
     621           2 :                 oldNspOid = RelationGetNamespace(rel);
     622             : 
     623           2 :                 AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
     624             : 
     625           2 :                 relation_close(rel, NoLock);
     626           2 :                 break;
     627             :             }
     628             : 
     629          16 :         case TypeRelationId:
     630          16 :             oldNspOid = AlterTypeNamespace_oid(objid, nspOid, true, objsMoved);
     631          16 :             break;
     632             : 
     633          22 :         case ProcedureRelationId:
     634             :         case CollationRelationId:
     635             :         case ConversionRelationId:
     636             :         case OperatorRelationId:
     637             :         case OperatorClassRelationId:
     638             :         case OperatorFamilyRelationId:
     639             :         case StatisticExtRelationId:
     640             :         case TSParserRelationId:
     641             :         case TSDictionaryRelationId:
     642             :         case TSTemplateRelationId:
     643             :         case TSConfigRelationId:
     644             :             {
     645             :                 Relation    catalog;
     646             : 
     647          22 :                 catalog = table_open(classId, RowExclusiveLock);
     648             : 
     649          22 :                 oldNspOid = AlterObjectNamespace_internal(catalog, objid,
     650             :                                                           nspOid);
     651             : 
     652          22 :                 table_close(catalog, RowExclusiveLock);
     653             :             }
     654          22 :             break;
     655             : 
     656          42 :         default:
     657             :             /* ignore object types that don't have schema-qualified names */
     658             :             Assert(get_object_attnum_namespace(classId) == InvalidAttrNumber);
     659             :     }
     660             : 
     661          42 :     return oldNspOid;
     662             : }
     663             : 
     664             : /*
     665             :  * Generic function to change the namespace of a given object, for simple
     666             :  * cases (won't work for tables, nor other cases where we need to do more
     667             :  * than change the namespace column of a single catalog entry).
     668             :  *
     669             :  * rel: catalog relation containing object (RowExclusiveLock'd by caller)
     670             :  * objid: OID of object to change the namespace of
     671             :  * nspOid: OID of new namespace
     672             :  *
     673             :  * Returns the OID of the object's previous namespace.
     674             :  */
     675             : static Oid
     676         280 : AlterObjectNamespace_internal(Relation rel, Oid objid, Oid nspOid)
     677             : {
     678         280 :     Oid         classId = RelationGetRelid(rel);
     679         280 :     int         oidCacheId = get_object_catcache_oid(classId);
     680         280 :     int         nameCacheId = get_object_catcache_name(classId);
     681         280 :     AttrNumber  Anum_name = get_object_attnum_name(classId);
     682         280 :     AttrNumber  Anum_namespace = get_object_attnum_namespace(classId);
     683         280 :     AttrNumber  Anum_owner = get_object_attnum_owner(classId);
     684             :     Oid         oldNspOid;
     685             :     Datum       name,
     686             :                 namespace;
     687             :     bool        isnull;
     688             :     HeapTuple   tup,
     689             :                 newtup;
     690             :     Datum      *values;
     691             :     bool       *nulls;
     692             :     bool       *replaces;
     693             : 
     694         280 :     tup = SearchSysCacheCopy1(oidCacheId, ObjectIdGetDatum(objid));
     695         280 :     if (!HeapTupleIsValid(tup)) /* should not happen */
     696           0 :         elog(ERROR, "cache lookup failed for object %u of catalog \"%s\"",
     697             :              objid, RelationGetRelationName(rel));
     698             : 
     699         280 :     name = heap_getattr(tup, Anum_name, RelationGetDescr(rel), &isnull);
     700             :     Assert(!isnull);
     701         280 :     namespace = heap_getattr(tup, Anum_namespace, RelationGetDescr(rel),
     702             :                              &isnull);
     703             :     Assert(!isnull);
     704         280 :     oldNspOid = DatumGetObjectId(namespace);
     705             : 
     706             :     /*
     707             :      * If the object is already in the correct namespace, we don't need to do
     708             :      * anything except fire the object access hook.
     709             :      */
     710         280 :     if (oldNspOid == nspOid)
     711             :     {
     712           6 :         InvokeObjectPostAlterHook(classId, objid, 0);
     713           6 :         return oldNspOid;
     714             :     }
     715             : 
     716             :     /* Check basic namespace related issues */
     717         274 :     CheckSetNamespace(oldNspOid, nspOid);
     718             : 
     719             :     /* Permission checks ... superusers can always do it */
     720         274 :     if (!superuser())
     721             :     {
     722             :         Datum       owner;
     723             :         Oid         ownerId;
     724             :         AclResult   aclresult;
     725             : 
     726             :         /* Fail if object does not have an explicit owner */
     727         156 :         if (Anum_owner <= 0)
     728           0 :             ereport(ERROR,
     729             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     730             :                      errmsg("must be superuser to set schema of %s",
     731             :                             getObjectDescriptionOids(classId, objid))));
     732             : 
     733             :         /* Otherwise, must be owner of the existing object */
     734         156 :         owner = heap_getattr(tup, Anum_owner, RelationGetDescr(rel), &isnull);
     735             :         Assert(!isnull);
     736         156 :         ownerId = DatumGetObjectId(owner);
     737             : 
     738         156 :         if (!has_privs_of_role(GetUserId(), ownerId))
     739          54 :             aclcheck_error(ACLCHECK_NOT_OWNER, get_object_type(classId, objid),
     740          54 :                            NameStr(*(DatumGetName(name))));
     741             : 
     742             :         /* User must have CREATE privilege on new namespace */
     743         102 :         aclresult = object_aclcheck(NamespaceRelationId, nspOid, GetUserId(), ACL_CREATE);
     744         102 :         if (aclresult != ACLCHECK_OK)
     745           0 :             aclcheck_error(aclresult, OBJECT_SCHEMA,
     746           0 :                            get_namespace_name(nspOid));
     747             :     }
     748             : 
     749             :     /*
     750             :      * Check for duplicate name (more friendly than unique-index failure).
     751             :      * Since this is just a friendliness check, we can just skip it in cases
     752             :      * where there isn't suitable support.
     753             :      */
     754         220 :     if (classId == ProcedureRelationId)
     755             :     {
     756          64 :         Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tup);
     757             : 
     758          64 :         IsThereFunctionInNamespace(NameStr(proc->proname), proc->pronargs,
     759             :                                    &proc->proargtypes, nspOid);
     760             :     }
     761         156 :     else if (classId == CollationRelationId)
     762             :     {
     763           6 :         Form_pg_collation coll = (Form_pg_collation) GETSTRUCT(tup);
     764             : 
     765           6 :         IsThereCollationInNamespace(NameStr(coll->collname), nspOid);
     766             :     }
     767         150 :     else if (classId == OperatorClassRelationId)
     768             :     {
     769          18 :         Form_pg_opclass opc = (Form_pg_opclass) GETSTRUCT(tup);
     770             : 
     771          18 :         IsThereOpClassInNamespace(NameStr(opc->opcname),
     772             :                                   opc->opcmethod, nspOid);
     773             :     }
     774         132 :     else if (classId == OperatorFamilyRelationId)
     775             :     {
     776          18 :         Form_pg_opfamily opf = (Form_pg_opfamily) GETSTRUCT(tup);
     777             : 
     778          18 :         IsThereOpFamilyInNamespace(NameStr(opf->opfname),
     779             :                                    opf->opfmethod, nspOid);
     780             :     }
     781         216 :     else if (nameCacheId >= 0 &&
     782         102 :              SearchSysCacheExists2(nameCacheId, name,
     783             :                                    ObjectIdGetDatum(nspOid)))
     784          36 :         report_namespace_conflict(classId,
     785          36 :                                   NameStr(*(DatumGetName(name))),
     786             :                                   nspOid);
     787             : 
     788             :     /* Build modified tuple */
     789         160 :     values = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(Datum));
     790         160 :     nulls = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(bool));
     791         160 :     replaces = palloc0(RelationGetNumberOfAttributes(rel) * sizeof(bool));
     792         160 :     values[Anum_namespace - 1] = ObjectIdGetDatum(nspOid);
     793         160 :     replaces[Anum_namespace - 1] = true;
     794         160 :     newtup = heap_modify_tuple(tup, RelationGetDescr(rel),
     795             :                                values, nulls, replaces);
     796             : 
     797             :     /* Perform actual update */
     798         160 :     CatalogTupleUpdate(rel, &tup->t_self, newtup);
     799             : 
     800             :     /* Release memory */
     801         160 :     pfree(values);
     802         160 :     pfree(nulls);
     803         160 :     pfree(replaces);
     804             : 
     805             :     /* update dependency to point to the new schema */
     806         160 :     if (changeDependencyFor(classId, objid,
     807             :                             NamespaceRelationId, oldNspOid, nspOid) != 1)
     808           0 :         elog(ERROR, "could not change schema dependency for object %u",
     809             :              objid);
     810             : 
     811         160 :     InvokeObjectPostAlterHook(classId, objid, 0);
     812             : 
     813         160 :     return oldNspOid;
     814             : }
     815             : 
     816             : /*
     817             :  * Executes an ALTER OBJECT / OWNER TO statement.  Based on the object
     818             :  * type, the function appropriate to that type is executed.
     819             :  */
     820             : ObjectAddress
     821        1572 : ExecAlterOwnerStmt(AlterOwnerStmt *stmt)
     822             : {
     823        1572 :     Oid         newowner = get_rolespec_oid(stmt->newowner, false);
     824             : 
     825        1560 :     switch (stmt->objectType)
     826             :     {
     827          50 :         case OBJECT_DATABASE:
     828          50 :             return AlterDatabaseOwner(strVal(stmt->object), newowner);
     829             : 
     830          54 :         case OBJECT_SCHEMA:
     831          54 :             return AlterSchemaOwner(strVal(stmt->object), newowner);
     832             : 
     833         120 :         case OBJECT_TYPE:
     834             :         case OBJECT_DOMAIN:     /* same as TYPE */
     835         120 :             return AlterTypeOwner(castNode(List, stmt->object), newowner, stmt->objectType);
     836             :             break;
     837             : 
     838          20 :         case OBJECT_FDW:
     839          20 :             return AlterForeignDataWrapperOwner(strVal(stmt->object),
     840             :                                                 newowner);
     841             : 
     842          68 :         case OBJECT_FOREIGN_SERVER:
     843          68 :             return AlterForeignServerOwner(strVal(stmt->object),
     844             :                                            newowner);
     845             : 
     846          14 :         case OBJECT_EVENT_TRIGGER:
     847          14 :             return AlterEventTriggerOwner(strVal(stmt->object),
     848             :                                           newowner);
     849             : 
     850          26 :         case OBJECT_PUBLICATION:
     851          26 :             return AlterPublicationOwner(strVal(stmt->object),
     852             :                                          newowner);
     853             : 
     854          18 :         case OBJECT_SUBSCRIPTION:
     855          18 :             return AlterSubscriptionOwner(strVal(stmt->object),
     856             :                                           newowner);
     857             : 
     858             :             /* Generic cases */
     859        1190 :         case OBJECT_AGGREGATE:
     860             :         case OBJECT_COLLATION:
     861             :         case OBJECT_CONVERSION:
     862             :         case OBJECT_FUNCTION:
     863             :         case OBJECT_LANGUAGE:
     864             :         case OBJECT_LARGEOBJECT:
     865             :         case OBJECT_OPERATOR:
     866             :         case OBJECT_OPCLASS:
     867             :         case OBJECT_OPFAMILY:
     868             :         case OBJECT_PROCEDURE:
     869             :         case OBJECT_ROUTINE:
     870             :         case OBJECT_STATISTIC_EXT:
     871             :         case OBJECT_TABLESPACE:
     872             :         case OBJECT_TSDICTIONARY:
     873             :         case OBJECT_TSCONFIGURATION:
     874             :             {
     875             :                 ObjectAddress address;
     876             : 
     877        1190 :                 address = get_object_address(stmt->objectType,
     878             :                                              stmt->object,
     879             :                                              NULL,
     880             :                                              AccessExclusiveLock,
     881             :                                              false);
     882             : 
     883        1182 :                 AlterObjectOwner_internal(address.classId, address.objectId,
     884             :                                           newowner);
     885             : 
     886        1008 :                 return address;
     887             :             }
     888             :             break;
     889             : 
     890           0 :         default:
     891           0 :             elog(ERROR, "unrecognized AlterOwnerStmt type: %d",
     892             :                  (int) stmt->objectType);
     893             :             return InvalidObjectAddress;    /* keep compiler happy */
     894             :     }
     895             : }
     896             : 
     897             : /*
     898             :  * Generic function to change the ownership of a given object, for simple
     899             :  * cases (won't work for tables, nor other cases where we need to do more than
     900             :  * change the ownership column of a single catalog entry).
     901             :  *
     902             :  * classId: OID of catalog containing object
     903             :  * objectId: OID of object to change the ownership of
     904             :  * new_ownerId: OID of new object owner
     905             :  *
     906             :  * This will work on large objects, but we have to beware of the fact that
     907             :  * classId isn't the OID of the catalog to modify in that case.
     908             :  */
     909             : void
     910        1202 : AlterObjectOwner_internal(Oid classId, Oid objectId, Oid new_ownerId)
     911             : {
     912             :     /* For large objects, the catalog to modify is pg_largeobject_metadata */
     913        1202 :     Oid         catalogId = (classId == LargeObjectRelationId) ? LargeObjectMetadataRelationId : classId;
     914        1202 :     AttrNumber  Anum_oid = get_object_attnum_oid(catalogId);
     915        1202 :     AttrNumber  Anum_owner = get_object_attnum_owner(catalogId);
     916        1202 :     AttrNumber  Anum_namespace = get_object_attnum_namespace(catalogId);
     917        1202 :     AttrNumber  Anum_acl = get_object_attnum_acl(catalogId);
     918        1202 :     AttrNumber  Anum_name = get_object_attnum_name(catalogId);
     919             :     Relation    rel;
     920             :     HeapTuple   oldtup;
     921             :     Datum       datum;
     922             :     bool        isnull;
     923             :     Oid         old_ownerId;
     924        1202 :     Oid         namespaceId = InvalidOid;
     925             : 
     926        1202 :     rel = table_open(catalogId, RowExclusiveLock);
     927             : 
     928             :     /* Search tuple and lock it. */
     929             :     oldtup =
     930        1202 :         get_catalog_object_by_oid_extended(rel, Anum_oid, objectId, true);
     931        1202 :     if (oldtup == NULL)
     932           0 :         elog(ERROR, "cache lookup failed for object %u of catalog \"%s\"",
     933             :              objectId, RelationGetRelationName(rel));
     934             : 
     935        1202 :     datum = heap_getattr(oldtup, Anum_owner,
     936             :                          RelationGetDescr(rel), &isnull);
     937             :     Assert(!isnull);
     938        1202 :     old_ownerId = DatumGetObjectId(datum);
     939             : 
     940        1202 :     if (Anum_namespace != InvalidAttrNumber)
     941             :     {
     942        1044 :         datum = heap_getattr(oldtup, Anum_namespace,
     943             :                              RelationGetDescr(rel), &isnull);
     944             :         Assert(!isnull);
     945        1044 :         namespaceId = DatumGetObjectId(datum);
     946             :     }
     947             : 
     948        1202 :     if (old_ownerId != new_ownerId)
     949             :     {
     950             :         AttrNumber  nattrs;
     951             :         HeapTuple   newtup;
     952             :         Datum      *values;
     953             :         bool       *nulls;
     954             :         bool       *replaces;
     955             : 
     956             :         /* Superusers can bypass permission checks */
     957         372 :         if (!superuser())
     958             :         {
     959             :             /* must be owner */
     960         234 :             if (!has_privs_of_role(GetUserId(), old_ownerId))
     961             :             {
     962             :                 char       *objname;
     963             :                 char        namebuf[NAMEDATALEN];
     964             : 
     965          60 :                 if (Anum_name != InvalidAttrNumber)
     966             :                 {
     967          60 :                     datum = heap_getattr(oldtup, Anum_name,
     968             :                                          RelationGetDescr(rel), &isnull);
     969             :                     Assert(!isnull);
     970          60 :                     objname = NameStr(*DatumGetName(datum));
     971             :                 }
     972             :                 else
     973             :                 {
     974           0 :                     snprintf(namebuf, sizeof(namebuf), "%u", objectId);
     975           0 :                     objname = namebuf;
     976             :                 }
     977          60 :                 aclcheck_error(ACLCHECK_NOT_OWNER,
     978             :                                get_object_type(catalogId, objectId),
     979             :                                objname);
     980             :             }
     981             :             /* Must be able to become new owner */
     982         174 :             check_can_set_role(GetUserId(), new_ownerId);
     983             : 
     984             :             /* New owner must have CREATE privilege on namespace */
     985          60 :             if (OidIsValid(namespaceId))
     986             :             {
     987             :                 AclResult   aclresult;
     988             : 
     989          54 :                 aclresult = object_aclcheck(NamespaceRelationId, namespaceId, new_ownerId,
     990             :                                             ACL_CREATE);
     991          54 :                 if (aclresult != ACLCHECK_OK)
     992           0 :                     aclcheck_error(aclresult, OBJECT_SCHEMA,
     993           0 :                                    get_namespace_name(namespaceId));
     994             :             }
     995             :         }
     996             : 
     997             :         /* Build a modified tuple */
     998         198 :         nattrs = RelationGetNumberOfAttributes(rel);
     999         198 :         values = palloc0(nattrs * sizeof(Datum));
    1000         198 :         nulls = palloc0(nattrs * sizeof(bool));
    1001         198 :         replaces = palloc0(nattrs * sizeof(bool));
    1002         198 :         values[Anum_owner - 1] = ObjectIdGetDatum(new_ownerId);
    1003         198 :         replaces[Anum_owner - 1] = true;
    1004             : 
    1005             :         /*
    1006             :          * Determine the modified ACL for the new owner.  This is only
    1007             :          * necessary when the ACL is non-null.
    1008             :          */
    1009         198 :         if (Anum_acl != InvalidAttrNumber)
    1010             :         {
    1011         100 :             datum = heap_getattr(oldtup,
    1012             :                                  Anum_acl, RelationGetDescr(rel), &isnull);
    1013         100 :             if (!isnull)
    1014             :             {
    1015             :                 Acl        *newAcl;
    1016             : 
    1017           8 :                 newAcl = aclnewowner(DatumGetAclP(datum),
    1018             :                                      old_ownerId, new_ownerId);
    1019           8 :                 values[Anum_acl - 1] = PointerGetDatum(newAcl);
    1020           8 :                 replaces[Anum_acl - 1] = true;
    1021             :             }
    1022             :         }
    1023             : 
    1024         198 :         newtup = heap_modify_tuple(oldtup, RelationGetDescr(rel),
    1025             :                                    values, nulls, replaces);
    1026             : 
    1027             :         /* Perform actual update */
    1028         198 :         CatalogTupleUpdate(rel, &newtup->t_self, newtup);
    1029             : 
    1030         198 :         UnlockTuple(rel, &oldtup->t_self, InplaceUpdateTupleLock);
    1031             : 
    1032             :         /* Update owner dependency reference */
    1033         198 :         changeDependencyOnOwner(classId, objectId, new_ownerId);
    1034             : 
    1035             :         /* Release memory */
    1036         198 :         pfree(values);
    1037         198 :         pfree(nulls);
    1038         198 :         pfree(replaces);
    1039             :     }
    1040             :     else
    1041         830 :         UnlockTuple(rel, &oldtup->t_self, InplaceUpdateTupleLock);
    1042             : 
    1043             :     /* Note the post-alter hook gets classId not catalogId */
    1044        1028 :     InvokeObjectPostAlterHook(classId, objectId, 0);
    1045             : 
    1046        1028 :     table_close(rel, RowExclusiveLock);
    1047        1028 : }

Generated by: LCOV version 1.14