]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/format_type.c
Replace pg_asprintf() with psprintf().
[postgresql] / src / backend / utils / adt / format_type.c
1 /*-------------------------------------------------------------------------
2  *
3  * format_type.c
4  *        Display type names "nicely".
5  *
6  *
7  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/adt/format_type.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <ctype.h>
19
20 #include "access/htup_details.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_type.h"
23 #include "utils/builtins.h"
24 #include "utils/lsyscache.h"
25 #include "utils/numeric.h"
26 #include "utils/syscache.h"
27 #include "mb/pg_wchar.h"
28
29 #define MAX_INT32_LEN 11
30
31 static char *format_type_internal(Oid type_oid, int32 typemod,
32                                          bool typemod_given, bool allow_invalid,
33                                          bool force_qualify);
34 static char *printTypmod(const char *typname, int32 typmod, Oid typmodout);
35
36
37 /*
38  * SQL function: format_type(type_oid, typemod)
39  *
40  * `type_oid' is from pg_type.oid, `typemod' is from
41  * pg_attribute.atttypmod. This function will get the type name and
42  * format it and the modifier to canonical SQL format, if the type is
43  * a standard type. Otherwise you just get pg_type.typname back,
44  * double quoted if it contains funny characters or matches a keyword.
45  *
46  * If typemod is NULL then we are formatting a type name in a context where
47  * no typemod is available, eg a function argument or result type.      This
48  * yields a slightly different result from specifying typemod = -1 in some
49  * cases.  Given typemod = -1 we feel compelled to produce an output that
50  * the parser will interpret as having typemod -1, so that pg_dump will
51  * produce CREATE TABLE commands that recreate the original state.      But
52  * given NULL typemod, we assume that the parser's interpretation of
53  * typemod doesn't matter, and so we are willing to output a slightly
54  * "prettier" representation of the same type.  For example, type = bpchar
55  * and typemod = NULL gets you "character", whereas typemod = -1 gets you
56  * "bpchar" --- the former will be interpreted as character(1) by the
57  * parser, which does not yield typemod -1.
58  *
59  * XXX encoding a meaning in typemod = NULL is ugly; it'd have been
60  * cleaner to make two functions of one and two arguments respectively.
61  * Not worth changing it now, however.
62  */
63 Datum
64 format_type(PG_FUNCTION_ARGS)
65 {
66         Oid                     type_oid;
67         int32           typemod;
68         char       *result;
69
70         /* Since this function is not strict, we must test for null args */
71         if (PG_ARGISNULL(0))
72                 PG_RETURN_NULL();
73
74         type_oid = PG_GETARG_OID(0);
75
76         if (PG_ARGISNULL(1))
77                 result = format_type_internal(type_oid, -1, false, true, false);
78         else
79         {
80                 typemod = PG_GETARG_INT32(1);
81                 result = format_type_internal(type_oid, typemod, true, true, false);
82         }
83
84         PG_RETURN_TEXT_P(cstring_to_text(result));
85 }
86
87 /*
88  * This version is for use within the backend in error messages, etc.
89  * One difference is that it will fail for an invalid type.
90  *
91  * The result is always a palloc'd string.
92  */
93 char *
94 format_type_be(Oid type_oid)
95 {
96         return format_type_internal(type_oid, -1, false, false, false);
97 }
98
99 char *
100 format_type_be_qualified(Oid type_oid)
101 {
102         return format_type_internal(type_oid, -1, false, false, true);
103 }
104
105 /*
106  * This version allows a nondefault typemod to be specified.
107  */
108 char *
109 format_type_with_typemod(Oid type_oid, int32 typemod)
110 {
111         return format_type_internal(type_oid, typemod, true, false, false);
112 }
113
114 static char *
115 format_type_internal(Oid type_oid, int32 typemod,
116                                          bool typemod_given, bool allow_invalid,
117                                          bool force_qualify)
118 {
119         bool            with_typemod = typemod_given && (typemod >= 0);
120         HeapTuple       tuple;
121         Form_pg_type typeform;
122         Oid                     array_base_type;
123         bool            is_array;
124         char       *buf;
125
126         if (type_oid == InvalidOid && allow_invalid)
127                 return pstrdup("-");
128
129         tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
130         if (!HeapTupleIsValid(tuple))
131         {
132                 if (allow_invalid)
133                         return pstrdup("???");
134                 else
135                         elog(ERROR, "cache lookup failed for type %u", type_oid);
136         }
137         typeform = (Form_pg_type) GETSTRUCT(tuple);
138
139         /*
140          * Check if it's a regular (variable length) array type.  Fixed-length
141          * array types such as "name" shouldn't get deconstructed.  As of Postgres
142          * 8.1, rather than checking typlen we check the toast property, and don't
143          * deconstruct "plain storage" array types --- this is because we don't
144          * want to show oidvector as oid[].
145          */
146         array_base_type = typeform->typelem;
147
148         if (array_base_type != InvalidOid &&
149                 typeform->typstorage != 'p')
150         {
151                 /* Switch our attention to the array element type */
152                 ReleaseSysCache(tuple);
153                 tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(array_base_type));
154                 if (!HeapTupleIsValid(tuple))
155                 {
156                         if (allow_invalid)
157                                 return pstrdup("???[]");
158                         else
159                                 elog(ERROR, "cache lookup failed for type %u", type_oid);
160                 }
161                 typeform = (Form_pg_type) GETSTRUCT(tuple);
162                 type_oid = array_base_type;
163                 is_array = true;
164         }
165         else
166                 is_array = false;
167
168         /*
169          * See if we want to special-case the output for certain built-in types.
170          * Note that these special cases should all correspond to special
171          * productions in gram.y, to ensure that the type name will be taken as a
172          * system type, not a user type of the same name.
173          *
174          * If we do not provide a special-case output here, the type name will be
175          * handled the same way as a user type name --- in particular, it will be
176          * double-quoted if it matches any lexer keyword.  This behavior is
177          * essential for some cases, such as types "bit" and "char".
178          */
179         buf = NULL;                                     /* flag for no special case */
180
181         switch (type_oid)
182         {
183                 case BITOID:
184                         if (with_typemod)
185                                 buf = printTypmod("bit", typemod, typeform->typmodout);
186                         else if (typemod_given)
187                         {
188                                 /*
189                                  * bit with typmod -1 is not the same as BIT, which means
190                                  * BIT(1) per SQL spec.  Report it as the quoted typename so
191                                  * that parser will not assign a bogus typmod.
192                                  */
193                         }
194                         else
195                                 buf = pstrdup("bit");
196                         break;
197
198                 case BOOLOID:
199                         buf = pstrdup("boolean");
200                         break;
201
202                 case BPCHAROID:
203                         if (with_typemod)
204                                 buf = printTypmod("character", typemod, typeform->typmodout);
205                         else if (typemod_given)
206                         {
207                                 /*
208                                  * bpchar with typmod -1 is not the same as CHARACTER, which
209                                  * means CHARACTER(1) per SQL spec.  Report it as bpchar so
210                                  * that parser will not assign a bogus typmod.
211                                  */
212                         }
213                         else
214                                 buf = pstrdup("character");
215                         break;
216
217                 case FLOAT4OID:
218                         buf = pstrdup("real");
219                         break;
220
221                 case FLOAT8OID:
222                         buf = pstrdup("double precision");
223                         break;
224
225                 case INT2OID:
226                         buf = pstrdup("smallint");
227                         break;
228
229                 case INT4OID:
230                         buf = pstrdup("integer");
231                         break;
232
233                 case INT8OID:
234                         buf = pstrdup("bigint");
235                         break;
236
237                 case NUMERICOID:
238                         if (with_typemod)
239                                 buf = printTypmod("numeric", typemod, typeform->typmodout);
240                         else
241                                 buf = pstrdup("numeric");
242                         break;
243
244                 case INTERVALOID:
245                         if (with_typemod)
246                                 buf = printTypmod("interval", typemod, typeform->typmodout);
247                         else
248                                 buf = pstrdup("interval");
249                         break;
250
251                 case TIMEOID:
252                         if (with_typemod)
253                                 buf = printTypmod("time", typemod, typeform->typmodout);
254                         else
255                                 buf = pstrdup("time without time zone");
256                         break;
257
258                 case TIMETZOID:
259                         if (with_typemod)
260                                 buf = printTypmod("time", typemod, typeform->typmodout);
261                         else
262                                 buf = pstrdup("time with time zone");
263                         break;
264
265                 case TIMESTAMPOID:
266                         if (with_typemod)
267                                 buf = printTypmod("timestamp", typemod, typeform->typmodout);
268                         else
269                                 buf = pstrdup("timestamp without time zone");
270                         break;
271
272                 case TIMESTAMPTZOID:
273                         if (with_typemod)
274                                 buf = printTypmod("timestamp", typemod, typeform->typmodout);
275                         else
276                                 buf = pstrdup("timestamp with time zone");
277                         break;
278
279                 case VARBITOID:
280                         if (with_typemod)
281                                 buf = printTypmod("bit varying", typemod, typeform->typmodout);
282                         else
283                                 buf = pstrdup("bit varying");
284                         break;
285
286                 case VARCHAROID:
287                         if (with_typemod)
288                                 buf = printTypmod("character varying", typemod, typeform->typmodout);
289                         else
290                                 buf = pstrdup("character varying");
291                         break;
292         }
293
294         if (buf == NULL)
295         {
296                 /*
297                  * Default handling: report the name as it appears in the catalog.
298                  * Here, we must qualify the name if it is not visible in the search
299                  * path, and we must double-quote it if it's not a standard identifier
300                  * or if it matches any keyword.
301                  */
302                 char       *nspname;
303                 char       *typname;
304
305                 if (!force_qualify && TypeIsVisible(type_oid))
306                         nspname = NULL;
307                 else
308                         nspname = get_namespace_name(typeform->typnamespace);
309
310                 typname = NameStr(typeform->typname);
311
312                 buf = quote_qualified_identifier(nspname, typname);
313
314                 if (with_typemod)
315                         buf = printTypmod(buf, typemod, typeform->typmodout);
316         }
317
318         if (is_array)
319                 buf = psprintf("%s[]", buf);
320
321         ReleaseSysCache(tuple);
322
323         return buf;
324 }
325
326
327 /*
328  * Add typmod decoration to the basic type name
329  */
330 static char *
331 printTypmod(const char *typname, int32 typmod, Oid typmodout)
332 {
333         char       *res;
334
335         /* Shouldn't be called if typmod is -1 */
336         Assert(typmod >= 0);
337
338         if (typmodout == InvalidOid)
339         {
340                 /* Default behavior: just print the integer typmod with parens */
341                 res = psprintf("%s(%d)", typname, (int) typmod);
342         }
343         else
344         {
345                 /* Use the type-specific typmodout procedure */
346                 char       *tmstr;
347
348                 tmstr = DatumGetCString(OidFunctionCall1(typmodout,
349                                                                                                  Int32GetDatum(typmod)));
350                 res = psprintf("%s%s", typname, tmstr);
351         }
352
353         return res;
354 }
355
356
357 /*
358  * type_maximum_size --- determine maximum width of a variable-width column
359  *
360  * If the max width is indeterminate, return -1.  In particular, we return
361  * -1 for any type not known to this routine.  We assume the caller has
362  * already determined that the type is a variable-width type, so it's not
363  * necessary to look up the type's pg_type tuple here.
364  *
365  * This may appear unrelated to format_type(), but in fact the two routines
366  * share knowledge of the encoding of typmod for different types, so it's
367  * convenient to keep them together.  (XXX now that most of this knowledge
368  * has been pushed out of format_type into the typmodout functions, it's
369  * interesting to wonder if it's worth trying to factor this code too...)
370  */
371 int32
372 type_maximum_size(Oid type_oid, int32 typemod)
373 {
374         if (typemod < 0)
375                 return -1;
376
377         switch (type_oid)
378         {
379                 case BPCHAROID:
380                 case VARCHAROID:
381                         /* typemod includes varlena header */
382
383                         /* typemod is in characters not bytes */
384                         return (typemod - VARHDRSZ) *
385                                 pg_encoding_max_length(GetDatabaseEncoding())
386                                 + VARHDRSZ;
387
388                 case NUMERICOID:
389                         return numeric_maximum_size(typemod);
390
391                 case VARBITOID:
392                 case BITOID:
393                         /* typemod is the (max) number of bits */
394                         return (typemod + (BITS_PER_BYTE - 1)) / BITS_PER_BYTE
395                                 + 2 * sizeof(int32);
396         }
397
398         /* Unknown type, or unlimited-width type such as 'text' */
399         return -1;
400 }
401
402
403 /*
404  * oidvectortypes                       - converts a vector of type OIDs to "typname" list
405  */
406 Datum
407 oidvectortypes(PG_FUNCTION_ARGS)
408 {
409         oidvector  *oidArray = (oidvector *) PG_GETARG_POINTER(0);
410         char       *result;
411         int                     numargs = oidArray->dim1;
412         int                     num;
413         size_t          total;
414         size_t          left;
415
416         total = 20 * numargs + 1;
417         result = palloc(total);
418         result[0] = '\0';
419         left = total - 1;
420
421         for (num = 0; num < numargs; num++)
422         {
423                 char       *typename = format_type_internal(oidArray->values[num], -1,
424                                                                                                         false, true, false);
425                 size_t          slen = strlen(typename);
426
427                 if (left < (slen + 2))
428                 {
429                         total += slen + 2;
430                         result = repalloc(result, total);
431                         left += slen + 2;
432                 }
433
434                 if (num > 0)
435                 {
436                         strcat(result, ", ");
437                         left -= 2;
438                 }
439                 strcat(result, typename);
440                 left -= slen;
441         }
442
443         PG_RETURN_TEXT_P(cstring_to_text(result));
444 }