88 lines
2.3 KiB
Rust
88 lines
2.3 KiB
Rust
|
use rusqlite::{params, Connection, Result};
|
||
|
// use std::collections::HashMap;
|
||
|
|
||
|
pub struct KeyValueStore {
|
||
|
conn: Connection,
|
||
|
}
|
||
|
|
||
|
impl KeyValueStore {
|
||
|
// Initialize the database and create the table if it doesn't exist
|
||
|
pub fn new(db_path: &str) -> Result<Self> {
|
||
|
let conn = Connection::open(db_path)?;
|
||
|
conn.execute(
|
||
|
"CREATE TABLE IF NOT EXISTS kv_store (
|
||
|
key TEXT PRIMARY KEY,
|
||
|
value TEXT NOT NULL
|
||
|
)",
|
||
|
[],
|
||
|
)?;
|
||
|
Ok(KeyValueStore { conn })
|
||
|
}
|
||
|
|
||
|
// Insert or update a key-value pair
|
||
|
pub fn set(&self, key: &str, value: &str) -> Result<()> {
|
||
|
self.conn.execute(
|
||
|
"INSERT INTO kv_store (key, value) VALUES (?1, ?2)
|
||
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||
|
params![key, value],
|
||
|
)?;
|
||
|
Ok(())
|
||
|
}
|
||
|
|
||
|
pub fn default(&self, key: &str, value: &str) {
|
||
|
self.conn.execute(
|
||
|
"INSERT INTO kv_store (key, value) VALUES (?1, ?2)
|
||
|
ON CONFLICT(key) DO NOTHING",
|
||
|
params![key, value],
|
||
|
).ok();
|
||
|
}
|
||
|
|
||
|
// Retrieve a value by key
|
||
|
pub fn get(&self, key: &str) -> Result<Option<String>> {
|
||
|
let mut stmt = self.conn.prepare("SELECT value FROM kv_store WHERE key = ?1")?;
|
||
|
let mut rows = stmt.query(params![key])?;
|
||
|
|
||
|
if let Some(row) = rows.next()? {
|
||
|
let value: String = row.get(0)?;
|
||
|
Ok(Some(value))
|
||
|
} else {
|
||
|
Ok(None)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Delete a key-value pair
|
||
|
pub fn delete(&self, key: &str) -> Result<()> {
|
||
|
self.conn.execute("DELETE FROM kv_store WHERE key = ?1", params![key])?;
|
||
|
Ok(())
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
/*
|
||
|
fn main() -> Result<()> {
|
||
|
let kv_store = KeyValueStore::new("kv_store.db")?;
|
||
|
|
||
|
// Set some key-value pairs
|
||
|
kv_store.set("last_week_pad", "pad_id_123")?;
|
||
|
kv_store.set("email_id", "email_id_456")?;
|
||
|
|
||
|
// Retrieve and print values
|
||
|
if let Some(value) = kv_store.get("last_week_pad")? {
|
||
|
println!("Last week's pad ID: {}", value);
|
||
|
} else {
|
||
|
println!("Key not found");
|
||
|
}
|
||
|
|
||
|
if let Some(value) = kv_store.get("email_id")? {
|
||
|
println!("Email ID: {}", value);
|
||
|
} else {
|
||
|
println!("Key not found");
|
||
|
}
|
||
|
|
||
|
// Delete a key-value pair
|
||
|
kv_store.delete("last_week_pad")?;
|
||
|
|
||
|
Ok(())
|
||
|
}
|
||
|
|
||
|
*/
|