# Derive macros

> Reference of the agdb derive macros: DbType, DbElement, DbValue, DbSerialize, DbTypeMarker and the agdb field attributes

The `agdb` crate provides derive macros that let you use your own structs and enums directly in queries. They are provided by the `agdb_derive` crate that is re-exported by `agdb` under the `derive` cargo feature, which is enabled by default:

```rs
use agdb::DbElement;
use agdb::DbSerialize;
use agdb::DbType;
use agdb::DbTypeMarker;
use agdb::DbValue;
```

If you disable default features you can bring the macros back with `features = ["derive"]`. For a runnable walk-through see the [user types example](/docs/examples/user-types). The `DbType` trait itself is described in the [queries reference](/docs/references/queries#dbtype).

<table>
<thead>
  <tr>
    <th>
      Macro
    </th>
    
    <th>
      Applies to
    </th>
    
    <th>
      Implements
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        DbType
      </code>
    </td>
    
    <td>
      structs
    </td>
    
    <td>
      <code>
        DbType
      </code>
      
      , <code>
        TryFrom<&DbElement>
      </code>
      
      , <code>
        TryFrom<QueryResult>
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        DbElement
      </code>
    </td>
    
    <td>
      structs
    </td>
    
    <td>
      same as <code>
        DbType
      </code>
      
       plus <code>
        DbType::db_element_id()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        DbValue
      </code>
    </td>
    
    <td>
      structs and enums
    </td>
    
    <td>
      <code>
        From<T>
      </code>
      
      , <code>
        From<&T>
      </code>
      
       for <code>
        DbValue
      </code>
      
       and <code>
        TryFrom<DbValue>
      </code>
      
       (as bytes)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        DbSerialize
      </code>
    </td>
    
    <td>
      structs and enums
    </td>
    
    <td>
      <code>
        AgdbSerialize
      </code>
      
       (serialization to and from bytes)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        DbTypeMarker
      </code>
    </td>
    
    <td>
      any type
    </td>
    
    <td>
      the empty marker trait <code>
        DbTypeMarker
      </code>
    </td>
  </tr>
</tbody>
</table>

## DbType

`#[derive(DbType)]` maps a struct with named fields to the key-value pairs of a single database element. Each field name becomes a key (a `String`) and the field value is converted to a `DbValue` (e.g. `i32` is stored as `i64`). See [data types](/docs/guides/concepts#data-types) for the supported conversions.

```rs
#[derive(DbType)]
struct User {
    db_id: Option<DbId>,
    name: String,
    age: u64,
}
```

The derive generates:

- `DbType::to_db_values()` - the key-value pairs to be stored.
- `DbType::from_db_element()` - the reverse conversion from a `DbElement`.
- `DbType::db_keys()` - the list of keys of the type (see below).
- `DbType::db_id()` - the id of the element if the type has a `db_id` field, otherwise `None`.
- `TryFrom<&DbElement>` and `TryFrom<QueryResult>` for the type. The latter converts the first element of the result.

### Requirements and limitations

- Only structs with named fields are supported. Using the derive on an enum is a compile error.
- Generic structs are not supported. (`DbValue`, `DbSerialize` and `DbTypeMarker` are covered separately below.)
- Every field type must convert to and from `DbValue`. That is the native types, the conversions listed in the [queries reference](/docs/references/queries#dbtype), or your own types with `From<T> for DbValue` and `TryFrom<DbValue> for T` implemented by hand or via [`DbValue`](#dbvalue). Nested structs can alternatively be merged into the parent with [`#[agdb(flatten)]`](#agdbflatten).
- Every stored field must implement `Clone`, because the values are cloned when converted.
- `Vec<T>` fields of your own types require `T: DbTypeMarker`, see [`DbTypeMarker`](#dbtypemarker).
- When reading, a missing key is a `NotFound` error and a value that cannot be converted is a `TypeError`.

### The `db_id` field

A field named `db_id` is special. It is never stored as a property. It is set from the id of the element when reading and used as the id when the type is passed to `insert().element()` / `insert().elements()`. Its type is either `Option<T>` where `T: Into<QueryId>` (e.g. `Option<DbId>` or `Option<QueryId>`) or a plain `DbId`. The field is optional - without it all other features still work, you just cannot use the shorthand updates.

### Optional fields

A field of type `Option<T>` is not stored when it is `None` and is read as `None` when its key is missing. Because not all keys are guaranteed to exist, `db_keys()` returns an empty list for a type with any `Option` field (other than `db_id`). Selecting with it - `select().values(T::db_keys())` or `select().elements::<T>()` - then selects all values of the element.

<warning>

Only the struct's own fields are checked. If a [flattened](#agdbflatten) type has an `Option` field, the parent's `db_keys()` silently leave out all the keys of the nested type, so `select().elements::<T>()` does not select them and they read back as missing (`None`, or an error for non-optional fields). Avoid `Option` fields in flattened types, or select all values (`select().ids(..)`) for such a type.

</warning>

### Using the type in queries

```rs
let users = vec![
    User { db_id: None, name: "Bob".to_string(), age: 30 },
    User { db_id: None, name: "Alice".to_string(), age: 25 },
];

// insert new nodes with the values taken from the structs
let result = db.exec_mut(QueryBuilder::insert().nodes().values(&users).query())?;

// select the elements as users
let users: Vec<User> = db
    .exec(QueryBuilder::select().elements::<User>().ids(result).query())?
    .try_into()?;

// update elements that have the db_id set
db.exec_mut(QueryBuilder::insert().elements(&users).query())?;

// a single element
db.exec_mut(QueryBuilder::insert().element(&users[0]).query())?;
```

- `values(&T)` / `values(&Vec<T>)` supply the values for inserts. A blanket `impl<T: DbType> DbType for &T` makes references work too.
- `insert().element(&t)` / `elements(&ts)` infer both ids (from `db_id`) and values. Elements without `db_id` are inserted as new nodes, otherwise they are updated.
- `select().elements::<T>()` selects the keys of `T` (all values if `db_keys()` is empty) and `select().element::<T>()` selects a single element (see [select values](/docs/references/queries#select-values)).
- `try_into()` converts a `QueryResult` to `T` (the first element) or to `Vec<T>` (all elements).
- `search().where_().element::<T>()` adds a condition matching the keys of `T` (or the `db_element_id` of [`DbElement`](#dbelement)). For a `DbType` with an `Option` field the key list is empty and the condition matches every element.

### `#[agdb(skip)]`

```rs
#[derive(DbType)]
struct Item {
    name: String,
    #[agdb(skip)]
    cache: Vec<String>,
}
```

The field is neither stored nor selected. When reading, it is filled with `Default::default()` (or `None` for an `Option`), so its type must implement `Default`.

### `#[agdb(rename = "...")]`

```rs
#[derive(DbType)]
struct Category {
    #[agdb(rename = "category_name")]
    name: String,
}
```

Uses the given string as the key instead of the field name. Useful to keep database keys stable independent of the Rust names and to disambiguate keys when flattening.

### `#[agdb(flatten)]`

```rs
#[derive(DbType)]
struct Address {
    city: String,
}

#[derive(DbType)]
struct Person {
    name: String,
    #[agdb(flatten)]
    address: Address,
}
```

The fields of the nested struct are stored directly on the element (`name`, `city`) instead of the nested value being converted to a single `DbValue`. The nested type must itself implement `DbType`, and it works transitively. If nested structs have the same key the last one written wins - use `rename` to disambiguate. A flattened `Option<T>` is `None` when reading if the nested type cannot be read from the element. If the nested type derives `DbElement`, its `db_element_id` is ignored and the parent's is used.

<note>

The attributes are written as `#[agdb(...)]`. Only `skip`, `rename` and `flatten` exist. They can be given on named fields of `DbType` and `DbElement` structs. Give a field at most one option: only the first `#[agdb(...)]` attribute of a field is read, the options are not meant to be combined (a skipped field has no key and a flattened field uses the keys of the nested type) and an option written after `rename = "..."` in the same attribute is not recognised. Unknown options are ignored.

</note>

## DbElement

`#[derive(DbElement)]` does everything `DbType` does and additionally implements `DbType::db_element_id()` returning the name of the type. When such a type is stored, an extra property `db_element_id` with the type name is added to the element. It is not part of `db_keys()`.

This allows telling apart types with the same fields. When used with the `QueryBuilder`, `select().element::<T>().search()` (and `elements::<T>()`) automatically adds the condition `key("db_element_id").value("T")` to the search, so only elements of that type are returned even when several types are reachable from the same node.

```rs
#[derive(DbElement)]
struct Dog {
    name: String,
}

#[derive(DbElement)]
struct Cat {
    name: String,
}

db.exec_mut(QueryBuilder::insert().nodes().aliases("pets").query())?;
let dog = db.exec_mut(QueryBuilder::insert().element(Dog { name: "Rex".into() }).query())?;
let cat = db.exec_mut(QueryBuilder::insert().element(Cat { name: "Tom".into() }).query())?;
db.exec_mut(
    QueryBuilder::insert()
        .edges()
        .from("pets")
        .to([dog.elements[0].id, cat.elements[0].id])
        .query(),
)?;

// no extra conditions needed, only the Dog is returned
let dog: Dog = db
    .exec(QueryBuilder::select().element::<Dog>().search().from("pets").query())?
    .try_into()?;
```

The name is the type name only (no module path), so two types with the same name in different modules are not distinguished. The requirements, attributes and limitations are the same as for [`DbType`](#dbtype).

## DbValue

`#[derive(DbValue)]` lets a struct or an enum be used as a field of a `DbType` struct (or anywhere `Into<DbValue>` is expected) without writing the conversions by hand. The value is stored as `DbValue::Bytes` using [`AgdbSerialize`](#dbserialize).

It implements `From<T>` and `From<&T>` for `DbValue` and `TryFrom<DbValue>` for `T` (returning `DbError` when the value is not bytes or the bytes are invalid).

```rs
#[derive(Clone, DbSerialize, DbValue)]
enum Status {
    Active,
    Inactive,
}
```

### Requirements and limitations

- The type must implement `AgdbSerialize`, which you get with `#[derive(DbSerialize)]`.
- Structs and enums are supported, including generic ones. The generic parameters and the `where` clause are carried over to the implementations without adding bounds, so bound the parameters yourself so that the type implements `AgdbSerialize` (e.g. `struct Foo<T: AgdbSerialize>`).
- To use the type as a field of a `DbType` struct it must also implement `Clone`.
- The value is opaque binary data. It cannot be searched or compared by its content, only by the whole value. If you need to query the fields, use `DbType` (with `flatten`) instead.
- To use it in `Vec<T>` fields also derive [`DbTypeMarker`](#dbtypemarker).

## DbSerialize

`#[derive(DbSerialize)]` implements `AgdbSerialize` - the platform agnostic binary serialization used by `agdb` itself. Use it to serialize your own structures when you do not want or cannot use `serde`. It is also what `DbValue` builds on.

```rs
#[derive(DbSerialize)]
struct Property {
    name: String,
    value: String,
}
```

- Supported are structs with named fields, tuple structs and enums (unit, tuple and struct variants). An enum is serialized as its variant index followed by the fields of the variant, so reordering or inserting variants changes the stored format.
- All fields must implement `AgdbSerialize`. It is implemented for `i64`, `u64`, `f64`, `usize`, `bool`, `String`, `Vec<T>`, `Option<T>`, pairs `(A, B)`, `PathBuf`, `SystemTime`, `SocketAddr` and `IpAddr` and for other types deriving `DbSerialize`. Other integer widths such as `i32` need to be wrapped or converted.
- Generic types are supported and each type parameter gets an `AgdbSerialize` bound.

## DbTypeMarker

`#[derive(DbTypeMarker)]` implements the empty marker trait `DbTypeMarker`. The marker is needed because `Vec<T>` converts to `DbValue` only when `T: Into<DbValue> + DbTypeMarker`, which avoids conflicts with the blanket implementations for native types. Derive it on the types you want to use in `Vec<T>` fields.

```rs
#[derive(Clone, DbTypeMarker, DbSerialize, DbValue)]
struct Property {
    name: String,
    value: String,
}

#[derive(DbType)]
struct Node {
    name: String,
    properties: Vec<Property>,
}
```

A single value of the type does not need the marker. The derive does not take generic parameters into account, so for generic types implement the trait by hand: `impl<T> agdb::DbTypeMarker for MyType<T> {}`.

## Putting it together

```rs
#[derive(Clone, DbTypeMarker, DbSerialize, DbValue)]
struct Property {
    name: String,
    value: String,
}

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

#[derive(DbType)]
struct User {
    db_id: Option<DbId>,
    username: String,
    #[agdb(rename = "name")]
    display_name: Option<String>,
    properties: Vec<Property>,
    #[agdb(skip)]
    session: (),
    #[agdb(flatten)]
    extra: Extra,
}
```

See the [user types example](/docs/examples/user-types) for the complete runnable program and [queries reference](/docs/references/queries#dbtype) for the `DbType` trait and the type conversions.
