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