complex.sql and complex.c. Composite examples
are in funcs.sql.
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.
Complex *
complex_in(char *str)
{
double x, y;
Complex *result;
if (sscanf(str, " ( %lf , %lf )", &x, &y) != 2) {
elog(WARN, "complex_in: error in parsing
return NULL;
}
result = (Complex *)palloc(sizeof(Complex));
result->x = x;
result->y = y;
return (result);
}
The output function can simply be:
char *
complex_out(Complex *complex)
{
char *result;
if (complex == NULL)
return(NULL);
result = (char *) palloc(60);
sprintf(result, "(%g,%g)", complex->x, complex->y);
return(result);
}
CREATE FUNCTION complex_in(opaque)
RETURNS complex
AS '/usr/local/postgres95/tutorial/obj/complex.so'
LANGUAGE 'c';
CREATE FUNCTION complex_out(opaque)
RETURNS opaque
AS '/usr/local/postgres95/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.