How can you close a tokio-postgres connection?

1.1k views Asked by At

In the tokio-postgres documentation in the first example, there is an example showing that you should run the database connection in a separate thread:

// The connection object performs the actual communication with the database,
// so spawn it off to run on its own.
tokio::spawn(async move {
    if let Err(e) = connection.await {
        eprintln!("connection error: {}", e);
    }
});

If you do so, how can you kill that connection afterwards?

1

There are 1 answers

0
sebpuetz On BEST ANSWER

If you're on tokio 1, tokio::task::JoinHandle has an abort() function that cancels the task, thus dropping the connection.

let handle = task::spawn(async move {
    if let Err(e) = connection.await {
        eprintln!("connection error: {}", e);
    }
}
handle.abort(); // this kills the task and drops the connection

Using my snippet as-is will immediately kill the task, thus this is probably not what you want in the end, but if you keep the handle around and use it e.g. in combination with some kind of shutdown listener you should be able to control the connection as wanted.