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