User-defined functions allow MariaDB to be extended with a new function that works like a native (built-in) MariaDB function such as ABS() or CONCAT(). There are alternative ways to add a new function: writing a native function (which requires modifying and compiling the server source code), or writing a stored function.
Statements making use of user-defined functions are not safe for replication.
Functions are written in C or C++, and to make use of them, the operating system must support dynamic loading.
Each new SQL function requires corresponding functions written in C/C++. In the list below, at least the main function - x() - and one other, are required. x should be replaced by the name of the function you are creating.
All functions need to be thread-safe, so not global or static variables that change can be allocated. Memory is allocated in x_init()/ and freed in x_deinit().
Required for all UDF's, this is where the results are calculated.
C/C++ type | SQL type |
---|---|
char * | STRING |
long long | INTEGER |
double | REAL |
DECIMAL functions return string values, and so should be written accordingly. It is not possible to create ROW functions.
Initialization function for x(). Can be used for the following:
De-initialization function for x(). Used to de-allocate memory that was allocated in x_init().
Each time the SQL function X() is called:
The following functions are required for aggregate functions, such as AVG() and SUM().
Used to reset the current aggregate, but without inserting the argument as the initial aggregate value for the new group.
Used to add the argument to the current aggregate.
Staring from MariaDB 10.4 it improves the support of window functions (so it is not obligatory to add it) and should remove the argument from the current aggregate.
Each time the aggregate SQL function X() is called:
For an example, see sql/udf_example.cc
in the source tree. For a collection of existing UDFs see https://github.com/mysqludf.
© 2019 MariaDB
Licensed under the Creative Commons Attribution 3.0 Unported License and the GNU Free Documentation License.
https://mariadb.com/kb/en/creating-user-defined-functions/