fix: Use incremental ID

This commit is contained in:
Mahmoud Emad
2025-05-17 13:46:16 +03:00
parent a676854251
commit 57f59da43e
10 changed files with 519 additions and 156 deletions

View File

@@ -1,3 +1,4 @@
use heromodels::db::{Collection, Db};
use heromodels_core::{BaseModelData, Model};
use heromodels_derive::model;
use serde::{Deserialize, Serialize};
@@ -33,26 +34,54 @@ fn main() {
println!("Hero Models - Model Macro Example");
println!("=================================");
// Create a new DB instance, reset before every run
let db_path = "/tmp/ourdb_model_macro_example";
let db = heromodels::db::hero::OurDB::new(db_path, true).expect("Can create DB");
// Example usage of the generated implementations
println!("SimpleUser DB Prefix: {}", SimpleUser::db_prefix());
println!("CustomUser DB Prefix: {}", CustomUser::db_prefix());
let user = SimpleUser {
base_data: BaseModelData::new(1),
base_data: BaseModelData::new(), // ID will be auto-generated by OurDB
login: "johndoe".to_string(),
full_name: "John Doe".to_string(),
};
let custom_user = CustomUser {
base_data: BaseModelData::new(2),
base_data: BaseModelData::new(), // ID will be auto-generated by OurDB
login_name: "janesmith".to_string(),
is_active: true,
full_name: "Jane Smith".to_string(),
};
println!("\nSimpleUser ID: {}", user.get_id());
println!("SimpleUser DB Keys: {:?}", user.db_keys());
println!("\nBefore saving - SimpleUser ID: {}", user.get_id());
println!("Before saving - SimpleUser DB Keys: {:?}", user.db_keys());
println!("\nCustomUser ID: {}", custom_user.get_id());
println!("CustomUser DB Keys: {:?}", custom_user.db_keys());
println!("\nBefore saving - CustomUser ID: {}", custom_user.get_id());
println!("Before saving - CustomUser DB Keys: {:?}", custom_user.db_keys());
// Save the models to the database
let simple_collection = db.collection::<SimpleUser>().expect("can open simple user collection");
let custom_collection = db.collection::<CustomUser>().expect("can open custom user collection");
let (user_id, saved_user) = simple_collection.set(&user).expect("can save simple user");
let (custom_user_id, saved_custom_user) = custom_collection.set(&custom_user).expect("can save custom user");
println!("\nAfter saving - SimpleUser ID: {}", saved_user.get_id());
println!("After saving - SimpleUser DB Keys: {:?}", saved_user.db_keys());
println!("Returned SimpleUser ID: {}", user_id);
println!("\nAfter saving - CustomUser ID: {}", saved_custom_user.get_id());
println!("After saving - CustomUser DB Keys: {:?}", saved_custom_user.db_keys());
println!("Returned CustomUser ID: {}", custom_user_id);
// Verify that the IDs were auto-generated
assert_eq!(saved_user.get_id(), user_id);
assert_ne!(saved_user.get_id(), 0);
assert_eq!(saved_custom_user.get_id(), custom_user_id);
assert_ne!(saved_custom_user.get_id(), 0);
println!("\nExample finished. DB stored at {}", db_path);
println!("To clean up, you can manually delete the directory: {}", db_path);
}