PostgreSQL Source Code  git master
format_type.c File Reference
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "mb/pg_wchar.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/numeric.h"
#include "utils/syscache.h"
Include dependency graph for format_type.c:

Go to the source code of this file.

Functions

static char * printTypmod (const char *typname, int32 typmod, Oid typmodout)
 
Datum format_type (PG_FUNCTION_ARGS)
 
char * format_type_extended (Oid type_oid, int32 typemod, bits16 flags)
 
char * format_type_be (Oid type_oid)
 
char * format_type_be_qualified (Oid type_oid)
 
char * format_type_with_typemod (Oid type_oid, int32 typemod)
 
int32 type_maximum_size (Oid type_oid, int32 typemod)
 
Datum oidvectortypes (PG_FUNCTION_ARGS)
 

Function Documentation

◆ format_type()

Datum format_type ( PG_FUNCTION_ARGS  )

Definition at line 59 of file format_type.c.

References cstring_to_text(), FORMAT_TYPE_ALLOW_INVALID, format_type_extended(), FORMAT_TYPE_TYPEMOD_GIVEN, PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

60 {
61  Oid type_oid;
62  int32 typemod;
63  char *result;
65 
66  /* Since this function is not strict, we must test for null args */
67  if (PG_ARGISNULL(0))
69 
70  type_oid = PG_GETARG_OID(0);
71 
72  if (PG_ARGISNULL(1))
73  typemod = -1;
74  else
75  {
76  typemod = PG_GETARG_INT32(1);
78  }
79 
80  result = format_type_extended(type_oid, typemod, flags);
81 
83 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
uint16 bits16
Definition: c.h:375
#define FORMAT_TYPE_TYPEMOD_GIVEN
Definition: builtins.h:113
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:355
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define FORMAT_TYPE_ALLOW_INVALID
Definition: builtins.h:114
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:370
text * cstring_to_text(const char *s)
Definition: varlena.c:172
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:111
#define PG_RETURN_NULL()
Definition: fmgr.h:344

◆ format_type_be()

char* format_type_be ( Oid  type_oid)

Definition at line 339 of file format_type.c.

References format_type_extended().

Referenced by aclcheck_error_type(), addFamilyMember(), addRangeTableEntryForFunction(), AggregateCreate(), AlterType(), AlterTypeNamespace(), AlterTypeNamespace_oid(), AlterTypeNamespaceInternal(), AlterTypeOwner(), appendTypeNameToBuffer(), array_cat(), array_cmp(), array_contain_compare(), array_eq(), array_position_common(), array_positions(), array_recv(), array_replace_internal(), array_send(), assign_record_type_identifier(), ATAddForeignKeyConstraint(), ATExecAlterColumnType(), ATExecSetStorage(), ATPrepAlterColumnType(), brinvalidate(), btvalidate(), build_attrmap_by_name(), build_column_default(), build_datatype(), build_pertrans_for_aggref(), build_subplan(), CastCreate(), check_object_ownership(), check_of_type(), check_safe_enum_use(), check_sql_fn_retval(), check_valid_polymorphic_signature(), CheckAttributeType(), checkDomainOwner(), checkEnumOwner(), checkRuleResultList(), CheckVarSlotCompatibility(), coerce_record_to_complex(), coerce_to_boolean(), coerce_to_common_type(), coerce_to_specific_type_typmod(), coerce_type(), compare_values_of_enum(), compile_plperl_function(), compile_pltcl_function(), ComputeIndexAttrs(), ComputePartitionAttrs(), cookDefault(), create_ctas_nodata(), CreateCast(), CreateFunction(), CreateStatistics(), CreateTransform(), DefineAggregate(), DefineDomain(), DefineRange(), DefineType(), do_compile(), domain_check_input(), domain_state_setup(), dropOperators(), dropProcedures(), enforce_generic_type_consistency(), enum_first(), enum_in(), enum_last(), enum_recv(), EvaluateParams(), exec_stmt_foreach_a(), ExecCheckPlanOutput(), ExecEvalArrayExpr(), ExecEvalConstraintCheck(), ExecEvalConstraintNotNull(), ExecEvalFieldSelect(), ExecEvalParamExtern(), ExecEvalWholeRowVar(), ExecInitExprRec(), exprType(), fetch_cursor_param_value(), findRangeSubOpclass(), findTypeInputFunction(), findTypeReceiveFunction(), fmgr_sql_validator(), format_operator_extended(), format_procedure_extended(), funcname_signature_string(), get_cast_oid(), get_domain_constraint_oid(), get_expr_result_tupdesc(), get_range_io_data(), get_rels_with_domain(), get_sort_group_operators(), get_transform_oid(), get_ts_parser_func(), get_ts_template_func(), GetColumnDefCollation(), GetDefaultOpClass(), getObjectDescription(), getTypeBinaryInputInfo(), getTypeBinaryOutputInfo(), getTypeInputInfo(), getTypeOutputInfo(), hash_array(), hash_array_extended(), hash_range(), hash_range_extended(), hashvalidate(), init_params(), initArrayResultArr(), initGinState(), internal_get_result_type(), intorel_startup(), load_enum_cache_data(), logicalrep_typmap_gettypname(), lookup_rowtype_tupdesc_domain(), lookup_rowtype_tupdesc_internal(), LookupTypeNameExtended(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), make_row_comparison_op(), make_scalar_array_op(), op_signature_string(), ParseFuncOrColumn(), pg_collation_for(), plperl_array_to_datum(), plperl_sv_to_datum(), plperl_validator(), plpgsql_build_variable(), plpgsql_param_eval_generic(), plpgsql_param_eval_generic_ro(), plpgsql_param_eval_recfield(), plpgsql_validator(), PLy_procedure_create(), prepare_sql_fn_parse_info(), print_function_arguments(), print_function_rettype(), print_function_trftypes(), processIndirection(), record_cmp(), record_eq(), record_image_cmp(), record_image_eq(), regtypeout(), RelationBuildPartitionKey(), RenameConstraintById(), RenameType(), resolve_anyarray_from_others(), resolve_anyelement_from_others(), ResolveOpClass(), revalidate_rectypeid(), ri_HashCompareOp(), satisfies_hash_partition(), select_common_type(), select_common_type_from_oids(), slot_store_error_callback(), spgvalidate(), storeOperators(), storeProcedures(), transformAggregateCall(), transformArrayExpr(), transformAssignedExpr(), transformAssignmentIndirection(), transformAssignmentSubscripts(), transformCollateClause(), transformColumnType(), transformContainerSubscripts(), transformContainerType(), transformFrameOffset(), transformPartitionBoundValue(), transformTypeCast(), transformXmlSerialize(), tuple_to_stringinfo(), tupledesc_match(), tuples_equal(), unknown_attribute(), validateConnectbyTupleDesc(), variable_coerce_param_hook(), and width_bucket_array().

340 {
341  return format_type_extended(type_oid, -1, 0);
342 }
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:111

◆ format_type_be_qualified()

char* format_type_be_qualified ( Oid  type_oid)

Definition at line 349 of file format_type.c.

References format_type_extended(), and FORMAT_TYPE_FORCE_QUALIFY.

Referenced by format_operator_extended(), format_operator_parts(), format_procedure_extended(), format_procedure_parts(), and getObjectIdentityParts().

350 {
351  return format_type_extended(type_oid, -1, FORMAT_TYPE_FORCE_QUALIFY);
352 }
#define FORMAT_TYPE_FORCE_QUALIFY
Definition: builtins.h:115
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:111

◆ format_type_extended()

char* format_type_extended ( Oid  type_oid,
int32  typemod,
bits16  flags 
)

Definition at line 111 of file format_type.c.

References buf, elog, ERROR, FORMAT_TYPE_ALLOW_INVALID, FORMAT_TYPE_FORCE_QUALIFY, FORMAT_TYPE_INVALID_AS_NULL, FORMAT_TYPE_TYPEMOD_GIVEN, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, InvalidOid, NameStr, ObjectIdGetDatum, printTypmod(), psprintf(), pstrdup(), quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1(), TypeIsVisible(), TYPEOID, and typname.

Referenced by deparse_type_name(), format_type(), format_type_be(), format_type_be_qualified(), format_type_with_typemod(), lookup_am_handler_func(), and oidvectortypes().

112 {
113  HeapTuple tuple;
114  Form_pg_type typeform;
115  Oid array_base_type;
116  bool is_array;
117  char *buf;
118  bool with_typemod;
119 
120  if (type_oid == InvalidOid)
121  {
122  if ((flags & FORMAT_TYPE_INVALID_AS_NULL) != 0)
123  return NULL;
124  else if ((flags & FORMAT_TYPE_ALLOW_INVALID) != 0)
125  return pstrdup("-");
126  }
127 
128  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
129  if (!HeapTupleIsValid(tuple))
130  {
131  if ((flags & FORMAT_TYPE_INVALID_AS_NULL) != 0)
132  return NULL;
133  else if ((flags & FORMAT_TYPE_ALLOW_INVALID) != 0)
134  return pstrdup("???");
135  else
136  elog(ERROR, "cache lookup failed for type %u", type_oid);
137  }
138  typeform = (Form_pg_type) GETSTRUCT(tuple);
139 
140  /*
141  * Check if it's a regular (variable length) array type. Fixed-length
142  * array types such as "name" shouldn't get deconstructed. As of Postgres
143  * 8.1, rather than checking typlen we check the toast property, and don't
144  * deconstruct "plain storage" array types --- this is because we don't
145  * want to show oidvector as oid[].
146  */
147  array_base_type = typeform->typelem;
148 
149  if (array_base_type != InvalidOid &&
150  typeform->typstorage != TYPSTORAGE_PLAIN)
151  {
152  /* Switch our attention to the array element type */
153  ReleaseSysCache(tuple);
154  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(array_base_type));
155  if (!HeapTupleIsValid(tuple))
156  {
157  if ((flags & FORMAT_TYPE_INVALID_AS_NULL) != 0)
158  return NULL;
159  else if ((flags & FORMAT_TYPE_ALLOW_INVALID) != 0)
160  return pstrdup("???[]");
161  else
162  elog(ERROR, "cache lookup failed for type %u", type_oid);
163  }
164  typeform = (Form_pg_type) GETSTRUCT(tuple);
165  type_oid = array_base_type;
166  is_array = true;
167  }
168  else
169  is_array = false;
170 
171  with_typemod = (flags & FORMAT_TYPE_TYPEMOD_GIVEN) != 0 && (typemod >= 0);
172 
173  /*
174  * See if we want to special-case the output for certain built-in types.
175  * Note that these special cases should all correspond to special
176  * productions in gram.y, to ensure that the type name will be taken as a
177  * system type, not a user type of the same name.
178  *
179  * If we do not provide a special-case output here, the type name will be
180  * handled the same way as a user type name --- in particular, it will be
181  * double-quoted if it matches any lexer keyword. This behavior is
182  * essential for some cases, such as types "bit" and "char".
183  */
184  buf = NULL; /* flag for no special case */
185 
186  switch (type_oid)
187  {
188  case BITOID:
189  if (with_typemod)
190  buf = printTypmod("bit", typemod, typeform->typmodout);
191  else if ((flags & FORMAT_TYPE_TYPEMOD_GIVEN) != 0)
192  {
193  /*
194  * bit with typmod -1 is not the same as BIT, which means
195  * BIT(1) per SQL spec. Report it as the quoted typename so
196  * that parser will not assign a bogus typmod.
197  */
198  }
199  else
200  buf = pstrdup("bit");
201  break;
202 
203  case BOOLOID:
204  buf = pstrdup("boolean");
205  break;
206 
207  case BPCHAROID:
208  if (with_typemod)
209  buf = printTypmod("character", typemod, typeform->typmodout);
210  else if ((flags & FORMAT_TYPE_TYPEMOD_GIVEN) != 0)
211  {
212  /*
213  * bpchar with typmod -1 is not the same as CHARACTER, which
214  * means CHARACTER(1) per SQL spec. Report it as bpchar so
215  * that parser will not assign a bogus typmod.
216  */
217  }
218  else
219  buf = pstrdup("character");
220  break;
221 
222  case FLOAT4OID:
223  buf = pstrdup("real");
224  break;
225 
226  case FLOAT8OID:
227  buf = pstrdup("double precision");
228  break;
229 
230  case INT2OID:
231  buf = pstrdup("smallint");
232  break;
233 
234  case INT4OID:
235  buf = pstrdup("integer");
236  break;
237 
238  case INT8OID:
239  buf = pstrdup("bigint");
240  break;
241 
242  case NUMERICOID:
243  if (with_typemod)
244  buf = printTypmod("numeric", typemod, typeform->typmodout);
245  else
246  buf = pstrdup("numeric");
247  break;
248 
249  case INTERVALOID:
250  if (with_typemod)
251  buf = printTypmod("interval", typemod, typeform->typmodout);
252  else
253  buf = pstrdup("interval");
254  break;
255 
256  case TIMEOID:
257  if (with_typemod)
258  buf = printTypmod("time", typemod, typeform->typmodout);
259  else
260  buf = pstrdup("time without time zone");
261  break;
262 
263  case TIMETZOID:
264  if (with_typemod)
265  buf = printTypmod("time", typemod, typeform->typmodout);
266  else
267  buf = pstrdup("time with time zone");
268  break;
269 
270  case TIMESTAMPOID:
271  if (with_typemod)
272  buf = printTypmod("timestamp", typemod, typeform->typmodout);
273  else
274  buf = pstrdup("timestamp without time zone");
275  break;
276 
277  case TIMESTAMPTZOID:
278  if (with_typemod)
279  buf = printTypmod("timestamp", typemod, typeform->typmodout);
280  else
281  buf = pstrdup("timestamp with time zone");
282  break;
283 
284  case VARBITOID:
285  if (with_typemod)
286  buf = printTypmod("bit varying", typemod, typeform->typmodout);
287  else
288  buf = pstrdup("bit varying");
289  break;
290 
291  case VARCHAROID:
292  if (with_typemod)
293  buf = printTypmod("character varying", typemod, typeform->typmodout);
294  else
295  buf = pstrdup("character varying");
296  break;
297  }
298 
299  if (buf == NULL)
300  {
301  /*
302  * Default handling: report the name as it appears in the catalog.
303  * Here, we must qualify the name if it is not visible in the search
304  * path or if caller requests it; and we must double-quote it if it's
305  * not a standard identifier or if it matches any keyword.
306  */
307  char *nspname;
308  char *typname;
309 
310  if ((flags & FORMAT_TYPE_FORCE_QUALIFY) == 0 &&
311  TypeIsVisible(type_oid))
312  nspname = NULL;
313  else
314  nspname = get_namespace_name_or_temp(typeform->typnamespace);
315 
316  typname = NameStr(typeform->typname);
317 
318  buf = quote_qualified_identifier(nspname, typname);
319 
320  if (with_typemod)
321  buf = printTypmod(buf, typemod, typeform->typmodout);
322  }
323 
324  if (is_array)
325  buf = psprintf("%s[]", buf);
326 
327  ReleaseSysCache(tuple);
328 
329  return buf;
330 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define FORMAT_TYPE_TYPEMOD_GIVEN
Definition: builtins.h:113
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define FORMAT_TYPE_FORCE_QUALIFY
Definition: builtins.h:115
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10811
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define FORMAT_TYPE_ALLOW_INVALID
Definition: builtins.h:114
#define FORMAT_TYPE_INVALID_AS_NULL
Definition: builtins.h:116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool TypeIsVisible(Oid typid)
Definition: namespace.c:816
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
static char * printTypmod(const char *typname, int32 typmod, Oid typmodout)
Definition: format_type.c:367
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3215
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ format_type_with_typemod()

char* format_type_with_typemod ( Oid  type_oid,
int32  typemod 
)

◆ oidvectortypes()

Datum oidvectortypes ( PG_FUNCTION_ARGS  )

Definition at line 443 of file format_type.c.

References cstring_to_text(), oidvector::dim1, FORMAT_TYPE_ALLOW_INVALID, format_type_extended(), palloc(), PG_GETARG_POINTER, PG_RETURN_TEXT_P, repalloc(), and oidvector::values.

444 {
445  oidvector *oidArray = (oidvector *) PG_GETARG_POINTER(0);
446  char *result;
447  int numargs = oidArray->dim1;
448  int num;
449  size_t total;
450  size_t left;
451 
452  total = 20 * numargs + 1;
453  result = palloc(total);
454  result[0] = '\0';
455  left = total - 1;
456 
457  for (num = 0; num < numargs; num++)
458  {
459  char *typename = format_type_extended(oidArray->values[num], -1,
461  size_t slen = strlen(typename);
462 
463  if (left < (slen + 2))
464  {
465  total += slen + 2;
466  result = repalloc(result, total);
467  left += slen + 2;
468  }
469 
470  if (num > 0)
471  {
472  strcat(result, ", ");
473  left -= 2;
474  }
475  strcat(result, typename);
476  left -= slen;
477  }
478 
480 }
Definition: c.h:594
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:602
int dim1
Definition: c.h:600
#define FORMAT_TYPE_ALLOW_INVALID
Definition: builtins.h:114
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:370
text * cstring_to_text(const char *s)
Definition: varlena.c:172
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:111
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
void * palloc(Size size)
Definition: mcxt.c:949

◆ printTypmod()

static char * printTypmod ( const char *  typname,
int32  typmod,
Oid  typmodout 
)
static

Definition at line 367 of file format_type.c.

References Assert, DatumGetCString, Int32GetDatum, InvalidOid, OidFunctionCall1, and psprintf().

Referenced by format_type_extended().

368 {
369  char *res;
370 
371  /* Shouldn't be called if typmod is -1 */
372  Assert(typmod >= 0);
373 
374  if (typmodout == InvalidOid)
375  {
376  /* Default behavior: just print the integer typmod with parens */
377  res = psprintf("%s(%d)", typname, (int) typmod);
378  }
379  else
380  {
381  /* Use the type-specific typmodout procedure */
382  char *tmstr;
383 
384  tmstr = DatumGetCString(OidFunctionCall1(typmodout,
385  Int32GetDatum(typmod)));
386  res = psprintf("%s%s", typname, tmstr);
387  }
388 
389  return res;
390 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define DatumGetCString(X)
Definition: postgres.h:566
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:662
NameData typname
Definition: pg_type.h:41
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:738
#define Int32GetDatum(X)
Definition: postgres.h:479

◆ type_maximum_size()

int32 type_maximum_size ( Oid  type_oid,
int32  typemod 
)

Definition at line 408 of file format_type.c.

References BITS_PER_BYTE, GetDatabaseEncoding(), numeric_maximum_size(), pg_encoding_max_length(), and VARHDRSZ.

Referenced by get_typavgwidth(), and heapam_relation_needs_toast_table().

409 {
410  if (typemod < 0)
411  return -1;
412 
413  switch (type_oid)
414  {
415  case BPCHAROID:
416  case VARCHAROID:
417  /* typemod includes varlena header */
418 
419  /* typemod is in characters not bytes */
420  return (typemod - VARHDRSZ) *
422  + VARHDRSZ;
423 
424  case NUMERICOID:
425  return numeric_maximum_size(typemod);
426 
427  case VARBITOID:
428  case BITOID:
429  /* typemod is the (max) number of bits */
430  return (typemod + (BITS_PER_BYTE - 1)) / BITS_PER_BYTE
431  + 2 * sizeof(int32);
432  }
433 
434  /* Unknown type, or unlimited-width type such as 'text' */
435  return -1;
436 }
#define BITS_PER_BYTE
#define VARHDRSZ
Definition: c.h:561
signed int int32
Definition: c.h:355
int pg_encoding_max_length(int encoding)
Definition: wchar.c:1589
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
int32 numeric_maximum_size(int32 typmod)
Definition: numeric.c:690