Created
June 22, 2021 21:40
-
-
Save lisael/75dc89592d8a8e863b1e6e9d11d0ce07 to your computer and use it in GitHub Desktop.
rusql stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rusqlite::{params, Connection, Result}; | |
use serde_derive::{Deserialize, Serialize}; | |
use serde_rusqlite::*; | |
use std::fs::File; | |
#[derive(Debug, Deserialize, Serialize)] | |
struct TodoItem { | |
id: Option<i32>, | |
content: String, | |
done: bool, | |
parent_id: Option<i32>, | |
} | |
impl TodoItem { | |
pub fn save(&mut self, conn: &Connection) -> Result<()> { | |
Ok(match self.id { | |
Some(_) => { | |
conn.execute( | |
"UPDATE TodoItem | |
SET content = :content, | |
done = :done, | |
WHERE id == :id", | |
to_params_named(&self).unwrap().to_slice().as_slice(), | |
)?; | |
} | |
None => { | |
let id = conn.query_row( | |
"INSERT INTO TodoItem (content, done) VALUES (?1, ?2) RETURNING id", | |
params![self.content, self.done], | |
|row| row.get(0), | |
)?; | |
self.id = id; | |
} | |
}) | |
} | |
pub fn get_by_id(conn: &Connection, id: i32) -> Result<Self> { | |
let mut stmt = conn.prepare("SELECT * FROM TodoItem WHERE id=?1")?; | |
let mut rows = stmt.query_and_then(params![id], from_row::<TodoItem>)?; | |
rows.next() | |
.unwrap() | |
.map_err(|_| rusqlite::Error::InvalidQuery) | |
} | |
} | |
fn init_db(conn: &Connection) -> Result<()> { | |
conn.execute( | |
"CREATE TABLE TodoItem ( | |
id INTEGER PRIMARY KEY, | |
content TEXT NOT NULL, | |
done BOOL, | |
parent_id INTEGER REFERENCES TodoItem | |
)", | |
[], | |
)?; | |
Ok(()) | |
} | |
fn main() -> Result<()> { | |
let conn: Connection; | |
match File::open("test.sqlite") { | |
Ok(_) => { | |
conn = Connection::open("test.sqlite")?; | |
} | |
Err(_) => { | |
conn = Connection::open("test.sqlite")?; | |
init_db(&conn)?; | |
} | |
} | |
let mut task1 = TodoItem { | |
id: None, | |
content: "Task one".to_owned(), | |
done: false, | |
}; | |
println!("{:?}", task1); | |
task1.save(&conn)?; | |
println!("{:?}", task1); | |
let mut stmt = conn.prepare("SELECT * FROM TodoItem")?; | |
let todo_iter = from_rows::<TodoItem>(stmt.query([])?); | |
for person in todo_iter { | |
println!("Found todo {:?}", person.unwrap()); | |
} | |
println!("get id=12: {:?}", TodoItem::get_by_id(&conn, 12)?); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment