macro_rules! realm_model {
($struct:ident => $($field:ident$(= $alias:expr)?),*$(; $backlinks:ident)?) => { ... };
}Expand description
Macro to implement conversion from a Row to a Realm model struct. This allows for easy creation of your own struct instances, based on data retrieved from a Realm database.
use realm_db_reader::realm_model;
struct MyStruct {
field1: String,
field2: i64,
}
realm_model!(MyStruct => field1, field2);You may only use types that either are valid Realm values, or can themselves be converted from Realm values. The builtin types are:
StringandOption<String>i64andOption<i64>boolandOption<bool>f32f64chrono::DateTime<Utc>andOption<chrono::DateTime<Utc>>Link,Option<Link>, andVec<Link>
All struct fields must be present, but you may omit columns that you don’t need. The types of the fields in your struct should, of course, match the types of the Realm table columns.
§Renaming fields
If you want to name a field differently, you can use the = syntax to
specify an alias:
use realm_db_reader::realm_model;
struct MyStruct {
my_struct_field: String,
my_other_struct_field: i64,
}
realm_model!(MyStruct => my_struct_field, my_other_struct_field = "realmColumnName");§Backlinks
Some tables in Realm can be linked to each other using backlinks. To define
a backlink, you can use the ; syntax to specify the name of your backlink
field:
use realm_db_reader::{realm_model, Backlink};
struct MyStruct {
field1: String,
field2: i64,
backlink_field: Vec<Backlink>,
}
realm_model!(MyStruct => field1, field2; backlink_field);This will create a backlink field in the struct that can be used to retrieve all rows that link to the current row. Backlink fields are unnamed in Realm, which is why they don’t follow the same conventions as other fields.
§Subtables
In the case where the Realm table contains a subtable, you can refer to this data too:
use realm_db_reader::realm_model;
struct MyStruct {
id: String,
// A subtable that contains a list of strings.
strings: Vec<String>,
// A subtable that contains complete data.
items: Vec<Item>,
}
realm_model!(MyStruct => id, strings, items);
struct Item {
subtable_row_id: String,
subtable_row_content: String,
}
// The aliases are not required here, it's just to illustrate they're
// available in subtables too.
realm_model!(Item => subtable_row_id = "id", subtable_row_content = "content");