66 lines
2.0 KiB
Rust
66 lines
2.0 KiB
Rust
use heromodels::db::{Collection, Db};
|
|
use heromodels_core::{BaseModelData, Model};
|
|
use heromodels_derive::model;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
// Define a custom attribute for indexing
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
#[model]
|
|
pub struct CustomUser {
|
|
pub base_data: BaseModelData,
|
|
|
|
// Mark fields for indexing with attributes
|
|
#[index]
|
|
pub login: String,
|
|
|
|
#[index]
|
|
pub is_active: bool,
|
|
|
|
pub full_name: String,
|
|
}
|
|
|
|
fn main() {
|
|
println!("Hero Models - Custom Model Example");
|
|
println!("==================================");
|
|
|
|
// Create a new DB instance, reset before every run
|
|
let db_path = "/tmp/ourdb_custom_model_example";
|
|
let db = heromodels::db::hero::OurDB::new(db_path, true).expect("Can create DB");
|
|
|
|
// Example usage of the generated implementation
|
|
println!("CustomUser DB Prefix: {}", CustomUser::db_prefix());
|
|
|
|
let user = CustomUser {
|
|
base_data: BaseModelData::new(), // ID will be auto-generated by OurDB
|
|
login: "johndoe".to_string(),
|
|
is_active: true,
|
|
full_name: "John Doe".to_string(),
|
|
};
|
|
|
|
println!("\nBefore saving - CustomUser ID: {}", user.get_id());
|
|
println!("Before saving - CustomUser DB Keys: {:?}", user.db_keys());
|
|
|
|
// Save the model to the database
|
|
let collection = db
|
|
.collection::<CustomUser>()
|
|
.expect("can open user collection");
|
|
let (user_id, saved_user) = collection.set(&user).expect("can save user");
|
|
|
|
println!("\nAfter saving - CustomUser ID: {}", saved_user.get_id());
|
|
println!(
|
|
"After saving - CustomUser DB Keys: {:?}",
|
|
saved_user.db_keys()
|
|
);
|
|
println!("Returned ID: {}", user_id);
|
|
|
|
// Verify that the ID was auto-generated
|
|
assert_eq!(saved_user.get_id(), user_id);
|
|
assert_ne!(saved_user.get_id(), 0);
|
|
|
|
println!("\nExample finished. DB stored at {}", db_path);
|
|
println!(
|
|
"To clean up, you can manually delete the directory: {}",
|
|
db_path
|
|
);
|
|
}
|