我正尝试着用C for PG处理数组.有读取现有数组的示例,但找不到如何创建和设置新数组的例子.
I'm trying to get a feel for processing arrays in C for PG. There are examples of reading existing arrays, but I can't find one on how to create and set a new one.
这是我到目前为止所获得的.我认为我的意图很明确:
This is what I've got so far. I think my intent is clear:
PG_FUNCTION_INFO_V1(makearray); PGMODULEEXPORT Datum makearray(PG_FUNCTION_ARGS) { long a = PG_GETARG_INT32(0); ArrayType* result = new_intArrayType(a); for (long i = 0; i < a; i++) { result[i] = DatumSetInt32(i); } PG_RETURN_ARRAYTYPE_P(result); }如何为每个元素设置值?另外,我实际上想要一个int8 []数组.
How do I set the value for each element? Also, I actually want an int8[] array.
注意
我不想传递参数.数组将完全在内部创建.如何设置元素而不获取它们?我的确切情况是拥有一个带有值的C long long数组,然后将其复制到PG数组.
I don't want to pass the arguments in. The array will be created entirely internally. How do I set the elements without getting them? My exact case is to have a C long long array that has the values and then copy these to the PG array.
推荐答案您应该使用函数 construct_array 或 construct_md_array
#include "catalog/pg_type.h" PG_FUNCTION_INFO_V1(array_four); Datum array_four(PG_FUNCTION_ARGS) { Datum elements[4]; ArrayType *array; elements[0] = PG_GETARG_DATUM(0); elements[1] = PG_GETARG_DATUM(1); elements[2] = PG_GETARG_DATUM(2); elements[3] = PG_GETARG_DATUM(3); array = construct_array(elements, 4, INT8OID, 8, true, 'd'); PG_RETURN_POINTER(array); }第二种变体:
Datum array_four(PG_FUNCTION_ARGS) { Datum elements[4]; ArrayType *array; int i; for (i = 0; i < 4; i++) elements[i] = Int64GetDatum(i); array = construct_array(elements, 4, INT8OID, 8, true, 'd'); PG_RETURN_POINTER(array); }注册:
CREATE FUNCTION array_four(int, int, int, int) RETURNS int[] AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT;测试:
postgres=# select array_four(10,20,30,40); ┌───────────────┐ │ array_four │ ╞═══════════════╡ │ {10,20,30,40} │ └───────────────┘ (1 row)更多推荐
在PostgreSQL C函数中创建int8 []数组
发布评论