EasyDB

Struct EasyDB 

Source
pub struct EasyDB {
    pub db_name: String,
    /* private fields */
}
Expand description

Main library structure (Server Engine)

Fieldsยง

ยงdb_name: String

Implementationsยง

Sourceยง

impl EasyDB

Source

pub fn init(name: &str) -> Result<Self>

Initializes the database connection.

Examples found in repository?
examples/school_server.rs (line 8)
4async fn main() -> anyhow::Result<()> {
5    println!("๐Ÿ”” Starting School Server...");
6
7    // 1. Initialize a database named 'school_db'
8    let mut db = EasyDB::init("school_db").expect("Failed to create database");
9
10    // 2. Create Students Table
11    // Columns: id, name, school_number, class_grade, gpa
12    db.create_table(
13        "students",
14        "id INTEGER PRIMARY KEY, name TEXT, school_number INTEGER, class_grade TEXT, gpa REAL",
15    )?;
16
17    // 3. Create Grades Table
18    // Columns: id, school_number, lesson, score
19    db.create_table(
20        "grades",
21        "id INTEGER PRIMARY KEY, school_number INTEGER, lesson TEXT, score INTEGER",
22    )?;
23
24    // 4. Create Teachers Table
25    // Columns: id, name, branch
26    db.create_table("teachers", "id INTEGER PRIMARY KEY, name TEXT, branch TEXT")?;
27
28    // 5. Start the server on port 9000
29    println!("โœ… Tables are ready. API is listening on port 9000.");
30    db.run_server(9000).await?;
31
32    Ok(())
33}
More examples
Hide additional examples
examples/full_system.rs (line 18)
8async fn main() -> anyhow::Result<()> {
9    println!("๐Ÿš€ --- STARTING MONOLITHIC SYSTEM DEMO --- \n");
10
11    // =====================================================
12    // PART 1: SERVER SETUP (Background Task)
13    // =====================================================
14    let port = 9900; // Using a different port for this demo
15    let db_name = "monolith_school_db";
16
17    // 1. Initialize Database
18    let mut db = EasyDB::init(db_name).expect("Failed to init DB");
19
20    // 2. Create Tables
21    db.create_table(
22        "students",
23        "id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gpa REAL",
24    )?;
25    db.create_table("logs", "id INTEGER PRIMARY KEY, message TEXT, level TEXT")?;
26
27    println!("โœ… [SERVER] Tables created.");
28
29    // 3. Spawn the Server in a Background Task
30    // This ensures the server runs without blocking the main thread.
31    tokio::spawn(async move {
32        println!("โœ… [SERVER] Listening on port {}...", port);
33        if let Err(e) = db.run_server(port).await {
34            eprintln!("โŒ [SERVER] Error: {}", e);
35        }
36    });
37
38    // Give the server a moment to start up
39    sleep(Duration::from_millis(500)).await;
40
41    // =====================================================
42    // PART 2: CLIENT OPERATIONS (Main Thread)
43    // =====================================================
44    let client = EasyClient::new("localhost", port);
45    println!("\n๐Ÿ”— [CLIENT] Connected to localhost:{}\n", port);
46
47    // --- SCENARIO 1: CREATE (POST) ---
48    println!("๐Ÿ“ Action: Adding Students...");
49    client
50        .post(
51            "students",
52            json!({"name": "Alice Wonderland", "age": 20, "gpa": 3.8}),
53        )
54        .await?;
55    client
56        .post(
57            "students",
58            json!({"name": "Bob Builder", "age": 22, "gpa": 2.5}),
59        )
60        .await?;
61    client
62        .post(
63            "students",
64            json!({"name": "Charlie Chaplin", "age": 25, "gpa": 4.0}),
65        )
66        .await?;
67    println!("โœ… Students added.");
68
69    // --- SCENARIO 2: READ & FILTER (GET) ---
70    println!("๐Ÿ” Action: Finding 'Bob Builder'...");
71    let mut params = HashMap::new();
72    params.insert("name", "Bob Builder");
73
74    let bob_res = client.get("students", Some(params)).await?;
75    let bob_list = bob_res.as_array().expect("Expected array");
76    let bob_id = bob_list[0]["id"].as_i64().unwrap();
77    println!("โœ… Found Bob. ID: {}", bob_id);
78
79    // --- SCENARIO 3: UPDATE (PUT) ---
80    println!("๐Ÿ”„ Action: Updating Bob's GPA...");
81    client
82        .put(
83            "students",
84            bob_id,
85            json!({
86                "gpa": 3.0,
87                "age": 23
88            }),
89        )
90        .await?;
91    println!("โœ… Bob's record updated.");
92
93    // --- SCENARIO 4: SORTING (GET) ---
94    println!("๐Ÿ“Š Action: Fetching Top Students (Sorted by GPA DESC)...");
95    let mut sort_params = HashMap::new();
96    sort_params.insert("_sort", "gpa");
97    sort_params.insert("_order", "desc");
98
99    let sorted = client.get("students", Some(sort_params)).await?;
100    if let Some(list) = sorted.as_array() {
101        for s in list {
102            println!("   - {} (GPA: {})", s["name"], s["gpa"]);
103        }
104    }
105
106    // --- SCENARIO 5: DELETE (DELETE) ---
107    println!("โŒ Action: Deleting Charlie...");
108    // Find Charlie first to get ID (Simulated) or assuming ID 3 since it's sequential
109    client.delete("students", 3).await?;
110    println!("โœ… Charlie deleted.");
111
112    println!("\nโœจ --- DEMO COMPLETED SUCCESSFULLY ---");
113
114    // Optional: Keep server running if you want to test manually via browser
115    // std::future::pending::<()>().await;
116
117    Ok(())
118}
Source

