surrealpatch/sdk
2024-08-30 12:39:55 +00:00
..
benches Rename lib to sdk (#4561) 2024-08-22 10:26:03 +00:00
examples Rename lib to sdk (#4561) 2024-08-22 10:26:03 +00:00
fuzz Improve array function implementations, and improve value::diff() and value::patch() functions (#4612) 2024-08-27 16:34:40 +01:00
src improve transparent api (#4651) 2024-08-30 12:39:55 +00:00
tests Show ENFORCED keyword in INFO statement (#4635) 2024-08-29 14:12:23 +01:00
build.rs Rename lib to sdk (#4561) 2024-08-22 10:26:03 +00:00
CARGO.md Rename lib to sdk (#4561) 2024-08-22 10:26:03 +00:00
Cargo.toml Bump MSRV to 1.80 (#4619) 2024-08-27 14:36:47 +00:00
README.md Rename lib to sdk (#4561) 2024-08-22 10:26:03 +00:00


 

The official SurrealDB SDK for Rust.


       

     

surrealdb

The official SurrealDB SDK for Rust.

  What is SurrealDB?

SurrealDB is an end-to-end cloud native database for web, mobile, serverless, jamstack, backend, and traditional applications. SurrealDB reduces the development time of modern applications by simplifying your database and API stack, removing the need for most server-side components, allowing you to build secure, performant apps quicker and cheaper. SurrealDB acts as both a database and a modern, realtime, collaborative API backend layer. SurrealDB can run as a single server or in a highly-available, highly-scalable distributed mode - with support for SQL querying from client devices, GraphQL, ACID transactions, WebSocket connections, structured and unstructured data, graph querying, full-text indexing, geospatial querying, and row-by-row permissions-based access.

View the features, the latest releases, and documentation.

  Features

  • Can be used as an embedded database (Surreal<Db>)
  • Connects to remote servers (Surreal<ws::Client> or Surreal<http::Client>)
  • Allows picking any protocol or storage engine at run-time (Surreal<Any>)
  • Compiles to WebAssembly
  • Supports typed SQL statements
  • Invalid SQL queries are never sent to the server, the client uses the same parser the server uses
  • Clonable connections with auto-reconnect capabilities, no need for a connection pool
  • Range queries
  • Consistent API across all supported protocols and storage engines
  • Asynchronous, lock-free connections
  • TLS support via either rustls or native-tls

  Documentation

View the SDK documentation here.

  How to install

To add this crate as a Rust dependency, simply run

cargo add surrealdb

  Quick look

This library enables simple and advanced querying of an embedded or remote database from server-side or client-side (via Wasm) code. By default, all remote connections to SurrealDB are made over WebSockets, and automatically reconnect when the connection is terminated. Connections are automatically closed when they get dropped.

use serde::{Deserialize, Serialize};
use serde_json::json;
use surrealdb::sql;
use surrealdb::sql::Thing;
use surrealdb::Surreal;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::Error;

#[derive(Serialize, Deserialize)]
struct Name {
    first: String,
    last: String,
}

#[derive(Serialize, Deserialize)]
struct Person {
    #[serde(skip_serializing)]
    id: Option<Thing>,
    title: String,
    name: Name,
    marketing: bool,
}

// Install at https://surrealdb.com/install 
// and use `surreal start --user root --pass root`
// to start a working database to take the following queries
// 
// See the results via `surreal sql --ns namespace --db database --pretty` 
// or https://surrealist.app/
// followed by the query `SELECT * FROM person;`

#[tokio::main]
async fn main() -> Result<(), Error> {
    let db = Surreal::new::<Ws>("localhost:8000").await?;

    // Signin as a namespace, database, or root user
    db.signin(Root {
        username: "root",
        password: "root",
    })
    .await?;

    // Select a specific namespace and database
    db.use_ns("namespace").use_db("database").await?;

    // Create a new person with a random ID
    let tobie: Vec<Person> = db
        .create("person")
        .content(Person {
            id: None,
            title: "Founder & CEO".into(),
            name: Name {
                first: "Tobie".into(),
                last: "Morgan Hitchcock".into(),
            },
            marketing: true,
        })
        .await?;

    // Create a new person with a specific ID
    let mut jaime: Option<Person> = db
        .create(("person", "jaime"))
        .content(Person {
            id: None,
            title: "Founder & COO".into(),
            name: Name {
                first: "Jaime".into(),
                last: "Morgan Hitchcock".into(),
            },
            marketing: false,
        })
        .await?;

    // Update a person record with a specific ID
    jaime = db
        .update(("person", "jaime"))
        .merge(json!({ "marketing": true }))
        .await?;

    // Select all people records
    let people: Vec<Person> = db.select("person").await?;

    // Perform a custom advanced query
    let query = r#"
        SELECT marketing, count()
        FROM type::table($table)
        GROUP BY marketing
    "#;

    let groups = db.query(sql)
        .bind(("table", "person"))
        .await?;

    // Delete all people up to but not including Jaime
    let people: Vec<Person> = db.delete("person").range(.."jaime").await?;

    // Delete all people
    let people: Vec<Person> = db.delete("person").await?;

    Ok(())
}