use std::path::Path;
use crate::admin::QueryAnalysis;
use crate::connection::Connection;
use crate::format::OutputFormat;
use super::engine::{Engine, EngineStartOptions};
use super::errors::{engine_err, err, Category, Result};
use super::types::BACKUP_FORMAT_BASELINE;
const SYNCHRONOUS_SETTINGS: [&str; 4] = [
"--async_insert=0",
"--wait_for_async_insert=1",
"--mutations_sync=2",
"--alter_sync=2",
];
#[derive(Debug, Default)]
pub struct ChdbEngine {
extra_args: Vec<String>,
connection: Option<Connection>,
}
impl ChdbEngine {
pub fn new() -> Self {
Self::default()
}
pub fn with_args(args: impl IntoIterator<Item = String>) -> Self {
Self {
extra_args: args.into_iter().collect(),
connection: None,
}
}
fn borrow(&self) -> Result<&Connection> {
self.connection
.as_ref()
.ok_or_else(|| err(Category::Engine, "durable: the engine is not started"))
}
}
fn quote_identifier(name: &str) -> String {
format!("`{}`", name.replace('\\', "\\\\").replace('`', "\\`"))
}
impl Engine for ChdbEngine {
fn version(&mut self) -> Result<String> {
crate::version::engine_version()
.map(str::to_string)
.map_err(|e| engine_err(e, "durable: cannot read the engine version"))
}
fn backup_format(&mut self) -> Result<u64> {
Ok(BACKUP_FORMAT_BASELINE)
}
fn start(&mut self, options: EngineStartOptions) -> Result<()> {
if self.connection.is_some() {
return Err(err(
Category::Engine,
"durable: the engine is already started",
));
}
let data = options
.data_path
.to_str()
.ok_or_else(|| err(Category::Engine, "durable: the scratch path is not UTF-8"))?;
let backups = options
.backups_allowed_path
.to_str()
.ok_or_else(|| err(Category::Engine, "durable: the archive path is not UTF-8"))?;
let owned: Vec<String> = [
format!("--path={data}"),
format!("--backups.allowed_path={backups}"),
]
.into_iter()
.chain(SYNCHRONOUS_SETTINGS.iter().map(|s| s.to_string()))
.chain(self.extra_args.iter().cloned())
.collect();
let args: Vec<&str> = owned.iter().map(String::as_str).collect();
self.connection = Some(Connection::open(&args).map_err(|e| {
engine_err(e, format!("durable: cannot open an engine on {data}"))
})?);
Ok(())
}
fn create_database(&mut self, database: &str) -> Result<()> {
let sql = format!(
"CREATE DATABASE IF NOT EXISTS {}",
quote_identifier(database)
);
self.run(&sql)
}
fn use_database(&mut self, database: &str) -> Result<()> {
let sql = format!("USE {}", quote_identifier(database));
self.run(&sql)
}
fn analyze(&mut self, sql: &str, target_database: &str) -> Result<QueryAnalysis> {
self.borrow()?
.classify_query(sql, Some(target_database))
.map_err(|e| engine_err(e, "durable: the engine could not analyse the statement"))
}
fn query(&mut self, sql: &str, format: OutputFormat) -> Result<Vec<u8>> {
let result = self
.borrow()?
.query(sql, format)
.map_err(|e| engine_err(e, "durable: the engine refused a read"))?;
Ok(result.data_ref().to_vec())
}
fn run(&mut self, sql: &str) -> Result<()> {
self.borrow()?
.query(sql, OutputFormat::CSV)
.map(|_| ())
.map_err(|e| engine_err(e, "durable: the engine refused a statement"))
}
fn backup_database(&mut self, database: &str, file_path: &Path) -> Result<()> {
self.borrow()?
.backup_database(database, file_path)
.map_err(|e| engine_err(e, format!("durable: backing up {database:?} failed")))
}
fn restore_database(&mut self, database: &str, file_path: &Path) -> Result<()> {
self.borrow()?
.restore_database(database, file_path)
.map_err(|e| engine_err(e, format!("durable: restoring {database:?} failed")))
}
fn close(&mut self) -> Result<()> {
drop(self.connection.take());
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn an_identifier_is_quoted_rather_than_interpolated() {
assert_eq!(quote_identifier("mem"), "`mem`");
assert_eq!(quote_identifier("my-db"), "`my-db`");
assert_eq!(quote_identifier("we`ird"), "`we\\`ird`");
assert_eq!(quote_identifier("back\\slash"), "`back\\\\slash`");
}
#[test]
fn an_engine_that_never_started_says_so_rather_than_panicking() {
let mut engine = ChdbEngine::new();
let error = engine.run("SELECT 1").expect_err("no connection yet");
assert_eq!(error.category(), Category::Engine);
assert!(
engine.close().is_ok(),
"closing an unstarted engine is fine"
);
}
}