basic_usage/
basic_usage.rs

1use avlon_db::AvlonDB;
2use serde::{Deserialize, Serialize};
3
4/// A struct representing a user account.
5#[derive(Serialize, Deserialize, Debug)]
6pub struct Account {
7    pub username: String,
8    pub password: String,
9    pub age: i32,
10}
11
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    // Define the database name and will create a same named directory in the current directory.
14    let db_name = String::from("test_db");
15
16    // Create an instance of Account
17    let account = Account {
18        username: String::from("johndoe"),
19        password: String::from("secretpassword"),
20        age: 30,
21    };
22
23    // Initialize the database
24    let db = AvlonDB::new(db_name);
25
26    // Save the account to the database
27    db.save(account.username.clone(), account)?;
28    println!("Account saved to database!");
29
30    // Load the account from the database
31    if let Some(loaded_account) = db.load::<Account>("johndoe")? {
32        println!("Account loaded from database: {:?}", loaded_account);
33    } else {
34        println!("Account not found in the database.");
35    }
36
37    // Update the account in the database
38    let updated_account = Account {
39        username: String::from("joker"),
40        password: String::from("123654987"),
41        age: 99,
42    };
43    db.update("johndoe", updated_account)?;
44
45    // Load the updated account from the database
46    if let Some(loaded_account) = db.load::<Account>("johndoe")? {
47        println!("Updated account loaded from database: {:?}", loaded_account);
48    } else {
49        println!("Account not found in the database.");
50    }
51
52    // Remove the account from the database
53    db.remove("johndoe")?;
54
55    // Attempt to load the account again after removal
56    if let Some(loaded_account) = db.load::<Account>("johndoe")? {
57        println!(
58            "Account loaded from database after removal: {:?}",
59            loaded_account
60        );
61    } else {
62        println!("Account successfully removed from the database.");
63    }
64
65    Ok(())
66}