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

Generated by: LCOV version 1.14