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