Connects to a local or remote database endpoint.
Surreal::new::<T>(address)Arguments
Argument | Description |
|---|---|
endpoint | The database endpoint to connect to. |
Example usage
Basic example
use surrealdb::engine::remote::ws::Ws;
use surrealdb::Surreal;
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;
Ok(())
}Configuring the database
The new() function takes an argument of impl IntoEndpoint, which is implemented not only for strings and string-like structs like PathBuf and SocketAddr, but also a tuple of one of these types for the address along with a second Config struct for the configuration.
use surrealdb::{Error, engine::any::connect, opt::{Config, capabilities::Capabilities}};
#[tokio::main]
async fn main() -> Result<(), Error> {
let mut capabilities = Capabilities::all();
capabilities.deny_function("math::abs").unwrap();
let config = Config::default()
.capabilities(capabilities);
let db = connect(("mem://", config)).await?;
db.use_ns("main").use_db("main").await?;
// Result: "Function 'math::abs' is not allowed to be executed"
println!("{:?}", db.query("math::abs(-10)").await?);
Ok(())
}Config options
Config is a builder with methods that can be chained. Config::new() and Config::default() are equivalent starting points.
Method | Description |
|---|---|
.user(root) | Sets the root user the local engines start with. Takes an opt::auth::Root. |
.capabilities(caps) | Sets which functions, network targets, scripting and live queries are permitted. See Capabilities . |
.query_timeout(duration) | Maximum time a single query may run for. |
.transaction_timeout(duration) | Maximum time a transaction may stay open for. |
.ast_payload() | Sends queries as a parsed AST rather than as text. .set_ast_payload(bool)sets the same option from a variable. |
.websocket(config) | Sets the WebSocket buffer sizes. Returns a Result, as the maximum write buffer must be larger than the write buffer. |
.grpc(config) | Sets the gRPC message size. Returns a Result, as a size too small for the protocol's own framing is refused here rather than at connect time. See message size . |
.rustls(config), .native_tls(config) | Configures TLS. Each requires the matching feature flag. Neither is covered by the SDK's stability guarantee, as the underlying crate is not yet stable. |
.temporary_directory(path) | Where the local engines spill temporary data. Requires a storage backend feature flag. |
.changefeed_gc_interval(duration) | How often expired change feed entries are collected. |
.node_membership_refresh_interval(duration), .node_membership_check_interval(duration), .node_membership_cleanup_interval(duration) | Intervals for the node maintenance tasks the local engines run. A zero duration is treated as unset. |
.datastore_option(key, value) | Sets a datastore setting for the local engines, named as the server's SURREAL_environment variable without that prefix. See Setting storage engine options . |
An example of the Config builder used to set a number of attributes in a single chain:
use std::time::Duration;
use surrealdb::engine::any::connect;
use surrealdb::opt::Config;
use surrealdb::opt::auth::Root;
use surrealdb::opt::capabilities::Capabilities;
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
let config = Config::new()
.user(Root {
username: "root".to_string(),
password: "secret".to_string(),
})
.query_timeout(Duration::from_secs(5))
.transaction_timeout(Duration::from_secs(10))
.capabilities(
Capabilities::all()
.with_function_denied("http::*")
.unwrap(),
);
let db = connect(("mem://", config)).await?;
db.signin(Root {
username: "root".to_string(),
password: "secret".to_string(),
})
.await?;
db.use_ns("main").use_db("main").await?;
println!("{:?}", db.query("RETURN http::get('https://example.com')").await?);
Ok(())
}The denied function shows up as an error on the statement rather than on the call as a whole:
Err(Error { code: -32602, message: "Function 'http::get' is not allowed to be executed", details: NotAllowed(Some(Function { name: "http::get" })), cause: None })Note that the Capabilities methods that take a function or network target parse their argument, so they return a Result. The pairs come in two shapes: allow_function / deny_function take &mut self, while with_function_allowed / with_function_denied consume and return the value, which is what makes them chainable.
Using a backend with versioning
To make a new connection that includes SurrealKV versioning, add the "kv-surrealkv" feature flag to the surrealdb dependency in Cargo.toml, add the path to the folder containing the database inside new(), and call the .versioned() method. The memory backend does not support versioning from 3.3.0, and Surreal::new::<Mem>(()).versioned() fails when the connection is opened.
use surrealdb::{Surreal, engine::local::SurrealKv};
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
// SurrealKV with versioning
let db = Surreal::new::<SurrealKv>("path/to/database-folder")
.versioned()
.await?;
Ok(())
}Durability of the local engines
.sync() sets when the local engines flush committed data to disk, and .aol() and .snapshot() set how the memory engine persists itself when it is given a path, such as Surreal::new::<Mem>("/tmp/data"). They take the SyncMode, AolMode and SnapshotMode types from surrealdb::opt, which exist with the kv-mem or kv-surrealkv feature. Available since: v4.0.0
use std::time::Duration;
use surrealdb::Surreal;
use surrealdb::engine::local::{Mem, SurrealKv};
use surrealdb::opt::{AolMode, SnapshotMode, SyncMode};
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
// Flush in the background every 200 ms instead of on every commit
let db = Surreal::new::<SurrealKv>("path/to/database-folder")
.sync(SyncMode::Interval(Duration::from_millis(200)))
.await?;
// A memory engine that keeps an append-only log and a snapshot every minute
let mem = Surreal::new::<Mem>("/tmp/data")
.aol(AolMode::Sync)
.snapshot(SnapshotMode::Interval(Duration::from_secs(60)))
.await?;
Ok(())
}SyncMode::Every is the default for SurrealKV on native targets, and a one-second SyncMode::Interval in the browser. The memory engine defaults to SyncMode::Never, and to no append-only log and no snapshots. .aol() and .snapshot() fail on any engine other than Mem.
Setting storage engine options
An embedded engine reads no environment variables, so the SURREAL_ variables a server uses to tune its storage have no effect on it. A local engine takes the same settings in two other ways, which both cap SurrealKV's block cache at 256 MiB and each memtable at 64 MiB in this example:
use surrealdb::{Surreal, engine::local::SurrealKv, opt::Config};
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
// As parameters on the path, named as on `surreal start`
let db = Surreal::new::<SurrealKv>(
"path/to/database-folder?block_cache_capacity=268435456&max_memtable_size=67108864",
)
.await?;
// With Config, named as the environment variable without `SURREAL_`
let config = Config::new()
.datastore_option("surrealkv_block_cache_capacity", 256 * 1024 * 1024)
.datastore_option("surrealkv_max_memtable_size", 64 * 1024 * 1024);
let db = Surreal::new::<SurrealKv>(("path/to/other-folder", config)).await?;
Ok(())
}datastore_option accepts any value that implements Display. Keys are not case-sensitive, and a later call for the same key replaces an earlier one. It also reaches the datastore's runtime settings, such as memory_limit for SURREAL_MEMORY_LIMIT. Where the path and datastore_option set the same storage setting, the path takes precedence. The bucket folder allowlist has its own method, .bucket_folder_allowlist(), and connecting with bucket_folder_allowlist set through datastore_option fails. Available since: v4.0.0
The SurrealKV environment variables reference lists the settings SurrealKV reads.