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