Skip to main content

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 [ IF NOT EXISTS ] 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,
};

Using IF NOT EXISTS clause Since 1.3.0

The IF NOT EXISTS clause can be used to define a function only if it does not already exist. If the function already exists, the DEFINE FUNCTION statement will return an error.

-- Create a FUNCTION if it does not already exist
DEFINE FUNCTION IF NOT EXISTS fn::example() {};