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