Skip to content

Computed data

Closures

Closures are small inline functions. They are generally used in two ways:

  • By binding them with LET as 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.

The examples on this page follow an online bookshop: pricing a book, checking a basket, and flagging titles that are low on stock. The closures reference lists the syntax on its own.

A closure bound to a parameter is called like a function. The first one adds 20% VAT to a price, and the second builds the label shown under a book cover.

LET $with_vat = |$price: number| $price * 1.2;
$with_vat(10);
//- 12f

LET $label = |$title: string, $author: string| $title + " by " + $author;
$label("Dune", "Frank Herbert");
//- 'Dune by Frank Herbert'

Like regular functions, closures can declare the type of each argument and of the value they return. A call with an argument of the wrong type fails instead of producing a wrong price or a broken label.

-- A label that must be built from two strings and must return one
LET $label = |$title: string, $author: string| -> string { $title + " by " + $author };
$label("Emma", "Jane Austen");
//- 'Emma by Jane Austen'
$label("Emma", 1815);
//- "Incorrect arguments for function ANONYMOUS(). Expected a value of type 'string' for argument $author"

-- A price passed as a string is refused
LET $with_vat = |$price: number| $price * 1.2;
$with_vat("10");
//- "Incorrect arguments for function ANONYMOUS(). Expected a value of type 'number' for argument $price"

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 performs an operation on a value before passing it on. Here it turns a price typed into a form, such as £12.50, into a whole number of pence:

"£12.50"
    .replace("£", "")
    .chain(|$price| <int>(<decimal>$price * 100));
Output
1250

The input to the .chain() method is a closure, so a closure that is assigned to a parameter can be passed in instead. This returns the same output as above, and the bookshop can use $to_pence on every price it reads.

LET $to_pence = |$price| <int>(<decimal>$price * 100);

"£12.50"
    .replace("£", "")
    .chain($to_pence);
Output
1250

Several of these methods can follow each other. A basket sent by a browser can hold empty entries, so the next example removes everything that is not an object with array::filter, which makes sure that the check that follows reads qty from a basket line. array::all then checks that every line orders at least one copy, and .chain() turns the result into a message.

[{ title: 'Dune', qty: 2 }, NONE, { title: 'Emma', qty: 1 }, NULL]
    .filter(|$line| $line.is_object())
    .all(|$line| $line.qty > 0)
    .chain(|$ok| IF $ok { 'Basket is valid' } ELSE { 'Basket has an empty line' });
Output
'Basket is valid'

To fail the query when the basket does not meet your assumptions, end the chain with .expect() instead. Here the second line orders no copies:

[{ title: 'Dune', qty: 2 }, NONE, { title: 'Emma', qty: 0 }, NULL]
    .filter(|$line| $line.is_object())
    .all(|$line| $line.qty > 0)
    .expect(|$ok| $ok, "Every basket line needs a quantity above 0");
Error output
"An error occurred: value::expect assertion failed with message: 'Every basket line needs a quantity above 0'"

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.

The closure below reads $in_stock without taking it as an argument, and keeps only the requested titles that the shop has.

LET $in_stock = ['Dune', 'Emma'];

['Dune', 'Ulysses', 'Emma'].filter(|$title| $title IN $in_stock);
Output
['Dune', 'Emma']

Closures capture parameters from SurrealDB 3.0. Before 3.0, a closure could not see $in_stock, so the query above returned []. See Capturing parameters.

A closure that writes makes the expression holding it a write, so it can modify database resources like any other statement. This applies wherever the closure is invoked, including closure-taking functions such as map, filter and fold, and it follows a write reached through a function the closure calls.

The bookshop records a stock_alert for each title that is running out. The function fn::flag_low_stock creates the record, and .map() calls it once for each title.

DEFINE TABLE stock_alert SCHEMAFULL;
DEFINE FIELD title ON stock_alert TYPE string;

DEFINE FUNCTION fn::flag_low_stock($title: string) -> object {
    CREATE stock_alert CONTENT { title: $title };
    { flagged: true, title: $title };
};

LET $low_stock = ['Dune', 'Emma'];
$low_stock.map(|$title| fn::flag_low_stock($title));
Output
[
	{ flagged: true, title: 'Dune' },
	{ flagged: true, title: 'Emma' }
]

A closure whose body only reads still resolves as a read, so map, filter and fold over a pure closure keep their read-only path.

A FOR loop or a SELECT over a list remains a good choice where it reads more clearly:

-- Setup from the example above
DEFINE TABLE stock_alert SCHEMAFULL;
DEFINE FIELD title ON stock_alert TYPE string;
DEFINE FUNCTION fn::flag_low_stock($title: string) -> object {
    CREATE stock_alert CONTENT { title: $title };
    { flagged: true, title: $title };
};

-- Function called once for each title
SELECT VALUE fn::flag_low_stock($this) FROM ['Dune', 'Emma'];
Output
[
	{ flagged: true, title: 'Dune' },
	{ flagged: true, title: 'Emma' }
]

Before SurrealDB 3.3, a closure ran in a read-only context, even when the write sat inside a function it called, so the .map() call above failed with Couldn't write to a read only transaction. The SELECT form works in every version.

These anonymous functions provide a flexible way to define small, reusable pieces of logic that can be used throughout your queries. Using them keeps SurrealQL code modular and easier to maintain.

Was this page helpful?

Last updated