I'm currently implementing a user-defined data type - a linked list that mimics a set of integers in a file called intList.c, and hopefully used with intList.source to install it onto my Postgres server.
So my questions are the following:
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?
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?
My code for intList.c is as follows: P.S. These functions all work in C, but I haven't installed them in my PostgreSQL server so I don't know how it'll turn out:
// 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);
}
This is only a part of my entire code, I'll be implementing operators and other functions so any tips and pointers would be greatly appreciated.