PostgreSQL
PrevChapter 32. Extending SQL: TypesNext

User-Defined Types

Functions Needed for a User-Defined Type

A user-defined type must always have input and output functions. These functions determine how the type appears in strings (for input by the user and output to the user) and how the type is organized in memory. The input function takes a null-delimited character string as its input and returns the internal (in memory) representation of the type. The output function takes the internal representation of the type and returns a null delimited character string. Suppose we want to define a complex type which represents complex numbers. Naturally, we choose to represent a complex in memory as the following C structure:

         typedef struct Complex {
             double      x;
             double      y;
         } Complex;
and a string of the form (x,y) as the external string representation. These functions are usually not hard to write, especially the output function. However, there are a number of points to remember:

To define the complex type, we need to create the two user-defined functions complex_in and complex_out before creating the type:

         CREATE FUNCTION complex_in(opaque)
            RETURNS complex
            AS 'PGROOT/tutorial/obj/complex.so'
            LANGUAGE 'c';

         CREATE FUNCTION complex_out(opaque)
            RETURNS opaque
            AS 'PGROOT/tutorial/obj/complex.so'
            LANGUAGE 'c';

         CREATE TYPE complex (
            internallength = 16,
            input = complex_in,
            output = complex_out
         );

As discussed earlier, Postgres fully supports arrays of base types. Additionally, Postgres supports arrays of user-defined types as well. When you define a type, Postgres automatically provides support for arrays of that type. For historical reasons, the array type has the same name as the user-defined type with the underscore character _ prepended. Composite types do not need any function defined on them, since the system already understands what they look like inside.

Large Objects

The types discussed to this point are all "small" objects -- that is, they are smaller than 8KB in size.

NOTE: 1024 longwords == 8192 bytes. In fact, the type must be considerably smaller than 8192 bytes, since the Postgres tuple and page overhead must also fit into this 8KB limitation. The actual value that fits depends on the machine architecture.

If you require a larger type for something like a document retrieval system or for storing bitmaps, you will need to use the Postgres large object interface.


PrevHomeNext
Extending SQL: TypesUpExtending SQL: Operators