Generic database request

Hello Rust World,

I'm new to Rust Lang; I'm coming from C++, and a few peculiarities of the language still pose problems for me.

I'm trying to create an interface to an SQLite DB using Rustqlite. I've made a basic method for handling generic requests, but I'm having trouble understanding the errors.

Code:

pub fn query_projects(&mut self, query: &str) -> Result<Rows<'_>> {
    let mut stmt = self.conn.prepare(query)?;
    let rows = stmt.query([]).unwrap();
    Ok(rows)
}

Error:

   Compiling myapp v0.1.0 (/home/jiel/rust/myapp)
error[E0515]: cannot return value referencing local variable `stmt`
  --> src/database.rs:28:9
   |
27 |         let rows = stmt.query([]).unwrap();
   |                    -------------- `stmt` is borrowed here
28 |         Ok(rows)
   |         ^^^^^^^^ returns a value referencing data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `myapp` due to previous error

Thank you for helping a new rust user.

The error message says it all; it can also be inferred from the signature of Statement::query(). The returned Rows handle contains a reference to the statement, so you can't hold onto it if the underlying statement is dropped.

1 Like

Args for the query is an implicit temporary variable stored on the stack, and returned Rows<'_> still needs to read it to iterate the query. That <'_> in its type means it's not a standalone-value, but it has a view (pointer) into the same data that it had as input.

Your [] is going to get destroyed before query_projects returns. You need to pass args to the function, so that they aren't stored in function call's stack. Alternatively if they're always empty, use a global constant ('static) for the args.

2 Likes