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

Generated by: LCOV version 1.14