Closures are small inline functions. They are generally used in two ways:
By binding them with
LETas a parameter for reuse,Passed directly into methods like
.map(),.filter(), or.chain().
Parameters passed into closures are contained within ||, after which the body of the function is written. They are not a replacement for DEFINE FUNCTION when you need a named, reusable routine with permissions.
Basic examples
Basic function definitions
Error handling and type enforcement
Like regular functions, you can also enforce type constraints within your functions to prevent type mismatches.
Closures in functions
Many of SurrealDB's functions require 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:
We can see that the input to the .chain() method is indeed a closure by creating our own that is assigned to a parameter. This closure can be passed into .chain(), returning the same output as above.
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.
Capturing parameters
Another aspect of closures is that they are able to capture parameters in their environment. This is in fact where the name "closure" comes from, as they are anonymous functions that are able to "enclose" such parameters without needing to pass them through the || parallel bars that hold its input arguments.
Closure limitations
Closures work inside a read-only context, and cannot be used to modify database resources.
In many cases, a closure can be substituted by another operation such as a FOR loop or a regular SELECT statement.
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.