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