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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
//! # Deadpool for PostgreSQL [![Latest Version](https://img.shields.io/crates/v/deadpool-postgres.svg)](https://crates.io/crates/deadpool-postgres) //! //! Deadpool is a dead simple async pool for connections and objects //! of any type. //! //! This crate implements a [`deadpool`](https://crates.io/crates/deadpool) //! manager for [`tokio-postgres`](https://crates.io/crates/tokio-postgres) //! and also provides a `statement` cache by wrapping `tokio_postgres::Client` //! and `tokio_postgres::Transaction`. //! //! ## Features //! //! | Feature | Description | Extra dependencies | Default | //! | ------- | ----------- | ------------------ | ------- | //! | `config` | Enable support for [config](https://crates.io/crates/config) crate | `config`, `serde/derive` | yes | //! //! ## Example //! //! ```rust,ignore //! use deadpool_postgres::{Config, Manager, ManagerConfig, Pool, RecyclingMethod }; //! use tokio_postgres::NoTls; //! //! #[tokio::main] //! async fn main() { //! let mut cfg = Config::new(); //! cfg.dbname = Some("deadpool".to_string()); //! cfg.manager = Some(ManagerConfig { recycling_method: RecyclingMethod::Fast }); //! let pool = cfg.create_pool(NoTls).unwrap(); //! for i in 1..10 { //! let mut client = pool.get().await.unwrap(); //! let stmt = client.prepare("SELECT 1 + $1").await.unwrap(); //! let rows = client.query(&stmt, &[&i]).await.unwrap(); //! let value: i32 = rows[0].get(0); //! assert_eq!(value, i + 1); //! } //! } //! ``` //! //! ## Example with `config` and `dotenv` crate //! //! ```env //! # .env //! PG__DBNAME=deadpool //! ``` //! //! ```rust //! use deadpool_postgres::{Manager, Pool}; //! use dotenv::dotenv; //! use serde::Deserialize; //! use tokio_postgres::NoTls; //! //! #[derive(Debug, Deserialize)] //! struct Config { //! pg: deadpool_postgres::Config //! } //! //! impl Config { //! pub fn from_env() -> Result<Self, ::config_crate::ConfigError> { //! let mut cfg = ::config_crate::Config::new(); //! cfg.merge(::config_crate::Environment::new().separator("__"))?; //! cfg.try_into() //! } //! } //! //! #[tokio::main] //! async fn main() { //! dotenv().ok(); //! let mut cfg = Config::from_env().unwrap(); //! let pool = cfg.pg.create_pool(NoTls).unwrap(); //! for i in 1..10 { //! let mut client = pool.get().await.unwrap(); //! let stmt = client.prepare("SELECT 1 + $1").await.unwrap(); //! let rows = client.query(&stmt, &[&i]).await.unwrap(); //! let value: i32 = rows[0].get(0); //! assert_eq!(value, i + 1); //! } //! } //! ``` //! //! **Note:** The code above uses the crate name `config_crate` because of the //! `config` feature and both features and dependencies share the same namespace. //! In your own code you will probably want to use `::config::ConfigError` and //! `::config::Config` instead. //! //! ## Example using an existing `tokio_postgres::Config` object //! //! ```rust,ignore //! use std::env; //! use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod}; //! use tokio_postgres::NoTls; //! //! #[tokio::main] //! async fn main() { //! let mut pg_config = tokio_postgres::Config::new(); //! pg_config.host_path("/run/postgresql"); //! pg_config.host_path("/tmp"); //! pg_config.user(env::var("USER").unwrap().as_str()); //! pg_config.dbname("deadpool"); //! let mgr_config = ManagerConfig { //! recycling_method: RecyclingMethod::Fast //! }; //! let mgr = Manager::from_config(pg_config, NoTls, mgr_config); //! let pool = Pool::new(mgr, 16); //! for i in 1..10 { //! let mut client = pool.get().await.unwrap(); //! let stmt = client.prepare("SELECT 1 + $1").await.unwrap(); //! let rows = client.query(&stmt, &[&i]).await.unwrap(); //! let value: i32 = rows[0].get(0); //! assert_eq!(value, i + 1); //! } //! } //! ``` //! //! ## FAQ //! //! - **The database is unreachable. Why does the pool creation not fail?** //! //! Deadpool has [identical startup and runtime behaviour](https://crates.io/crates/deadpool/#reasons-for-yet-another-connection-pool) //! and therefore the pool creation will never fail. //! //! If you want your application to crash on startup if no database //! connection can be established just call `pool.get().await` right after //! creating the pool. //! //! - **Why are connections retrieved from the pool sometimes unuseable?** //! //! In deadpool-postgres `0.5.5` a new recycling method was implemented which //! will become the default in `0.6`. With that recycling method the manager no //! longer performs a test query prior returning the connection but relies //! solely on `tokio_postgres::Client::is_closed` instead. Under some rare //! circumstances (e.g. unreliable networks) this can lead to `tokio_postgres` //! not noticing a disconnect and reporting the connection as useable. //! //! The old and slightly slower recycling method can be enabled by setting //! `ManagerConfig::recycling_method` to `RecyclingMethod::Verified` or when //! using the `config` crate by setting `PG.MANAGER.RECYCLING_METHOD=Verified`. //! //! - **How can I enable features of the `tokio-postgres` crate?** //! //! Make sure that you depend on the same version of `tokio-postgres` as //! `deadpool-postgres` does and enable the needed features in your own //! `Crate.toml` file: //! //! ```toml //! [dependencies] //! deadpool-postgres = { version = "0.6" } //! tokio-postgres = { version = "0.6", features = ["with-uuid-0_8"] } //! ``` //! //! **Important:** The version numbers of `deadpool-postgres` and //! `tokio-postgres` do not necessarily match. It is just a coincidence //! that both crates have the same MAJOR and MINOR version number at the //! time of this writing. //! //! ## License //! //! Licensed under either of //! //! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) //! - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) //! //! at your option. #![warn(missing_docs, unreachable_pub)] use std::borrow::Cow; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicUsize, Ordering}; use async_trait::async_trait; use futures::FutureExt; use log::{info, warn}; use tokio::spawn; use tokio::sync::RwLock; use tokio_postgres::{ tls::MakeTlsConnect, tls::TlsConnect, types::Type, Client as PgClient, Config as PgConfig, Error, IsolationLevel, Socket, Statement, Transaction as PgTransaction, TransactionBuilder as PgTransactionBuilder, }; pub mod config; pub use crate::config::{Config, ManagerConfig, RecyclingMethod}; /// Re-export deadpool::managed::PoolConfig use deadpool::managed::PoolConfig; /// A type alias for using `deadpool::Pool` with `tokio_postgres` pub type Pool = deadpool::managed::Pool<ClientWrapper, tokio_postgres::Error>; /// A type alias for using `deadpool::PoolError` with `tokio_postgres` pub type PoolError = deadpool::managed::PoolError<tokio_postgres::Error>; /// A type alias for using `deadpool::Object` with `tokio_postgres` pub type Client = deadpool::managed::Object<ClientWrapper, tokio_postgres::Error>; type RecycleResult = deadpool::managed::RecycleResult<Error>; type RecycleError = deadpool::managed::RecycleError<Error>; /// Re-export tokio_postgres crate pub use tokio_postgres; /// The manager for creating and recyling postgresql connections pub struct Manager<T: MakeTlsConnect<Socket>> { config: ManagerConfig, pg_config: PgConfig, tls: T, } impl<T: MakeTlsConnect<Socket>> Manager<T> { /// Create manager using a `tokio_postgres::Config` and a `TlsConnector`. pub fn new(pg_config: tokio_postgres::Config, tls: T) -> Manager<T> { Manager { config: ManagerConfig::default(), pg_config, tls, } } /// Create manager using a `tokio_postgres::Config` and a `TlsConnector` /// and also pub fn from_config( pg_config: tokio_postgres::Config, tls: T, config: ManagerConfig, ) -> Manager<T> { Manager { config, pg_config, tls, } } } #[async_trait] impl<T> deadpool::managed::Manager<ClientWrapper, Error> for Manager<T> where T: MakeTlsConnect<Socket> + Clone + Sync + Send + 'static, T::Stream: Sync + Send, T::TlsConnect: Sync + Send, <T::TlsConnect as TlsConnect<Socket>>::Future: Send, { async fn create(&self) -> Result<ClientWrapper, Error> { let (client, connection) = self.pg_config.connect(self.tls.clone()).await?; let connection = connection.map(|r| { if let Err(e) = r { warn!(target: "deadpool.postgres", "Connection error: {}", e); } }); spawn(connection); Ok(ClientWrapper::new(client)) } async fn recycle(&self, client: &mut ClientWrapper) -> RecycleResult { if client.is_closed() { info!(target: "deadpool.postgres", "Connection could not be recycled: Connection closed"); return Err(RecycleError::Message("Connection closed".to_string())); } match self.config.recycling_method.query() { Some(sql) => match client.simple_query(sql).await { Ok(_) => Ok(()), Err(e) => { info!(target: "deadpool.postgres", "Connection could not be recycled: {}", e); Err(e.into()) } }, None => Ok(()), } } } /// This structure holds the cached statements and provides access to /// functions for retrieving the current size and clearing the cache. pub struct StatementCache { map: RwLock<HashMap<StatementCacheKey<'static>, Statement>>, size: AtomicUsize, } // Allows us to use owned keys in the `HashMap`, but still be able // to call `get` with borrowed keys instead of allocating them each time. #[derive(Hash, Eq, PartialEq)] struct StatementCacheKey<'a> { query: Cow<'a, str>, types: Cow<'a, [Type]>, } impl StatementCache { fn new() -> StatementCache { StatementCache { map: RwLock::new(HashMap::new()), size: AtomicUsize::new(0), } } /// Retrieve current size of the cache pub fn size(&self) -> usize { self.size.load(Ordering::Relaxed) } /// Clear cache pub async fn clear(&self) { let mut map = self.map.write().await; map.clear(); self.size.store(0, Ordering::Relaxed); } /// Remove statement from cache pub async fn remove(&self, query: &str, types: &[Type]) -> Option<Statement> { let key = StatementCacheKey { query: Cow::Owned(query.to_owned()), types: Cow::Owned(types.to_owned()), }; let mut map = self.map.write().await; let removed = map.remove(&key).map(|stmt| stmt.to_owned()); if removed.is_some() { self.size.fetch_sub(1, Ordering::Relaxed); } removed } /// Get statement from cache async fn get<'a>(&self, query: &str, types: &[Type]) -> Option<Statement> { let key = StatementCacheKey { query: Cow::Borrowed(query), types: Cow::Borrowed(types), }; self.map.read().await.get(&key).map(|stmt| stmt.to_owned()) } /// Insert statement into cache async fn insert(&self, query: &str, types: &[Type], stmt: Statement) { let key = StatementCacheKey { query: Cow::Owned(query.to_owned()), types: Cow::Owned(types.to_owned()), }; let mut map = self.map.write().await; if map.insert(key, stmt).is_none() { self.size.fetch_add(1, Ordering::Relaxed); } } } /// A wrapper for `tokio_postgres::Client` which includes a statement cache. pub struct ClientWrapper { client: PgClient, /// The statement cache pub statement_cache: StatementCache, } impl ClientWrapper { /// Create new wrapper instance using an existing `tokio_postgres::Client` pub fn new(client: PgClient) -> Self { Self { client, statement_cache: StatementCache::new(), } } /// Creates a new prepared statement using the statement cache if possible. /// /// See [`tokio_postgres::Client::prepare`](#method.prepare-1) pub async fn prepare(&self, query: &str) -> Result<Statement, Error> { self.prepare_typed(query, &[]).await } /// Creates a new prepared statement using the statement cache if possible. /// /// See [`tokio_postgres::Client::prepare_typed`](#method.prepare_typed-1) pub async fn prepare_typed(&self, query: &str, types: &[Type]) -> Result<Statement, Error> { match self.statement_cache.get(query, types).await { Some(statement) => Ok(statement), None => { let stmt = self.client.prepare_typed(query, types).await?; self.statement_cache .insert(query, types, stmt.clone()) .await; Ok(stmt) } } } /// Begins a new database transaction which supports the statement cache. /// /// See [`tokio_postgres::Client::transaction`](#method.transaction-1) pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> { Ok(Transaction { txn: PgClient::transaction(&mut self.client).await?, statement_cache: &mut self.statement_cache, }) } /// Returns a builder for a transaction with custom settings. /// /// Unlike the `transaction` method, the builder can be used to control the /// transaction's isolation level and other attributes. /// /// See [`tokio_postgres::Client::transaction_builder`](#method.transaction_builder-1) pub fn build_transaction(&mut self) -> TransactionBuilder { TransactionBuilder { builder: self.client.build_transaction(), statement_cache: &mut self.statement_cache, } } } impl Deref for ClientWrapper { type Target = PgClient; fn deref(&self) -> &PgClient { &self.client } } impl DerefMut for ClientWrapper { fn deref_mut(&mut self) -> &mut PgClient { &mut self.client } } /// A wrapper for `tokio_postgres::Transaction` which uses the statement cache /// from the client object it was created by. pub struct Transaction<'a> { txn: PgTransaction<'a>, /// The statement cache pub statement_cache: &'a mut StatementCache, } impl<'a> Transaction<'a> { /// Creates a new prepared statement using the statement cache if possible. /// /// See [`tokio_postgres::Client::prepare`](#method.prepare_typed-1) pub async fn prepare(&self, query: &str) -> Result<Statement, Error> { self.prepare_typed(query, &[]).await } /// Creates a new prepared statement using the statement cache if possible. /// /// See [`tokio_postgres::Transaction::prepare_typed`](#method.prepare_typed-1) pub async fn prepare_typed(&self, query: &str, types: &[Type]) -> Result<Statement, Error> { match self.statement_cache.get(query, types).await { Some(statement) => Ok(statement), None => { let stmt = self.txn.prepare_typed(query, types).await?; self.statement_cache .insert(query, types, stmt.clone()) .await; Ok(stmt) } } } /// Like `tokio_postgres::Transaction::commit` pub async fn commit(self) -> Result<(), Error> { self.txn.commit().await } /// Like `tokio_postgres::Transaction::rollback` pub async fn rollback(self) -> Result<(), Error> { self.txn.rollback().await } /// Like `tokio_postgres::Transaction::transaction` pub async fn transaction<'b>(&'b mut self) -> Result<Transaction<'b>, Error> { Ok(Transaction { txn: PgTransaction::transaction(&mut self.txn).await?, statement_cache: &mut self.statement_cache, }) } } impl<'a> Deref for Transaction<'a> { type Target = PgTransaction<'a>; fn deref(&self) -> &PgTransaction<'a> { &self.txn } } impl<'a> DerefMut for Transaction<'a> { fn deref_mut(&mut self) -> &mut PgTransaction<'a> { &mut self.txn } } /// A wrapper for `tokio_postgres::TransactionBuilder` which uses the /// statement cache from the client object it was created by. pub struct TransactionBuilder<'a> { builder: PgTransactionBuilder<'a>, statement_cache: &'a mut StatementCache, } impl<'a> TransactionBuilder<'a> { /// Sets the isolation level of the transaction. /// /// Like `tokio_postgres::TransactionBuilder::isolation_level` pub fn isolation_level(self, isolation_level: IsolationLevel) -> Self { Self { builder: self.builder.isolation_level(isolation_level), statement_cache: self.statement_cache, } } /// Sets the access mode of the transaction. /// /// Like `tokio_postgres::TransactionBuilder::read_only` pub fn read_only(self, read_only: bool) -> Self { Self { builder: self.builder.read_only(read_only), statement_cache: self.statement_cache, } } /// Sets the deferrability of the transaction. /// /// If the transaction is also serializable and read only, creation /// of the transaction may block, but when it completes the transaction /// is able to run with less overhead and a guarantee that it will not /// be aborted due to serialization failure. /// /// Like `tokio_postgres::TransactionBuilder::deferrable` pub fn deferrable(self, deferrable: bool) -> Self { Self { builder: self.builder.deferrable(deferrable), statement_cache: self.statement_cache, } } /// Begins the transaction. /// /// The transaction will roll back by default - use the commit method /// to commit it. /// /// Like `tokio_postgres::TransactionBuilder::start` pub async fn start(self) -> Result<Transaction<'a>, Error> { Ok(Transaction { txn: self.builder.start().await?, statement_cache: self.statement_cache, }) } } impl<'a> Deref for TransactionBuilder<'a> { type Target = PgTransactionBuilder<'a>; fn deref(&self) -> &Self::Target { &self.builder } } impl<'a> DerefMut for TransactionBuilder<'a> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.builder } }