Examples

User types

View source
agdb example: using your own structs and enums in queries via derive macros

What it shows

The example shows the derive macros that let you use your own Rust types directly in queries:

  • DbValue + DbSerialize store an enum or a struct as a single value.
  • DbTypeMarker allows a type to be used in a Vec of values.
  • DbType maps a struct to the key-value pairs of a database element, with the rename, skip and flatten field attributes and optional fields.
  • DbElement additionally stores the type of the struct so that two types with the same fields can be told apart.

Run it

cargo run -p agdb --example user_types

The derive macros are part of the default derive feature of the agdb crate.

Defining the types

#[derive(Debug, Clone, DbSerialize, DbValue)]
enum UserStatus {
    Active,
    Inactive,
    Banned,
}

// The empty trait `DbTypeMarker` (deriveable via
// `agdb::DbTypeMarker`) is used to allow the user
// types (structs & enums) to be used in vectorized
// variants of the user types.
#[derive(Debug, Clone, DbTypeMarker, DbSerialize, DbValue)]
struct Property {
    name: String,
    value: String,
}

#[derive(Debug, DbType)]
struct SubProperty {
    id: i32,
}

#[derive(Debug, DbType)]
struct User {
    username: String,
    password: String,
    #[agdb(rename = "name")]
    display_name: Option<String>,
    status: UserStatus,
    extra: Vec<Property>,
    #[agdb(skip)]
    _skipped: (),
    #[agdb(flatten)]
    sub: SubProperty,
}

Telling overlapping types apart

Types derived with DbElement store their type with each element, so a search can return only the elements of one type even when several types with the same fields are reachable from the same node - no extra conditions needed:

let type1: T1 = db
    .exec(
        QueryBuilder::select()
            .element::<T1>()
            .search()
            .from("types")
            .query(),
    )?
    .try_into()?;
let type2: T2 = db
    .exec(
        QueryBuilder::select()
            .element::<T2>()
            .search()
            .from("types")
            .query(),
    )?
    .try_into()?;

Learn more

  • DbType in the queries reference.
  • Data types - which Rust types map to which database values.
  • Quickstart - a step-by-step guide using user types.