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