use rudb_common::{Cancel, Error, Result, Value};
use crate::database::Shared;
use crate::prepared::Prepared;
use crate::result::QueryResult;
#[derive(Debug, Clone)]
pub struct Connection {
shared: Shared,
cancel: Cancel,
}
impl Connection {
pub(crate) fn new(shared: Shared) -> Self {
Self { shared, cancel: Cancel::new() }
}
pub fn interrupt(&self) {
self.cancel.cancel();
}
fn token(&self) -> Cancel {
self.cancel.restart(self.shared.timeout())
}
pub fn query(&self, sql: &str) -> Result<QueryResult> {
self.shared.query(sql, &self.token())
}
pub fn execute(&self, sql: &str) -> Result<QueryResult> {
self.shared.execute(sql, &self.token())
}
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))
}