Created
March 7, 2024 10:21
-
-
Save RGGH/9da96fb3e7558931e2153d5b647ebcba to your computer and use it in GitHub Desktop.
rust_example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::{Deserialize, Serialize}; | |
use surrealdb::engine::remote::ws::Ws; | |
use surrealdb::opt::auth::Root; | |
use surrealdb::sql::Thing; | |
use surrealdb::Surreal; | |
#[derive(Debug, Serialize)] | |
struct Name<'a> { | |
first: &'a str, | |
last: &'a str, | |
} | |
#[derive(Debug, Serialize)] | |
struct Person<'a> { | |
title: &'a str, | |
name: Name<'a>, | |
marketing: bool, | |
} | |
#[derive(Debug, Serialize)] | |
struct Responsibility { | |
marketing: bool, | |
} | |
#[derive(Debug, Deserialize)] | |
struct Record { | |
#[allow(dead_code)] | |
id: Thing, | |
} | |
#[tokio::main] | |
async fn main() -> surrealdb::Result<()> { | |
// Connect to the server | |
let db = Surreal::new::<Ws>("127.0.0.1:8000").await?; | |
// Signin as a namespace, database, or root user | |
db.signin(Root { | |
username: "root", | |
password: "root", | |
}) | |
.await?; | |
// Select a specific namespace / database | |
db.use_ns("test").use_db("test").await?; | |
// Create a new person with a random id | |
let created: Vec<Record> = db | |
.create("person") | |
.content(Person { | |
title: "Founder & CEO", | |
name: Name { | |
first: "Tobie", | |
last: "Morgan Hitchcock", | |
}, | |
marketing: true, | |
}) | |
.await?; | |
dbg!(created); | |
// Update a person record with a specific id | |
let updated: Option<Record> = db | |
.update(("person", "jaime")) | |
.merge(Responsibility { marketing: true }) | |
.await?; | |
dbg!(updated); | |
// Select all people records | |
let people: Vec<Record> = db.select("person").await?; | |
dbg!(people); | |
// Perform a custom advanced query | |
let groups = db | |
.query("SELECT marketing, count() FROM type::table($table) GROUP BY marketing") | |
.bind(("table", "person")) | |
.await?; | |
dbg!(groups); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment