Created
June 9, 2018 14:42
-
-
Save patshaughnessy/db735e90d58376fdd550b35838aa5339 to your computer and use it in GitHub Desktop.
Execute a simple SQL report using Rust and Diesel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate diesel; | |
use diesel::prelude::*; | |
table! { | |
users (id) { | |
id -> Int4, | |
first_name -> Nullable<Varchar>, | |
last_name -> Nullable<Varchar>, | |
} | |
} | |
#[derive(Queryable)] | |
pub struct User { | |
pub id: i32, | |
pub first_name: Option<String>, | |
pub last_name: Option<String>, | |
} | |
fn main() { | |
let database_url = "postgres://pat@localhost:5432/names"; | |
let connection = PgConnection::establish(&database_url).expect( | |
&format!("Error connecting to {}", database_url) | |
); | |
println!("Connected!"); | |
use users::dsl::*; | |
let results = users.load::<User>(&connection).expect( | |
"Error loading users" | |
); | |
let (mult, one): (Vec<User>, Vec<User>) = | |
results.into_iter().partition(|user| | |
if let Some(ref name) = user.last_name { | |
name.split(' ').collect::<Vec<&str>>().len() > 1 | |
} else { | |
false | |
} | |
); | |
println!("Found {} users with more than one last name.", mult.len()); | |
println!("Found {} users with one last name.", one.len()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you use the count method here?