SurrealDB Docs Logo

Enter a search query

Anonymous Functions

Available since: v2.0.0

SurrealQL Syntax
$@parameter = |@parameters| @expression;

One of the powerful features now available in SurrealDB is the ability to define anonymous functions. These functions can be used to encapsulate reusable logic and can be called from within your queries. Below are some examples demonstrating their capabilities:

Basic Function Definitions

-- Define an anonymous function that doubles a number
$double = |$n: number| $n * 2;
RETURN $double(2);  -- Returns 4

-- Define a function that concatenates two strings
$concat = |$a: string, $b: string| $a + $b;
RETURN $concat("Hello, ", "World!");  -- Returns "Hello, World!"
-- Define a function that greets a person
$greet = |$name: string| -> string { "Hello, " + $name + "!" };
RETURN $greet("Alice");   -- Returns "Hello, Alice!"

Error Handling and Type Enforcement

You can also enforce type constraints within your functions to prevent type mismatches:

-- Define a function with a return type
$to_upper = |$text: string| -> string { string::uppercase($text) };
RETURN $to_upper("hello");  -- Returns "HELLO"
RETURN $to_upper(123);      -- Error: type mismatch

-- Define a function that accepts only numbers
$square = |$num: number| $num * $num;
RETURN $square(4);    -- Returns 16
RETURN $square("4");  -- Error: type mismatch

Closures in functions

Many of SurrealDB’s functions allow a closure to be passed in, making it easy to use complex logic on a value or the elements of an array.

The chain function which performs an operation on a value before passing it on:

"Two"
    .replace("Two", "2")
    .chain(|$num| <number>$num * 1000);
Response
2000

The following example shows a chain of array functions used to remove useless data, followed by a check to see if all items in the array match a certain condition, and then a cast into another type. The array::filter call in the middle ensures that the string::len function that follows is being called on string values.

[NONE, NONE, "good data", "Also good", "important", NULL]
    .filter(|$v| $v.is_string())
    .all(|$s| $s.len() > 5)
    .chain(|$v| <string>$v);
Response
'true'

Conclusion

These anonymous functions provide a flexible way to define small, reusable pieces of logic that can be used throughout your queries. By leveraging them, you can write more modular and maintainable SurrealQL code.

© SurrealDB GitHub Discord Community Cloud Features Releases Install