我正在为PostgreSQL创建一个扩展程序。我根据PostgreSQL文档展示创建了新的Complex数据类型。请遵循以下代码:
#include "postgres.h"
#include "fmgr.h"
#include "libpq/pqformat.h" /* needed for send/recv functions */
PG_MODULE_MAGIC;
typedef struct Complex
{
double x;
double y;
} Complex;
/*****************************************************************************
* Input/Output functions
*****************************************************************************/
PG_FUNCTION_INFO_V1(complex_in);
Datum
complex_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
double x,
y;
Complex *result;
if (sscanf(str, " ( %lf , %lf )", &x, &y) != 2)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for complex: \"%s\"",
str)));
result = (Complex *) palloc(sizeof(Complex));
result->x = x;
result->y = y;
PG_RETURN_POINTER(result);
}
PG_FUNCTION_INFO_V1(complex_out);
Datum
complex_out(PG_FUNCTION_ARGS)
{
Complex *complex = (Complex *) PG_GETARG_POINTER(0);
char *result;
result = psprintf("(%g,%g)", complex->x, complex->y);
PG_RETURN_CSTRING(result);
}
和SQL
CREATE OR REPLACE FUNCTION complex_in(cstring)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION complex_out(complex)
RETURNS cstring
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION complex_recv(internal)
RETURNS complex
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION complex_send(complex)
RETURNS bytea
AS '$libdir/complex'
LANGUAGE C IMMUTABLE STRICT;
CREATE TYPE complex (
internallength = 16,
input = complex_in,
output = complex_out,
receive = complex_recv,
send = complex_send,
alignment = double
);
和Makefile
EXTENSION = complex # the extensions name
DATA = complex--0.0.1.sql # script files to install
MODULES = complex # our c module file to build
# postgres build stuff
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
我使用CREATE TYPE complex创建新类型,但是当我使用新数据类型时出现以下错误
错误:类型“complex”只是一个shell。
代码有什么问题吗?
答案 0 :(得分:2)
阅读CREATE TYPE
的文档。
首先,使用类似
的语句创建 shell类型CREATE TYPE complex;
这只是一个名字,尚未使用。可以把它想象成C中的函数声明。
接下来,使用定义中的shell类型,使用CREATE FUNCTION
创建类型输入和输出函数。
最后,使用类似
的语句完成类型定义CREATE TYPE complex (
internallength = 16,
input = complex_in,
output = complex_out,
receive = complex_recv,
send = complex_send,
alignment = double
);
这可以与C中的函数定义进行比较。现在可以使用类型。
从您的错误消息中,您似乎忘记运行最终的CREATE TYPE
声明。