OSDN Git Service

2a2ff5387e51ef1106d7ac309330a20def3e60e0
[pg-rex/syncrep.git] / src / backend / commands / typecmds.c
1 /*-------------------------------------------------------------------------
2  *
3  * typecmds.c
4  *        Routines for SQL commands that manipulate types (and domains).
5  *
6  * Portions Copyright (c) 1996-2011, 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 "FooDefine" routines (in src/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/heapam.h"
36 #include "access/xact.h"
37 #include "catalog/catalog.h"
38 #include "catalog/dependency.h"
39 #include "catalog/heap.h"
40 #include "catalog/indexing.h"
41 #include "catalog/pg_collation.h"
42 #include "catalog/pg_constraint.h"
43 #include "catalog/pg_depend.h"
44 #include "catalog/pg_enum.h"
45 #include "catalog/pg_namespace.h"
46 #include "catalog/pg_type.h"
47 #include "catalog/pg_type_fn.h"
48 #include "commands/defrem.h"
49 #include "commands/tablecmds.h"
50 #include "commands/typecmds.h"
51 #include "executor/executor.h"
52 #include "miscadmin.h"
53 #include "nodes/makefuncs.h"
54 #include "optimizer/planner.h"
55 #include "optimizer/var.h"
56 #include "parser/parse_coerce.h"
57 #include "parser/parse_collate.h"
58 #include "parser/parse_expr.h"
59 #include "parser/parse_func.h"
60 #include "parser/parse_type.h"
61 #include "utils/acl.h"
62 #include "utils/builtins.h"
63 #include "utils/fmgroids.h"
64 #include "utils/lsyscache.h"
65 #include "utils/memutils.h"
66 #include "utils/syscache.h"
67 #include "utils/tqual.h"
68
69
70 /* result structure for get_rels_with_domain() */
71 typedef struct
72 {
73         Relation        rel;                    /* opened and locked relation */
74         int                     natts;                  /* number of attributes of interest */
75         int                *atts;                       /* attribute numbers */
76         /* atts[] is of allocated length RelationGetNumberOfAttributes(rel) */
77 } RelToCheck;
78
79 /* Potentially set by contrib/pg_upgrade_support functions */
80 Oid                     binary_upgrade_next_array_pg_type_oid = InvalidOid;
81
82 static Oid      findTypeInputFunction(List *procname, Oid typeOid);
83 static Oid      findTypeOutputFunction(List *procname, Oid typeOid);
84 static Oid      findTypeReceiveFunction(List *procname, Oid typeOid);
85 static Oid      findTypeSendFunction(List *procname, Oid typeOid);
86 static Oid      findTypeTypmodinFunction(List *procname);
87 static Oid      findTypeTypmodoutFunction(List *procname);
88 static Oid      findTypeAnalyzeFunction(List *procname, Oid typeOid);
89 static void     validateDomainConstraint(Oid domainoid, char *ccbin);
90 static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
91 static void checkDomainOwner(HeapTuple tup);
92 static void checkEnumOwner(HeapTuple tup);
93 static char *domainAddConstraint(Oid domainOid, Oid domainNamespace,
94                                         Oid baseTypeOid,
95                                         int typMod, Constraint *constr,
96                                         char *domainName);
97
98
99 /*
100  * DefineType
101  *              Registers a new base type.
102  */
103 void
104 DefineType(List *names, List *parameters)
105 {
106         char       *typeName;
107         Oid                     typeNamespace;
108         int16           internalLength = -1;    /* default: variable-length */
109         List       *inputName = NIL;
110         List       *outputName = NIL;
111         List       *receiveName = NIL;
112         List       *sendName = NIL;
113         List       *typmodinName = NIL;
114         List       *typmodoutName = NIL;
115         List       *analyzeName = NIL;
116         char            category = TYPCATEGORY_USER;
117         bool            preferred = false;
118         char            delimiter = DEFAULT_TYPDELIM;
119         Oid                     elemType = InvalidOid;
120         char       *defaultValue = NULL;
121         bool            byValue = false;
122         char            alignment = 'i';        /* default alignment */
123         char            storage = 'p';  /* default TOAST storage method */
124         Oid                     collation = InvalidOid;
125         DefElem    *likeTypeEl = NULL;
126         DefElem    *internalLengthEl = NULL;
127         DefElem    *inputNameEl = NULL;
128         DefElem    *outputNameEl = NULL;
129         DefElem    *receiveNameEl = NULL;
130         DefElem    *sendNameEl = NULL;
131         DefElem    *typmodinNameEl = NULL;
132         DefElem    *typmodoutNameEl = NULL;
133         DefElem    *analyzeNameEl = NULL;
134         DefElem    *categoryEl = NULL;
135         DefElem    *preferredEl = NULL;
136         DefElem    *delimiterEl = NULL;
137         DefElem    *elemTypeEl = NULL;
138         DefElem    *defaultValueEl = NULL;
139         DefElem    *byValueEl = NULL;
140         DefElem    *alignmentEl = NULL;
141         DefElem    *storageEl = NULL;
142         DefElem    *collatableEl = NULL;
143         Oid                     inputOid;
144         Oid                     outputOid;
145         Oid                     receiveOid = InvalidOid;
146         Oid                     sendOid = InvalidOid;
147         Oid                     typmodinOid = InvalidOid;
148         Oid                     typmodoutOid = InvalidOid;
149         Oid                     analyzeOid = InvalidOid;
150         char       *array_type;
151         Oid                     array_oid;
152         Oid                     typoid;
153         Oid                     resulttype;
154         ListCell   *pl;
155
156         /*
157          * As of Postgres 8.4, we require superuser privilege to create a base
158          * type.  This is simple paranoia: there are too many ways to mess up the
159          * system with an incorrect type definition (for instance, representation
160          * parameters that don't match what the C code expects).  In practice it
161          * takes superuser privilege to create the I/O functions, and so the
162          * former requirement that you own the I/O functions pretty much forced
163          * superuserness anyway.  We're just making doubly sure here.
164          *
165          * XXX re-enable NOT_USED code sections below if you remove this test.
166          */
167         if (!superuser())
168                 ereport(ERROR,
169                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
170                                  errmsg("must be superuser to create a base type")));
171
172         /* Convert list of names to a name and namespace */
173         typeNamespace = QualifiedNameGetCreationNamespace(names, &typeName);
174
175 #ifdef NOT_USED
176         /* XXX this is unnecessary given the superuser check above */
177         /* Check we have creation rights in target namespace */
178         aclresult = pg_namespace_aclcheck(typeNamespace, GetUserId(), ACL_CREATE);
179         if (aclresult != ACLCHECK_OK)
180                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
181                                            get_namespace_name(typeNamespace));
182 #endif
183
184         /*
185          * Look to see if type already exists (presumably as a shell; if not,
186          * TypeCreate will complain).
187          */
188         typoid = GetSysCacheOid2(TYPENAMENSP,
189                                                          CStringGetDatum(typeName),
190                                                          ObjectIdGetDatum(typeNamespace));
191
192         /*
193          * If it's not a shell, see if it's an autogenerated array type, and if so
194          * rename it out of the way.
195          */
196         if (OidIsValid(typoid) && get_typisdefined(typoid))
197         {
198                 if (moveArrayTypeName(typoid, typeName, typeNamespace))
199                         typoid = InvalidOid;
200         }
201
202         /*
203          * If it doesn't exist, create it as a shell, so that the OID is known for
204          * use in the I/O function definitions.
205          */
206         if (!OidIsValid(typoid))
207         {
208                 typoid = TypeShellMake(typeName, typeNamespace, GetUserId());
209                 /* Make new shell type visible for modification below */
210                 CommandCounterIncrement();
211
212                 /*
213                  * If the command was a parameterless CREATE TYPE, we're done ---
214                  * creating the shell type was all we're supposed to do.
215                  */
216                 if (parameters == NIL)
217                         return;
218         }
219         else
220         {
221                 /* Complain if dummy CREATE TYPE and entry already exists */
222                 if (parameters == NIL)
223                         ereport(ERROR,
224                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
225                                          errmsg("type \"%s\" already exists", typeName)));
226         }
227
228         /* Extract the parameters from the parameter list */
229         foreach(pl, parameters)
230         {
231                 DefElem    *defel = (DefElem *) lfirst(pl);
232                 DefElem   **defelp;
233
234                 if (pg_strcasecmp(defel->defname, "like") == 0)
235                         defelp = &likeTypeEl;
236                 else if (pg_strcasecmp(defel->defname, "internallength") == 0)
237                         defelp = &internalLengthEl;
238                 else if (pg_strcasecmp(defel->defname, "input") == 0)
239                         defelp = &inputNameEl;
240                 else if (pg_strcasecmp(defel->defname, "output") == 0)
241                         defelp = &outputNameEl;
242                 else if (pg_strcasecmp(defel->defname, "receive") == 0)
243                         defelp = &receiveNameEl;
244                 else if (pg_strcasecmp(defel->defname, "send") == 0)
245                         defelp = &sendNameEl;
246                 else if (pg_strcasecmp(defel->defname, "typmod_in") == 0)
247                         defelp = &typmodinNameEl;
248                 else if (pg_strcasecmp(defel->defname, "typmod_out") == 0)
249                         defelp = &typmodoutNameEl;
250                 else if (pg_strcasecmp(defel->defname, "analyze") == 0 ||
251                                  pg_strcasecmp(defel->defname, "analyse") == 0)
252                         defelp = &analyzeNameEl;
253                 else if (pg_strcasecmp(defel->defname, "category") == 0)
254                         defelp = &categoryEl;
255                 else if (pg_strcasecmp(defel->defname, "preferred") == 0)
256                         defelp = &preferredEl;
257                 else if (pg_strcasecmp(defel->defname, "delimiter") == 0)
258                         defelp = &delimiterEl;
259                 else if (pg_strcasecmp(defel->defname, "element") == 0)
260                         defelp = &elemTypeEl;
261                 else if (pg_strcasecmp(defel->defname, "default") == 0)
262                         defelp = &defaultValueEl;
263                 else if (pg_strcasecmp(defel->defname, "passedbyvalue") == 0)
264                         defelp = &byValueEl;
265                 else if (pg_strcasecmp(defel->defname, "alignment") == 0)
266                         defelp = &alignmentEl;
267                 else if (pg_strcasecmp(defel->defname, "storage") == 0)
268                         defelp = &storageEl;
269                 else if (pg_strcasecmp(defel->defname, "collatable") == 0)
270                         defelp = &collatableEl;
271                 else
272                 {
273                         /* WARNING, not ERROR, for historical backwards-compatibility */
274                         ereport(WARNING,
275                                         (errcode(ERRCODE_SYNTAX_ERROR),
276                                          errmsg("type attribute \"%s\" not recognized",
277                                                         defel->defname)));
278                         continue;
279                 }
280                 if (*defelp != NULL)
281                         ereport(ERROR,
282                                         (errcode(ERRCODE_SYNTAX_ERROR),
283                                          errmsg("conflicting or redundant options")));
284                 *defelp = defel;
285         }
286
287         /*
288          * Now interpret the options; we do this separately so that LIKE can be
289          * overridden by other options regardless of the ordering in the parameter
290          * list.
291          */
292         if (likeTypeEl)
293         {
294                 Type            likeType;
295                 Form_pg_type likeForm;
296
297                 likeType = typenameType(NULL, defGetTypeName(likeTypeEl), NULL);
298                 likeForm = (Form_pg_type) GETSTRUCT(likeType);
299                 internalLength = likeForm->typlen;
300                 byValue = likeForm->typbyval;
301                 alignment = likeForm->typalign;
302                 storage = likeForm->typstorage;
303                 ReleaseSysCache(likeType);
304         }
305         if (internalLengthEl)
306                 internalLength = defGetTypeLength(internalLengthEl);
307         if (inputNameEl)
308                 inputName = defGetQualifiedName(inputNameEl);
309         if (outputNameEl)
310                 outputName = defGetQualifiedName(outputNameEl);
311         if (receiveNameEl)
312                 receiveName = defGetQualifiedName(receiveNameEl);
313         if (sendNameEl)
314                 sendName = defGetQualifiedName(sendNameEl);
315         if (typmodinNameEl)
316                 typmodinName = defGetQualifiedName(typmodinNameEl);
317         if (typmodoutNameEl)
318                 typmodoutName = defGetQualifiedName(typmodoutNameEl);
319         if (analyzeNameEl)
320                 analyzeName = defGetQualifiedName(analyzeNameEl);
321         if (categoryEl)
322         {
323                 char       *p = defGetString(categoryEl);
324
325                 category = p[0];
326                 /* restrict to non-control ASCII */
327                 if (category < 32 || category > 126)
328                         ereport(ERROR,
329                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
330                                  errmsg("invalid type category \"%s\": must be simple ASCII",
331                                                 p)));
332         }
333         if (preferredEl)
334                 preferred = defGetBoolean(preferredEl);
335         if (delimiterEl)
336         {
337                 char       *p = defGetString(delimiterEl);
338
339                 delimiter = p[0];
340                 /* XXX shouldn't we restrict the delimiter? */
341         }
342         if (elemTypeEl)
343         {
344                 elemType = typenameTypeId(NULL, defGetTypeName(elemTypeEl));
345                 /* disallow arrays of pseudotypes */
346                 if (get_typtype(elemType) == TYPTYPE_PSEUDO)
347                         ereport(ERROR,
348                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
349                                          errmsg("array element type cannot be %s",
350                                                         format_type_be(elemType))));
351         }
352         if (defaultValueEl)
353                 defaultValue = defGetString(defaultValueEl);
354         if (byValueEl)
355                 byValue = defGetBoolean(byValueEl);
356         if (alignmentEl)
357         {
358                 char       *a = defGetString(alignmentEl);
359
360                 /*
361                  * Note: if argument was an unquoted identifier, parser will have
362                  * applied translations to it, so be prepared to recognize translated
363                  * type names as well as the nominal form.
364                  */
365                 if (pg_strcasecmp(a, "double") == 0 ||
366                         pg_strcasecmp(a, "float8") == 0 ||
367                         pg_strcasecmp(a, "pg_catalog.float8") == 0)
368                         alignment = 'd';
369                 else if (pg_strcasecmp(a, "int4") == 0 ||
370                                  pg_strcasecmp(a, "pg_catalog.int4") == 0)
371                         alignment = 'i';
372                 else if (pg_strcasecmp(a, "int2") == 0 ||
373                                  pg_strcasecmp(a, "pg_catalog.int2") == 0)
374                         alignment = 's';
375                 else if (pg_strcasecmp(a, "char") == 0 ||
376                                  pg_strcasecmp(a, "pg_catalog.bpchar") == 0)
377                         alignment = 'c';
378                 else
379                         ereport(ERROR,
380                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
381                                          errmsg("alignment \"%s\" not recognized", a)));
382         }
383         if (storageEl)
384         {
385                 char       *a = defGetString(storageEl);
386
387                 if (pg_strcasecmp(a, "plain") == 0)
388                         storage = 'p';
389                 else if (pg_strcasecmp(a, "external") == 0)
390                         storage = 'e';
391                 else if (pg_strcasecmp(a, "extended") == 0)
392                         storage = 'x';
393                 else if (pg_strcasecmp(a, "main") == 0)
394                         storage = 'm';
395                 else
396                         ereport(ERROR,
397                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
398                                          errmsg("storage \"%s\" not recognized", a)));
399         }
400         if (collatableEl)
401                 collation = defGetBoolean(collatableEl) ? DEFAULT_COLLATION_OID : InvalidOid;
402
403         /*
404          * make sure we have our required definitions
405          */
406         if (inputName == NIL)
407                 ereport(ERROR,
408                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
409                                  errmsg("type input function must be specified")));
410         if (outputName == NIL)
411                 ereport(ERROR,
412                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
413                                  errmsg("type output function must be specified")));
414
415         if (typmodinName == NIL && typmodoutName != NIL)
416                 ereport(ERROR,
417                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
418                                  errmsg("type modifier output function is useless without a type modifier input function")));
419
420         /*
421          * Convert I/O proc names to OIDs
422          */
423         inputOid = findTypeInputFunction(inputName, typoid);
424         outputOid = findTypeOutputFunction(outputName, typoid);
425         if (receiveName)
426                 receiveOid = findTypeReceiveFunction(receiveName, typoid);
427         if (sendName)
428                 sendOid = findTypeSendFunction(sendName, typoid);
429
430         /*
431          * Verify that I/O procs return the expected thing.  If we see OPAQUE,
432          * complain and change it to the correct type-safe choice.
433          */
434         resulttype = get_func_rettype(inputOid);
435         if (resulttype != typoid)
436         {
437                 if (resulttype == OPAQUEOID)
438                 {
439                         /* backwards-compatibility hack */
440                         ereport(WARNING,
441                                         (errmsg("changing return type of function %s from \"opaque\" to %s",
442                                                         NameListToString(inputName), typeName)));
443                         SetFunctionReturnType(inputOid, typoid);
444                 }
445                 else
446                         ereport(ERROR,
447                                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
448                                          errmsg("type input function %s must return type %s",
449                                                         NameListToString(inputName), typeName)));
450         }
451         resulttype = get_func_rettype(outputOid);
452         if (resulttype != CSTRINGOID)
453         {
454                 if (resulttype == OPAQUEOID)
455                 {
456                         /* backwards-compatibility hack */
457                         ereport(WARNING,
458                                         (errmsg("changing return type of function %s from \"opaque\" to \"cstring\"",
459                                                         NameListToString(outputName))));
460                         SetFunctionReturnType(outputOid, CSTRINGOID);
461                 }
462                 else
463                         ereport(ERROR,
464                                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
465                            errmsg("type output function %s must return type \"cstring\"",
466                                           NameListToString(outputName))));
467         }
468         if (receiveOid)
469         {
470                 resulttype = get_func_rettype(receiveOid);
471                 if (resulttype != typoid)
472                         ereport(ERROR,
473                                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
474                                          errmsg("type receive function %s must return type %s",
475                                                         NameListToString(receiveName), typeName)));
476         }
477         if (sendOid)
478         {
479                 resulttype = get_func_rettype(sendOid);
480                 if (resulttype != BYTEAOID)
481                         ereport(ERROR,
482                                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
483                                    errmsg("type send function %s must return type \"bytea\"",
484                                                   NameListToString(sendName))));
485         }
486
487         /*
488          * Convert typmodin/out function proc names to OIDs.
489          */
490         if (typmodinName)
491                 typmodinOid = findTypeTypmodinFunction(typmodinName);
492         if (typmodoutName)
493                 typmodoutOid = findTypeTypmodoutFunction(typmodoutName);
494
495         /*
496          * Convert analysis function proc name to an OID. If no analysis function
497          * is specified, we'll use zero to select the built-in default algorithm.
498          */
499         if (analyzeName)
500                 analyzeOid = findTypeAnalyzeFunction(analyzeName, typoid);
501
502         /*
503          * Check permissions on functions.      We choose to require the creator/owner
504          * of a type to also own the underlying functions.      Since creating a type
505          * is tantamount to granting public execute access on the functions, the
506          * minimum sane check would be for execute-with-grant-option.  But we
507          * don't have a way to make the type go away if the grant option is
508          * revoked, so ownership seems better.
509          */
510 #ifdef NOT_USED
511         /* XXX this is unnecessary given the superuser check above */
512         if (inputOid && !pg_proc_ownercheck(inputOid, GetUserId()))
513                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
514                                            NameListToString(inputName));
515         if (outputOid && !pg_proc_ownercheck(outputOid, GetUserId()))
516                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
517                                            NameListToString(outputName));
518         if (receiveOid && !pg_proc_ownercheck(receiveOid, GetUserId()))
519                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
520                                            NameListToString(receiveName));
521         if (sendOid && !pg_proc_ownercheck(sendOid, GetUserId()))
522                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
523                                            NameListToString(sendName));
524         if (typmodinOid && !pg_proc_ownercheck(typmodinOid, GetUserId()))
525                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
526                                            NameListToString(typmodinName));
527         if (typmodoutOid && !pg_proc_ownercheck(typmodoutOid, GetUserId()))
528                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
529                                            NameListToString(typmodoutName));
530         if (analyzeOid && !pg_proc_ownercheck(analyzeOid, GetUserId()))
531                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
532                                            NameListToString(analyzeName));
533 #endif
534
535         array_oid = AssignTypeArrayOid();
536
537         /*
538          * now have TypeCreate do all the real work.
539          *
540          * Note: the pg_type.oid is stored in user tables as array elements (base
541          * types) in ArrayType and in composite types in DatumTupleFields.      This
542          * oid must be preserved by binary upgrades.
543          */
544         typoid =
545                 TypeCreate(InvalidOid,  /* no predetermined type OID */
546                                    typeName,    /* type name */
547                                    typeNamespace,               /* namespace */
548                                    InvalidOid,  /* relation oid (n/a here) */
549                                    0,                   /* relation kind (ditto) */
550                                    GetUserId(), /* owner's ID */
551                                    internalLength,              /* internal size */
552                                    TYPTYPE_BASE,        /* type-type (base type) */
553                                    category,    /* type-category */
554                                    preferred,   /* is it a preferred type? */
555                                    delimiter,   /* array element delimiter */
556                                    inputOid,    /* input procedure */
557                                    outputOid,   /* output procedure */
558                                    receiveOid,  /* receive procedure */
559                                    sendOid,             /* send procedure */
560                                    typmodinOid, /* typmodin procedure */
561                                    typmodoutOid,        /* typmodout procedure */
562                                    analyzeOid,  /* analyze procedure */
563                                    elemType,    /* element type ID */
564                                    false,               /* this is not an array type */
565                                    array_oid,   /* array type we are about to create */
566                                    InvalidOid,  /* base type ID (only for domains) */
567                                    defaultValue,        /* default type value */
568                                    NULL,                /* no binary form available */
569                                    byValue,             /* passed by value */
570                                    alignment,   /* required alignment */
571                                    storage,             /* TOAST strategy */
572                                    -1,                  /* typMod (Domains only) */
573                                    0,                   /* Array Dimensions of typbasetype */
574                                    false,               /* Type NOT NULL */
575                                    collation);  /* type's collation */
576
577         /*
578          * Create the array type that goes with it.
579          */
580         array_type = makeArrayTypeName(typeName, typeNamespace);
581
582         /* alignment must be 'i' or 'd' for arrays */
583         alignment = (alignment == 'd') ? 'd' : 'i';
584
585         TypeCreate(array_oid,           /* force assignment of this type OID */
586                            array_type,          /* type name */
587                            typeNamespace,       /* namespace */
588                            InvalidOid,          /* relation oid (n/a here) */
589                            0,                           /* relation kind (ditto) */
590                            GetUserId(),         /* owner's ID */
591                            -1,                          /* internal size (always varlena) */
592                            TYPTYPE_BASE,        /* type-type (base type) */
593                            TYPCATEGORY_ARRAY,           /* type-category (array) */
594                            false,                       /* array types are never preferred */
595                            delimiter,           /* array element delimiter */
596                            F_ARRAY_IN,          /* input procedure */
597                            F_ARRAY_OUT,         /* output procedure */
598                            F_ARRAY_RECV,        /* receive procedure */
599                            F_ARRAY_SEND,        /* send procedure */
600                            typmodinOid,         /* typmodin procedure */
601                            typmodoutOid,        /* typmodout procedure */
602                            InvalidOid,          /* analyze procedure - default */
603                            typoid,                      /* element type ID */
604                            true,                        /* yes this is an array type */
605                            InvalidOid,          /* no further array type */
606                            InvalidOid,          /* base type ID */
607                            NULL,                        /* never a default type value */
608                            NULL,                        /* binary default isn't sent either */
609                            false,                       /* never passed by value */
610                            alignment,           /* see above */
611                            'x',                         /* ARRAY is always toastable */
612                            -1,                          /* typMod (Domains only) */
613                            0,                           /* Array dimensions of typbasetype */
614                            false,                       /* Type NOT NULL */
615                            collation);          /* type's collation */
616
617         pfree(array_type);
618 }
619
620
621 /*
622  *      RemoveTypes
623  *              Implements DROP TYPE and DROP DOMAIN
624  *
625  * Note: if DOMAIN is specified, we enforce that each type is a domain, but
626  * we don't enforce the converse for DROP TYPE
627  */
628 void
629 RemoveTypes(DropStmt *drop)
630 {
631         ObjectAddresses *objects;
632         ListCell   *cell;
633
634         /*
635          * First we identify all the types, then we delete them in a single
636          * performMultipleDeletions() call.  This is to avoid unwanted DROP
637          * RESTRICT errors if one of the types depends on another.
638          */
639         objects = new_object_addresses();
640
641         foreach(cell, drop->objects)
642         {
643                 List       *names = (List *) lfirst(cell);
644                 TypeName   *typename;
645                 Oid                     typeoid;
646                 HeapTuple       tup;
647                 ObjectAddress object;
648                 Form_pg_type typ;
649
650                 /* Make a TypeName so we can use standard type lookup machinery */
651                 typename = makeTypeNameFromNameList(names);
652
653                 /* Use LookupTypeName here so that shell types can be removed. */
654                 tup = LookupTypeName(NULL, typename, NULL);
655                 if (tup == NULL)
656                 {
657                         if (!drop->missing_ok)
658                         {
659                                 ereport(ERROR,
660                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
661                                                  errmsg("type \"%s\" does not exist",
662                                                                 TypeNameToString(typename))));
663                         }
664                         else
665                         {
666                                 ereport(NOTICE,
667                                                 (errmsg("type \"%s\" does not exist, skipping",
668                                                                 TypeNameToString(typename))));
669                         }
670                         continue;
671                 }
672
673                 typeoid = typeTypeId(tup);
674                 typ = (Form_pg_type) GETSTRUCT(tup);
675
676                 /* Permission check: must own type or its namespace */
677                 if (!pg_type_ownercheck(typeoid, GetUserId()) &&
678                         !pg_namespace_ownercheck(typ->typnamespace, GetUserId()))
679                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
680                                                    format_type_be(typeoid));
681
682                 if (drop->removeType == OBJECT_DOMAIN)
683                 {
684                         /* Check that this is actually a domain */
685                         if (typ->typtype != TYPTYPE_DOMAIN)
686                                 ereport(ERROR,
687                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
688                                                  errmsg("\"%s\" is not a domain",
689                                                                 TypeNameToString(typename))));
690                 }
691
692                 /*
693                  * Note: we need no special check for array types here, as the normal
694                  * treatment of internal dependencies handles it just fine
695                  */
696
697                 object.classId = TypeRelationId;
698                 object.objectId = typeoid;
699                 object.objectSubId = 0;
700
701                 add_exact_object_address(&object, objects);
702
703                 ReleaseSysCache(tup);
704         }
705
706         performMultipleDeletions(objects, drop->behavior);
707
708         free_object_addresses(objects);
709 }
710
711
712 /*
713  * Guts of type deletion.
714  */
715 void
716 RemoveTypeById(Oid typeOid)
717 {
718         Relation        relation;
719         HeapTuple       tup;
720
721         relation = heap_open(TypeRelationId, RowExclusiveLock);
722
723         tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
724         if (!HeapTupleIsValid(tup))
725                 elog(ERROR, "cache lookup failed for type %u", typeOid);
726
727         simple_heap_delete(relation, &tup->t_self);
728
729         /*
730          * If it is an enum, delete the pg_enum entries too; we don't bother with
731          * making dependency entries for those, so it has to be done "by hand"
732          * here.
733          */
734         if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_ENUM)
735                 EnumValuesDelete(typeOid);
736
737         ReleaseSysCache(tup);
738
739         heap_close(relation, RowExclusiveLock);
740 }
741
742
743 /*
744  * DefineDomain
745  *              Registers a new domain.
746  */
747 void
748 DefineDomain(CreateDomainStmt *stmt)
749 {
750         char       *domainName;
751         Oid                     domainNamespace;
752         AclResult       aclresult;
753         int16           internalLength;
754         Oid                     inputProcedure;
755         Oid                     outputProcedure;
756         Oid                     receiveProcedure;
757         Oid                     sendProcedure;
758         Oid                     analyzeProcedure;
759         bool            byValue;
760         char            category;
761         char            delimiter;
762         char            alignment;
763         char            storage;
764         char            typtype;
765         Datum           datum;
766         bool            isnull;
767         char       *defaultValue = NULL;
768         char       *defaultValueBin = NULL;
769         bool            saw_default = false;
770         bool            typNotNull = false;
771         bool            nullDefined = false;
772         int32           typNDims = list_length(stmt->typeName->arrayBounds);
773         HeapTuple       typeTup;
774         List       *schema = stmt->constraints;
775         ListCell   *listptr;
776         Oid                     basetypeoid;
777         Oid                     domainoid;
778         Oid                     old_type_oid;
779         Oid                     domaincoll;
780         Form_pg_type baseType;
781         int32           basetypeMod;
782         Oid                     baseColl;
783
784         /* Convert list of names to a name and namespace */
785         domainNamespace = QualifiedNameGetCreationNamespace(stmt->domainname,
786                                                                                                                 &domainName);
787
788         /* Check we have creation rights in target namespace */
789         aclresult = pg_namespace_aclcheck(domainNamespace, GetUserId(),
790                                                                           ACL_CREATE);
791         if (aclresult != ACLCHECK_OK)
792                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
793                                            get_namespace_name(domainNamespace));
794
795         /*
796          * Check for collision with an existing type name.      If there is one and
797          * it's an autogenerated array, we can rename it out of the way.
798          */
799         old_type_oid = GetSysCacheOid2(TYPENAMENSP,
800                                                                    CStringGetDatum(domainName),
801                                                                    ObjectIdGetDatum(domainNamespace));
802         if (OidIsValid(old_type_oid))
803         {
804                 if (!moveArrayTypeName(old_type_oid, domainName, domainNamespace))
805                         ereport(ERROR,
806                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
807                                          errmsg("type \"%s\" already exists", domainName)));
808         }
809
810         /*
811          * Look up the base type.
812          */
813         typeTup = typenameType(NULL, stmt->typeName, &basetypeMod);
814         baseType = (Form_pg_type) GETSTRUCT(typeTup);
815         basetypeoid = HeapTupleGetOid(typeTup);
816
817         /*
818          * Base type must be a plain base type, another domain or an enum. Domains
819          * over pseudotypes would create a security hole.  Domains over composite
820          * types might be made to work in the future, but not today.
821          */
822         typtype = baseType->typtype;
823         if (typtype != TYPTYPE_BASE &&
824                 typtype != TYPTYPE_DOMAIN &&
825                 typtype != TYPTYPE_ENUM)
826                 ereport(ERROR,
827                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
828                                  errmsg("\"%s\" is not a valid base type for a domain",
829                                                 TypeNameToString(stmt->typeName))));
830
831         /*
832          * Identify the collation if any
833          */
834         baseColl = baseType->typcollation;
835         if (stmt->collClause)
836                 domaincoll = get_collation_oid(stmt->collClause->collname, false);
837         else
838                 domaincoll = baseColl;
839
840         /* Complain if COLLATE is applied to an uncollatable type */
841         if (OidIsValid(domaincoll) && !OidIsValid(baseColl))
842                 ereport(ERROR,
843                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
844                                  errmsg("collations are not supported by type %s",
845                                                 format_type_be(basetypeoid))));
846
847         /* passed by value */
848         byValue = baseType->typbyval;
849
850         /* Required Alignment */
851         alignment = baseType->typalign;
852
853         /* TOAST Strategy */
854         storage = baseType->typstorage;
855
856         /* Storage Length */
857         internalLength = baseType->typlen;
858
859         /* Type Category */
860         category = baseType->typcategory;
861
862         /* Array element Delimiter */
863         delimiter = baseType->typdelim;
864
865         /* I/O Functions */
866         inputProcedure = F_DOMAIN_IN;
867         outputProcedure = baseType->typoutput;
868         receiveProcedure = F_DOMAIN_RECV;
869         sendProcedure = baseType->typsend;
870
871         /* Domains never accept typmods, so no typmodin/typmodout needed */
872
873         /* Analysis function */
874         analyzeProcedure = baseType->typanalyze;
875
876         /* Inherited default value */
877         datum = SysCacheGetAttr(TYPEOID, typeTup,
878                                                         Anum_pg_type_typdefault, &isnull);
879         if (!isnull)
880                 defaultValue = TextDatumGetCString(datum);
881
882         /* Inherited default binary value */
883         datum = SysCacheGetAttr(TYPEOID, typeTup,
884                                                         Anum_pg_type_typdefaultbin, &isnull);
885         if (!isnull)
886                 defaultValueBin = TextDatumGetCString(datum);
887
888         /*
889          * Run through constraints manually to avoid the additional processing
890          * conducted by DefineRelation() and friends.
891          */
892         foreach(listptr, schema)
893         {
894                 Constraint *constr = lfirst(listptr);
895
896                 if (!IsA(constr, Constraint))
897                         elog(ERROR, "unrecognized node type: %d",
898                                  (int) nodeTag(constr));
899                 switch (constr->contype)
900                 {
901                         case CONSTR_DEFAULT:
902
903                                 /*
904                                  * The inherited default value may be overridden by the user
905                                  * with the DEFAULT <expr> clause ... but only once.
906                                  */
907                                 if (saw_default)
908                                         ereport(ERROR,
909                                                         (errcode(ERRCODE_SYNTAX_ERROR),
910                                                          errmsg("multiple default expressions")));
911                                 saw_default = true;
912
913                                 if (constr->raw_expr)
914                                 {
915                                         ParseState *pstate;
916                                         Node       *defaultExpr;
917
918                                         /* Create a dummy ParseState for transformExpr */
919                                         pstate = make_parsestate(NULL);
920
921                                         /*
922                                          * Cook the constr->raw_expr into an expression. Note:
923                                          * name is strictly for error message
924                                          */
925                                         defaultExpr = cookDefault(pstate, constr->raw_expr,
926                                                                                           basetypeoid,
927                                                                                           basetypeMod,
928                                                                                           domainName);
929
930                                         /*
931                                          * If the expression is just a NULL constant, we treat it
932                                          * like not having a default.
933                                          *
934                                          * Note that if the basetype is another domain, we'll see
935                                          * a CoerceToDomain expr here and not discard the default.
936                                          * This is critical because the domain default needs to be
937                                          * retained to override any default that the base domain
938                                          * might have.
939                                          */
940                                         if (defaultExpr == NULL ||
941                                                 (IsA(defaultExpr, Const) &&
942                                                  ((Const *) defaultExpr)->constisnull))
943                                         {
944                                                 defaultValue = NULL;
945                                                 defaultValueBin = NULL;
946                                         }
947                                         else
948                                         {
949                                                 /*
950                                                  * Expression must be stored as a nodeToString result,
951                                                  * but we also require a valid textual representation
952                                                  * (mainly to make life easier for pg_dump).
953                                                  */
954                                                 defaultValue =
955                                                         deparse_expression(defaultExpr,
956                                                                                            deparse_context_for(domainName,
957                                                                                                                                  InvalidOid),
958                                                                                            false, false);
959                                                 defaultValueBin = nodeToString(defaultExpr);
960                                         }
961                                 }
962                                 else
963                                 {
964                                         /* No default (can this still happen?) */
965                                         defaultValue = NULL;
966                                         defaultValueBin = NULL;
967                                 }
968                                 break;
969
970                         case CONSTR_NOTNULL:
971                                 if (nullDefined && !typNotNull)
972                                         ereport(ERROR,
973                                                         (errcode(ERRCODE_SYNTAX_ERROR),
974                                                    errmsg("conflicting NULL/NOT NULL constraints")));
975                                 typNotNull = true;
976                                 nullDefined = true;
977                                 break;
978
979                         case CONSTR_NULL:
980                                 if (nullDefined && typNotNull)
981                                         ereport(ERROR,
982                                                         (errcode(ERRCODE_SYNTAX_ERROR),
983                                                    errmsg("conflicting NULL/NOT NULL constraints")));
984                                 typNotNull = false;
985                                 nullDefined = true;
986                                 break;
987
988                         case CONSTR_CHECK:
989
990                                 /*
991                                  * Check constraints are handled after domain creation, as
992                                  * they require the Oid of the domain
993                                  */
994                                 break;
995
996                                 /*
997                                  * All else are error cases
998                                  */
999                         case CONSTR_UNIQUE:
1000                                 ereport(ERROR,
1001                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1002                                          errmsg("unique constraints not possible for domains")));
1003                                 break;
1004
1005                         case CONSTR_PRIMARY:
1006                                 ereport(ERROR,
1007                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1008                                 errmsg("primary key constraints not possible for domains")));
1009                                 break;
1010
1011                         case CONSTR_EXCLUSION:
1012                                 ereport(ERROR,
1013                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1014                                   errmsg("exclusion constraints not possible for domains")));
1015                                 break;
1016
1017                         case CONSTR_FOREIGN:
1018                                 ereport(ERROR,
1019                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1020                                 errmsg("foreign key constraints not possible for domains")));
1021                                 break;
1022
1023                         case CONSTR_ATTR_DEFERRABLE:
1024                         case CONSTR_ATTR_NOT_DEFERRABLE:
1025                         case CONSTR_ATTR_DEFERRED:
1026                         case CONSTR_ATTR_IMMEDIATE:
1027                                 ereport(ERROR,
1028                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1029                                                  errmsg("specifying constraint deferrability not supported for domains")));
1030                                 break;
1031
1032                         default:
1033                                 elog(ERROR, "unrecognized constraint subtype: %d",
1034                                          (int) constr->contype);
1035                                 break;
1036                 }
1037         }
1038
1039         /*
1040          * Have TypeCreate do all the real work.
1041          */
1042         domainoid =
1043                 TypeCreate(InvalidOid,  /* no predetermined type OID */
1044                                    domainName,  /* type name */
1045                                    domainNamespace,             /* namespace */
1046                                    InvalidOid,  /* relation oid (n/a here) */
1047                                    0,                   /* relation kind (ditto) */
1048                                    GetUserId(), /* owner's ID */
1049                                    internalLength,              /* internal size */
1050                                    TYPTYPE_DOMAIN,              /* type-type (domain type) */
1051                                    category,    /* type-category */
1052                                    false,               /* domain types are never preferred */
1053                                    delimiter,   /* array element delimiter */
1054                                    inputProcedure,              /* input procedure */
1055                                    outputProcedure,             /* output procedure */
1056                                    receiveProcedure,    /* receive procedure */
1057                                    sendProcedure,               /* send procedure */
1058                                    InvalidOid,  /* typmodin procedure - none */
1059                                    InvalidOid,  /* typmodout procedure - none */
1060                                    analyzeProcedure,    /* analyze procedure */
1061                                    InvalidOid,  /* no array element type */
1062                                    false,               /* this isn't an array */
1063                                    InvalidOid,  /* no arrays for domains (yet) */
1064                                    basetypeoid, /* base type ID */
1065                                    defaultValue,        /* default type value (text) */
1066                                    defaultValueBin,             /* default type value (binary) */
1067                                    byValue,             /* passed by value */
1068                                    alignment,   /* required alignment */
1069                                    storage,             /* TOAST strategy */
1070                                    basetypeMod, /* typeMod value */
1071                                    typNDims,    /* Array dimensions for base type */
1072                                    typNotNull,  /* Type NOT NULL */
1073                                    domaincoll); /* type's collation */
1074
1075         /*
1076          * Process constraints which refer to the domain ID returned by TypeCreate
1077          */
1078         foreach(listptr, schema)
1079         {
1080                 Constraint *constr = lfirst(listptr);
1081
1082                 /* it must be a Constraint, per check above */
1083
1084                 switch (constr->contype)
1085                 {
1086                         case CONSTR_CHECK:
1087                                 domainAddConstraint(domainoid, domainNamespace,
1088                                                                         basetypeoid, basetypeMod,
1089                                                                         constr, domainName);
1090                                 break;
1091
1092                                 /* Other constraint types were fully processed above */
1093
1094                         default:
1095                                 break;
1096                 }
1097
1098                 /* CCI so we can detect duplicate constraint names */
1099                 CommandCounterIncrement();
1100         }
1101
1102         /*
1103          * Now we can clean up.
1104          */
1105         ReleaseSysCache(typeTup);
1106 }
1107
1108
1109 /*
1110  * DefineEnum
1111  *              Registers a new enum.
1112  */
1113 void
1114 DefineEnum(CreateEnumStmt *stmt)
1115 {
1116         char       *enumName;
1117         char       *enumArrayName;
1118         Oid                     enumNamespace;
1119         Oid                     enumTypeOid;
1120         AclResult       aclresult;
1121         Oid                     old_type_oid;
1122         Oid                     enumArrayOid;
1123
1124         /* Convert list of names to a name and namespace */
1125         enumNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
1126                                                                                                           &enumName);
1127
1128         /* Check we have creation rights in target namespace */
1129         aclresult = pg_namespace_aclcheck(enumNamespace, GetUserId(), ACL_CREATE);
1130         if (aclresult != ACLCHECK_OK)
1131                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1132                                            get_namespace_name(enumNamespace));
1133
1134         /*
1135          * Check for collision with an existing type name.      If there is one and
1136          * it's an autogenerated array, we can rename it out of the way.
1137          */
1138         old_type_oid = GetSysCacheOid2(TYPENAMENSP,
1139                                                                    CStringGetDatum(enumName),
1140                                                                    ObjectIdGetDatum(enumNamespace));
1141         if (OidIsValid(old_type_oid))
1142         {
1143                 if (!moveArrayTypeName(old_type_oid, enumName, enumNamespace))
1144                         ereport(ERROR,
1145                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
1146                                          errmsg("type \"%s\" already exists", enumName)));
1147         }
1148
1149         enumArrayOid = AssignTypeArrayOid();
1150
1151         /* Create the pg_type entry */
1152         enumTypeOid =
1153                 TypeCreate(InvalidOid,  /* no predetermined type OID */
1154                                    enumName,    /* type name */
1155                                    enumNamespace,               /* namespace */
1156                                    InvalidOid,  /* relation oid (n/a here) */
1157                                    0,                   /* relation kind (ditto) */
1158                                    GetUserId(), /* owner's ID */
1159                                    sizeof(Oid), /* internal size */
1160                                    TYPTYPE_ENUM,        /* type-type (enum type) */
1161                                    TYPCATEGORY_ENUM,    /* type-category (enum type) */
1162                                    false,               /* enum types are never preferred */
1163                                    DEFAULT_TYPDELIM,    /* array element delimiter */
1164                                    F_ENUM_IN,   /* input procedure */
1165                                    F_ENUM_OUT,  /* output procedure */
1166                                    F_ENUM_RECV, /* receive procedure */
1167                                    F_ENUM_SEND, /* send procedure */
1168                                    InvalidOid,  /* typmodin procedure - none */
1169                                    InvalidOid,  /* typmodout procedure - none */
1170                                    InvalidOid,  /* analyze procedure - default */
1171                                    InvalidOid,  /* element type ID */
1172                                    false,               /* this is not an array type */
1173                                    enumArrayOid,        /* array type we are about to create */
1174                                    InvalidOid,  /* base type ID (only for domains) */
1175                                    NULL,                /* never a default type value */
1176                                    NULL,                /* binary default isn't sent either */
1177                                    true,                /* always passed by value */
1178                                    'i',                 /* int alignment */
1179                                    'p',                 /* TOAST strategy always plain */
1180                                    -1,                  /* typMod (Domains only) */
1181                                    0,                   /* Array dimensions of typbasetype */
1182                                    false,               /* Type NOT NULL */
1183                                    InvalidOid); /* type's collation */
1184
1185         /* Enter the enum's values into pg_enum */
1186         EnumValuesCreate(enumTypeOid, stmt->vals);
1187
1188         /*
1189          * Create the array type that goes with it.
1190          */
1191         enumArrayName = makeArrayTypeName(enumName, enumNamespace);
1192
1193         TypeCreate(enumArrayOid,        /* force assignment of this type OID */
1194                            enumArrayName,       /* type name */
1195                            enumNamespace,       /* namespace */
1196                            InvalidOid,          /* relation oid (n/a here) */
1197                            0,                           /* relation kind (ditto) */
1198                            GetUserId(),         /* owner's ID */
1199                            -1,                          /* internal size (always varlena) */
1200                            TYPTYPE_BASE,        /* type-type (base type) */
1201                            TYPCATEGORY_ARRAY,           /* type-category (array) */
1202                            false,                       /* array types are never preferred */
1203                            DEFAULT_TYPDELIM,    /* array element delimiter */
1204                            F_ARRAY_IN,          /* input procedure */
1205                            F_ARRAY_OUT,         /* output procedure */
1206                            F_ARRAY_RECV,        /* receive procedure */
1207                            F_ARRAY_SEND,        /* send procedure */
1208                            InvalidOid,          /* typmodin procedure - none */
1209                            InvalidOid,          /* typmodout procedure - none */
1210                            InvalidOid,          /* analyze procedure - default */
1211                            enumTypeOid,         /* element type ID */
1212                            true,                        /* yes this is an array type */
1213                            InvalidOid,          /* no further array type */
1214                            InvalidOid,          /* base type ID */
1215                            NULL,                        /* never a default type value */
1216                            NULL,                        /* binary default isn't sent either */
1217                            false,                       /* never passed by value */
1218                            'i',                         /* enums have align i, so do their arrays */
1219                            'x',                         /* ARRAY is always toastable */
1220                            -1,                          /* typMod (Domains only) */
1221                            0,                           /* Array dimensions of typbasetype */
1222                            false,                       /* Type NOT NULL */
1223                            InvalidOid);         /* type's collation */
1224
1225         pfree(enumArrayName);
1226 }
1227
1228 /*
1229  * AlterEnum
1230  *              Adds a new label to an existing enum.
1231  */
1232 void
1233 AlterEnum(AlterEnumStmt *stmt)
1234 {
1235         Oid                     enum_type_oid;
1236         TypeName   *typename;
1237         HeapTuple       tup;
1238
1239         /* Make a TypeName so we can use standard type lookup machinery */
1240         typename = makeTypeNameFromNameList(stmt->typeName);
1241         enum_type_oid = typenameTypeId(NULL, typename);
1242
1243         tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enum_type_oid));
1244         if (!HeapTupleIsValid(tup))
1245                 elog(ERROR, "cache lookup failed for type %u", enum_type_oid);
1246
1247         /* Check it's an enum and check user has permission to ALTER the enum */
1248         checkEnumOwner(tup);
1249
1250         /* Add the new label */
1251         AddEnumLabel(enum_type_oid, stmt->newVal,
1252                                  stmt->newValNeighbor, stmt->newValIsAfter);
1253
1254         ReleaseSysCache(tup);
1255 }
1256
1257
1258 /*
1259  * checkEnumOwner
1260  *
1261  * Check that the type is actually an enum and that the current user
1262  * has permission to do ALTER TYPE on it.  Throw an error if not.
1263  */
1264 static void
1265 checkEnumOwner(HeapTuple tup)
1266 {
1267         Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
1268
1269         /* Check that this is actually an enum */
1270         if (typTup->typtype != TYPTYPE_ENUM)
1271                 ereport(ERROR,
1272                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1273                                  errmsg("%s is not an enum",
1274                                                 format_type_be(HeapTupleGetOid(tup)))));
1275
1276         /* Permission check: must own type */
1277         if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
1278                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
1279                                            format_type_be(HeapTupleGetOid(tup)));
1280 }
1281
1282
1283 /*
1284  * Find suitable I/O functions for a type.
1285  *
1286  * typeOid is the type's OID (which will already exist, if only as a shell
1287  * type).
1288  */
1289
1290 static Oid
1291 findTypeInputFunction(List *procname, Oid typeOid)
1292 {
1293         Oid                     argList[3];
1294         Oid                     procOid;
1295
1296         /*
1297          * Input functions can take a single argument of type CSTRING, or three
1298          * arguments (string, typioparam OID, typmod).
1299          *
1300          * For backwards compatibility we allow OPAQUE in place of CSTRING; if we
1301          * see this, we issue a warning and fix up the pg_proc entry.
1302          */
1303         argList[0] = CSTRINGOID;
1304
1305         procOid = LookupFuncName(procname, 1, argList, true);
1306         if (OidIsValid(procOid))
1307                 return procOid;
1308
1309         argList[1] = OIDOID;
1310         argList[2] = INT4OID;
1311
1312         procOid = LookupFuncName(procname, 3, argList, true);
1313         if (OidIsValid(procOid))
1314                 return procOid;
1315
1316         /* No luck, try it with OPAQUE */
1317         argList[0] = OPAQUEOID;
1318
1319         procOid = LookupFuncName(procname, 1, argList, true);
1320
1321         if (!OidIsValid(procOid))
1322         {
1323                 argList[1] = OIDOID;
1324                 argList[2] = INT4OID;
1325
1326                 procOid = LookupFuncName(procname, 3, argList, true);
1327         }
1328
1329         if (OidIsValid(procOid))
1330         {
1331                 /* Found, but must complain and fix the pg_proc entry */
1332                 ereport(WARNING,
1333                                 (errmsg("changing argument type of function %s from \"opaque\" to \"cstring\"",
1334                                                 NameListToString(procname))));
1335                 SetFunctionArgType(procOid, 0, CSTRINGOID);
1336
1337                 /*
1338                  * Need CommandCounterIncrement since DefineType will likely try to
1339                  * alter the pg_proc tuple again.
1340                  */
1341                 CommandCounterIncrement();
1342
1343                 return procOid;
1344         }
1345
1346         /* Use CSTRING (preferred) in the error message */
1347         argList[0] = CSTRINGOID;
1348
1349         ereport(ERROR,
1350                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1351                          errmsg("function %s does not exist",
1352                                         func_signature_string(procname, 1, NIL, argList))));
1353
1354         return InvalidOid;                      /* keep compiler quiet */
1355 }
1356
1357 static Oid
1358 findTypeOutputFunction(List *procname, Oid typeOid)
1359 {
1360         Oid                     argList[1];
1361         Oid                     procOid;
1362
1363         /*
1364          * Output functions can take a single argument of the type.
1365          *
1366          * For backwards compatibility we allow OPAQUE in place of the actual type
1367          * name; if we see this, we issue a warning and fix up the pg_proc entry.
1368          */
1369         argList[0] = typeOid;
1370
1371         procOid = LookupFuncName(procname, 1, argList, true);
1372         if (OidIsValid(procOid))
1373                 return procOid;
1374
1375         /* No luck, try it with OPAQUE */
1376         argList[0] = OPAQUEOID;
1377
1378         procOid = LookupFuncName(procname, 1, argList, true);
1379
1380         if (OidIsValid(procOid))
1381         {
1382                 /* Found, but must complain and fix the pg_proc entry */
1383                 ereport(WARNING,
1384                 (errmsg("changing argument type of function %s from \"opaque\" to %s",
1385                                 NameListToString(procname), format_type_be(typeOid))));
1386                 SetFunctionArgType(procOid, 0, typeOid);
1387
1388                 /*
1389                  * Need CommandCounterIncrement since DefineType will likely try to
1390                  * alter the pg_proc tuple again.
1391                  */
1392                 CommandCounterIncrement();
1393
1394                 return procOid;
1395         }
1396
1397         /* Use type name, not OPAQUE, in the failure message. */
1398         argList[0] = typeOid;
1399
1400         ereport(ERROR,
1401                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1402                          errmsg("function %s does not exist",
1403                                         func_signature_string(procname, 1, NIL, argList))));
1404
1405         return InvalidOid;                      /* keep compiler quiet */
1406 }
1407
1408 static Oid
1409 findTypeReceiveFunction(List *procname, Oid typeOid)
1410 {
1411         Oid                     argList[3];
1412         Oid                     procOid;
1413
1414         /*
1415          * Receive functions can take a single argument of type INTERNAL, or three
1416          * arguments (internal, typioparam OID, typmod).
1417          */
1418         argList[0] = INTERNALOID;
1419
1420         procOid = LookupFuncName(procname, 1, argList, true);
1421         if (OidIsValid(procOid))
1422                 return procOid;
1423
1424         argList[1] = OIDOID;
1425         argList[2] = INT4OID;
1426
1427         procOid = LookupFuncName(procname, 3, argList, true);
1428         if (OidIsValid(procOid))
1429                 return procOid;
1430
1431         ereport(ERROR,
1432                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1433                          errmsg("function %s does not exist",
1434                                         func_signature_string(procname, 1, NIL, argList))));
1435
1436         return InvalidOid;                      /* keep compiler quiet */
1437 }
1438
1439 static Oid
1440 findTypeSendFunction(List *procname, Oid typeOid)
1441 {
1442         Oid                     argList[1];
1443         Oid                     procOid;
1444
1445         /*
1446          * Send functions can take a single argument of the type.
1447          */
1448         argList[0] = typeOid;
1449
1450         procOid = LookupFuncName(procname, 1, argList, true);
1451         if (OidIsValid(procOid))
1452                 return procOid;
1453
1454         ereport(ERROR,
1455                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1456                          errmsg("function %s does not exist",
1457                                         func_signature_string(procname, 1, NIL, argList))));
1458
1459         return InvalidOid;                      /* keep compiler quiet */
1460 }
1461
1462 static Oid
1463 findTypeTypmodinFunction(List *procname)
1464 {
1465         Oid                     argList[1];
1466         Oid                     procOid;
1467
1468         /*
1469          * typmodin functions always take one cstring[] argument and return int4.
1470          */
1471         argList[0] = CSTRINGARRAYOID;
1472
1473         procOid = LookupFuncName(procname, 1, argList, true);
1474         if (!OidIsValid(procOid))
1475                 ereport(ERROR,
1476                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1477                                  errmsg("function %s does not exist",
1478                                                 func_signature_string(procname, 1, NIL, argList))));
1479
1480         if (get_func_rettype(procOid) != INT4OID)
1481                 ereport(ERROR,
1482                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1483                                  errmsg("typmod_in function %s must return type \"integer\"",
1484                                                 NameListToString(procname))));
1485
1486         return procOid;
1487 }
1488
1489 static Oid
1490 findTypeTypmodoutFunction(List *procname)
1491 {
1492         Oid                     argList[1];
1493         Oid                     procOid;
1494
1495         /*
1496          * typmodout functions always take one int4 argument and return cstring.
1497          */
1498         argList[0] = INT4OID;
1499
1500         procOid = LookupFuncName(procname, 1, argList, true);
1501         if (!OidIsValid(procOid))
1502                 ereport(ERROR,
1503                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1504                                  errmsg("function %s does not exist",
1505                                                 func_signature_string(procname, 1, NIL, argList))));
1506
1507         if (get_func_rettype(procOid) != CSTRINGOID)
1508                 ereport(ERROR,
1509                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1510                                  errmsg("typmod_out function %s must return type \"cstring\"",
1511                                                 NameListToString(procname))));
1512
1513         return procOid;
1514 }
1515
1516 static Oid
1517 findTypeAnalyzeFunction(List *procname, Oid typeOid)
1518 {
1519         Oid                     argList[1];
1520         Oid                     procOid;
1521
1522         /*
1523          * Analyze functions always take one INTERNAL argument and return bool.
1524          */
1525         argList[0] = INTERNALOID;
1526
1527         procOid = LookupFuncName(procname, 1, argList, true);
1528         if (!OidIsValid(procOid))
1529                 ereport(ERROR,
1530                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1531                                  errmsg("function %s does not exist",
1532                                                 func_signature_string(procname, 1, NIL, argList))));
1533
1534         if (get_func_rettype(procOid) != BOOLOID)
1535                 ereport(ERROR,
1536                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1537                           errmsg("type analyze function %s must return type \"boolean\"",
1538                                          NameListToString(procname))));
1539
1540         return procOid;
1541 }
1542
1543 /*
1544  *      AssignTypeArrayOid
1545  *
1546  *      Pre-assign the type's array OID for use in pg_type.typarray
1547  */
1548 Oid
1549 AssignTypeArrayOid(void)
1550 {
1551         Oid                     type_array_oid;
1552
1553         /* Use binary-upgrade override for pg_type.typarray, if supplied. */
1554         if (IsBinaryUpgrade && OidIsValid(binary_upgrade_next_array_pg_type_oid))
1555         {
1556                 type_array_oid = binary_upgrade_next_array_pg_type_oid;
1557                 binary_upgrade_next_array_pg_type_oid = InvalidOid;
1558         }
1559         else
1560         {
1561                 Relation        pg_type = heap_open(TypeRelationId, AccessShareLock);
1562
1563                 type_array_oid = GetNewOid(pg_type);
1564                 heap_close(pg_type, AccessShareLock);
1565         }
1566
1567         return type_array_oid;
1568 }
1569
1570
1571 /*-------------------------------------------------------------------
1572  * DefineCompositeType
1573  *
1574  * Create a Composite Type relation.
1575  * `DefineRelation' does all the work, we just provide the correct
1576  * arguments!
1577  *
1578  * If the relation already exists, then 'DefineRelation' will abort
1579  * the xact...
1580  *
1581  * DefineCompositeType returns relid for use when creating
1582  * an implicit composite type during function creation
1583  *-------------------------------------------------------------------
1584  */
1585 Oid
1586 DefineCompositeType(const RangeVar *typevar, List *coldeflist)
1587 {
1588         CreateStmt *createStmt = makeNode(CreateStmt);
1589         Oid                     old_type_oid;
1590         Oid                     typeNamespace;
1591         Oid                     relid;
1592
1593         /*
1594          * now set the parameters for keys/inheritance etc. All of these are
1595          * uninteresting for composite types...
1596          */
1597         createStmt->relation = (RangeVar *) typevar;
1598         createStmt->tableElts = coldeflist;
1599         createStmt->inhRelations = NIL;
1600         createStmt->constraints = NIL;
1601         createStmt->options = list_make1(defWithOids(false));
1602         createStmt->oncommit = ONCOMMIT_NOOP;
1603         createStmt->tablespacename = NULL;
1604         createStmt->if_not_exists = false;
1605
1606         /*
1607          * Check for collision with an existing type name. If there is one and
1608          * it's an autogenerated array, we can rename it out of the way.  This
1609          * check is here mainly to get a better error message about a "type"
1610          * instead of below about a "relation".
1611          */
1612         typeNamespace = RangeVarGetCreationNamespace(createStmt->relation);
1613         RangeVarAdjustRelationPersistence(createStmt->relation, typeNamespace);
1614         old_type_oid =
1615                 GetSysCacheOid2(TYPENAMENSP,
1616                                                 CStringGetDatum(createStmt->relation->relname),
1617                                                 ObjectIdGetDatum(typeNamespace));
1618         if (OidIsValid(old_type_oid))
1619         {
1620                 if (!moveArrayTypeName(old_type_oid, createStmt->relation->relname, typeNamespace))
1621                         ereport(ERROR,
1622                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
1623                                          errmsg("type \"%s\" already exists", createStmt->relation->relname)));
1624         }
1625
1626         /*
1627          * Finally create the relation.  This also creates the type.
1628          */
1629         relid = DefineRelation(createStmt, RELKIND_COMPOSITE_TYPE, InvalidOid);
1630         Assert(relid != InvalidOid);
1631         return relid;
1632 }
1633
1634 /*
1635  * AlterDomainDefault
1636  *
1637  * Routine implementing ALTER DOMAIN SET/DROP DEFAULT statements.
1638  */
1639 void
1640 AlterDomainDefault(List *names, Node *defaultRaw)
1641 {
1642         TypeName   *typename;
1643         Oid                     domainoid;
1644         HeapTuple       tup;
1645         ParseState *pstate;
1646         Relation        rel;
1647         char       *defaultValue;
1648         Node       *defaultExpr = NULL;         /* NULL if no default specified */
1649         Datum           new_record[Natts_pg_type];
1650         bool            new_record_nulls[Natts_pg_type];
1651         bool            new_record_repl[Natts_pg_type];
1652         HeapTuple       newtuple;
1653         Form_pg_type typTup;
1654
1655         /* Make a TypeName so we can use standard type lookup machinery */
1656         typename = makeTypeNameFromNameList(names);
1657         domainoid = typenameTypeId(NULL, typename);
1658
1659         /* Look up the domain in the type table */
1660         rel = heap_open(TypeRelationId, RowExclusiveLock);
1661
1662         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
1663         if (!HeapTupleIsValid(tup))
1664                 elog(ERROR, "cache lookup failed for type %u", domainoid);
1665         typTup = (Form_pg_type) GETSTRUCT(tup);
1666
1667         /* Check it's a domain and check user has permission for ALTER DOMAIN */
1668         checkDomainOwner(tup);
1669
1670         /* Setup new tuple */
1671         MemSet(new_record, (Datum) 0, sizeof(new_record));
1672         MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1673         MemSet(new_record_repl, false, sizeof(new_record_repl));
1674
1675         /* Store the new default into the tuple */
1676         if (defaultRaw)
1677         {
1678                 /* Create a dummy ParseState for transformExpr */
1679                 pstate = make_parsestate(NULL);
1680
1681                 /*
1682                  * Cook the colDef->raw_expr into an expression. Note: Name is
1683                  * strictly for error message
1684                  */
1685                 defaultExpr = cookDefault(pstate, defaultRaw,
1686                                                                   typTup->typbasetype,
1687                                                                   typTup->typtypmod,
1688                                                                   NameStr(typTup->typname));
1689
1690                 /*
1691                  * If the expression is just a NULL constant, we treat the command
1692                  * like ALTER ... DROP DEFAULT.  (But see note for same test in
1693                  * DefineDomain.)
1694                  */
1695                 if (defaultExpr == NULL ||
1696                         (IsA(defaultExpr, Const) &&((Const *) defaultExpr)->constisnull))
1697                 {
1698                         /* Default is NULL, drop it */
1699                         new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
1700                         new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
1701                         new_record_nulls[Anum_pg_type_typdefault - 1] = true;
1702                         new_record_repl[Anum_pg_type_typdefault - 1] = true;
1703                 }
1704                 else
1705                 {
1706                         /*
1707                          * Expression must be stored as a nodeToString result, but we also
1708                          * require a valid textual representation (mainly to make life
1709                          * easier for pg_dump).
1710                          */
1711                         defaultValue = deparse_expression(defaultExpr,
1712                                                                 deparse_context_for(NameStr(typTup->typname),
1713                                                                                                         InvalidOid),
1714                                                                                           false, false);
1715
1716                         /*
1717                          * Form an updated tuple with the new default and write it back.
1718                          */
1719                         new_record[Anum_pg_type_typdefaultbin - 1] = CStringGetTextDatum(nodeToString(defaultExpr));
1720
1721                         new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
1722                         new_record[Anum_pg_type_typdefault - 1] = CStringGetTextDatum(defaultValue);
1723                         new_record_repl[Anum_pg_type_typdefault - 1] = true;
1724                 }
1725         }
1726         else
1727         {
1728                 /* ALTER ... DROP DEFAULT */
1729                 new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
1730                 new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
1731                 new_record_nulls[Anum_pg_type_typdefault - 1] = true;
1732                 new_record_repl[Anum_pg_type_typdefault - 1] = true;
1733         }
1734
1735         newtuple = heap_modify_tuple(tup, RelationGetDescr(rel),
1736                                                                  new_record, new_record_nulls,
1737                                                                  new_record_repl);
1738
1739         simple_heap_update(rel, &tup->t_self, newtuple);
1740
1741         CatalogUpdateIndexes(rel, newtuple);
1742
1743         /* Rebuild dependencies */
1744         GenerateTypeDependencies(typTup->typnamespace,
1745                                                          domainoid,
1746                                                          InvalidOid,            /* typrelid is n/a */
1747                                                          0, /* relation kind is n/a */
1748                                                          typTup->typowner,
1749                                                          typTup->typinput,
1750                                                          typTup->typoutput,
1751                                                          typTup->typreceive,
1752                                                          typTup->typsend,
1753                                                          typTup->typmodin,
1754                                                          typTup->typmodout,
1755                                                          typTup->typanalyze,
1756                                                          InvalidOid,
1757                                                          false,         /* a domain isn't an implicit array */
1758                                                          typTup->typbasetype,
1759                                                          typTup->typcollation,
1760                                                          defaultExpr,
1761                                                          true);         /* Rebuild is true */
1762
1763         /* Clean up */
1764         heap_close(rel, NoLock);
1765         heap_freetuple(newtuple);
1766 }
1767
1768 /*
1769  * AlterDomainNotNull
1770  *
1771  * Routine implementing ALTER DOMAIN SET/DROP NOT NULL statements.
1772  */
1773 void
1774 AlterDomainNotNull(List *names, bool notNull)
1775 {
1776         TypeName   *typename;
1777         Oid                     domainoid;
1778         Relation        typrel;
1779         HeapTuple       tup;
1780         Form_pg_type typTup;
1781
1782         /* Make a TypeName so we can use standard type lookup machinery */
1783         typename = makeTypeNameFromNameList(names);
1784         domainoid = typenameTypeId(NULL, typename);
1785
1786         /* Look up the domain in the type table */
1787         typrel = heap_open(TypeRelationId, RowExclusiveLock);
1788
1789         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
1790         if (!HeapTupleIsValid(tup))
1791                 elog(ERROR, "cache lookup failed for type %u", domainoid);
1792         typTup = (Form_pg_type) GETSTRUCT(tup);
1793
1794         /* Check it's a domain and check user has permission for ALTER DOMAIN */
1795         checkDomainOwner(tup);
1796
1797         /* Is the domain already set to the desired constraint? */
1798         if (typTup->typnotnull == notNull)
1799         {
1800                 heap_close(typrel, RowExclusiveLock);
1801                 return;
1802         }
1803
1804         /* Adding a NOT NULL constraint requires checking existing columns */
1805         if (notNull)
1806         {
1807                 List       *rels;
1808                 ListCell   *rt;
1809
1810                 /* Fetch relation list with attributes based on this domain */
1811                 /* ShareLock is sufficient to prevent concurrent data changes */
1812
1813                 rels = get_rels_with_domain(domainoid, ShareLock);
1814
1815                 foreach(rt, rels)
1816                 {
1817                         RelToCheck *rtc = (RelToCheck *) lfirst(rt);
1818                         Relation        testrel = rtc->rel;
1819                         TupleDesc       tupdesc = RelationGetDescr(testrel);
1820                         HeapScanDesc scan;
1821                         HeapTuple       tuple;
1822
1823                         /* Scan all tuples in this relation */
1824                         scan = heap_beginscan(testrel, SnapshotNow, 0, NULL);
1825                         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1826                         {
1827                                 int                     i;
1828
1829                                 /* Test attributes that are of the domain */
1830                                 for (i = 0; i < rtc->natts; i++)
1831                                 {
1832                                         int                     attnum = rtc->atts[i];
1833
1834                                         if (heap_attisnull(tuple, attnum))
1835                                                 ereport(ERROR,
1836                                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1837                                                                  errmsg("column \"%s\" of table \"%s\" contains null values",
1838                                                                 NameStr(tupdesc->attrs[attnum - 1]->attname),
1839                                                                                 RelationGetRelationName(testrel))));
1840                                 }
1841                         }
1842                         heap_endscan(scan);
1843
1844                         /* Close each rel after processing, but keep lock */
1845                         heap_close(testrel, NoLock);
1846                 }
1847         }
1848
1849         /*
1850          * Okay to update pg_type row.  We can scribble on typTup because it's a
1851          * copy.
1852          */
1853         typTup->typnotnull = notNull;
1854
1855         simple_heap_update(typrel, &tup->t_self, tup);
1856
1857         CatalogUpdateIndexes(typrel, tup);
1858
1859         /* Clean up */
1860         heap_freetuple(tup);
1861         heap_close(typrel, RowExclusiveLock);
1862 }
1863
1864 /*
1865  * AlterDomainDropConstraint
1866  *
1867  * Implements the ALTER DOMAIN DROP CONSTRAINT statement
1868  */
1869 void
1870 AlterDomainDropConstraint(List *names, const char *constrName,
1871                                                   DropBehavior behavior)
1872 {
1873         TypeName   *typename;
1874         Oid                     domainoid;
1875         HeapTuple       tup;
1876         Relation        rel;
1877         Relation        conrel;
1878         SysScanDesc conscan;
1879         ScanKeyData key[1];
1880         HeapTuple       contup;
1881
1882         /* Make a TypeName so we can use standard type lookup machinery */
1883         typename = makeTypeNameFromNameList(names);
1884         domainoid = typenameTypeId(NULL, typename);
1885
1886         /* Look up the domain in the type table */
1887         rel = heap_open(TypeRelationId, RowExclusiveLock);
1888
1889         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
1890         if (!HeapTupleIsValid(tup))
1891                 elog(ERROR, "cache lookup failed for type %u", domainoid);
1892
1893         /* Check it's a domain and check user has permission for ALTER DOMAIN */
1894         checkDomainOwner(tup);
1895
1896         /* Grab an appropriate lock on the pg_constraint relation */
1897         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
1898
1899         /* Use the index to scan only constraints of the target relation */
1900         ScanKeyInit(&key[0],
1901                                 Anum_pg_constraint_contypid,
1902                                 BTEqualStrategyNumber, F_OIDEQ,
1903                                 ObjectIdGetDatum(HeapTupleGetOid(tup)));
1904
1905         conscan = systable_beginscan(conrel, ConstraintTypidIndexId, true,
1906                                                                  SnapshotNow, 1, key);
1907
1908         /*
1909          * Scan over the result set, removing any matching entries.
1910          */
1911         while ((contup = systable_getnext(conscan)) != NULL)
1912         {
1913                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
1914
1915                 if (strcmp(NameStr(con->conname), constrName) == 0)
1916                 {
1917                         ObjectAddress conobj;
1918
1919                         conobj.classId = ConstraintRelationId;
1920                         conobj.objectId = HeapTupleGetOid(contup);
1921                         conobj.objectSubId = 0;
1922
1923                         performDeletion(&conobj, behavior);
1924                 }
1925         }
1926         /* Clean up after the scan */
1927         systable_endscan(conscan);
1928         heap_close(conrel, RowExclusiveLock);
1929
1930         heap_close(rel, NoLock);
1931 }
1932
1933 /*
1934  * AlterDomainAddConstraint
1935  *
1936  * Implements the ALTER DOMAIN .. ADD CONSTRAINT statement.
1937  */
1938 void
1939 AlterDomainAddConstraint(List *names, Node *newConstraint)
1940 {
1941         TypeName   *typename;
1942         Oid                     domainoid;
1943         Relation        typrel;
1944         HeapTuple       tup;
1945         Form_pg_type typTup;
1946         Constraint *constr;
1947         char       *ccbin;
1948
1949         /* Make a TypeName so we can use standard type lookup machinery */
1950         typename = makeTypeNameFromNameList(names);
1951         domainoid = typenameTypeId(NULL, typename);
1952
1953         /* Look up the domain in the type table */
1954         typrel = heap_open(TypeRelationId, RowExclusiveLock);
1955
1956         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
1957         if (!HeapTupleIsValid(tup))
1958                 elog(ERROR, "cache lookup failed for type %u", domainoid);
1959         typTup = (Form_pg_type) GETSTRUCT(tup);
1960
1961         /* Check it's a domain and check user has permission for ALTER DOMAIN */
1962         checkDomainOwner(tup);
1963
1964         if (!IsA(newConstraint, Constraint))
1965                 elog(ERROR, "unrecognized node type: %d",
1966                          (int) nodeTag(newConstraint));
1967
1968         constr = (Constraint *) newConstraint;
1969
1970         switch (constr->contype)
1971         {
1972                 case CONSTR_CHECK:
1973                         /* processed below */
1974                         break;
1975
1976                 case CONSTR_UNIQUE:
1977                         ereport(ERROR,
1978                                         (errcode(ERRCODE_SYNTAX_ERROR),
1979                                          errmsg("unique constraints not possible for domains")));
1980                         break;
1981
1982                 case CONSTR_PRIMARY:
1983                         ereport(ERROR,
1984                                         (errcode(ERRCODE_SYNTAX_ERROR),
1985                                 errmsg("primary key constraints not possible for domains")));
1986                         break;
1987
1988                 case CONSTR_EXCLUSION:
1989                         ereport(ERROR,
1990                                         (errcode(ERRCODE_SYNTAX_ERROR),
1991                                   errmsg("exclusion constraints not possible for domains")));
1992                         break;
1993
1994                 case CONSTR_FOREIGN:
1995                         ereport(ERROR,
1996                                         (errcode(ERRCODE_SYNTAX_ERROR),
1997                                 errmsg("foreign key constraints not possible for domains")));
1998                         break;
1999
2000                 case CONSTR_ATTR_DEFERRABLE:
2001                 case CONSTR_ATTR_NOT_DEFERRABLE:
2002                 case CONSTR_ATTR_DEFERRED:
2003                 case CONSTR_ATTR_IMMEDIATE:
2004                         ereport(ERROR,
2005                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2006                                          errmsg("specifying constraint deferrability not supported for domains")));
2007                         break;
2008
2009                 default:
2010                         elog(ERROR, "unrecognized constraint subtype: %d",
2011                                  (int) constr->contype);
2012                         break;
2013         }
2014
2015         /*
2016          * Since all other constraint types throw errors, this must be a check
2017          * constraint.  First, process the constraint expression and add an entry
2018          * to pg_constraint.
2019          */
2020
2021         ccbin = domainAddConstraint(HeapTupleGetOid(tup), typTup->typnamespace,
2022                                                                 typTup->typbasetype, typTup->typtypmod,
2023                                                                 constr, NameStr(typTup->typname));
2024
2025         /*
2026          * If requested to validate the constraint, test all values stored in the
2027          * attributes based on the domain the constraint is being added to.
2028          */
2029         if (!constr->skip_validation)
2030                 validateDomainConstraint(domainoid, ccbin);
2031
2032         /* Clean up */
2033         heap_close(typrel, RowExclusiveLock);
2034 }
2035
2036 /*
2037  * AlterDomainValidateConstraint
2038  *
2039  * Implements the ALTER DOMAIN .. VALIDATE CONSTRAINT statement.
2040  */
2041 void
2042 AlterDomainValidateConstraint(List *names, char *constrName)
2043 {
2044         TypeName   *typename;
2045         Oid                     domainoid;
2046         Relation        typrel;
2047         Relation        conrel;
2048         HeapTuple       tup;
2049         Form_pg_constraint con = NULL;
2050         Form_pg_constraint copy_con;
2051         char       *conbin;
2052         SysScanDesc     scan;
2053         Datum           val;
2054         bool            found = false;
2055         bool            isnull;
2056         HeapTuple       tuple;
2057         HeapTuple       copyTuple;
2058         ScanKeyData     key;
2059
2060         /* Make a TypeName so we can use standard type lookup machinery */
2061         typename = makeTypeNameFromNameList(names);
2062         domainoid = typenameTypeId(NULL, typename);
2063
2064         /* Look up the domain in the type table */
2065         typrel = heap_open(TypeRelationId, AccessShareLock);
2066
2067         tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(domainoid));
2068         if (!HeapTupleIsValid(tup))
2069                 elog(ERROR, "cache lookup failed for type %u", domainoid);
2070
2071         /* Check it's a domain and check user has permission for ALTER DOMAIN */
2072         checkDomainOwner(tup);
2073
2074         /*
2075          * Find and check the target constraint
2076          */
2077         conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
2078         ScanKeyInit(&key,
2079                                 Anum_pg_constraint_contypid,
2080                                 BTEqualStrategyNumber, F_OIDEQ,
2081                                 ObjectIdGetDatum(domainoid));
2082         scan = systable_beginscan(conrel, ConstraintTypidIndexId,
2083                                                           true, SnapshotNow, 1, &key);
2084
2085         while (HeapTupleIsValid(tuple = systable_getnext(scan)))
2086         {
2087                 con = (Form_pg_constraint) GETSTRUCT(tuple);
2088                 if (strcmp(NameStr(con->conname), constrName) == 0)
2089                 {
2090                         found = true;
2091                         break;
2092                 }
2093         }
2094
2095         if (!found)
2096                 ereport(ERROR,
2097                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2098                                  errmsg("constraint \"%s\" of domain \"%s\" does not exist",
2099                                                 constrName, TypeNameToString(typename))));
2100
2101         if (con->contype != CONSTRAINT_CHECK)
2102                 ereport(ERROR,
2103                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2104                                  errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
2105                                                 constrName, TypeNameToString(typename))));
2106
2107         val = SysCacheGetAttr(CONSTROID, tuple,
2108                                                   Anum_pg_constraint_conbin,
2109                                                   &isnull);
2110         if (isnull)
2111                 elog(ERROR, "null conbin for constraint %u",
2112                          HeapTupleGetOid(tuple));
2113         conbin = TextDatumGetCString(val);
2114
2115         validateDomainConstraint(domainoid, conbin);
2116
2117         /*
2118          * Now update the catalog, while we have the door open.
2119          */
2120         copyTuple = heap_copytuple(tuple);
2121         copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
2122         copy_con->convalidated = true;
2123         simple_heap_update(conrel, &copyTuple->t_self, copyTuple);
2124         CatalogUpdateIndexes(conrel, copyTuple);
2125         heap_freetuple(copyTuple);
2126
2127         systable_endscan(scan);
2128
2129         heap_close(typrel, AccessShareLock);
2130         heap_close(conrel, RowExclusiveLock);
2131
2132         ReleaseSysCache(tup);
2133 }
2134
2135 static void
2136 validateDomainConstraint(Oid domainoid, char *ccbin)
2137 {
2138         Expr       *expr = (Expr *) stringToNode(ccbin);
2139         List       *rels;
2140         ListCell   *rt;
2141         EState     *estate;
2142         ExprContext *econtext;
2143         ExprState  *exprstate;
2144
2145         /* Need an EState to run ExecEvalExpr */
2146         estate = CreateExecutorState();
2147         econtext = GetPerTupleExprContext(estate);
2148
2149         /* build execution state for expr */
2150         exprstate = ExecPrepareExpr(expr, estate);
2151
2152         /* Fetch relation list with attributes based on this domain */
2153         /* ShareLock is sufficient to prevent concurrent data changes */
2154
2155         rels = get_rels_with_domain(domainoid, ShareLock);
2156
2157         foreach(rt, rels)
2158         {
2159                 RelToCheck *rtc = (RelToCheck *) lfirst(rt);
2160                 Relation        testrel = rtc->rel;
2161                 TupleDesc       tupdesc = RelationGetDescr(testrel);
2162                 HeapScanDesc scan;
2163                 HeapTuple       tuple;
2164
2165                 /* Scan all tuples in this relation */
2166                 scan = heap_beginscan(testrel, SnapshotNow, 0, NULL);
2167                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2168                 {
2169                         int                     i;
2170
2171                         /* Test attributes that are of the domain */
2172                         for (i = 0; i < rtc->natts; i++)
2173                         {
2174                                 int                     attnum = rtc->atts[i];
2175                                 Datum           d;
2176                                 bool            isNull;
2177                                 Datum           conResult;
2178
2179                                 d = heap_getattr(tuple, attnum, tupdesc, &isNull);
2180
2181                                 econtext->domainValue_datum = d;
2182                                 econtext->domainValue_isNull = isNull;
2183
2184                                 conResult = ExecEvalExprSwitchContext(exprstate,
2185                                                                                                           econtext,
2186                                                                                                           &isNull, NULL);
2187
2188                                 if (!isNull && !DatumGetBool(conResult))
2189                                         ereport(ERROR,
2190                                                         (errcode(ERRCODE_CHECK_VIOLATION),
2191                                                          errmsg("column \"%s\" of table \"%s\" contains values that violate the new constraint",
2192                                                                 NameStr(tupdesc->attrs[attnum - 1]->attname),
2193                                                                         RelationGetRelationName(testrel))));
2194                         }
2195
2196                         ResetExprContext(econtext);
2197                 }
2198                 heap_endscan(scan);
2199
2200                 /* Hold relation lock till commit (XXX bad for concurrency) */
2201                 heap_close(testrel, NoLock);
2202         }
2203
2204         FreeExecutorState(estate);
2205 }
2206 /*
2207  * get_rels_with_domain
2208  *
2209  * Fetch all relations / attributes which are using the domain
2210  *
2211  * The result is a list of RelToCheck structs, one for each distinct
2212  * relation, each containing one or more attribute numbers that are of
2213  * the domain type.  We have opened each rel and acquired the specified lock
2214  * type on it.
2215  *
2216  * We support nested domains by including attributes that are of derived
2217  * domain types.  Current callers do not need to distinguish between attributes
2218  * that are of exactly the given domain and those that are of derived domains.
2219  *
2220  * XXX this is completely broken because there is no way to lock the domain
2221  * to prevent columns from being added or dropped while our command runs.
2222  * We can partially protect against column drops by locking relations as we
2223  * come across them, but there is still a race condition (the window between
2224  * seeing a pg_depend entry and acquiring lock on the relation it references).
2225  * Also, holding locks on all these relations simultaneously creates a non-
2226  * trivial risk of deadlock.  We can minimize but not eliminate the deadlock
2227  * risk by using the weakest suitable lock (ShareLock for most callers).
2228  *
2229  * XXX the API for this is not sufficient to support checking domain values
2230  * that are inside composite types or arrays.  Currently we just error out
2231  * if a composite type containing the target domain is stored anywhere.
2232  * There are not currently arrays of domains; if there were, we could take
2233  * the same approach, but it'd be nicer to fix it properly.
2234  *
2235  * Generally used for retrieving a list of tests when adding
2236  * new constraints to a domain.
2237  */
2238 static List *
2239 get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
2240 {
2241         List       *result = NIL;
2242         Relation        depRel;
2243         ScanKeyData key[2];
2244         SysScanDesc depScan;
2245         HeapTuple       depTup;
2246
2247         Assert(lockmode != NoLock);
2248
2249         /*
2250          * We scan pg_depend to find those things that depend on the domain. (We
2251          * assume we can ignore refobjsubid for a domain.)
2252          */
2253         depRel = heap_open(DependRelationId, AccessShareLock);
2254
2255         ScanKeyInit(&key[0],
2256                                 Anum_pg_depend_refclassid,
2257                                 BTEqualStrategyNumber, F_OIDEQ,
2258                                 ObjectIdGetDatum(TypeRelationId));
2259         ScanKeyInit(&key[1],
2260                                 Anum_pg_depend_refobjid,
2261                                 BTEqualStrategyNumber, F_OIDEQ,
2262                                 ObjectIdGetDatum(domainOid));
2263
2264         depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
2265                                                                  SnapshotNow, 2, key);
2266
2267         while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
2268         {
2269                 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
2270                 RelToCheck *rtc = NULL;
2271                 ListCell   *rellist;
2272                 Form_pg_attribute pg_att;
2273                 int                     ptr;
2274
2275                 /* Check for directly dependent types --- must be domains */
2276                 if (pg_depend->classid == TypeRelationId)
2277                 {
2278                         Assert(get_typtype(pg_depend->objid) == TYPTYPE_DOMAIN);
2279
2280                         /*
2281                          * Recursively add dependent columns to the output list.  This is
2282                          * a bit inefficient since we may fail to combine RelToCheck
2283                          * entries when attributes of the same rel have different derived
2284                          * domain types, but it's probably not worth improving.
2285                          */
2286                         result = list_concat(result,
2287                                                                  get_rels_with_domain(pg_depend->objid,
2288                                                                                                           lockmode));
2289                         continue;
2290                 }
2291
2292                 /* Else, ignore dependees that aren't user columns of relations */
2293                 /* (we assume system columns are never of domain types) */
2294                 if (pg_depend->classid != RelationRelationId ||
2295                         pg_depend->objsubid <= 0)
2296                         continue;
2297
2298                 /* See if we already have an entry for this relation */
2299                 foreach(rellist, result)
2300                 {
2301                         RelToCheck *rt = (RelToCheck *) lfirst(rellist);
2302
2303                         if (RelationGetRelid(rt->rel) == pg_depend->objid)
2304                         {
2305                                 rtc = rt;
2306                                 break;
2307                         }
2308                 }
2309
2310                 if (rtc == NULL)
2311                 {
2312                         /* First attribute found for this relation */
2313                         Relation        rel;
2314
2315                         /* Acquire requested lock on relation */
2316                         rel = relation_open(pg_depend->objid, lockmode);
2317
2318                         /*
2319                          * Check to see if rowtype is stored anyplace as a composite-type
2320                          * column; if so we have to fail, for now anyway.
2321                          */
2322                         if (OidIsValid(rel->rd_rel->reltype))
2323                                 find_composite_type_dependencies(rel->rd_rel->reltype,
2324                                                                                                  NULL,
2325                                                                                                  format_type_be(domainOid));
2326
2327                         /* Otherwise we can ignore views, composite types, etc */
2328                         if (rel->rd_rel->relkind != RELKIND_RELATION)
2329                         {
2330                                 relation_close(rel, lockmode);
2331                                 continue;
2332                         }
2333
2334                         /* Build the RelToCheck entry with enough space for all atts */
2335                         rtc = (RelToCheck *) palloc(sizeof(RelToCheck));
2336                         rtc->rel = rel;
2337                         rtc->natts = 0;
2338                         rtc->atts = (int *) palloc(sizeof(int) * RelationGetNumberOfAttributes(rel));
2339                         result = lcons(rtc, result);
2340                 }
2341
2342                 /*
2343                  * Confirm column has not been dropped, and is of the expected type.
2344                  * This defends against an ALTER DROP COLUMN occuring just before we
2345                  * acquired lock ... but if the whole table were dropped, we'd still
2346                  * have a problem.
2347                  */
2348                 if (pg_depend->objsubid > RelationGetNumberOfAttributes(rtc->rel))
2349                         continue;
2350                 pg_att = rtc->rel->rd_att->attrs[pg_depend->objsubid - 1];
2351                 if (pg_att->attisdropped || pg_att->atttypid != domainOid)
2352                         continue;
2353
2354                 /*
2355                  * Okay, add column to result.  We store the columns in column-number
2356                  * order; this is just a hack to improve predictability of regression
2357                  * test output ...
2358                  */
2359                 Assert(rtc->natts < RelationGetNumberOfAttributes(rtc->rel));
2360
2361                 ptr = rtc->natts++;
2362                 while (ptr > 0 && rtc->atts[ptr - 1] > pg_depend->objsubid)
2363                 {
2364                         rtc->atts[ptr] = rtc->atts[ptr - 1];
2365                         ptr--;
2366                 }
2367                 rtc->atts[ptr] = pg_depend->objsubid;
2368         }
2369
2370         systable_endscan(depScan);
2371
2372         relation_close(depRel, AccessShareLock);
2373
2374         return result;
2375 }
2376
2377 /*
2378  * checkDomainOwner
2379  *
2380  * Check that the type is actually a domain and that the current user
2381  * has permission to do ALTER DOMAIN on it.  Throw an error if not.
2382  */
2383 static void
2384 checkDomainOwner(HeapTuple tup)
2385 {
2386         Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
2387
2388         /* Check that this is actually a domain */
2389         if (typTup->typtype != TYPTYPE_DOMAIN)
2390                 ereport(ERROR,
2391                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2392                                  errmsg("%s is not a domain",
2393                                                 format_type_be(HeapTupleGetOid(tup)))));
2394
2395         /* Permission check: must own type */
2396         if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
2397                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
2398                                            format_type_be(HeapTupleGetOid(tup)));
2399 }
2400
2401 /*
2402  * domainAddConstraint - code shared between CREATE and ALTER DOMAIN
2403  */
2404 static char *
2405 domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
2406                                         int typMod, Constraint *constr,
2407                                         char *domainName)
2408 {
2409         Node       *expr;
2410         char       *ccsrc;
2411         char       *ccbin;
2412         ParseState *pstate;
2413         CoerceToDomainValue *domVal;
2414
2415         /*
2416          * Assign or validate constraint name
2417          */
2418         if (constr->conname)
2419         {
2420                 if (ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
2421                                                                  domainOid,
2422                                                                  domainNamespace,
2423                                                                  constr->conname))
2424                         ereport(ERROR,
2425                                         (errcode(ERRCODE_DUPLICATE_OBJECT),
2426                                  errmsg("constraint \"%s\" for domain \"%s\" already exists",
2427                                                 constr->conname, domainName)));
2428         }
2429         else
2430                 constr->conname = ChooseConstraintName(domainName,
2431                                                                                            NULL,
2432                                                                                            "check",
2433                                                                                            domainNamespace,
2434                                                                                            NIL);
2435
2436         /*
2437          * Convert the A_EXPR in raw_expr into an EXPR
2438          */
2439         pstate = make_parsestate(NULL);
2440
2441         /*
2442          * Set up a CoerceToDomainValue to represent the occurrence of VALUE in
2443          * the expression.      Note that it will appear to have the type of the base
2444          * type, not the domain.  This seems correct since within the check
2445          * expression, we should not assume the input value can be considered a
2446          * member of the domain.
2447          */
2448         domVal = makeNode(CoerceToDomainValue);
2449         domVal->typeId = baseTypeOid;
2450         domVal->typeMod = typMod;
2451         domVal->collation = get_typcollation(baseTypeOid);
2452         domVal->location = -1;          /* will be set when/if used */
2453
2454         pstate->p_value_substitute = (Node *) domVal;
2455
2456         expr = transformExpr(pstate, constr->raw_expr);
2457
2458         /*
2459          * Make sure it yields a boolean result.
2460          */
2461         expr = coerce_to_boolean(pstate, expr, "CHECK");
2462
2463         /*
2464          * Fix up collation information.
2465          */
2466         assign_expr_collations(pstate, expr);
2467
2468         /*
2469          * Make sure no outside relations are referred to.
2470          */
2471         if (list_length(pstate->p_rtable) != 0)
2472                 ereport(ERROR,
2473                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2474                   errmsg("cannot use table references in domain check constraint")));
2475
2476         /*
2477          * Domains don't allow var clauses (this should be redundant with the
2478          * above check, but make it anyway)
2479          */
2480         if (contain_var_clause(expr))
2481                 ereport(ERROR,
2482                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2483                   errmsg("cannot use table references in domain check constraint")));
2484
2485         /*
2486          * No subplans or aggregates, either...
2487          */
2488         if (pstate->p_hasSubLinks)
2489                 ereport(ERROR,
2490                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2491                                  errmsg("cannot use subquery in check constraint")));
2492         if (pstate->p_hasAggs)
2493                 ereport(ERROR,
2494                                 (errcode(ERRCODE_GROUPING_ERROR),
2495                            errmsg("cannot use aggregate function in check constraint")));
2496         if (pstate->p_hasWindowFuncs)
2497                 ereport(ERROR,
2498                                 (errcode(ERRCODE_WINDOWING_ERROR),
2499                                  errmsg("cannot use window function in check constraint")));
2500
2501         /*
2502          * Convert to string form for storage.
2503          */
2504         ccbin = nodeToString(expr);
2505
2506         /*
2507          * Deparse it to produce text for consrc.
2508          *
2509          * Since VARNOs aren't allowed in domain constraints, relation context
2510          * isn't required as anything other than a shell.
2511          */
2512         ccsrc = deparse_expression(expr,
2513                                                            deparse_context_for(domainName,
2514                                                                                                    InvalidOid),
2515                                                            false, false);
2516
2517         /*
2518          * Store the constraint in pg_constraint
2519          */
2520         CreateConstraintEntry(constr->conname,          /* Constraint Name */
2521                                                   domainNamespace,              /* namespace */
2522                                                   CONSTRAINT_CHECK,             /* Constraint Type */
2523                                                   false,        /* Is Deferrable */
2524                                                   false,        /* Is Deferred */
2525                                                   !constr->skip_validation, /* Is Validated */
2526                                                   InvalidOid,   /* not a relation constraint */
2527                                                   NULL,
2528                                                   0,
2529                                                   domainOid,    /* domain constraint */
2530                                                   InvalidOid,   /* no associated index */
2531                                                   InvalidOid,   /* Foreign key fields */
2532                                                   NULL,
2533                                                   NULL,
2534                                                   NULL,
2535                                                   NULL,
2536                                                   0,
2537                                                   ' ',
2538                                                   ' ',
2539                                                   ' ',
2540                                                   NULL, /* not an exclusion constraint */
2541                                                   expr, /* Tree form of check constraint */
2542                                                   ccbin,        /* Binary form of check constraint */
2543                                                   ccsrc,        /* Source form of check constraint */
2544                                                   true, /* is local */
2545                                                   0);   /* inhcount */
2546
2547         /*
2548          * Return the compiled constraint expression so the calling routine can
2549          * perform any additional required tests.
2550          */
2551         return ccbin;
2552 }
2553
2554 /*
2555  * GetDomainConstraints - get a list of the current constraints of domain
2556  *
2557  * Returns a possibly-empty list of DomainConstraintState nodes.
2558  *
2559  * This is called by the executor during plan startup for a CoerceToDomain
2560  * expression node.  The given constraints will be checked for each value
2561  * passed through the node.
2562  *
2563  * We allow this to be called for non-domain types, in which case the result
2564  * is always NIL.
2565  */
2566 List *
2567 GetDomainConstraints(Oid typeOid)
2568 {
2569         List       *result = NIL;
2570         bool            notNull = false;
2571         Relation        conRel;
2572
2573         conRel = heap_open(ConstraintRelationId, AccessShareLock);
2574
2575         for (;;)
2576         {
2577                 HeapTuple       tup;
2578                 HeapTuple       conTup;
2579                 Form_pg_type typTup;
2580                 ScanKeyData key[1];
2581                 SysScanDesc scan;
2582
2583                 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
2584                 if (!HeapTupleIsValid(tup))
2585                         elog(ERROR, "cache lookup failed for type %u", typeOid);
2586                 typTup = (Form_pg_type) GETSTRUCT(tup);
2587
2588                 if (typTup->typtype != TYPTYPE_DOMAIN)
2589                 {
2590                         /* Not a domain, so done */
2591                         ReleaseSysCache(tup);
2592                         break;
2593                 }
2594
2595                 /* Test for NOT NULL Constraint */
2596                 if (typTup->typnotnull)
2597                         notNull = true;
2598
2599                 /* Look for CHECK Constraints on this domain */
2600                 ScanKeyInit(&key[0],
2601                                         Anum_pg_constraint_contypid,
2602                                         BTEqualStrategyNumber, F_OIDEQ,
2603                                         ObjectIdGetDatum(typeOid));
2604
2605                 scan = systable_beginscan(conRel, ConstraintTypidIndexId, true,
2606                                                                   SnapshotNow, 1, key);
2607
2608                 while (HeapTupleIsValid(conTup = systable_getnext(scan)))
2609                 {
2610                         Form_pg_constraint c = (Form_pg_constraint) GETSTRUCT(conTup);
2611                         Datum           val;
2612                         bool            isNull;
2613                         Expr       *check_expr;
2614                         DomainConstraintState *r;
2615
2616                         /* Ignore non-CHECK constraints (presently, shouldn't be any) */
2617                         if (c->contype != CONSTRAINT_CHECK)
2618                                 continue;
2619
2620                         /*
2621                          * Not expecting conbin to be NULL, but we'll test for it anyway
2622                          */
2623                         val = fastgetattr(conTup, Anum_pg_constraint_conbin,
2624                                                           conRel->rd_att, &isNull);
2625                         if (isNull)
2626                                 elog(ERROR, "domain \"%s\" constraint \"%s\" has NULL conbin",
2627                                          NameStr(typTup->typname), NameStr(c->conname));
2628
2629                         check_expr = (Expr *) stringToNode(TextDatumGetCString(val));
2630
2631                         /* ExecInitExpr assumes we've planned the expression */
2632                         check_expr = expression_planner(check_expr);
2633
2634                         r = makeNode(DomainConstraintState);
2635                         r->constrainttype = DOM_CONSTRAINT_CHECK;
2636                         r->name = pstrdup(NameStr(c->conname));
2637                         r->check_expr = ExecInitExpr(check_expr, NULL);
2638
2639                         /*
2640                          * use lcons() here because constraints of lower domains should be
2641                          * applied earlier.
2642                          */
2643                         result = lcons(r, result);
2644                 }
2645
2646                 systable_endscan(scan);
2647
2648                 /* loop to next domain in stack */
2649                 typeOid = typTup->typbasetype;
2650                 ReleaseSysCache(tup);
2651         }
2652
2653         heap_close(conRel, AccessShareLock);
2654
2655         /*
2656          * Only need to add one NOT NULL check regardless of how many domains in
2657          * the stack request it.
2658          */
2659         if (notNull)
2660         {
2661                 DomainConstraintState *r = makeNode(DomainConstraintState);
2662
2663                 r->constrainttype = DOM_CONSTRAINT_NOTNULL;
2664                 r->name = pstrdup("NOT NULL");
2665                 r->check_expr = NULL;
2666
2667                 /* lcons to apply the nullness check FIRST */
2668                 result = lcons(r, result);
2669         }
2670
2671         return result;
2672 }
2673
2674
2675 /*
2676  * Execute ALTER TYPE RENAME
2677  */
2678 void
2679 RenameType(List *names, const char *newTypeName)
2680 {
2681         TypeName   *typename;
2682         Oid                     typeOid;
2683         Relation        rel;
2684         HeapTuple       tup;
2685         Form_pg_type typTup;
2686
2687         /* Make a TypeName so we can use standard type lookup machinery */
2688         typename = makeTypeNameFromNameList(names);
2689         typeOid = typenameTypeId(NULL, typename);
2690
2691         /* Look up the type in the type table */
2692         rel = heap_open(TypeRelationId, RowExclusiveLock);
2693
2694         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
2695         if (!HeapTupleIsValid(tup))
2696                 elog(ERROR, "cache lookup failed for type %u", typeOid);
2697         typTup = (Form_pg_type) GETSTRUCT(tup);
2698
2699         /* check permissions on type */
2700         if (!pg_type_ownercheck(typeOid, GetUserId()))
2701                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
2702                                            format_type_be(typeOid));
2703
2704         /*
2705          * If it's a composite type, we need to check that it really is a
2706          * free-standing composite type, and not a table's rowtype. We want people
2707          * to use ALTER TABLE not ALTER TYPE for that case.
2708          */
2709         if (typTup->typtype == TYPTYPE_COMPOSITE &&
2710                 get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
2711                 ereport(ERROR,
2712                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2713                                  errmsg("%s is a table's row type",
2714                                                 format_type_be(typeOid)),
2715                                  errhint("Use ALTER TABLE instead.")));
2716
2717         /* don't allow direct alteration of array types, either */
2718         if (OidIsValid(typTup->typelem) &&
2719                 get_array_type(typTup->typelem) == typeOid)
2720                 ereport(ERROR,
2721                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2722                                  errmsg("cannot alter array type %s",
2723                                                 format_type_be(typeOid)),
2724                                  errhint("You can alter type %s, which will alter the array type as well.",
2725                                                  format_type_be(typTup->typelem))));
2726
2727         /*
2728          * If type is composite we need to rename associated pg_class entry too.
2729          * RenameRelationInternal will call RenameTypeInternal automatically.
2730          */
2731         if (typTup->typtype == TYPTYPE_COMPOSITE)
2732                 RenameRelationInternal(typTup->typrelid, newTypeName,
2733                                                            typTup->typnamespace);
2734         else
2735                 RenameTypeInternal(typeOid, newTypeName,
2736                                                    typTup->typnamespace);
2737
2738         /* Clean up */
2739         heap_close(rel, RowExclusiveLock);
2740 }
2741
2742 /*
2743  * Change the owner of a type.
2744  */
2745 void
2746 AlterTypeOwner(List *names, Oid newOwnerId)
2747 {
2748         TypeName   *typename;
2749         Oid                     typeOid;
2750         Relation        rel;
2751         HeapTuple       tup;
2752         HeapTuple       newtup;
2753         Form_pg_type typTup;
2754         AclResult       aclresult;
2755
2756         rel = heap_open(TypeRelationId, RowExclusiveLock);
2757
2758         /* Make a TypeName so we can use standard type lookup machinery */
2759         typename = makeTypeNameFromNameList(names);
2760
2761         /* Use LookupTypeName here so that shell types can be processed */
2762         tup = LookupTypeName(NULL, typename, NULL);
2763         if (tup == NULL)
2764                 ereport(ERROR,
2765                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2766                                  errmsg("type \"%s\" does not exist",
2767                                                 TypeNameToString(typename))));
2768         typeOid = typeTypeId(tup);
2769
2770         /* Copy the syscache entry so we can scribble on it below */
2771         newtup = heap_copytuple(tup);
2772         ReleaseSysCache(tup);
2773         tup = newtup;
2774         typTup = (Form_pg_type) GETSTRUCT(tup);
2775
2776         /*
2777          * If it's a composite type, we need to check that it really is a
2778          * free-standing composite type, and not a table's rowtype. We want people
2779          * to use ALTER TABLE not ALTER TYPE for that case.
2780          */
2781         if (typTup->typtype == TYPTYPE_COMPOSITE &&
2782                 get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
2783                 ereport(ERROR,
2784                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2785                                  errmsg("%s is a table's row type",
2786                                                 format_type_be(typeOid)),
2787                                  errhint("Use ALTER TABLE instead.")));
2788
2789         /* don't allow direct alteration of array types, either */
2790         if (OidIsValid(typTup->typelem) &&
2791                 get_array_type(typTup->typelem) == typeOid)
2792                 ereport(ERROR,
2793                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2794                                  errmsg("cannot alter array type %s",
2795                                                 format_type_be(typeOid)),
2796                                  errhint("You can alter type %s, which will alter the array type as well.",
2797                                                  format_type_be(typTup->typelem))));
2798
2799         /*
2800          * If the new owner is the same as the existing owner, consider the
2801          * command to have succeeded.  This is for dump restoration purposes.
2802          */
2803         if (typTup->typowner != newOwnerId)
2804         {
2805                 /* Superusers can always do it */
2806                 if (!superuser())
2807                 {
2808                         /* Otherwise, must be owner of the existing object */
2809                         if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
2810                                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
2811                                                            format_type_be(HeapTupleGetOid(tup)));
2812
2813                         /* Must be able to become new owner */
2814                         check_is_member_of_role(GetUserId(), newOwnerId);
2815
2816                         /* New owner must have CREATE privilege on namespace */
2817                         aclresult = pg_namespace_aclcheck(typTup->typnamespace,
2818                                                                                           newOwnerId,
2819                                                                                           ACL_CREATE);
2820                         if (aclresult != ACLCHECK_OK)
2821                                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2822                                                            get_namespace_name(typTup->typnamespace));
2823                 }
2824
2825                 /*
2826                  * If it's a composite type, invoke ATExecChangeOwner so that we fix
2827                  * up the pg_class entry properly.      That will call back to
2828                  * AlterTypeOwnerInternal to take care of the pg_type entry(s).
2829                  */
2830                 if (typTup->typtype == TYPTYPE_COMPOSITE)
2831                         ATExecChangeOwner(typTup->typrelid, newOwnerId, true, AccessExclusiveLock);
2832                 else
2833                 {
2834                         /*
2835                          * We can just apply the modification directly.
2836                          *
2837                          * okay to scribble on typTup because it's a copy
2838                          */
2839                         typTup->typowner = newOwnerId;
2840
2841                         simple_heap_update(rel, &tup->t_self, tup);
2842
2843                         CatalogUpdateIndexes(rel, tup);
2844
2845                         /* Update owner dependency reference */
2846                         changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
2847
2848                         /* If it has an array type, update that too */
2849                         if (OidIsValid(typTup->typarray))
2850                                 AlterTypeOwnerInternal(typTup->typarray, newOwnerId, false);
2851                 }
2852         }
2853
2854         /* Clean up */
2855         heap_close(rel, RowExclusiveLock);
2856 }
2857
2858 /*
2859  * AlterTypeOwnerInternal - change type owner unconditionally
2860  *
2861  * This is currently only used to propagate ALTER TABLE/TYPE OWNER to a
2862  * table's rowtype or an array type, and to implement REASSIGN OWNED BY.
2863  * It assumes the caller has done all needed checks.  The function will
2864  * automatically recurse to an array type if the type has one.
2865  *
2866  * hasDependEntry should be TRUE if type is expected to have a pg_shdepend
2867  * entry (ie, it's not a table rowtype nor an array type).
2868  */
2869 void
2870 AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId,
2871                                            bool hasDependEntry)
2872 {
2873         Relation        rel;
2874         HeapTuple       tup;
2875         Form_pg_type typTup;
2876
2877         rel = heap_open(TypeRelationId, RowExclusiveLock);
2878
2879         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
2880         if (!HeapTupleIsValid(tup))
2881                 elog(ERROR, "cache lookup failed for type %u", typeOid);
2882         typTup = (Form_pg_type) GETSTRUCT(tup);
2883
2884         /*
2885          * Modify the owner --- okay to scribble on typTup because it's a copy
2886          */
2887         typTup->typowner = newOwnerId;
2888
2889         simple_heap_update(rel, &tup->t_self, tup);
2890
2891         CatalogUpdateIndexes(rel, tup);
2892
2893         /* Update owner dependency reference, if it has one */
2894         if (hasDependEntry)
2895                 changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
2896
2897         /* If it has an array type, update that too */
2898         if (OidIsValid(typTup->typarray))
2899                 AlterTypeOwnerInternal(typTup->typarray, newOwnerId, false);
2900
2901         /* Clean up */
2902         heap_close(rel, RowExclusiveLock);
2903 }
2904
2905 /*
2906  * Execute ALTER TYPE SET SCHEMA
2907  */
2908 void
2909 AlterTypeNamespace(List *names, const char *newschema)
2910 {
2911         TypeName   *typename;
2912         Oid                     typeOid;
2913         Oid                     nspOid;
2914
2915         /* Make a TypeName so we can use standard type lookup machinery */
2916         typename = makeTypeNameFromNameList(names);
2917         typeOid = typenameTypeId(NULL, typename);
2918
2919         /* get schema OID and check its permissions */
2920         nspOid = LookupCreationNamespace(newschema);
2921
2922         AlterTypeNamespace_oid(typeOid, nspOid);
2923 }
2924
2925 Oid
2926 AlterTypeNamespace_oid(Oid typeOid, Oid nspOid)
2927 {
2928         Oid                     elemOid;
2929
2930         /* check permissions on type */
2931         if (!pg_type_ownercheck(typeOid, GetUserId()))
2932                 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_TYPE,
2933                                            format_type_be(typeOid));
2934
2935         /* don't allow direct alteration of array types */
2936         elemOid = get_element_type(typeOid);
2937         if (OidIsValid(elemOid) && get_array_type(elemOid) == typeOid)
2938                 ereport(ERROR,
2939                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2940                                  errmsg("cannot alter array type %s",
2941                                                 format_type_be(typeOid)),
2942                                  errhint("You can alter type %s, which will alter the array type as well.",
2943                                                  format_type_be(elemOid))));
2944
2945         /* and do the work */
2946         return AlterTypeNamespaceInternal(typeOid, nspOid, false, true);
2947 }
2948
2949 /*
2950  * Move specified type to new namespace.
2951  *
2952  * Caller must have already checked privileges.
2953  *
2954  * The function automatically recurses to process the type's array type,
2955  * if any.      isImplicitArray should be TRUE only when doing this internal
2956  * recursion (outside callers must never try to move an array type directly).
2957  *
2958  * If errorOnTableType is TRUE, the function errors out if the type is
2959  * a table type.  ALTER TABLE has to be used to move a table to a new
2960  * namespace.
2961  *
2962  * Returns the type's old namespace OID.
2963  */
2964 Oid
2965 AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid,
2966                                                    bool isImplicitArray,
2967                                                    bool errorOnTableType)
2968 {
2969         Relation        rel;
2970         HeapTuple       tup;
2971         Form_pg_type typform;
2972         Oid                     oldNspOid;
2973         Oid                     arrayOid;
2974         bool            isCompositeType;
2975
2976         rel = heap_open(TypeRelationId, RowExclusiveLock);
2977
2978         tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
2979         if (!HeapTupleIsValid(tup))
2980                 elog(ERROR, "cache lookup failed for type %u", typeOid);
2981         typform = (Form_pg_type) GETSTRUCT(tup);
2982
2983         oldNspOid = typform->typnamespace;
2984         arrayOid = typform->typarray;
2985
2986         /* common checks on switching namespaces */
2987         CheckSetNamespace(oldNspOid, nspOid, TypeRelationId, typeOid);
2988
2989         /* check for duplicate name (more friendly than unique-index failure) */
2990         if (SearchSysCacheExists2(TYPENAMENSP,
2991                                                           CStringGetDatum(NameStr(typform->typname)),
2992                                                           ObjectIdGetDatum(nspOid)))
2993                 ereport(ERROR,
2994                                 (errcode(ERRCODE_DUPLICATE_OBJECT),
2995                                  errmsg("type \"%s\" already exists in schema \"%s\"",
2996                                                 NameStr(typform->typname),
2997                                                 get_namespace_name(nspOid))));
2998
2999         /* Detect whether type is a composite type (but not a table rowtype) */
3000         isCompositeType =
3001                 (typform->typtype == TYPTYPE_COMPOSITE &&
3002                  get_rel_relkind(typform->typrelid) == RELKIND_COMPOSITE_TYPE);
3003
3004         /* Enforce not-table-type if requested */
3005         if (typform->typtype == TYPTYPE_COMPOSITE && !isCompositeType &&
3006                 errorOnTableType)
3007                 ereport(ERROR,
3008                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3009                                  errmsg("%s is a table's row type",
3010                                                 format_type_be(typeOid)),
3011                                  errhint("Use ALTER TABLE instead.")));
3012
3013         /* OK, modify the pg_type row */
3014
3015         /* tup is a copy, so we can scribble directly on it */
3016         typform->typnamespace = nspOid;
3017
3018         simple_heap_update(rel, &tup->t_self, tup);
3019         CatalogUpdateIndexes(rel, tup);
3020
3021         /*
3022          * Composite types have pg_class entries.
3023          *
3024          * We need to modify the pg_class tuple as well to reflect the change of
3025          * schema.
3026          */
3027         if (isCompositeType)
3028         {
3029                 Relation        classRel;
3030
3031                 classRel = heap_open(RelationRelationId, RowExclusiveLock);
3032
3033                 AlterRelationNamespaceInternal(classRel, typform->typrelid,
3034                                                                            oldNspOid, nspOid,
3035                                                                            false);
3036
3037                 heap_close(classRel, RowExclusiveLock);
3038
3039                 /*
3040                  * Check for constraints associated with the composite type (we don't
3041                  * currently support this, but probably will someday).
3042                  */
3043                 AlterConstraintNamespaces(typform->typrelid, oldNspOid,
3044                                                                   nspOid, false);
3045         }
3046         else
3047         {
3048                 /* If it's a domain, it might have constraints */
3049                 if (typform->typtype == TYPTYPE_DOMAIN)
3050                         AlterConstraintNamespaces(typeOid, oldNspOid, nspOid, true);
3051         }
3052
3053         /*
3054          * Update dependency on schema, if any --- a table rowtype has not got
3055          * one, and neither does an implicit array.
3056          */
3057         if ((isCompositeType || typform->typtype != TYPTYPE_COMPOSITE) &&
3058                 !isImplicitArray)
3059                 if (changeDependencyFor(TypeRelationId, typeOid,
3060                                                                 NamespaceRelationId, oldNspOid, nspOid) != 1)
3061                         elog(ERROR, "failed to change schema dependency for type %s",
3062                                  format_type_be(typeOid));
3063
3064         heap_freetuple(tup);
3065
3066         heap_close(rel, RowExclusiveLock);
3067
3068         /* Recursively alter the associated array type, if any */
3069         if (OidIsValid(arrayOid))
3070                 AlterTypeNamespaceInternal(arrayOid, nspOid, true, true);
3071
3072         return oldNspOid;
3073 }