Skip to content

Instantly share code, notes, and snippets.

@graffic
Last active November 16, 2021 15:21
Show Gist options
  • Save graffic/8734d58eba5d4727b553ba55579ecbba to your computer and use it in GitHub Desktop.
Save graffic/8734d58eba5d4727b553ba55579ecbba to your computer and use it in GitHub Desktop.
use std::rc::Rc;
use rusqlite::{params, Connection, Statement};
use owning_ref::OwningHandle;
struct MyStatements<'a> {
select_all: Statement<'a>,
select_one: Statement<'a>
}
type MyStatementsOwned = OwningHandle<Rc<Connection>, Box<MyStatements<'static>>>;
impl<'a> MyStatements<'a> {
fn new_owned(conn: Rc<Connection>) -> MyStatementsOwned {
OwningHandle::try_new(conn, |conn| -> Result<_,()> {
let (select_all, select_one) = unsafe {
((*conn).prepare("SELECT * FROM data").unwrap(),
(*conn).prepare("SELECT 1").unwrap())
};
let tr = MyStatements {
select_all,
select_one,
};
Ok(Box::new(tr))
}).unwrap()
}
}
pub struct SqliteHelper {
connection: Rc<Connection>,
statements: MyStatementsOwned
}
impl SqliteHelper {
fn new(db: &str) -> SqliteHelper {
let conn = Rc::new(Connection::open(db).unwrap());
SqliteHelper {
statements: MyStatements::new_owned(conn.clone()),
connection: conn,
}
}
fn do_something(&mut self) {
self.statements.select_one.execute(params![]).unwrap();
}
}
fn main() {
let mut helper = SqliteHelper::new("my_database.db");
helper.do_something();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment