LCOV - code coverage report
Current view: top level - src/backend/commands - opclasscmds.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 553 617 89.6 %
Date: 2026-01-03 09:16:53 Functions: 21 21 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * opclasscmds.c
       4             :  *
       5             :  *    Routines for opclass (and opfamily) manipulation commands
       6             :  *
       7             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       8             :  * Portions Copyright (c) 1994, Regents of the University of California
       9             :  *
      10             :  *
      11             :  * IDENTIFICATION
      12             :  *    src/backend/commands/opclasscmds.c
      13             :  *
      14             :  *-------------------------------------------------------------------------
      15             :  */
      16             : #include "postgres.h"
      17             : 
      18             : #include <limits.h>
      19             : 
      20             : #include "access/genam.h"
      21             : #include "access/hash.h"
      22             : #include "access/htup_details.h"
      23             : #include "access/nbtree.h"
      24             : #include "access/table.h"
      25             : #include "catalog/catalog.h"
      26             : #include "catalog/dependency.h"
      27             : #include "catalog/indexing.h"
      28             : #include "catalog/objectaccess.h"
      29             : #include "catalog/pg_am.h"
      30             : #include "catalog/pg_amop.h"
      31             : #include "catalog/pg_amproc.h"
      32             : #include "catalog/pg_namespace.h"
      33             : #include "catalog/pg_opclass.h"
      34             : #include "catalog/pg_operator.h"
      35             : #include "catalog/pg_opfamily.h"
      36             : #include "catalog/pg_proc.h"
      37             : #include "catalog/pg_type.h"
      38             : #include "commands/defrem.h"
      39             : #include "commands/event_trigger.h"
      40             : #include "miscadmin.h"
      41             : #include "parser/parse_func.h"
      42             : #include "parser/parse_oper.h"
      43             : #include "parser/parse_type.h"
      44             : #include "utils/acl.h"
      45             : #include "utils/builtins.h"
      46             : #include "utils/fmgroids.h"
      47             : #include "utils/lsyscache.h"
      48             : #include "utils/rel.h"
      49             : #include "utils/syscache.h"
      50             : 
      51             : static void AlterOpFamilyAdd(AlterOpFamilyStmt *stmt,
      52             :                              Oid amoid, Oid opfamilyoid,
      53             :                              int maxOpNumber, int maxProcNumber,
      54             :                              int optsProcNumber, List *items);
      55             : static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt,
      56             :                               Oid amoid, Oid opfamilyoid,
      57             :                               int maxOpNumber, int maxProcNumber,
      58             :                               List *items);
      59             : static void processTypesSpec(List *args, Oid *lefttype, Oid *righttype);
      60             : static void assignOperTypes(OpFamilyMember *member, Oid amoid, Oid typeoid);
      61             : static void assignProcTypes(OpFamilyMember *member, Oid amoid, Oid typeoid,
      62             :                             int opclassOptsProcNum);
      63             : static void addFamilyMember(List **list, OpFamilyMember *member);
      64             : static void storeOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
      65             :                            List *operators, bool isAdd);
      66             : static void storeProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
      67             :                             List *procedures, bool isAdd);
      68             : static bool typeDepNeeded(Oid typid, OpFamilyMember *member);
      69             : static void dropOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
      70             :                           List *operators);
      71             : static void dropProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
      72             :                            List *procedures);
      73             : 
      74             : /*
      75             :  * OpFamilyCacheLookup
      76             :  *      Look up an existing opfamily by name.
      77             :  *
      78             :  * Returns a syscache tuple reference, or NULL if not found.
      79             :  */
      80             : static HeapTuple
      81        1352 : OpFamilyCacheLookup(Oid amID, List *opfamilyname, bool missing_ok)
      82             : {
      83             :     char       *schemaname;
      84             :     char       *opfname;
      85             :     HeapTuple   htup;
      86             : 
      87             :     /* deconstruct the name list */
      88        1352 :     DeconstructQualifiedName(opfamilyname, &schemaname, &opfname);
      89             : 
      90        1352 :     if (schemaname)
      91             :     {
      92             :         /* Look in specific schema only */
      93             :         Oid         namespaceId;
      94             : 
      95         148 :         namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
      96         142 :         if (!OidIsValid(namespaceId))
      97           6 :             htup = NULL;
      98             :         else
      99         136 :             htup = SearchSysCache3(OPFAMILYAMNAMENSP,
     100             :                                    ObjectIdGetDatum(amID),
     101             :                                    PointerGetDatum(opfname),
     102             :                                    ObjectIdGetDatum(namespaceId));
     103             :     }
     104             :     else
     105             :     {
     106             :         /* Unqualified opfamily name, so search the search path */
     107        1204 :         Oid         opfID = OpfamilynameGetOpfid(amID, opfname);
     108             : 
     109        1204 :         if (!OidIsValid(opfID))
     110          12 :             htup = NULL;
     111             :         else
     112        1192 :             htup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfID));
     113             :     }
     114             : 
     115        1346 :     if (!HeapTupleIsValid(htup) && !missing_ok)
     116             :     {
     117             :         HeapTuple   amtup;
     118             : 
     119           6 :         amtup = SearchSysCache1(AMOID, ObjectIdGetDatum(amID));
     120           6 :         if (!HeapTupleIsValid(amtup))
     121           0 :             elog(ERROR, "cache lookup failed for access method %u", amID);
     122           6 :         ereport(ERROR,
     123             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     124             :                  errmsg("operator family \"%s\" does not exist for access method \"%s\"",
     125             :                         NameListToString(opfamilyname),
     126             :                         NameStr(((Form_pg_am) GETSTRUCT(amtup))->amname))));
     127             :     }
     128             : 
     129        1340 :     return htup;
     130             : }
     131             : 
     132             : /*
     133             :  * get_opfamily_oid
     134             :  *    find an opfamily OID by possibly qualified name
     135             :  *
     136             :  * If not found, returns InvalidOid if missing_ok, else throws error.
     137             :  */
     138             : Oid
     139        1352 : get_opfamily_oid(Oid amID, List *opfamilyname, bool missing_ok)
     140             : {
     141             :     HeapTuple   htup;
     142             :     Form_pg_opfamily opfamform;
     143             :     Oid         opfID;
     144             : 
     145        1352 :     htup = OpFamilyCacheLookup(amID, opfamilyname, missing_ok);
     146        1340 :     if (!HeapTupleIsValid(htup))
     147          12 :         return InvalidOid;
     148        1328 :     opfamform = (Form_pg_opfamily) GETSTRUCT(htup);
     149        1328 :     opfID = opfamform->oid;
     150        1328 :     ReleaseSysCache(htup);
     151             : 
     152        1328 :     return opfID;
     153             : }
     154             : 
     155             : /*
     156             :  * OpClassCacheLookup
     157             :  *      Look up an existing opclass by name.
     158             :  *
     159             :  * Returns a syscache tuple reference, or NULL if not found.
     160             :  */
     161             : static HeapTuple
     162         216 : OpClassCacheLookup(Oid amID, List *opclassname, bool missing_ok)
     163             : {
     164             :     char       *schemaname;
     165             :     char       *opcname;
     166             :     HeapTuple   htup;
     167             : 
     168             :     /* deconstruct the name list */
     169         216 :     DeconstructQualifiedName(opclassname, &schemaname, &opcname);
     170             : 
     171         216 :     if (schemaname)
     172             :     {
     173             :         /* Look in specific schema only */
     174             :         Oid         namespaceId;
     175             : 
     176          26 :         namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
     177          26 :         if (!OidIsValid(namespaceId))
     178           6 :             htup = NULL;
     179             :         else
     180          20 :             htup = SearchSysCache3(CLAAMNAMENSP,
     181             :                                    ObjectIdGetDatum(amID),
     182             :                                    PointerGetDatum(opcname),
     183             :                                    ObjectIdGetDatum(namespaceId));
     184             :     }
     185             :     else
     186             :     {
     187             :         /* Unqualified opclass name, so search the search path */
     188         190 :         Oid         opcID = OpclassnameGetOpcid(amID, opcname);
     189             : 
     190         190 :         if (!OidIsValid(opcID))
     191          12 :             htup = NULL;
     192             :         else
     193         178 :             htup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcID));
     194             :     }
     195             : 
     196         216 :     if (!HeapTupleIsValid(htup) && !missing_ok)
     197             :     {
     198             :         HeapTuple   amtup;
     199             : 
     200           6 :         amtup = SearchSysCache1(AMOID, ObjectIdGetDatum(amID));
     201           6 :         if (!HeapTupleIsValid(amtup))
     202           0 :             elog(ERROR, "cache lookup failed for access method %u", amID);
     203           6 :         ereport(ERROR,
     204             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     205             :                  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
     206             :                         NameListToString(opclassname),
     207             :                         NameStr(((Form_pg_am) GETSTRUCT(amtup))->amname))));
     208             :     }
     209             : 
     210         210 :     return htup;
     211             : }
     212             : 
     213             : /*
     214             :  * get_opclass_oid
     215             :  *    find an opclass OID by possibly qualified name
     216             :  *
     217             :  * If not found, returns InvalidOid if missing_ok, else throws error.
     218             :  */
     219             : Oid
     220         216 : get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
     221             : {
     222             :     HeapTuple   htup;
     223             :     Form_pg_opclass opcform;
     224             :     Oid         opcID;
     225             : 
     226         216 :     htup = OpClassCacheLookup(amID, opclassname, missing_ok);
     227         210 :     if (!HeapTupleIsValid(htup))
     228          12 :         return InvalidOid;
     229         198 :     opcform = (Form_pg_opclass) GETSTRUCT(htup);
     230         198 :     opcID = opcform->oid;
     231         198 :     ReleaseSysCache(htup);
     232             : 
     233         198 :     return opcID;
     234             : }
     235             : 
     236             : /*
     237             :  * CreateOpFamily
     238             :  *      Internal routine to make the catalog entry for a new operator family.
     239             :  *
     240             :  * Caller must have done permissions checks etc. already.
     241             :  */
     242             : static ObjectAddress
     243         648 : CreateOpFamily(CreateOpFamilyStmt *stmt, const char *opfname,
     244             :                Oid namespaceoid, Oid amoid)
     245             : {
     246             :     Oid         opfamilyoid;
     247             :     Relation    rel;
     248             :     HeapTuple   tup;
     249             :     Datum       values[Natts_pg_opfamily];
     250             :     bool        nulls[Natts_pg_opfamily];
     251             :     NameData    opfName;
     252             :     ObjectAddress myself,
     253             :                 referenced;
     254             : 
     255         648 :     rel = table_open(OperatorFamilyRelationId, RowExclusiveLock);
     256             : 
     257             :     /*
     258             :      * Make sure there is no existing opfamily of this name (this is just to
     259             :      * give a more friendly error message than "duplicate key").
     260             :      */
     261         648 :     if (SearchSysCacheExists3(OPFAMILYAMNAMENSP,
     262             :                               ObjectIdGetDatum(amoid),
     263             :                               CStringGetDatum(opfname),
     264             :                               ObjectIdGetDatum(namespaceoid)))
     265           0 :         ereport(ERROR,
     266             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     267             :                  errmsg("operator family \"%s\" for access method \"%s\" already exists",
     268             :                         opfname, stmt->amname)));
     269             : 
     270             :     /*
     271             :      * Okay, let's create the pg_opfamily entry.
     272             :      */
     273         648 :     memset(values, 0, sizeof(values));
     274         648 :     memset(nulls, false, sizeof(nulls));
     275             : 
     276         648 :     opfamilyoid = GetNewOidWithIndex(rel, OpfamilyOidIndexId,
     277             :                                      Anum_pg_opfamily_oid);
     278         648 :     values[Anum_pg_opfamily_oid - 1] = ObjectIdGetDatum(opfamilyoid);
     279         648 :     values[Anum_pg_opfamily_opfmethod - 1] = ObjectIdGetDatum(amoid);
     280         648 :     namestrcpy(&opfName, opfname);
     281         648 :     values[Anum_pg_opfamily_opfname - 1] = NameGetDatum(&opfName);
     282         648 :     values[Anum_pg_opfamily_opfnamespace - 1] = ObjectIdGetDatum(namespaceoid);
     283         648 :     values[Anum_pg_opfamily_opfowner - 1] = ObjectIdGetDatum(GetUserId());
     284             : 
     285         648 :     tup = heap_form_tuple(rel->rd_att, values, nulls);
     286             : 
     287         648 :     CatalogTupleInsert(rel, tup);
     288             : 
     289         648 :     heap_freetuple(tup);
     290             : 
     291             :     /*
     292             :      * Create dependencies for the opfamily proper.
     293             :      */
     294         648 :     myself.classId = OperatorFamilyRelationId;
     295         648 :     myself.objectId = opfamilyoid;
     296         648 :     myself.objectSubId = 0;
     297             : 
     298             :     /* dependency on access method */
     299         648 :     referenced.classId = AccessMethodRelationId;
     300         648 :     referenced.objectId = amoid;
     301         648 :     referenced.objectSubId = 0;
     302         648 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
     303             : 
     304             :     /* dependency on namespace */
     305         648 :     referenced.classId = NamespaceRelationId;
     306         648 :     referenced.objectId = namespaceoid;
     307         648 :     referenced.objectSubId = 0;
     308         648 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     309             : 
     310             :     /* dependency on owner */
     311         648 :     recordDependencyOnOwner(OperatorFamilyRelationId, opfamilyoid, GetUserId());
     312             : 
     313             :     /* dependency on extension */
     314         648 :     recordDependencyOnCurrentExtension(&myself, false);
     315             : 
     316             :     /* Report the new operator family to possibly interested event triggers */
     317         648 :     EventTriggerCollectSimpleCommand(myself, InvalidObjectAddress,
     318             :                                      (Node *) stmt);
     319             : 
     320             :     /* Post creation hook for new operator family */
     321         648 :     InvokeObjectPostCreateHook(OperatorFamilyRelationId, opfamilyoid, 0);
     322             : 
     323         648 :     table_close(rel, RowExclusiveLock);
     324             : 
     325         648 :     return myself;
     326             : }
     327             : 
     328             : /*
     329             :  * DefineOpClass
     330             :  *      Define a new index operator class.
     331             :  */
     332             : ObjectAddress
     333         556 : DefineOpClass(CreateOpClassStmt *stmt)
     334             : {
     335             :     char       *opcname;        /* name of opclass we're creating */
     336             :     Oid         amoid,          /* our AM's oid */
     337             :                 typeoid,        /* indexable datatype oid */
     338             :                 storageoid,     /* storage datatype oid, if any */
     339             :                 namespaceoid,   /* namespace to create opclass in */
     340             :                 opfamilyoid,    /* oid of containing opfamily */
     341             :                 opclassoid;     /* oid of opclass we create */
     342             :     int         maxOpNumber,    /* amstrategies value */
     343             :                 optsProcNumber, /* amoptsprocnum value */
     344             :                 maxProcNumber;  /* amsupport value */
     345             :     bool        amstorage;      /* amstorage flag */
     346             :     List       *operators;      /* OpFamilyMember list for operators */
     347             :     List       *procedures;     /* OpFamilyMember list for support procs */
     348             :     ListCell   *l;
     349             :     Relation    rel;
     350             :     HeapTuple   tup;
     351             :     Form_pg_am  amform;
     352             :     const IndexAmRoutine *amroutine;
     353             :     Datum       values[Natts_pg_opclass];
     354             :     bool        nulls[Natts_pg_opclass];
     355             :     AclResult   aclresult;
     356             :     NameData    opcName;
     357             :     ObjectAddress myself,
     358             :                 referenced;
     359             : 
     360             :     /* Convert list of names to a name and namespace */
     361         556 :     namespaceoid = QualifiedNameGetCreationNamespace(stmt->opclassname,
     362             :                                                      &opcname);
     363             : 
     364             :     /* Check we have creation rights in target namespace */
     365         556 :     aclresult = object_aclcheck(NamespaceRelationId, namespaceoid, GetUserId(), ACL_CREATE);
     366         556 :     if (aclresult != ACLCHECK_OK)
     367           0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
     368           0 :                        get_namespace_name(namespaceoid));
     369             : 
     370             :     /* Get necessary info about access method */
     371         556 :     tup = SearchSysCache1(AMNAME, CStringGetDatum(stmt->amname));
     372         556 :     if (!HeapTupleIsValid(tup))
     373           0 :         ereport(ERROR,
     374             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     375             :                  errmsg("access method \"%s\" does not exist",
     376             :                         stmt->amname)));
     377             : 
     378         556 :     amform = (Form_pg_am) GETSTRUCT(tup);
     379         556 :     amoid = amform->oid;
     380         556 :     amroutine = GetIndexAmRoutineByAmId(amoid, false);
     381         556 :     ReleaseSysCache(tup);
     382             : 
     383         556 :     maxOpNumber = amroutine->amstrategies;
     384             :     /* if amstrategies is zero, just enforce that op numbers fit in int16 */
     385         556 :     if (maxOpNumber <= 0)
     386         340 :         maxOpNumber = SHRT_MAX;
     387         556 :     maxProcNumber = amroutine->amsupport;
     388         556 :     optsProcNumber = amroutine->amoptsprocnum;
     389         556 :     amstorage = amroutine->amstorage;
     390             : 
     391             :     /* XXX Should we make any privilege check against the AM? */
     392             : 
     393             :     /*
     394             :      * The question of appropriate permissions for CREATE OPERATOR CLASS is
     395             :      * interesting.  Creating an opclass is tantamount to granting public
     396             :      * execute access on the functions involved, since the index machinery
     397             :      * generally does not check access permission before using the functions.
     398             :      * A minimum expectation therefore is that the caller have execute
     399             :      * privilege with grant option.  Since we don't have a way to make the
     400             :      * opclass go away if the grant option is revoked, we choose instead to
     401             :      * require ownership of the functions.  It's also not entirely clear what
     402             :      * permissions should be required on the datatype, but ownership seems
     403             :      * like a safe choice.
     404             :      *
     405             :      * Currently, we require superuser privileges to create an opclass. This
     406             :      * seems necessary because we have no way to validate that the offered set
     407             :      * of operators and functions are consistent with the AM's expectations.
     408             :      * It would be nice to provide such a check someday, if it can be done
     409             :      * without solving the halting problem :-(
     410             :      *
     411             :      * XXX re-enable NOT_USED code sections below if you remove this test.
     412             :      */
     413         556 :     if (!superuser())
     414           0 :         ereport(ERROR,
     415             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     416             :                  errmsg("must be superuser to create an operator class")));
     417             : 
     418             :     /* Look up the datatype */
     419         556 :     typeoid = typenameTypeId(NULL, stmt->datatype);
     420             : 
     421             : #ifdef NOT_USED
     422             :     /* XXX this is unnecessary given the superuser check above */
     423             :     /* Check we have ownership of the datatype */
     424             :     if (!object_ownercheck(TypeRelationId, typeoid, GetUserId()))
     425             :         aclcheck_error_type(ACLCHECK_NOT_OWNER, typeoid);
     426             : #endif
     427             : 
     428             :     /*
     429             :      * Look up the containing operator family, or create one if FAMILY option
     430             :      * was omitted and there's not a match already.
     431             :      */
     432         556 :     if (stmt->opfamilyname)
     433             :     {
     434          44 :         opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
     435             :     }
     436             :     else
     437             :     {
     438             :         /* Lookup existing family of same name and namespace */
     439         512 :         tup = SearchSysCache3(OPFAMILYAMNAMENSP,
     440             :                               ObjectIdGetDatum(amoid),
     441             :                               PointerGetDatum(opcname),
     442             :                               ObjectIdGetDatum(namespaceoid));
     443         512 :         if (HeapTupleIsValid(tup))
     444             :         {
     445          12 :             opfamilyoid = ((Form_pg_opfamily) GETSTRUCT(tup))->oid;
     446             : 
     447             :             /*
     448             :              * XXX given the superuser check above, there's no need for an
     449             :              * ownership check here
     450             :              */
     451          12 :             ReleaseSysCache(tup);
     452             :         }
     453             :         else
     454             :         {
     455             :             CreateOpFamilyStmt *opfstmt;
     456             :             ObjectAddress tmpAddr;
     457             : 
     458         500 :             opfstmt = makeNode(CreateOpFamilyStmt);
     459         500 :             opfstmt->opfamilyname = stmt->opclassname;
     460         500 :             opfstmt->amname = stmt->amname;
     461             : 
     462             :             /*
     463             :              * Create it ... again no need for more permissions ...
     464             :              */
     465         500 :             tmpAddr = CreateOpFamily(opfstmt, opcname, namespaceoid, amoid);
     466         500 :             opfamilyoid = tmpAddr.objectId;
     467             :         }
     468             :     }
     469             : 
     470         556 :     operators = NIL;
     471         556 :     procedures = NIL;
     472             : 
     473             :     /* Storage datatype is optional */
     474         556 :     storageoid = InvalidOid;
     475             : 
     476             :     /*
     477             :      * Scan the "items" list to obtain additional info.
     478             :      */
     479        5496 :     foreach(l, stmt->items)
     480             :     {
     481        4940 :         CreateOpClassItem *item = lfirst_node(CreateOpClassItem, l);
     482             :         Oid         operOid;
     483             :         Oid         funcOid;
     484             :         Oid         sortfamilyOid;
     485             :         OpFamilyMember *member;
     486             : 
     487        4940 :         switch (item->itemtype)
     488             :         {
     489        2332 :             case OPCLASS_ITEM_OPERATOR:
     490        2332 :                 if (item->number <= 0 || item->number > maxOpNumber)
     491           0 :                     ereport(ERROR,
     492             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     493             :                              errmsg("invalid operator number %d,"
     494             :                                     " must be between 1 and %d",
     495             :                                     item->number, maxOpNumber)));
     496        2332 :                 if (item->name->objargs != NIL)
     497         472 :                     operOid = LookupOperWithArgs(item->name, false);
     498             :                 else
     499             :                 {
     500             :                     /* Default to binary op on input datatype */
     501        1860 :                     operOid = LookupOperName(NULL, item->name->objname,
     502             :                                              typeoid, typeoid,
     503             :                                              false, -1);
     504             :                 }
     505             : 
     506        2332 :                 if (item->order_family)
     507          24 :                     sortfamilyOid = get_opfamily_oid(BTREE_AM_OID,
     508             :                                                      item->order_family,
     509             :                                                      false);
     510             :                 else
     511        2308 :                     sortfamilyOid = InvalidOid;
     512             : 
     513             : #ifdef NOT_USED
     514             :                 /* XXX this is unnecessary given the superuser check above */
     515             :                 /* Caller must own operator and its underlying function */
     516             :                 if (!object_ownercheck(OperatorRelationId, operOid, GetUserId()))
     517             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_OPERATOR,
     518             :                                    get_opname(operOid));
     519             :                 funcOid = get_opcode(operOid);
     520             :                 if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
     521             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     522             :                                    get_func_name(funcOid));
     523             : #endif
     524             : 
     525             :                 /* Save the info */
     526        2332 :                 member = palloc0_object(OpFamilyMember);
     527        2332 :                 member->is_func = false;
     528        2332 :                 member->object = operOid;
     529        2332 :                 member->number = item->number;
     530        2332 :                 member->sortfamily = sortfamilyOid;
     531        2332 :                 assignOperTypes(member, amoid, typeoid);
     532        2332 :                 addFamilyMember(&operators, member);
     533        2332 :                 break;
     534        2254 :             case OPCLASS_ITEM_FUNCTION:
     535        2254 :                 if (item->number <= 0 || item->number > maxProcNumber)
     536           0 :                     ereport(ERROR,
     537             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     538             :                              errmsg("invalid function number %d,"
     539             :                                     " must be between 1 and %d",
     540             :                                     item->number, maxProcNumber)));
     541        2254 :                 funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
     542             : #ifdef NOT_USED
     543             :                 /* XXX this is unnecessary given the superuser check above */
     544             :                 /* Caller must own function */
     545             :                 if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
     546             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     547             :                                    get_func_name(funcOid));
     548             : #endif
     549             :                 /* Save the info */
     550        2254 :                 member = palloc0_object(OpFamilyMember);
     551        2254 :                 member->is_func = true;
     552        2254 :                 member->object = funcOid;
     553        2254 :                 member->number = item->number;
     554             : 
     555             :                 /* allow overriding of the function's actual arg types */
     556        2254 :                 if (item->class_args)
     557           0 :                     processTypesSpec(item->class_args,
     558             :                                      &member->lefttype, &member->righttype);
     559             : 
     560        2254 :                 assignProcTypes(member, amoid, typeoid, optsProcNumber);
     561        2254 :                 addFamilyMember(&procedures, member);
     562        2254 :                 break;
     563         354 :             case OPCLASS_ITEM_STORAGETYPE:
     564         354 :                 if (OidIsValid(storageoid))
     565           0 :                     ereport(ERROR,
     566             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     567             :                              errmsg("storage type specified more than once")));
     568         354 :                 storageoid = typenameTypeId(NULL, item->storedtype);
     569             : 
     570             : #ifdef NOT_USED
     571             :                 /* XXX this is unnecessary given the superuser check above */
     572             :                 /* Check we have ownership of the datatype */
     573             :                 if (!object_ownercheck(TypeRelationId, storageoid, GetUserId()))
     574             :                     aclcheck_error_type(ACLCHECK_NOT_OWNER, storageoid);
     575             : #endif
     576         354 :                 break;
     577           0 :             default:
     578           0 :                 elog(ERROR, "unrecognized item type: %d", item->itemtype);
     579             :                 break;
     580             :         }
     581             :     }
     582             : 
     583             :     /*
     584             :      * If storagetype is specified, make sure it's legal.
     585             :      */
     586         556 :     if (OidIsValid(storageoid))
     587             :     {
     588             :         /* Just drop the spec if same as column datatype */
     589         354 :         if (storageoid == typeoid)
     590         152 :             storageoid = InvalidOid;
     591         202 :         else if (!amstorage)
     592           0 :             ereport(ERROR,
     593             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     594             :                      errmsg("storage type cannot be different from data type for access method \"%s\"",
     595             :                             stmt->amname)));
     596             :     }
     597             : 
     598         556 :     rel = table_open(OperatorClassRelationId, RowExclusiveLock);
     599             : 
     600             :     /*
     601             :      * Make sure there is no existing opclass of this name (this is just to
     602             :      * give a more friendly error message than "duplicate key").
     603             :      */
     604         556 :     if (SearchSysCacheExists3(CLAAMNAMENSP,
     605             :                               ObjectIdGetDatum(amoid),
     606             :                               CStringGetDatum(opcname),
     607             :                               ObjectIdGetDatum(namespaceoid)))
     608           0 :         ereport(ERROR,
     609             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     610             :                  errmsg("operator class \"%s\" for access method \"%s\" already exists",
     611             :                         opcname, stmt->amname)));
     612             : 
     613             :     /*
     614             :      * If we are creating a default opclass, check there isn't one already.
     615             :      * (Note we do not restrict this test to visible opclasses; this ensures
     616             :      * that typcache.c can find unique solutions to its questions.)
     617             :      */
     618         556 :     if (stmt->isDefault)
     619             :     {
     620             :         ScanKeyData skey[1];
     621             :         SysScanDesc scan;
     622             : 
     623         438 :         ScanKeyInit(&skey[0],
     624             :                     Anum_pg_opclass_opcmethod,
     625             :                     BTEqualStrategyNumber, F_OIDEQ,
     626             :                     ObjectIdGetDatum(amoid));
     627             : 
     628         438 :         scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
     629             :                                   NULL, 1, skey);
     630             : 
     631       10644 :         while (HeapTupleIsValid(tup = systable_getnext(scan)))
     632             :         {
     633       10206 :             Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
     634             : 
     635       10206 :             if (opclass->opcintype == typeoid && opclass->opcdefault)
     636           0 :                 ereport(ERROR,
     637             :                         (errcode(ERRCODE_DUPLICATE_OBJECT),
     638             :                          errmsg("could not make operator class \"%s\" be default for type %s",
     639             :                                 opcname,
     640             :                                 TypeNameToString(stmt->datatype)),
     641             :                          errdetail("Operator class \"%s\" already is the default.",
     642             :                                    NameStr(opclass->opcname))));
     643             :         }
     644             : 
     645         438 :         systable_endscan(scan);
     646             :     }
     647             : 
     648             :     /*
     649             :      * Okay, let's create the pg_opclass entry.
     650             :      */
     651         556 :     memset(values, 0, sizeof(values));
     652         556 :     memset(nulls, false, sizeof(nulls));
     653             : 
     654         556 :     opclassoid = GetNewOidWithIndex(rel, OpclassOidIndexId,
     655             :                                     Anum_pg_opclass_oid);
     656         556 :     values[Anum_pg_opclass_oid - 1] = ObjectIdGetDatum(opclassoid);
     657         556 :     values[Anum_pg_opclass_opcmethod - 1] = ObjectIdGetDatum(amoid);
     658         556 :     namestrcpy(&opcName, opcname);
     659         556 :     values[Anum_pg_opclass_opcname - 1] = NameGetDatum(&opcName);
     660         556 :     values[Anum_pg_opclass_opcnamespace - 1] = ObjectIdGetDatum(namespaceoid);
     661         556 :     values[Anum_pg_opclass_opcowner - 1] = ObjectIdGetDatum(GetUserId());
     662         556 :     values[Anum_pg_opclass_opcfamily - 1] = ObjectIdGetDatum(opfamilyoid);
     663         556 :     values[Anum_pg_opclass_opcintype - 1] = ObjectIdGetDatum(typeoid);
     664         556 :     values[Anum_pg_opclass_opcdefault - 1] = BoolGetDatum(stmt->isDefault);
     665         556 :     values[Anum_pg_opclass_opckeytype - 1] = ObjectIdGetDatum(storageoid);
     666             : 
     667         556 :     tup = heap_form_tuple(rel->rd_att, values, nulls);
     668             : 
     669         556 :     CatalogTupleInsert(rel, tup);
     670             : 
     671         556 :     heap_freetuple(tup);
     672             : 
     673             :     /*
     674             :      * Now that we have the opclass OID, set up default dependency info for
     675             :      * the pg_amop and pg_amproc entries.  Historically, CREATE OPERATOR CLASS
     676             :      * has created hard dependencies on the opclass, so that's what we use.
     677             :      */
     678        2888 :     foreach(l, operators)
     679             :     {
     680        2332 :         OpFamilyMember *op = (OpFamilyMember *) lfirst(l);
     681             : 
     682        2332 :         op->ref_is_hard = true;
     683        2332 :         op->ref_is_family = false;
     684        2332 :         op->refobjid = opclassoid;
     685             :     }
     686        2810 :     foreach(l, procedures)
     687             :     {
     688        2254 :         OpFamilyMember *proc = (OpFamilyMember *) lfirst(l);
     689             : 
     690        2254 :         proc->ref_is_hard = true;
     691        2254 :         proc->ref_is_family = false;
     692        2254 :         proc->refobjid = opclassoid;
     693             :     }
     694             : 
     695             :     /*
     696             :      * Let the index AM editorialize on the dependency choices.  It could also
     697             :      * do further validation on the operators and functions, if it likes.
     698             :      */
     699         556 :     if (amroutine->amadjustmembers)
     700         546 :         amroutine->amadjustmembers(opfamilyoid,
     701             :                                    opclassoid,
     702             :                                    operators,
     703             :                                    procedures);
     704             : 
     705             :     /*
     706             :      * Now add tuples to pg_amop and pg_amproc tying in the operators and
     707             :      * functions.  Dependencies on them are inserted, too.
     708             :      */
     709         556 :     storeOperators(stmt->opfamilyname, amoid, opfamilyoid,
     710             :                    operators, false);
     711         556 :     storeProcedures(stmt->opfamilyname, amoid, opfamilyoid,
     712             :                     procedures, false);
     713             : 
     714             :     /* let event triggers know what happened */
     715         556 :     EventTriggerCollectCreateOpClass(stmt, opclassoid, operators, procedures);
     716             : 
     717             :     /*
     718             :      * Create dependencies for the opclass proper.  Note: we do not need a
     719             :      * dependency link to the AM, because that exists through the opfamily.
     720             :      */
     721         556 :     myself.classId = OperatorClassRelationId;
     722         556 :     myself.objectId = opclassoid;
     723         556 :     myself.objectSubId = 0;
     724             : 
     725             :     /* dependency on namespace */
     726         556 :     referenced.classId = NamespaceRelationId;
     727         556 :     referenced.objectId = namespaceoid;
     728         556 :     referenced.objectSubId = 0;
     729         556 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     730             : 
     731             :     /* dependency on opfamily */
     732         556 :     referenced.classId = OperatorFamilyRelationId;
     733         556 :     referenced.objectId = opfamilyoid;
     734         556 :     referenced.objectSubId = 0;
     735         556 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
     736             : 
     737             :     /* dependency on indexed datatype */
     738         556 :     referenced.classId = TypeRelationId;
     739         556 :     referenced.objectId = typeoid;
     740         556 :     referenced.objectSubId = 0;
     741         556 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     742             : 
     743             :     /* dependency on storage datatype */
     744         556 :     if (OidIsValid(storageoid))
     745             :     {
     746         202 :         referenced.classId = TypeRelationId;
     747         202 :         referenced.objectId = storageoid;
     748         202 :         referenced.objectSubId = 0;
     749         202 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     750             :     }
     751             : 
     752             :     /* dependency on owner */
     753         556 :     recordDependencyOnOwner(OperatorClassRelationId, opclassoid, GetUserId());
     754             : 
     755             :     /* dependency on extension */
     756         556 :     recordDependencyOnCurrentExtension(&myself, false);
     757             : 
     758             :     /* Post creation hook for new operator class */
     759         556 :     InvokeObjectPostCreateHook(OperatorClassRelationId, opclassoid, 0);
     760             : 
     761         556 :     table_close(rel, RowExclusiveLock);
     762             : 
     763         556 :     return myself;
     764             : }
     765             : 
     766             : 
     767             : /*
     768             :  * DefineOpFamily
     769             :  *      Define a new index operator family.
     770             :  */
     771             : ObjectAddress
     772         148 : DefineOpFamily(CreateOpFamilyStmt *stmt)
     773             : {
     774             :     char       *opfname;        /* name of opfamily we're creating */
     775             :     Oid         amoid,          /* our AM's oid */
     776             :                 namespaceoid;   /* namespace to create opfamily in */
     777             :     AclResult   aclresult;
     778             : 
     779             :     /* Convert list of names to a name and namespace */
     780         148 :     namespaceoid = QualifiedNameGetCreationNamespace(stmt->opfamilyname,
     781             :                                                      &opfname);
     782             : 
     783             :     /* Check we have creation rights in target namespace */
     784         148 :     aclresult = object_aclcheck(NamespaceRelationId, namespaceoid, GetUserId(), ACL_CREATE);
     785         148 :     if (aclresult != ACLCHECK_OK)
     786           0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
     787           0 :                        get_namespace_name(namespaceoid));
     788             : 
     789             :     /* Get access method OID, throwing an error if it doesn't exist. */
     790         148 :     amoid = get_index_am_oid(stmt->amname, false);
     791             : 
     792             :     /* XXX Should we make any privilege check against the AM? */
     793             : 
     794             :     /*
     795             :      * Currently, we require superuser privileges to create an opfamily. See
     796             :      * comments in DefineOpClass.
     797             :      */
     798         148 :     if (!superuser())
     799           0 :         ereport(ERROR,
     800             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     801             :                  errmsg("must be superuser to create an operator family")));
     802             : 
     803             :     /* Insert pg_opfamily catalog entry */
     804         148 :     return CreateOpFamily(stmt, opfname, namespaceoid, amoid);
     805             : }
     806             : 
     807             : 
     808             : /*
     809             :  * AlterOpFamily
     810             :  *      Add or remove operators/procedures within an existing operator family.
     811             :  *
     812             :  * Note: this implements only ALTER OPERATOR FAMILY ... ADD/DROP.  Some
     813             :  * other commands called ALTER OPERATOR FAMILY exist, but go through
     814             :  * different code paths.
     815             :  */
     816             : Oid
     817         920 : AlterOpFamily(AlterOpFamilyStmt *stmt)
     818             : {
     819             :     Oid         amoid,          /* our AM's oid */
     820             :                 opfamilyoid;    /* oid of opfamily */
     821             :     int         maxOpNumber,    /* amstrategies value */
     822             :                 optsProcNumber, /* amoptsprocnum value */
     823             :                 maxProcNumber;  /* amsupport value */
     824             :     HeapTuple   tup;
     825             :     Form_pg_am  amform;
     826             :     const IndexAmRoutine *amroutine;
     827             : 
     828             :     /* Get necessary info about access method */
     829         920 :     tup = SearchSysCache1(AMNAME, CStringGetDatum(stmt->amname));
     830         920 :     if (!HeapTupleIsValid(tup))
     831           6 :         ereport(ERROR,
     832             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     833             :                  errmsg("access method \"%s\" does not exist",
     834             :                         stmt->amname)));
     835             : 
     836         914 :     amform = (Form_pg_am) GETSTRUCT(tup);
     837         914 :     amoid = amform->oid;
     838         914 :     amroutine = GetIndexAmRoutineByAmId(amoid, false);
     839         914 :     ReleaseSysCache(tup);
     840             : 
     841         914 :     maxOpNumber = amroutine->amstrategies;
     842             :     /* if amstrategies is zero, just enforce that op numbers fit in int16 */
     843         914 :     if (maxOpNumber <= 0)
     844         602 :         maxOpNumber = SHRT_MAX;
     845         914 :     maxProcNumber = amroutine->amsupport;
     846         914 :     optsProcNumber = amroutine->amoptsprocnum;
     847             : 
     848             :     /* XXX Should we make any privilege check against the AM? */
     849             : 
     850             :     /* Look up the opfamily */
     851         914 :     opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
     852             : 
     853             :     /*
     854             :      * Currently, we require superuser privileges to alter an opfamily.
     855             :      *
     856             :      * XXX re-enable NOT_USED code sections below if you remove this test.
     857             :      */
     858         908 :     if (!superuser())
     859           6 :         ereport(ERROR,
     860             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     861             :                  errmsg("must be superuser to alter an operator family")));
     862             : 
     863             :     /*
     864             :      * ADD and DROP cases need separate code from here on down.
     865             :      */
     866         902 :     if (stmt->isDrop)
     867          64 :         AlterOpFamilyDrop(stmt, amoid, opfamilyoid,
     868             :                           maxOpNumber, maxProcNumber, stmt->items);
     869             :     else
     870         838 :         AlterOpFamilyAdd(stmt, amoid, opfamilyoid,
     871             :                          maxOpNumber, maxProcNumber, optsProcNumber,
     872             :                          stmt->items);
     873             : 
     874         758 :     return opfamilyoid;
     875             : }
     876             : 
     877             : /*
     878             :  * ADD part of ALTER OP FAMILY
     879             :  */
     880             : static void
     881         838 : AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
     882             :                  int maxOpNumber, int maxProcNumber, int optsProcNumber,
     883             :                  List *items)
     884             : {
     885         838 :     const IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(amoid, false);
     886             :     List       *operators;      /* OpFamilyMember list for operators */
     887             :     List       *procedures;     /* OpFamilyMember list for support procs */
     888             :     ListCell   *l;
     889             : 
     890         838 :     operators = NIL;
     891         838 :     procedures = NIL;
     892             : 
     893             :     /*
     894             :      * Scan the "items" list to obtain additional info.
     895             :      */
     896        2560 :     foreach(l, items)
     897             :     {
     898        1836 :         CreateOpClassItem *item = lfirst_node(CreateOpClassItem, l);
     899             :         Oid         operOid;
     900             :         Oid         funcOid;
     901             :         Oid         sortfamilyOid;
     902             :         OpFamilyMember *member;
     903             : 
     904        1836 :         switch (item->itemtype)
     905             :         {
     906        1086 :             case OPCLASS_ITEM_OPERATOR:
     907        1086 :                 if (item->number <= 0 || item->number > maxOpNumber)
     908          12 :                     ereport(ERROR,
     909             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     910             :                              errmsg("invalid operator number %d,"
     911             :                                     " must be between 1 and %d",
     912             :                                     item->number, maxOpNumber)));
     913        1074 :                 if (item->name->objargs != NIL)
     914        1068 :                     operOid = LookupOperWithArgs(item->name, false);
     915             :                 else
     916             :                 {
     917           6 :                     ereport(ERROR,
     918             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     919             :                              errmsg("operator argument types must be specified in ALTER OPERATOR FAMILY")));
     920             :                     operOid = InvalidOid;   /* keep compiler quiet */
     921             :                 }
     922             : 
     923        1068 :                 if (item->order_family)
     924          96 :                     sortfamilyOid = get_opfamily_oid(BTREE_AM_OID,
     925             :                                                      item->order_family,
     926             :                                                      false);
     927             :                 else
     928         972 :                     sortfamilyOid = InvalidOid;
     929             : 
     930             : #ifdef NOT_USED
     931             :                 /* XXX this is unnecessary given the superuser check above */
     932             :                 /* Caller must own operator and its underlying function */
     933             :                 if (!object_ownercheck(OperatorRelationId, operOid, GetUserId()))
     934             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_OPERATOR,
     935             :                                    get_opname(operOid));
     936             :                 funcOid = get_opcode(operOid);
     937             :                 if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
     938             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     939             :                                    get_func_name(funcOid));
     940             : #endif
     941             : 
     942             :                 /* Save the info */
     943        1068 :                 member = palloc0_object(OpFamilyMember);
     944        1068 :                 member->is_func = false;
     945        1068 :                 member->object = operOid;
     946        1068 :                 member->number = item->number;
     947        1068 :                 member->sortfamily = sortfamilyOid;
     948             :                 /* We can set up dependency fields immediately */
     949             :                 /* Historically, ALTER ADD has created soft dependencies */
     950        1068 :                 member->ref_is_hard = false;
     951        1068 :                 member->ref_is_family = true;
     952        1068 :                 member->refobjid = opfamilyoid;
     953        1068 :                 assignOperTypes(member, amoid, InvalidOid);
     954        1062 :                 addFamilyMember(&operators, member);
     955        1056 :                 break;
     956         744 :             case OPCLASS_ITEM_FUNCTION:
     957         744 :                 if (item->number <= 0 || item->number > maxProcNumber)
     958          12 :                     ereport(ERROR,
     959             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     960             :                              errmsg("invalid function number %d,"
     961             :                                     " must be between 1 and %d",
     962             :                                     item->number, maxProcNumber)));
     963         732 :                 funcOid = LookupFuncWithArgs(OBJECT_FUNCTION, item->name, false);
     964             : #ifdef NOT_USED
     965             :                 /* XXX this is unnecessary given the superuser check above */
     966             :                 /* Caller must own function */
     967             :                 if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
     968             :                     aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     969             :                                    get_func_name(funcOid));
     970             : #endif
     971             : 
     972             :                 /* Save the info */
     973         726 :                 member = palloc0_object(OpFamilyMember);
     974         726 :                 member->is_func = true;
     975         726 :                 member->object = funcOid;
     976         726 :                 member->number = item->number;
     977             :                 /* We can set up dependency fields immediately */
     978             :                 /* Historically, ALTER ADD has created soft dependencies */
     979         726 :                 member->ref_is_hard = false;
     980         726 :                 member->ref_is_family = true;
     981         726 :                 member->refobjid = opfamilyoid;
     982             : 
     983             :                 /* allow overriding of the function's actual arg types */
     984         726 :                 if (item->class_args)
     985         590 :                     processTypesSpec(item->class_args,
     986             :                                      &member->lefttype, &member->righttype);
     987             : 
     988         726 :                 assignProcTypes(member, amoid, InvalidOid, optsProcNumber);
     989         672 :                 addFamilyMember(&procedures, member);
     990         666 :                 break;
     991           6 :             case OPCLASS_ITEM_STORAGETYPE:
     992           6 :                 ereport(ERROR,
     993             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     994             :                          errmsg("STORAGE cannot be specified in ALTER OPERATOR FAMILY")));
     995             :                 break;
     996           0 :             default:
     997           0 :                 elog(ERROR, "unrecognized item type: %d", item->itemtype);
     998             :                 break;
     999             :         }
    1000             :     }
    1001             : 
    1002             :     /*
    1003             :      * Let the index AM editorialize on the dependency choices.  It could also
    1004             :      * do further validation on the operators and functions, if it likes.
    1005             :      */
    1006         724 :     if (amroutine->amadjustmembers)
    1007         724 :         amroutine->amadjustmembers(opfamilyoid,
    1008             :                                    InvalidOid,  /* no specific opclass */
    1009             :                                    operators,
    1010             :                                    procedures);
    1011             : 
    1012             :     /*
    1013             :      * Add tuples to pg_amop and pg_amproc tying in the operators and
    1014             :      * functions.  Dependencies on them are inserted, too.
    1015             :      */
    1016         724 :     storeOperators(stmt->opfamilyname, amoid, opfamilyoid,
    1017             :                    operators, true);
    1018         712 :     storeProcedures(stmt->opfamilyname, amoid, opfamilyoid,
    1019             :                     procedures, true);
    1020             : 
    1021             :     /* make information available to event triggers */
    1022         712 :     EventTriggerCollectAlterOpFam(stmt, opfamilyoid,
    1023             :                                   operators, procedures);
    1024         712 : }
    1025             : 
    1026             : /*
    1027             :  * DROP part of ALTER OP FAMILY
    1028             :  */
    1029             : static void
    1030          64 : AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid,
    1031             :                   int maxOpNumber, int maxProcNumber, List *items)
    1032             : {
    1033             :     List       *operators;      /* OpFamilyMember list for operators */
    1034             :     List       *procedures;     /* OpFamilyMember list for support procs */
    1035             :     ListCell   *l;
    1036             : 
    1037          64 :     operators = NIL;
    1038          64 :     procedures = NIL;
    1039             : 
    1040             :     /*
    1041             :      * Scan the "items" list to obtain additional info.
    1042             :      */
    1043         152 :     foreach(l, items)
    1044             :     {
    1045          94 :         CreateOpClassItem *item = lfirst_node(CreateOpClassItem, l);
    1046             :         Oid         lefttype,
    1047             :                     righttype;
    1048             :         OpFamilyMember *member;
    1049             : 
    1050          94 :         switch (item->itemtype)
    1051             :         {
    1052          56 :             case OPCLASS_ITEM_OPERATOR:
    1053          56 :                 if (item->number <= 0 || item->number > maxOpNumber)
    1054           0 :                     ereport(ERROR,
    1055             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1056             :                              errmsg("invalid operator number %d,"
    1057             :                                     " must be between 1 and %d",
    1058             :                                     item->number, maxOpNumber)));
    1059          56 :                 processTypesSpec(item->class_args, &lefttype, &righttype);
    1060             :                 /* Save the info */
    1061          50 :                 member = palloc0_object(OpFamilyMember);
    1062          50 :                 member->is_func = false;
    1063          50 :                 member->number = item->number;
    1064          50 :                 member->lefttype = lefttype;
    1065          50 :                 member->righttype = righttype;
    1066          50 :                 addFamilyMember(&operators, member);
    1067          50 :                 break;
    1068          38 :             case OPCLASS_ITEM_FUNCTION:
    1069          38 :                 if (item->number <= 0 || item->number > maxProcNumber)
    1070           0 :                     ereport(ERROR,
    1071             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1072             :                              errmsg("invalid function number %d,"
    1073             :                                     " must be between 1 and %d",
    1074             :                                     item->number, maxProcNumber)));
    1075          38 :                 processTypesSpec(item->class_args, &lefttype, &righttype);
    1076             :                 /* Save the info */
    1077          38 :                 member = palloc0_object(OpFamilyMember);
    1078          38 :                 member->is_func = true;
    1079          38 :                 member->number = item->number;
    1080          38 :                 member->lefttype = lefttype;
    1081          38 :                 member->righttype = righttype;
    1082          38 :                 addFamilyMember(&procedures, member);
    1083          38 :                 break;
    1084           0 :             case OPCLASS_ITEM_STORAGETYPE:
    1085             :                 /* grammar prevents this from appearing */
    1086             :             default:
    1087           0 :                 elog(ERROR, "unrecognized item type: %d", item->itemtype);
    1088             :                 break;
    1089             :         }
    1090             :     }
    1091             : 
    1092             :     /*
    1093             :      * Remove tuples from pg_amop and pg_amproc.
    1094             :      */
    1095          58 :     dropOperators(stmt->opfamilyname, amoid, opfamilyoid, operators);
    1096          52 :     dropProcedures(stmt->opfamilyname, amoid, opfamilyoid, procedures);
    1097             : 
    1098             :     /* make information available to event triggers */
    1099          46 :     EventTriggerCollectAlterOpFam(stmt, opfamilyoid,
    1100             :                                   operators, procedures);
    1101          46 : }
    1102             : 
    1103             : 
    1104             : /*
    1105             :  * Deal with explicit arg types used in ALTER ADD/DROP
    1106             :  */
    1107             : static void
    1108         684 : processTypesSpec(List *args, Oid *lefttype, Oid *righttype)
    1109             : {
    1110             :     TypeName   *typeName;
    1111             : 
    1112             :     Assert(args != NIL);
    1113             : 
    1114         684 :     typeName = (TypeName *) linitial(args);
    1115         684 :     *lefttype = typenameTypeId(NULL, typeName);
    1116             : 
    1117         684 :     if (list_length(args) > 1)
    1118             :     {
    1119         624 :         typeName = (TypeName *) lsecond(args);
    1120         624 :         *righttype = typenameTypeId(NULL, typeName);
    1121             :     }
    1122             :     else
    1123          60 :         *righttype = *lefttype;
    1124             : 
    1125         684 :     if (list_length(args) > 2)
    1126           6 :         ereport(ERROR,
    1127             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1128             :                  errmsg("one or two argument types must be specified")));
    1129         678 : }
    1130             : 
    1131             : 
    1132             : /*
    1133             :  * Determine the lefttype/righttype to assign to an operator,
    1134             :  * and do any validity checking we can manage.
    1135             :  */
    1136             : static void
    1137        3400 : assignOperTypes(OpFamilyMember *member, Oid amoid, Oid typeoid)
    1138             : {
    1139             :     Operator    optup;
    1140             :     Form_pg_operator opform;
    1141             : 
    1142             :     /* Fetch the operator definition */
    1143        3400 :     optup = SearchSysCache1(OPEROID, ObjectIdGetDatum(member->object));
    1144        3400 :     if (!HeapTupleIsValid(optup))
    1145           0 :         elog(ERROR, "cache lookup failed for operator %u", member->object);
    1146        3400 :     opform = (Form_pg_operator) GETSTRUCT(optup);
    1147             : 
    1148             :     /*
    1149             :      * Opfamily operators must be binary.
    1150             :      */
    1151        3400 :     if (opform->oprkind != 'b')
    1152           0 :         ereport(ERROR,
    1153             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1154             :                  errmsg("index operators must be binary")));
    1155             : 
    1156        3400 :     if (OidIsValid(member->sortfamily))
    1157             :     {
    1158             :         /*
    1159             :          * Ordering op, check index supports that.  (We could perhaps also
    1160             :          * check that the operator returns a type supported by the sortfamily,
    1161             :          * but that seems more trouble than it's worth here.  If it does not,
    1162             :          * the operator will never be matchable to any ORDER BY clause, but no
    1163             :          * worse consequences can ensue.  Also, trying to check that would
    1164             :          * create an ordering hazard during dump/reload: it's possible that
    1165             :          * the family has been created but not yet populated with the required
    1166             :          * operators.)
    1167             :          */
    1168         120 :         if (!GetIndexAmRoutineByAmId(amoid, false)->amcanorderbyop)
    1169           6 :             ereport(ERROR,
    1170             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1171             :                      errmsg("access method \"%s\" does not support ordering operators",
    1172             :                             get_am_name(amoid))));
    1173             :     }
    1174             :     else
    1175             :     {
    1176             :         /*
    1177             :          * Search operators must return boolean.
    1178             :          */
    1179        3280 :         if (opform->oprresult != BOOLOID)
    1180           0 :             ereport(ERROR,
    1181             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1182             :                      errmsg("index search operators must return boolean")));
    1183             :     }
    1184             : 
    1185             :     /*
    1186             :      * If lefttype/righttype isn't specified, use the operator's input types
    1187             :      */
    1188        3394 :     if (!OidIsValid(member->lefttype))
    1189        3394 :         member->lefttype = opform->oprleft;
    1190        3394 :     if (!OidIsValid(member->righttype))
    1191        3394 :         member->righttype = opform->oprright;
    1192             : 
    1193        3394 :     ReleaseSysCache(optup);
    1194        3394 : }
    1195             : 
    1196             : /*
    1197             :  * Determine the lefttype/righttype to assign to a support procedure,
    1198             :  * and do any validity checking we can manage.
    1199             :  */
    1200             : static void
    1201        2980 : assignProcTypes(OpFamilyMember *member, Oid amoid, Oid typeoid,
    1202             :                 int opclassOptsProcNum)
    1203             : {
    1204             :     HeapTuple   proctup;
    1205             :     Form_pg_proc procform;
    1206             : 
    1207             :     /* Fetch the procedure definition */
    1208        2980 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(member->object));
    1209        2980 :     if (!HeapTupleIsValid(proctup))
    1210           0 :         elog(ERROR, "cache lookup failed for function %u", member->object);
    1211        2980 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
    1212             : 
    1213             :     /* Check the signature of the opclass options parsing function */
    1214        2980 :     if (member->number == opclassOptsProcNum)
    1215             :     {
    1216          46 :         if (OidIsValid(typeoid))
    1217             :         {
    1218           0 :             if ((OidIsValid(member->lefttype) && member->lefttype != typeoid) ||
    1219           0 :                 (OidIsValid(member->righttype) && member->righttype != typeoid))
    1220           0 :                 ereport(ERROR,
    1221             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1222             :                          errmsg("associated data types for operator class options parsing functions must match opclass input type")));
    1223             :         }
    1224             :         else
    1225             :         {
    1226          46 :             if (member->lefttype != member->righttype)
    1227           6 :                 ereport(ERROR,
    1228             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1229             :                          errmsg("left and right associated data types for operator class options parsing functions must match")));
    1230             :         }
    1231             : 
    1232          40 :         if (procform->prorettype != VOIDOID ||
    1233          34 :             procform->pronargs != 1 ||
    1234          34 :             procform->proargtypes.values[0] != INTERNALOID)
    1235           6 :             ereport(ERROR,
    1236             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1237             :                      errmsg("invalid operator class options parsing function"),
    1238             :                      errhint("Valid signature of operator class options parsing function is %s.",
    1239             :                              "(internal) RETURNS void")));
    1240             :     }
    1241             : 
    1242             :     /*
    1243             :      * Ordering comparison procs must be 2-arg procs returning int4.  Ordering
    1244             :      * sortsupport procs must take internal and return void.  Ordering
    1245             :      * in_range procs must be 5-arg procs returning bool.  Ordering equalimage
    1246             :      * procs must take 1 arg and return bool.  Hashing support proc 1 must be
    1247             :      * a 1-arg proc returning int4, while proc 2 must be a 2-arg proc
    1248             :      * returning int8. Otherwise we don't know.
    1249             :      */
    1250        2934 :     else if (GetIndexAmRoutineByAmId(amoid, false)->amcanorder)
    1251             :     {
    1252         202 :         if (member->number == BTORDER_PROC)
    1253             :         {
    1254         182 :             if (procform->pronargs != 2)
    1255           6 :                 ereport(ERROR,
    1256             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1257             :                          errmsg("ordering comparison functions must have two arguments")));
    1258         176 :             if (procform->prorettype != INT4OID)
    1259           6 :                 ereport(ERROR,
    1260             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1261             :                          errmsg("ordering comparison functions must return integer")));
    1262             : 
    1263             :             /*
    1264             :              * If lefttype/righttype isn't specified, use the proc's input
    1265             :              * types
    1266             :              */
    1267         170 :             if (!OidIsValid(member->lefttype))
    1268         168 :                 member->lefttype = procform->proargtypes.values[0];
    1269         170 :             if (!OidIsValid(member->righttype))
    1270         168 :                 member->righttype = procform->proargtypes.values[1];
    1271             :         }
    1272          20 :         else if (member->number == BTSORTSUPPORT_PROC)
    1273             :         {
    1274           4 :             if (procform->pronargs != 1 ||
    1275           4 :                 procform->proargtypes.values[0] != INTERNALOID)
    1276           0 :                 ereport(ERROR,
    1277             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1278             :                          errmsg("ordering sort support functions must accept type \"internal\"")));
    1279           4 :             if (procform->prorettype != VOIDOID)
    1280           0 :                 ereport(ERROR,
    1281             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1282             :                          errmsg("ordering sort support functions must return void")));
    1283             : 
    1284             :             /*
    1285             :              * Can't infer lefttype/righttype from proc, so use default rule
    1286             :              */
    1287             :         }
    1288          16 :         else if (member->number == BTINRANGE_PROC)
    1289             :         {
    1290           0 :             if (procform->pronargs != 5)
    1291           0 :                 ereport(ERROR,
    1292             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1293             :                          errmsg("ordering in_range functions must have five arguments")));
    1294           0 :             if (procform->prorettype != BOOLOID)
    1295           0 :                 ereport(ERROR,
    1296             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1297             :                          errmsg("ordering in_range functions must return boolean")));
    1298             : 
    1299             :             /*
    1300             :              * If lefttype/righttype isn't specified, use the proc's input
    1301             :              * types (we look at the test-value and offset arguments)
    1302             :              */
    1303           0 :             if (!OidIsValid(member->lefttype))
    1304           0 :                 member->lefttype = procform->proargtypes.values[0];
    1305           0 :             if (!OidIsValid(member->righttype))
    1306           0 :                 member->righttype = procform->proargtypes.values[2];
    1307             :         }
    1308          16 :         else if (member->number == BTEQUALIMAGE_PROC)
    1309             :         {
    1310          10 :             if (procform->pronargs != 1)
    1311           0 :                 ereport(ERROR,
    1312             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1313             :                          errmsg("ordering equal image functions must have one argument")));
    1314          10 :             if (procform->prorettype != BOOLOID)
    1315           0 :                 ereport(ERROR,
    1316             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1317             :                          errmsg("ordering equal image functions must return boolean")));
    1318             : 
    1319             :             /*
    1320             :              * pg_amproc functions are indexed by (lefttype, righttype), but
    1321             :              * an equalimage function can only be called at CREATE INDEX time.
    1322             :              * The same opclass opcintype OID is always used for lefttype and
    1323             :              * righttype.  Providing a cross-type routine isn't sensible.
    1324             :              * Reject cross-type ALTER OPERATOR FAMILY ...  ADD FUNCTION 4
    1325             :              * statements here.
    1326             :              */
    1327          10 :             if (member->lefttype != member->righttype)
    1328           6 :                 ereport(ERROR,
    1329             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1330             :                          errmsg("ordering equal image functions must not be cross-type")));
    1331             :         }
    1332           6 :         else if (member->number == BTSKIPSUPPORT_PROC)
    1333             :         {
    1334           6 :             if (procform->pronargs != 1 ||
    1335           6 :                 procform->proargtypes.values[0] != INTERNALOID)
    1336           0 :                 ereport(ERROR,
    1337             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1338             :                          errmsg("btree skip support functions must accept type \"internal\"")));
    1339           6 :             if (procform->prorettype != VOIDOID)
    1340           0 :                 ereport(ERROR,
    1341             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1342             :                          errmsg("btree skip support functions must return void")));
    1343             : 
    1344             :             /*
    1345             :              * pg_amproc functions are indexed by (lefttype, righttype), but a
    1346             :              * skip support function doesn't make sense in cross-type
    1347             :              * scenarios.  The same opclass opcintype OID is always used for
    1348             :              * lefttype and righttype.  Providing a cross-type routine isn't
    1349             :              * sensible.  Reject cross-type ALTER OPERATOR FAMILY ...  ADD
    1350             :              * FUNCTION 6 statements here.
    1351             :              */
    1352           6 :             if (member->lefttype != member->righttype)
    1353           6 :                 ereport(ERROR,
    1354             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1355             :                          errmsg("btree skip support functions must not be cross-type")));
    1356             :         }
    1357             :     }
    1358        2732 :     else if (GetIndexAmRoutineByAmId(amoid, false)->amcanhash)
    1359             :     {
    1360         120 :         if (member->number == HASHSTANDARD_PROC)
    1361             :         {
    1362          62 :             if (procform->pronargs != 1)
    1363           6 :                 ereport(ERROR,
    1364             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1365             :                          errmsg("hash function 1 must have one argument")));
    1366          56 :             if (procform->prorettype != INT4OID)
    1367           6 :                 ereport(ERROR,
    1368             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1369             :                          errmsg("hash function 1 must return integer")));
    1370             :         }
    1371          58 :         else if (member->number == HASHEXTENDED_PROC)
    1372             :         {
    1373          58 :             if (procform->pronargs != 2)
    1374           0 :                 ereport(ERROR,
    1375             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1376             :                          errmsg("hash function 2 must have two arguments")));
    1377          58 :             if (procform->prorettype != INT8OID)
    1378           0 :                 ereport(ERROR,
    1379             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1380             :                          errmsg("hash function 2 must return bigint")));
    1381             :         }
    1382             : 
    1383             :         /*
    1384             :          * If lefttype/righttype isn't specified, use the proc's input type
    1385             :          */
    1386         108 :         if (!OidIsValid(member->lefttype))
    1387         102 :             member->lefttype = procform->proargtypes.values[0];
    1388         108 :         if (!OidIsValid(member->righttype))
    1389         102 :             member->righttype = procform->proargtypes.values[0];
    1390             :     }
    1391             : 
    1392             :     /*
    1393             :      * The default in CREATE OPERATOR CLASS is to use the class' opcintype as
    1394             :      * lefttype and righttype.  In CREATE or ALTER OPERATOR FAMILY, opcintype
    1395             :      * isn't available, so make the user specify the types.
    1396             :      */
    1397        2932 :     if (!OidIsValid(member->lefttype))
    1398        2096 :         member->lefttype = typeoid;
    1399        2932 :     if (!OidIsValid(member->righttype))
    1400        2096 :         member->righttype = typeoid;
    1401             : 
    1402        2932 :     if (!OidIsValid(member->lefttype) || !OidIsValid(member->righttype))
    1403           6 :         ereport(ERROR,
    1404             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1405             :                  errmsg("associated data types must be specified for index support function")));
    1406             : 
    1407        2926 :     ReleaseSysCache(proctup);
    1408        2926 : }
    1409             : 
    1410             : /*
    1411             :  * Add a new family member to the appropriate list, after checking for
    1412             :  * duplicated strategy or proc number.
    1413             :  */
    1414             : static void
    1415        6408 : addFamilyMember(List **list, OpFamilyMember *member)
    1416             : {
    1417             :     ListCell   *l;
    1418             : 
    1419       20864 :     foreach(l, *list)
    1420             :     {
    1421       14468 :         OpFamilyMember *old = (OpFamilyMember *) lfirst(l);
    1422             : 
    1423       14468 :         if (old->number == member->number &&
    1424         390 :             old->lefttype == member->lefttype &&
    1425         390 :             old->righttype == member->righttype)
    1426             :         {
    1427          12 :             if (member->is_func)
    1428           6 :                 ereport(ERROR,
    1429             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1430             :                          errmsg("function number %d for (%s,%s) appears more than once",
    1431             :                                 member->number,
    1432             :                                 format_type_be(member->lefttype),
    1433             :                                 format_type_be(member->righttype))));
    1434             :             else
    1435           6 :                 ereport(ERROR,
    1436             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1437             :                          errmsg("operator number %d for (%s,%s) appears more than once",
    1438             :                                 member->number,
    1439             :                                 format_type_be(member->lefttype),
    1440             :                                 format_type_be(member->righttype))));
    1441             :         }
    1442             :     }
    1443        6396 :     *list = lappend(*list, member);
    1444        6396 : }
    1445             : 
    1446             : /*
    1447             :  * Dump the operators to pg_amop
    1448             :  *
    1449             :  * We also make dependency entries in pg_depend for the pg_amop entries.
    1450             :  */
    1451             : static void
    1452        1280 : storeOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
    1453             :                List *operators, bool isAdd)
    1454             : {
    1455             :     Relation    rel;
    1456             :     Datum       values[Natts_pg_amop];
    1457             :     bool        nulls[Natts_pg_amop];
    1458             :     HeapTuple   tup;
    1459             :     Oid         entryoid;
    1460             :     ObjectAddress myself,
    1461             :                 referenced;
    1462             :     ListCell   *l;
    1463             : 
    1464        1280 :     rel = table_open(AccessMethodOperatorRelationId, RowExclusiveLock);
    1465             : 
    1466        4596 :     foreach(l, operators)
    1467             :     {
    1468        3328 :         OpFamilyMember *op = (OpFamilyMember *) lfirst(l);
    1469             :         char        oppurpose;
    1470             : 
    1471             :         /*
    1472             :          * If adding to an existing family, check for conflict with an
    1473             :          * existing pg_amop entry (just to give a nicer error message)
    1474             :          */
    1475        4324 :         if (isAdd &&
    1476         996 :             SearchSysCacheExists4(AMOPSTRATEGY,
    1477             :                                   ObjectIdGetDatum(opfamilyoid),
    1478             :                                   ObjectIdGetDatum(op->lefttype),
    1479             :                                   ObjectIdGetDatum(op->righttype),
    1480             :                                   Int16GetDatum(op->number)))
    1481          12 :             ereport(ERROR,
    1482             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1483             :                      errmsg("operator %d(%s,%s) already exists in operator family \"%s\"",
    1484             :                             op->number,
    1485             :                             format_type_be(op->lefttype),
    1486             :                             format_type_be(op->righttype),
    1487             :                             NameListToString(opfamilyname))));
    1488             : 
    1489        3316 :         oppurpose = OidIsValid(op->sortfamily) ? AMOP_ORDER : AMOP_SEARCH;
    1490             : 
    1491             :         /* Create the pg_amop entry */
    1492        3316 :         memset(values, 0, sizeof(values));
    1493        3316 :         memset(nulls, false, sizeof(nulls));
    1494             : 
    1495        3316 :         entryoid = GetNewOidWithIndex(rel, AccessMethodOperatorOidIndexId,
    1496             :                                       Anum_pg_amop_oid);
    1497        3316 :         values[Anum_pg_amop_oid - 1] = ObjectIdGetDatum(entryoid);
    1498        3316 :         values[Anum_pg_amop_amopfamily - 1] = ObjectIdGetDatum(opfamilyoid);
    1499        3316 :         values[Anum_pg_amop_amoplefttype - 1] = ObjectIdGetDatum(op->lefttype);
    1500        3316 :         values[Anum_pg_amop_amoprighttype - 1] = ObjectIdGetDatum(op->righttype);
    1501        3316 :         values[Anum_pg_amop_amopstrategy - 1] = Int16GetDatum(op->number);
    1502        3316 :         values[Anum_pg_amop_amoppurpose - 1] = CharGetDatum(oppurpose);
    1503        3316 :         values[Anum_pg_amop_amopopr - 1] = ObjectIdGetDatum(op->object);
    1504        3316 :         values[Anum_pg_amop_amopmethod - 1] = ObjectIdGetDatum(amoid);
    1505        3316 :         values[Anum_pg_amop_amopsortfamily - 1] = ObjectIdGetDatum(op->sortfamily);
    1506             : 
    1507        3316 :         tup = heap_form_tuple(rel->rd_att, values, nulls);
    1508             : 
    1509        3316 :         CatalogTupleInsert(rel, tup);
    1510             : 
    1511        3316 :         heap_freetuple(tup);
    1512             : 
    1513             :         /* Make its dependencies */
    1514        3316 :         myself.classId = AccessMethodOperatorRelationId;
    1515        3316 :         myself.objectId = entryoid;
    1516        3316 :         myself.objectSubId = 0;
    1517             : 
    1518        3316 :         referenced.classId = OperatorRelationId;
    1519        3316 :         referenced.objectId = op->object;
    1520        3316 :         referenced.objectSubId = 0;
    1521             : 
    1522             :         /* see comments in amapi.h about dependency strength */
    1523        3316 :         recordDependencyOn(&myself, &referenced,
    1524        3316 :                            op->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1525             : 
    1526        3316 :         referenced.classId = op->ref_is_family ? OperatorFamilyRelationId :
    1527             :             OperatorClassRelationId;
    1528        3316 :         referenced.objectId = op->refobjid;
    1529        3316 :         referenced.objectSubId = 0;
    1530             : 
    1531        3316 :         recordDependencyOn(&myself, &referenced,
    1532        3316 :                            op->ref_is_hard ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
    1533             : 
    1534        3316 :         if (typeDepNeeded(op->lefttype, op))
    1535             :         {
    1536           0 :             referenced.classId = TypeRelationId;
    1537           0 :             referenced.objectId = op->lefttype;
    1538           0 :             referenced.objectSubId = 0;
    1539             : 
    1540             :             /* see comments in amapi.h about dependency strength */
    1541           0 :             recordDependencyOn(&myself, &referenced,
    1542           0 :                                op->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1543             :         }
    1544             : 
    1545        4152 :         if (op->lefttype != op->righttype &&
    1546         836 :             typeDepNeeded(op->righttype, op))
    1547             :         {
    1548           0 :             referenced.classId = TypeRelationId;
    1549           0 :             referenced.objectId = op->righttype;
    1550           0 :             referenced.objectSubId = 0;
    1551             : 
    1552             :             /* see comments in amapi.h about dependency strength */
    1553           0 :             recordDependencyOn(&myself, &referenced,
    1554           0 :                                op->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1555             :         }
    1556             : 
    1557             :         /* A search operator also needs a dep on the referenced opfamily */
    1558        3316 :         if (OidIsValid(op->sortfamily))
    1559             :         {
    1560         114 :             referenced.classId = OperatorFamilyRelationId;
    1561         114 :             referenced.objectId = op->sortfamily;
    1562         114 :             referenced.objectSubId = 0;
    1563             : 
    1564         114 :             recordDependencyOn(&myself, &referenced,
    1565         114 :                                op->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1566             :         }
    1567             : 
    1568             :         /* Post create hook of this access method operator */
    1569        3316 :         InvokeObjectPostCreateHook(AccessMethodOperatorRelationId,
    1570             :                                    entryoid, 0);
    1571             :     }
    1572             : 
    1573        1268 :     table_close(rel, RowExclusiveLock);
    1574        1268 : }
    1575             : 
    1576             : /*
    1577             :  * Dump the procedures (support routines) to pg_amproc
    1578             :  *
    1579             :  * We also make dependency entries in pg_depend for the pg_amproc entries.
    1580             :  */
    1581             : static void
    1582        1268 : storeProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
    1583             :                 List *procedures, bool isAdd)
    1584             : {
    1585             :     Relation    rel;
    1586             :     Datum       values[Natts_pg_amproc];
    1587             :     bool        nulls[Natts_pg_amproc];
    1588             :     HeapTuple   tup;
    1589             :     Oid         entryoid;
    1590             :     ObjectAddress myself,
    1591             :                 referenced;
    1592             :     ListCell   *l;
    1593             : 
    1594        1268 :     rel = table_open(AccessMethodProcedureRelationId, RowExclusiveLock);
    1595             : 
    1596        4176 :     foreach(l, procedures)
    1597             :     {
    1598        2908 :         OpFamilyMember *proc = (OpFamilyMember *) lfirst(l);
    1599             : 
    1600             :         /*
    1601             :          * If adding to an existing family, check for conflict with an
    1602             :          * existing pg_amproc entry (just to give a nicer error message)
    1603             :          */
    1604        3562 :         if (isAdd &&
    1605         654 :             SearchSysCacheExists4(AMPROCNUM,
    1606             :                                   ObjectIdGetDatum(opfamilyoid),
    1607             :                                   ObjectIdGetDatum(proc->lefttype),
    1608             :                                   ObjectIdGetDatum(proc->righttype),
    1609             :                                   Int16GetDatum(proc->number)))
    1610           0 :             ereport(ERROR,
    1611             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1612             :                      errmsg("function %d(%s,%s) already exists in operator family \"%s\"",
    1613             :                             proc->number,
    1614             :                             format_type_be(proc->lefttype),
    1615             :                             format_type_be(proc->righttype),
    1616             :                             NameListToString(opfamilyname))));
    1617             : 
    1618             :         /* Create the pg_amproc entry */
    1619        2908 :         memset(values, 0, sizeof(values));
    1620        2908 :         memset(nulls, false, sizeof(nulls));
    1621             : 
    1622        2908 :         entryoid = GetNewOidWithIndex(rel, AccessMethodProcedureOidIndexId,
    1623             :                                       Anum_pg_amproc_oid);
    1624        2908 :         values[Anum_pg_amproc_oid - 1] = ObjectIdGetDatum(entryoid);
    1625        2908 :         values[Anum_pg_amproc_amprocfamily - 1] = ObjectIdGetDatum(opfamilyoid);
    1626        2908 :         values[Anum_pg_amproc_amproclefttype - 1] = ObjectIdGetDatum(proc->lefttype);
    1627        2908 :         values[Anum_pg_amproc_amprocrighttype - 1] = ObjectIdGetDatum(proc->righttype);
    1628        2908 :         values[Anum_pg_amproc_amprocnum - 1] = Int16GetDatum(proc->number);
    1629        2908 :         values[Anum_pg_amproc_amproc - 1] = ObjectIdGetDatum(proc->object);
    1630             : 
    1631        2908 :         tup = heap_form_tuple(rel->rd_att, values, nulls);
    1632             : 
    1633        2908 :         CatalogTupleInsert(rel, tup);
    1634             : 
    1635        2908 :         heap_freetuple(tup);
    1636             : 
    1637             :         /* Make its dependencies */
    1638        2908 :         myself.classId = AccessMethodProcedureRelationId;
    1639        2908 :         myself.objectId = entryoid;
    1640        2908 :         myself.objectSubId = 0;
    1641             : 
    1642        2908 :         referenced.classId = ProcedureRelationId;
    1643        2908 :         referenced.objectId = proc->object;
    1644        2908 :         referenced.objectSubId = 0;
    1645             : 
    1646             :         /* see comments in amapi.h about dependency strength */
    1647        2908 :         recordDependencyOn(&myself, &referenced,
    1648        2908 :                            proc->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1649             : 
    1650        2908 :         referenced.classId = proc->ref_is_family ? OperatorFamilyRelationId :
    1651             :             OperatorClassRelationId;
    1652        2908 :         referenced.objectId = proc->refobjid;
    1653        2908 :         referenced.objectSubId = 0;
    1654             : 
    1655        2908 :         recordDependencyOn(&myself, &referenced,
    1656        2908 :                            proc->ref_is_hard ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
    1657             : 
    1658        2908 :         if (typeDepNeeded(proc->lefttype, proc))
    1659             :         {
    1660         218 :             referenced.classId = TypeRelationId;
    1661         218 :             referenced.objectId = proc->lefttype;
    1662         218 :             referenced.objectSubId = 0;
    1663             : 
    1664             :             /* see comments in amapi.h about dependency strength */
    1665         218 :             recordDependencyOn(&myself, &referenced,
    1666         218 :                                proc->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1667             :         }
    1668             : 
    1669        2972 :         if (proc->lefttype != proc->righttype &&
    1670          64 :             typeDepNeeded(proc->righttype, proc))
    1671             :         {
    1672           0 :             referenced.classId = TypeRelationId;
    1673           0 :             referenced.objectId = proc->righttype;
    1674           0 :             referenced.objectSubId = 0;
    1675             : 
    1676             :             /* see comments in amapi.h about dependency strength */
    1677           0 :             recordDependencyOn(&myself, &referenced,
    1678           0 :                                proc->ref_is_hard ? DEPENDENCY_NORMAL : DEPENDENCY_AUTO);
    1679             :         }
    1680             : 
    1681             :         /* Post create hook of access method procedure */
    1682        2908 :         InvokeObjectPostCreateHook(AccessMethodProcedureRelationId,
    1683             :                                    entryoid, 0);
    1684             :     }
    1685             : 
    1686        1268 :     table_close(rel, RowExclusiveLock);
    1687        1268 : }
    1688             : 
    1689             : /*
    1690             :  * Detect whether a pg_amop or pg_amproc entry needs an explicit dependency
    1691             :  * on its lefttype or righttype.
    1692             :  *
    1693             :  * We make such a dependency unless the entry has an indirect dependency
    1694             :  * via its referenced operator or function.  That's nearly always true
    1695             :  * for operators, but might well not be true for support functions.
    1696             :  */
    1697             : static bool
    1698        7124 : typeDepNeeded(Oid typid, OpFamilyMember *member)
    1699             : {
    1700        7124 :     bool        result = true;
    1701             : 
    1702             :     /*
    1703             :      * If the type is pinned, we don't need a dependency.  This is a bit of a
    1704             :      * layering violation perhaps (recordDependencyOn would ignore the request
    1705             :      * anyway), but it's a cheap test and will frequently save a syscache
    1706             :      * lookup here.
    1707             :      */
    1708        7124 :     if (IsPinnedObject(TypeRelationId, typid))
    1709        5398 :         return false;
    1710             : 
    1711             :     /* Nope, so check the input types of the function or operator. */
    1712        1726 :     if (member->is_func)
    1713             :     {
    1714             :         Oid        *argtypes;
    1715             :         int         nargs;
    1716             : 
    1717         518 :         (void) get_func_signature(member->object, &argtypes, &nargs);
    1718        1034 :         for (int i = 0; i < nargs; i++)
    1719             :         {
    1720         816 :             if (typid == argtypes[i])
    1721             :             {
    1722         300 :                 result = false; /* match, no dependency needed */
    1723         300 :                 break;
    1724             :             }
    1725             :         }
    1726         518 :         pfree(argtypes);
    1727             :     }
    1728             :     else
    1729             :     {
    1730             :         Oid         lefttype,
    1731             :                     righttype;
    1732             : 
    1733        1208 :         op_input_types(member->object, &lefttype, &righttype);
    1734        1208 :         if (typid == lefttype || typid == righttype)
    1735        1208 :             result = false;     /* match, no dependency needed */
    1736             :     }
    1737        1726 :     return result;
    1738             : }
    1739             : 
    1740             : 
    1741             : /*
    1742             :  * Remove operator entries from an opfamily.
    1743             :  *
    1744             :  * Note: this is only allowed for "loose" members of an opfamily, hence
    1745             :  * behavior is always RESTRICT.
    1746             :  */
    1747             : static void
    1748          58 : dropOperators(List *opfamilyname, Oid amoid, Oid opfamilyoid,
    1749             :               List *operators)
    1750             : {
    1751             :     ListCell   *l;
    1752             : 
    1753         102 :     foreach(l, operators)
    1754             :     {
    1755          50 :         OpFamilyMember *op = (OpFamilyMember *) lfirst(l);
    1756             :         Oid         amopid;
    1757             :         ObjectAddress object;
    1758             : 
    1759          50 :         amopid = GetSysCacheOid4(AMOPSTRATEGY, Anum_pg_amop_oid,
    1760             :                                  ObjectIdGetDatum(opfamilyoid),
    1761             :                                  ObjectIdGetDatum(op->lefttype),
    1762             :                                  ObjectIdGetDatum(op->righttype),
    1763             :                                  Int16GetDatum(op->number));
    1764          50 :         if (!OidIsValid(amopid))
    1765           6 :             ereport(ERROR,
    1766             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1767             :                      errmsg("operator %d(%s,%s) does not exist in operator family \"%s\"",
    1768             :                             op->number,
    1769             :                             format_type_be(op->lefttype),
    1770             :                             format_type_be(op->righttype),
    1771             :                             NameListToString(opfamilyname))));
    1772             : 
    1773          44 :         object.classId = AccessMethodOperatorRelationId;
    1774          44 :         object.objectId = amopid;
    1775          44 :         object.objectSubId = 0;
    1776             : 
    1777          44 :         performDeletion(&object, DROP_RESTRICT, 0);
    1778             :     }
    1779          52 : }
    1780             : 
    1781             : /*
    1782             :  * Remove procedure entries from an opfamily.
    1783             :  *
    1784             :  * Note: this is only allowed for "loose" members of an opfamily, hence
    1785             :  * behavior is always RESTRICT.
    1786             :  */
    1787             : static void
    1788          52 : dropProcedures(List *opfamilyname, Oid amoid, Oid opfamilyoid,
    1789             :                List *procedures)
    1790             : {
    1791             :     ListCell   *l;
    1792             : 
    1793          84 :     foreach(l, procedures)
    1794             :     {
    1795          38 :         OpFamilyMember *op = (OpFamilyMember *) lfirst(l);
    1796             :         Oid         amprocid;
    1797             :         ObjectAddress object;
    1798             : 
    1799          38 :         amprocid = GetSysCacheOid4(AMPROCNUM, Anum_pg_amproc_oid,
    1800             :                                    ObjectIdGetDatum(opfamilyoid),
    1801             :                                    ObjectIdGetDatum(op->lefttype),
    1802             :                                    ObjectIdGetDatum(op->righttype),
    1803             :                                    Int16GetDatum(op->number));
    1804          38 :         if (!OidIsValid(amprocid))
    1805           6 :             ereport(ERROR,
    1806             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1807             :                      errmsg("function %d(%s,%s) does not exist in operator family \"%s\"",
    1808             :                             op->number,
    1809             :                             format_type_be(op->lefttype),
    1810             :                             format_type_be(op->righttype),
    1811             :                             NameListToString(opfamilyname))));
    1812             : 
    1813          32 :         object.classId = AccessMethodProcedureRelationId;
    1814          32 :         object.objectId = amprocid;
    1815          32 :         object.objectSubId = 0;
    1816             : 
    1817          32 :         performDeletion(&object, DROP_RESTRICT, 0);
    1818             :     }
    1819          46 : }
    1820             : 
    1821             : /*
    1822             :  * Subroutine for ALTER OPERATOR CLASS SET SCHEMA/RENAME
    1823             :  *
    1824             :  * Is there an operator class with the given name and signature already
    1825             :  * in the given namespace?  If so, raise an appropriate error message.
    1826             :  */
    1827             : void
    1828          36 : IsThereOpClassInNamespace(const char *opcname, Oid opcmethod,
    1829             :                           Oid opcnamespace)
    1830             : {
    1831             :     /* make sure the new name doesn't exist */
    1832          36 :     if (SearchSysCacheExists3(CLAAMNAMENSP,
    1833             :                               ObjectIdGetDatum(opcmethod),
    1834             :                               CStringGetDatum(opcname),
    1835             :                               ObjectIdGetDatum(opcnamespace)))
    1836          12 :         ereport(ERROR,
    1837             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    1838             :                  errmsg("operator class \"%s\" for access method \"%s\" already exists in schema \"%s\"",
    1839             :                         opcname,
    1840             :                         get_am_name(opcmethod),
    1841             :                         get_namespace_name(opcnamespace))));
    1842          24 : }
    1843             : 
    1844             : /*
    1845             :  * Subroutine for ALTER OPERATOR FAMILY SET SCHEMA/RENAME
    1846             :  *
    1847             :  * Is there an operator family with the given name and signature already
    1848             :  * in the given namespace?  If so, raise an appropriate error message.
    1849             :  */
    1850             : void
    1851          36 : IsThereOpFamilyInNamespace(const char *opfname, Oid opfmethod,
    1852             :                            Oid opfnamespace)
    1853             : {
    1854             :     /* make sure the new name doesn't exist */
    1855          36 :     if (SearchSysCacheExists3(OPFAMILYAMNAMENSP,
    1856             :                               ObjectIdGetDatum(opfmethod),
    1857             :                               CStringGetDatum(opfname),
    1858             :                               ObjectIdGetDatum(opfnamespace)))
    1859          12 :         ereport(ERROR,
    1860             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    1861             :                  errmsg("operator family \"%s\" for access method \"%s\" already exists in schema \"%s\"",
    1862             :                         opfname,
    1863             :                         get_am_name(opfmethod),
    1864             :                         get_namespace_name(opfnamespace))));
    1865          24 : }

Generated by: LCOV version 1.16