SurrealDB Docs Logo

Enter a search query

run()

Runs a SurrealQL function.

Method Syntax
db.run(function)

Arguments

ArgumentDescription
function

Specifies the path of the function.

Example usage

Calling an existing SurrealQL function:

use surrealdb::engine::any::connect; use surrealdb::opt::auth::Root; #[tokio::main] async fn main() -> surrealdb::Result<()> { let db = connect("ws://localhost:8000").await?; db.signin(Root { username: "root", password: "root", }) .await?; let res: f32 = db.run("rand::float").await?; dbg!(res); Ok(()) }

User-defined functions can be called as well.

use surrealdb::engine::any::connect; use surrealdb::opt::auth::Root; #[tokio::main] async fn main() -> surrealdb::Result<()> { let db = connect("ws://localhost:8000").await?; db.signin(Root { username: "root", password: "root", }) .await?; db.use_ns("ns").use_db("db").await?; db.query("DEFINE FUNCTION fn::return_one() -> int { RETURN 1 };") .await?; let res: i32 = db.run("fn::return_one").await?; dbg!(res); Ok(()) }

The return value of the .run() function can be deserialized in the same way as any other database function.

use serde::Deserialize; use surrealdb::engine::any::connect; use surrealdb::opt::auth::Root; #[derive(Debug, Deserialize)] struct Person { first_name: String, middle_name: String, last_name: String, } #[tokio::main] async fn main() -> surrealdb::Result<()> { let db = connect("ws://localhost:8000").await?; db.signin(Root { username: "root", password: "root", }) .await?; db.use_ns("ns").use_db("db").await?; db.query( "DEFINE FUNCTION fn::j_jonah_jameson() -> object { RETURN { first_name: 'J', middle_name: 'Jonah', last_name: 'Jameson' } };", ) .await?; let res: Person = db.run("fn::j_jonah_jameson").await?; dbg!(res); Ok(()) }

On this page

© SurrealDB GitHub Discord Community Cloud Features Releases Install