LCOV - code coverage report
Current view: top level - src/backend/commands - typecmds.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 85.5 % 1370 1171
Test Date: 2026-04-01 03:15:52 Functions: 97.8 % 45 44
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * typecmds.c
       4              :  *    Routines for SQL commands that manipulate types (and domains).
       5              :  *
       6              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7              :  * Portions Copyright (c) 1994, Regents of the University of California
       8              :  *
       9              :  *
      10              :  * IDENTIFICATION
      11              :  *    src/backend/commands/typecmds.c
      12              :  *
      13              :  * DESCRIPTION
      14              :  *    The "DefineFoo" routines take the parse tree and pick out the
      15              :  *    appropriate arguments/flags, passing the results to the
      16              :  *    corresponding "FooCreate" routines (in src/backend/catalog) that do
      17              :  *    the actual catalog-munging.  These routines also verify permission
      18              :  *    of the user to execute the command.
      19              :  *
      20              :  * NOTES
      21              :  *    These things must be defined and committed in the following order:
      22              :  *      "create function":
      23              :  *              input/output, recv/send functions
      24              :  *      "create type":
      25              :  *              type
      26              :  *      "create operator":
      27              :  *              operators
      28              :  *
      29              :  *
      30              :  *-------------------------------------------------------------------------
      31              :  */
      32              : #include "postgres.h"
      33              : 
      34              : #include "access/genam.h"
      35              : #include "access/htup_details.h"
      36              : #include "access/relation.h"
      37              : #include "access/table.h"
      38              : #include "access/tableam.h"
      39              : #include "access/xact.h"
      40              : #include "catalog/binary_upgrade.h"
      41              : #include "catalog/catalog.h"
      42              : #include "catalog/heap.h"
      43              : #include "catalog/objectaccess.h"
      44              : #include "catalog/pg_am.h"
      45              : #include "catalog/pg_authid.h"
      46              : #include "catalog/pg_cast.h"
      47              : #include "catalog/pg_collation.h"
      48              : #include "catalog/pg_constraint.h"
      49              : #include "catalog/pg_depend.h"
      50              : #include "catalog/pg_enum.h"
      51              : #include "catalog/pg_language.h"
      52              : #include "catalog/pg_namespace.h"
      53              : #include "catalog/pg_proc.h"
      54              : #include "catalog/pg_range.h"
      55              : #include "catalog/pg_type.h"
      56              : #include "commands/defrem.h"
      57              : #include "commands/tablecmds.h"
      58              : #include "commands/typecmds.h"
      59              : #include "executor/executor.h"
      60              : #include "miscadmin.h"
      61              : #include "nodes/makefuncs.h"
      62              : #include "optimizer/optimizer.h"
      63              : #include "parser/parse_coerce.h"
      64              : #include "parser/parse_collate.h"
      65              : #include "parser/parse_expr.h"
      66              : #include "parser/parse_func.h"
      67              : #include "parser/parse_type.h"
      68              : #include "utils/builtins.h"
      69              : #include "utils/fmgroids.h"
      70              : #include "utils/inval.h"
      71              : #include "utils/lsyscache.h"
      72              : #include "utils/rel.h"
      73              : #include "utils/ruleutils.h"
      74              : #include "utils/snapmgr.h"
      75              : #include "utils/syscache.h"
      76              : 
      77              : 
      78              : /* result structure for get_rels_with_domain() */
      79              : typedef struct
      80              : {
      81              :     Relation    rel;            /* opened and locked relation */
      82              :     int         natts;          /* number of attributes of interest */
      83              :     int        *atts;           /* attribute numbers */
      84              :     /* atts[] is of allocated length RelationGetNumberOfAttributes(rel) */
      85              : } RelToCheck;
      86              : 
      87              : /* parameter structure for AlterTypeRecurse() */
      88              : typedef struct
      89              : {
      90              :     /* Flags indicating which type attributes to update */
      91              :     bool        updateStorage;
      92              :     bool        updateReceive;
      93              :     bool        updateSend;
      94              :     bool        updateTypmodin;
      95              :     bool        updateTypmodout;
      96              :     bool        updateAnalyze;
      97              :     bool        updateSubscript;
      98              :     /* New values for relevant attributes */
      99              :     char        storage;
     100              :     Oid         receiveOid;
     101              :     Oid         sendOid;
     102              :     Oid         typmodinOid;
     103              :     Oid         typmodoutOid;
     104              :     Oid         analyzeOid;
     105              :     Oid         subscriptOid;
     106              : } AlterTypeRecurseParams;
     107              : 
     108              : /* Potentially set by pg_upgrade_support functions */
     109              : Oid         binary_upgrade_next_array_pg_type_oid = InvalidOid;
     110              : Oid         binary_upgrade_next_mrng_pg_type_oid = InvalidOid;
     111              : Oid         binary_upgrade_next_mrng_array_pg_type_oid = InvalidOid;
     112              : 
     113              : static void makeRangeConstructors(const char *name, Oid namespace,
     114              :                                   Oid rangeOid, Oid subtype,
     115              :                                   Oid *rangeConstruct2_p, Oid *rangeConstruct3_p);
     116              : static void makeMultirangeConstructors(const char *name, Oid namespace,
     117              :                                        Oid multirangeOid, Oid rangeOid,
     118              :                                        Oid rangeArrayOid,
     119              :                                        Oid *mltrngConstruct0_p, Oid *mltrngConstruct1_p, Oid *mltrngConstruct2_p);
     120              : static Oid  findTypeInputFunction(List *procname, Oid typeOid);
     121              : static Oid  findTypeOutputFunction(List *procname, Oid typeOid);
     122              : static Oid  findTypeReceiveFunction(List *procname, Oid typeOid);
     123              : static Oid  findTypeSendFunction(List *procname, Oid typeOid);
     124              : static Oid  findTypeTypmodinFunction(List *procname);
     125              : static Oid  findTypeTypmodoutFunction(List *procname);
     126              : static Oid  findTypeAnalyzeFunction(List *procname, Oid typeOid);
     127              : static Oid  findTypeSubscriptingFunction(List *procname, Oid typeOid);
     128              : static Oid  findRangeSubOpclass(List *opcname, Oid subtype);
     129              : static Oid  findRangeCanonicalFunction(List *procname, Oid typeOid);
     130              : static Oid  findRangeSubtypeDiffFunction(List *procname, Oid subtype);
     131              : static void validateDomainCheckConstraint(Oid domainoid, const char *ccbin, LOCKMODE lockmode);
     132              : static void validateDomainNotNullConstraint(Oid domainoid);
     133              : static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
     134              : static void checkEnumOwner(HeapTuple tup);
     135              : static char *domainAddCheckConstraint(Oid domainOid, Oid domainNamespace,
     136              :                                       Oid baseTypeOid,
     137              :                                       int typMod, Constraint *constr,
     138              :                                       const char *domainName, ObjectAddress *constrAddr);
     139              : static Node *replace_domain_constraint_value(ParseState *pstate,
     140              :                                              ColumnRef *cref);
     141              : static void domainAddNotNullConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
     142              :                                        int typMod, Constraint *constr,
     143              :                                        const char *domainName, ObjectAddress *constrAddr);
     144              : static void AlterTypeRecurse(Oid typeOid, bool isImplicitArray,
     145              :                              HeapTuple tup, Relation catalog,
     146              :                              AlterTypeRecurseParams *atparams);
     147              : 
     148              : 
     149              : /*
     150              :  * DefineType
     151              :  *      Registers a new base type.
     152              :  */
     153              : ObjectAddress
     154          230 : DefineType(ParseState *pstate, List *names, List *parameters)
     155              : {
     156              :     char       *typeName;
     157              :     Oid         typeNamespace;
     158          230 :     int16       internalLength = -1;    /* default: variable-length */
     159          230 :     List       *inputName = NIL;
     160          230 :     List       *outputName = NIL;
     161          230 :     List       *receiveName = NIL;
     162          230 :     List       *sendName = NIL;
     163          230 :     List       *typmodinName = NIL;
     164          230 :     List       *typmodoutName = NIL;
     165          230 :     List       *analyzeName = NIL;
     166          230 :     List       *subscriptName = NIL;
     167          230 :     char        category = TYPCATEGORY_USER;
     168          230 :     bool        preferred = false;
     169          230 :     char        delimiter = DEFAULT_TYPDELIM;
     170          230 :     Oid         elemType = InvalidOid;
     171          230 :     char       *defaultValue = NULL;
     172          230 :     bool        byValue = false;
     173          230 :     char        alignment = TYPALIGN_INT;   /* default alignment */
     174          230 :     char        storage = TYPSTORAGE_PLAIN; /* default TOAST storage method */
     175          230 :     Oid         collation = InvalidOid;
     176          230 :     DefElem    *likeTypeEl = NULL;
     177          230 :     DefElem    *internalLengthEl = NULL;
     178          230 :     DefElem    *inputNameEl = NULL;
     179          230 :     DefElem    *outputNameEl = NULL;
     180          230 :     DefElem    *receiveNameEl = NULL;
     181          230 :     DefElem    *sendNameEl = NULL;
     182          230 :     DefElem    *typmodinNameEl = NULL;
     183          230 :     DefElem    *typmodoutNameEl = NULL;
     184          230 :     DefElem    *analyzeNameEl = NULL;
     185          230 :     DefElem    *subscriptNameEl = NULL;
     186          230 :     DefElem    *categoryEl = NULL;
     187          230 :     DefElem    *preferredEl = NULL;
     188          230 :     DefElem    *delimiterEl = NULL;
     189          230 :     DefElem    *elemTypeEl = NULL;
     190          230 :     DefElem    *defaultValueEl = NULL;
     191          230 :     DefElem    *byValueEl = NULL;
     192          230 :     DefElem    *alignmentEl = NULL;
     193          230 :     DefElem    *storageEl = NULL;
     194          230 :     DefElem    *collatableEl = NULL;
     195              :     Oid         inputOid;
     196              :     Oid         outputOid;
     197          230 :     Oid         receiveOid = InvalidOid;
     198          230 :     Oid         sendOid = InvalidOid;
     199          230 :     Oid         typmodinOid = InvalidOid;
     200          230 :     Oid         typmodoutOid = InvalidOid;
     201          230 :     Oid         analyzeOid = InvalidOid;
     202          230 :     Oid         subscriptOid = InvalidOid;
     203              :     char       *array_type;
     204              :     Oid         array_oid;
     205              :     Oid         typoid;
     206              :     ListCell   *pl;
     207              :     ObjectAddress address;
     208              : 
     209              :     /*
     210              :      * As of Postgres 8.4, we require superuser privilege to create a base
     211              :      * type.  This is simple paranoia: there are too many ways to mess up the
     212              :      * system with an incorrect type definition (for instance, representation
     213              :      * parameters that don't match what the C code expects).  In practice it
     214              :      * takes superuser privilege to create the I/O functions, and so the
     215              :      * former requirement that you own the I/O functions pretty much forced
     216              :      * superuserness anyway.  We're just making doubly sure here.
     217              :      *
     218              :      * XXX re-enable NOT_USED code sections below if you remove this test.
     219              :      */
     220          230 :     if (!superuser())
     221            0 :         ereport(ERROR,
     222              :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     223              :                  errmsg("must be superuser to create a base type")));
     224              : 
     225              :     /* Convert list of names to a name and namespace */
     226          230 :     typeNamespace = QualifiedNameGetCreationNamespace(names, &typeName);
     227              : 
     228              : #ifdef NOT_USED
     229              :     /* XXX this is unnecessary given the superuser check above */
     230              :     /* Check we have creation rights in target namespace */
     231              :     aclresult = object_aclcheck(NamespaceRelationId, typeNamespace, GetUserId(), ACL_CREATE);
     232              :     if (aclresult != ACLCHECK_OK)
     233              :         aclcheck_error(aclresult, OBJECT_SCHEMA,
     234              :                        get_namespace_name(typeNamespace));
     235              : #endif
     236              : 
     237              :     /*
     238              :      * Look to see if type already exists.
     239              :      */
     240          230 :     typoid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
     241              :                              CStringGetDatum(typeName),
     242              :                              ObjectIdGetDatum(typeNamespace));
     243              : 
     244              :     /*
     245              :      * If it's not a shell, see if it's an autogenerated array type, and if so
     246              :      * rename it out of the way.
     247              :      */
     248          230 :     if (OidIsValid(typoid) && get_typisdefined(typoid))
     249              :     {
     250            4 :         if (moveArrayTypeName(typoid, typeName, typeNamespace))
     251            0 :             typoid = InvalidOid;
     252              :         else
     253            4 :             ereport(ERROR,
     254              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     255              :                      errmsg("type \"%s\" already exists", typeName)));
     256              :     }
     257              : 
     258              :     /*
     259              :      * If this command is a parameterless CREATE TYPE, then we're just here to
     260              :      * make a shell type, so do that (or fail if there already is a shell).
     261              :      */
     262          226 :     if (parameters == NIL)
     263              :     {
     264           89 :         if (OidIsValid(typoid))
     265            4 :             ereport(ERROR,
     266              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     267              :                      errmsg("type \"%s\" already exists", typeName)));
     268              : 
     269           85 :         address = TypeShellMake(typeName, typeNamespace, GetUserId());
     270           85 :         return address;
     271              :     }
     272              : 
     273              :     /*
     274              :      * Otherwise, we must already have a shell type, since there is no other
     275              :      * way that the I/O functions could have been created.
     276              :      */
     277          137 :     if (!OidIsValid(typoid))
     278            4 :         ereport(ERROR,
     279              :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     280              :                  errmsg("type \"%s\" does not exist", typeName),
     281              :                  errhint("Create the type as a shell type, then create its I/O functions, then do a full CREATE TYPE.")));
     282              : 
     283              :     /* Extract the parameters from the parameter list */
     284          671 :     foreach(pl, parameters)
     285              :     {
     286          538 :         DefElem    *defel = (DefElem *) lfirst(pl);
     287              :         DefElem   **defelp;
     288              : 
     289          538 :         if (strcmp(defel->defname, "like") == 0)
     290           35 :             defelp = &likeTypeEl;
     291          503 :         else if (strcmp(defel->defname, "internallength") == 0)
     292           84 :             defelp = &internalLengthEl;
     293          419 :         else if (strcmp(defel->defname, "input") == 0)
     294          129 :             defelp = &inputNameEl;
     295          290 :         else if (strcmp(defel->defname, "output") == 0)
     296          129 :             defelp = &outputNameEl;
     297          161 :         else if (strcmp(defel->defname, "receive") == 0)
     298            9 :             defelp = &receiveNameEl;
     299          152 :         else if (strcmp(defel->defname, "send") == 0)
     300            9 :             defelp = &sendNameEl;
     301          143 :         else if (strcmp(defel->defname, "typmod_in") == 0)
     302            5 :             defelp = &typmodinNameEl;
     303          138 :         else if (strcmp(defel->defname, "typmod_out") == 0)
     304            5 :             defelp = &typmodoutNameEl;
     305          133 :         else if (strcmp(defel->defname, "analyze") == 0 ||
     306          133 :                  strcmp(defel->defname, "analyse") == 0)
     307            0 :             defelp = &analyzeNameEl;
     308          133 :         else if (strcmp(defel->defname, "subscript") == 0)
     309            1 :             defelp = &subscriptNameEl;
     310          132 :         else if (strcmp(defel->defname, "category") == 0)
     311            7 :             defelp = &categoryEl;
     312          125 :         else if (strcmp(defel->defname, "preferred") == 0)
     313            7 :             defelp = &preferredEl;
     314          118 :         else if (strcmp(defel->defname, "delimiter") == 0)
     315            0 :             defelp = &delimiterEl;
     316          118 :         else if (strcmp(defel->defname, "element") == 0)
     317            9 :             defelp = &elemTypeEl;
     318          109 :         else if (strcmp(defel->defname, "default") == 0)
     319           11 :             defelp = &defaultValueEl;
     320           98 :         else if (strcmp(defel->defname, "passedbyvalue") == 0)
     321            8 :             defelp = &byValueEl;
     322           90 :         else if (strcmp(defel->defname, "alignment") == 0)
     323           33 :             defelp = &alignmentEl;
     324           57 :         else if (strcmp(defel->defname, "storage") == 0)
     325           31 :             defelp = &storageEl;
     326           26 :         else if (strcmp(defel->defname, "collatable") == 0)
     327            2 :             defelp = &collatableEl;
     328              :         else
     329              :         {
     330              :             /* WARNING, not ERROR, for historical backwards-compatibility */
     331           24 :             ereport(WARNING,
     332              :                     (errcode(ERRCODE_SYNTAX_ERROR),
     333              :                      errmsg("type attribute \"%s\" not recognized",
     334              :                             defel->defname),
     335              :                      parser_errposition(pstate, defel->location)));
     336           24 :             continue;
     337              :         }
     338          514 :         if (*defelp != NULL)
     339            0 :             errorConflictingDefElem(defel, pstate);
     340          514 :         *defelp = defel;
     341              :     }
     342              : 
     343              :     /*
     344              :      * Now interpret the options; we do this separately so that LIKE can be
     345              :      * overridden by other options regardless of the ordering in the parameter
     346              :      * list.
     347              :      */
     348          133 :     if (likeTypeEl)
     349              :     {
     350              :         Type        likeType;
     351              :         Form_pg_type likeForm;
     352              : 
     353           35 :         likeType = typenameType(pstate, defGetTypeName(likeTypeEl), NULL);
     354           31 :         likeForm = (Form_pg_type) GETSTRUCT(likeType);
     355           31 :         internalLength = likeForm->typlen;
     356           31 :         byValue = likeForm->typbyval;
     357           31 :         alignment = likeForm->typalign;
     358           31 :         storage = likeForm->typstorage;
     359           31 :         ReleaseSysCache(likeType);
     360              :     }
     361          129 :     if (internalLengthEl)
     362           84 :         internalLength = defGetTypeLength(internalLengthEl);
     363          129 :     if (inputNameEl)
     364          125 :         inputName = defGetQualifiedName(inputNameEl);
     365          129 :     if (outputNameEl)
     366          125 :         outputName = defGetQualifiedName(outputNameEl);
     367          129 :     if (receiveNameEl)
     368            9 :         receiveName = defGetQualifiedName(receiveNameEl);
     369          129 :     if (sendNameEl)
     370            9 :         sendName = defGetQualifiedName(sendNameEl);
     371          129 :     if (typmodinNameEl)
     372            5 :         typmodinName = defGetQualifiedName(typmodinNameEl);
     373          129 :     if (typmodoutNameEl)
     374            5 :         typmodoutName = defGetQualifiedName(typmodoutNameEl);
     375          129 :     if (analyzeNameEl)
     376            0 :         analyzeName = defGetQualifiedName(analyzeNameEl);
     377          129 :     if (subscriptNameEl)
     378            1 :         subscriptName = defGetQualifiedName(subscriptNameEl);
     379          129 :     if (categoryEl)
     380              :     {
     381            7 :         char       *p = defGetString(categoryEl);
     382              : 
     383            7 :         category = p[0];
     384              :         /* restrict to non-control ASCII */
     385            7 :         if (category < 32 || category > 126)
     386            0 :             ereport(ERROR,
     387              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     388              :                      errmsg("invalid type category \"%s\": must be simple ASCII",
     389              :                             p)));
     390              :     }
     391          129 :     if (preferredEl)
     392            7 :         preferred = defGetBoolean(preferredEl);
     393          129 :     if (delimiterEl)
     394              :     {
     395            0 :         char       *p = defGetString(delimiterEl);
     396              : 
     397            0 :         delimiter = p[0];
     398              :         /* XXX shouldn't we restrict the delimiter? */
     399              :     }
     400          129 :     if (elemTypeEl)
     401              :     {
     402            9 :         elemType = typenameTypeId(NULL, defGetTypeName(elemTypeEl));
     403              :         /* disallow arrays of pseudotypes */
     404            9 :         if (get_typtype(elemType) == TYPTYPE_PSEUDO)
     405            0 :             ereport(ERROR,
     406              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     407              :                      errmsg("array element type cannot be %s",
     408              :                             format_type_be(elemType))));
     409              :     }
     410          129 :     if (defaultValueEl)
     411           11 :         defaultValue = defGetString(defaultValueEl);
     412          129 :     if (byValueEl)
     413            8 :         byValue = defGetBoolean(byValueEl);
     414          129 :     if (alignmentEl)
     415              :     {
     416           33 :         char       *a = defGetString(alignmentEl);
     417              : 
     418              :         /*
     419              :          * Note: if argument was an unquoted identifier, parser will have
     420              :          * applied translations to it, so be prepared to recognize translated
     421              :          * type names as well as the nominal form.
     422              :          */
     423           56 :         if (pg_strcasecmp(a, "double") == 0 ||
     424           46 :             pg_strcasecmp(a, "float8") == 0 ||
     425           23 :             pg_strcasecmp(a, "pg_catalog.float8") == 0)
     426           10 :             alignment = TYPALIGN_DOUBLE;
     427           27 :         else if (pg_strcasecmp(a, "int4") == 0 ||
     428            4 :                  pg_strcasecmp(a, "pg_catalog.int4") == 0)
     429           23 :             alignment = TYPALIGN_INT;
     430            0 :         else if (pg_strcasecmp(a, "int2") == 0 ||
     431            0 :                  pg_strcasecmp(a, "pg_catalog.int2") == 0)
     432            0 :             alignment = TYPALIGN_SHORT;
     433            0 :         else if (pg_strcasecmp(a, "char") == 0 ||
     434            0 :                  pg_strcasecmp(a, "pg_catalog.bpchar") == 0)
     435            0 :             alignment = TYPALIGN_CHAR;
     436              :         else
     437            0 :             ereport(ERROR,
     438              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     439              :                      errmsg("alignment \"%s\" not recognized", a)));
     440              :     }
     441          129 :     if (storageEl)
     442              :     {
     443           31 :         char       *a = defGetString(storageEl);
     444              : 
     445           31 :         if (pg_strcasecmp(a, "plain") == 0)
     446            9 :             storage = TYPSTORAGE_PLAIN;
     447           22 :         else if (pg_strcasecmp(a, "external") == 0)
     448            0 :             storage = TYPSTORAGE_EXTERNAL;
     449           22 :         else if (pg_strcasecmp(a, "extended") == 0)
     450           18 :             storage = TYPSTORAGE_EXTENDED;
     451            4 :         else if (pg_strcasecmp(a, "main") == 0)
     452            4 :             storage = TYPSTORAGE_MAIN;
     453              :         else
     454            0 :             ereport(ERROR,
     455              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     456              :                      errmsg("storage \"%s\" not recognized", a)));
     457              :     }
     458          129 :     if (collatableEl)
     459            2 :         collation = defGetBoolean(collatableEl) ? DEFAULT_COLLATION_OID : InvalidOid;
     460              : 
     461              :     /*
     462              :      * make sure we have our required definitions
     463              :      */
     464          129 :     if (inputName == NIL)
     465            4 :         ereport(ERROR,
     466              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     467              :                  errmsg("type input function must be specified")));
     468          125 :     if (outputName == NIL)
     469            0 :         ereport(ERROR,
     470              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     471              :                  errmsg("type output function must be specified")));
     472              : 
     473          125 :     if (typmodinName == NIL && typmodoutName != NIL)
     474            0 :         ereport(ERROR,
     475              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     476              :                  errmsg("type modifier output function is useless without a type modifier input function")));
     477              : 
     478              :     /*
     479              :      * Convert I/O proc names to OIDs
     480              :      */
     481          125 :     inputOid = findTypeInputFunction(inputName, typoid);
     482          121 :     outputOid = findTypeOutputFunction(outputName, typoid);
     483          121 :     if (receiveName)
     484            9 :         receiveOid = findTypeReceiveFunction(receiveName, typoid);
     485          121 :     if (sendName)
     486            9 :         sendOid = findTypeSendFunction(sendName, typoid);
     487              : 
     488              :     /*
     489              :      * Convert typmodin/out function proc names to OIDs.
     490              :      */
     491          121 :     if (typmodinName)
     492            5 :         typmodinOid = findTypeTypmodinFunction(typmodinName);
     493          121 :     if (typmodoutName)
     494            5 :         typmodoutOid = findTypeTypmodoutFunction(typmodoutName);
     495              : 
     496              :     /*
     497              :      * Convert analysis function proc name to an OID. If no analysis function
     498              :      * is specified, we'll use zero to select the built-in default algorithm.
     499              :      */
     500          121 :     if (analyzeName)
     501            0 :         analyzeOid = findTypeAnalyzeFunction(analyzeName, typoid);
     502              : 
     503              :     /*
     504              :      * Likewise look up the subscripting function if any.  If it is not
     505              :      * specified, but a typelem is specified, allow that if
     506              :      * raw_array_subscript_handler can be used.  (This is for backwards
     507              :      * compatibility; maybe someday we should throw an error instead.)
     508              :      */
     509          121 :     if (subscriptName)
     510            1 :         subscriptOid = findTypeSubscriptingFunction(subscriptName, typoid);
     511          120 :     else if (OidIsValid(elemType))
     512              :     {
     513            4 :         if (internalLength > 0 && !byValue && get_typlen(elemType) > 0)
     514            4 :             subscriptOid = F_RAW_ARRAY_SUBSCRIPT_HANDLER;
     515              :         else
     516            0 :             ereport(ERROR,
     517              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     518              :                      errmsg("element type cannot be specified without a subscripting function")));
     519              :     }
     520              : 
     521              :     /*
     522              :      * Check permissions on functions.  We choose to require the creator/owner
     523              :      * of a type to also own the underlying functions.  Since creating a type
     524              :      * is tantamount to granting public execute access on the functions, the
     525              :      * minimum sane check would be for execute-with-grant-option.  But we
     526              :      * don't have a way to make the type go away if the grant option is
     527              :      * revoked, so ownership seems better.
     528              :      *
     529              :      * XXX For now, this is all unnecessary given the superuser check above.
     530              :      * If we ever relax that, these calls likely should be moved into
     531              :      * findTypeInputFunction et al, where they could be shared by AlterType.
     532              :      */
     533              : #ifdef NOT_USED
     534              :     if (inputOid && !object_ownercheck(ProcedureRelationId, inputOid, GetUserId()))
     535              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     536              :                        NameListToString(inputName));
     537              :     if (outputOid && !object_ownercheck(ProcedureRelationId, outputOid, GetUserId()))
     538              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     539              :                        NameListToString(outputName));
     540              :     if (receiveOid && !object_ownercheck(ProcedureRelationId, receiveOid, GetUserId()))
     541              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     542              :                        NameListToString(receiveName));
     543              :     if (sendOid && !object_ownercheck(ProcedureRelationId, sendOid, GetUserId()))
     544              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     545              :                        NameListToString(sendName));
     546              :     if (typmodinOid && !object_ownercheck(ProcedureRelationId, typmodinOid, GetUserId()))
     547              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     548              :                        NameListToString(typmodinName));
     549              :     if (typmodoutOid && !object_ownercheck(ProcedureRelationId, typmodoutOid, GetUserId()))
     550              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     551              :                        NameListToString(typmodoutName));
     552              :     if (analyzeOid && !object_ownercheck(ProcedureRelationId, analyzeOid, GetUserId()))
     553              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     554              :                        NameListToString(analyzeName));
     555              :     if (subscriptOid && !object_ownercheck(ProcedureRelationId, subscriptOid, GetUserId()))
     556              :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     557              :                        NameListToString(subscriptName));
     558              : #endif
     559              : 
     560              :     /*
     561              :      * OK, we're done checking, time to make the type.  We must assign the
     562              :      * array type OID ahead of calling TypeCreate, since the base type and
     563              :      * array type each refer to the other.
     564              :      */
     565          121 :     array_oid = AssignTypeArrayOid();
     566              : 
     567              :     /*
     568              :      * now have TypeCreate do all the real work.
     569              :      *
     570              :      * Note: the pg_type.oid is stored in user tables as array elements (base
     571              :      * types) in ArrayType and in composite types in DatumTupleFields.  This
     572              :      * oid must be preserved by binary upgrades.
     573              :      */
     574              :     address =
     575          121 :         TypeCreate(InvalidOid,  /* no predetermined type OID */
     576              :                    typeName,    /* type name */
     577              :                    typeNamespace,   /* namespace */
     578              :                    InvalidOid,  /* relation oid (n/a here) */
     579              :                    0,           /* relation kind (ditto) */
     580              :                    GetUserId(), /* owner's ID */
     581              :                    internalLength,  /* internal size */
     582              :                    TYPTYPE_BASE,    /* type-type (base type) */
     583              :                    category,    /* type-category */
     584              :                    preferred,   /* is it a preferred type? */
     585              :                    delimiter,   /* array element delimiter */
     586              :                    inputOid,    /* input procedure */
     587              :                    outputOid,   /* output procedure */
     588              :                    receiveOid,  /* receive procedure */
     589              :                    sendOid,     /* send procedure */
     590              :                    typmodinOid, /* typmodin procedure */
     591              :                    typmodoutOid,    /* typmodout procedure */
     592              :                    analyzeOid,  /* analyze procedure */
     593              :                    subscriptOid,    /* subscript procedure */
     594              :                    elemType,    /* element type ID */
     595              :                    false,       /* this is not an implicit array type */
     596              :                    array_oid,   /* array type we are about to create */
     597              :                    InvalidOid,  /* base type ID (only for domains) */
     598              :                    defaultValue,    /* default type value */
     599              :                    NULL,        /* no binary form available */
     600              :                    byValue,     /* passed by value */
     601              :                    alignment,   /* required alignment */
     602              :                    storage,     /* TOAST strategy */
     603              :                    -1,          /* typMod (Domains only) */
     604              :                    0,           /* Array Dimensions of typbasetype */
     605              :                    false,       /* Type NOT NULL */
     606              :                    collation);  /* type's collation */
     607              :     Assert(typoid == address.objectId);
     608              : 
     609              :     /*
     610              :      * Create the array type that goes with it.
     611              :      */
     612          121 :     array_type = makeArrayTypeName(typeName, typeNamespace);
     613              : 
     614              :     /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for arrays */
     615          121 :     alignment = (alignment == TYPALIGN_DOUBLE) ? TYPALIGN_DOUBLE : TYPALIGN_INT;
     616              : 
     617          121 :     TypeCreate(array_oid,       /* force assignment of this type OID */
     618              :                array_type,      /* type name */
     619              :                typeNamespace,   /* namespace */
     620              :                InvalidOid,      /* relation oid (n/a here) */
     621              :                0,               /* relation kind (ditto) */
     622              :                GetUserId(),     /* owner's ID */
     623              :                -1,              /* internal size (always varlena) */
     624              :                TYPTYPE_BASE,    /* type-type (base type) */
     625              :                TYPCATEGORY_ARRAY,   /* type-category (array) */
     626              :                false,           /* array types are never preferred */
     627              :                delimiter,       /* array element delimiter */
     628              :                F_ARRAY_IN,      /* input procedure */
     629              :                F_ARRAY_OUT,     /* output procedure */
     630              :                F_ARRAY_RECV,    /* receive procedure */
     631              :                F_ARRAY_SEND,    /* send procedure */
     632              :                typmodinOid,     /* typmodin procedure */
     633              :                typmodoutOid,    /* typmodout procedure */
     634              :                F_ARRAY_TYPANALYZE,  /* analyze procedure */
     635              :                F_ARRAY_SUBSCRIPT_HANDLER,   /* array subscript procedure */
     636              :                typoid,          /* element type ID */
     637              :                true,            /* yes this is an array type */
     638              :                InvalidOid,      /* no further array type */
     639              :                InvalidOid,      /* base type ID */
     640              :                NULL,            /* never a default type value */
     641              :                NULL,            /* binary default isn't sent either */
     642              :                false,           /* never passed by value */
     643              :                alignment,       /* see above */
     644              :                TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
     645              :                -1,              /* typMod (Domains only) */
     646              :                0,               /* Array dimensions of typbasetype */
     647              :                false,           /* Type NOT NULL */
     648              :                collation);      /* type's collation */
     649              : 
     650          121 :     pfree(array_type);
     651              : 
     652          121 :     return address;
     653              : }
     654              : 
     655              : /*
     656              :  * Guts of type deletion.
     657              :  */
     658              : void
     659        51899 : RemoveTypeById(Oid typeOid)
     660              : {
     661              :     Relation    relation;
     662              :     HeapTuple   tup;
     663              : 
     664        51899 :     relation = table_open(TypeRelationId, RowExclusiveLock);
     665              : 
     666        51899 :     tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
     667        51899 :     if (!HeapTupleIsValid(tup))
     668            0 :         elog(ERROR, "cache lookup failed for type %u", typeOid);
     669              : 
     670        51899 :     CatalogTupleDelete(relation, &tup->t_self);
     671              : 
     672              :     /*
     673              :      * If it is an enum, delete the pg_enum entries too; we don't bother with
     674              :      * making dependency entries for those, so it has to be done "by hand"
     675              :      * here.
     676              :      */
     677        51899 :     if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_ENUM)
     678          174 :         EnumValuesDelete(typeOid);
     679              : 
     680              :     /*
     681              :      * If it is a range type, delete the pg_range entry too; we don't bother
     682              :      * with making a dependency entry for that, so it has to be done "by hand"
     683              :      * here.
     684              :      */
     685        51899 :     if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_RANGE)
     686           77 :         RangeDelete(typeOid);
     687              : 
     688        51899 :     ReleaseSysCache(tup);
     689              : 
     690        51899 :     table_close(relation, RowExclusiveLock);
     691        51899 : }
     692              : 
     693              : 
     694              : /*
     695              :  * DefineDomain
     696              :  *      Registers a new domain.
     697              :  */
     698              : ObjectAddress
     699          938 : DefineDomain(ParseState *pstate, CreateDomainStmt *stmt)
     700              : {
     701              :     char       *domainName;
     702              :     char       *domainArrayName;
     703              :     Oid         domainNamespace;
     704              :     AclResult   aclresult;
     705              :     int16       internalLength;
     706              :     Oid         inputProcedure;
     707              :     Oid         outputProcedure;
     708              :     Oid         receiveProcedure;
     709              :     Oid         sendProcedure;
     710              :     Oid         analyzeProcedure;
     711              :     bool        byValue;
     712              :     char        category;
     713              :     char        delimiter;
     714              :     char        alignment;
     715              :     char        storage;
     716              :     char        typtype;
     717              :     Datum       datum;
     718              :     bool        isnull;
     719          938 :     char       *defaultValue = NULL;
     720          938 :     char       *defaultValueBin = NULL;
     721          938 :     bool        saw_default = false;
     722          938 :     bool        typNotNull = false;
     723          938 :     bool        nullDefined = false;
     724          938 :     int32       typNDims = list_length(stmt->typeName->arrayBounds);
     725              :     HeapTuple   typeTup;
     726          938 :     List       *schema = stmt->constraints;
     727              :     ListCell   *listptr;
     728              :     Oid         basetypeoid;
     729              :     Oid         old_type_oid;
     730              :     Oid         domaincoll;
     731              :     Oid         domainArrayOid;
     732              :     Form_pg_type baseType;
     733              :     int32       basetypeMod;
     734              :     Oid         baseColl;
     735              :     ObjectAddress address;
     736              : 
     737              :     /* Convert list of names to a name and namespace */
     738          938 :     domainNamespace = QualifiedNameGetCreationNamespace(stmt->domainname,
     739              :                                                         &domainName);
     740              : 
     741              :     /* Check we have creation rights in target namespace */
     742          938 :     aclresult = object_aclcheck(NamespaceRelationId, domainNamespace, GetUserId(),
     743              :                                 ACL_CREATE);
     744          938 :     if (aclresult != ACLCHECK_OK)
     745            0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
     746            0 :                        get_namespace_name(domainNamespace));
     747              : 
     748              :     /*
     749              :      * Check for collision with an existing type name.  If there is one and
     750              :      * it's an autogenerated array, we can rename it out of the way.
     751              :      */
     752          938 :     old_type_oid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
     753              :                                    CStringGetDatum(domainName),
     754              :                                    ObjectIdGetDatum(domainNamespace));
     755          938 :     if (OidIsValid(old_type_oid))
     756              :     {
     757            0 :         if (!moveArrayTypeName(old_type_oid, domainName, domainNamespace))
     758            0 :             ereport(ERROR,
     759              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     760              :                      errmsg("type \"%s\" already exists", domainName)));
     761              :     }
     762              : 
     763              :     /*
     764              :      * Look up the base type.
     765              :      */
     766          938 :     typeTup = typenameType(pstate, stmt->typeName, &basetypeMod);
     767          934 :     baseType = (Form_pg_type) GETSTRUCT(typeTup);
     768          934 :     basetypeoid = baseType->oid;
     769              : 
     770              :     /*
     771              :      * Base type must be a plain base type, a composite type, another domain,
     772              :      * an enum or a range type.  Domains over pseudotypes would create a
     773              :      * security hole.  (It would be shorter to code this to just check for
     774              :      * pseudotypes; but it seems safer to call out the specific typtypes that
     775              :      * are supported, rather than assume that all future typtypes would be
     776              :      * automatically supported.)
     777              :      */
     778          934 :     typtype = baseType->typtype;
     779          934 :     if (typtype != TYPTYPE_BASE &&
     780           54 :         typtype != TYPTYPE_COMPOSITE &&
     781           21 :         typtype != TYPTYPE_DOMAIN &&
     782           12 :         typtype != TYPTYPE_ENUM &&
     783            8 :         typtype != TYPTYPE_RANGE &&
     784              :         typtype != TYPTYPE_MULTIRANGE)
     785            4 :         ereport(ERROR,
     786              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
     787              :                  errmsg("\"%s\" is not a valid base type for a domain",
     788              :                         TypeNameToString(stmt->typeName)),
     789              :                  parser_errposition(pstate, stmt->typeName->location)));
     790              : 
     791          930 :     aclresult = object_aclcheck(TypeRelationId, basetypeoid, GetUserId(), ACL_USAGE);
     792          930 :     if (aclresult != ACLCHECK_OK)
     793            4 :         aclcheck_error_type(aclresult, basetypeoid);
     794              : 
     795              :     /*
     796              :      * Collect the properties of the new domain.  Some are inherited from the
     797              :      * base type, some are not.  If you change any of this inheritance
     798              :      * behavior, be sure to update AlterTypeRecurse() to match!
     799              :      */
     800              : 
     801              :     /*
     802              :      * Identify the collation if any
     803              :      */
     804          926 :     baseColl = baseType->typcollation;
     805          926 :     if (stmt->collClause)
     806          131 :         domaincoll = get_collation_oid(stmt->collClause->collname, false);
     807              :     else
     808          795 :         domaincoll = baseColl;
     809              : 
     810              :     /* Complain if COLLATE is applied to an uncollatable type */
     811          926 :     if (OidIsValid(domaincoll) && !OidIsValid(baseColl))
     812           12 :         ereport(ERROR,
     813              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
     814              :                  errmsg("collations are not supported by type %s",
     815              :                         format_type_be(basetypeoid)),
     816              :                  parser_errposition(pstate, stmt->typeName->location)));
     817              : 
     818              :     /* passed by value */
     819          914 :     byValue = baseType->typbyval;
     820              : 
     821              :     /* Required Alignment */
     822          914 :     alignment = baseType->typalign;
     823              : 
     824              :     /* TOAST Strategy */
     825          914 :     storage = baseType->typstorage;
     826              : 
     827              :     /* Storage Length */
     828          914 :     internalLength = baseType->typlen;
     829              : 
     830              :     /* Type Category */
     831          914 :     category = baseType->typcategory;
     832              : 
     833              :     /* Array element Delimiter */
     834          914 :     delimiter = baseType->typdelim;
     835              : 
     836              :     /* I/O Functions */
     837          914 :     inputProcedure = F_DOMAIN_IN;
     838          914 :     outputProcedure = baseType->typoutput;
     839          914 :     receiveProcedure = F_DOMAIN_RECV;
     840          914 :     sendProcedure = baseType->typsend;
     841              : 
     842              :     /* Domains never accept typmods, so no typmodin/typmodout needed */
     843              : 
     844              :     /* Analysis function */
     845          914 :     analyzeProcedure = baseType->typanalyze;
     846              : 
     847              :     /*
     848              :      * Domains don't need a subscript function, since they are not
     849              :      * subscriptable on their own.  If the base type is subscriptable, the
     850              :      * parser will reduce the type to the base type before subscripting.
     851              :      */
     852              : 
     853              :     /* Inherited default value */
     854          914 :     datum = SysCacheGetAttr(TYPEOID, typeTup,
     855              :                             Anum_pg_type_typdefault, &isnull);
     856          914 :     if (!isnull)
     857            0 :         defaultValue = TextDatumGetCString(datum);
     858              : 
     859              :     /* Inherited default binary value */
     860          914 :     datum = SysCacheGetAttr(TYPEOID, typeTup,
     861              :                             Anum_pg_type_typdefaultbin, &isnull);
     862          914 :     if (!isnull)
     863            0 :         defaultValueBin = TextDatumGetCString(datum);
     864              : 
     865              :     /*
     866              :      * Run through constraints manually to avoid the additional processing
     867              :      * conducted by DefineRelation() and friends.
     868              :      */
     869         1473 :     foreach(listptr, schema)
     870              :     {
     871          611 :         Constraint *constr = lfirst(listptr);
     872              : 
     873          611 :         if (!IsA(constr, Constraint))
     874            0 :             elog(ERROR, "unrecognized node type: %d",
     875              :                  (int) nodeTag(constr));
     876          611 :         switch (constr->contype)
     877              :         {
     878          112 :             case CONSTR_DEFAULT:
     879              : 
     880              :                 /*
     881              :                  * The inherited default value may be overridden by the user
     882              :                  * with the DEFAULT <expr> clause ... but only once.
     883              :                  */
     884          112 :                 if (saw_default)
     885            4 :                     ereport(ERROR,
     886              :                             errcode(ERRCODE_SYNTAX_ERROR),
     887              :                             errmsg("multiple default expressions"),
     888              :                             parser_errposition(pstate, constr->location));
     889          108 :                 saw_default = true;
     890              : 
     891          108 :                 if (constr->raw_expr)
     892              :                 {
     893              :                     Node       *defaultExpr;
     894              : 
     895              :                     /*
     896              :                      * Cook the constr->raw_expr into an expression. Note:
     897              :                      * name is strictly for error message
     898              :                      */
     899          108 :                     defaultExpr = cookDefault(pstate, constr->raw_expr,
     900              :                                               basetypeoid,
     901              :                                               basetypeMod,
     902              :                                               domainName,
     903              :                                               0);
     904              : 
     905              :                     /*
     906              :                      * If the expression is just a NULL constant, we treat it
     907              :                      * like not having a default.
     908              :                      *
     909              :                      * Note that if the basetype is another domain, we'll see
     910              :                      * a CoerceToDomain expr here and not discard the default.
     911              :                      * This is critical because the domain default needs to be
     912              :                      * retained to override any default that the base domain
     913              :                      * might have.
     914              :                      */
     915          104 :                     if (defaultExpr == NULL ||
     916          104 :                         (IsA(defaultExpr, Const) &&
     917           27 :                          ((Const *) defaultExpr)->constisnull))
     918              :                     {
     919            0 :                         defaultValue = NULL;
     920            0 :                         defaultValueBin = NULL;
     921              :                     }
     922              :                     else
     923              :                     {
     924              :                         /*
     925              :                          * Expression must be stored as a nodeToString result,
     926              :                          * but we also require a valid textual representation
     927              :                          * (mainly to make life easier for pg_dump).
     928              :                          */
     929              :                         defaultValue =
     930          104 :                             deparse_expression(defaultExpr,
     931              :                                                NIL, false, false);
     932          104 :                         defaultValueBin = nodeToString(defaultExpr);
     933              :                     }
     934              :                 }
     935              :                 else
     936              :                 {
     937              :                     /* No default (can this still happen?) */
     938            0 :                     defaultValue = NULL;
     939            0 :                     defaultValueBin = NULL;
     940              :                 }
     941          104 :                 break;
     942              : 
     943           80 :             case CONSTR_NOTNULL:
     944           80 :                 if (nullDefined)
     945              :                 {
     946            4 :                     if (!typNotNull)
     947            0 :                         ereport(ERROR,
     948              :                                 errcode(ERRCODE_SYNTAX_ERROR),
     949              :                                 errmsg("conflicting NULL/NOT NULL constraints"),
     950              :                                 parser_errposition(pstate, constr->location));
     951              : 
     952            4 :                     ereport(ERROR,
     953              :                             errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     954              :                             errmsg("redundant NOT NULL constraint definition"),
     955              :                             parser_errposition(pstate, constr->location));
     956              :                 }
     957           76 :                 if (constr->is_no_inherit)
     958            4 :                     ereport(ERROR,
     959              :                             errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     960              :                             errmsg("not-null constraints for domains cannot be marked NO INHERIT"),
     961              :                             parser_errposition(pstate, constr->location));
     962           72 :                 typNotNull = true;
     963           72 :                 nullDefined = true;
     964           72 :                 break;
     965              : 
     966            4 :             case CONSTR_NULL:
     967            4 :                 if (nullDefined && typNotNull)
     968            4 :                     ereport(ERROR,
     969              :                             errcode(ERRCODE_SYNTAX_ERROR),
     970              :                             errmsg("conflicting NULL/NOT NULL constraints"),
     971              :                             parser_errposition(pstate, constr->location));
     972            0 :                 typNotNull = false;
     973            0 :                 nullDefined = true;
     974            0 :                 break;
     975              : 
     976          387 :             case CONSTR_CHECK:
     977              : 
     978              :                 /*
     979              :                  * Check constraints are handled after domain creation, as
     980              :                  * they require the Oid of the domain; at this point we can
     981              :                  * only check that they're not marked NO INHERIT, because that
     982              :                  * would be bogus.
     983              :                  */
     984          387 :                 if (constr->is_no_inherit)
     985            4 :                     ereport(ERROR,
     986              :                             errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     987              :                             errmsg("check constraints for domains cannot be marked NO INHERIT"),
     988              :                             parser_errposition(pstate, constr->location));
     989              : 
     990          383 :                 break;
     991              : 
     992              :                 /*
     993              :                  * All else are error cases
     994              :                  */
     995            4 :             case CONSTR_UNIQUE:
     996            4 :                 ereport(ERROR,
     997              :                         errcode(ERRCODE_SYNTAX_ERROR),
     998              :                         errmsg("unique constraints not possible for domains"),
     999              :                         parser_errposition(pstate, constr->location));
    1000              :                 break;
    1001              : 
    1002            4 :             case CONSTR_PRIMARY:
    1003            4 :                 ereport(ERROR,
    1004              :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1005              :                          errmsg("primary key constraints not possible for domains"),
    1006              :                          parser_errposition(pstate, constr->location)));
    1007              :                 break;
    1008              : 
    1009            0 :             case CONSTR_EXCLUSION:
    1010            0 :                 ereport(ERROR,
    1011              :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1012              :                          errmsg("exclusion constraints not possible for domains"),
    1013              :                          parser_errposition(pstate, constr->location)));
    1014              :                 break;
    1015              : 
    1016            4 :             case CONSTR_FOREIGN:
    1017            4 :                 ereport(ERROR,
    1018              :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1019              :                          errmsg("foreign key constraints not possible for domains"),
    1020              :                          parser_errposition(pstate, constr->location)));
    1021              :                 break;
    1022              : 
    1023            4 :             case CONSTR_ATTR_DEFERRABLE:
    1024              :             case CONSTR_ATTR_NOT_DEFERRABLE:
    1025              :             case CONSTR_ATTR_DEFERRED:
    1026              :             case CONSTR_ATTR_IMMEDIATE:
    1027            4 :                 ereport(ERROR,
    1028              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1029              :                          errmsg("specifying constraint deferrability not supported for domains"),
    1030              :                          parser_errposition(pstate, constr->location)));
    1031              :                 break;
    1032              : 
    1033            4 :             case CONSTR_GENERATED:
    1034              :             case CONSTR_IDENTITY:
    1035            4 :                 ereport(ERROR,
    1036              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1037              :                          errmsg("specifying GENERATED not supported for domains"),
    1038              :                          parser_errposition(pstate, constr->location)));
    1039              :                 break;
    1040              : 
    1041            8 :             case CONSTR_ATTR_ENFORCED:
    1042              :             case CONSTR_ATTR_NOT_ENFORCED:
    1043            8 :                 ereport(ERROR,
    1044              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1045              :                          errmsg("specifying constraint enforceability not supported for domains"),
    1046              :                          parser_errposition(pstate, constr->location)));
    1047              :                 break;
    1048              : 
    1049              :                 /* no default, to let compiler warn about missing case */
    1050              :         }
    1051              :     }
    1052              : 
    1053              :     /* Allocate OID for array type */
    1054          862 :     domainArrayOid = AssignTypeArrayOid();
    1055              : 
    1056              :     /*
    1057              :      * Have TypeCreate do all the real work.
    1058              :      */
    1059              :     address =
    1060          862 :         TypeCreate(InvalidOid,  /* no predetermined type OID */
    1061              :                    domainName,  /* type name */
    1062              :                    domainNamespace, /* namespace */
    1063              :                    InvalidOid,  /* relation oid (n/a here) */
    1064              :                    0,           /* relation kind (ditto) */
    1065              :                    GetUserId(), /* owner's ID */
    1066              :                    internalLength,  /* internal size */
    1067              :                    TYPTYPE_DOMAIN,  /* type-type (domain type) */
    1068              :                    category,    /* type-category */
    1069              :                    false,       /* domain types are never preferred */
    1070              :                    delimiter,   /* array element delimiter */
    1071              :                    inputProcedure,  /* input procedure */
    1072              :                    outputProcedure, /* output procedure */
    1073              :                    receiveProcedure,    /* receive procedure */
    1074              :                    sendProcedure,   /* send procedure */
    1075              :                    InvalidOid,  /* typmodin procedure - none */
    1076              :                    InvalidOid,  /* typmodout procedure - none */
    1077              :                    analyzeProcedure,    /* analyze procedure */
    1078              :                    InvalidOid,  /* subscript procedure - none */
    1079              :                    InvalidOid,  /* no array element type */
    1080              :                    false,       /* this isn't an array */
    1081              :                    domainArrayOid,  /* array type we are about to create */
    1082              :                    basetypeoid, /* base type ID */
    1083              :                    defaultValue,    /* default type value (text) */
    1084              :                    defaultValueBin, /* default type value (binary) */
    1085              :                    byValue,     /* passed by value */
    1086              :                    alignment,   /* required alignment */
    1087              :                    storage,     /* TOAST strategy */
    1088              :                    basetypeMod, /* typeMod value */
    1089              :                    typNDims,    /* Array dimensions for base type */
    1090              :                    typNotNull,  /* Type NOT NULL */
    1091              :                    domaincoll); /* type's collation */
    1092              : 
    1093              :     /*
    1094              :      * Create the array type that goes with it.
    1095              :      */
    1096          862 :     domainArrayName = makeArrayTypeName(domainName, domainNamespace);
    1097              : 
    1098              :     /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for arrays */
    1099          862 :     alignment = (alignment == TYPALIGN_DOUBLE) ? TYPALIGN_DOUBLE : TYPALIGN_INT;
    1100              : 
    1101          862 :     TypeCreate(domainArrayOid,  /* force assignment of this type OID */
    1102              :                domainArrayName, /* type name */
    1103              :                domainNamespace, /* namespace */
    1104              :                InvalidOid,      /* relation oid (n/a here) */
    1105              :                0,               /* relation kind (ditto) */
    1106              :                GetUserId(),     /* owner's ID */
    1107              :                -1,              /* internal size (always varlena) */
    1108              :                TYPTYPE_BASE,    /* type-type (base type) */
    1109              :                TYPCATEGORY_ARRAY,   /* type-category (array) */
    1110              :                false,           /* array types are never preferred */
    1111              :                delimiter,       /* array element delimiter */
    1112              :                F_ARRAY_IN,      /* input procedure */
    1113              :                F_ARRAY_OUT,     /* output procedure */
    1114              :                F_ARRAY_RECV,    /* receive procedure */
    1115              :                F_ARRAY_SEND,    /* send procedure */
    1116              :                InvalidOid,      /* typmodin procedure - none */
    1117              :                InvalidOid,      /* typmodout procedure - none */
    1118              :                F_ARRAY_TYPANALYZE,  /* analyze procedure */
    1119              :                F_ARRAY_SUBSCRIPT_HANDLER,   /* array subscript procedure */
    1120              :                address.objectId,    /* element type ID */
    1121              :                true,            /* yes this is an array type */
    1122              :                InvalidOid,      /* no further array type */
    1123              :                InvalidOid,      /* base type ID */
    1124              :                NULL,            /* never a default type value */
    1125              :                NULL,            /* binary default isn't sent either */
    1126              :                false,           /* never passed by value */
    1127              :                alignment,       /* see above */
    1128              :                TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
    1129              :                -1,              /* typMod (Domains only) */
    1130              :                0,               /* Array dimensions of typbasetype */
    1131              :                false,           /* Type NOT NULL */
    1132              :                domaincoll);     /* type's collation */
    1133              : 
    1134          862 :     pfree(domainArrayName);
    1135              : 
    1136              :     /*
    1137              :      * Process constraints which refer to the domain ID returned by TypeCreate
    1138              :      */
    1139         1393 :     foreach(listptr, schema)
    1140              :     {
    1141          531 :         Constraint *constr = lfirst(listptr);
    1142              : 
    1143              :         /* it must be a Constraint, per check above */
    1144              : 
    1145          531 :         switch (constr->contype)
    1146              :         {
    1147          371 :             case CONSTR_CHECK:
    1148          371 :                 domainAddCheckConstraint(address.objectId, domainNamespace,
    1149              :                                          basetypeoid, basetypeMod,
    1150              :                                          constr, domainName, NULL);
    1151          371 :                 break;
    1152              : 
    1153           60 :             case CONSTR_NOTNULL:
    1154           60 :                 domainAddNotNullConstraint(address.objectId, domainNamespace,
    1155              :                                            basetypeoid, basetypeMod,
    1156              :                                            constr, domainName, NULL);
    1157           60 :                 break;
    1158              : 
    1159              :                 /* Other constraint types were fully processed above */
    1160              : 
    1161          100 :             default:
    1162          100 :                 break;
    1163              :         }
    1164              : 
    1165              :         /* CCI so we can detect duplicate constraint names */
    1166          531 :         CommandCounterIncrement();
    1167              :     }
    1168              : 
    1169              :     /*
    1170              :      * Now we can clean up.
    1171              :      */
    1172          862 :     ReleaseSysCache(typeTup);
    1173              : 
    1174          862 :     return address;
    1175              : }
    1176              : 
    1177              : 
    1178              : /*
    1179              :  * DefineEnum
    1180              :  *      Registers a new enum.
    1181              :  */
    1182              : ObjectAddress
    1183          246 : DefineEnum(CreateEnumStmt *stmt)
    1184              : {
    1185              :     char       *enumName;
    1186              :     char       *enumArrayName;
    1187              :     Oid         enumNamespace;
    1188              :     AclResult   aclresult;
    1189              :     Oid         old_type_oid;
    1190              :     Oid         enumArrayOid;
    1191              :     ObjectAddress enumTypeAddr;
    1192              : 
    1193              :     /* Convert list of names to a name and namespace */
    1194          246 :     enumNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
    1195              :                                                       &enumName);
    1196              : 
    1197              :     /* Check we have creation rights in target namespace */
    1198          246 :     aclresult = object_aclcheck(NamespaceRelationId, enumNamespace, GetUserId(), ACL_CREATE);
    1199          246 :     if (aclresult != ACLCHECK_OK)
    1200            0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
    1201            0 :                        get_namespace_name(enumNamespace));
    1202              : 
    1203              :     /*
    1204              :      * Check for collision with an existing type name.  If there is one and
    1205              :      * it's an autogenerated array, we can rename it out of the way.
    1206              :      */
    1207          246 :     old_type_oid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    1208              :                                    CStringGetDatum(enumName),
    1209              :                                    ObjectIdGetDatum(enumNamespace));
    1210          246 :     if (OidIsValid(old_type_oid))
    1211              :     {
    1212            5 :         if (!moveArrayTypeName(old_type_oid, enumName, enumNamespace))
    1213            0 :             ereport(ERROR,
    1214              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1215              :                      errmsg("type \"%s\" already exists", enumName)));
    1216              :     }
    1217              : 
    1218              :     /* Allocate OID for array type */
    1219          246 :     enumArrayOid = AssignTypeArrayOid();
    1220              : 
    1221              :     /* Create the pg_type entry */
    1222              :     enumTypeAddr =
    1223          246 :         TypeCreate(InvalidOid,  /* no predetermined type OID */
    1224              :                    enumName,    /* type name */
    1225              :                    enumNamespace,   /* namespace */
    1226              :                    InvalidOid,  /* relation oid (n/a here) */
    1227              :                    0,           /* relation kind (ditto) */
    1228              :                    GetUserId(), /* owner's ID */
    1229              :                    sizeof(Oid), /* internal size */
    1230              :                    TYPTYPE_ENUM,    /* type-type (enum type) */
    1231              :                    TYPCATEGORY_ENUM,    /* type-category (enum type) */
    1232              :                    false,       /* enum types are never preferred */
    1233              :                    DEFAULT_TYPDELIM,    /* array element delimiter */
    1234              :                    F_ENUM_IN,   /* input procedure */
    1235              :                    F_ENUM_OUT,  /* output procedure */
    1236              :                    F_ENUM_RECV, /* receive procedure */
    1237              :                    F_ENUM_SEND, /* send procedure */
    1238              :                    InvalidOid,  /* typmodin procedure - none */
    1239              :                    InvalidOid,  /* typmodout procedure - none */
    1240              :                    InvalidOid,  /* analyze procedure - default */
    1241              :                    InvalidOid,  /* subscript procedure - none */
    1242              :                    InvalidOid,  /* element type ID */
    1243              :                    false,       /* this is not an array type */
    1244              :                    enumArrayOid,    /* array type we are about to create */
    1245              :                    InvalidOid,  /* base type ID (only for domains) */
    1246              :                    NULL,        /* never a default type value */
    1247              :                    NULL,        /* binary default isn't sent either */
    1248              :                    true,        /* always passed by value */
    1249              :                    TYPALIGN_INT,    /* int alignment */
    1250              :                    TYPSTORAGE_PLAIN,    /* TOAST strategy always plain */
    1251              :                    -1,          /* typMod (Domains only) */
    1252              :                    0,           /* Array dimensions of typbasetype */
    1253              :                    false,       /* Type NOT NULL */
    1254              :                    InvalidOid); /* type's collation */
    1255              : 
    1256              :     /* Enter the enum's values into pg_enum */
    1257          245 :     EnumValuesCreate(enumTypeAddr.objectId, stmt->vals);
    1258              : 
    1259              :     /*
    1260              :      * Create the array type that goes with it.
    1261              :      */
    1262          241 :     enumArrayName = makeArrayTypeName(enumName, enumNamespace);
    1263              : 
    1264          241 :     TypeCreate(enumArrayOid,    /* force assignment of this type OID */
    1265              :                enumArrayName,   /* type name */
    1266              :                enumNamespace,   /* namespace */
    1267              :                InvalidOid,      /* relation oid (n/a here) */
    1268              :                0,               /* relation kind (ditto) */
    1269              :                GetUserId(),     /* owner's ID */
    1270              :                -1,              /* internal size (always varlena) */
    1271              :                TYPTYPE_BASE,    /* type-type (base type) */
    1272              :                TYPCATEGORY_ARRAY,   /* type-category (array) */
    1273              :                false,           /* array types are never preferred */
    1274              :                DEFAULT_TYPDELIM,    /* array element delimiter */
    1275              :                F_ARRAY_IN,      /* input procedure */
    1276              :                F_ARRAY_OUT,     /* output procedure */
    1277              :                F_ARRAY_RECV,    /* receive procedure */
    1278              :                F_ARRAY_SEND,    /* send procedure */
    1279              :                InvalidOid,      /* typmodin procedure - none */
    1280              :                InvalidOid,      /* typmodout procedure - none */
    1281              :                F_ARRAY_TYPANALYZE,  /* analyze procedure */
    1282              :                F_ARRAY_SUBSCRIPT_HANDLER,   /* array subscript procedure */
    1283              :                enumTypeAddr.objectId,   /* element type ID */
    1284              :                true,            /* yes this is an array type */
    1285              :                InvalidOid,      /* no further array type */
    1286              :                InvalidOid,      /* base type ID */
    1287              :                NULL,            /* never a default type value */
    1288              :                NULL,            /* binary default isn't sent either */
    1289              :                false,           /* never passed by value */
    1290              :                TYPALIGN_INT,    /* enums have int align, so do their arrays */
    1291              :                TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
    1292              :                -1,              /* typMod (Domains only) */
    1293              :                0,               /* Array dimensions of typbasetype */
    1294              :                false,           /* Type NOT NULL */
    1295              :                InvalidOid);     /* type's collation */
    1296              : 
    1297          241 :     pfree(enumArrayName);
    1298              : 
    1299          241 :     return enumTypeAddr;
    1300              : }
    1301              : 
    1302              : /*
    1303              :  * AlterEnum
    1304              :  *      Adds a new label to an existing enum.
    1305              :  */
    1306              : ObjectAddress
    1307          246 : AlterEnum(AlterEnumStmt *stmt)
    1308              : {
    1309              :     Oid         enum_type_oid;
    1310              :     TypeName   *typename;
    1311              :     HeapTuple   tup;
    1312              :     ObjectAddress address;
    1313              : 
    1314              :     /* Make a TypeName so we can use standard type lookup machinery */
    1315          246 :     typename = makeTypeNameFromNameList(stmt->typeName);
    1316          246 :     enum_type_oid = typenameTypeId(NULL, typename);
    1317              : 
    1318          246 :     tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enum_type_oid));
    1319          246 :     if (!HeapTupleIsValid(tup))
    1320            0 :         elog(ERROR, "cache lookup failed for type %u", enum_type_oid);
    1321              : 
    1322              :     /* Check it's an enum and check user has permission to ALTER the enum */
    1323          246 :     checkEnumOwner(tup);
    1324              : 
    1325          246 :     ReleaseSysCache(tup);
    1326              : 
    1327          246 :     if (stmt->oldVal)
    1328              :     {
    1329              :         /* Rename an existing label */
    1330           16 :         RenameEnumLabel(enum_type_oid, stmt->oldVal, stmt->newVal);
    1331              :     }
    1332              :     else
    1333              :     {
    1334              :         /* Add a new label */
    1335          230 :         AddEnumLabel(enum_type_oid, stmt->newVal,
    1336          230 :                      stmt->newValNeighbor, stmt->newValIsAfter,
    1337          230 :                      stmt->skipIfNewValExists);
    1338              :     }
    1339              : 
    1340          226 :     InvokeObjectPostAlterHook(TypeRelationId, enum_type_oid, 0);
    1341              : 
    1342          226 :     ObjectAddressSet(address, TypeRelationId, enum_type_oid);
    1343              : 
    1344          226 :     return address;
    1345              : }
    1346              : 
    1347              : 
    1348              : /*
    1349              :  * checkEnumOwner
    1350              :  *
    1351              :  * Check that the type is actually an enum and that the current user
    1352              :  * has permission to do ALTER TYPE on it.  Throw an error if not.
    1353              :  */
    1354              : static void
    1355          246 : checkEnumOwner(HeapTuple tup)
    1356              : {
    1357          246 :     Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
    1358              : 
    1359              :     /* Check that this is actually an enum */
    1360          246 :     if (typTup->typtype != TYPTYPE_ENUM)
    1361            0 :         ereport(ERROR,
    1362              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1363              :                  errmsg("%s is not an enum",
    1364              :                         format_type_be(typTup->oid))));
    1365              : 
    1366              :     /* Permission check: must own type */
    1367          246 :     if (!object_ownercheck(TypeRelationId, typTup->oid, GetUserId()))
    1368            0 :         aclcheck_error_type(ACLCHECK_NOT_OWNER, typTup->oid);
    1369          246 : }
    1370              : 
    1371              : 
    1372              : /*
    1373              :  * DefineRange
    1374              :  *      Registers a new range type.
    1375              :  *
    1376              :  * Perhaps it might be worthwhile to set pg_type.typelem to the base type,
    1377              :  * and likewise on multiranges to set it to the range type. But having a
    1378              :  * non-zero typelem is treated elsewhere as a synonym for being an array,
    1379              :  * and users might have queries with that same assumption.
    1380              :  */
    1381              : ObjectAddress
    1382          127 : DefineRange(ParseState *pstate, CreateRangeStmt *stmt)
    1383              : {
    1384              :     char       *typeName;
    1385              :     Oid         typeNamespace;
    1386              :     Oid         typoid;
    1387              :     char       *rangeArrayName;
    1388          127 :     char       *multirangeTypeName = NULL;
    1389              :     char       *multirangeArrayName;
    1390          127 :     Oid         multirangeNamespace = InvalidOid;
    1391              :     Oid         rangeArrayOid;
    1392              :     Oid         multirangeOid;
    1393              :     Oid         multirangeArrayOid;
    1394          127 :     Oid         rangeSubtype = InvalidOid;
    1395          127 :     List       *rangeSubOpclassName = NIL;
    1396          127 :     List       *rangeCollationName = NIL;
    1397          127 :     List       *rangeCanonicalName = NIL;
    1398          127 :     List       *rangeSubtypeDiffName = NIL;
    1399              :     Oid         rangeSubOpclass;
    1400              :     Oid         rangeCollation;
    1401              :     regproc     rangeCanonical;
    1402              :     regproc     rangeSubtypeDiff;
    1403              :     int16       subtyplen;
    1404              :     bool        subtypbyval;
    1405              :     char        subtypalign;
    1406              :     char        alignment;
    1407              :     AclResult   aclresult;
    1408              :     ListCell   *lc;
    1409              :     ObjectAddress address;
    1410              :     ObjectAddress mltrngaddress PG_USED_FOR_ASSERTS_ONLY;
    1411          127 :     Oid         rangeConstruct2Oid = InvalidOid;
    1412          127 :     Oid         rangeConstruct3Oid = InvalidOid;
    1413          127 :     Oid         mltrngConstruct0Oid = InvalidOid;
    1414          127 :     Oid         mltrngConstruct1Oid = InvalidOid;
    1415          127 :     Oid         mltrngConstruct2Oid = InvalidOid;
    1416              :     Oid         castFuncOid;
    1417              : 
    1418              :     /* Convert list of names to a name and namespace */
    1419          127 :     typeNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
    1420              :                                                       &typeName);
    1421              : 
    1422              :     /* Check we have creation rights in target namespace */
    1423          127 :     aclresult = object_aclcheck(NamespaceRelationId, typeNamespace, GetUserId(), ACL_CREATE);
    1424          127 :     if (aclresult != ACLCHECK_OK)
    1425            0 :         aclcheck_error(aclresult, OBJECT_SCHEMA,
    1426            0 :                        get_namespace_name(typeNamespace));
    1427              : 
    1428              :     /*
    1429              :      * Look to see if type already exists.
    1430              :      */
    1431          127 :     typoid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    1432              :                              CStringGetDatum(typeName),
    1433              :                              ObjectIdGetDatum(typeNamespace));
    1434              : 
    1435              :     /*
    1436              :      * If it's not a shell, see if it's an autogenerated array type, and if so
    1437              :      * rename it out of the way.
    1438              :      */
    1439          127 :     if (OidIsValid(typoid) && get_typisdefined(typoid))
    1440              :     {
    1441            0 :         if (moveArrayTypeName(typoid, typeName, typeNamespace))
    1442            0 :             typoid = InvalidOid;
    1443              :         else
    1444            0 :             ereport(ERROR,
    1445              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    1446              :                      errmsg("type \"%s\" already exists", typeName)));
    1447              :     }
    1448              : 
    1449              :     /*
    1450              :      * Unlike DefineType(), we don't insist on a shell type existing first, as
    1451              :      * it's only needed if the user wants to specify a canonical function.
    1452              :      */
    1453              : 
    1454              :     /* Extract the parameters from the parameter list */
    1455          336 :     foreach(lc, stmt->params)
    1456              :     {
    1457          209 :         DefElem    *defel = (DefElem *) lfirst(lc);
    1458              : 
    1459          209 :         if (strcmp(defel->defname, "subtype") == 0)
    1460              :         {
    1461          127 :             if (OidIsValid(rangeSubtype))
    1462            0 :                 errorConflictingDefElem(defel, pstate);
    1463              :             /* we can look up the subtype name immediately */
    1464          127 :             rangeSubtype = typenameTypeId(NULL, defGetTypeName(defel));
    1465              :         }
    1466           82 :         else if (strcmp(defel->defname, "subtype_opclass") == 0)
    1467              :         {
    1468            5 :             if (rangeSubOpclassName != NIL)
    1469            0 :                 errorConflictingDefElem(defel, pstate);
    1470            5 :             rangeSubOpclassName = defGetQualifiedName(defel);
    1471              :         }
    1472           77 :         else if (strcmp(defel->defname, "collation") == 0)
    1473              :         {
    1474           46 :             if (rangeCollationName != NIL)
    1475            0 :                 errorConflictingDefElem(defel, pstate);
    1476           46 :             rangeCollationName = defGetQualifiedName(defel);
    1477              :         }
    1478           31 :         else if (strcmp(defel->defname, "canonical") == 0)
    1479              :         {
    1480            0 :             if (rangeCanonicalName != NIL)
    1481            0 :                 errorConflictingDefElem(defel, pstate);
    1482            0 :             rangeCanonicalName = defGetQualifiedName(defel);
    1483              :         }
    1484           31 :         else if (strcmp(defel->defname, "subtype_diff") == 0)
    1485              :         {
    1486            9 :             if (rangeSubtypeDiffName != NIL)
    1487            0 :                 errorConflictingDefElem(defel, pstate);
    1488            9 :             rangeSubtypeDiffName = defGetQualifiedName(defel);
    1489              :         }
    1490           22 :         else if (strcmp(defel->defname, "multirange_type_name") == 0)
    1491              :         {
    1492           22 :             if (multirangeTypeName != NULL)
    1493            0 :                 errorConflictingDefElem(defel, pstate);
    1494              :             /* we can look up the subtype name immediately */
    1495           22 :             multirangeNamespace = QualifiedNameGetCreationNamespace(defGetQualifiedName(defel),
    1496              :                                                                     &multirangeTypeName);
    1497              :         }
    1498              :         else
    1499            0 :             ereport(ERROR,
    1500              :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1501              :                      errmsg("type attribute \"%s\" not recognized",
    1502              :                             defel->defname)));
    1503              :     }
    1504              : 
    1505              :     /* Must have a subtype */
    1506          127 :     if (!OidIsValid(rangeSubtype))
    1507            0 :         ereport(ERROR,
    1508              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1509              :                  errmsg("type attribute \"subtype\" is required")));
    1510              :     /* disallow ranges of pseudotypes */
    1511          127 :     if (get_typtype(rangeSubtype) == TYPTYPE_PSEUDO)
    1512            0 :         ereport(ERROR,
    1513              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1514              :                  errmsg("range subtype cannot be %s",
    1515              :                         format_type_be(rangeSubtype))));
    1516              : 
    1517              :     /* Identify subopclass */
    1518          127 :     rangeSubOpclass = findRangeSubOpclass(rangeSubOpclassName, rangeSubtype);
    1519              : 
    1520              :     /* Identify collation to use, if any */
    1521          127 :     if (type_is_collatable(rangeSubtype))
    1522              :     {
    1523           51 :         if (rangeCollationName != NIL)
    1524           46 :             rangeCollation = get_collation_oid(rangeCollationName, false);
    1525              :         else
    1526            5 :             rangeCollation = get_typcollation(rangeSubtype);
    1527              :     }
    1528              :     else
    1529              :     {
    1530           76 :         if (rangeCollationName != NIL)
    1531            0 :             ereport(ERROR,
    1532              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1533              :                      errmsg("range collation specified but subtype does not support collation")));
    1534           76 :         rangeCollation = InvalidOid;
    1535              :     }
    1536              : 
    1537              :     /* Identify support functions, if provided */
    1538          127 :     if (rangeCanonicalName != NIL)
    1539              :     {
    1540            0 :         if (!OidIsValid(typoid))
    1541            0 :             ereport(ERROR,
    1542              :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    1543              :                      errmsg("cannot specify a canonical function without a pre-created shell type"),
    1544              :                      errhint("Create the type as a shell type, then create its canonicalization function, then do a full CREATE TYPE.")));
    1545            0 :         rangeCanonical = findRangeCanonicalFunction(rangeCanonicalName,
    1546              :                                                     typoid);
    1547              :     }
    1548              :     else
    1549          127 :         rangeCanonical = InvalidOid;
    1550              : 
    1551          127 :     if (rangeSubtypeDiffName != NIL)
    1552            9 :         rangeSubtypeDiff = findRangeSubtypeDiffFunction(rangeSubtypeDiffName,
    1553              :                                                         rangeSubtype);
    1554              :     else
    1555          118 :         rangeSubtypeDiff = InvalidOid;
    1556              : 
    1557          123 :     get_typlenbyvalalign(rangeSubtype,
    1558              :                          &subtyplen, &subtypbyval, &subtypalign);
    1559              : 
    1560              :     /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for ranges */
    1561          123 :     alignment = (subtypalign == TYPALIGN_DOUBLE) ? TYPALIGN_DOUBLE : TYPALIGN_INT;
    1562              : 
    1563              :     /* Allocate OID for array type, its multirange, and its multirange array */
    1564          123 :     rangeArrayOid = AssignTypeArrayOid();
    1565          123 :     multirangeOid = AssignTypeMultirangeOid();
    1566          123 :     multirangeArrayOid = AssignTypeMultirangeArrayOid();
    1567              : 
    1568              :     /* Create the pg_type entry */
    1569              :     address =
    1570          123 :         TypeCreate(InvalidOid,  /* no predetermined type OID */
    1571              :                    typeName,    /* type name */
    1572              :                    typeNamespace,   /* namespace */
    1573              :                    InvalidOid,  /* relation oid (n/a here) */
    1574              :                    0,           /* relation kind (ditto) */
    1575              :                    GetUserId(), /* owner's ID */
    1576              :                    -1,          /* internal size (always varlena) */
    1577              :                    TYPTYPE_RANGE,   /* type-type (range type) */
    1578              :                    TYPCATEGORY_RANGE,   /* type-category (range type) */
    1579              :                    false,       /* range types are never preferred */
    1580              :                    DEFAULT_TYPDELIM,    /* array element delimiter */
    1581              :                    F_RANGE_IN,  /* input procedure */
    1582              :                    F_RANGE_OUT, /* output procedure */
    1583              :                    F_RANGE_RECV,    /* receive procedure */
    1584              :                    F_RANGE_SEND,    /* send procedure */
    1585              :                    InvalidOid,  /* typmodin procedure - none */
    1586              :                    InvalidOid,  /* typmodout procedure - none */
    1587              :                    F_RANGE_TYPANALYZE,  /* analyze procedure */
    1588              :                    InvalidOid,  /* subscript procedure - none */
    1589              :                    InvalidOid,  /* element type ID - none */
    1590              :                    false,       /* this is not an array type */
    1591              :                    rangeArrayOid,   /* array type we are about to create */
    1592              :                    InvalidOid,  /* base type ID (only for domains) */
    1593              :                    NULL,        /* never a default type value */
    1594              :                    NULL,        /* no binary form available either */
    1595              :                    false,       /* never passed by value */
    1596              :                    alignment,   /* alignment */
    1597              :                    TYPSTORAGE_EXTENDED, /* TOAST strategy (always extended) */
    1598              :                    -1,          /* typMod (Domains only) */
    1599              :                    0,           /* Array dimensions of typbasetype */
    1600              :                    false,       /* Type NOT NULL */
    1601              :                    InvalidOid); /* type's collation (ranges never have one) */
    1602              :     Assert(typoid == InvalidOid || typoid == address.objectId);
    1603          123 :     typoid = address.objectId;
    1604              : 
    1605              :     /* Create the multirange that goes with it */
    1606          123 :     if (multirangeTypeName)
    1607              :     {
    1608              :         Oid         old_typoid;
    1609              : 
    1610              :         /*
    1611              :          * Look to see if multirange type already exists.
    1612              :          */
    1613           22 :         old_typoid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    1614              :                                      CStringGetDatum(multirangeTypeName),
    1615              :                                      ObjectIdGetDatum(multirangeNamespace));
    1616              : 
    1617              :         /*
    1618              :          * If it's not a shell, see if it's an autogenerated array type, and
    1619              :          * if so rename it out of the way.
    1620              :          */
    1621           22 :         if (OidIsValid(old_typoid) && get_typisdefined(old_typoid))
    1622              :         {
    1623            8 :             if (!moveArrayTypeName(old_typoid, multirangeTypeName, multirangeNamespace))
    1624            4 :                 ereport(ERROR,
    1625              :                         (errcode(ERRCODE_DUPLICATE_OBJECT),
    1626              :                          errmsg("type \"%s\" already exists", multirangeTypeName)));
    1627              :         }
    1628              :     }
    1629              :     else
    1630              :     {
    1631              :         /* Generate multirange name automatically */
    1632          101 :         multirangeNamespace = typeNamespace;
    1633          101 :         multirangeTypeName = makeMultirangeTypeName(typeName, multirangeNamespace);
    1634              :     }
    1635              : 
    1636              :     mltrngaddress =
    1637          111 :         TypeCreate(multirangeOid,   /* force assignment of this type OID */
    1638              :                    multirangeTypeName,  /* type name */
    1639              :                    multirangeNamespace, /* namespace */
    1640              :                    InvalidOid,  /* relation oid (n/a here) */
    1641              :                    0,           /* relation kind (ditto) */
    1642              :                    GetUserId(), /* owner's ID */
    1643              :                    -1,          /* internal size (always varlena) */
    1644              :                    TYPTYPE_MULTIRANGE,  /* type-type (multirange type) */
    1645              :                    TYPCATEGORY_RANGE,   /* type-category (range type) */
    1646              :                    false,       /* multirange types are never preferred */
    1647              :                    DEFAULT_TYPDELIM,    /* array element delimiter */
    1648              :                    F_MULTIRANGE_IN, /* input procedure */
    1649              :                    F_MULTIRANGE_OUT,    /* output procedure */
    1650              :                    F_MULTIRANGE_RECV,   /* receive procedure */
    1651              :                    F_MULTIRANGE_SEND,   /* send procedure */
    1652              :                    InvalidOid,  /* typmodin procedure - none */
    1653              :                    InvalidOid,  /* typmodout procedure - none */
    1654              :                    F_MULTIRANGE_TYPANALYZE, /* analyze procedure */
    1655              :                    InvalidOid,  /* subscript procedure - none */
    1656              :                    InvalidOid,  /* element type ID - none */
    1657              :                    false,       /* this is not an array type */
    1658              :                    multirangeArrayOid,  /* array type we are about to create */
    1659              :                    InvalidOid,  /* base type ID (only for domains) */
    1660              :                    NULL,        /* never a default type value */
    1661              :                    NULL,        /* no binary form available either */
    1662              :                    false,       /* never passed by value */
    1663              :                    alignment,   /* alignment */
    1664              :                    'x',         /* TOAST strategy (always extended) */
    1665              :                    -1,          /* typMod (Domains only) */
    1666              :                    0,           /* Array dimensions of typbasetype */
    1667              :                    false,       /* Type NOT NULL */
    1668              :                    InvalidOid); /* type's collation (ranges never have one) */
    1669              :     Assert(multirangeOid == mltrngaddress.objectId);
    1670              : 
    1671              :     /*
    1672              :      * Create the array type that goes with it.
    1673              :      */
    1674          111 :     rangeArrayName = makeArrayTypeName(typeName, typeNamespace);
    1675              : 
    1676          111 :     TypeCreate(rangeArrayOid,   /* force assignment of this type OID */
    1677              :                rangeArrayName,  /* type name */
    1678              :                typeNamespace,   /* namespace */
    1679              :                InvalidOid,      /* relation oid (n/a here) */
    1680              :                0,               /* relation kind (ditto) */
    1681              :                GetUserId(),     /* owner's ID */
    1682              :                -1,              /* internal size (always varlena) */
    1683              :                TYPTYPE_BASE,    /* type-type (base type) */
    1684              :                TYPCATEGORY_ARRAY,   /* type-category (array) */
    1685              :                false,           /* array types are never preferred */
    1686              :                DEFAULT_TYPDELIM,    /* array element delimiter */
    1687              :                F_ARRAY_IN,      /* input procedure */
    1688              :                F_ARRAY_OUT,     /* output procedure */
    1689              :                F_ARRAY_RECV,    /* receive procedure */
    1690              :                F_ARRAY_SEND,    /* send procedure */
    1691              :                InvalidOid,      /* typmodin procedure - none */
    1692              :                InvalidOid,      /* typmodout procedure - none */
    1693              :                F_ARRAY_TYPANALYZE,  /* analyze procedure */
    1694              :                F_ARRAY_SUBSCRIPT_HANDLER,   /* array subscript procedure */
    1695              :                typoid,          /* element type ID */
    1696              :                true,            /* yes this is an array type */
    1697              :                InvalidOid,      /* no further array type */
    1698              :                InvalidOid,      /* base type ID */
    1699              :                NULL,            /* never a default type value */
    1700              :                NULL,            /* binary default isn't sent either */
    1701              :                false,           /* never passed by value */
    1702              :                alignment,       /* alignment - same as range's */
    1703              :                TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
    1704              :                -1,              /* typMod (Domains only) */
    1705              :                0,               /* Array dimensions of typbasetype */
    1706              :                false,           /* Type NOT NULL */
    1707              :                InvalidOid);     /* typcollation */
    1708              : 
    1709          111 :     pfree(rangeArrayName);
    1710              : 
    1711              :     /* Create the multirange's array type */
    1712              : 
    1713          111 :     multirangeArrayName = makeArrayTypeName(multirangeTypeName, typeNamespace);
    1714              : 
    1715          111 :     TypeCreate(multirangeArrayOid,  /* force assignment of this type OID */
    1716              :                multirangeArrayName, /* type name */
    1717              :                multirangeNamespace, /* namespace */
    1718              :                InvalidOid,      /* relation oid (n/a here) */
    1719              :                0,               /* relation kind (ditto) */
    1720              :                GetUserId(),     /* owner's ID */
    1721              :                -1,              /* internal size (always varlena) */
    1722              :                TYPTYPE_BASE,    /* type-type (base type) */
    1723              :                TYPCATEGORY_ARRAY,   /* type-category (array) */
    1724              :                false,           /* array types are never preferred */
    1725              :                DEFAULT_TYPDELIM,    /* array element delimiter */
    1726              :                F_ARRAY_IN,      /* input procedure */
    1727              :                F_ARRAY_OUT,     /* output procedure */
    1728              :                F_ARRAY_RECV,    /* receive procedure */
    1729              :                F_ARRAY_SEND,    /* send procedure */
    1730              :                InvalidOid,      /* typmodin procedure - none */
    1731              :                InvalidOid,      /* typmodout procedure - none */
    1732              :                F_ARRAY_TYPANALYZE,  /* analyze procedure */
    1733              :                F_ARRAY_SUBSCRIPT_HANDLER,   /* array subscript procedure */
    1734              :                multirangeOid,   /* element type ID */
    1735              :                true,            /* yes this is an array type */
    1736              :                InvalidOid,      /* no further array type */
    1737              :                InvalidOid,      /* base type ID */
    1738              :                NULL,            /* never a default type value */
    1739              :                NULL,            /* binary default isn't sent either */
    1740              :                false,           /* never passed by value */
    1741              :                alignment,       /* alignment - same as range's */
    1742              :                'x',             /* ARRAY is always toastable */
    1743              :                -1,              /* typMod (Domains only) */
    1744              :                0,               /* Array dimensions of typbasetype */
    1745              :                false,           /* Type NOT NULL */
    1746              :                InvalidOid);     /* typcollation */
    1747              : 
    1748              :     /* Ensure these new types are visible to ProcedureCreate */
    1749          111 :     CommandCounterIncrement();
    1750              : 
    1751              :     /* And create the constructor functions for this range type */
    1752          111 :     makeRangeConstructors(typeName, typeNamespace, typoid, rangeSubtype,
    1753              :                           &rangeConstruct2Oid, &rangeConstruct3Oid);
    1754          111 :     makeMultirangeConstructors(multirangeTypeName, typeNamespace,
    1755              :                                multirangeOid, typoid, rangeArrayOid,
    1756              :                                &mltrngConstruct0Oid, &mltrngConstruct1Oid, &mltrngConstruct2Oid);
    1757          111 :     castFuncOid = mltrngConstruct1Oid;
    1758              : 
    1759              :     /* Create the entry in pg_range */
    1760          111 :     RangeCreate(typoid, rangeSubtype, rangeCollation, rangeSubOpclass,
    1761              :                 rangeCanonical, rangeSubtypeDiff, multirangeOid,
    1762              :                 rangeConstruct2Oid, rangeConstruct3Oid,
    1763              :                 mltrngConstruct0Oid, mltrngConstruct1Oid, mltrngConstruct2Oid);
    1764              : 
    1765              :     /* Create cast from the range type to its multirange type */
    1766          111 :     CastCreate(typoid, multirangeOid, castFuncOid, InvalidOid, InvalidOid,
    1767              :                COERCION_CODE_EXPLICIT, COERCION_METHOD_FUNCTION,
    1768              :                DEPENDENCY_INTERNAL);
    1769              : 
    1770          111 :     pfree(multirangeArrayName);
    1771              : 
    1772          111 :     return address;
    1773              : }
    1774              : 
    1775              : /*
    1776              :  * Because there may exist several range types over the same subtype, the
    1777              :  * range type can't be uniquely determined from the subtype.  So it's
    1778              :  * impossible to define a polymorphic constructor; we have to generate new
    1779              :  * constructor functions explicitly for each range type.
    1780              :  *
    1781              :  * We actually define 2 functions, with 2 through 3 arguments.  This is just
    1782              :  * to offer more convenience for the user.
    1783              :  *
    1784              :  * The OIDs of the created functions are returned through the pointer
    1785              :  * arguments.
    1786              :  */
    1787              : static void
    1788          111 : makeRangeConstructors(const char *name, Oid namespace,
    1789              :                       Oid rangeOid, Oid subtype,
    1790              :                       Oid *rangeConstruct2_p, Oid *rangeConstruct3_p)
    1791              : {
    1792              :     static const char *const prosrc[2] = {"range_constructor2",
    1793              :     "range_constructor3"};
    1794              :     static const int pronargs[2] = {2, 3};
    1795              : 
    1796              :     Oid         constructorArgTypes[3];
    1797              :     ObjectAddress myself,
    1798              :                 referenced;
    1799              :     int         i;
    1800              : 
    1801          111 :     constructorArgTypes[0] = subtype;
    1802          111 :     constructorArgTypes[1] = subtype;
    1803          111 :     constructorArgTypes[2] = TEXTOID;
    1804              : 
    1805          111 :     referenced.classId = TypeRelationId;
    1806          111 :     referenced.objectId = rangeOid;
    1807          111 :     referenced.objectSubId = 0;
    1808              : 
    1809          333 :     for (i = 0; i < lengthof(prosrc); i++)
    1810              :     {
    1811              :         oidvector  *constructorArgTypesVector;
    1812              : 
    1813          222 :         constructorArgTypesVector = buildoidvector(constructorArgTypes,
    1814          222 :                                                    pronargs[i]);
    1815              : 
    1816          222 :         myself = ProcedureCreate(name,  /* name: same as range type */
    1817              :                                  namespace, /* namespace */
    1818              :                                  false, /* replace */
    1819              :                                  false, /* returns set */
    1820              :                                  rangeOid,  /* return type */
    1821              :                                  BOOTSTRAP_SUPERUSERID, /* proowner */
    1822              :                                  INTERNALlanguageId,    /* language */
    1823              :                                  F_FMGR_INTERNAL_VALIDATOR, /* language validator */
    1824          222 :                                  prosrc[i], /* prosrc */
    1825              :                                  NULL,  /* probin */
    1826              :                                  NULL,  /* prosqlbody */
    1827              :                                  PROKIND_FUNCTION,
    1828              :                                  false, /* security_definer */
    1829              :                                  false, /* leakproof */
    1830              :                                  false, /* isStrict */
    1831              :                                  PROVOLATILE_IMMUTABLE, /* volatility */
    1832              :                                  PROPARALLEL_SAFE,  /* parallel safety */
    1833              :                                  constructorArgTypesVector, /* parameterTypes */
    1834              :                                  PointerGetDatum(NULL), /* allParameterTypes */
    1835              :                                  PointerGetDatum(NULL), /* parameterModes */
    1836              :                                  PointerGetDatum(NULL), /* parameterNames */
    1837              :                                  NIL,   /* parameterDefaults */
    1838              :                                  PointerGetDatum(NULL), /* trftypes */
    1839              :                                  NIL,   /* trfoids */
    1840              :                                  PointerGetDatum(NULL), /* proconfig */
    1841              :                                  InvalidOid,    /* prosupport */
    1842              :                                  1.0,   /* procost */
    1843              :                                  0.0);  /* prorows */
    1844              : 
    1845              :         /*
    1846              :          * Make the constructors internally-dependent on the range type so
    1847              :          * that they go away silently when the type is dropped.  Note that
    1848              :          * pg_dump depends on this choice to avoid dumping the constructors.
    1849              :          */
    1850          222 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
    1851              : 
    1852          222 :         if (pronargs[i] == 2)
    1853          111 :             *rangeConstruct2_p = myself.objectId;
    1854          111 :         else if (pronargs[i] == 3)
    1855          111 :             *rangeConstruct3_p = myself.objectId;
    1856              :     }
    1857          111 : }
    1858              : 
    1859              : /*
    1860              :  * We make a separate multirange constructor for each range type
    1861              :  * so its name can include the base type, like range constructors do.
    1862              :  * If we had an anyrangearray polymorphic type we could use it here,
    1863              :  * but since each type has its own constructor name there's no need.
    1864              :  *
    1865              :  * The OIDs of the created functions are returned through the pointer
    1866              :  * arguments.
    1867              :  */
    1868              : static void
    1869          111 : makeMultirangeConstructors(const char *name, Oid namespace,
    1870              :                            Oid multirangeOid, Oid rangeOid, Oid rangeArrayOid,
    1871              :                            Oid *mltrngConstruct0_p, Oid *mltrngConstruct1_p, Oid *mltrngConstruct2_p)
    1872              : {
    1873              :     ObjectAddress myself,
    1874              :                 referenced;
    1875              :     oidvector  *argtypes;
    1876              :     Datum       allParamTypes;
    1877              :     ArrayType  *allParameterTypes;
    1878              :     Datum       paramModes;
    1879              :     ArrayType  *parameterModes;
    1880              : 
    1881          111 :     referenced.classId = TypeRelationId;
    1882          111 :     referenced.objectId = multirangeOid;
    1883          111 :     referenced.objectSubId = 0;
    1884              : 
    1885              :     /* 0-arg constructor - for empty multiranges */
    1886          111 :     argtypes = buildoidvector(NULL, 0);
    1887          111 :     myself = ProcedureCreate(name,  /* name: same as multirange type */
    1888              :                              namespace,
    1889              :                              false, /* replace */
    1890              :                              false, /* returns set */
    1891              :                              multirangeOid, /* return type */
    1892              :                              BOOTSTRAP_SUPERUSERID, /* proowner */
    1893              :                              INTERNALlanguageId,    /* language */
    1894              :                              F_FMGR_INTERNAL_VALIDATOR,
    1895              :                              "multirange_constructor0", /* prosrc */
    1896              :                              NULL,  /* probin */
    1897              :                              NULL,  /* prosqlbody */
    1898              :                              PROKIND_FUNCTION,
    1899              :                              false, /* security_definer */
    1900              :                              false, /* leakproof */
    1901              :                              true,  /* isStrict */
    1902              :                              PROVOLATILE_IMMUTABLE, /* volatility */
    1903              :                              PROPARALLEL_SAFE,  /* parallel safety */
    1904              :                              argtypes,  /* parameterTypes */
    1905              :                              PointerGetDatum(NULL), /* allParameterTypes */
    1906              :                              PointerGetDatum(NULL), /* parameterModes */
    1907              :                              PointerGetDatum(NULL), /* parameterNames */
    1908              :                              NIL,   /* parameterDefaults */
    1909              :                              PointerGetDatum(NULL), /* trftypes */
    1910              :                              NIL,   /* trfoids */
    1911              :                              PointerGetDatum(NULL), /* proconfig */
    1912              :                              InvalidOid,    /* prosupport */
    1913              :                              1.0,   /* procost */
    1914              :                              0.0);  /* prorows */
    1915              : 
    1916              :     /*
    1917              :      * Make the constructor internally-dependent on the multirange type so
    1918              :      * that they go away silently when the type is dropped.  Note that pg_dump
    1919              :      * depends on this choice to avoid dumping the constructors.
    1920              :      */
    1921          111 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
    1922          111 :     *mltrngConstruct0_p = myself.objectId;
    1923          111 :     pfree(argtypes);
    1924              : 
    1925              :     /*
    1926              :      * 1-arg constructor - for casts
    1927              :      *
    1928              :      * In theory we shouldn't need both this and the vararg (n-arg)
    1929              :      * constructor, but having a separate 1-arg function lets us define casts
    1930              :      * against it.
    1931              :      */
    1932          111 :     argtypes = buildoidvector(&rangeOid, 1);
    1933          111 :     myself = ProcedureCreate(name,  /* name: same as multirange type */
    1934              :                              namespace,
    1935              :                              false, /* replace */
    1936              :                              false, /* returns set */
    1937              :                              multirangeOid, /* return type */
    1938              :                              BOOTSTRAP_SUPERUSERID, /* proowner */
    1939              :                              INTERNALlanguageId,    /* language */
    1940              :                              F_FMGR_INTERNAL_VALIDATOR,
    1941              :                              "multirange_constructor1", /* prosrc */
    1942              :                              NULL,  /* probin */
    1943              :                              NULL,  /* prosqlbody */
    1944              :                              PROKIND_FUNCTION,
    1945              :                              false, /* security_definer */
    1946              :                              false, /* leakproof */
    1947              :                              true,  /* isStrict */
    1948              :                              PROVOLATILE_IMMUTABLE, /* volatility */
    1949              :                              PROPARALLEL_SAFE,  /* parallel safety */
    1950              :                              argtypes,  /* parameterTypes */
    1951              :                              PointerGetDatum(NULL), /* allParameterTypes */
    1952              :                              PointerGetDatum(NULL), /* parameterModes */
    1953              :                              PointerGetDatum(NULL), /* parameterNames */
    1954              :                              NIL,   /* parameterDefaults */
    1955              :                              PointerGetDatum(NULL), /* trftypes */
    1956              :                              NIL,   /* trfoids */
    1957              :                              PointerGetDatum(NULL), /* proconfig */
    1958              :                              InvalidOid,    /* prosupport */
    1959              :                              1.0,   /* procost */
    1960              :                              0.0);  /* prorows */
    1961              :     /* ditto */
    1962          111 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
    1963          111 :     *mltrngConstruct1_p = myself.objectId;
    1964          111 :     pfree(argtypes);
    1965              : 
    1966              :     /* n-arg constructor - vararg */
    1967          111 :     argtypes = buildoidvector(&rangeArrayOid, 1);
    1968          111 :     allParamTypes = ObjectIdGetDatum(rangeArrayOid);
    1969          111 :     allParameterTypes = construct_array_builtin(&allParamTypes, 1, OIDOID);
    1970          111 :     paramModes = CharGetDatum(FUNC_PARAM_VARIADIC);
    1971          111 :     parameterModes = construct_array_builtin(&paramModes, 1, CHAROID);
    1972          111 :     myself = ProcedureCreate(name,  /* name: same as multirange type */
    1973              :                              namespace,
    1974              :                              false, /* replace */
    1975              :                              false, /* returns set */
    1976              :                              multirangeOid, /* return type */
    1977              :                              BOOTSTRAP_SUPERUSERID, /* proowner */
    1978              :                              INTERNALlanguageId,    /* language */
    1979              :                              F_FMGR_INTERNAL_VALIDATOR,
    1980              :                              "multirange_constructor2", /* prosrc */
    1981              :                              NULL,  /* probin */
    1982              :                              NULL,  /* prosqlbody */
    1983              :                              PROKIND_FUNCTION,
    1984              :                              false, /* security_definer */
    1985              :                              false, /* leakproof */
    1986              :                              true,  /* isStrict */
    1987              :                              PROVOLATILE_IMMUTABLE, /* volatility */
    1988              :                              PROPARALLEL_SAFE,  /* parallel safety */
    1989              :                              argtypes,  /* parameterTypes */
    1990              :                              PointerGetDatum(allParameterTypes),    /* allParameterTypes */
    1991              :                              PointerGetDatum(parameterModes),   /* parameterModes */
    1992              :                              PointerGetDatum(NULL), /* parameterNames */
    1993              :                              NIL,   /* parameterDefaults */
    1994              :                              PointerGetDatum(NULL), /* trftypes */
    1995              :                              NIL,   /* trfoids */
    1996              :                              PointerGetDatum(NULL), /* proconfig */
    1997              :                              InvalidOid,    /* prosupport */
    1998              :                              1.0,   /* procost */
    1999              :                              0.0);  /* prorows */
    2000              :     /* ditto */
    2001          111 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
    2002          111 :     *mltrngConstruct2_p = myself.objectId;
    2003          111 :     pfree(argtypes);
    2004          111 :     pfree(allParameterTypes);
    2005          111 :     pfree(parameterModes);
    2006          111 : }
    2007              : 
    2008              : /*
    2009              :  * Find suitable I/O and other support functions for a type.
    2010              :  *
    2011              :  * typeOid is the type's OID (which will already exist, if only as a shell
    2012              :  * type).
    2013              :  */
    2014              : 
    2015              : static Oid
    2016          125 : findTypeInputFunction(List *procname, Oid typeOid)
    2017              : {
    2018              :     Oid         argList[3];
    2019              :     Oid         procOid;
    2020              :     Oid         procOid2;
    2021              : 
    2022              :     /*
    2023              :      * Input functions can take a single argument of type CSTRING, or three
    2024              :      * arguments (string, typioparam OID, typmod).  Whine about ambiguity if
    2025              :      * both forms exist.
    2026              :      */
    2027          125 :     argList[0] = CSTRINGOID;
    2028          125 :     argList[1] = OIDOID;
    2029          125 :     argList[2] = INT4OID;
    2030              : 
    2031          125 :     procOid = LookupFuncName(procname, 1, argList, true);
    2032          125 :     procOid2 = LookupFuncName(procname, 3, argList, true);
    2033          125 :     if (OidIsValid(procOid))
    2034              :     {
    2035          115 :         if (OidIsValid(procOid2))
    2036            0 :             ereport(ERROR,
    2037              :                     (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
    2038              :                      errmsg("type input function %s has multiple matches",
    2039              :                             NameListToString(procname))));
    2040              :     }
    2041              :     else
    2042              :     {
    2043           10 :         procOid = procOid2;
    2044              :         /* If not found, reference the 1-argument signature in error msg */
    2045           10 :         if (!OidIsValid(procOid))
    2046            0 :             ereport(ERROR,
    2047              :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2048              :                      errmsg("function %s does not exist",
    2049              :                             func_signature_string(procname, 1, NIL, argList))));
    2050              :     }
    2051              : 
    2052              :     /* Input functions must return the target type. */
    2053          125 :     if (get_func_rettype(procOid) != typeOid)
    2054            4 :         ereport(ERROR,
    2055              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2056              :                  errmsg("type input function %s must return type %s",
    2057              :                         NameListToString(procname), format_type_be(typeOid))));
    2058              : 
    2059              :     /*
    2060              :      * Print warnings if any of the type's I/O functions are marked volatile.
    2061              :      * There is a general assumption that I/O functions are stable or
    2062              :      * immutable; this allows us for example to mark record_in/record_out
    2063              :      * stable rather than volatile.  Ideally we would throw errors not just
    2064              :      * warnings here; but since this check is new as of 9.5, and since the
    2065              :      * volatility marking might be just an error-of-omission and not a true
    2066              :      * indication of how the function behaves, we'll let it pass as a warning
    2067              :      * for now.
    2068              :      */
    2069          121 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2070            0 :         ereport(WARNING,
    2071              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2072              :                  errmsg("type input function %s should not be volatile",
    2073              :                         NameListToString(procname))));
    2074              : 
    2075          121 :     return procOid;
    2076              : }
    2077              : 
    2078              : static Oid
    2079          121 : findTypeOutputFunction(List *procname, Oid typeOid)
    2080              : {
    2081              :     Oid         argList[1];
    2082              :     Oid         procOid;
    2083              : 
    2084              :     /*
    2085              :      * Output functions always take a single argument of the type and return
    2086              :      * cstring.
    2087              :      */
    2088          121 :     argList[0] = typeOid;
    2089              : 
    2090          121 :     procOid = LookupFuncName(procname, 1, argList, true);
    2091          121 :     if (!OidIsValid(procOid))
    2092            0 :         ereport(ERROR,
    2093              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2094              :                  errmsg("function %s does not exist",
    2095              :                         func_signature_string(procname, 1, NIL, argList))));
    2096              : 
    2097          121 :     if (get_func_rettype(procOid) != CSTRINGOID)
    2098            0 :         ereport(ERROR,
    2099              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2100              :                  errmsg("type output function %s must return type %s",
    2101              :                         NameListToString(procname), "cstring")));
    2102              : 
    2103              :     /* Just a warning for now, per comments in findTypeInputFunction */
    2104          121 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2105            0 :         ereport(WARNING,
    2106              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2107              :                  errmsg("type output function %s should not be volatile",
    2108              :                         NameListToString(procname))));
    2109              : 
    2110          121 :     return procOid;
    2111              : }
    2112              : 
    2113              : static Oid
    2114           24 : findTypeReceiveFunction(List *procname, Oid typeOid)
    2115              : {
    2116              :     Oid         argList[3];
    2117              :     Oid         procOid;
    2118              :     Oid         procOid2;
    2119              : 
    2120              :     /*
    2121              :      * Receive functions can take a single argument of type INTERNAL, or three
    2122              :      * arguments (internal, typioparam OID, typmod).  Whine about ambiguity if
    2123              :      * both forms exist.
    2124              :      */
    2125           24 :     argList[0] = INTERNALOID;
    2126           24 :     argList[1] = OIDOID;
    2127           24 :     argList[2] = INT4OID;
    2128              : 
    2129           24 :     procOid = LookupFuncName(procname, 1, argList, true);
    2130           24 :     procOid2 = LookupFuncName(procname, 3, argList, true);
    2131           24 :     if (OidIsValid(procOid))
    2132              :     {
    2133           18 :         if (OidIsValid(procOid2))
    2134            0 :             ereport(ERROR,
    2135              :                     (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
    2136              :                      errmsg("type receive function %s has multiple matches",
    2137              :                             NameListToString(procname))));
    2138              :     }
    2139              :     else
    2140              :     {
    2141            6 :         procOid = procOid2;
    2142              :         /* If not found, reference the 1-argument signature in error msg */
    2143            6 :         if (!OidIsValid(procOid))
    2144            0 :             ereport(ERROR,
    2145              :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2146              :                      errmsg("function %s does not exist",
    2147              :                             func_signature_string(procname, 1, NIL, argList))));
    2148              :     }
    2149              : 
    2150              :     /* Receive functions must return the target type. */
    2151           24 :     if (get_func_rettype(procOid) != typeOid)
    2152            0 :         ereport(ERROR,
    2153              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2154              :                  errmsg("type receive function %s must return type %s",
    2155              :                         NameListToString(procname), format_type_be(typeOid))));
    2156              : 
    2157              :     /* Just a warning for now, per comments in findTypeInputFunction */
    2158           24 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2159            0 :         ereport(WARNING,
    2160              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2161              :                  errmsg("type receive function %s should not be volatile",
    2162              :                         NameListToString(procname))));
    2163              : 
    2164           24 :     return procOid;
    2165              : }
    2166              : 
    2167              : static Oid
    2168           24 : findTypeSendFunction(List *procname, Oid typeOid)
    2169              : {
    2170              :     Oid         argList[1];
    2171              :     Oid         procOid;
    2172              : 
    2173              :     /*
    2174              :      * Send functions always take a single argument of the type and return
    2175              :      * bytea.
    2176              :      */
    2177           24 :     argList[0] = typeOid;
    2178              : 
    2179           24 :     procOid = LookupFuncName(procname, 1, argList, true);
    2180           24 :     if (!OidIsValid(procOid))
    2181            0 :         ereport(ERROR,
    2182              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2183              :                  errmsg("function %s does not exist",
    2184              :                         func_signature_string(procname, 1, NIL, argList))));
    2185              : 
    2186           24 :     if (get_func_rettype(procOid) != BYTEAOID)
    2187            0 :         ereport(ERROR,
    2188              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2189              :                  errmsg("type send function %s must return type %s",
    2190              :                         NameListToString(procname), "bytea")));
    2191              : 
    2192              :     /* Just a warning for now, per comments in findTypeInputFunction */
    2193           24 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2194            0 :         ereport(WARNING,
    2195              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2196              :                  errmsg("type send function %s should not be volatile",
    2197              :                         NameListToString(procname))));
    2198              : 
    2199           24 :     return procOid;
    2200              : }
    2201              : 
    2202              : static Oid
    2203            9 : findTypeTypmodinFunction(List *procname)
    2204              : {
    2205              :     Oid         argList[1];
    2206              :     Oid         procOid;
    2207              : 
    2208              :     /*
    2209              :      * typmodin functions always take one cstring[] argument and return int4.
    2210              :      */
    2211            9 :     argList[0] = CSTRINGARRAYOID;
    2212              : 
    2213            9 :     procOid = LookupFuncName(procname, 1, argList, true);
    2214            9 :     if (!OidIsValid(procOid))
    2215            0 :         ereport(ERROR,
    2216              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2217              :                  errmsg("function %s does not exist",
    2218              :                         func_signature_string(procname, 1, NIL, argList))));
    2219              : 
    2220            9 :     if (get_func_rettype(procOid) != INT4OID)
    2221            0 :         ereport(ERROR,
    2222              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2223              :                  errmsg("typmod_in function %s must return type %s",
    2224              :                         NameListToString(procname), "integer")));
    2225              : 
    2226              :     /* Just a warning for now, per comments in findTypeInputFunction */
    2227            9 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2228            0 :         ereport(WARNING,
    2229              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2230              :                  errmsg("type modifier input function %s should not be volatile",
    2231              :                         NameListToString(procname))));
    2232              : 
    2233            9 :     return procOid;
    2234              : }
    2235              : 
    2236              : static Oid
    2237            9 : findTypeTypmodoutFunction(List *procname)
    2238              : {
    2239              :     Oid         argList[1];
    2240              :     Oid         procOid;
    2241              : 
    2242              :     /*
    2243              :      * typmodout functions always take one int4 argument and return cstring.
    2244              :      */
    2245            9 :     argList[0] = INT4OID;
    2246              : 
    2247            9 :     procOid = LookupFuncName(procname, 1, argList, true);
    2248            9 :     if (!OidIsValid(procOid))
    2249            0 :         ereport(ERROR,
    2250              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2251              :                  errmsg("function %s does not exist",
    2252              :                         func_signature_string(procname, 1, NIL, argList))));
    2253              : 
    2254            9 :     if (get_func_rettype(procOid) != CSTRINGOID)
    2255            0 :         ereport(ERROR,
    2256              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2257              :                  errmsg("typmod_out function %s must return type %s",
    2258              :                         NameListToString(procname), "cstring")));
    2259              : 
    2260              :     /* Just a warning for now, per comments in findTypeInputFunction */
    2261            9 :     if (func_volatile(procOid) == PROVOLATILE_VOLATILE)
    2262            0 :         ereport(WARNING,
    2263              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2264              :                  errmsg("type modifier output function %s should not be volatile",
    2265              :                         NameListToString(procname))));
    2266              : 
    2267            9 :     return procOid;
    2268              : }
    2269              : 
    2270              : static Oid
    2271            6 : findTypeAnalyzeFunction(List *procname, Oid typeOid)
    2272              : {
    2273              :     Oid         argList[1];
    2274              :     Oid         procOid;
    2275              : 
    2276              :     /*
    2277              :      * Analyze functions always take one INTERNAL argument and return bool.
    2278              :      */
    2279            6 :     argList[0] = INTERNALOID;
    2280              : 
    2281            6 :     procOid = LookupFuncName(procname, 1, argList, true);
    2282            6 :     if (!OidIsValid(procOid))
    2283            0 :         ereport(ERROR,
    2284              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2285              :                  errmsg("function %s does not exist",
    2286              :                         func_signature_string(procname, 1, NIL, argList))));
    2287              : 
    2288            6 :     if (get_func_rettype(procOid) != BOOLOID)
    2289            0 :         ereport(ERROR,
    2290              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2291              :                  errmsg("type analyze function %s must return type %s",
    2292              :                         NameListToString(procname), "boolean")));
    2293              : 
    2294            6 :     return procOid;
    2295              : }
    2296              : 
    2297              : static Oid
    2298           12 : findTypeSubscriptingFunction(List *procname, Oid typeOid)
    2299              : {
    2300              :     Oid         argList[1];
    2301              :     Oid         procOid;
    2302              : 
    2303              :     /*
    2304              :      * Subscripting support functions always take one INTERNAL argument and
    2305              :      * return INTERNAL.  (The argument is not used, but we must have it to
    2306              :      * maintain type safety.)
    2307              :      */
    2308           12 :     argList[0] = INTERNALOID;
    2309              : 
    2310           12 :     procOid = LookupFuncName(procname, 1, argList, true);
    2311           12 :     if (!OidIsValid(procOid))
    2312            0 :         ereport(ERROR,
    2313              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2314              :                  errmsg("function %s does not exist",
    2315              :                         func_signature_string(procname, 1, NIL, argList))));
    2316              : 
    2317           12 :     if (get_func_rettype(procOid) != INTERNALOID)
    2318            0 :         ereport(ERROR,
    2319              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2320              :                  errmsg("type subscripting function %s must return type %s",
    2321              :                         NameListToString(procname), "internal")));
    2322              : 
    2323              :     /*
    2324              :      * We disallow array_subscript_handler() from being selected explicitly,
    2325              :      * since that must only be applied to autogenerated array types.
    2326              :      */
    2327           12 :     if (procOid == F_ARRAY_SUBSCRIPT_HANDLER)
    2328            0 :         ereport(ERROR,
    2329              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2330              :                  errmsg("user-defined types cannot use subscripting function %s",
    2331              :                         NameListToString(procname))));
    2332              : 
    2333           12 :     return procOid;
    2334              : }
    2335              : 
    2336              : /*
    2337              :  * Find suitable support functions and opclasses for a range type.
    2338              :  */
    2339              : 
    2340              : /*
    2341              :  * Find named btree opclass for subtype, or default btree opclass if
    2342              :  * opcname is NIL.
    2343              :  */
    2344              : static Oid
    2345          127 : findRangeSubOpclass(List *opcname, Oid subtype)
    2346              : {
    2347              :     Oid         opcid;
    2348              :     Oid         opInputType;
    2349              : 
    2350          127 :     if (opcname != NIL)
    2351              :     {
    2352            5 :         opcid = get_opclass_oid(BTREE_AM_OID, opcname, false);
    2353              : 
    2354              :         /*
    2355              :          * Verify that the operator class accepts this datatype. Note we will
    2356              :          * accept binary compatibility.
    2357              :          */
    2358            5 :         opInputType = get_opclass_input_type(opcid);
    2359            5 :         if (!IsBinaryCoercible(subtype, opInputType))
    2360            0 :             ereport(ERROR,
    2361              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2362              :                      errmsg("operator class \"%s\" does not accept data type %s",
    2363              :                             NameListToString(opcname),
    2364              :                             format_type_be(subtype))));
    2365              :     }
    2366              :     else
    2367              :     {
    2368          122 :         opcid = GetDefaultOpClass(subtype, BTREE_AM_OID);
    2369          122 :         if (!OidIsValid(opcid))
    2370              :         {
    2371              :             /* We spell the error message identically to ResolveOpClass */
    2372            0 :             ereport(ERROR,
    2373              :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2374              :                      errmsg("data type %s has no default operator class for access method \"%s\"",
    2375              :                             format_type_be(subtype), "btree"),
    2376              :                      errhint("You must specify an operator class for the range type or define a default operator class for the subtype.")));
    2377              :         }
    2378              :     }
    2379              : 
    2380          127 :     return opcid;
    2381              : }
    2382              : 
    2383              : static Oid
    2384            0 : findRangeCanonicalFunction(List *procname, Oid typeOid)
    2385              : {
    2386              :     Oid         argList[1];
    2387              :     Oid         procOid;
    2388              :     AclResult   aclresult;
    2389              : 
    2390              :     /*
    2391              :      * Range canonical functions must take and return the range type, and must
    2392              :      * be immutable.
    2393              :      */
    2394            0 :     argList[0] = typeOid;
    2395              : 
    2396            0 :     procOid = LookupFuncName(procname, 1, argList, true);
    2397              : 
    2398            0 :     if (!OidIsValid(procOid))
    2399            0 :         ereport(ERROR,
    2400              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2401              :                  errmsg("function %s does not exist",
    2402              :                         func_signature_string(procname, 1, NIL, argList))));
    2403              : 
    2404            0 :     if (get_func_rettype(procOid) != typeOid)
    2405            0 :         ereport(ERROR,
    2406              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2407              :                  errmsg("range canonical function %s must return range type",
    2408              :                         func_signature_string(procname, 1, NIL, argList))));
    2409              : 
    2410            0 :     if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
    2411            0 :         ereport(ERROR,
    2412              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2413              :                  errmsg("range canonical function %s must be immutable",
    2414              :                         func_signature_string(procname, 1, NIL, argList))));
    2415              : 
    2416              :     /* Also, range type's creator must have permission to call function */
    2417            0 :     aclresult = object_aclcheck(ProcedureRelationId, procOid, GetUserId(), ACL_EXECUTE);
    2418            0 :     if (aclresult != ACLCHECK_OK)
    2419            0 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(procOid));
    2420              : 
    2421            0 :     return procOid;
    2422              : }
    2423              : 
    2424              : static Oid
    2425            9 : findRangeSubtypeDiffFunction(List *procname, Oid subtype)
    2426              : {
    2427              :     Oid         argList[2];
    2428              :     Oid         procOid;
    2429              :     AclResult   aclresult;
    2430              : 
    2431              :     /*
    2432              :      * Range subtype diff functions must take two arguments of the subtype,
    2433              :      * must return float8, and must be immutable.
    2434              :      */
    2435            9 :     argList[0] = subtype;
    2436            9 :     argList[1] = subtype;
    2437              : 
    2438            9 :     procOid = LookupFuncName(procname, 2, argList, true);
    2439              : 
    2440            9 :     if (!OidIsValid(procOid))
    2441            4 :         ereport(ERROR,
    2442              :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2443              :                  errmsg("function %s does not exist",
    2444              :                         func_signature_string(procname, 2, NIL, argList))));
    2445              : 
    2446            5 :     if (get_func_rettype(procOid) != FLOAT8OID)
    2447            0 :         ereport(ERROR,
    2448              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2449              :                  errmsg("range subtype diff function %s must return type %s",
    2450              :                         func_signature_string(procname, 2, NIL, argList),
    2451              :                         "double precision")));
    2452              : 
    2453            5 :     if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
    2454            0 :         ereport(ERROR,
    2455              :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2456              :                  errmsg("range subtype diff function %s must be immutable",
    2457              :                         func_signature_string(procname, 2, NIL, argList))));
    2458              : 
    2459              :     /* Also, range type's creator must have permission to call function */
    2460            5 :     aclresult = object_aclcheck(ProcedureRelationId, procOid, GetUserId(), ACL_EXECUTE);
    2461            5 :     if (aclresult != ACLCHECK_OK)
    2462            0 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(procOid));
    2463              : 
    2464            5 :     return procOid;
    2465              : }
    2466              : 
    2467              : /*
    2468              :  *  AssignTypeArrayOid
    2469              :  *
    2470              :  *  Pre-assign the type's array OID for use in pg_type.typarray
    2471              :  */
    2472              : Oid
    2473        44953 : AssignTypeArrayOid(void)
    2474              : {
    2475              :     Oid         type_array_oid;
    2476              : 
    2477              :     /* Use binary-upgrade override for pg_type.typarray? */
    2478        44953 :     if (IsBinaryUpgrade)
    2479              :     {
    2480          938 :         if (!OidIsValid(binary_upgrade_next_array_pg_type_oid))
    2481            0 :             ereport(ERROR,
    2482              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2483              :                      errmsg("pg_type array OID value not set when in binary upgrade mode")));
    2484              : 
    2485          938 :         type_array_oid = binary_upgrade_next_array_pg_type_oid;
    2486          938 :         binary_upgrade_next_array_pg_type_oid = InvalidOid;
    2487              :     }
    2488              :     else
    2489              :     {
    2490        44015 :         Relation    pg_type = table_open(TypeRelationId, AccessShareLock);
    2491              : 
    2492        44015 :         type_array_oid = GetNewOidWithIndex(pg_type, TypeOidIndexId,
    2493              :                                             Anum_pg_type_oid);
    2494        44015 :         table_close(pg_type, AccessShareLock);
    2495              :     }
    2496              : 
    2497        44953 :     return type_array_oid;
    2498              : }
    2499              : 
    2500              : /*
    2501              :  *  AssignTypeMultirangeOid
    2502              :  *
    2503              :  *  Pre-assign the range type's multirange OID for use in pg_type.oid
    2504              :  */
    2505              : Oid
    2506          123 : AssignTypeMultirangeOid(void)
    2507              : {
    2508              :     Oid         type_multirange_oid;
    2509              : 
    2510              :     /* Use binary-upgrade override for pg_type.oid? */
    2511          123 :     if (IsBinaryUpgrade)
    2512              :     {
    2513            6 :         if (!OidIsValid(binary_upgrade_next_mrng_pg_type_oid))
    2514            0 :             ereport(ERROR,
    2515              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2516              :                      errmsg("pg_type multirange OID value not set when in binary upgrade mode")));
    2517              : 
    2518            6 :         type_multirange_oid = binary_upgrade_next_mrng_pg_type_oid;
    2519            6 :         binary_upgrade_next_mrng_pg_type_oid = InvalidOid;
    2520              :     }
    2521              :     else
    2522              :     {
    2523          117 :         Relation    pg_type = table_open(TypeRelationId, AccessShareLock);
    2524              : 
    2525          117 :         type_multirange_oid = GetNewOidWithIndex(pg_type, TypeOidIndexId,
    2526              :                                                  Anum_pg_type_oid);
    2527          117 :         table_close(pg_type, AccessShareLock);
    2528              :     }
    2529              : 
    2530          123 :     return type_multirange_oid;
    2531              : }
    2532              : 
    2533              : /*
    2534              :  *  AssignTypeMultirangeArrayOid
    2535              :  *
    2536              :  *  Pre-assign the range type's multirange array OID for use in pg_type.typarray
    2537              :  */
    2538              : Oid
    2539          123 : AssignTypeMultirangeArrayOid(void)
    2540              : {
    2541              :     Oid         type_multirange_array_oid;
    2542              : 
    2543              :     /* Use binary-upgrade override for pg_type.oid? */
    2544          123 :     if (IsBinaryUpgrade)
    2545              :     {
    2546            6 :         if (!OidIsValid(binary_upgrade_next_mrng_array_pg_type_oid))
    2547            0 :             ereport(ERROR,
    2548              :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2549              :                      errmsg("pg_type multirange array OID value not set when in binary upgrade mode")));
    2550              : 
    2551            6 :         type_multirange_array_oid = binary_upgrade_next_mrng_array_pg_type_oid;
    2552            6 :         binary_upgrade_next_mrng_array_pg_type_oid = InvalidOid;
    2553              :     }
    2554              :     else
    2555              :     {
    2556          117 :         Relation    pg_type = table_open(TypeRelationId, AccessShareLock);
    2557              : 
    2558          117 :         type_multirange_array_oid = GetNewOidWithIndex(pg_type, TypeOidIndexId,
    2559              :                                                        Anum_pg_type_oid);
    2560          117 :         table_close(pg_type, AccessShareLock);
    2561              :     }
    2562              : 
    2563          123 :     return type_multirange_array_oid;
    2564              : }
    2565              : 
    2566              : 
    2567              : /*-------------------------------------------------------------------
    2568              :  * DefineCompositeType
    2569              :  *
    2570              :  * Create a Composite Type relation.
    2571              :  * `DefineRelation' does all the work, we just provide the correct
    2572              :  * arguments!
    2573              :  *
    2574              :  * If the relation already exists, then 'DefineRelation' will abort
    2575              :  * the xact...
    2576              :  *
    2577              :  * Return type is the new type's object address.
    2578              :  *-------------------------------------------------------------------
    2579              :  */
    2580              : ObjectAddress
    2581         2358 : DefineCompositeType(RangeVar *typevar, List *coldeflist)
    2582              : {
    2583         2358 :     CreateStmt *createStmt = makeNode(CreateStmt);
    2584              :     Oid         old_type_oid;
    2585              :     Oid         typeNamespace;
    2586              :     ObjectAddress address;
    2587              : 
    2588              :     /*
    2589              :      * now set the parameters for keys/inheritance etc. All of these are
    2590              :      * uninteresting for composite types...
    2591              :      */
    2592         2358 :     createStmt->relation = typevar;
    2593         2358 :     createStmt->tableElts = coldeflist;
    2594         2358 :     createStmt->inhRelations = NIL;
    2595         2358 :     createStmt->constraints = NIL;
    2596         2358 :     createStmt->options = NIL;
    2597         2358 :     createStmt->oncommit = ONCOMMIT_NOOP;
    2598         2358 :     createStmt->tablespacename = NULL;
    2599         2358 :     createStmt->if_not_exists = false;
    2600              : 
    2601              :     /*
    2602              :      * Check for collision with an existing type name. If there is one and
    2603              :      * it's an autogenerated array, we can rename it out of the way.  This
    2604              :      * check is here mainly to get a better error message about a "type"
    2605              :      * instead of below about a "relation".
    2606              :      */
    2607         2358 :     typeNamespace = RangeVarGetAndCheckCreationNamespace(createStmt->relation,
    2608              :                                                          NoLock, NULL);
    2609         2358 :     RangeVarAdjustRelationPersistence(createStmt->relation, typeNamespace);
    2610              :     old_type_oid =
    2611         2358 :         GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
    2612              :                         CStringGetDatum(createStmt->relation->relname),
    2613              :                         ObjectIdGetDatum(typeNamespace));
    2614         2358 :     if (OidIsValid(old_type_oid))
    2615              :     {
    2616            0 :         if (!moveArrayTypeName(old_type_oid, createStmt->relation->relname, typeNamespace))
    2617            0 :             ereport(ERROR,
    2618              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    2619              :                      errmsg("type \"%s\" already exists", createStmt->relation->relname)));
    2620              :     }
    2621              : 
    2622              :     /*
    2623              :      * Finally create the relation.  This also creates the type.
    2624              :      */
    2625         2358 :     DefineRelation(createStmt, RELKIND_COMPOSITE_TYPE, InvalidOid, &address,
    2626              :                    NULL);
    2627              : 
    2628         2350 :     return address;
    2629              : }
    2630              : 
    2631              : /*
    2632              :  * AlterDomainDefault
    2633              :  *
    2634              :  * Routine implementing ALTER DOMAIN SET/DROP DEFAULT statements.
    2635              :  *
    2636              :  * Returns ObjectAddress of the modified domain.
    2637              :  */
    2638              : ObjectAddress
    2639            9 : AlterDomainDefault(List *names, Node *defaultRaw)
    2640              : {
    2641              :     TypeName   *typename;
    2642              :     Oid         domainoid;
    2643              :     HeapTuple   tup;
    2644              :     ParseState *pstate;
    2645              :     Relation    rel;
    2646              :     char       *defaultValue;
    2647            9 :     Node       *defaultExpr = NULL; /* NULL if no default specified */
    2648            9 :     Datum       new_record[Natts_pg_type] = {0};
    2649            9 :     bool        new_record_nulls[Natts_pg_type] = {0};
    2650            9 :     bool        new_record_repl[Natts_pg_type] = {0};
    2651              :     HeapTuple   newtuple;
    2652              :     Form_pg_type typTup;
    2653              :     ObjectAddress address;
    2654              : 
    2655              :     /* Make a TypeName so we can use standard type lookup machinery */
    2656            9 :     typename = makeTypeNameFromNameList(names);
    2657            9 :     domainoid = typenameTypeId(NULL, typename);
    2658              : 
    2659              :     /* Look up the domain in the type table */
    2660            9 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    2661              : 
    2662            9 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
    2663            9 :     if (!HeapTupleIsValid(tup))
    2664            0 :         elog(ERROR, "cache lookup failed for type %u", domainoid);
    2665            9 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    2666              : 
    2667              :     /* Check it's a domain and check user has permission for ALTER DOMAIN */
    2668            9 :     checkDomainOwner(tup);
    2669              : 
    2670              :     /* Setup new tuple */
    2671              : 
    2672              :     /* Store the new default into the tuple */
    2673            9 :     if (defaultRaw)
    2674              :     {
    2675              :         /* Create a dummy ParseState for transformExpr */
    2676            5 :         pstate = make_parsestate(NULL);
    2677              : 
    2678              :         /*
    2679              :          * Cook the colDef->raw_expr into an expression. Note: Name is
    2680              :          * strictly for error message
    2681              :          */
    2682            5 :         defaultExpr = cookDefault(pstate, defaultRaw,
    2683              :                                   typTup->typbasetype,
    2684              :                                   typTup->typtypmod,
    2685            5 :                                   NameStr(typTup->typname),
    2686              :                                   0);
    2687              : 
    2688              :         /*
    2689              :          * If the expression is just a NULL constant, we treat the command
    2690              :          * like ALTER ... DROP DEFAULT.  (But see note for same test in
    2691              :          * DefineDomain.)
    2692              :          */
    2693            5 :         if (defaultExpr == NULL ||
    2694            5 :             (IsA(defaultExpr, Const) && ((Const *) defaultExpr)->constisnull))
    2695              :         {
    2696              :             /* Default is NULL, drop it */
    2697            0 :             defaultExpr = NULL;
    2698            0 :             new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
    2699            0 :             new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
    2700            0 :             new_record_nulls[Anum_pg_type_typdefault - 1] = true;
    2701            0 :             new_record_repl[Anum_pg_type_typdefault - 1] = true;
    2702              :         }
    2703              :         else
    2704              :         {
    2705              :             /*
    2706              :              * Expression must be stored as a nodeToString result, but we also
    2707              :              * require a valid textual representation (mainly to make life
    2708              :              * easier for pg_dump).
    2709              :              */
    2710            5 :             defaultValue = deparse_expression(defaultExpr,
    2711              :                                               NIL, false, false);
    2712              : 
    2713              :             /*
    2714              :              * Form an updated tuple with the new default and write it back.
    2715              :              */
    2716            5 :             new_record[Anum_pg_type_typdefaultbin - 1] = CStringGetTextDatum(nodeToString(defaultExpr));
    2717              : 
    2718            5 :             new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
    2719            5 :             new_record[Anum_pg_type_typdefault - 1] = CStringGetTextDatum(defaultValue);
    2720            5 :             new_record_repl[Anum_pg_type_typdefault - 1] = true;
    2721              :         }
    2722              :     }
    2723              :     else
    2724              :     {
    2725              :         /* ALTER ... DROP DEFAULT */
    2726            4 :         new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
    2727            4 :         new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
    2728            4 :         new_record_nulls[Anum_pg_type_typdefault - 1] = true;
    2729            4 :         new_record_repl[Anum_pg_type_typdefault - 1] = true;
    2730              :     }
    2731              : 
    2732            9 :     newtuple = heap_modify_tuple(tup, RelationGetDescr(rel),
    2733              :                                  new_record, new_record_nulls,
    2734              :                                  new_record_repl);
    2735              : 
    2736            9 :     CatalogTupleUpdate(rel, &tup->t_self, newtuple);
    2737              : 
    2738              :     /* Rebuild dependencies */
    2739            9 :     GenerateTypeDependencies(newtuple,
    2740              :                              rel,
    2741              :                              defaultExpr,
    2742              :                              NULL,  /* don't have typacl handy */
    2743              :                              0, /* relation kind is n/a */
    2744              :                              false, /* a domain isn't an implicit array */
    2745              :                              false, /* nor is it any kind of dependent type */
    2746              :                              false, /* don't touch extension membership */
    2747              :                              true); /* We do need to rebuild dependencies */
    2748              : 
    2749            9 :     InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
    2750              : 
    2751            9 :     ObjectAddressSet(address, TypeRelationId, domainoid);
    2752              : 
    2753              :     /* Clean up */
    2754            9 :     table_close(rel, RowExclusiveLock);
    2755            9 :     heap_freetuple(newtuple);
    2756              : 
    2757            9 :     return address;
    2758              : }
    2759              : 
    2760              : /*
    2761              :  * AlterDomainNotNull
    2762              :  *
    2763              :  * Routine implementing ALTER DOMAIN SET/DROP NOT NULL statements.
    2764              :  *
    2765              :  * Returns ObjectAddress of the modified domain.
    2766              :  */
    2767              : ObjectAddress
    2768           24 : AlterDomainNotNull(List *names, bool notNull)
    2769              : {
    2770              :     TypeName   *typename;
    2771              :     Oid         domainoid;
    2772              :     Relation    typrel;
    2773              :     HeapTuple   tup;
    2774              :     Form_pg_type typTup;
    2775           24 :     ObjectAddress address = InvalidObjectAddress;
    2776              : 
    2777              :     /* Make a TypeName so we can use standard type lookup machinery */
    2778           24 :     typename = makeTypeNameFromNameList(names);
    2779           24 :     domainoid = typenameTypeId(NULL, typename);
    2780              : 
    2781              :     /* Look up the domain in the type table */
    2782           24 :     typrel = table_open(TypeRelationId, RowExclusiveLock);
    2783              : 
    2784           24 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
    2785           24 :     if (!HeapTupleIsValid(tup))
    2786            0 :         elog(ERROR, "cache lookup failed for type %u", domainoid);
    2787           24 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    2788              : 
    2789              :     /* Check it's a domain and check user has permission for ALTER DOMAIN */
    2790           24 :     checkDomainOwner(tup);
    2791              : 
    2792              :     /* Is the domain already set to the desired constraint? */
    2793           24 :     if (typTup->typnotnull == notNull)
    2794              :     {
    2795            0 :         table_close(typrel, RowExclusiveLock);
    2796            0 :         return address;
    2797              :     }
    2798              : 
    2799           24 :     if (notNull)
    2800              :     {
    2801              :         Constraint *constr;
    2802              : 
    2803           16 :         constr = makeNode(Constraint);
    2804           16 :         constr->contype = CONSTR_NOTNULL;
    2805           16 :         constr->initially_valid = true;
    2806           16 :         constr->location = -1;
    2807              : 
    2808           16 :         domainAddNotNullConstraint(domainoid, typTup->typnamespace,
    2809              :                                    typTup->typbasetype, typTup->typtypmod,
    2810           16 :                                    constr, NameStr(typTup->typname), NULL);
    2811              : 
    2812           16 :         validateDomainNotNullConstraint(domainoid);
    2813              :     }
    2814              :     else
    2815              :     {
    2816              :         HeapTuple   conTup;
    2817              :         ObjectAddress conobj;
    2818              : 
    2819            8 :         conTup = findDomainNotNullConstraint(domainoid);
    2820            8 :         if (conTup == NULL)
    2821            0 :             elog(ERROR, "could not find not-null constraint on domain \"%s\"", NameStr(typTup->typname));
    2822              : 
    2823            8 :         ObjectAddressSet(conobj, ConstraintRelationId, ((Form_pg_constraint) GETSTRUCT(conTup))->oid);
    2824            8 :         performDeletion(&conobj, DROP_RESTRICT, 0);
    2825              :     }
    2826              : 
    2827              :     /*
    2828              :      * Okay to update pg_type row.  We can scribble on typTup because it's a
    2829              :      * copy.
    2830              :      */
    2831           16 :     typTup->typnotnull = notNull;
    2832              : 
    2833           16 :     CatalogTupleUpdate(typrel, &tup->t_self, tup);
    2834              : 
    2835           16 :     InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
    2836              : 
    2837           16 :     ObjectAddressSet(address, TypeRelationId, domainoid);
    2838              : 
    2839              :     /* Clean up */
    2840           16 :     heap_freetuple(tup);
    2841           16 :     table_close(typrel, RowExclusiveLock);
    2842              : 
    2843           16 :     return address;
    2844              : }
    2845              : 
    2846              : /*
    2847              :  * AlterDomainDropConstraint
    2848              :  *
    2849              :  * Implements the ALTER DOMAIN DROP CONSTRAINT statement
    2850              :  *
    2851              :  * Returns ObjectAddress of the modified domain.
    2852              :  */
    2853              : ObjectAddress
    2854           40 : AlterDomainDropConstraint(List *names, const char *constrName,
    2855              :                           DropBehavior behavior, bool missing_ok)
    2856              : {
    2857              :     TypeName   *typename;
    2858              :     Oid         domainoid;
    2859              :     HeapTuple   tup;
    2860              :     Relation    rel;
    2861              :     Relation    conrel;
    2862              :     SysScanDesc conscan;
    2863              :     ScanKeyData skey[3];
    2864              :     HeapTuple   contup;
    2865           40 :     bool        found = false;
    2866              :     ObjectAddress address;
    2867              : 
    2868              :     /* Make a TypeName so we can use standard type lookup machinery */
    2869           40 :     typename = makeTypeNameFromNameList(names);
    2870           40 :     domainoid = typenameTypeId(NULL, typename);
    2871              : 
    2872              :     /* Look up the domain in the type table */
    2873           40 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    2874              : 
    2875           40 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
    2876           40 :     if (!HeapTupleIsValid(tup))
    2877            0 :         elog(ERROR, "cache lookup failed for type %u", domainoid);
    2878              : 
    2879              :     /* Check it's a domain and check user has permission for ALTER DOMAIN */
    2880           40 :     checkDomainOwner(tup);
    2881              : 
    2882              :     /* Grab an appropriate lock on the pg_constraint relation */
    2883           40 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
    2884              : 
    2885              :     /* Find and remove the target constraint */
    2886           40 :     ScanKeyInit(&skey[0],
    2887              :                 Anum_pg_constraint_conrelid,
    2888              :                 BTEqualStrategyNumber, F_OIDEQ,
    2889              :                 ObjectIdGetDatum(InvalidOid));
    2890           40 :     ScanKeyInit(&skey[1],
    2891              :                 Anum_pg_constraint_contypid,
    2892              :                 BTEqualStrategyNumber, F_OIDEQ,
    2893              :                 ObjectIdGetDatum(domainoid));
    2894           40 :     ScanKeyInit(&skey[2],
    2895              :                 Anum_pg_constraint_conname,
    2896              :                 BTEqualStrategyNumber, F_NAMEEQ,
    2897              :                 CStringGetDatum(constrName));
    2898              : 
    2899           40 :     conscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
    2900              :                                  NULL, 3, skey);
    2901              : 
    2902              :     /* There can be at most one matching row */
    2903           40 :     if ((contup = systable_getnext(conscan)) != NULL)
    2904              :     {
    2905           32 :         Form_pg_constraint construct = (Form_pg_constraint) GETSTRUCT(contup);
    2906              :         ObjectAddress conobj;
    2907              : 
    2908           32 :         if (construct->contype == CONSTRAINT_NOTNULL)
    2909              :         {
    2910            8 :             ((Form_pg_type) GETSTRUCT(tup))->typnotnull = false;
    2911            8 :             CatalogTupleUpdate(rel, &tup->t_self, tup);
    2912              :         }
    2913              : 
    2914           32 :         conobj.classId = ConstraintRelationId;
    2915           32 :         conobj.objectId = construct->oid;
    2916           32 :         conobj.objectSubId = 0;
    2917              : 
    2918           32 :         performDeletion(&conobj, behavior, 0);
    2919           32 :         found = true;
    2920              :     }
    2921              : 
    2922              :     /* Clean up after the scan */
    2923           40 :     systable_endscan(conscan);
    2924           40 :     table_close(conrel, RowExclusiveLock);
    2925              : 
    2926           40 :     if (!found)
    2927              :     {
    2928            8 :         if (!missing_ok)
    2929            4 :             ereport(ERROR,
    2930              :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2931              :                      errmsg("constraint \"%s\" of domain \"%s\" does not exist",
    2932              :                             constrName, TypeNameToString(typename))));
    2933              :         else
    2934            4 :             ereport(NOTICE,
    2935              :                     (errmsg("constraint \"%s\" of domain \"%s\" does not exist, skipping",
    2936              :                             constrName, TypeNameToString(typename))));
    2937              :     }
    2938              : 
    2939              :     /*
    2940              :      * We must send out an sinval message for the domain, to ensure that any
    2941              :      * dependent plans get rebuilt.  Since this command doesn't change the
    2942              :      * domain's pg_type row, that won't happen automatically; do it manually.
    2943              :      */
    2944           36 :     CacheInvalidateHeapTuple(rel, tup, NULL);
    2945              : 
    2946           36 :     ObjectAddressSet(address, TypeRelationId, domainoid);
    2947              : 
    2948              :     /* Clean up */
    2949           36 :     table_close(rel, RowExclusiveLock);
    2950              : 
    2951           36 :     return address;
    2952              : }
    2953              : 
    2954              : /*
    2955              :  * AlterDomainAddConstraint
    2956              :  *
    2957              :  * Implements the ALTER DOMAIN .. ADD CONSTRAINT statement.
    2958              :  */
    2959              : ObjectAddress
    2960          120 : AlterDomainAddConstraint(List *names, Node *newConstraint,
    2961              :                          ObjectAddress *constrAddr)
    2962              : {
    2963              :     TypeName   *typename;
    2964              :     Oid         domainoid;
    2965              :     Relation    typrel;
    2966              :     HeapTuple   tup;
    2967              :     Form_pg_type typTup;
    2968              :     Constraint *constr;
    2969              :     char       *ccbin;
    2970          120 :     ObjectAddress address = InvalidObjectAddress;
    2971              : 
    2972              :     /* Make a TypeName so we can use standard type lookup machinery */
    2973          120 :     typename = makeTypeNameFromNameList(names);
    2974          120 :     domainoid = typenameTypeId(NULL, typename);
    2975              : 
    2976              :     /* Look up the domain in the type table */
    2977          120 :     typrel = table_open(TypeRelationId, RowExclusiveLock);
    2978              : 
    2979          120 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
    2980          120 :     if (!HeapTupleIsValid(tup))
    2981            0 :         elog(ERROR, "cache lookup failed for type %u", domainoid);
    2982          120 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    2983              : 
    2984              :     /* Check it's a domain and check user has permission for ALTER DOMAIN */
    2985          120 :     checkDomainOwner(tup);
    2986              : 
    2987          120 :     if (!IsA(newConstraint, Constraint))
    2988            0 :         elog(ERROR, "unrecognized node type: %d",
    2989              :              (int) nodeTag(newConstraint));
    2990              : 
    2991          120 :     constr = (Constraint *) newConstraint;
    2992              : 
    2993              :     /* enforced by parser */
    2994              :     Assert(constr->contype == CONSTR_CHECK || constr->contype == CONSTR_NOTNULL);
    2995              : 
    2996          120 :     if (constr->contype == CONSTR_CHECK)
    2997              :     {
    2998              :         /*
    2999              :          * First, process the constraint expression and add an entry to
    3000              :          * pg_constraint.
    3001              :          */
    3002              : 
    3003          100 :         ccbin = domainAddCheckConstraint(domainoid, typTup->typnamespace,
    3004              :                                          typTup->typbasetype, typTup->typtypmod,
    3005          100 :                                          constr, NameStr(typTup->typname), constrAddr);
    3006              : 
    3007              : 
    3008              :         /*
    3009              :          * If requested to validate the constraint, test all values stored in
    3010              :          * the attributes based on the domain the constraint is being added
    3011              :          * to.
    3012              :          */
    3013           96 :         if (!constr->skip_validation)
    3014           87 :             validateDomainCheckConstraint(domainoid, ccbin, ShareLock);
    3015              : 
    3016              :         /*
    3017              :          * We must send out an sinval message for the domain, to ensure that
    3018              :          * any dependent plans get rebuilt.  Since this command doesn't change
    3019              :          * the domain's pg_type row, that won't happen automatically; do it
    3020              :          * manually.
    3021              :          */
    3022           56 :         CacheInvalidateHeapTuple(typrel, tup, NULL);
    3023              :     }
    3024           20 :     else if (constr->contype == CONSTR_NOTNULL)
    3025              :     {
    3026              :         /* Is the domain already set NOT NULL? */
    3027           20 :         if (typTup->typnotnull)
    3028              :         {
    3029            4 :             table_close(typrel, RowExclusiveLock);
    3030            4 :             return address;
    3031              :         }
    3032           16 :         domainAddNotNullConstraint(domainoid, typTup->typnamespace,
    3033              :                                    typTup->typbasetype, typTup->typtypmod,
    3034           16 :                                    constr, NameStr(typTup->typname), constrAddr);
    3035              : 
    3036           16 :         if (!constr->skip_validation)
    3037           16 :             validateDomainNotNullConstraint(domainoid);
    3038              : 
    3039            8 :         typTup->typnotnull = true;
    3040            8 :         CatalogTupleUpdate(typrel, &tup->t_self, tup);
    3041              :     }
    3042              : 
    3043           64 :     ObjectAddressSet(address, TypeRelationId, domainoid);
    3044              : 
    3045              :     /* Clean up */
    3046           64 :     table_close(typrel, RowExclusiveLock);
    3047              : 
    3048           64 :     return address;
    3049              : }
    3050              : 
    3051              : /*
    3052              :  * AlterDomainValidateConstraint
    3053              :  *
    3054              :  * Implements the ALTER DOMAIN .. VALIDATE CONSTRAINT statement.
    3055              :  *
    3056              :  * Return value is the address of the validated constraint.  If the constraint
    3057              :  * was already validated, InvalidObjectAddress is returned.
    3058              :  */
    3059              : ObjectAddress
    3060            8 : AlterDomainValidateConstraint(List *names, const char *constrName)
    3061              : {
    3062              :     TypeName   *typename;
    3063              :     Oid         domainoid;
    3064              :     Relation    typrel;
    3065              :     Relation    conrel;
    3066              :     HeapTuple   tup;
    3067              :     Form_pg_constraint con;
    3068              :     Form_pg_constraint copy_con;
    3069              :     char       *conbin;
    3070              :     SysScanDesc scan;
    3071              :     Datum       val;
    3072              :     HeapTuple   tuple;
    3073              :     HeapTuple   copyTuple;
    3074              :     ScanKeyData skey[3];
    3075            8 :     ObjectAddress address = InvalidObjectAddress;
    3076              : 
    3077              :     /* Make a TypeName so we can use standard type lookup machinery */
    3078            8 :     typename = makeTypeNameFromNameList(names);
    3079            8 :     domainoid = typenameTypeId(NULL, typename);
    3080              : 
    3081              :     /* Look up the domain in the type table */
    3082            8 :     typrel = table_open(TypeRelationId, AccessShareLock);
    3083              : 
    3084            8 :     tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(domainoid));
    3085            8 :     if (!HeapTupleIsValid(tup))
    3086            0 :         elog(ERROR, "cache lookup failed for type %u", domainoid);
    3087              : 
    3088              :     /* Check it's a domain and check user has permission for ALTER DOMAIN */
    3089            8 :     checkDomainOwner(tup);
    3090              : 
    3091              :     /*
    3092              :      * Find and check the target constraint
    3093              :      */
    3094            8 :     conrel = table_open(ConstraintRelationId, RowExclusiveLock);
    3095              : 
    3096            8 :     ScanKeyInit(&skey[0],
    3097              :                 Anum_pg_constraint_conrelid,
    3098              :                 BTEqualStrategyNumber, F_OIDEQ,
    3099              :                 ObjectIdGetDatum(InvalidOid));
    3100            8 :     ScanKeyInit(&skey[1],
    3101              :                 Anum_pg_constraint_contypid,
    3102              :                 BTEqualStrategyNumber, F_OIDEQ,
    3103              :                 ObjectIdGetDatum(domainoid));
    3104            8 :     ScanKeyInit(&skey[2],
    3105              :                 Anum_pg_constraint_conname,
    3106              :                 BTEqualStrategyNumber, F_NAMEEQ,
    3107              :                 CStringGetDatum(constrName));
    3108              : 
    3109            8 :     scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
    3110              :                               NULL, 3, skey);
    3111              : 
    3112              :     /* There can be at most one matching row */
    3113            8 :     if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
    3114            0 :         ereport(ERROR,
    3115              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3116              :                  errmsg("constraint \"%s\" of domain \"%s\" does not exist",
    3117              :                         constrName, TypeNameToString(typename))));
    3118              : 
    3119            8 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
    3120            8 :     if (con->contype != CONSTRAINT_CHECK)
    3121            0 :         ereport(ERROR,
    3122              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3123              :                  errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
    3124              :                         constrName, TypeNameToString(typename))));
    3125              : 
    3126            8 :     if (!con->convalidated)
    3127              :     {
    3128            8 :         val = SysCacheGetAttrNotNull(CONSTROID, tuple, Anum_pg_constraint_conbin);
    3129            8 :         conbin = TextDatumGetCString(val);
    3130              : 
    3131              :         /*
    3132              :          * Locking related relations with ShareUpdateExclusiveLock is ok
    3133              :          * because not-yet-valid constraints are still enforced against
    3134              :          * concurrent inserts or updates.
    3135              :          */
    3136            8 :         validateDomainCheckConstraint(domainoid, conbin, ShareUpdateExclusiveLock);
    3137              : 
    3138              :         /*
    3139              :          * Now update the catalog, while we have the door open.
    3140              :          */
    3141            4 :         copyTuple = heap_copytuple(tuple);
    3142            4 :         copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
    3143            4 :         copy_con->convalidated = true;
    3144            4 :         CatalogTupleUpdate(conrel, &copyTuple->t_self, copyTuple);
    3145              : 
    3146            4 :         InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
    3147              : 
    3148            4 :         ObjectAddressSet(address, TypeRelationId, domainoid);
    3149              : 
    3150            4 :         heap_freetuple(copyTuple);
    3151              :     }
    3152              : 
    3153            4 :     systable_endscan(scan);
    3154              : 
    3155            4 :     table_close(typrel, AccessShareLock);
    3156            4 :     table_close(conrel, RowExclusiveLock);
    3157              : 
    3158            4 :     ReleaseSysCache(tup);
    3159              : 
    3160            4 :     return address;
    3161              : }
    3162              : 
    3163              : /*
    3164              :  * Verify that all columns currently using the domain are not null.
    3165              :  */
    3166              : static void
    3167           32 : validateDomainNotNullConstraint(Oid domainoid)
    3168              : {
    3169              :     List       *rels;
    3170              :     ListCell   *rt;
    3171              : 
    3172              :     /* Fetch relation list with attributes based on this domain */
    3173              :     /* ShareLock is sufficient to prevent concurrent data changes */
    3174              : 
    3175           32 :     rels = get_rels_with_domain(domainoid, ShareLock);
    3176              : 
    3177           44 :     foreach(rt, rels)
    3178              :     {
    3179           28 :         RelToCheck *rtc = (RelToCheck *) lfirst(rt);
    3180           28 :         Relation    testrel = rtc->rel;
    3181           28 :         TupleDesc   tupdesc = RelationGetDescr(testrel);
    3182              :         TupleTableSlot *slot;
    3183              :         TableScanDesc scan;
    3184              :         Snapshot    snapshot;
    3185              : 
    3186              :         /* Scan all tuples in this relation */
    3187           28 :         snapshot = RegisterSnapshot(GetLatestSnapshot());
    3188           28 :         scan = table_beginscan(testrel, snapshot, 0, NULL,
    3189              :                                SO_NONE);
    3190           28 :         slot = table_slot_create(testrel, NULL);
    3191           40 :         while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
    3192              :         {
    3193              :             int         i;
    3194              : 
    3195              :             /* Test attributes that are of the domain */
    3196           60 :             for (i = 0; i < rtc->natts; i++)
    3197              :             {
    3198           48 :                 int         attnum = rtc->atts[i];
    3199           48 :                 Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
    3200              : 
    3201           48 :                 if (slot_attisnull(slot, attnum))
    3202              :                 {
    3203              :                     /*
    3204              :                      * In principle the auxiliary information for this error
    3205              :                      * should be errdatatype(), but errtablecol() seems
    3206              :                      * considerably more useful in practice.  Since this code
    3207              :                      * only executes in an ALTER DOMAIN command, the client
    3208              :                      * should already know which domain is in question.
    3209              :                      */
    3210           16 :                     ereport(ERROR,
    3211              :                             (errcode(ERRCODE_NOT_NULL_VIOLATION),
    3212              :                              errmsg("column \"%s\" of table \"%s\" contains null values",
    3213              :                                     NameStr(attr->attname),
    3214              :                                     RelationGetRelationName(testrel)),
    3215              :                              errtablecol(testrel, attnum)));
    3216              :                 }
    3217              :             }
    3218              :         }
    3219           12 :         ExecDropSingleTupleTableSlot(slot);
    3220           12 :         table_endscan(scan);
    3221           12 :         UnregisterSnapshot(snapshot);
    3222              : 
    3223              :         /* Close each rel after processing, but keep lock */
    3224           12 :         table_close(testrel, NoLock);
    3225              :     }
    3226           16 : }
    3227              : 
    3228              : /*
    3229              :  * Verify that all columns currently using the domain satisfy the given check
    3230              :  * constraint expression.
    3231              :  *
    3232              :  * It is used to validate existing constraints and to add newly created check
    3233              :  * constraints to a domain.
    3234              :  *
    3235              :  * The lockmode is used for relations using the domain.  It should be
    3236              :  * ShareLock when adding a new constraint to domain.  It can be
    3237              :  * ShareUpdateExclusiveLock when validating an existing constraint.
    3238              :  */
    3239              : static void
    3240           95 : validateDomainCheckConstraint(Oid domainoid, const char *ccbin, LOCKMODE lockmode)
    3241              : {
    3242           95 :     Expr       *expr = (Expr *) stringToNode(ccbin);
    3243              :     List       *rels;
    3244              :     ListCell   *rt;
    3245              :     EState     *estate;
    3246              :     ExprContext *econtext;
    3247              :     ExprState  *exprstate;
    3248              : 
    3249              :     /* Need an EState to run ExecEvalExpr */
    3250           95 :     estate = CreateExecutorState();
    3251           95 :     econtext = GetPerTupleExprContext(estate);
    3252              : 
    3253              :     /* build execution state for expr */
    3254           95 :     exprstate = ExecPrepareExpr(expr, estate);
    3255              : 
    3256              :     /* Fetch relation list with attributes based on this domain */
    3257           95 :     rels = get_rels_with_domain(domainoid, lockmode);
    3258              : 
    3259           99 :     foreach(rt, rels)
    3260              :     {
    3261           48 :         RelToCheck *rtc = (RelToCheck *) lfirst(rt);
    3262           48 :         Relation    testrel = rtc->rel;
    3263           48 :         TupleDesc   tupdesc = RelationGetDescr(testrel);
    3264              :         TupleTableSlot *slot;
    3265              :         TableScanDesc scan;
    3266              :         Snapshot    snapshot;
    3267              : 
    3268              :         /* Scan all tuples in this relation */
    3269           48 :         snapshot = RegisterSnapshot(GetLatestSnapshot());
    3270           48 :         scan = table_beginscan(testrel, snapshot, 0, NULL,
    3271              :                                SO_NONE);
    3272           48 :         slot = table_slot_create(testrel, NULL);
    3273          112 :         while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
    3274              :         {
    3275              :             int         i;
    3276              : 
    3277              :             /* Test attributes that are of the domain */
    3278          152 :             for (i = 0; i < rtc->natts; i++)
    3279              :             {
    3280           88 :                 int         attnum = rtc->atts[i];
    3281              :                 Datum       d;
    3282              :                 bool        isNull;
    3283              :                 Datum       conResult;
    3284              : 
    3285           88 :                 d = slot_getattr(slot, attnum, &isNull);
    3286              : 
    3287           88 :                 econtext->domainValue_datum = d;
    3288           88 :                 econtext->domainValue_isNull = isNull;
    3289              : 
    3290           88 :                 conResult = ExecEvalExprSwitchContext(exprstate,
    3291              :                                                       econtext,
    3292              :                                                       &isNull);
    3293              : 
    3294           88 :                 if (!isNull && !DatumGetBool(conResult))
    3295              :                 {
    3296           24 :                     Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
    3297              : 
    3298              :                     /*
    3299              :                      * In principle the auxiliary information for this error
    3300              :                      * should be errdomainconstraint(), but errtablecol()
    3301              :                      * seems considerably more useful in practice.  Since this
    3302              :                      * code only executes in an ALTER DOMAIN command, the
    3303              :                      * client should already know which domain is in question,
    3304              :                      * and which constraint too.
    3305              :                      */
    3306           24 :                     ereport(ERROR,
    3307              :                             (errcode(ERRCODE_CHECK_VIOLATION),
    3308              :                              errmsg("column \"%s\" of table \"%s\" contains values that violate the new constraint",
    3309              :                                     NameStr(attr->attname),
    3310              :                                     RelationGetRelationName(testrel)),
    3311              :                              errtablecol(testrel, attnum)));
    3312              :                 }
    3313              :             }
    3314              : 
    3315           64 :             ResetExprContext(econtext);
    3316              :         }
    3317           24 :         ExecDropSingleTupleTableSlot(slot);
    3318           24 :         table_endscan(scan);
    3319           24 :         UnregisterSnapshot(snapshot);
    3320              : 
    3321              :         /* Hold relation lock till commit (XXX bad for concurrency) */
    3322           24 :         table_close(testrel, NoLock);
    3323              :     }
    3324              : 
    3325           51 :     FreeExecutorState(estate);
    3326           51 : }
    3327              : 
    3328              : /*
    3329              :  * get_rels_with_domain
    3330              :  *
    3331              :  * Fetch all relations / attributes which are using the domain
    3332              :  *
    3333              :  * The result is a list of RelToCheck structs, one for each distinct
    3334              :  * relation, each containing one or more attribute numbers that are of
    3335              :  * the domain type.  We have opened each rel and acquired the specified lock
    3336              :  * type on it.
    3337              :  *
    3338              :  * We support nested domains by including attributes that are of derived
    3339              :  * domain types.  Current callers do not need to distinguish between attributes
    3340              :  * that are of exactly the given domain and those that are of derived domains.
    3341              :  *
    3342              :  * XXX this is completely broken because there is no way to lock the domain
    3343              :  * to prevent columns from being added or dropped while our command runs.
    3344              :  * We can partially protect against column drops by locking relations as we
    3345              :  * come across them, but there is still a race condition (the window between
    3346              :  * seeing a pg_depend entry and acquiring lock on the relation it references).
    3347              :  * Also, holding locks on all these relations simultaneously creates a non-
    3348              :  * trivial risk of deadlock.  We can minimize but not eliminate the deadlock
    3349              :  * risk by using the weakest suitable lock (ShareLock for most callers).
    3350              :  *
    3351              :  * XXX the API for this is not sufficient to support checking domain values
    3352              :  * that are inside container types, such as composite types, arrays, or
    3353              :  * ranges.  Currently we just error out if a container type containing the
    3354              :  * target domain is stored anywhere.
    3355              :  *
    3356              :  * Generally used for retrieving a list of tests when adding
    3357              :  * new constraints to a domain.
    3358              :  */
    3359              : static List *
    3360          135 : get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
    3361              : {
    3362          135 :     List       *result = NIL;
    3363          135 :     char       *domainTypeName = format_type_be(domainOid);
    3364              :     Relation    depRel;
    3365              :     ScanKeyData key[2];
    3366              :     SysScanDesc depScan;
    3367              :     HeapTuple   depTup;
    3368              : 
    3369              :     Assert(lockmode != NoLock);
    3370              : 
    3371              :     /* since this function recurses, it could be driven to stack overflow */
    3372          135 :     check_stack_depth();
    3373              : 
    3374              :     /*
    3375              :      * We scan pg_depend to find those things that depend on the domain. (We
    3376              :      * assume we can ignore refobjsubid for a domain.)
    3377              :      */
    3378          135 :     depRel = table_open(DependRelationId, AccessShareLock);
    3379              : 
    3380          135 :     ScanKeyInit(&key[0],
    3381              :                 Anum_pg_depend_refclassid,
    3382              :                 BTEqualStrategyNumber, F_OIDEQ,
    3383              :                 ObjectIdGetDatum(TypeRelationId));
    3384          135 :     ScanKeyInit(&key[1],
    3385              :                 Anum_pg_depend_refobjid,
    3386              :                 BTEqualStrategyNumber, F_OIDEQ,
    3387              :                 ObjectIdGetDatum(domainOid));
    3388              : 
    3389          135 :     depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
    3390              :                                  NULL, 2, key);
    3391              : 
    3392          467 :     while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
    3393              :     {
    3394          352 :         Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
    3395          352 :         RelToCheck *rtc = NULL;
    3396              :         ListCell   *rellist;
    3397              :         Form_pg_attribute pg_att;
    3398              :         int         ptr;
    3399              : 
    3400              :         /* Check for directly dependent types */
    3401          352 :         if (pg_depend->classid == TypeRelationId)
    3402              :         {
    3403          147 :             if (get_typtype(pg_depend->objid) == TYPTYPE_DOMAIN)
    3404              :             {
    3405              :                 /*
    3406              :                  * This is a sub-domain, so recursively add dependent columns
    3407              :                  * to the output list.  This is a bit inefficient since we may
    3408              :                  * fail to combine RelToCheck entries when attributes of the
    3409              :                  * same rel have different derived domain types, but it's
    3410              :                  * probably not worth improving.
    3411              :                  */
    3412            8 :                 result = list_concat(result,
    3413            8 :                                      get_rels_with_domain(pg_depend->objid,
    3414              :                                                           lockmode));
    3415              :             }
    3416              :             else
    3417              :             {
    3418              :                 /*
    3419              :                  * Otherwise, it is some container type using the domain, so
    3420              :                  * fail if there are any columns of this type.
    3421              :                  */
    3422          139 :                 find_composite_type_dependencies(pg_depend->objid,
    3423              :                                                  NULL,
    3424              :                                                  domainTypeName);
    3425              :             }
    3426          143 :             continue;
    3427              :         }
    3428              : 
    3429              :         /* Else, ignore dependees that aren't user columns of relations */
    3430              :         /* (we assume system columns are never of domain types) */
    3431          205 :         if (pg_depend->classid != RelationRelationId ||
    3432          144 :             pg_depend->objsubid <= 0)
    3433           61 :             continue;
    3434              : 
    3435              :         /* See if we already have an entry for this relation */
    3436          144 :         foreach(rellist, result)
    3437              :         {
    3438           28 :             RelToCheck *rt = (RelToCheck *) lfirst(rellist);
    3439              : 
    3440           28 :             if (RelationGetRelid(rt->rel) == pg_depend->objid)
    3441              :             {
    3442           28 :                 rtc = rt;
    3443           28 :                 break;
    3444              :             }
    3445              :         }
    3446              : 
    3447          144 :         if (rtc == NULL)
    3448              :         {
    3449              :             /* First attribute found for this relation */
    3450              :             Relation    rel;
    3451              : 
    3452              :             /* Acquire requested lock on relation */
    3453          116 :             rel = relation_open(pg_depend->objid, lockmode);
    3454              : 
    3455              :             /*
    3456              :              * Check to see if rowtype is stored anyplace as a composite-type
    3457              :              * column; if so we have to fail, for now anyway.
    3458              :              */
    3459          116 :             if (OidIsValid(rel->rd_rel->reltype))
    3460          116 :                 find_composite_type_dependencies(rel->rd_rel->reltype,
    3461              :                                                  NULL,
    3462              :                                                  domainTypeName);
    3463              : 
    3464              :             /*
    3465              :              * Otherwise, we can ignore relations except those with both
    3466              :              * storage and user-chosen column types.
    3467              :              *
    3468              :              * XXX If an index-only scan could satisfy "col::some_domain" from
    3469              :              * a suitable expression index, this should also check expression
    3470              :              * index columns.
    3471              :              */
    3472          100 :             if (rel->rd_rel->relkind != RELKIND_RELATION &&
    3473           24 :                 rel->rd_rel->relkind != RELKIND_MATVIEW)
    3474              :             {
    3475           24 :                 relation_close(rel, lockmode);
    3476           24 :                 continue;
    3477              :             }
    3478              : 
    3479              :             /* Build the RelToCheck entry with enough space for all atts */
    3480           76 :             rtc = palloc_object(RelToCheck);
    3481           76 :             rtc->rel = rel;
    3482           76 :             rtc->natts = 0;
    3483           76 :             rtc->atts = palloc_array(int, RelationGetNumberOfAttributes(rel));
    3484           76 :             result = lappend(result, rtc);
    3485              :         }
    3486              : 
    3487              :         /*
    3488              :          * Confirm column has not been dropped, and is of the expected type.
    3489              :          * This defends against an ALTER DROP COLUMN occurring just before we
    3490              :          * acquired lock ... but if the whole table were dropped, we'd still
    3491              :          * have a problem.
    3492              :          */
    3493          104 :         if (pg_depend->objsubid > RelationGetNumberOfAttributes(rtc->rel))
    3494            0 :             continue;
    3495          104 :         pg_att = TupleDescAttr(rtc->rel->rd_att, pg_depend->objsubid - 1);
    3496          104 :         if (pg_att->attisdropped || pg_att->atttypid != domainOid)
    3497            0 :             continue;
    3498              : 
    3499              :         /*
    3500              :          * Okay, add column to result.  We store the columns in column-number
    3501              :          * order; this is just a hack to improve predictability of regression
    3502              :          * test output ...
    3503              :          */
    3504              :         Assert(rtc->natts < RelationGetNumberOfAttributes(rtc->rel));
    3505              : 
    3506          104 :         ptr = rtc->natts++;
    3507          104 :         while (ptr > 0 && rtc->atts[ptr - 1] > pg_depend->objsubid)
    3508              :         {
    3509            0 :             rtc->atts[ptr] = rtc->atts[ptr - 1];
    3510            0 :             ptr--;
    3511              :         }
    3512          104 :         rtc->atts[ptr] = pg_depend->objsubid;
    3513              :     }
    3514              : 
    3515          115 :     systable_endscan(depScan);
    3516              : 
    3517          115 :     relation_close(depRel, AccessShareLock);
    3518              : 
    3519          115 :     return result;
    3520              : }
    3521              : 
    3522              : /*
    3523              :  * checkDomainOwner
    3524              :  *
    3525              :  * Check that the type is actually a domain and that the current user
    3526              :  * has permission to do ALTER DOMAIN on it.  Throw an error if not.
    3527              :  */
    3528              : void
    3529          205 : checkDomainOwner(HeapTuple tup)
    3530              : {
    3531          205 :     Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
    3532              : 
    3533              :     /* Check that this is actually a domain */
    3534          205 :     if (typTup->typtype != TYPTYPE_DOMAIN)
    3535            0 :         ereport(ERROR,
    3536              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3537              :                  errmsg("%s is not a domain",
    3538              :                         format_type_be(typTup->oid))));
    3539              : 
    3540              :     /* Permission check: must own type */
    3541          205 :     if (!object_ownercheck(TypeRelationId, typTup->oid, GetUserId()))
    3542            0 :         aclcheck_error_type(ACLCHECK_NOT_OWNER, typTup->oid);
    3543          205 : }
    3544              : 
    3545              : /*
    3546              :  * domainAddCheckConstraint - code shared between CREATE and ALTER DOMAIN
    3547              :  */
    3548              : static char *
    3549          471 : domainAddCheckConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
    3550              :                          int typMod, Constraint *constr,
    3551              :                          const char *domainName, ObjectAddress *constrAddr)
    3552              : {
    3553              :     Node       *expr;
    3554              :     char       *ccbin;
    3555              :     ParseState *pstate;
    3556              :     CoerceToDomainValue *domVal;
    3557              :     Oid         ccoid;
    3558              : 
    3559              :     Assert(constr->contype == CONSTR_CHECK);
    3560              : 
    3561              :     /*
    3562              :      * Assign or validate constraint name
    3563              :      */
    3564          471 :     if (constr->conname)
    3565              :     {
    3566          227 :         if (ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
    3567              :                                  domainOid,
    3568          227 :                                  constr->conname))
    3569            0 :             ereport(ERROR,
    3570              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    3571              :                      errmsg("constraint \"%s\" for domain \"%s\" already exists",
    3572              :                             constr->conname, domainName)));
    3573              :     }
    3574              :     else
    3575          244 :         constr->conname = ChooseConstraintName(domainName,
    3576              :                                                NULL,
    3577              :                                                "check",
    3578              :                                                domainNamespace,
    3579              :                                                NIL);
    3580              : 
    3581              :     /*
    3582              :      * Convert the A_EXPR in raw_expr into an EXPR
    3583              :      */
    3584          471 :     pstate = make_parsestate(NULL);
    3585              : 
    3586              :     /*
    3587              :      * Set up a CoerceToDomainValue to represent the occurrence of VALUE in
    3588              :      * the expression.  Note that it will appear to have the type of the base
    3589              :      * type, not the domain.  This seems correct since within the check
    3590              :      * expression, we should not assume the input value can be considered a
    3591              :      * member of the domain.
    3592              :      */
    3593          471 :     domVal = makeNode(CoerceToDomainValue);
    3594          471 :     domVal->typeId = baseTypeOid;
    3595          471 :     domVal->typeMod = typMod;
    3596          471 :     domVal->collation = get_typcollation(baseTypeOid);
    3597          471 :     domVal->location = -1;       /* will be set when/if used */
    3598              : 
    3599          471 :     pstate->p_pre_columnref_hook = replace_domain_constraint_value;
    3600          471 :     pstate->p_ref_hook_state = domVal;
    3601              : 
    3602          471 :     expr = transformExpr(pstate, constr->raw_expr, EXPR_KIND_DOMAIN_CHECK);
    3603              : 
    3604              :     /*
    3605              :      * Make sure it yields a boolean result.
    3606              :      */
    3607          467 :     expr = coerce_to_boolean(pstate, expr, "CHECK");
    3608              : 
    3609              :     /*
    3610              :      * Fix up collation information.
    3611              :      */
    3612          467 :     assign_expr_collations(pstate, expr);
    3613              : 
    3614              :     /*
    3615              :      * Domains don't allow variables (this is probably dead code now that
    3616              :      * add_missing_from is history, but let's be sure).
    3617              :      */
    3618          934 :     if (pstate->p_rtable != NIL ||
    3619          467 :         contain_var_clause(expr))
    3620            0 :         ereport(ERROR,
    3621              :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3622              :                  errmsg("cannot use table references in domain check constraint")));
    3623              : 
    3624              :     /*
    3625              :      * Convert to string form for storage.
    3626              :      */
    3627          467 :     ccbin = nodeToString(expr);
    3628              : 
    3629              :     /*
    3630              :      * Store the constraint in pg_constraint
    3631              :      */
    3632              :     ccoid =
    3633          467 :         CreateConstraintEntry(constr->conname,   /* Constraint Name */
    3634              :                               domainNamespace,  /* namespace */
    3635              :                               CONSTRAINT_CHECK, /* Constraint Type */
    3636              :                               false,    /* Is Deferrable */
    3637              :                               false,    /* Is Deferred */
    3638              :                               true, /* Is Enforced */
    3639          467 :                               !constr->skip_validation, /* Is Validated */
    3640              :                               InvalidOid,   /* no parent constraint */
    3641              :                               InvalidOid,   /* not a relation constraint */
    3642              :                               NULL,
    3643              :                               0,
    3644              :                               0,
    3645              :                               domainOid,    /* domain constraint */
    3646              :                               InvalidOid,   /* no associated index */
    3647              :                               InvalidOid,   /* Foreign key fields */
    3648              :                               NULL,
    3649              :                               NULL,
    3650              :                               NULL,
    3651              :                               NULL,
    3652              :                               0,
    3653              :                               ' ',
    3654              :                               ' ',
    3655              :                               NULL,
    3656              :                               0,
    3657              :                               ' ',
    3658              :                               NULL, /* not an exclusion constraint */
    3659              :                               expr, /* Tree form of check constraint */
    3660              :                               ccbin,    /* Binary form of check constraint */
    3661              :                               true, /* is local */
    3662              :                               0,    /* inhcount */
    3663              :                               false,    /* connoinherit */
    3664              :                               false,    /* conperiod */
    3665          467 :                               false);   /* is_internal */
    3666          467 :     if (constrAddr)
    3667           91 :         ObjectAddressSet(*constrAddr, ConstraintRelationId, ccoid);
    3668              : 
    3669              :     /*
    3670              :      * Return the compiled constraint expression so the calling routine can
    3671              :      * perform any additional required tests.
    3672              :      */
    3673          467 :     return ccbin;
    3674              : }
    3675              : 
    3676              : /* Parser pre_columnref_hook for domain CHECK constraint parsing */
    3677              : static Node *
    3678          535 : replace_domain_constraint_value(ParseState *pstate, ColumnRef *cref)
    3679              : {
    3680              :     /*
    3681              :      * Check for a reference to "value", and if that's what it is, replace
    3682              :      * with a CoerceToDomainValue as prepared for us by
    3683              :      * domainAddCheckConstraint. (We handle VALUE as a name, not a keyword, to
    3684              :      * avoid breaking a lot of applications that have used VALUE as a column
    3685              :      * name in the past.)
    3686              :      */
    3687          535 :     if (list_length(cref->fields) == 1)
    3688              :     {
    3689          535 :         Node       *field1 = (Node *) linitial(cref->fields);
    3690              :         char       *colname;
    3691              : 
    3692          535 :         colname = strVal(field1);
    3693          535 :         if (strcmp(colname, "value") == 0)
    3694              :         {
    3695          535 :             CoerceToDomainValue *domVal = copyObject(pstate->p_ref_hook_state);
    3696              : 
    3697              :             /* Propagate location knowledge, if any */
    3698          535 :             domVal->location = cref->location;
    3699          535 :             return (Node *) domVal;
    3700              :         }
    3701              :     }
    3702            0 :     return NULL;
    3703              : }
    3704              : 
    3705              : /*
    3706              :  * domainAddNotNullConstraint - code shared between CREATE and ALTER DOMAIN
    3707              :  */
    3708              : static void
    3709           92 : domainAddNotNullConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
    3710              :                            int typMod, Constraint *constr,
    3711              :                            const char *domainName, ObjectAddress *constrAddr)
    3712              : {
    3713              :     Oid         ccoid;
    3714              : 
    3715              :     Assert(constr->contype == CONSTR_NOTNULL);
    3716              : 
    3717              :     /*
    3718              :      * Assign or validate constraint name
    3719              :      */
    3720           92 :     if (constr->conname)
    3721              :     {
    3722            9 :         if (ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
    3723              :                                  domainOid,
    3724            9 :                                  constr->conname))
    3725            0 :             ereport(ERROR,
    3726              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    3727              :                      errmsg("constraint \"%s\" for domain \"%s\" already exists",
    3728              :                             constr->conname, domainName)));
    3729              :     }
    3730              :     else
    3731           83 :         constr->conname = ChooseConstraintName(domainName,
    3732              :                                                NULL,
    3733              :                                                "not_null",
    3734              :                                                domainNamespace,
    3735              :                                                NIL);
    3736              : 
    3737              :     /*
    3738              :      * Store the constraint in pg_constraint
    3739              :      */
    3740              :     ccoid =
    3741           92 :         CreateConstraintEntry(constr->conname,   /* Constraint Name */
    3742              :                               domainNamespace,  /* namespace */
    3743              :                               CONSTRAINT_NOTNULL,   /* Constraint Type */
    3744              :                               false,    /* Is Deferrable */
    3745              :                               false,    /* Is Deferred */
    3746              :                               true, /* Is Enforced */
    3747           92 :                               !constr->skip_validation, /* Is Validated */
    3748              :                               InvalidOid,   /* no parent constraint */
    3749              :                               InvalidOid,   /* not a relation constraint */
    3750              :                               NULL,
    3751              :                               0,
    3752              :                               0,
    3753              :                               domainOid,    /* domain constraint */
    3754              :                               InvalidOid,   /* no associated index */
    3755              :                               InvalidOid,   /* Foreign key fields */
    3756              :                               NULL,
    3757              :                               NULL,
    3758              :                               NULL,
    3759              :                               NULL,
    3760              :                               0,
    3761              :                               ' ',
    3762              :                               ' ',
    3763              :                               NULL,
    3764              :                               0,
    3765              :                               ' ',
    3766              :                               NULL, /* not an exclusion constraint */
    3767              :                               NULL,
    3768              :                               NULL,
    3769              :                               true, /* is local */
    3770              :                               0,    /* inhcount */
    3771              :                               false,    /* connoinherit */
    3772              :                               false,    /* conperiod */
    3773           92 :                               false);   /* is_internal */
    3774              : 
    3775           92 :     if (constrAddr)
    3776           16 :         ObjectAddressSet(*constrAddr, ConstraintRelationId, ccoid);
    3777           92 : }
    3778              : 
    3779              : 
    3780              : /*
    3781              :  * Execute ALTER TYPE RENAME
    3782              :  */
    3783              : ObjectAddress
    3784           21 : RenameType(RenameStmt *stmt)
    3785              : {
    3786           21 :     List       *names = castNode(List, stmt->object);
    3787           21 :     const char *newTypeName = stmt->newname;
    3788              :     TypeName   *typename;
    3789              :     Oid         typeOid;
    3790              :     Relation    rel;
    3791              :     HeapTuple   tup;
    3792              :     Form_pg_type typTup;
    3793              :     ObjectAddress address;
    3794              : 
    3795              :     /* Make a TypeName so we can use standard type lookup machinery */
    3796           21 :     typename = makeTypeNameFromNameList(names);
    3797           21 :     typeOid = typenameTypeId(NULL, typename);
    3798              : 
    3799              :     /* Look up the type in the type table */
    3800           21 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    3801              : 
    3802           21 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
    3803           21 :     if (!HeapTupleIsValid(tup))
    3804            0 :         elog(ERROR, "cache lookup failed for type %u", typeOid);
    3805           21 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    3806              : 
    3807              :     /* check permissions on type */
    3808           21 :     if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
    3809            0 :         aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
    3810              : 
    3811              :     /* ALTER DOMAIN used on a non-domain? */
    3812           21 :     if (stmt->renameType == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
    3813            0 :         ereport(ERROR,
    3814              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3815              :                  errmsg("%s is not a domain",
    3816              :                         format_type_be(typeOid))));
    3817              : 
    3818              :     /*
    3819              :      * If it's a composite type, we need to check that it really is a
    3820              :      * free-standing composite type, and not a table's rowtype. We want people
    3821              :      * to use ALTER TABLE not ALTER TYPE for that case.
    3822              :      */
    3823           22 :     if (typTup->typtype == TYPTYPE_COMPOSITE &&
    3824            1 :         get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
    3825            0 :         ereport(ERROR,
    3826              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3827              :                  errmsg("%s is a table's row type",
    3828              :                         format_type_be(typeOid)),
    3829              :         /* translator: %s is an SQL ALTER command */
    3830              :                  errhint("Use %s instead.",
    3831              :                          "ALTER TABLE")));
    3832              : 
    3833              :     /* don't allow direct alteration of array types, either */
    3834           21 :     if (IsTrueArrayType(typTup))
    3835            0 :         ereport(ERROR,
    3836              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3837              :                  errmsg("cannot alter array type %s",
    3838              :                         format_type_be(typeOid)),
    3839              :                  errhint("You can alter type %s, which will alter the array type as well.",
    3840              :                          format_type_be(typTup->typelem))));
    3841              : 
    3842              :     /* we do allow separate renaming of multirange types, though */
    3843              : 
    3844              :     /*
    3845              :      * If type is composite we need to rename associated pg_class entry too.
    3846              :      * RenameRelationInternal will call RenameTypeInternal automatically.
    3847              :      */
    3848           21 :     if (typTup->typtype == TYPTYPE_COMPOSITE)
    3849            1 :         RenameRelationInternal(typTup->typrelid, newTypeName, false, false);
    3850              :     else
    3851           20 :         RenameTypeInternal(typeOid, newTypeName,
    3852              :                            typTup->typnamespace);
    3853              : 
    3854           21 :     ObjectAddressSet(address, TypeRelationId, typeOid);
    3855              :     /* Clean up */
    3856           21 :     table_close(rel, RowExclusiveLock);
    3857              : 
    3858           21 :     return address;
    3859              : }
    3860              : 
    3861              : /*
    3862              :  * Change the owner of a type.
    3863              :  */
    3864              : ObjectAddress
    3865           68 : AlterTypeOwner(List *names, Oid newOwnerId, ObjectType objecttype)
    3866              : {
    3867              :     TypeName   *typename;
    3868              :     Oid         typeOid;
    3869              :     Relation    rel;
    3870              :     HeapTuple   tup;
    3871              :     HeapTuple   newtup;
    3872              :     Form_pg_type typTup;
    3873              :     AclResult   aclresult;
    3874              :     ObjectAddress address;
    3875              : 
    3876           68 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    3877              : 
    3878              :     /* Make a TypeName so we can use standard type lookup machinery */
    3879           68 :     typename = makeTypeNameFromNameList(names);
    3880              : 
    3881              :     /* Use LookupTypeName here so that shell types can be processed */
    3882           68 :     tup = LookupTypeName(NULL, typename, NULL, false);
    3883           68 :     if (tup == NULL)
    3884            0 :         ereport(ERROR,
    3885              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3886              :                  errmsg("type \"%s\" does not exist",
    3887              :                         TypeNameToString(typename))));
    3888           68 :     typeOid = typeTypeId(tup);
    3889              : 
    3890              :     /* Copy the syscache entry so we can scribble on it below */
    3891           68 :     newtup = heap_copytuple(tup);
    3892           68 :     ReleaseSysCache(tup);
    3893           68 :     tup = newtup;
    3894           68 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    3895              : 
    3896              :     /* Don't allow ALTER DOMAIN on a type */
    3897           68 :     if (objecttype == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
    3898            0 :         ereport(ERROR,
    3899              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3900              :                  errmsg("%s is not a domain",
    3901              :                         format_type_be(typeOid))));
    3902              : 
    3903              :     /*
    3904              :      * If it's a composite type, we need to check that it really is a
    3905              :      * free-standing composite type, and not a table's rowtype. We want people
    3906              :      * to use ALTER TABLE not ALTER TYPE for that case.
    3907              :      */
    3908           84 :     if (typTup->typtype == TYPTYPE_COMPOSITE &&
    3909           16 :         get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
    3910            0 :         ereport(ERROR,
    3911              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3912              :                  errmsg("%s is a table's row type",
    3913              :                         format_type_be(typeOid)),
    3914              :         /* translator: %s is an SQL ALTER command */
    3915              :                  errhint("Use %s instead.",
    3916              :                          "ALTER TABLE")));
    3917              : 
    3918              :     /* don't allow direct alteration of array types, either */
    3919           68 :     if (IsTrueArrayType(typTup))
    3920            0 :         ereport(ERROR,
    3921              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3922              :                  errmsg("cannot alter array type %s",
    3923              :                         format_type_be(typeOid)),
    3924              :                  errhint("You can alter type %s, which will alter the array type as well.",
    3925              :                          format_type_be(typTup->typelem))));
    3926              : 
    3927              :     /* don't allow direct alteration of multirange types, either */
    3928           68 :     if (typTup->typtype == TYPTYPE_MULTIRANGE)
    3929              :     {
    3930            4 :         Oid         rangetype = get_multirange_range(typeOid);
    3931              : 
    3932              :         /* We don't expect get_multirange_range to fail, but cope if so */
    3933            4 :         ereport(ERROR,
    3934              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3935              :                  errmsg("cannot alter multirange type %s",
    3936              :                         format_type_be(typeOid)),
    3937              :                  OidIsValid(rangetype) ?
    3938              :                  errhint("You can alter type %s, which will alter the multirange type as well.",
    3939              :                          format_type_be(rangetype)) : 0));
    3940              :     }
    3941              : 
    3942              :     /*
    3943              :      * If the new owner is the same as the existing owner, consider the
    3944              :      * command to have succeeded.  This is for dump restoration purposes.
    3945              :      */
    3946           64 :     if (typTup->typowner != newOwnerId)
    3947              :     {
    3948              :         /* Superusers can always do it */
    3949            4 :         if (!superuser())
    3950              :         {
    3951              :             /* Otherwise, must be owner of the existing object */
    3952            0 :             if (!object_ownercheck(TypeRelationId, typTup->oid, GetUserId()))
    3953            0 :                 aclcheck_error_type(ACLCHECK_NOT_OWNER, typTup->oid);
    3954              : 
    3955              :             /* Must be able to become new owner */
    3956            0 :             check_can_set_role(GetUserId(), newOwnerId);
    3957              : 
    3958              :             /* New owner must have CREATE privilege on namespace */
    3959            0 :             aclresult = object_aclcheck(NamespaceRelationId, typTup->typnamespace,
    3960              :                                         newOwnerId,
    3961              :                                         ACL_CREATE);
    3962            0 :             if (aclresult != ACLCHECK_OK)
    3963            0 :                 aclcheck_error(aclresult, OBJECT_SCHEMA,
    3964            0 :                                get_namespace_name(typTup->typnamespace));
    3965              :         }
    3966              : 
    3967            4 :         AlterTypeOwner_oid(typeOid, newOwnerId, true);
    3968              :     }
    3969              : 
    3970           64 :     ObjectAddressSet(address, TypeRelationId, typeOid);
    3971              : 
    3972              :     /* Clean up */
    3973           64 :     table_close(rel, RowExclusiveLock);
    3974              : 
    3975           64 :     return address;
    3976              : }
    3977              : 
    3978              : /*
    3979              :  * AlterTypeOwner_oid - change type owner unconditionally
    3980              :  *
    3981              :  * This function recurses to handle dependent types (arrays and multiranges).
    3982              :  * It invokes any necessary access object hooks.  If hasDependEntry is true,
    3983              :  * this function modifies the pg_shdepend entry appropriately (this should be
    3984              :  * passed as false only for table rowtypes and dependent types).
    3985              :  *
    3986              :  * This is used by ALTER TABLE/TYPE OWNER commands, as well as by REASSIGN
    3987              :  * OWNED BY.  It assumes the caller has done all needed checks.
    3988              :  */
    3989              : void
    3990           17 : AlterTypeOwner_oid(Oid typeOid, Oid newOwnerId, bool hasDependEntry)
    3991              : {
    3992              :     Relation    rel;
    3993              :     HeapTuple   tup;
    3994              :     Form_pg_type typTup;
    3995              : 
    3996           17 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    3997              : 
    3998           17 :     tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
    3999           17 :     if (!HeapTupleIsValid(tup))
    4000            0 :         elog(ERROR, "cache lookup failed for type %u", typeOid);
    4001           17 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    4002              : 
    4003              :     /*
    4004              :      * If it's a composite type, invoke ATExecChangeOwner so that we fix up
    4005              :      * the pg_class entry properly.  That will call back to
    4006              :      * AlterTypeOwnerInternal to take care of the pg_type entry(s).
    4007              :      */
    4008           17 :     if (typTup->typtype == TYPTYPE_COMPOSITE)
    4009            5 :         ATExecChangeOwner(typTup->typrelid, newOwnerId, true, AccessExclusiveLock);
    4010              :     else
    4011           12 :         AlterTypeOwnerInternal(typeOid, newOwnerId);
    4012              : 
    4013              :     /* Update owner dependency reference */
    4014           17 :     if (hasDependEntry)
    4015           17 :         changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
    4016              : 
    4017           17 :     InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
    4018              : 
    4019           17 :     ReleaseSysCache(tup);
    4020           17 :     table_close(rel, RowExclusiveLock);
    4021           17 : }
    4022              : 
    4023              : /*
    4024              :  * AlterTypeOwnerInternal - bare-bones type owner change.
    4025              :  *
    4026              :  * This routine simply modifies the owner of a pg_type entry, and recurses
    4027              :  * to handle any dependent types.
    4028              :  */
    4029              : void
    4030          532 : AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
    4031              : {
    4032              :     Relation    rel;
    4033              :     HeapTuple   tup;
    4034              :     Form_pg_type typTup;
    4035              :     Datum       repl_val[Natts_pg_type];
    4036              :     bool        repl_null[Natts_pg_type];
    4037              :     bool        repl_repl[Natts_pg_type];
    4038              :     Acl        *newAcl;
    4039              :     Datum       aclDatum;
    4040              :     bool        isNull;
    4041              : 
    4042          532 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    4043              : 
    4044          532 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
    4045          532 :     if (!HeapTupleIsValid(tup))
    4046            0 :         elog(ERROR, "cache lookup failed for type %u", typeOid);
    4047          532 :     typTup = (Form_pg_type) GETSTRUCT(tup);
    4048              : 
    4049          532 :     memset(repl_null, false, sizeof(repl_null));
    4050          532 :     memset(repl_repl, false, sizeof(repl_repl));
    4051              : 
    4052          532 :     repl_repl[Anum_pg_type_typowner - 1] = true;
    4053          532 :     repl_val[Anum_pg_type_typowner - 1] = ObjectIdGetDatum(newOwnerId);
    4054              : 
    4055          532 :     aclDatum = heap_getattr(tup,
    4056              :                             Anum_pg_type_typacl,
    4057              :                             RelationGetDescr(rel),
    4058              :                             &isNull);
    4059              :     /* Null ACLs do not require changes */
    4060          532 :     if (!isNull)
    4061              :     {
    4062            1 :         newAcl = aclnewowner(DatumGetAclP(aclDatum),
    4063              :                              typTup->typowner, newOwnerId);
    4064            1 :         repl_repl[Anum_pg_type_typacl - 1] = true;
    4065            1 :         repl_val[Anum_pg_type_typacl - 1] = PointerGetDatum(newAcl);
    4066              :     }
    4067              : 
    4068          532 :     tup = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val, repl_null,
    4069              :                             repl_repl);
    4070              : 
    4071          532 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
    4072              : 
    4073              :     /* If it has an array type, update that too */
    4074          532 :     if (OidIsValid(typTup->typarray))
    4075          266 :         AlterTypeOwnerInternal(typTup->typarray, newOwnerId);
    4076              : 
    4077              :     /* If it is a range type, update the associated multirange too */
    4078          532 :     if (typTup->typtype == TYPTYPE_RANGE)
    4079              :     {
    4080            8 :         Oid         multirange_typeid = get_range_multirange(typeOid);
    4081              : 
    4082            8 :         if (!OidIsValid(multirange_typeid))
    4083            0 :             ereport(ERROR,
    4084              :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    4085              :                      errmsg("could not find multirange type for data type %s",
    4086              :                             format_type_be(typeOid))));
    4087            8 :         AlterTypeOwnerInternal(multirange_typeid, newOwnerId);
    4088              :     }
    4089              : 
    4090              :     /* Clean up */
    4091          532 :     table_close(rel, RowExclusiveLock);
    4092          532 : }
    4093              : 
    4094              : /*
    4095              :  * Execute ALTER TYPE SET SCHEMA
    4096              :  */
    4097              : ObjectAddress
    4098           12 : AlterTypeNamespace(List *names, const char *newschema, ObjectType objecttype,
    4099              :                    Oid *oldschema)
    4100              : {
    4101              :     TypeName   *typename;
    4102              :     Oid         typeOid;
    4103              :     Oid         nspOid;
    4104              :     Oid         oldNspOid;
    4105              :     ObjectAddresses *objsMoved;
    4106              :     ObjectAddress myself;
    4107              : 
    4108              :     /* Make a TypeName so we can use standard type lookup machinery */
    4109           12 :     typename = makeTypeNameFromNameList(names);
    4110           12 :     typeOid = typenameTypeId(NULL, typename);
    4111              : 
    4112              :     /* Don't allow ALTER DOMAIN on a non-domain type */
    4113           12 :     if (objecttype == OBJECT_DOMAIN && get_typtype(typeOid) != TYPTYPE_DOMAIN)
    4114            0 :         ereport(ERROR,
    4115              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4116              :                  errmsg("%s is not a domain",
    4117              :                         format_type_be(typeOid))));
    4118              : 
    4119              :     /* get schema OID and check its permissions */
    4120           12 :     nspOid = LookupCreationNamespace(newschema);
    4121              : 
    4122           12 :     objsMoved = new_object_addresses();
    4123           12 :     oldNspOid = AlterTypeNamespace_oid(typeOid, nspOid, false, objsMoved);
    4124           12 :     free_object_addresses(objsMoved);
    4125              : 
    4126           12 :     if (oldschema)
    4127           12 :         *oldschema = oldNspOid;
    4128              : 
    4129           12 :     ObjectAddressSet(myself, TypeRelationId, typeOid);
    4130              : 
    4131           12 :     return myself;
    4132              : }
    4133              : 
    4134              : /*
    4135              :  * ALTER TYPE SET SCHEMA, where the caller has already looked up the OIDs
    4136              :  * of the type and the target schema and checked the schema's privileges.
    4137              :  *
    4138              :  * If ignoreDependent is true, we silently ignore dependent types
    4139              :  * (array types and table rowtypes) rather than raising errors.
    4140              :  *
    4141              :  * This entry point is exported for use by AlterObjectNamespace_oid,
    4142              :  * which doesn't want errors when it passes OIDs of dependent types.
    4143              :  *
    4144              :  * Returns the type's old namespace OID, or InvalidOid if we did nothing.
    4145              :  */
    4146              : Oid
    4147           20 : AlterTypeNamespace_oid(Oid typeOid, Oid nspOid, bool ignoreDependent,
    4148              :                        ObjectAddresses *objsMoved)
    4149              : {
    4150              :     Oid         elemOid;
    4151              : 
    4152              :     /* check permissions on type */
    4153           20 :     if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
    4154            0 :         aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
    4155              : 
    4156              :     /* don't allow direct alteration of array types */
    4157           20 :     elemOid = get_element_type(typeOid);
    4158           20 :     if (OidIsValid(elemOid) && get_array_type(elemOid) == typeOid)
    4159              :     {
    4160            4 :         if (ignoreDependent)
    4161            4 :             return InvalidOid;
    4162            0 :         ereport(ERROR,
    4163              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4164              :                  errmsg("cannot alter array type %s",
    4165              :                         format_type_be(typeOid)),
    4166              :                  errhint("You can alter type %s, which will alter the array type as well.",
    4167              :                          format_type_be(elemOid))));
    4168              :     }
    4169              : 
    4170              :     /* and do the work */
    4171           16 :     return AlterTypeNamespaceInternal(typeOid, nspOid,
    4172              :                                       false,    /* isImplicitArray */
    4173              :                                       ignoreDependent,  /* ignoreDependent */
    4174              :                                       true, /* errorOnTableType */
    4175              :                                       objsMoved);
    4176              : }
    4177              : 
    4178              : /*
    4179              :  * Move specified type to new namespace.
    4180              :  *
    4181              :  * Caller must have already checked privileges.
    4182              :  *
    4183              :  * The function automatically recurses to process the type's array type,
    4184              :  * if any.  isImplicitArray should be true only when doing this internal
    4185              :  * recursion (outside callers must never try to move an array type directly).
    4186              :  *
    4187              :  * If ignoreDependent is true, we silently don't process table types.
    4188              :  *
    4189              :  * If errorOnTableType is true, the function errors out if the type is
    4190              :  * a table type.  ALTER TABLE has to be used to move a table to a new
    4191              :  * namespace.  (This flag is ignored if ignoreDependent is true.)
    4192              :  *
    4193              :  * We also do nothing if the type is already listed in *objsMoved.
    4194              :  * After a successful move, we add the type to *objsMoved.
    4195              :  *
    4196              :  * Returns the type's old namespace OID, or InvalidOid if we did nothing.
    4197              :  */
    4198              : Oid
    4199          157 : AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid,
    4200              :                            bool isImplicitArray,
    4201              :                            bool ignoreDependent,
    4202              :                            bool errorOnTableType,
    4203              :                            ObjectAddresses *objsMoved)
    4204              : {
    4205              :     Relation    rel;
    4206              :     HeapTuple   tup;
    4207              :     Form_pg_type typform;
    4208              :     Oid         oldNspOid;
    4209              :     Oid         arrayOid;
    4210              :     bool        isCompositeType;
    4211              :     ObjectAddress thisobj;
    4212              : 
    4213              :     /*
    4214              :      * Make sure we haven't moved this object previously.
    4215              :      */
    4216          157 :     thisobj.classId = TypeRelationId;
    4217          157 :     thisobj.objectId = typeOid;
    4218          157 :     thisobj.objectSubId = 0;
    4219              : 
    4220          157 :     if (object_address_present(&thisobj, objsMoved))
    4221            0 :         return InvalidOid;
    4222              : 
    4223          157 :     rel = table_open(TypeRelationId, RowExclusiveLock);
    4224              : 
    4225          157 :     tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
    4226          157 :     if (!HeapTupleIsValid(tup))
    4227            0 :         elog(ERROR, "cache lookup failed for type %u", typeOid);
    4228          157 :     typform = (Form_pg_type) GETSTRUCT(tup);
    4229              : 
    4230          157 :     oldNspOid = typform->typnamespace;
    4231          157 :     arrayOid = typform->typarray;
    4232              : 
    4233              :     /* If the type is already there, we scan skip these next few checks. */
    4234          157 :     if (oldNspOid != nspOid)
    4235              :     {
    4236              :         /* common checks on switching namespaces */
    4237          133 :         CheckSetNamespace(oldNspOid, nspOid);
    4238              : 
    4239              :         /* check for duplicate name (more friendly than unique-index failure) */
    4240          133 :         if (SearchSysCacheExists2(TYPENAMENSP,
    4241              :                                   NameGetDatum(&typform->typname),
    4242              :                                   ObjectIdGetDatum(nspOid)))
    4243            0 :             ereport(ERROR,
    4244              :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
    4245              :                      errmsg("type \"%s\" already exists in schema \"%s\"",
    4246              :                             NameStr(typform->typname),
    4247              :                             get_namespace_name(nspOid))));
    4248              :     }
    4249              : 
    4250              :     /* Detect whether type is a composite type (but not a table rowtype) */
    4251          157 :     isCompositeType =
    4252          230 :         (typform->typtype == TYPTYPE_COMPOSITE &&
    4253           73 :          get_rel_relkind(typform->typrelid) == RELKIND_COMPOSITE_TYPE);
    4254              : 
    4255              :     /* Enforce not-table-type if requested */
    4256          157 :     if (typform->typtype == TYPTYPE_COMPOSITE && !isCompositeType)
    4257              :     {
    4258           64 :         if (ignoreDependent)
    4259              :         {
    4260            1 :             table_close(rel, RowExclusiveLock);
    4261            1 :             return InvalidOid;
    4262              :         }
    4263           63 :         if (errorOnTableType)
    4264            0 :             ereport(ERROR,
    4265              :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4266              :                      errmsg("%s is a table's row type",
    4267              :                             format_type_be(typeOid)),
    4268              :             /* translator: %s is an SQL ALTER command */
    4269              :                      errhint("Use %s instead.", "ALTER TABLE")));
    4270              :     }
    4271              : 
    4272          156 :     if (oldNspOid != nspOid)
    4273              :     {
    4274              :         /* OK, modify the pg_type row */
    4275              : 
    4276              :         /* tup is a copy, so we can scribble directly on it */
    4277          132 :         typform->typnamespace = nspOid;
    4278              : 
    4279          132 :         CatalogTupleUpdate(rel, &tup->t_self, tup);
    4280              :     }
    4281              : 
    4282              :     /*
    4283              :      * Composite types have pg_class entries.
    4284              :      *
    4285              :      * We need to modify the pg_class tuple as well to reflect the change of
    4286              :      * schema.
    4287              :      */
    4288          156 :     if (isCompositeType)
    4289              :     {
    4290              :         Relation    classRel;
    4291              : 
    4292            9 :         classRel = table_open(RelationRelationId, RowExclusiveLock);
    4293              : 
    4294            9 :         AlterRelationNamespaceInternal(classRel, typform->typrelid,
    4295              :                                        oldNspOid, nspOid,
    4296              :                                        false, objsMoved);
    4297              : 
    4298            9 :         table_close(classRel, RowExclusiveLock);
    4299              : 
    4300              :         /*
    4301              :          * Check for constraints associated with the composite type (we don't
    4302              :          * currently support this, but probably will someday).
    4303              :          */
    4304            9 :         AlterConstraintNamespaces(typform->typrelid, oldNspOid,
    4305              :                                   nspOid, false, objsMoved);
    4306              :     }
    4307              :     else
    4308              :     {
    4309              :         /* If it's a domain, it might have constraints */
    4310          147 :         if (typform->typtype == TYPTYPE_DOMAIN)
    4311            4 :             AlterConstraintNamespaces(typeOid, oldNspOid, nspOid, true,
    4312              :                                       objsMoved);
    4313              :     }
    4314              : 
    4315              :     /*
    4316              :      * Update dependency on schema, if any --- a table rowtype has not got
    4317              :      * one, and neither does an implicit array.
    4318              :      */
    4319          156 :     if (oldNspOid != nspOid &&
    4320          127 :         (isCompositeType || typform->typtype != TYPTYPE_COMPOSITE) &&
    4321           77 :         !isImplicitArray)
    4322           11 :         if (changeDependencyFor(TypeRelationId, typeOid,
    4323              :                                 NamespaceRelationId, oldNspOid, nspOid) != 1)
    4324            0 :             elog(ERROR, "could not change schema dependency for type \"%s\"",
    4325              :                  format_type_be(typeOid));
    4326              : 
    4327          156 :     InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
    4328              : 
    4329          156 :     heap_freetuple(tup);
    4330              : 
    4331          156 :     table_close(rel, RowExclusiveLock);
    4332              : 
    4333          156 :     add_exact_object_address(&thisobj, objsMoved);
    4334              : 
    4335              :     /* Recursively alter the associated array type, if any */
    4336          156 :     if (OidIsValid(arrayOid))
    4337           78 :         AlterTypeNamespaceInternal(arrayOid, nspOid,
    4338              :                                    true,    /* isImplicitArray */
    4339              :                                    false,   /* ignoreDependent */
    4340              :                                    true,    /* errorOnTableType */
    4341              :                                    objsMoved);
    4342              : 
    4343          156 :     return oldNspOid;
    4344              : }
    4345              : 
    4346              : /*
    4347              :  * AlterType
    4348              :  *      ALTER TYPE <type> SET (option = ...)
    4349              :  *
    4350              :  * NOTE: the set of changes that can be allowed here is constrained by many
    4351              :  * non-obvious implementation restrictions.  Tread carefully when considering
    4352              :  * adding new flexibility.
    4353              :  */
    4354              : ObjectAddress
    4355           36 : AlterType(AlterTypeStmt *stmt)
    4356              : {
    4357              :     ObjectAddress address;
    4358              :     Relation    catalog;
    4359              :     TypeName   *typename;
    4360              :     HeapTuple   tup;
    4361              :     Oid         typeOid;
    4362              :     Form_pg_type typForm;
    4363           36 :     bool        requireSuper = false;
    4364              :     AlterTypeRecurseParams atparams;
    4365              :     ListCell   *pl;
    4366              : 
    4367           36 :     catalog = table_open(TypeRelationId, RowExclusiveLock);
    4368              : 
    4369              :     /* Make a TypeName so we can use standard type lookup machinery */
    4370           36 :     typename = makeTypeNameFromNameList(stmt->typeName);
    4371           36 :     tup = typenameType(NULL, typename, NULL);
    4372              : 
    4373           32 :     typeOid = typeTypeId(tup);
    4374           32 :     typForm = (Form_pg_type) GETSTRUCT(tup);
    4375              : 
    4376              :     /* Process options */
    4377           32 :     memset(&atparams, 0, sizeof(atparams));
    4378           91 :     foreach(pl, stmt->options)
    4379              :     {
    4380           63 :         DefElem    *defel = (DefElem *) lfirst(pl);
    4381              : 
    4382           63 :         if (strcmp(defel->defname, "storage") == 0)
    4383              :         {
    4384            8 :             char       *a = defGetString(defel);
    4385              : 
    4386            8 :             if (pg_strcasecmp(a, "plain") == 0)
    4387            4 :                 atparams.storage = TYPSTORAGE_PLAIN;
    4388            4 :             else if (pg_strcasecmp(a, "external") == 0)
    4389            0 :                 atparams.storage = TYPSTORAGE_EXTERNAL;
    4390            4 :             else if (pg_strcasecmp(a, "extended") == 0)
    4391            4 :                 atparams.storage = TYPSTORAGE_EXTENDED;
    4392            0 :             else if (pg_strcasecmp(a, "main") == 0)
    4393            0 :                 atparams.storage = TYPSTORAGE_MAIN;
    4394              :             else
    4395            0 :                 ereport(ERROR,
    4396              :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4397              :                          errmsg("storage \"%s\" not recognized", a)));
    4398              : 
    4399              :             /*
    4400              :              * Validate the storage request.  If the type isn't varlena, it
    4401              :              * certainly doesn't support non-PLAIN storage.
    4402              :              */
    4403            8 :             if (atparams.storage != TYPSTORAGE_PLAIN && typForm->typlen != -1)
    4404            0 :                 ereport(ERROR,
    4405              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4406              :                          errmsg("fixed-size types must have storage PLAIN")));
    4407              : 
    4408              :             /*
    4409              :              * Switching from PLAIN to non-PLAIN is allowed, but it requires
    4410              :              * superuser, since we can't validate that the type's C functions
    4411              :              * will support it.  Switching from non-PLAIN to PLAIN is
    4412              :              * disallowed outright, because it's not practical to ensure that
    4413              :              * no tables have toasted values of the type.  Switching among
    4414              :              * different non-PLAIN settings is OK, since it just constitutes a
    4415              :              * change in the strategy requested for columns created in the
    4416              :              * future.
    4417              :              */
    4418            8 :             if (atparams.storage != TYPSTORAGE_PLAIN &&
    4419            4 :                 typForm->typstorage == TYPSTORAGE_PLAIN)
    4420            0 :                 requireSuper = true;
    4421            8 :             else if (atparams.storage == TYPSTORAGE_PLAIN &&
    4422            4 :                      typForm->typstorage != TYPSTORAGE_PLAIN)
    4423            4 :                 ereport(ERROR,
    4424              :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    4425              :                          errmsg("cannot change type's storage to PLAIN")));
    4426              : 
    4427            4 :             atparams.updateStorage = true;
    4428              :         }
    4429           55 :         else if (strcmp(defel->defname, "receive") == 0)
    4430              :         {
    4431           15 :             if (defel->arg != NULL)
    4432           15 :                 atparams.receiveOid =
    4433           15 :                     findTypeReceiveFunction(defGetQualifiedName(defel),
    4434              :                                             typeOid);
    4435              :             else
    4436            0 :                 atparams.receiveOid = InvalidOid;   /* NONE, remove function */
    4437           15 :             atparams.updateReceive = true;
    4438              :             /* Replacing an I/O function requires superuser. */
    4439           15 :             requireSuper = true;
    4440              :         }
    4441           40 :         else if (strcmp(defel->defname, "send") == 0)
    4442              :         {
    4443           15 :             if (defel->arg != NULL)
    4444           15 :                 atparams.sendOid =
    4445           15 :                     findTypeSendFunction(defGetQualifiedName(defel),
    4446              :                                          typeOid);
    4447              :             else
    4448            0 :                 atparams.sendOid = InvalidOid;  /* NONE, remove function */
    4449           15 :             atparams.updateSend = true;
    4450              :             /* Replacing an I/O function requires superuser. */
    4451           15 :             requireSuper = true;
    4452              :         }
    4453           25 :         else if (strcmp(defel->defname, "typmod_in") == 0)
    4454              :         {
    4455            4 :             if (defel->arg != NULL)
    4456            4 :                 atparams.typmodinOid =
    4457            4 :                     findTypeTypmodinFunction(defGetQualifiedName(defel));
    4458              :             else
    4459            0 :                 atparams.typmodinOid = InvalidOid;  /* NONE, remove function */
    4460            4 :             atparams.updateTypmodin = true;
    4461              :             /* Replacing an I/O function requires superuser. */
    4462            4 :             requireSuper = true;
    4463              :         }
    4464           21 :         else if (strcmp(defel->defname, "typmod_out") == 0)
    4465              :         {
    4466            4 :             if (defel->arg != NULL)
    4467            4 :                 atparams.typmodoutOid =
    4468            4 :                     findTypeTypmodoutFunction(defGetQualifiedName(defel));
    4469              :             else
    4470            0 :                 atparams.typmodoutOid = InvalidOid; /* NONE, remove function */
    4471            4 :             atparams.updateTypmodout = true;
    4472              :             /* Replacing an I/O function requires superuser. */
    4473            4 :             requireSuper = true;
    4474              :         }
    4475           17 :         else if (strcmp(defel->defname, "analyze") == 0)
    4476              :         {
    4477            6 :             if (defel->arg != NULL)
    4478            6 :                 atparams.analyzeOid =
    4479            6 :                     findTypeAnalyzeFunction(defGetQualifiedName(defel),
    4480              :                                             typeOid);
    4481              :             else
    4482            0 :                 atparams.analyzeOid = InvalidOid;   /* NONE, remove function */
    4483            6 :             atparams.updateAnalyze = true;
    4484              :             /* Replacing an analyze function requires superuser. */
    4485            6 :             requireSuper = true;
    4486              :         }
    4487           11 :         else if (strcmp(defel->defname, "subscript") == 0)
    4488              :         {
    4489           11 :             if (defel->arg != NULL)
    4490           11 :                 atparams.subscriptOid =
    4491           11 :                     findTypeSubscriptingFunction(defGetQualifiedName(defel),
    4492              :                                                  typeOid);
    4493              :             else
    4494            0 :                 atparams.subscriptOid = InvalidOid; /* NONE, remove function */
    4495           11 :             atparams.updateSubscript = true;
    4496              :             /* Replacing a subscript function requires superuser. */
    4497           11 :             requireSuper = true;
    4498              :         }
    4499              : 
    4500              :         /*
    4501              :          * The rest of the options that CREATE accepts cannot be changed.
    4502              :          * Check for them so that we can give a meaningful error message.
    4503              :          */
    4504            0 :         else if (strcmp(defel->defname, "input") == 0 ||
    4505            0 :                  strcmp(defel->defname, "output") == 0 ||
    4506            0 :                  strcmp(defel->defname, "internallength") == 0 ||
    4507            0 :                  strcmp(defel->defname, "passedbyvalue") == 0 ||
    4508            0 :                  strcmp(defel->defname, "alignment") == 0 ||
    4509            0 :                  strcmp(defel->defname, "like") == 0 ||
    4510            0 :                  strcmp(defel->defname, "category") == 0 ||
    4511            0 :                  strcmp(defel->defname, "preferred") == 0 ||
    4512            0 :                  strcmp(defel->defname, "default") == 0 ||
    4513            0 :                  strcmp(defel->defname, "element") == 0 ||
    4514            0 :                  strcmp(defel->defname, "delimiter") == 0 ||
    4515            0 :                  strcmp(defel->defname, "collatable") == 0)
    4516            0 :             ereport(ERROR,
    4517              :                     (errcode(ERRCODE_SYNTAX_ERROR),
    4518              :                      errmsg("type attribute \"%s\" cannot be changed",
    4519              :                             defel->defname)));
    4520              :         else
    4521            0 :             ereport(ERROR,
    4522              :                     (errcode(ERRCODE_SYNTAX_ERROR),
    4523              :                      errmsg("type attribute \"%s\" not recognized",
    4524              :                             defel->defname)));
    4525              :     }
    4526              : 
    4527              :     /*
    4528              :      * Permissions check.  Require superuser if we decided the command
    4529              :      * requires that, else must own the type.
    4530              :      */
    4531           28 :     if (requireSuper)
    4532              :     {
    4533           24 :         if (!superuser())
    4534            0 :             ereport(ERROR,
    4535              :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    4536              :                      errmsg("must be superuser to alter a type")));
    4537              :     }
    4538              :     else
    4539              :     {
    4540            4 :         if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
    4541            0 :             aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
    4542              :     }
    4543              : 
    4544              :     /*
    4545              :      * We disallow all forms of ALTER TYPE SET on types that aren't plain base
    4546              :      * types.  It would for example be highly unsafe, not to mention
    4547              :      * pointless, to change the send/receive functions for a composite type.
    4548              :      * Moreover, pg_dump has no support for changing these properties on
    4549              :      * non-base types.  We might weaken this someday, but not now.
    4550              :      *
    4551              :      * Note: if you weaken this enough to allow composite types, be sure to
    4552              :      * adjust the GenerateTypeDependencies call in AlterTypeRecurse.
    4553              :      */
    4554           28 :     if (typForm->typtype != TYPTYPE_BASE)
    4555            0 :         ereport(ERROR,
    4556              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4557              :                  errmsg("%s is not a base type",
    4558              :                         format_type_be(typeOid))));
    4559              : 
    4560              :     /*
    4561              :      * For the same reasons, don't allow direct alteration of array types.
    4562              :      */
    4563           28 :     if (IsTrueArrayType(typForm))
    4564            0 :         ereport(ERROR,
    4565              :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    4566              :                  errmsg("%s is not a base type",
    4567              :                         format_type_be(typeOid))));
    4568              : 
    4569              :     /* OK, recursively update this type and any arrays/domains over it */
    4570           28 :     AlterTypeRecurse(typeOid, false, tup, catalog, &atparams);
    4571              : 
    4572              :     /* Clean up */
    4573           28 :     ReleaseSysCache(tup);
    4574              : 
    4575           28 :     table_close(catalog, RowExclusiveLock);
    4576              : 
    4577           28 :     ObjectAddressSet(address, TypeRelationId, typeOid);
    4578              : 
    4579           28 :     return address;
    4580              : }
    4581              : 
    4582              : /*
    4583              :  * AlterTypeRecurse: one recursion step for AlterType()
    4584              :  *
    4585              :  * Apply the changes specified by "atparams" to the type identified by
    4586              :  * "typeOid", whose existing pg_type tuple is "tup".  If necessary,
    4587              :  * recursively update its array type as well.  Then search for any domains
    4588              :  * over this type, and recursively apply (most of) the same changes to those
    4589              :  * domains.
    4590              :  *
    4591              :  * We need this because the system generally assumes that a domain inherits
    4592              :  * many properties from its base type.  See DefineDomain() above for details
    4593              :  * of what is inherited.  Arrays inherit a smaller number of properties,
    4594              :  * but not none.
    4595              :  *
    4596              :  * There's a race condition here, in that some other transaction could
    4597              :  * concurrently add another domain atop this base type; we'd miss updating
    4598              :  * that one.  Hence, be wary of allowing ALTER TYPE to change properties for
    4599              :  * which it'd be really fatal for a domain to be out of sync with its base
    4600              :  * type (typlen, for example).  In practice, races seem unlikely to be an
    4601              :  * issue for plausible use-cases for ALTER TYPE.  If one does happen, it could
    4602              :  * be fixed by re-doing the same ALTER TYPE once all prior transactions have
    4603              :  * committed.
    4604              :  */
    4605              : static void
    4606           40 : AlterTypeRecurse(Oid typeOid, bool isImplicitArray,
    4607              :                  HeapTuple tup, Relation catalog,
    4608              :                  AlterTypeRecurseParams *atparams)
    4609              : {
    4610              :     Datum       values[Natts_pg_type];
    4611              :     bool        nulls[Natts_pg_type];
    4612              :     bool        replaces[Natts_pg_type];
    4613              :     HeapTuple   newtup;
    4614              :     SysScanDesc scan;
    4615              :     ScanKeyData key[1];
    4616              :     HeapTuple   domainTup;
    4617              : 
    4618              :     /* Since this function recurses, it could be driven to stack overflow */
    4619           40 :     check_stack_depth();
    4620              : 
    4621              :     /* Update the current type's tuple */
    4622           40 :     memset(values, 0, sizeof(values));
    4623           40 :     memset(nulls, 0, sizeof(nulls));
    4624           40 :     memset(replaces, 0, sizeof(replaces));
    4625              : 
    4626           40 :     if (atparams->updateStorage)
    4627              :     {
    4628            8 :         replaces[Anum_pg_type_typstorage - 1] = true;
    4629            8 :         values[Anum_pg_type_typstorage - 1] = CharGetDatum(atparams->storage);
    4630              :     }
    4631           40 :     if (atparams->updateReceive)
    4632              :     {
    4633           15 :         replaces[Anum_pg_type_typreceive - 1] = true;
    4634           15 :         values[Anum_pg_type_typreceive - 1] = ObjectIdGetDatum(atparams->receiveOid);
    4635              :     }
    4636           40 :     if (atparams->updateSend)
    4637              :     {
    4638           19 :         replaces[Anum_pg_type_typsend - 1] = true;
    4639           19 :         values[Anum_pg_type_typsend - 1] = ObjectIdGetDatum(atparams->sendOid);
    4640              :     }
    4641           40 :     if (atparams->updateTypmodin)
    4642              :     {
    4643            8 :         replaces[Anum_pg_type_typmodin - 1] = true;
    4644            8 :         values[Anum_pg_type_typmodin - 1] = ObjectIdGetDatum(atparams->typmodinOid);
    4645              :     }
    4646           40 :     if (atparams->updateTypmodout)
    4647              :     {
    4648            8 :         replaces[Anum_pg_type_typmodout - 1] = true;
    4649            8 :         values[Anum_pg_type_typmodout - 1] = ObjectIdGetDatum(atparams->typmodoutOid);
    4650              :     }
    4651           40 :     if (atparams->updateAnalyze)
    4652              :     {
    4653           10 :         replaces[Anum_pg_type_typanalyze - 1] = true;
    4654           10 :         values[Anum_pg_type_typanalyze - 1] = ObjectIdGetDatum(atparams->analyzeOid);
    4655              :     }
    4656           40 :     if (atparams->updateSubscript)
    4657              :     {
    4658           11 :         replaces[Anum_pg_type_typsubscript - 1] = true;
    4659           11 :         values[Anum_pg_type_typsubscript - 1] = ObjectIdGetDatum(atparams->subscriptOid);
    4660              :     }
    4661              : 
    4662           40 :     newtup = heap_modify_tuple(tup, RelationGetDescr(catalog),
    4663              :                                values, nulls, replaces);
    4664              : 
    4665           40 :     CatalogTupleUpdate(catalog, &newtup->t_self, newtup);
    4666              : 
    4667              :     /* Rebuild dependencies for this type */
    4668           40 :     GenerateTypeDependencies(newtup,
    4669              :                              catalog,
    4670              :                              NULL,  /* don't have defaultExpr handy */
    4671              :                              NULL,  /* don't have typacl handy */
    4672              :                              0, /* we rejected composite types above */
    4673              :                              isImplicitArray,   /* it might be an array */
    4674              :                              isImplicitArray,   /* dependent iff it's array */
    4675              :                              false, /* don't touch extension membership */
    4676              :                              true);
    4677              : 
    4678           40 :     InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
    4679              : 
    4680              :     /*
    4681              :      * Arrays inherit their base type's typmodin and typmodout, but none of
    4682              :      * the other properties we're concerned with here.  Recurse to the array
    4683              :      * type if needed.
    4684              :      */
    4685           40 :     if (!isImplicitArray &&
    4686           36 :         (atparams->updateTypmodin || atparams->updateTypmodout))
    4687              :     {
    4688            4 :         Oid         arrtypoid = ((Form_pg_type) GETSTRUCT(newtup))->typarray;
    4689              : 
    4690            4 :         if (OidIsValid(arrtypoid))
    4691              :         {
    4692              :             HeapTuple   arrtup;
    4693              :             AlterTypeRecurseParams arrparams;
    4694              : 
    4695            4 :             arrtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(arrtypoid));
    4696            4 :             if (!HeapTupleIsValid(arrtup))
    4697            0 :                 elog(ERROR, "cache lookup failed for type %u", arrtypoid);
    4698              : 
    4699            4 :             memset(&arrparams, 0, sizeof(arrparams));
    4700            4 :             arrparams.updateTypmodin = atparams->updateTypmodin;
    4701            4 :             arrparams.updateTypmodout = atparams->updateTypmodout;
    4702            4 :             arrparams.typmodinOid = atparams->typmodinOid;
    4703            4 :             arrparams.typmodoutOid = atparams->typmodoutOid;
    4704              : 
    4705            4 :             AlterTypeRecurse(arrtypoid, true, arrtup, catalog, &arrparams);
    4706              : 
    4707            4 :             ReleaseSysCache(arrtup);
    4708              :         }
    4709              :     }
    4710              : 
    4711              :     /*
    4712              :      * Now we need to recurse to domains.  However, some properties are not
    4713              :      * inherited by domains, so clear the update flags for those.
    4714              :      */
    4715           40 :     atparams->updateReceive = false; /* domains use F_DOMAIN_RECV */
    4716           40 :     atparams->updateTypmodin = false;    /* domains don't have typmods */
    4717           40 :     atparams->updateTypmodout = false;
    4718           40 :     atparams->updateSubscript = false;   /* domains don't have subscriptors */
    4719              : 
    4720              :     /* Skip the scan if nothing remains to be done */
    4721           40 :     if (!(atparams->updateStorage ||
    4722           32 :           atparams->updateSend ||
    4723           13 :           atparams->updateAnalyze))
    4724           11 :         return;
    4725              : 
    4726              :     /* Search pg_type for possible domains over this type */
    4727           29 :     ScanKeyInit(&key[0],
    4728              :                 Anum_pg_type_typbasetype,
    4729              :                 BTEqualStrategyNumber, F_OIDEQ,
    4730              :                 ObjectIdGetDatum(typeOid));
    4731              : 
    4732           29 :     scan = systable_beginscan(catalog, InvalidOid, false,
    4733              :                               NULL, 1, key);
    4734              : 
    4735           37 :     while ((domainTup = systable_getnext(scan)) != NULL)
    4736              :     {
    4737            8 :         Form_pg_type domainForm = (Form_pg_type) GETSTRUCT(domainTup);
    4738              : 
    4739              :         /*
    4740              :          * Shouldn't have a nonzero typbasetype in a non-domain, but let's
    4741              :          * check
    4742              :          */
    4743            8 :         if (domainForm->typtype != TYPTYPE_DOMAIN)
    4744            0 :             continue;
    4745              : 
    4746            8 :         AlterTypeRecurse(domainForm->oid, false, domainTup, catalog, atparams);
    4747              :     }
    4748              : 
    4749           29 :     systable_endscan(scan);
    4750              : }
        

Generated by: LCOV version 2.0-1