1<!--
2doc/src/sgml/ref/create_cast.sgml
3PostgreSQL documentation
4-->
5
6<refentry id="sql-createcast">
7 <indexterm zone="sql-createcast">
8  <primary>CREATE CAST</primary>
9 </indexterm>
10
11 <refmeta>
12  <refentrytitle>CREATE CAST</refentrytitle>
13  <manvolnum>7</manvolnum>
14  <refmiscinfo>SQL - Language Statements</refmiscinfo>
15 </refmeta>
16
17 <refnamediv>
18  <refname>CREATE CAST</refname>
19  <refpurpose>define a new cast</refpurpose>
20 </refnamediv>
21
22 <refsynopsisdiv>
23<synopsis>
24CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>)
25    WITH FUNCTION <replaceable>function_name</replaceable> [ (<replaceable>argument_type</replaceable> [, ...]) ]
26    [ AS ASSIGNMENT | AS IMPLICIT ]
27
28CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>)
29    WITHOUT FUNCTION
30    [ AS ASSIGNMENT | AS IMPLICIT ]
31
32CREATE CAST (<replaceable>source_type</replaceable> AS <replaceable>target_type</replaceable>)
33    WITH INOUT
34    [ AS ASSIGNMENT | AS IMPLICIT ]
35</synopsis>
36 </refsynopsisdiv>
37
38 <refsect1 id="sql-createcast-description">
39  <title>Description</title>
40
41  <para>
42   <command>CREATE CAST</command> defines a new cast.  A cast
43   specifies how to perform a conversion between
44   two data types.  For example,
45<programlisting>
46SELECT CAST(42 AS float8);
47</programlisting>
48   converts the integer constant 42 to type <type>float8</type> by
49   invoking a previously specified function, in this case
50   <literal>float8(int4)</literal>. (If no suitable cast has been defined, the
51   conversion fails.)
52  </para>
53
54  <para>
55   Two types can be <firstterm>binary coercible</firstterm>, which
56   means that the conversion can be performed <quote>for free</quote>
57   without invoking any function.  This requires that corresponding
58   values use the same internal representation.  For instance, the
59   types <type>text</type> and <type>varchar</type> are binary
60   coercible both ways.  Binary coercibility is not necessarily a
61   symmetric relationship.  For example, the cast
62   from <type>xml</type> to <type>text</type> can be performed for
63   free in the present implementation, but the reverse direction
64   requires a function that performs at least a syntax check.  (Two
65   types that are binary coercible both ways are also referred to as
66   binary compatible.)
67  </para>
68
69  <para>
70   You can define a cast as an <firstterm>I/O conversion cast</firstterm> by using
71   the <literal>WITH INOUT</literal> syntax. An I/O conversion cast is
72   performed by invoking the output function of the source data type, and
73   passing the resulting string to the input function of the target data type.
74   In many common cases, this feature avoids the need to write a separate
75   cast function for conversion. An I/O conversion cast acts the same as
76   a regular function-based cast; only the implementation is different.
77  </para>
78
79  <para>
80   By default, a cast can be invoked only by an explicit cast request,
81   that is an explicit <literal>CAST(<replaceable>x</replaceable> AS
82   <replaceable>typename</replaceable>)</literal> or
83   <replaceable>x</replaceable><literal>::</literal><replaceable>typename</replaceable>
84   construct.
85  </para>
86
87  <para>
88   If the cast is marked <literal>AS ASSIGNMENT</literal> then it can be invoked
89   implicitly when assigning a value to a column of the target data type.
90   For example, supposing that <literal>foo.f1</literal> is a column of
91   type <type>text</type>, then:
92<programlisting>
93INSERT INTO foo (f1) VALUES (42);
94</programlisting>
95   will be allowed if the cast from type <type>integer</type> to type
96   <type>text</type> is marked <literal>AS ASSIGNMENT</literal>, otherwise not.
97   (We generally use the term <firstterm>assignment
98   cast</firstterm> to describe this kind of cast.)
99  </para>
100
101  <para>
102   If the cast is marked <literal>AS IMPLICIT</literal> then it can be invoked
103   implicitly in any context, whether assignment or internally in an
104   expression.  (We generally use the term <firstterm>implicit
105   cast</firstterm> to describe this kind of cast.)
106   For example, consider this query:
107<programlisting>
108SELECT 2 + 4.0;
109</programlisting>
110   The parser initially marks the constants as being of type <type>integer</type>
111   and <type>numeric</type> respectively.  There is no <type>integer</type>
112   <literal>+</literal> <type>numeric</type> operator in the system catalogs,
113   but there is a <type>numeric</type> <literal>+</literal> <type>numeric</type> operator.
114   The query will therefore succeed if a cast from <type>integer</type> to
115   <type>numeric</type> is available and is marked <literal>AS IMPLICIT</literal> &mdash;
116   which in fact it is.  The parser will apply the implicit cast and resolve
117   the query as if it had been written
118<programlisting>
119SELECT CAST ( 2 AS numeric ) + 4.0;
120</programlisting>
121  </para>
122
123  <para>
124   Now, the catalogs also provide a cast from <type>numeric</type> to
125   <type>integer</type>.  If that cast were marked <literal>AS IMPLICIT</literal> &mdash;
126   which it is not &mdash; then the parser would be faced with choosing
127   between the above interpretation and the alternative of casting the
128   <type>numeric</type> constant to <type>integer</type> and applying the
129   <type>integer</type> <literal>+</literal> <type>integer</type> operator.  Lacking any
130   knowledge of which choice to prefer, it would give up and declare the
131   query ambiguous.  The fact that only one of the two casts is
132   implicit is the way in which we teach the parser to prefer resolution
133   of a mixed <type>numeric</type>-and-<type>integer</type> expression as
134   <type>numeric</type>; there is no built-in knowledge about that.
135  </para>
136
137  <para>
138   It is wise to be conservative about marking casts as implicit.  An
139   overabundance of implicit casting paths can cause
140   <productname>PostgreSQL</productname> to choose surprising
141   interpretations of commands, or to be unable to resolve commands at
142   all because there are multiple possible interpretations.  A good
143   rule of thumb is to make a cast implicitly invokable only for
144   information-preserving transformations between types in the same
145   general type category.  For example, the cast from <type>int2</type> to
146   <type>int4</type> can reasonably be implicit, but the cast from
147   <type>float8</type> to <type>int4</type> should probably be
148   assignment-only.  Cross-type-category casts, such as <type>text</type>
149   to <type>int4</type>, are best made explicit-only.
150  </para>
151
152  <note>
153   <para>
154    Sometimes it is necessary for usability or standards-compliance reasons
155    to provide multiple implicit casts among a set of types, resulting in
156    ambiguity that cannot be avoided as above.  The parser has a fallback
157    heuristic based on <firstterm>type categories</firstterm> and <firstterm>preferred
158    types</firstterm> that can help to provide desired behavior in such cases.  See
159    <xref linkend="sql-createtype"/> for
160    more information.
161   </para>
162  </note>
163
164  <para>
165   To be able to create a cast, you must own the source or the target data type
166   and have <literal>USAGE</literal> privilege on the other type.  To create a
167   binary-coercible cast, you must be superuser.  (This restriction is made
168   because an erroneous binary-coercible cast conversion can easily crash the
169   server.)
170  </para>
171 </refsect1>
172
173 <refsect1>
174  <title>Parameters</title>
175
176   <variablelist>
177    <varlistentry>
178     <term><replaceable>source_type</replaceable></term>
179
180     <listitem>
181      <para>
182       The name of the source data type of the cast.
183      </para>
184     </listitem>
185    </varlistentry>
186
187    <varlistentry>
188     <term><replaceable>target_type</replaceable></term>
189
190     <listitem>
191      <para>
192       The name of the target data type of the cast.
193      </para>
194     </listitem>
195    </varlistentry>
196
197    <varlistentry>
198     <term><literal><replaceable>function_name</replaceable>[(<replaceable>argument_type</replaceable> [, ...])]</literal></term>
199
200     <listitem>
201      <para>
202       The function used to perform the cast.  The function name can
203       be schema-qualified.  If it is not, the function will be looked
204       up in the schema search path.  The function's result data type must
205       match the target type of the cast.   Its arguments are discussed below.
206       If no argument list is specified, the function name must be unique in
207       its schema.
208      </para>
209     </listitem>
210    </varlistentry>
211
212    <varlistentry>
213     <term><literal>WITHOUT FUNCTION</literal></term>
214
215     <listitem>
216      <para>
217       Indicates that the source type is binary-coercible to the target type,
218       so no function is required to perform the cast.
219      </para>
220     </listitem>
221    </varlistentry>
222
223    <varlistentry>
224     <term><literal>WITH INOUT</literal></term>
225
226     <listitem>
227      <para>
228       Indicates that the cast is an I/O conversion cast, performed by
229       invoking the output function of the source data type, and passing the
230       resulting string to the input function of the target data type.
231      </para>
232     </listitem>
233    </varlistentry>
234
235    <varlistentry>
236     <term><literal>AS ASSIGNMENT</literal></term>
237
238     <listitem>
239      <para>
240       Indicates that the cast can be invoked implicitly in assignment
241       contexts.
242      </para>
243     </listitem>
244    </varlistentry>
245
246    <varlistentry>
247     <term><literal>AS IMPLICIT</literal></term>
248
249     <listitem>
250      <para>
251       Indicates that the cast can be invoked implicitly in any context.
252      </para>
253     </listitem>
254    </varlistentry>
255   </variablelist>
256
257  <para>
258   Cast implementation functions can have one to three arguments.
259   The first argument type must be identical to or binary-coercible from
260   the cast's source type.  The second argument,
261   if present, must be type <type>integer</type>; it receives the type
262   modifier associated with the destination type, or <literal>-1</literal>
263   if there is none.  The third argument,
264   if present, must be type <type>boolean</type>; it receives <literal>true</literal>
265   if the cast is an explicit cast, <literal>false</literal> otherwise.
266   (Bizarrely, the SQL standard demands different behaviors for explicit and
267   implicit casts in some cases.  This argument is supplied for functions
268   that must implement such casts.  It is not recommended that you design
269   your own data types so that this matters.)
270  </para>
271
272  <para>
273   The return type of a cast function must be identical to or
274   binary-coercible to the cast's target type.
275  </para>
276
277  <para>
278   Ordinarily a cast must have different source and target data types.
279   However, it is allowed to declare a cast with identical source and
280   target types if it has a cast implementation function with more than one
281   argument.  This is used to represent type-specific length coercion
282   functions in the system catalogs.  The named function is used to
283   coerce a value of the type to the type modifier value given by its
284   second argument.
285  </para>
286
287  <para>
288   When a cast has different source and
289   target types and a function that takes more than one argument, it
290   supports converting from one type to another and applying a length
291   coercion in a single step.  When no such entry is available, coercion
292   to a type that uses a type modifier involves two cast steps, one to
293   convert between data types and a second to apply the modifier.
294  </para>
295
296  <para>
297   A cast to or from a domain type currently has no effect.  Casting
298   to or from a domain uses the casts associated with its underlying type.
299  </para>
300
301 </refsect1>
302
303 <refsect1 id="sql-createcast-notes">
304  <title>Notes</title>
305
306  <para>
307   Use <xref linkend="sql-dropcast"/> to remove user-defined casts.
308  </para>
309
310  <para>
311   Remember that if you want to be able to convert types both ways you
312   need to declare casts both ways explicitly.
313  </para>
314
315 <indexterm zone="sql-createcast">
316  <primary>cast</primary>
317  <secondary>I/O conversion</secondary>
318 </indexterm>
319
320  <para>
321   It is normally not necessary to create casts between user-defined types
322   and the standard string types (<type>text</type>, <type>varchar</type>, and
323   <type>char(<replaceable>n</replaceable>)</type>, as well as user-defined types that
324   are defined to be in the string category).  <productname>PostgreSQL</productname>
325   provides automatic I/O conversion casts for that. The automatic casts to
326   string types are treated as assignment casts, while the automatic casts
327   from string types are
328   explicit-only.  You can override this behavior by declaring your own
329   cast to replace an automatic cast, but usually the only reason to
330   do so is if you want the conversion to be more easily invokable than the
331   standard assignment-only or explicit-only setting.  Another possible
332   reason is that you want the conversion to behave differently from the
333   type's I/O function; but that is sufficiently surprising that you
334   should think twice about whether it's a good idea.  (A small number of
335   the built-in types do indeed have different behaviors for conversions,
336   mostly because of requirements of the SQL standard.)
337  </para>
338
339  <para>
340   While not required, it is recommended that you continue to follow this old
341   convention of naming cast implementation functions after the target data
342   type.  Many users are used to being able to cast data types using a
343   function-style notation, that is
344   <replaceable>typename</replaceable>(<replaceable>x</replaceable>).  This notation is in fact
345   nothing more nor less than a call of the cast implementation function; it
346   is not specially treated as a cast.  If your conversion functions are not
347   named to support this convention then you will have surprised users.
348   Since <productname>PostgreSQL</productname> allows overloading of the same function
349   name with different argument types, there is no difficulty in having
350   multiple conversion functions from different types that all use the
351   target type's name.
352  </para>
353
354  <note>
355   <para>
356    Actually the preceding paragraph is an oversimplification: there are
357    two cases in which a function-call construct will be treated as a cast
358    request without having matched it to an actual function.
359    If a function call <replaceable>name</replaceable>(<replaceable>x</replaceable>) does not
360    exactly match any existing function, but <replaceable>name</replaceable> is the name
361    of a data type and <structname>pg_cast</structname> provides a binary-coercible cast
362    to this type from the type of <replaceable>x</replaceable>, then the call will be
363    construed as a binary-coercible cast.  This exception is made so that
364    binary-coercible casts can be invoked using functional syntax, even
365    though they lack any function.  Likewise, if there is no
366    <structname>pg_cast</structname> entry but the cast would be to or from a string
367    type, the call will be construed as an I/O conversion cast.  This
368    exception allows I/O conversion casts to be invoked using functional
369    syntax.
370   </para>
371  </note>
372
373  <note>
374   <para>
375    There is also an exception to the exception: I/O conversion casts from
376    composite types to string types cannot be invoked using functional
377    syntax, but must be written in explicit cast syntax (either
378    <literal>CAST</literal> or <literal>::</literal> notation).  This exception was added
379    because after the introduction of automatically-provided I/O conversion
380    casts, it was found too easy to accidentally invoke such a cast when
381    a function or column reference was intended.
382   </para>
383  </note>
384 </refsect1>
385
386
387 <refsect1 id="sql-createcast-examples">
388  <title>Examples</title>
389
390  <para>
391   To create an assignment cast from type <type>bigint</type> to type
392   <type>int4</type> using the function <literal>int4(bigint)</literal>:
393<programlisting>
394CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT;
395</programlisting>
396   (This cast is already predefined in the system.)
397  </para>
398 </refsect1>
399
400 <refsect1 id="sql-createcast-compat">
401  <title>Compatibility</title>
402
403  <para>
404   The <command>CREATE CAST</command> command conforms to the
405   <acronym>SQL</acronym> standard,
406   except that SQL does not make provisions for binary-coercible
407   types or extra arguments to implementation functions.
408   <literal>AS IMPLICIT</literal> is a <productname>PostgreSQL</productname>
409   extension, too.
410  </para>
411 </refsect1>
412
413
414 <refsect1 id="sql-createcast-seealso">
415  <title>See Also</title>
416
417  <para>
418   <xref linkend="sql-createfunction"/>,
419   <xref linkend="sql-createtype"/>,
420   <xref linkend="sql-dropcast"/>
421  </para>
422 </refsect1>
423
424</refentry>
425