Skip to content

Instantly share code, notes, and snippets.

Created Nov 5, 2015
Embed
What would you like to do?
Shared via Rust Playground
extern crate r2d2;
extern crate r2d2_postgres;
extern crate postgres;
extern crate uuid;
extern crate rustc_serialize as serialize;
use std::default::Default;
use postgres::SslMode;
use r2d2_postgres::PostgresConnectionManager;
use uuid::Uuid;
use serialize::json::Json;
fn main() {
let config = r2d2::Config::default();
let manager = PostgresConnectionManager::new("postgres://user:pass@localhost:5432/db",
SslMode::None).unwrap();
let pool = r2d2::Pool::new(config, manager).unwrap();
let pool = pool.clone();
let conn = pool.get().unwrap();
// this table has 3 fields:
// id - Uuid type
// username - varchar type
// data - json type (yes, postgres > 9.3 has support for this...)
let stmt = conn.prepare("select id, username, data from my_table where username = $1").unwrap();
for row in stmt.query(&[&"johndoe"]).unwrap() {
let id : Uuid = row.get_opt("id").unwrap();
let username : String = row.get_opt("username").unwrap();
let data : Option<Json> = row.get_opt("data").unwrap();
let content;
match data {
Some(y) => { content = y.to_string() },
None => { content = "{}".to_string() }
}
println!("result: {}, {}, {}", id, username, content);
}
println!("");
println!("==================================================");
println!("");
// trying to do the same thing on a better and cleaner way
let stmt = conn.prepare("select id, username, data from my_table where username = $1").unwrap();
let rows = match stmt.query( &[&"johndoe"]) {
Ok(rows) => rows,
Err(err) => panic!("Error running query: {:?}", err)
};
struct Block {
id : Uuid,
username : String,
data : String
}
for row in &rows {
let block = Block {
id: match row.get_opt("id") {
Ok(id) => id,
Err(err) => panic!("Error getting id: {:?}", err)
},
username: match row.get_opt("username") {
Ok(name) => name,
Err(err) => panic!("Error getting username: {:}", err)
},
data: match row.get_opt("data") {
Ok(info) => { info },
Err(err) => { println!("Error: {:?}", err); "".to_string() }
}
};
println!("result: {}, {}, {:?}", block.id, block.username, block.data);
}
// this prints:
// result: 304a593d-e897-4843-8969-2e31cda2e58e, johndoe, {}
// result: 38229103-e8e9-4e2c-a77c-33e2aab58493, johndoe, {}
// result: 1dd48f87-b940-4c91-9f8b-4fe76c5e436a, johndoe, {}
// ==================================================
// result: 304a593d-e897-4843-8969-2e31cda2e58e, johndoe, ""
// Error: WrongType(Json)
// result: 38229103-e8e9-4e2c-a77c-33e2aab58493, johndoe, ""
// Error: WrongType(Json)
// result: 1dd48f87-b940-4c91-9f8b-4fe76c5e436a, johndoe, ""
// Error: WrongType(Json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment