Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bb8 + postgresql example #889

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ serde_derive = "1.0"
handlebars = "4.0"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread", "io-util"] }
tokio-stream = { version = "0.1.1", features = ["net"] }
tokio-postgres = "0.7"
listenfd = "0.3"
bb8 = "0.7"
bb8-postgres = "0.7"

[features]
default = ["multipart", "websocket", "trace-log", "http2"]
Expand Down
49 changes: 49 additions & 0 deletions examples/postgres.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#![deny(warnings)]

use bb8::{Pool, RunError};
use bb8_postgres::PostgresConnectionManager;
use std::{convert::Infallible, str::FromStr};
use tokio_postgres::{config::Config, NoTls};
use warp::{reject::Reject, Filter, Rejection};

type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;

#[derive(Debug)]
struct ConnectionError(RunError<tokio_postgres::Error>);

impl Reject for ConnectionError {}

fn with_pool(
pool: ConnectionPool,
) -> impl Filter<Extract = (ConnectionPool,), Error = Infallible> + Clone {
warp::any().map(move || pool.clone())
}

async fn index_handler(pool: ConnectionPool) -> Result<String, Rejection> {
let connection = pool.get().await.map_err(|e| ConnectionError(e.into()))?;
let stmt = connection
.prepare("SELECT 1")
.await
.map_err(|e| ConnectionError(e.into()))?;
let row = connection
.query_one(&stmt, &[])
.await
.map_err(|e| ConnectionError(e.into()))?;
Ok(row.get::<usize, i32>(0).to_string())
}

#[tokio::main]
async fn main() {
// The simplest way to start the DB is using Docker:
// docker run --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
let config = Config::from_str("postgresql://postgres:postgres@localhost:5432").unwrap();
let manager = PostgresConnectionManager::new(config, NoTls);
let pool = match Pool::builder().build(manager).await {
Ok(pool) => pool,
Err(e) => panic!("Pool builder error: {:?}", e),
};
let routes = warp::any()
.and(with_pool(pool.clone()))
.and_then(index_handler);
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}