ruststructserdesurrealdb

SurrealDB - How to store record linkage in Rust struct?


There is an example in SurrealDB documentation about using Rust's structs to store received data:

#[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,
}

I couldn't find an example about storing a Record in a struct. Should I use Thing or create a struct called Record with id field?

For example this is the database schema I use and I want to store the select result of a notification table as a struct:

Schema.surql:

DEFINE TABLE notification SCHEMAFULL;

DEFINE FIELD content ON notification TYPE string;
DEFINE FIELD user_id ON notification TYPE record(user);

Notification Struct:

#[derive(Debug, Serialize)]
struct Notification {
    content: String,
    user_id: TYPE_HERE, <= ???
}

What is the type to store record linkage in Rust?

Thanks!


Solution

  • I just put id: Option<Thing>, its from use surrealdb::sql::Thing;

    #[derive(Debug, Serialize)]
    struct Person<'a> {
      id: Option<Thing>
      title: &'a str,
      name: Name<'a>,
      marketing: bool,
    }
    

    When you save it to db, and you want auto id, you put id None and set table name only, no table id.

    let data = Person {
      id: None, title, name, marketing
    }
    let table_name = "test";
    let result = db.create(table_name).content(data).await?;
    

    OR if you want to set an id to it:

    let data_to_save = Person {
      id: None, title, name, marketing
    }
    let table_name = "test";
    let person_id = "person_id";
    let dbData: Option<Person> = db.update((table_name, 
      person_id)).merge(data_to_save ).await?; 
    

    It will save to db with tb:test, id: person_id.