How to close a rusqlite connection in a mutex?

447 views Asked by At

I have a rusqlite connect in a mutex

as follows:

struct MyStruct {
    connection: std::sync::Mutex<rusqlite::Connection>,
}

When I'm finished with it I want to close it, which I attempted to do as follows:

let lock_ro = mystruct.connection.lock().unwrap();
lock_ro.close()
.map_err(|e| e.1)
.with_context(|| format!("failed to close))?;

However I get this error:

error[E0507]: cannot move out of dereference of std::sync::MutexGuard<'_, rusqlite::Connection>

and: ^^^^^^^ move occurs because value has type rusqlite::Connection, which does not implement the Copy trait

If I can't move it how can I close it?

1

There are 1 answers

0
kmdreko On

If MyStruct is shared between threads when you want to close it, you can store it as an Option:

struct MyStruct {
    connection: std::sync::Mutex<Option<rusqlite::Connection>>,
}

So then when you want to close it, you can take ownership of the value via .take() and then call .close():

mystruct.connection
    .lock()
    .expect("lock should not be poisoned")
    .take()
    .expect("there should be a connection")
    .close()
    .map_err(|e| e.1)
    .with_context(|| format!("failed to close"))?;