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

81 lines
2.9 KiB
Rust

use herodb::db::{DB, DBBuilder, Model};
use herodb::models::biz::{Product, ProductBuilder, ProductType, ProductStatus, Currency, CurrencyBuilder};
use chrono::Utc;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("OurDB Backend Example");
println!("====================\n");
// Create a temporary directory for the database
let db_path = std::env::temp_dir().join("herodb_ourdb_example");
std::fs::create_dir_all(&db_path)?;
println!("Creating database at: {}", db_path.display());
// Create a new database with Product model registered
let db = DBBuilder::new(db_path.clone())
.register_model::<Product>()
.build()?;
println!("Database created successfully");
// Create a currency for pricing
let usd = CurrencyBuilder::new()
.id(1) // Add an ID for the currency
.amount(99.99)
.currency_code("USD")
.build()
.expect("Failed to create currency");
// Create a product
let product = ProductBuilder::new()
.id(1) // We're setting an ID manually for this example
.name("Test Product")
.description("A test product for our OurDB example")
.price(usd)
.type_(ProductType::Product)
.category("Test")
.status(ProductStatus::Available)
.max_amount(100)
.validity_days(365)
.build()
.expect("Failed to create product");
println!("\nCreated product: {}", product.name);
println!("Product ID: {}", product.get_id());
// Insert the product into the database
db.set(&product)?;
println!("Product saved to database");
// Retrieve the product from the database
let retrieved_product = db.get::<Product>(product.get_id())?;
println!("\nRetrieved product from database:");
println!(" Name: {}", retrieved_product.name);
println!(" Description: {}", retrieved_product.description);
println!(" Price: ${} {}", retrieved_product.price.amount, retrieved_product.price.currency_code);
// Create a product with auto-incremented ID
// For this to work, we would need to modify the Product model to support auto-incremented IDs
// This is just a conceptual example
println!("\nDemonstrating auto-incremented IDs:");
println!("(Note: This would require additional implementation in the Product model)");
// Delete the product
db.delete::<Product>(product.get_id())?;
println!("\nProduct deleted from database");
// Try to retrieve the deleted product (should fail)
match db.get::<Product>(product.get_id()) {
Ok(_) => println!("Product still exists (unexpected)"),
Err(e) => println!("Verified deletion: {}", e),
}
println!("\nExample completed successfully!");
// Clean up
std::fs::remove_dir_all(&db_path)?;
println!("Cleaned up database directory");
Ok(())
}