run()
Runs a SurrealQL function.
Method Syntaxdb.run(function)
Argument | Description | ||
---|---|---|---|
function | Specifies the path of the function. |
Calling an existing SurrealQL function:
use surrealdb::engine::any::connect; use surrealdb::opt::auth::Root; 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; 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; struct Person { first_name: String, middle_name: String, last_name: String, } 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(()) }