pub fn create_table(&mut self, table_name: &str, columns: &str) -> Result<()>

Creates a table and automatically exposes it to the API.

Examples found in repository?
examples/school_server.rs (lines 12-15)
4async fn main() -> anyhow::Result<()> {
5    println!("๐Ÿ”” Starting School Server...");
6
7    // 1. Initialize a database named 'school_db'
8    let mut db = EasyDB::init("school_db").expect("Failed to create database");
9
10    // 2. Create Students Table
11    // Columns: id, name, school_number, class_grade, gpa
12    db.create_table(
13        "students",
14        "id INTEGER PRIMARY KEY, name TEXT, school_number INTEGER, class_grade TEXT, gpa REAL",
15    )?;
16
17    // 3. Create Grades Table
18    // Columns: id, school_number, lesson, score
19    db.create_table(
20        "grades",
21        "id INTEGER PRIMARY KEY, school_number INTEGER, lesson TEXT, score INTEGER",
22    )?;
23
24    // 4. Create Teachers Table
25    // Columns: id, name, branch
26    db.create_table("teachers", "id INTEGER PRIMARY KEY, name TEXT, branch TEXT")?;
27
28    // 5. Start the server on port 9000
29    println!("โœ… Tables are ready. API is listening on port 9000.");
30    db.run_server(9000).await?;
31
32    Ok(())
33}
More examples
Hide additional examples
examples/full_system.rs (lines 21-24)
8async fn main() -> anyhow::Result<()> {
9    println!("๐Ÿš€ --- STARTING MONOLITHIC SYSTEM DEMO --- \n");
10
11    // =====================================================
12    // PART 1: SERVER SETUP (Background Task)
13    // =====================================================
14    let port = 9900; // Using a different port for this demo
15    let db_name = "monolith_school_db";
16
17    // 1. Initialize Database
18    let mut db = EasyDB::init(db_name).expect("Failed to init DB");
19
20    // 2. Create Tables
21    db.create_table(
22        "students",
23        "id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gpa REAL",
24    )?;
25    db.create_table("logs", "id INTEGER PRIMARY KEY, message TEXT, level TEXT")?;
26
27    println!("โœ… [SERVER] Tables created.");
28
29    // 3. Spawn the Server in a Background Task
30    // This ensures the server runs without blocking the main thread.
31    tokio::spawn(async move {
32        println!("โœ… [SERVER] Listening on port {}...", port);
33        if let Err(e) = db.run_server(port).await {
34            eprintln!("โŒ [SERVER] Error: {}", e);
35        }
36    });
37
38    // Give the server a moment to start up
39    sleep(Duration::from_millis(500)).await;
40
41    // =====================================================
42    // PART 2: CLIENT OPERATIONS (Main Thread)
43    // =====================================================
44    let client = EasyClient::new("localhost", port);
45    println!("\n๐Ÿ”— [CLIENT] Connected to localhost:{}\n", port);
46
47    // --- SCENARIO 1: CREATE (POST) ---
48    println!("๐Ÿ“ Action: Adding Students...");
49    client
50        .post(
51            "students",
52            json!({"name": "Alice Wonderland", "age": 20, "gpa": 3.8}),
53        )
54        .await?;
55    client
56        .post(
57            "students",
58            json!({"name": "Bob Builder", "age": 22, "gpa": 2.5}),
59        )
60        .await?;
61    client
62        .post(
63            "students",
64            json!({"name": "Charlie Chaplin", "age": 25, "gpa": 4.0}),
65        )
66        .await?;
67    println!("โœ… Students added.");
68
69    // --- SCENARIO 2: READ & FILTER (GET) ---
70    println!("๐Ÿ” Action: Finding 'Bob Builder'...");
71    let mut params = HashMap::new();
72    params.insert("name", "Bob Builder");
73
74    let bob_res = client.get("students", Some(params)).await?;
75    let bob_list = bob_res.as_array().expect("Expected array");
76    let bob_id = bob_list[0]["id"].as_i64().unwrap();
77    println!("โœ… Found Bob. ID: {}", bob_id);
78
79    // --- SCENARIO 3: UPDATE (PUT) ---
80    println!("๐Ÿ”„ Action: Updating Bob's GPA...");
81    client
82        .put(
83            "students",
84            bob_id,
85            json!({
86                "gpa": 3.0,
87                "age": 23
88            }),
89        )
90        .await?;
91    println!("โœ… Bob's record updated.");
92
93    // --- SCENARIO 4: SORTING (GET) ---
94    println!("๐Ÿ“Š Action: Fetching Top Students (Sorted by GPA DESC)...");
95    let mut sort_params = HashMap::new();
96    sort_params.insert("_sort", "gpa");
97    sort_params.insert("_order", "desc");
98
99    let sorted = client.get("students", Some(sort_params)).await?;
100    if let Some(list) = sorted.as_array() {
101        for s in list {
102            println!("   - {} (GPA: {})", s["name"], s["gpa"]);
103        }
104    }
105
106    // --- SCENARIO 5: DELETE (DELETE) ---
107    println!("โŒ Action: Deleting Charlie...");
108    // Find Charlie first to get ID (Simulated) or assuming ID 3 since it's sequential
109    client.delete("students", 3).await?;
110    println!("โœ… Charlie deleted.");
111
112    println!("\nโœจ --- DEMO COMPLETED SUCCESSFULLY ---");
113
114    // Optional: Keep server running if you want to test manually via browser
115    // std::future::pending::<()>().await;
116
117    Ok(())
118}
Source

