Skip to content

Instantly share code, notes, and snippets.

@bsodmike
Created May 4, 2020 10:29
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 bsodmike/cc5708c9727e371d10437ccb5e505e49 to your computer and use it in GitHub Desktop.
Save bsodmike/cc5708c9727e371d10437ccb5e505e49 to your computer and use it in GitHub Desktop.
Fetching fields with Mysql crate in Rust
#[macro_use]
use crate::mysql::*;
use crate::mysql::prelude::*;
use crate::errors::Error;
#[derive(Debug)]
pub struct ConnectorMysql {
}
#[derive(Debug)]
pub struct ConnectorPostgres {
}
#[derive(Debug)]
struct Connection {
}
pub trait Fetch<ReturnType> {
fn call_db(&self) -> ReturnType;
}
#[derive(Debug)]
pub struct Data {
host: String,
user: String
}
impl Fetch<Vec<Data>> for ConnectorMysql
{
fn call_db(&self) -> Vec<Data> {
let url = "mysql://root:a@localhost:3306/";
let pool = Pool::new(url).unwrap();
let mut conn = pool.get_conn().unwrap();
let mut stmt = conn.prep(r#"select host, user from mysql.user"#).unwrap();
let result: Vec<Data> = conn.exec_iter(stmt, ()).map(|result| {
result.map(|x| x.unwrap()).map(|row| {
let (host, user) = mysql::from_row(row);
Data {
host,
user
}
}).collect()
}).unwrap();
result
}
}
impl Fetch<String> for ConnectorPostgres
{
fn call_db(&self) -> String {
panic!("Err: {:#?}", Error::NotImplementedError)
}
}
pub fn fetch<ConnectorType, ReturnType>(connector: &ConnectorType) -> ReturnType
where
ConnectorType: Fetch<ReturnType>
{
connector.call_db()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment