Skip to content
Sign In

Methods

connect

The .connect() method for the SurrealDB Rust SDK connects to a local or remote database endpoint.

Connects to a local or remote database endpoint.

Method Syntax
db.connect(address)

Argument

Description

endpoint

The database endpoint to connect to.

The .connect() method will usually take a String or a type that implements Into<String>. Note that the final .connect() with a Config is possible because of the implementation impl<T> IntoEndpoint for (T, Config) where T: Into<String>.

use std::sync::LazyLock;
use std::time::Duration;
use surrealdb::engine::remote::ws::{Client, Ws, Wss};
use surrealdb::opt::Config;
use surrealdb::Surreal;

static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    // Connect to a local endpoint
    DB.connect::<Ws>("127.0.0.1:8000").await?;
    // Connect to a remote endpoint
    DB.connect::<Wss>("cloud.surrealdb.com").await?;
    // A tuple with a Config struct can also be passed in for fine tuning of the connection
    let config = Config::default().query_timeout(Duration::from_millis(1500));
    DB.connect::<Ws>(("127.0.0.1:8000", config)).await?;
    Ok(())
}

Available since: v3.3.0

Alongside WebSocket and HTTP, the SDK can talk to a server over gRPC. The server exposes it on the same address and port as the other two, so no extra server configuration is needed.

gRPC is the only remote protocol that delivers query results incrementally, which is what makes .stream_items() worthwhile on a remote connection. On WebSocket and HTTP the results are buffered and replayed instead.

The engine is behind the protocol-grpc feature, which is not enabled by default:

Cargo.toml
surrealdb = { version = "3", features = ["protocol-grpc"] }

Use Grpc for a plain connection and Grpcs for a TLS one, in the same way as Ws and Wss.

use surrealdb::Surreal;
use surrealdb::engine::remote::grpc::Grpc;
use surrealdb::opt::auth::Root;
use surrealdb::types::Value;

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = Surreal::new::<Grpc>("127.0.0.1:8000").await?;

    db.signin(Root {
        username: "root".to_string(),
        password: "secret".to_string(),
    })
    .await?;

    db.use_ns("main").use_db("main").await?;

    let mut res = db.query("RETURN 1 + 1").await?;
    println!("{:?}", res.take::<Value>(0)?);
    Ok(())
}

The any engine accepts grpc:// and grpcs:// URLs, so a connection can be chosen at runtime in the same way as ws:// or http://.

let db = surrealdb::engine::any::connect("grpc://127.0.0.1:8000").await?;
Note

A grpc:// URL passed to any::connect() in a build without the protocol-grpc feature fails at connection time rather than at compile time, with Cannot connect to the gRPC remote engine as it is not enabled in this build of SurrealDB. The engine is also unavailable on wasm32 targets, as its underlying transport does not build for them.

Was this page helpful?