db/_archive/herodb_old/examples/tst_index_example.rs
2025-06-27 12:11:04 +03:00

93 lines
2.9 KiB
Rust

use herodb::db::{DB, DBBuilder, Model, IndexKey};
use herodb::models::biz::Customer;
use std::path::PathBuf;
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("TST Index Example");
println!("================");
// Create a temporary directory for the database
let db_path = PathBuf::from("/tmp/tst_index_example");
if db_path.exists() {
fs::remove_dir_all(&db_path)?;
}
fs::create_dir_all(&db_path)?;
println!("Database path: {:?}", db_path);
// Create a database instance with the Customer model registered
let db = DBBuilder::new(&db_path)
.register_model::<Customer>()
.build()?;
// Create some customers
let customer1 = Customer::new(
1,
"John Doe".to_string(),
"A regular customer".to_string(),
"pk123456".to_string(),
);
let customer2 = Customer::new(
2,
"Jane Smith".to_string(),
"A VIP customer".to_string(),
"pk789012".to_string(),
);
let customer3 = Customer::new(
3,
"John Smith".to_string(),
"Another customer".to_string(),
"pk345678".to_string(),
);
// Insert the customers
db.set(&customer1)?;
db.set(&customer2)?;
db.set(&customer3)?;
println!("\nCustomers created:");
println!("1. {} ({})", customer1.name, customer1.pubkey);
println!("2. {} ({})", customer2.name, customer2.pubkey);
println!("3. {} ({})", customer3.name, customer3.pubkey);
// List all customers
println!("\nListing all customers:");
let customers = db.list::<Customer>()?;
for customer in &customers {
println!("- {} (ID: {})", customer.name, customer.id);
}
println!("Total: {} customers", customers.len());
// Find customers by name index
println!("\nFinding customers by name 'John':");
let john_customers = db.find_by_index_prefix::<Customer>("name", "John")?;
for customer in &john_customers {
println!("- {} (ID: {})", customer.name, customer.id);
}
println!("Total: {} customers", john_customers.len());
// Find customers by pubkey index
println!("\nFinding customer by pubkey 'pk789012':");
let pubkey_customers = db.find_by_index::<Customer>("pubkey", "pk789012")?;
for customer in &pubkey_customers {
println!("- {} (ID: {})", customer.name, customer.id);
}
println!("Total: {} customers", pubkey_customers.len());
// Delete a customer
println!("\nDeleting customer with ID 2");
db.delete::<Customer>(2)?;
// List all customers again
println!("\nListing all customers after deletion:");
let customers = db.list::<Customer>()?;
for customer in &customers {
println!("- {} (ID: {})", customer.name, customer.id);
}
println!("Total: {} customers", customers.len());
println!("\nExample completed successfully!");
Ok(())
}