如何在postgres扩展中定义动态字符串数据类型?

时间:2012-02-07 16:32:04

标签: c database postgresql

我试图在postgreSQL中定义一个带有两个参数的自定义数据类型:long long int(postgres中的int8)和动态字符串(postgres中的varchar或TEXT)。我可以让long long int工作,但是我遇到了实现动态字符串的麻烦。这就是我的c代码中的in和out函数:

在功能中:

 Datum object3d_in(PG_FUNCTION_ARGS) {
    char* str = PG_GETARG_CSTRING(0);
    long long int timeStamp;
    char *temp;
    Object3d *result;

    if (sscanf(str, "(%lli, %s)", &timeStamp, temp) != 2)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                        errmsg("Invalid input syntax for object3d: \"%s\"",
                                str)));

    result = (Object3d *) palloc(sizeof(Object3d));
    result->timeStamp = timeStamp;

    result->object = (char*) palloc(sizeof(char)*(strlen(temp) + 1));
    sscanf(str, "(%lli, %s)", &timeStamp, result->object); //Reload
    PG_RETURN_POINTER(result);
}

输出功能:

Datum object3d_out(PG_FUNCTION_ARGS) {
    Object3d *object3d = (Object3d *) PG_GETARG_POINTER(0);
    char *result;
    result = (char *) palloc(128);
    snprintf(result, 128, "[%lli, %s]", object3d->timeStamp, object3d->object);
    PG_RETURN_CSTRING(result);
}

postgres类型命令:

CREATE TYPE object3d;

CREATE FUNCTION object3d_in(cstring)
RETURNS object3d
AS 'mdobject.dll'
LANGUAGE C IMMUTABLE STRICT;

CREATE FUNCTION object3d_out(object3d)
RETURNS cstring
AS 'mdobject.dll'
LANGUAGE C IMMUTABLE STRICT; 

CREATE TYPE object3d(
    INTERNALLENGTH = 128, 
    input = object3d_in,
    output = object3d_out
);

CREATE TABLE listobject3d (id integer, theobject object3d);
INSERT INTO listobject3d VALUES (random()*100, '(203,12 )'); 
INSERT INTO listobject3d VALUES (random()*100, '(20120202,r )');
INSERT INTO listobject3d VALUES (random()*100, '(20120203,c )');
INSERT INTO listobject3d VALUES (random()*100, '(20120203,triangle )');

输出:

SELECT * FROM listobject3d;

 id |     theobject
----+-------------------
 21 | [203, 12]
 42 | [20120202, /\x01]
 19 | [20120203, /\x01]
 33 | [20120203,     ]
(4 rows)

1 个答案:

答案 0 :(得分:1)

结果数据应采用varlena格式 - 等前四个字节应该是完整的长度。

http://www.iphelp.ru/faq/15/ch06lev1sec1.html