Skip to main content
Version: 1.2.x

DEFINE FUNCTION

DEFINE FUNCTION statement

The DEFINE FUNCTION statement allows you to define custom functions that can be reused throughout a database.

Requirements

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;
};

Optional arguments

If one or more ending arguments have the option<T> type, they can be omitted when you run the invoke the function.

DEFINE FUNCTION fn::last_option($required: number, $optional: option<number>) {
RETURN {
required_present: type::is::number($required),
optional_present: type::is::number($optional),
}
};

RETURN fn::last_option(1, 2);
{
required_present: true,
optional_present: true,
};

RETURN fn::last_option(1);
{
required_present: true,
optional_present: false,
};