我有一个用户定义的类型 mytype :
CREATE TYPE mytype AS (
timestamps timestamp[],
last integer
);
我想使用C函数访问 timestamps 字段中的值。这是我写的:
#include "postgres.h"
#include "fmgr.h"
#include "executor/executor.h"
#include "datatype/timestamp.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(testfunc);
Datum
testfunc(PG_FUNCTION_ARGS) {
bool isnull;
HeapTupleHeader at = PG_GETARG_HEAPTUPLEHEADER(0);
Datum dt = GetAttributeByName(at, "timestamps", &isnull);
Timestamp ** tts = (Timestamp **) DatumGetPointer(dt);
PG_RETURN_DATUM(**tts);
}
SQL参考:
CREATE OR REPLACE FUNCTION testfunc(mytype) RETURNS timestamp AS 'path/to/library.so', 'testfunc' LANGUAGE C STRICT;
现在,当我尝试测试时,我得到垃圾结果:
postgres=# SELECT testfunc('("{""2017-01-11 00:00:00"", NULL}", 10)');
testfunc
---------------------------
2000-01-01 00:00:00.00001
(1 row)
答案 0 :(得分:1)
查看PostgreSQL源代码,了解如何处理数组参数。
您的代码应该看起来像这样:
HeapTupleHeader at = PG_GETARG_HEAPTUPLEHEADER(0);
Datum dt = GetAttributeByName(at, "timestamps", &isnull);
ArrayType *ts = DatumGetArrayTypeP(dt);
Timestamp *timestamps = (Timestamp *) ARR_DATA_PTR(ts);
这不完整;如果数组具有预期的维数和类似数,则可能需要添加NULL
的检查。