db/heromodels/examples/gov_rhai_example.rs
2025-06-21 09:23:22 +02:00

58 lines
1.8 KiB
Rust

use heromodels::db::hero::OurDB;
use heromodels::register_db_functions;
use rhai::Engine;
use std::sync::Arc;
use std::fs;
use std::path::Path;
use chrono::{DateTime, Utc, Duration};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a temporary directory for the database
let temp_dir = std::env::temp_dir().join("heromodels_gov_example");
if temp_dir.exists() {
fs::remove_dir_all(&temp_dir)?;
}
fs::create_dir_all(&temp_dir)?;
println!("Using temporary database at: {}", temp_dir.display());
// Create a new OurDB instance
let db = OurDB::new(&temp_dir, true)?;
let db = Arc::new(db);
// Create a new Rhai engine
let mut engine = Engine::new();
// Register the auto-generated DB functions with the engine
register_db_functions(&mut engine);
// Register print functions
engine.register_fn("println", |s: &str| println!("{}", s));
engine.register_fn("print", |s: &str| print!("{}", s));
// Register date/time functions
engine.register_fn("now", || Utc::now());
engine.register_fn("days", |n: i64| Duration::days(n));
engine.register_fn("+", |dt: DateTime<Utc>, duration: Duration| dt + duration);
// Add the DB instance to the engine's scope
engine.register_fn("get_db", move || -> Arc<OurDB> { db.clone() });
// Load and execute the Rhai script
let script_path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("examples")
.join("gov_example.rhai");
println!("Loading Rhai script from: {}", script_path.display());
match engine.eval_file::<()>(script_path) {
Ok(_) => println!("Script executed successfully"),
Err(e) => eprintln!("Error executing script: {}", e),
}
// Clean up the temporary directory
fs::remove_dir_all(&temp_dir)?;
Ok(())
}