async_duckdb/client.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
use crate::Error;
use std::{
path::{Path, PathBuf},
thread,
};
use crossbeam_channel::{bounded, unbounded, Sender};
use duckdb::{Config, Connection};
use futures_channel::oneshot;
/// A `ClientBuilder` can be used to create a [`Client`] with custom
/// configuration.
///
/// For more information on creating a duckdb connection, see the
/// [duckdb docs](duckdb::Connection::open()).
///
/// # Examples
///
/// ```rust
/// # use async_duckdb::ClientBuilder;
/// # async fn run() -> Result<(), async_duckdb::Error> {
/// let client = ClientBuilder::new().path("path/to/db.duckdb").open().await?;
///
/// // ...
///
/// client.close().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct ClientBuilder {
pub(crate) path: Option<PathBuf>,
pub(crate) flagsfn: Option<fn() -> duckdb::Result<Config>>,
}
impl ClientBuilder {
/// Returns a new [`ClientBuilder`] with the default settings.
pub fn new() -> Self {
Self::default()
}
/// Specify the path of the duckdb database to open.
///
/// By default, an in-memory database is used.
pub fn path<P: AsRef<Path>>(mut self, path: P) -> Self {
self.path = Some(path.as_ref().into());
self
}
/// Specify the [`OpenFlags`] to use when opening a new connection.
///
/// By default, [`OpenFlags::default()`] is used.
pub fn flagsfn(mut self, flags: fn() -> duckdb::Result<Config>) -> Self {
self.flagsfn = Some(flags);
self
}
/// Returns a new [`Client`] that uses the `ClientBuilder` configuration.
///
/// # Examples
///
/// ```rust
/// # use async_duckdb::ClientBuilder;
/// # async fn run() -> Result<(), async_duckdb::Error> {
/// let client = ClientBuilder::new().open().await?;
/// # Ok(())
/// # }
/// ```
pub async fn open(self) -> Result<Client, Error> {
Client::open_async(self).await
}
/// Returns a new [`Client`] that uses the `ClientBuilder` configuration,
/// blocking the current thread.
///
/// # Examples
///
/// ```rust
/// # use async_duckdb::ClientBuilder;
/// # fn run() -> Result<(), async_duckdb::Error> {
/// let client = ClientBuilder::new().open_blocking()?;
/// # Ok(())
/// # }
/// ```
pub fn open_blocking(self) -> Result<Client, Error> {
Client::open_blocking(self)
}
}
enum Command {
Func(Box<dyn FnOnce(&mut Connection) + Send>),
Shutdown(Box<dyn FnOnce(Result<(), Error>) + Send>),
}
/// Client represents a single duckdb connection that can be used from async
/// contexts.
#[derive(Clone)]
pub struct Client {
conn_tx: Sender<Command>,
}
impl Client {
async fn open_async(builder: ClientBuilder) -> Result<Self, Error> {
let (open_tx, open_rx) = oneshot::channel();
Self::open(builder, |res| {
_ = open_tx.send(res);
});
open_rx.await?
}
fn open_blocking(builder: ClientBuilder) -> Result<Self, Error> {
let (conn_tx, conn_rx) = bounded(1);
Self::open(builder, move |res| {
_ = conn_tx.send(res);
});
conn_rx.recv()?
}
fn open<F>(builder: ClientBuilder, func: F)
where
F: FnOnce(Result<Self, Error>) + Send + 'static,
{
thread::spawn(move || {
let (conn_tx, conn_rx) = unbounded();
let mut conn = match Client::create_conn(builder) {
Ok(conn) => conn,
Err(err) => {
func(Err(err));
return;
}
};
let client = Self { conn_tx };
func(Ok(client));
while let Ok(cmd) = conn_rx.recv() {
match cmd {
Command::Func(func) => func(&mut conn),
Command::Shutdown(func) => match conn.close() {
Ok(()) => {
func(Ok(()));
return;
}
Err((c, e)) => {
conn = c;
func(Err(e.into()));
}
},
}
}
});
}
fn create_conn(mut builder: ClientBuilder) -> Result<Connection, Error> {
let path = builder.path.take().unwrap_or_else(|| ":memory:".into());
let config = if let Some(flagsfn) = builder.flagsfn {
flagsfn()?
} else {
Config::default()
};
let conn = Connection::open_with_flags(path, config)?;
Ok(conn)
}
/// Invokes the provided function with a [`duckdb::Connection`].
pub async fn conn<F, T>(&self, func: F) -> Result<T, Error>
where
F: FnOnce(&Connection) -> Result<T, duckdb::Error> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = oneshot::channel();
self.conn_tx.send(Command::Func(Box::new(move |conn| {
_ = tx.send(func(conn));
})))?;
Ok(rx.await??)
}
/// Invokes the provided function with a mutable [`duckdb::Connection`].
pub async fn conn_mut<F, T>(&self, func: F) -> Result<T, Error>
where
F: FnOnce(&mut Connection) -> Result<T, duckdb::Error> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = oneshot::channel();
self.conn_tx.send(Command::Func(Box::new(move |conn| {
_ = tx.send(func(conn));
})))?;
Ok(rx.await??)
}
/// Closes the underlying duckdb connection.
///
/// After this method returns, all calls to `self::conn()` or
/// `self::conn_mut()` will return an [`Error::Closed`] error.
pub async fn close(&self) -> Result<(), Error> {
let (tx, rx) = oneshot::channel();
let func = Box::new(|res| _ = tx.send(res));
if self.conn_tx.send(Command::Shutdown(func)).is_err() {
// If the worker thread has already shut down, return Ok here.
return Ok(());
}
// If receiving fails, the connection is already closed.
rx.await.unwrap_or(Ok(()))
}
/// Invokes the provided function with a [`duckdb::Connection`], blocking
/// the current thread until completion.
pub fn conn_blocking<F, T>(&self, func: F) -> Result<T, Error>
where
F: FnOnce(&Connection) -> Result<T, duckdb::Error> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = bounded(1);
self.conn_tx.send(Command::Func(Box::new(move |conn| {
_ = tx.send(func(conn));
})))?;
Ok(rx.recv()??)
}
/// Invokes the provided function with a mutable [`duckdb::Connection`],
/// blocking the current thread until completion.
pub fn conn_mut_blocking<F, T>(&self, func: F) -> Result<T, Error>
where
F: FnOnce(&mut Connection) -> Result<T, duckdb::Error> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = bounded(1);
self.conn_tx.send(Command::Func(Box::new(move |conn| {
_ = tx.send(func(conn));
})))?;
Ok(rx.recv()??)
}
/// Closes the underlying duckdb connection, blocking the current thread
/// until complete.
///
/// After this method returns, all calls to `self::conn_blocking()` or
/// `self::conn_mut_blocking()` will return an [`Error::Closed`] error.
pub fn close_blocking(&self) -> Result<(), Error> {
let (tx, rx) = bounded(1);
let func = Box::new(move |res| _ = tx.send(res));
if self.conn_tx.send(Command::Shutdown(func)).is_err() {
return Ok(());
}
// If receiving fails, the connection is already closed.
rx.recv().unwrap_or(Ok(()))
}
}