dhb_heroku_postgres_client/
lib.rs

1//! # dhb-heroku-postgres-client
2//! Given a DATABASE_URL, it should be dead simple to connect to a Heroku postgres database.
3//! This crate makes it dead simple:
4//! You pass a DATABASE_URL to the postgres_client function and get a working client back.
5//! 
6//! The reason I found the work to create this crate necessary is that connecting to Heroku has 2 quirks.
7//! 1. On the one hand, it requires that we have a secure connection.
8//! 2. On the other hand, it uses self-verified certificates.  So we have to enable Ssl, but turn off verification.  
9
10// postgres connection
11use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
12pub use postgres::Client;
13use postgres_openssl::MakeTlsConnector;
14
15pub use postgres;
16
17/// # Example:
18/// ```rust,no_run
19/// use dhb_heroku_postgres_client:postgres_client;
20///
21/// let database_url = "postgres://username:password@host:port/db_name";
22/// let mut client = postgres_client(&database_url);
23/// ```
24/// # Panics
25/// This will panic if it can't connect.  
26/// That could be because your database_url is wrong, because your database is down, because your internet connection is failing, etc.
27pub fn postgres_client(database_url: &str) -> Client {
28    // Create Ssl postgres connector without verification as required to connect to Heroku.
29    let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
30    builder.set_verify(SslVerifyMode::NONE);
31    let connector = MakeTlsConnector::new(builder.build());
32
33    // Create client with Heroku DATABASE_URL
34    Client::connect(
35        database_url,
36        connector,
37    ).unwrap()
38}
39
40pub fn postgres_smoke_test(client: &mut Client) {
41    // 1. Create table. 
42    client.simple_query("
43        CREATE TABLE IF NOT EXISTS person_nonconflicting (
44            id      SERIAL PRIMARY KEY,
45            name    TEXT NOT NULL,
46            data    BYTEA
47        )
48    ").unwrap();
49
50    // 2. Save a row.
51    let name = "Ferris";
52    let data = None::<&[u8]>;
53    client.execute(
54        "INSERT INTO person_nonconflicting (name, data) VALUES ($1, $2)",
55        &[&name, &data],
56    ).unwrap();
57
58    // 3. Retrieve a row and verify by printing.
59    for row in client.query("SELECT id, name, data FROM person_nonconflicting", &[]).unwrap() {
60        let id: i32 = row.get(0);
61        let name: &str = row.get(1);
62        let data: Option<&[u8]> = row.get(2);
63
64        println!("found person_nonconflicting: {} {} {:?}", id, name, data);
65    }
66
67    // 4. Clean up your mess by dropping the table.
68    client.simple_query("DROP TABLE person_nonconflicting").unwrap();
69}