DEFINE FUNCTION
DEFINE FUNCTION
statement
The DEFINE FUNCTION
statement allows you to define custom functions that can be reused throughout a database.
Requirements
- You must be authenticated as a root or namespace user before you can use the
DEFINE FUNCTION
statement. - You must select your namespace and database before you can use the
DEFINE FUNCTION
statement.
Statement syntax
SurrealQL Syntax
DEFINE FUNCTION fn::@name(
[ @argument: @type ... ]
) {
[ @query ... ]
[ RETURN @returned ]
}
Example usage
Below shows how you can define a custom function using the DEFINE FUNCTION
statement, and how to call it.
-- It is necessary to prefix the name of your function with "fn::"
-- This indicates that it's a custom function
DEFINE FUNCTION fn::greet($name: string) {
RETURN "Hello, " + $name + "!";
}
-- Returns: "Hello, Tobie!"
RETURN fn::greet("Tobie");
To showcase a slightly more complex custom function, this will check if a relation between two nodes exists:
DEFINE FUNCTION fn::relation_exists(
$in: record,
$tb: string,
$out: record
) {
LET $results = SELECT VALUE id FROM type::table($tb) WHERE in = $in AND out = $out;
RETURN array::len($results) > 0;
};