use std::sync::Arc;
use datafusion::config::ConfigOptions;
use parking_lot::RwLock;
use pyo3::prelude::*;
use pyo3::types::*;
use crate::common::data_type::PyScalarValue;
use crate::errors::PyDataFusionResult;
#[pyclass(
from_py_object,
name = "Config",
module = "datafusion",
subclass,
frozen
)]
#[derive(Clone)]
pub(crate) struct PyConfig {
config: Arc<RwLock<ConfigOptions>>,
}
#[pymethods]
impl PyConfig {
#[new]
fn py_new() -> Self {
Self {
config: Arc::new(RwLock::new(ConfigOptions::new())),
}
}
#[staticmethod]
pub fn from_env() -> PyDataFusionResult<Self> {
Ok(Self {
config: Arc::new(RwLock::new(ConfigOptions::from_env()?)),
})
}
pub fn get<'py>(&self, key: &str, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let value: Option<Option<String>> = {
let options = self.config.read();
options
.entries()
.into_iter()
.find_map(|entry| (entry.key == key).then_some(entry.value.clone()))
};
match value {
Some(value) => Ok(value.into_pyobject(py)?),
None => Ok(None::<String>.into_pyobject(py)?),
}
}
pub fn set(&self, key: &str, value: Py<PyAny>, py: Python) -> PyDataFusionResult<()> {
let scalar_value: PyScalarValue = value.extract(py)?;
let mut options = self.config.write();
options.set(key, scalar_value.0.to_string().as_str())?;
Ok(())
}
pub fn get_all(&self, py: Python) -> PyResult<Py<PyAny>> {
let entries: Vec<(String, Option<String>)> = {
let options = self.config.read();
options
.entries()
.into_iter()
.map(|entry| (entry.key.clone(), entry.value.clone()))
.collect()
};
let dict = PyDict::new(py);
for (key, value) in entries {
dict.set_item(key, value.into_pyobject(py)?)?;
}
Ok(dict.into())
}
fn __repr__(&self, py: Python) -> PyResult<String> {
match self.get_all(py) {
Ok(result) => Ok(format!("Config({result})")),
Err(err) => Ok(format!("Error: {:?}", err.to_string())),
}
}
}