pub async fn run_server(self, port: u16) -> Result<()>

Starts the server and generates routes.

Examples found in repository?
examples/school_server.rs (line 30)
4async fn main() -> anyhow::Result<()> {
5    println!("๐Ÿ”” Starting School Server...");
6
7    // 1. Initialize a database named 'school_db'
8    let mut db = EasyDB::init("school_db").expect("Failed to create database");
9
10    // 2. Create Students Table
11    // Columns: id, name, school_number, class_grade, gpa
12    db.create_table(
13        "students",
14        "id INTEGER PRIMARY KEY, name TEXT, school_number INTEGER, class_grade TEXT, gpa REAL",
15    )?;
16
17    // 3. Create Grades Table
18    // Columns: id, school_number, lesson, score
19    db.create_table(
20        "grades",
21        "id INTEGER PRIMARY KEY, school_number INTEGER, lesson TEXT, score INTEGER",
22    )?;
23
24    // 4. Create Teachers Table
25    // Columns: id, name, branch
26    db.create_table("teachers", "id INTEGER PRIMARY KEY, name TEXT, branch TEXT")?;
27
28    // 5. Start the server on port 9000
29    println!("โœ… Tables are ready. API is listening on port 9000.");
30    db.run_server(9000).await?;
31
32    Ok(())
33}
More examples
Hide additional examples
examples/full_system.rs (line 33)
8async fn main() -> anyhow::Result<()> {
9    println!("๐Ÿš€ --- STARTING MONOLITHIC SYSTEM DEMO --- \n");
10
11    // =====================================================
12    // PART 1: SERVER SETUP (Background Task)
13    // =====================================================
14    let port = 9900; // Using a different port for this demo
15    let db_name = "monolith_school_db";
16
17    // 1. Initialize Database
18    let mut db = EasyDB::init(db_name).expect("Failed to init DB");
19
20    // 2. Create Tables
21    db.create_table(
22        "students",
23        "id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gpa REAL",
24    )?;
25    db.create_table("logs", "id INTEGER PRIMARY KEY, message TEXT, level TEXT")?;
26
27    println!("โœ… [SERVER] Tables created.");
28
29    // 3. Spawn the Server in a Background Task
30    // This ensures the server runs without blocking the main thread.
31    tokio::spawn(async move {
32        println!("โœ… [SERVER] Listening on port {}...", port);
33        if let Err(e) = db.run_server(port).await {
34            eprintln!("โŒ [SERVER] Error: {}", e);
35        }
36    });
37
38    // Give the server a moment to start up
39    sleep(Duration::from_millis(500)).await;
40
41    // =====================================================
42    // PART 2: CLIENT OPERATIONS (Main Thread)
43    // =====================================================
44    let client = EasyClient::new("localhost", port);
45    println!("\n๐Ÿ”— [CLIENT] Connected to localhost:{}\n", port);
46
47    // --- SCENARIO 1: CREATE (POST) ---
48    println!("๐Ÿ“ Action: Adding Students...");
49    client
50        .post(
51            "students",
52            json!({"name": "Alice Wonderland", "age": 20, "gpa": 3.8}),
53        )
54        .await?;
55    client
56        .post(
57            "students",
58            json!({"name": "Bob Builder", "age": 22, "gpa": 2.5}),
59        )
60        .await?;
61    client
62        .post(
63            "students",
64            json!({"name": "Charlie Chaplin", "age": 25, "gpa": 4.0}),
65        )
66        .await?;
67    println!("โœ… Students added.");
68
69    // --- SCENARIO 2: READ & FILTER (GET) ---
70    println!("๐Ÿ” Action: Finding 'Bob Builder'...");
71    let mut params = HashMap::new();
72    params.insert("name", "Bob Builder");
73
74    let bob_res = client.get("students", Some(params)).await?;
75    let bob_list = bob_res.as_array().expect("Expected array");
76    let bob_id = bob_list[0]["id"].as_i64().unwrap();
77    println!("โœ… Found Bob. ID: {}", bob_id);
78
79    // --- SCENARIO 3: UPDATE (PUT) ---
80    println!("๐Ÿ”„ Action: Updating Bob's GPA...");
81    client
82        .put(
83            "students",
84            bob_id,
85            json!({
86                "gpa": 3.0,
87                "age": 23
88            }),
89        )
90        .await?;
91    println!("โœ… Bob's record updated.");
92
93    // --- SCENARIO 4: SORTING (GET) ---
94    println!("๐Ÿ“Š Action: Fetching Top Students (Sorted by GPA DESC)...");
95    let mut sort_params = HashMap::new();
96    sort_params.insert("_sort", "gpa");
97    sort_params.insert("_order", "desc");
98
99    let sorted = client.get("students", Some(sort_params)).await?;
100    if let Some(list) = sorted.as_array() {
101        for s in list {
102            println!("   - {} (GPA: {})", s["name"], s["gpa"]);
103        }
104    }
105
106    // --- SCENARIO 5: DELETE (DELETE) ---
107    println!("โŒ Action: Deleting Charlie...");
108    // Find Charlie first to get ID (Simulated) or assuming ID 3 since it's sequential
109    client.delete("students", 3).await?;
110    println!("โœ… Charlie deleted.");
111
112    println!("\nโœจ --- DEMO COMPLETED SUCCESSFULLY ---");
113
114    // Optional: Keep server running if you want to test manually via browser
115    // std::future::pending::<()>().await;
116
117    Ok(())
118}

Auto Trait Implementationsยง

Blanket Implementationsยง

Sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

Sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Sourceยง

impl<T> From<T> for T

Sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

Sourceยง

impl<T> Instrument for T

Sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

Sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Sourceยง

impl<T> PolicyExt for T
where T: ?Sized,

Sourceยง

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Sourceยง

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
Sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Sourceยง

impl<T> WithSubscriber for T

Sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more