]> begriffs open source - ai-pg/blob - full-docs/txt/sql-createtype.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / sql-createtype.txt
1
2 CREATE TYPE
3
4    CREATE TYPE — define a new data type
5
6 Synopsis
7
8 CREATE TYPE name AS
9     ( [ attribute_name data_type [ COLLATE collation ] [, ... ] ] )
10
11 CREATE TYPE name AS ENUM
12     ( [ 'label' [, ... ] ] )
13
14 CREATE TYPE name AS RANGE (
15     SUBTYPE = subtype
16     [ , SUBTYPE_OPCLASS = subtype_operator_class ]
17     [ , COLLATION = collation ]
18     [ , CANONICAL = canonical_function ]
19     [ , SUBTYPE_DIFF = subtype_diff_function ]
20     [ , MULTIRANGE_TYPE_NAME = multirange_type_name ]
21 )
22
23 CREATE TYPE name (
24     INPUT = input_function,
25     OUTPUT = output_function
26     [ , RECEIVE = receive_function ]
27     [ , SEND = send_function ]
28     [ , TYPMOD_IN = type_modifier_input_function ]
29     [ , TYPMOD_OUT = type_modifier_output_function ]
30     [ , ANALYZE = analyze_function ]
31     [ , SUBSCRIPT = subscript_function ]
32     [ , INTERNALLENGTH = { internallength | VARIABLE } ]
33     [ , PASSEDBYVALUE ]
34     [ , ALIGNMENT = alignment ]
35     [ , STORAGE = storage ]
36     [ , LIKE = like_type ]
37     [ , CATEGORY = category ]
38     [ , PREFERRED = preferred ]
39     [ , DEFAULT = default ]
40     [ , ELEMENT = element ]
41     [ , DELIMITER = delimiter ]
42     [ , COLLATABLE = collatable ]
43 )
44
45 CREATE TYPE name
46
47 Description
48
49    CREATE TYPE registers a new data type for use in the current database.
50    The user who defines a type becomes its owner.
51
52    If a schema name is given then the type is created in the specified
53    schema. Otherwise it is created in the current schema. The type name
54    must be distinct from the name of any existing type or domain in the
55    same schema. (Because tables have associated data types, the type name
56    must also be distinct from the name of any existing table in the same
57    schema.)
58
59    There are five forms of CREATE TYPE, as shown in the syntax synopsis
60    above. They respectively create a composite type, an enum type, a range
61    type, a base type, or a shell type. The first four of these are
62    discussed in turn below. A shell type is simply a placeholder for a
63    type to be defined later; it is created by issuing CREATE TYPE with no
64    parameters except for the type name. Shell types are needed as forward
65    references when creating range types and base types, as discussed in
66    those sections.
67
68 Composite Types
69
70    The first form of CREATE TYPE creates a composite type. The composite
71    type is specified by a list of attribute names and data types. An
72    attribute's collation can be specified too, if its data type is
73    collatable. A composite type is essentially the same as the row type of
74    a table, but using CREATE TYPE avoids the need to create an actual
75    table when all that is wanted is to define a type. A stand-alone
76    composite type is useful, for example, as the argument or return type
77    of a function.
78
79    To be able to create a composite type, you must have USAGE privilege on
80    all attribute types.
81
82 Enumerated Types
83
84    The second form of CREATE TYPE creates an enumerated (enum) type, as
85    described in Section 8.7. Enum types take a list of quoted labels, each
86    of which must be less than NAMEDATALEN bytes long (64 bytes in a
87    standard PostgreSQL build). (It is possible to create an enumerated
88    type with zero labels, but such a type cannot be used to hold values
89    before at least one label is added using ALTER TYPE.)
90
91 Range Types
92
93    The third form of CREATE TYPE creates a new range type, as described in
94    Section 8.17.
95
96    The range type's subtype can be any type with an associated b-tree
97    operator class (to determine the ordering of values for the range
98    type). Normally the subtype's default b-tree operator class is used to
99    determine ordering; to use a non-default operator class, specify its
100    name with subtype_opclass. If the subtype is collatable, and you want
101    to use a non-default collation in the range's ordering, specify the
102    desired collation with the collation option.
103
104    The optional canonical function must take one argument of the range
105    type being defined, and return a value of the same type. This is used
106    to convert range values to a canonical form, when applicable. See
107    Section 8.17.8 for more information. Creating a canonical function is a
108    bit tricky, since it must be defined before the range type can be
109    declared. To do this, you must first create a shell type, which is a
110    placeholder type that has no properties except a name and an owner.
111    This is done by issuing the command CREATE TYPE name, with no
112    additional parameters. Then the function can be declared using the
113    shell type as argument and result, and finally the range type can be
114    declared using the same name. This automatically replaces the shell
115    type entry with a valid range type.
116
117    The optional subtype_diff function must take two values of the subtype
118    type as argument, and return a double precision value representing the
119    difference between the two given values. While this is optional,
120    providing it allows much greater efficiency of GiST indexes on columns
121    of the range type. See Section 8.17.8 for more information.
122
123    The optional multirange_type_name parameter specifies the name of the
124    corresponding multirange type. If not specified, this name is chosen
125    automatically as follows. If the range type name contains the substring
126    range, then the multirange type name is formed by replacement of the
127    range substring with multirange in the range type name. Otherwise, the
128    multirange type name is formed by appending a _multirange suffix to the
129    range type name.
130
131 Base Types
132
133    The fourth form of CREATE TYPE creates a new base type (scalar type).
134    To create a new base type, you must be a superuser. (This restriction
135    is made because an erroneous type definition could confuse or even
136    crash the server.)
137
138    The parameters can appear in any order, not only that illustrated
139    above, and most are optional. You must register two or more functions
140    (using CREATE FUNCTION) before defining the type. The support functions
141    input_function and output_function are required, while the functions
142    receive_function, send_function, type_modifier_input_function,
143    type_modifier_output_function, analyze_function, and subscript_function
144    are optional. Generally these functions have to be coded in C or
145    another low-level language.
146
147    The input_function converts the type's external textual representation
148    to the internal representation used by the operators and functions
149    defined for the type. output_function performs the reverse
150    transformation. The input function can be declared as taking one
151    argument of type cstring, or as taking three arguments of types
152    cstring, oid, integer. The first argument is the input text as a C
153    string, the second argument is the type's own OID (except for array
154    types, which instead receive their element type's OID), and the third
155    is the typmod of the destination column, if known (-1 will be passed if
156    not). The input function must return a value of the data type itself.
157    Usually, an input function should be declared STRICT; if it is not, it
158    will be called with a NULL first parameter when reading a NULL input
159    value. The function must still return NULL in this case, unless it
160    raises an error. (This case is mainly meant to support domain input
161    functions, which might need to reject NULL inputs.) The output function
162    must be declared as taking one argument of the new data type. The
163    output function must return type cstring. Output functions are not
164    invoked for NULL values.
165
166    The optional receive_function converts the type's external binary
167    representation to the internal representation. If this function is not
168    supplied, the type cannot participate in binary input. The binary
169    representation should be chosen to be cheap to convert to internal
170    form, while being reasonably portable. (For example, the standard
171    integer data types use network byte order as the external binary
172    representation, while the internal representation is in the machine's
173    native byte order.) The receive function should perform adequate
174    checking to ensure that the value is valid. The receive function can be
175    declared as taking one argument of type internal, or as taking three
176    arguments of types internal, oid, integer. The first argument is a
177    pointer to a StringInfo buffer holding the received byte string; the
178    optional arguments are the same as for the text input function. The
179    receive function must return a value of the data type itself. Usually,
180    a receive function should be declared STRICT; if it is not, it will be
181    called with a NULL first parameter when reading a NULL input value. The
182    function must still return NULL in this case, unless it raises an
183    error. (This case is mainly meant to support domain receive functions,
184    which might need to reject NULL inputs.) Similarly, the optional
185    send_function converts from the internal representation to the external
186    binary representation. If this function is not supplied, the type
187    cannot participate in binary output. The send function must be declared
188    as taking one argument of the new data type. The send function must
189    return type bytea. Send functions are not invoked for NULL values.
190
191    You should at this point be wondering how the input and output
192    functions can be declared to have results or arguments of the new type,
193    when they have to be created before the new type can be created. The
194    answer is that the type should first be defined as a shell type, which
195    is a placeholder type that has no properties except a name and an
196    owner. This is done by issuing the command CREATE TYPE name, with no
197    additional parameters. Then the C I/O functions can be defined
198    referencing the shell type. Finally, CREATE TYPE with a full definition
199    replaces the shell entry with a complete, valid type definition, after
200    which the new type can be used normally.
201
202    The optional type_modifier_input_function and
203    type_modifier_output_function are needed if the type supports
204    modifiers, that is optional constraints attached to a type declaration,
205    such as char(5) or numeric(30,2). PostgreSQL allows user-defined types
206    to take one or more simple constants or identifiers as modifiers.
207    However, this information must be capable of being packed into a single
208    non-negative integer value for storage in the system catalogs. The
209    type_modifier_input_function is passed the declared modifier(s) in the
210    form of a cstring array. It must check the values for validity
211    (throwing an error if they are wrong), and if they are correct, return
212    a single non-negative integer value that will be stored as the column
213    “typmod”. Type modifiers will be rejected if the type does not have a
214    type_modifier_input_function. The type_modifier_output_function
215    converts the internal integer typmod value back to the correct form for
216    user display. It must return a cstring value that is the exact string
217    to append to the type name; for example numeric's function might return
218    (30,2). It is allowed to omit the type_modifier_output_function, in
219    which case the default display format is just the stored typmod integer
220    value enclosed in parentheses.
221
222    The optional analyze_function performs type-specific statistics
223    collection for columns of the data type. By default, ANALYZE will
224    attempt to gather statistics using the type's “equals” and “less-than”
225    operators, if there is a default b-tree operator class for the type.
226    For non-scalar types this behavior is likely to be unsuitable, so it
227    can be overridden by specifying a custom analysis function. The
228    analysis function must be declared to take a single argument of type
229    internal, and return a boolean result. The detailed API for analysis
230    functions appears in src/include/commands/vacuum.h.
231
232    The optional subscript_function allows the data type to be subscripted
233    in SQL commands. Specifying this function does not cause the type to be
234    considered a “true” array type; for example, it will not be a candidate
235    for the result type of ARRAY[] constructs. But if subscripting a value
236    of the type is a natural notation for extracting data from it, then a
237    subscript_function can be written to define what that means. The
238    subscript function must be declared to take a single argument of type
239    internal, and return an internal result, which is a pointer to a struct
240    of methods (functions) that implement subscripting. The detailed API
241    for subscript functions appears in src/include/nodes/subscripting.h. It
242    may also be useful to read the array implementation in
243    src/backend/utils/adt/arraysubs.c, or the simpler code in
244    contrib/hstore/hstore_subs.c. Additional information appears in Array
245    Types below.
246
247    While the details of the new type's internal representation are only
248    known to the I/O functions and other functions you create to work with
249    the type, there are several properties of the internal representation
250    that must be declared to PostgreSQL. Foremost of these is
251    internallength. Base data types can be fixed-length, in which case
252    internallength is a positive integer, or variable-length, indicated by
253    setting internallength to VARIABLE. (Internally, this is represented by
254    setting typlen to -1.) The internal representation of all
255    variable-length types must start with a 4-byte integer giving the total
256    length of this value of the type. (Note that the length field is often
257    encoded, as described in Section 66.2; it's unwise to access it
258    directly.)
259
260    The optional flag PASSEDBYVALUE indicates that values of this data type
261    are passed by value, rather than by reference. Types passed by value
262    must be fixed-length, and their internal representation cannot be
263    larger than the size of the Datum type (4 bytes on some machines, 8
264    bytes on others).
265
266    The alignment parameter specifies the storage alignment required for
267    the data type. The allowed values equate to alignment on 1, 2, 4, or 8
268    byte boundaries. Note that variable-length types must have an alignment
269    of at least 4, since they necessarily contain an int4 as their first
270    component.
271
272    The storage parameter allows selection of storage strategies for
273    variable-length data types. (Only plain is allowed for fixed-length
274    types.) plain specifies that data of the type will always be stored
275    in-line and not compressed. extended specifies that the system will
276    first try to compress a long data value, and will move the value out of
277    the main table row if it's still too long. external allows the value to
278    be moved out of the main table, but the system will not try to compress
279    it. main allows compression, but discourages moving the value out of
280    the main table. (Data items with this storage strategy might still be
281    moved out of the main table if there is no other way to make a row fit,
282    but they will be kept in the main table preferentially over extended
283    and external items.)
284
285    All storage values other than plain imply that the functions of the
286    data type can handle values that have been toasted, as described in
287    Section 66.2 and Section 36.13.1. The specific other value given merely
288    determines the default TOAST storage strategy for columns of a
289    toastable data type; users can pick other strategies for individual
290    columns using ALTER TABLE SET STORAGE.
291
292    The like_type parameter provides an alternative method for specifying
293    the basic representation properties of a data type: copy them from some
294    existing type. The values of internallength, passedbyvalue, alignment,
295    and storage are copied from the named type. (It is possible, though
296    usually undesirable, to override some of these values by specifying
297    them along with the LIKE clause.) Specifying representation this way is
298    especially useful when the low-level implementation of the new type
299    “piggybacks” on an existing type in some fashion.
300
301    The category and preferred parameters can be used to help control which
302    implicit cast will be applied in ambiguous situations. Each data type
303    belongs to a category named by a single ASCII character, and each type
304    is either “preferred” or not within its category. The parser will
305    prefer casting to preferred types (but only from other types within the
306    same category) when this rule is helpful in resolving overloaded
307    functions or operators. For more details see Chapter 10. For types that
308    have no implicit casts to or from any other types, it is sufficient to
309    leave these settings at the defaults. However, for a group of related
310    types that have implicit casts, it is often helpful to mark them all as
311    belonging to a category and select one or two of the “most general”
312    types as being preferred within the category. The category parameter is
313    especially useful when adding a user-defined type to an existing
314    built-in category, such as the numeric or string types. However, it is
315    also possible to create new entirely-user-defined type categories.
316    Select any ASCII character other than an upper-case letter to name such
317    a category.
318
319    A default value can be specified, in case a user wants columns of the
320    data type to default to something other than the null value. Specify
321    the default with the DEFAULT key word. (Such a default can be
322    overridden by an explicit DEFAULT clause attached to a particular
323    column.)
324
325    To indicate that a type is a fixed-length array type, specify the type
326    of the array elements using the ELEMENT key word. For example, to
327    define an array of 4-byte integers (int4), specify ELEMENT = int4. For
328    more details, see Array Types below.
329
330    To indicate the delimiter to be used between values in the external
331    representation of arrays of this type, delimiter can be set to a
332    specific character. The default delimiter is the comma (,). Note that
333    the delimiter is associated with the array element type, not the array
334    type itself.
335
336    If the optional Boolean parameter collatable is true, column
337    definitions and expressions of the type may carry collation information
338    through use of the COLLATE clause. It is up to the implementations of
339    the functions operating on the type to actually make use of the
340    collation information; this does not happen automatically merely by
341    marking the type collatable.
342
343 Array Types
344
345    Whenever a user-defined type is created, PostgreSQL automatically
346    creates an associated array type, whose name consists of the element
347    type's name prepended with an underscore, and truncated if necessary to
348    keep it less than NAMEDATALEN bytes long. (If the name so generated
349    collides with an existing type name, the process is repeated until a
350    non-colliding name is found.) This implicitly-created array type is
351    variable length and uses the built-in input and output functions
352    array_in and array_out. Furthermore, this type is what the system uses
353    for constructs such as ARRAY[] over the user-defined type. The array
354    type tracks any changes in its element type's owner or schema, and is
355    dropped if the element type is.
356
357    You might reasonably ask why there is an ELEMENT option, if the system
358    makes the correct array type automatically. The main case where it's
359    useful to use ELEMENT is when you are making a fixed-length type that
360    happens to be internally an array of a number of identical things, and
361    you want to allow these things to be accessed directly by subscripting,
362    in addition to whatever operations you plan to provide for the type as
363    a whole. For example, type point is represented as just two
364    floating-point numbers, which can be accessed using point[0] and
365    point[1]. Note that this facility only works for fixed-length types
366    whose internal form is exactly a sequence of identical fixed-length
367    fields. For historical reasons (i.e., this is clearly wrong but it's
368    far too late to change it), subscripting of fixed-length array types
369    starts from zero, rather than from one as for variable-length arrays.
370
371    Specifying the SUBSCRIPT option allows a data type to be subscripted,
372    even though the system does not otherwise regard it as an array type.
373    The behavior just described for fixed-length arrays is actually
374    implemented by the SUBSCRIPT handler function
375    raw_array_subscript_handler, which is used automatically if you specify
376    ELEMENT for a fixed-length type without also writing SUBSCRIPT.
377
378    When specifying a custom SUBSCRIPT function, it is not necessary to
379    specify ELEMENT unless the SUBSCRIPT handler function needs to consult
380    typelem to find out what to return. Be aware that specifying ELEMENT
381    causes the system to assume that the new type contains, or is somehow
382    physically dependent on, the element type; thus for example changing
383    properties of the element type won't be allowed if there are any
384    columns of the dependent type.
385
386 Parameters
387
388    name
389           The name (optionally schema-qualified) of a type to be created.
390
391    attribute_name
392           The name of an attribute (column) for the composite type.
393
394    data_type
395           The name of an existing data type to become a column of the
396           composite type.
397
398    collation
399           The name of an existing collation to be associated with a column
400           of a composite type, or with a range type.
401
402    label
403           A string literal representing the textual label associated with
404           one value of an enum type.
405
406    subtype
407           The name of the element type that the range type will represent
408           ranges of.
409
410    subtype_operator_class
411           The name of a b-tree operator class for the subtype.
412
413    canonical_function
414           The name of the canonicalization function for the range type.
415
416    subtype_diff_function
417           The name of a difference function for the subtype.
418
419    multirange_type_name
420           The name of the corresponding multirange type.
421
422    input_function
423           The name of a function that converts data from the type's
424           external textual form to its internal form.
425
426    output_function
427           The name of a function that converts data from the type's
428           internal form to its external textual form.
429
430    receive_function
431           The name of a function that converts data from the type's
432           external binary form to its internal form.
433
434    send_function
435           The name of a function that converts data from the type's
436           internal form to its external binary form.
437
438    type_modifier_input_function
439           The name of a function that converts an array of modifier(s) for
440           the type into internal form.
441
442    type_modifier_output_function
443           The name of a function that converts the internal form of the
444           type's modifier(s) to external textual form.
445
446    analyze_function
447           The name of a function that performs statistical analysis for
448           the data type.
449
450    subscript_function
451           The name of a function that defines what subscripting a value of
452           the data type does.
453
454    internallength
455           A numeric constant that specifies the length in bytes of the new
456           type's internal representation. The default assumption is that
457           it is variable-length.
458
459    alignment
460           The storage alignment requirement of the data type. If
461           specified, it must be char, int2, int4, or double; the default
462           is int4.
463
464    storage
465           The storage strategy for the data type. If specified, must be
466           plain, external, extended, or main; the default is plain.
467
468    like_type
469           The name of an existing data type that the new type will have
470           the same representation as. The values of internallength,
471           passedbyvalue, alignment, and storage are copied from that type,
472           unless overridden by explicit specification elsewhere in this
473           CREATE TYPE command.
474
475    category
476           The category code (a single ASCII character) for this type. The
477           default is 'U' for “user-defined type”. Other standard category
478           codes can be found in Table 52.65. You may also choose other
479           ASCII characters in order to create custom categories.
480
481    preferred
482           True if this type is a preferred type within its type category,
483           else false. The default is false. Be very careful about creating
484           a new preferred type within an existing type category, as this
485           could cause surprising changes in behavior.
486
487    default
488           The default value for the data type. If this is omitted, the
489           default is null.
490
491    element
492           The type being created is an array; this specifies the type of
493           the array elements.
494
495    delimiter
496           The delimiter character to be used between values in arrays made
497           of this type.
498
499    collatable
500           True if this type's operations can use collation information.
501           The default is false.
502
503 Notes
504
505    Because there are no restrictions on use of a data type once it's been
506    created, creating a base type or range type is tantamount to granting
507    public execute permission on the functions mentioned in the type
508    definition. This is usually not an issue for the sorts of functions
509    that are useful in a type definition. But you might want to think twice
510    before designing a type in a way that would require “secret”
511    information to be used while converting it to or from external form.
512
513    Before PostgreSQL version 8.3, the name of a generated array type was
514    always exactly the element type's name with one underscore character
515    (_) prepended. (Type names were therefore restricted in length to one
516    fewer character than other names.) While this is still usually the
517    case, the array type name may vary from this in case of maximum-length
518    names or collisions with user type names that begin with underscore.
519    Writing code that depends on this convention is therefore deprecated.
520    Instead, use pg_type.typarray to locate the array type associated with
521    a given type.
522
523    It may be advisable to avoid using type and table names that begin with
524    underscore. While the server will change generated array type names to
525    avoid collisions with user-given names, there is still risk of
526    confusion, particularly with old client software that may assume that
527    type names beginning with underscores always represent arrays.
528
529    Before PostgreSQL version 8.2, the shell-type creation syntax CREATE
530    TYPE name did not exist. The way to create a new base type was to
531    create its input function first. In this approach, PostgreSQL will
532    first see the name of the new data type as the return type of the input
533    function. The shell type is implicitly created in this situation, and
534    then it can be referenced in the definitions of the remaining I/O
535    functions. This approach still works, but is deprecated and might be
536    disallowed in some future release. Also, to avoid accidentally
537    cluttering the catalogs with shell types as a result of simple typos in
538    function definitions, a shell type will only be made this way when the
539    input function is written in C.
540
541    In PostgreSQL version 16 and later, it is desirable for base types'
542    input functions to return “soft” errors using the new
543    errsave()/ereturn() mechanism, rather than throwing ereport()
544    exceptions as in previous versions. See src/backend/utils/fmgr/README
545    for more information.
546
547 Examples
548
549    This example creates a composite type and uses it in a function
550    definition:
551 CREATE TYPE compfoo AS (f1 int, f2 text);
552
553 CREATE FUNCTION getfoo() RETURNS SETOF compfoo AS $$
554     SELECT fooid, fooname FROM foo
555 $$ LANGUAGE SQL;
556
557    This example creates an enumerated type and uses it in a table
558    definition:
559 CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');
560
561 CREATE TABLE bug (
562     id serial,
563     description text,
564     status bug_status
565 );
566
567    This example creates a range type:
568 CREATE TYPE float8_range AS RANGE (subtype = float8, subtype_diff = float8mi);
569
570    This example creates the base data type box and then uses the type in a
571    table definition:
572 CREATE TYPE box;
573
574 CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ;
575 CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ;
576
577 CREATE TYPE box (
578     INTERNALLENGTH = 16,
579     INPUT = my_box_in_function,
580     OUTPUT = my_box_out_function
581 );
582
583 CREATE TABLE myboxes (
584     id integer,
585     description box
586 );
587
588    If the internal structure of box were an array of four float4 elements,
589    we might instead use:
590 CREATE TYPE box (
591     INTERNALLENGTH = 16,
592     INPUT = my_box_in_function,
593     OUTPUT = my_box_out_function,
594     ELEMENT = float4
595 );
596
597    which would allow a box value's component numbers to be accessed by
598    subscripting. Otherwise the type behaves the same as before.
599
600    This example creates a large object type and uses it in a table
601    definition:
602 CREATE TYPE bigobj (
603     INPUT = lo_filein, OUTPUT = lo_fileout,
604     INTERNALLENGTH = VARIABLE
605 );
606 CREATE TABLE big_objs (
607     id integer,
608     obj bigobj
609 );
610
611    More examples, including suitable input and output functions, are in
612    Section 36.13.
613
614 Compatibility
615
616    The first form of the CREATE TYPE command, which creates a composite
617    type, conforms to the SQL standard. The other forms are PostgreSQL
618    extensions. The CREATE TYPE statement in the SQL standard also defines
619    other forms that are not implemented in PostgreSQL.
620
621    The ability to create a composite type with zero attributes is a
622    PostgreSQL-specific deviation from the standard (analogous to the same
623    case in CREATE TABLE).
624
625 See Also
626
627    ALTER TYPE, CREATE DOMAIN, CREATE FUNCTION, DROP TYPE