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