Skip to content

Instantly share code, notes, and snippets.

@holyjak
Last active February 16, 2021 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holyjak/742ada208fb16cd49295d5bc28bc7853 to your computer and use it in GitHub Desktop.
Save holyjak/742ada208fb16cd49295d5bc28bc7853 to your computer and use it in GitHub Desktop.
Problem with factoring out common code in Rust
// Read from DB, write data to CSV
extern crate csv;
extern crate oracle;
use std::error::Error;
use std::env;
use oracle::Connection;
use oracle::sql_type::FromSql;
use oracle::row
use serde::ser::{ Serialize };
// FIXME: T should be a tuple of items implementing `FromSql + Serialize` due to `conn.query_as::<T>`
// SOLUTION: `fn sql_to_csv<T: RowValue + Serialize>` + `use oracle::RowValue;`
fn sql_to_csv<T: FromSql + Serialize>(psw: &str, sql: &str, colnames: &[&str], filename: &str) -> Result<(), Box<dyn Error>> {
let conn = Connection::connect("admin", psw, "//localhost:1541/MYDB")?;
let rows = conn.query_as::<T>(sql, &[])?;
let mut wtr = csv::Writer::from_path(filename)?;
wtr.write_record(colnames)?;
for row_result in rows {
wtr.serialize(row_result?)?;
}
wtr.flush()?;
println!("Written {}", filename);
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
println!("Hello, world!");
let psw = env::var("DB_PSW").expect("Env var DB_PSW is required");
// Fails with "the trait `FromSql` is not implemented for `(std::string::String,)`"
sql_to_csv::<(String,)>(
psw.as_ref(),
"select ORGANIZATION_NUMBER from organization",
&["ORGANIZATION_NUMBER"],
"organization.csv"
)?;
// Fails with "the trait `FromSql` is not implemented for `(std::string::String,std::string::String,std::string::String)`"
sql_to_csv::<(String, String, String)>(
psw.as_ref(),
"select SUBSCRIBER_ID, PROFILE_ID, ORGANIZATION_NUMBER \
from SUBSCRIBER",
&["SUBSCRIBER_ID", "PROFILE_ID", "ORGANIZATION_NUMBER"],
"subscriber.csv"
)?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment