User scalar/aggregate functions

User scalar/aggregate functions are specified in the configuration object with the Function::tag@library.so option, where tag is the name of the struct qdb_function entry describing the function, and library.so is the name of a DLL containing your code (this can be an absolute path or a relative path within the library search path). This is set up as follows:

static void myfunc(sqlite3_context *context, int narg, 
                   sqlite3_value **value)
{
}

struct qdb_function ftag = { 
    "func", SQLITE_UTF8, 1, NULL, myfunc, NULL, NULL };

The tag value in this case is ftag, the function name as visible to SQL is func, and the function called is myfunc(), which can retrieve the fourth field (here NULL) as its sqlite3_user_data().

Note: The ftag was used to clarify the example. You would probably use the name func here so it was the same as the SQL name.

There can be multiple functions defined (in the same or different DLLs), but each must have a Function:: entry in the configuration object for the database it is associated with, and each must have a struct qdb_function with a unique name describing it.

The qdb_function structure has these members:

struct qdb_function {
  char  *name;
  int   encoding;
  int   narg;
  void  *arg;
  void  (*func)(struct sqlite3_context *, int, struct Mem **);
  void  (*step)(struct sqlite3_context *, int, struct Mem **);
  void  (*final)(struct sqlite3_context *);
};
name
The name used for this function in SQL statements. This is limited to 255 bytes, exclusive of the null-terminator, and it can't contain any special tokens, or start with a digit. Any attempt to create a function with an invalid name will result in an SQLITE_ERROR error.
encoding
The character encoding of strings passed to your function. Can be one of:
  • SQLITE_UTF8
  • SQLITE_UTF16
  • SQLITE_UTF16BE
  • SQLITE_UTF16LE
narg
The number of arguments that the function or aggregate takes. If this argument is -1, then the function or aggregate may take any number of arguments. The maximum number of arguments to a new SQL function is 127. A number larger than 127 for the third argument results in an SQLITE_ERROR error.
arg
An arbitrary pointer to user data that is passed to your function each time it's invoked. The function can gain access to this pointer by using the sqlite_user_data() function.
func, step, final
Pointers to your function or aggregate. A scalar function requires an implementation of the func callback only; NULL pointers should be passed as the step and final arguments. An aggregate function requires an implementation of step and final, and NULL should be passed for func. Specifying an inconsistent set of callback values, such as a func and a final, or an step but no final, results in an SQLITE_ERROR return.