Skip to content

Scripting

Scripting functions overview

SurrealDB allows for advanced functions with complicated logic, by allowing embedded functions to be written in JavaScript. These functions support the ES2020 JavaScript specification.

To allow scripting functions to be used, the --allow-scripting flag must be passed in when using the surreal start command to start the database.

Embedded JavaScript functions within SurrealDB support all functionality in the ES2020 specification including async / await functions, and generator functions. Any value from SurrealDB is converted into a JavaScript type automatically, and the return value from the JavaScript function is converted to a SurrealDB value.

CREATE person SET scores = function() {
	return [1,2,3].map(v => v * 10);
};
Output
[
	{
		id: person:zju99ptfepm87ylqf2h2,
		scores: [
			10,
			20,
			30
		]
	}
]

SurrealQL has no bitwise operators and no math::bitand-style functions. The array::boolean_* functions work on the truthiness of elements, not on the bits of an integer. Where bitwise logic is needed, an embedded scripting function can apply the JavaScript operators &, |, ^ and <<, and a DEFINE FUNCTION can wrap the call so that queries use a plain function name.

DEFINE FUNCTION fn::bitand($a: int, $b: int) -> int {
	function($a, $b) { return arguments[0] & arguments[1]; }
};

DEFINE FUNCTION fn::bitor($a: int, $b: int) -> int {
	function($a, $b) { return arguments[0] | arguments[1]; }
};

[fn::bitand(12, 10), fn::bitor(12, 10)];
Output
[8, 14]

The server must be started with --allow-scripting, otherwise the call fails with Scripting functions are not allowed. JavaScript applies bitwise operators to 32-bit signed integers, so bits above the 32nd are dropped: fn::bitor(4294967296, 1) returns 1.

  • Arguments - pass values from the surrounding query into the function

  • Function context - what this is bound to, and what the function inherits

  • Type conversion - how SurrealDB values arrive in JavaScript and come back

  • Built-in functions - the JavaScript utilities and SurrealDB classes available inside a function

  • SurrealQL functions - call native SurrealQL functions from JavaScript

Was this page helpful?