Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created January 13, 2020 21:40
Show Gist options
  • Save leocavalcante/187cf87c267de9ec6f6d3462f19b513b to your computer and use it in GitHub Desktop.
Save leocavalcante/187cf87c267de9ec6f6d3462f19b513b to your computer and use it in GitHub Desktop.
Rust match
#[macro_use]
extern crate mysql;
extern crate dotenv;
use std::error::Error;
use mysql::Row;
use std::env::var;
struct Lead {
id: u32,
source: String,
}
fn main() -> Result<(), Box<dyn Error>> {
dotenv::dotenv().ok();
let mut conn = mysql::Conn::new(std::env::var("MYSQL_URL")?)?;
let mut stmt = conn.prepare(r"select id, source from lead where email = :email and product_id = 312")?;
let mut rdr = csv::Reader::from_path("data.csv")?;
let mut wtr = csv::Writer::from_path("output.csv")?;
for result in rdr.records() {
let mut record = result?;
let email = record.get(8).unwrap();
let qr: Option<Row> = stmt.first_exec(params!{"email" => email})?;
let lead = qr.map(|row| {
let (id, source) = mysql::from_row(row);
Lead { id, source }
});
match lead {
Some(lead) => {
record.push_field(format!("{}/{}", var("LEAD_BASE_URL")?, lead.id).as_str());
record.push_field(&lead.source);
},
None => {
record.push_field("Not found");
record.push_field("N/A");
},
};
wtr.write_record(record.iter());
}
wtr.flush();
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment