r2d2_duckdb/
lib.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
#![deny(warnings)]
//! # DuckDb support for the `r2d2` connection pool.
//!
//! Library crate: [r2d2-duckdb](https://crates.io/crates/r2d2-duckdb/)
//!
//! Integrated with: [r2d2](https://crates.io/crates/r2d2)
//!
//! ## Example
//!
//! ```rust,no_run
//! extern crate r2d2;
//! extern crate r2d2_duckdb;
//! extern crate duckdb;
//!
//! use std::thread;
//! use r2d2_duckdb::DuckDBConnectionManager;
//!
//! fn main() {
//!     let manager = DuckDBConnectionManager::file("file.db");
//!     let pool = r2d2::Pool::builder().build(manager).unwrap();
//!
//!     for i in 0..10i32 {
//!         let pool = pool.clone();
//!         thread::spawn(move || {
//!             let conn = pool.get().unwrap();
//!             let result = conn.execute("INSERT INTO foo (bar) VALUES (?)", duckdb::params![42]).unwrap();
//!         });
//!     }
//! }
//! ```
extern crate r2d2;
extern crate duckdb;

use duckdb::{params, Connection, Error};
use std::path::{Path, PathBuf};

enum ConnectionConfig {
    File(PathBuf),
    Memory,
}

/// An `r2d2::ManageConnection` for `ruDuckDB::Connection`s.
pub struct DuckDBConnectionManager(ConnectionConfig);

impl DuckDBConnectionManager {
    /// Creates a new `DuckDBConnectionManager` from file.
    ///
    pub fn file<P: AsRef<Path>>(path: P) -> Self {
        DuckDBConnectionManager(ConnectionConfig::File(path.as_ref().to_path_buf()))
    }

    pub fn memory() -> Self {
        DuckDBConnectionManager(ConnectionConfig::Memory)
    }
}

impl r2d2::ManageConnection for DuckDBConnectionManager {
    type Connection = Connection;
    type Error = duckdb::Error;

    fn connect(&self) -> Result<Connection, Error> {
        match self.0 {
            ConnectionConfig::File(ref path) => Connection::open(path),
            ConnectionConfig::Memory => Connection::open_in_memory(),
        }
    }

    fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
        let _ = conn.execute("", params![]);
        Ok(())
    }

    fn has_broken(&self, _: &mut Connection) -> bool {
        false
    }
}