gpt4 book ai didi

postgresql - C/Postgres - 在非 PG 函数中使用 palloc

转载 作者:行者123 更新时间:2023-11-29 12:23:56 26 4
gpt4 key购买 nike

我目前正在实现一个用户定义的数据类型 - 一个链接列表,它模仿名为 intList.c 的文件中的一组整数,并希望与 intList.source 一起使用以将其安装到我的 Postgres 服务器上。

所以我的问题如下:

  1. 我能否在我的代码中编写 C 函数,例如 (link newNode) 和 (link InsertEnd),其中它们不是要在源文件中声明和创建的 postgres 函数?

  2. 我可以在从我的输入函数调用的函数中使用 palloc 吗? (在这种情况下链接 newNode)?或者我应该在我的输入函数中这样做吗?

我的 intList.c 代码如下:这些函数都可以在 C 中使用,但我还没有在我的 PostgreSQL 服务器中安装它们,所以我不知道结果如何:

 // Defining struct for linked list
typedef struct intSet *link;

typedef struct intList {
int num;
link next;
} intList;

// Create a new node
link newNode(int item) {
link n = (link) palloc(sizeof(*n));
n->num = item;
n->next = NULL;
return n;
}

link insertEnd(link list, link n){
link curr;
// Empty list
if(list == NULL){
list = n;
n->next = NULL;
// If list not empty, iterate to end of list, then append
} else {
for(curr = list; curr->next != NULL; curr = curr->next) {
}
curr->next = n;
n->next = NULL;
}
return list;
}

PG_FUNCTION_INFO_V1(intList_in);

Datum
intList_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
char *token;

// Create an empty linked list
link newList;
newList = NULL;

// Get individual ints from a set e.g. {1, 2, 3, 4}
token = strtok(str, ",{} ");

// For each int, create a new node then
// append to list
while (token != NULL) {
link a = NULL;
a = newNode(atoi(token));
newList = insertEnd(newList, a);
token = strtok(NULL, ",{} ");
}

PG_RETURN_POINTER(newList);
}

Datum
intList_out(PG_FUNCTION_ARGS)
{
// Start our string
char* out = "{";
char* num;
// Retrieve our list from arg(0)
link List = PG_GETARG_POINTER(0);
link curr;
// Traverse list till last node, add commas after each node
for (curr = List; curr->next != NULL; curr = curr->next) {
num = itoa(curr->num);
strcat(num, ", ");
strcat(out, num);
}
// At last node, add closing bracket to close list
num = itoa(curr->num);
strcat(num, "}");
strcat(out, num);

// Psprintf to result then return it
char *result;
result = psprintf("%s", out);
PG_RETURN_CSTRING(result);

}

这只是我整个代码的一部分,我将实现运算符和其他函数,因此非常感谢任何提示和指示。

最佳答案

Can I write C functions such as (link newNode) and (link InsertEnd) in my code wherein they're not postgres functions to be declared & created in the source file?

我假设你的意思是你可以在没有 palloc 的情况下编写它们吗? .你当然可以。虽然不建议这样做。 PostgreSQL 包装 malloc出于性能原因和完整性原因(确保在 txn 结束时释放内存)。如果没有palloc,你将不得不处理这个问题,我不确定您会遇到什么样的挑战。

Can I use palloc in a function called from my input function? (in this case link newNode)? Or should I do it in my input function?

当然,如果您在服务器上运行那是您应该做的。就#include <postres.h>

关于postgresql - C/Postgres - 在非 PG 函数中使用 palloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52077895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com