Expand description
§Deadpool for PostgreSQL

Deadpool is a dead simple async pool for connections and objects of any type.
This crate implements a deadpool
manager for tokio-postgres
and also provides a statement cache by wrapping tokio_postgres::Client
and tokio_postgres::Transaction.
§Features
| Feature | Description | Extra dependencies | Default |
|---|---|---|---|
rt_tokio_1 | Enable support for tokio crate | deadpool/rt_tokio_1 | yes |
rt_async-std_1 | Enable support for async-std crate | deadpool/rt_async-std_1 | no |
serde | Enable support for serde crate | deadpool/serde, serde/derive | no |
Important: async-std support is currently limited to the
async-std specific timeout function. You still need to enable
the tokio1 feature of async-std in order to use this crate
with async-std.
§Example
use deadpool_postgres::{Config, Manager, ManagerConfig, Pool, RecyclingMethod, Runtime};
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(Some(Runtime::Tokio1), NoTls).unwrap();
for i in 1..10 {
let mut client = pool.get().await.unwrap();
let stmt = client.prepare_cached("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
PG__DBNAME=deadpooluse deadpool_postgres::{Manager, Pool, Runtime};
use dotenv::dotenv;
use tokio_postgres::NoTls;
#[derive(Debug, serde::Deserialize)]
struct Config {
pg: deadpool_postgres::Config
}
impl Config {
pub fn from_env() -> Result<Self, config::ConfigError> {
config::Config::builder()
.add_source(config::Environment::default().separator("__"))
.build()?
.try_deserialize()
}
}
#[tokio::main]
async fn main() {
dotenv().ok();
let mut cfg = Config::from_env().unwrap();
let pool = cfg.pg.create_pool(Some(Runtime::Tokio1), NoTls).unwrap();
for i in 1..10 {
let mut client = pool.get().await.unwrap();
let stmt = client.prepare_cached("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
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::builder(mgr).max_size(16).build().unwrap();
for i in 1..10 {
let mut client = pool.get().await.unwrap();
let stmt = client.prepare_cached("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 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().awaitright after creating the pool. -
Why are connections retrieved from the pool sometimes unuseable?
In
deadpool-postgres 0.5.5a new recycling method was implemented which is the default since0.8. With that recycling method the manager no longer performs a test query prior returning the connection but relies solely ontokio_postgres::Client::is_closedinstead. Under some rare circumstances (e.g. unreliable networks) this can lead totokio_postgresnot noticing a disconnect and reporting the connection as useable.The old and slightly slower recycling method can be enabled by setting
ManagerConfig::recycling_methodtoRecyclingMethod::Verifiedor when using theconfigcrate by settingPG__MANAGER__RECYCLING_METHOD=Verified. -
How can I enable features of the
tokio-postgrescrate?Make sure that you depend on the same version of
tokio-postgresasdeadpool-postgresdoes and enable the needed features in your ownCrate.tomlfile:[dependencies] deadpool-postgres = { version = "0.9" } tokio-postgres = { version = "0.7", features = ["with-uuid-0_8"] }Important: The version numbers of
deadpool-postgresandtokio-postgresdo not necessarily match. If they do it is just a coincidence that both crates have the same MAJOR and MINOR version number. -
How can I clear the statement cache?
You can call
pool.manager().statement_cache.clear()to clear all statement caches orpool.manager().statement_cache.remove()to remove a single statement from all caches.Important: The
ClientWrapperalso provides astatement_cachefield which hasclear()andremove()methods which only affect a single client.
§License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Re-exports§
pub use tokio_postgres;
Structs§
- Client
Wrapper - Wrapper around
tokio_postgres::Clientwith aStatementCache. - Config
- Configuration object.
- Manager
Managerfor creating and recycling PostgreSQL connections.- Manager
Config - Configuration object for a
Manager. - Metrics
- Statistics regarding an object returned by the pool
- Pool
Config Poolconfiguration.- Statement
Cache - Representation of a cache of
Statements. - Statement
Caches - Structure holding a reference to all
StatementCaches and providing access for clearing all caches and removing single statements from them. - Status
- The current pool status.
- Timeouts
- Timeouts when getting
Objects from aPool. - Transaction
- Wrapper around
tokio_postgres::Transactionwith aStatementCachefrom theClientobject it was created by. - Transaction
Builder - Wrapper around
tokio_postgres::TransactionBuilderwith aStatementCachefrom theClientobject it was created by.
Enums§
- Channel
Binding - Channel binding configuration.
- Config
Error - This error is returned if there is something wrong with the configuration
- Recycling
Method - Possible methods of how a connection is recycled.
- Runtime
- Enumeration for picking a runtime implementation.
- SslMode
- TLS configuration.
- Target
Session Attrs - Properties required of a session.
Type Aliases§
- Build
Error - Type alias for using
deadpool::managed::BuildErrorwithtokio_postgres. - Client
- Type alias for
Object - Create
Pool Error - Type alias for using
deadpool::managed::CreatePoolErrorwithtokio_postgres. - Hook
- Type alias for using
deadpool::managed::Hookwithtokio_postgres. - Hook
Error - Type alias for using
deadpool::managed::HookErrorwithtokio_postgres. - Hook
Error Cause - Type alias for using
deadpool::managed::HookErrorCausewithtokio_postgres. - Object
- Type alias for using
deadpool::managed::Objectwithtokio_postgres. - Pool
- Type alias for using
deadpool::managed::Poolwithtokio_postgres. - Pool
Builder - Type alias for using
deadpool::managed::PoolBuilderwithtokio_postgres. - Pool
Error - Type alias for using
deadpool::managed::PoolErrorwithtokio_postgres.