surrealpatch/lib/examples/query/main.rs
Rushmore Mushambi 3e80aa9914
Implement to_value for sql::Value (#1659)
`sql::Value` is an integral part of `surrealdb`. It's the internal type used by our storage layer. Because of this, we do a lot of converting between this type and native Rust types. Currently this conversion is done through `JSON` using the `serde_json` crate because we do not have our own custom data format implementation. This works because `SQL` is a superset of `JSON`.  This, however, means that this conversion is lossy and can cause surprises in some cases. For example expecting record IDs to be deserialized into a `String` instead of its corresponding Rust native type.

This change implements a custom data format around `sql::Value` and introduces a `to_value` function that facilitates that conversion.
2023-03-30 11:41:44 +01:00

51 lines
1 KiB
Rust

use serde::Deserialize;
use serde::Serialize;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::sql::thing;
use surrealdb::sql::Thing;
use surrealdb::Surreal;
#[derive(Debug, Serialize, Deserialize)]
#[allow(dead_code)]
struct User {
id: Thing,
name: String,
company: String,
}
#[tokio::main]
async fn main() -> surrealdb::Result<()> {
let db = Surreal::new::<Ws>("localhost:8000").await?;
db.signin(Root {
username: "root",
password: "root",
})
.await?;
db.use_ns("namespace").use_db("database").await?;
let sql = "CREATE user SET name = $name, company = $company";
let mut results = db
.query(sql)
.bind(User {
id: thing("user:john")?,
name: "John Doe".to_owned(),
company: "ACME Corporation".to_owned(),
})
.await?;
// print the created user:
let user: Option<User> = results.take(0)?;
println!("{user:?}");
let mut response = db.query("SELECT * FROM user WHERE name.first = 'John'").await?;
// print all users:
let users: Vec<User> = response.take(0)?;
println!("{users:?}");
Ok(())
}