-1

I am trying to create a custom C-language function for an Apache AGE extension in PostgreSQL, but I'm not sure how to handle a variable number of arguments of different types. Ideally, I would like to call this function using the syntax

SELECT function(arg1, arg2, ..., argN);

Can anyone provide guidance or examples of how to accomplish this? Here's some additional context:

  • The function should be able to handle a variable number of arguments, with different types (e.g. integers, floats, strings, etc.).
  • I am familiar with the basics of C programming, but I have limited experience with PostgreSQL extensions.
  • I have already created a basic function in C that can be called from PostgreSQL, but it only accepts a fixed number of arguments of a specific type.

Any suggestions or pointers in the right direction would be greatly appreciated. Thanks in advance!

Marco Souza
  • 296
  • 7
  • This seems to be a related question: https://stackoverflow.com/q/64466474/21105992 ... to me it suggests to look at the implementation of [json_build_array](https://doxygen.postgresql.org/json_8c.html#a972bbbcee769f54742b6352cbcf19452) for inspiration. – teapot418 Mar 15 '23 at 15:29

1 Answers1

0

I think you can use Variadic function. Variadic functions are functions that can take a variable number of arguments. It takes one fixed argument and then any number of arguments can be passed.

We can consider that is like a printf function

For example, implementing a function mleast takes varadic number of inputs

float mleast(int n, ...)
{
    float least = 0;
 
    // Declaring pointer to the
    // argument list
    va_list ptr;
 
    // Initializing argument to the
    // list pointer
    va_start(ptr, n);
 
    for (int i = 0; i < n; i++) {
 
        // Accessing current variable
        // and pointing to next one
        float ni = va_arg(ptr, float);

        if (i==0) least = ni;
        else if (ni<least) least = ni;
    }
    // Ending argument list traversal
    va_end(ptr);
 
    return least;
}

For calling it from Postgres

SELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);

Reference:

  • You might want to elaborate on how such a function would be declared, retrieve its arguments and how you would **call it from sql**. (which I believe the question is also about) – teapot418 Mar 15 '23 at 16:09
  • (Updated) @teapot418 Thank you for your notice – Mohamed Mokhtar - rrrokhtar Mar 15 '23 at 16:39
  • Your claim that `VARIADIC` in postgresql and a variadic function in C should be used together is ... interesting but does not appear to be supported by evidence as far as I can tell. Have you tested it? – teapot418 Mar 15 '23 at 16:54
  • No, I have not tested it yet, but I am going to take a look after getting my work day done (If you have done and did not work, let me know if possible) – Mohamed Mokhtar - rrrokhtar Mar 15 '23 at 17:22