Stored function calls
How to call a function made with CREATE FUNCTION in a statement, how Raft DB evaluates the call, and the limits.
A stored function is made with CREATE FUNCTION (see CREATE PROCEDURE and CREATE FUNCTION) and called by name inside an expression, like a built-in function.
Syntax#
function_name([argument [, argument] ...])CREATE FUNCTION f_add(a INT, b INT) RETURNS INT DETERMINISTIC
BEGIN
RETURN a + b;
ENDDescription#
A call is allowed wherever an expression is: in the select list, in WHERE, in the values of INSERT, in SET @var = ..., in another function.
How Raft DB runs a call: it finds the calls in the text of the statement, runs each function first (its body is parsed and run by the routine engine, with the arguments as local variables), and replaces the call by its value; then the statement is run as if the values had been written. A call that is a whole select item keeps its text as the column name (f_add(2, 3)), as the servers do.
Remarks#
- Arguments must not use columns.
SELECT f_add(2, 3),f_add(@x, 1),INSERT ... VALUES (..., f_add(1, 1))andWHERE id = f_inc(0)work;SELECT f_add(n, 1) FROM t(a call whose argument uses a column of the row) is refused as not supported yet, because the call is run once for the statement, not once per row. Likewise a function called with a column of the row in anUPDATE. - Nesting. A function can call another function and itself (
RETURN f_inc(f_inc(x))). Recursion is refused unless@@max_sp_recursion_depthallows it. A call is stopped after 50 million statements and loop turns in its body. - The default database while a function runs is the function's own.
- Characteristics (
DETERMINISTIC,NO SQL,READS SQL DATA,MODIFIES SQL DATA,COMMENT,LANGUAGE SQL,SQL SECURITY) are read and kept; they are shown bySHOW CREATE FUNCTIONandinformation_schema.ROUTINES.SQL SECURITY INVOKERand the privilegesEXECUTEandCREATE ROUTINEare not enforced yet. - Not supported yet:
ALTER FUNCTION, loadable functions (CREATE FUNCTION ... SONAME), aggregate stored functions, Oracle-style packages and%TYPE. - Unknown function. A name that is neither built in nor stored is error 1305 (
FUNCTION db.name is unknown). - Both dialects run the same stored functions (identical to MySQL 9.7 and MariaDB 11.4 except the account host in
DEFINERand the times).
Examples#
SELECT f_add(2, 3), f_fact(5), f_greet('World');
SET @y = f_add(10, 20);
INSERT INTO t (name, n) VALUES ('e', f_add(1, 1));
SELECT f_inc(1), f_nested(10);
SELECT msg FROM log WHERE id = f_inc(0);
DROP FUNCTION f_add;
SELECT f_add(1, 2); -- error 1305: FUNCTION ... is unknown