r2d2_sqlite3/lib.rs
1#![deny(warnings)]
2//! # Sqlite support for the `r2d2` connection pool.
3//!
4//! Library crate: [r2d2-sqlite](https://crates.io/crates/r2d2-sqlite/)
5//!
6//! Integrated with: [r2d2](https://crates.io/crates/r2d2)
7//! and [rusqlite](https://crates.io/crates/rusqlite)
8//!
9//! ## Example
10//!
11//! ```rust,no_run
12//! extern crate r2d2;
13//! extern crate r2d2_sqlite3;
14//! extern crate sqlite3;
15//!
16//! use std::thread;
17//! use r2d2_sqlite3::SqliteConnectionManager;
18//!
19//! fn main() {
20//! let manager = SqliteConnectionManager::file("file.db");
21//! let pool = r2d2::Pool::builder().build(manager).unwrap();
22//!
23//! for i in 0..10i32 {
24//! let pool = pool.clone();
25//! thread::spawn(move || {
26//! let conn = pool.get().unwrap();
27//! let mut stmt = conn.prepare("INSERT INTO foo (bar) VALUES (?)").unwrap();
28//! stmt.bind(1, 42).unwrap();
29//! });
30//! }
31//! }
32//! ```
33extern crate r2d2;
34extern crate sqlite3;
35
36use sqlite3::{Connection, Error};
37use std::path::{Path, PathBuf};
38
39enum ConnectionConfig {
40 File(PathBuf),
41 Memory,
42}
43
44/// An `r2d2::ManageConnection` for `rusqlite::Connection`s.
45pub struct SqliteConnectionManager(ConnectionConfig);
46
47impl SqliteConnectionManager {
48 /// Creates a new `SqliteConnectionManager` from file.
49 ///
50 pub fn file<P: AsRef<Path>>(path: P) -> Self {
51 SqliteConnectionManager(ConnectionConfig::File(path.as_ref().to_path_buf()))
52 }
53
54 pub fn memory() -> Self {
55 SqliteConnectionManager(ConnectionConfig::Memory)
56 }
57}
58
59impl r2d2::ManageConnection for SqliteConnectionManager {
60 type Connection = Connection;
61 type Error = sqlite3::Error;
62
63 fn connect(&self) -> Result<Connection, Error> {
64 match self.0 {
65 ConnectionConfig::File(ref path) => Connection::open(path),
66 ConnectionConfig::Memory => Connection::open(":memory:"),
67 }
68 }
69
70 fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
71 conn.execute("").map_err(Into::into)
72 }
73
74 fn has_broken(&self, _: &mut Connection) -> bool {
75 false
76 }
77}