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
//! # dhb-heroku-postgres-client
//! Given a DATABASE_URL, it should be dead simple to connect to a Heroku postgres database.
//! This crate makes it dead simple:
//! You pass a DATABASE_URL to the postgres_client function and get a working client back.
//! 
//! The reason I found the work to create this crate necessary is that connecting to Heroku has 2 quirks.
//! 1. On the one hand, it requires that we have a secure connection.
//! 2. On the other hand, it uses self-verified certificates.  So we have to enable Ssl, but turn off verification.  

// postgres connection
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
pub use postgres::Client;
use postgres_openssl::MakeTlsConnector;

pub use postgres;

/// # Example:
/// ```rust,no_run
/// use dhb_heroku_postgres_client:postgres_client;
///
/// let database_url = "postgres://username:password@host:port/db_name";
/// let mut client = postgres_client(&database_url);
/// ```
/// # Panics
/// This will panic if it can't connect.  
/// That could be because your database_url is wrong, because your database is down, because your internet connection is failing, etc.
pub fn postgres_client(database_url: &str) -> Client {
    // Create Ssl postgres connector without verification as required to connect to Heroku.
    let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
    builder.set_verify(SslVerifyMode::NONE);
    let connector = MakeTlsConnector::new(builder.build());

    // Create client with Heroku DATABASE_URL
    Client::connect(
        database_url,
        connector,
    ).unwrap()
}

pub fn postgres_smoke_test(client: &mut Client) {
    // 1. Create table. 
    client.simple_query("
        CREATE TABLE IF NOT EXISTS person_nonconflicting (
            id      SERIAL PRIMARY KEY,
            name    TEXT NOT NULL,
            data    BYTEA
        )
    ").unwrap();

    // 2. Save a row.
    let name = "Ferris";
    let data = None::<&[u8]>;
    client.execute(
        "INSERT INTO person_nonconflicting (name, data) VALUES ($1, $2)",
        &[&name, &data],
    ).unwrap();

    // 3. Retrieve a row and verify by printing.
    for row in client.query("SELECT id, name, data FROM person_nonconflicting", &[]).unwrap() {
        let id: i32 = row.get(0);
        let name: &str = row.get(1);
        let data: Option<&[u8]> = row.get(2);

        println!("found person_nonconflicting: {} {} {:?}", id, name, data);
    }

    // 4. Clean up your mess by dropping the table.
    client.simple_query("DROP TABLE person_nonconflicting").unwrap();
}