在PostgreSQL C函数中创建int8 []数组 [英] Create int8[] array in PostgreSQL C function

查看:140
本文介绍了在PostgreSQL C函数中创建int8 []数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试着用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 []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