core/src/db/mod.rs

60 lines
1.6 KiB
Rust
Raw Normal View History

2021-02-27 21:58:55 +00:00
use rusqlite::{params, Connection, Result};
2020-11-22 14:31:45 +00:00
pub mod messaging;
2021-02-27 21:58:55 +00:00
#[derive(Debug)]
pub struct Person {
id: i32,
name: String,
2021-03-11 06:53:47 +00:00
key: String,
2021-02-27 21:58:55 +00:00
}
2021-03-11 06:53:47 +00:00
fn create_db(conn: &Connection) -> Result<()> {
match conn.execute(
"CREATE TABLE users (
2021-02-27 21:58:55 +00:00
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
2021-03-11 06:53:47 +00:00
key BLOB
2021-02-27 21:58:55 +00:00
)",
2021-03-11 06:53:47 +00:00
params![],
) {
Ok(_) => {log::info!("USER table created successfully!")},
Err(e) => log::error!("failed to create USER table {:?}", e),
}
Ok(())
}
pub fn start_db() -> Result<()> {
let conn = Connection::open("hole.db")?;
println!("{}", conn.is_autocommit());
match create_db(&conn) {
Ok(_) => log::info!("Successfully created DB!"),
Err(e) => log::error!("Failed to create DB: {:?}", e)
2021-02-27 21:58:55 +00:00
}
let me = Person {
id: 0,
name: "Steven".to_string(),
2021-03-11 06:53:47 +00:00
key: "SSK@OolaRmEpOc1q0JF9iypUHZTlNNIqstOnScyb15SUr6k,MgxYrnex5LfvW-pRwMINs~d4nE2mYKjW1AE1U9vIPUM,AQECAAE".to_string(),
2021-02-27 21:58:55 +00:00
};
conn.execute(
2021-03-11 06:53:47 +00:00
"INSERT INTO users (name, key) VALUES (?1, ?2)",
params![me.name, me.key],
2021-02-27 21:58:55 +00:00
)?;
2021-03-11 06:53:47 +00:00
let mut stmt = conn.prepare("SELECT id, name, key FROM users")?;
2021-02-27 21:58:55 +00:00
let person_iter = stmt.query_map(params![], |row| {
Ok(Person {
id: row.get(0)?,
name: row.get(1)?,
2021-03-11 06:53:47 +00:00
key: row.get(2)?,
2021-02-27 21:58:55 +00:00
})
})?;
2021-03-11 06:53:47 +00:00
2021-02-27 21:58:55 +00:00
for person in person_iter {
println!("Found person {:?}", person.unwrap());
}
Ok(())
2020-11-22 14:31:45 +00:00
}