use crate::QueryResult;
use odbc_api::Cursor;
use odbc_api::ResultSetMetadata;
use std::error::Error;
pub struct Connection<'a> {
connection: odbc_api::Connection<'a>,
}
impl Connection<'_>{
pub fn execute_query(&self, query_string: &str) -> Result<QueryResult, Box<dyn Error>> {
match self.connection.execute(query_string, (), None) {
Ok(Some(mut cursor)) => {
let colnames: Vec<String> = cursor.column_names()?.collect::<Result<_, _>>()?;
let mut table: Vec<Vec<String>> = Vec::new();
while let Some(mut row) = cursor.next_row()? {
let mut row_data: Vec<String> = Vec::new();
for i in 1..colnames.len() + 1 {
let mut buf = Vec::new();
row.get_text(i as u16, &mut buf)?;
let val = String::from_utf8_lossy(&buf).to_string();
row_data.push(val);
}
table.push(row_data);
}
Ok(QueryResult::new(table, colnames))
}
Err(e) => Err(Box::new(e)),
Ok(None) => Ok(QueryResult::new(Vec::new(),Vec::new())),
}
}
pub(crate) fn new<'a>(connection: odbc_api::Connection<'a>)-> Connection::<'a> {
Connection{connection}
}
pub fn execute_queries(&self, query_strings: Vec<&str>) -> Result<Vec<QueryResult>, Box<dyn Error>> {
let mut results:Vec<QueryResult>= Vec::new();
for q_str in query_strings {
match self.execute_query(q_str) {
Ok(result) => {
results.push(result);
},
Err(e) => return Err(e),
}
}
return Ok(results);
}
}