use rudb_common::{Error, Result, Value};
use crate::database::Shared;
use crate::prepared::Prepared;
use crate::result::QueryResult;
#[derive(Debug, Clone)]
pub struct Connection {
shared: Shared,
}
impl Connection {
pub(crate) fn new(shared: Shared) -> Self {
Self { shared }
}
pub fn query(&self, sql: &str) -> Result<QueryResult> {
self.shared.query(sql)
}
pub fn execute(&self, sql: &str) -> Result<QueryResult> {
self.shared.execute(sql)
}
pub fn plan(&self, sql: &str) -> Result<String> {
self.shared.plan(sql)
}
pub fn prepare(&self, sql: &str) -> Result<Prepared> {
Prepared::new(self.shared.clone(), sql)
}
pub fn value(&self, sql: &str) -> Result<Value> {
let result = self.query(sql)?;
single(&result)
}
}
pub(crate) fn single(result: &QueryResult) -> Result<Value> {
if result.len() != 1 || result.width() != 1 {
return Err(Error::invalid_input(format!(
"expected one row of one column, got {} rows of {} columns",
result.len(),
result.width()
)));
}
Ok(result.value_at(0, 0))
}