Giter Club home page Giter Club logo

surrealdb.rs's Introduction

surrealdb.rs

The official SurrealDB library 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, the product roadmap, and documentation.

  Features

  • WebSocket connections
  • HTTP connections
  • 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
  • Static clients, no need for once_cell or lazy_static
  • Clonable connections with auto-reconnect capabilities, no need for a connection pool
  • Range queries
  • Consistent API across all supported protocols, just change the scheme on the connect method and you are good to go
  • Asynchronous, lock-free connections
  • TLS support via either rustls or native-tls
  • FFI bindings for third-party languages

  Installation

To add this crate as a Rust dependency, simply run

cargo add surrealdb-rs --git https://github.com/surrealdb/surrealdb.rs

IMPORTANT: This client supports SurrealDB v1.0.0-beta.8+20221030.c12a1cc or later. So please make sure you have that or a newer version of the server before proceeding. For now, that means a recent nightly version.

  Quick look

This library enables simple and advanced querying of a remote database from server-side or client-side (via Wasm) code. By default, all 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 std::borrow::Cow;
use surrealdb_rs::param::Root;
use surrealdb_rs::protocol::Ws;
use surrealdb_rs::{Result, Surreal};

#[derive(Serialize, Deserialize)]
struct Name {
    first: Cow<'static, str>,
    last: Cow<'static, str>,
}

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

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

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

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

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

    assert!(tobie.id.is_some());

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

    assert_eq!(jaime.id.unwrap(), "person:jaime");

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

    assert!(jaime.marketing);

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

    assert!(!people.is_empty());

    // Perform a custom advanced query
    let groups = client
        .query("
            SELECT marketing,
                   count()
            FROM type::table($table)
            GROUP BY marketing
        ")
        .bind("table", "person")
        .await?;

    dbg!(groups);

    // Delete all people upto but not including Jaime
    client.delete("person").range(.."jaime").await?;

    // Delete all people
    client.delete("person").await?;

    Ok(())
}

surrealdb.rs's People

Contributors

rushmorem avatar tobiemh avatar pathetic avatar aelto avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.