How to wrap "rusqlite" connection *and* prepared statements together in a struct? Or is there a better alternative?
⚓ Rust 📅 2025-09-17 👤 surdeus 👁️ 9I'm writing a struct that represents a DB and that should provide "high level" functions to access the database, hiding the details of the SQL stuff. I'm using the rusqlite crate, internally.
Now, it is straight forward to wrap the underlying rusqlite DB connection in my struct. The connection will be created in the constructor (i.e., new()) and it will be closed in the Drop handler. The DB tables will also be created in new(), the via self.conn.execute() function.
The problem is that, for the actual load() and store() functions, which will do the heavy lifting, I want to use prepared statements. These should be created once and re-used whenever load() or store() is called. So, I need to create them in the new() function, by calling self.conn.prepare(), and store them in my struct alongside the connection.
Essentially, what I need is:
pub struct MyDatabase<'a> {
conn: Connection,
prepared_statement_1: Statement<'a>,
prepared_statement_2: Statement<'a>,
...
prepared_statement_n: Statement<'a>,
}
Unfortunately, this doesn't work, because Statement<'a> holds a reference to the Connection that has lifetime 'a, and Rust doesn't allow me to store the owned Connection instance in the same struct as the Statement<'a> instances that hold references to that connection ![]()
From a "lifetime" perspective, this is perfectly fine, because the Statement<'a> is referencing a Connection that lives in the same struct, which means that the Connection will obviously be alive for as long as the Statement<'a> is alive. But how do I convince the Rust compiler?
Is there a "good" way to maintain the Statement<'a>s together with the Connection ??? ![]()
Thanks for any suggestions!
2 posts - 2 participants
🏷️ Rust_feed