use crate::physical_plan::PyExecutionPlan;
use crate::sql::logical::PyLogicalPlan;
use crate::utils::wait_for_future;
use crate::{errors::DataFusionError, expr::PyExpr};
use datafusion::arrow::datatypes::Schema;
use datafusion::arrow::pyarrow::{PyArrowType, ToPyArrow};
use datafusion::arrow::util::pretty;
use datafusion::dataframe::{DataFrame, DataFrameWriteOptions};
use datafusion::parquet::basic::{BrotliLevel, Compression, GzipLevel, ZstdLevel};
use datafusion::parquet::file::properties::WriterProperties;
use datafusion::prelude::*;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyTuple;
use std::sync::Arc;
#[pyclass(name = "DataFrame", module = "datafusion", subclass)]
#[derive(Clone)]
pub(crate) struct PyDataFrame {
df: Arc<DataFrame>,
}
impl PyDataFrame {
pub fn new(df: DataFrame) -> Self {
Self { df: Arc::new(df) }
}
}
#[pymethods]
impl PyDataFrame {
fn __getitem__(&self, key: PyObject) -> PyResult<Self> {
Python::with_gil(|py| {
if let Ok(key) = key.extract::<&str>(py) {
self.select_columns(vec![key])
} else if let Ok(tuple) = key.extract::<&PyTuple>(py) {
let keys = tuple
.iter()
.map(|item| item.extract::<&str>())
.collect::<PyResult<Vec<&str>>>()?;
self.select_columns(keys)
} else if let Ok(keys) = key.extract::<Vec<&str>>(py) {
self.select_columns(keys)
} else {
let message = "DataFrame can only be indexed by string index or indices";
Err(PyTypeError::new_err(message))
}
})
}
fn __repr__(&self, py: Python) -> PyResult<String> {
let df = self.df.as_ref().clone().limit(0, Some(10))?;
let batches = wait_for_future(py, df.collect())?;
let batches_as_string = pretty::pretty_format_batches(&batches);
match batches_as_string {
Ok(batch) => Ok(format!("DataFrame()\n{batch}")),
Err(err) => Ok(format!("Error: {:?}", err.to_string())),
}
}
fn describe(&self, py: Python) -> PyResult<Self> {
let df = self.df.as_ref().clone();
let stat_df = wait_for_future(py, df.describe())?;
Ok(Self::new(stat_df))
}
fn schema(&self) -> PyArrowType<Schema> {
PyArrowType(self.df.schema().into())
}
#[pyo3(signature = (*args))]
fn select_columns(&self, args: Vec<&str>) -> PyResult<Self> {
let df = self.df.as_ref().clone().select_columns(&args)?;
Ok(Self::new(df))
}
#[pyo3(signature = (*args))]
fn select(&self, args: Vec<PyExpr>) -> PyResult<Self> {
let expr = args.into_iter().map(|e| e.into()).collect();
let df = self.df.as_ref().clone().select(expr)?;
Ok(Self::new(df))
}
fn filter(&self, predicate: PyExpr) -> PyResult<Self> {
let df = self.df.as_ref().clone().filter(predicate.into())?;
Ok(Self::new(df))
}
fn with_column(&self, name: &str, expr: PyExpr) -> PyResult<Self> {
let df = self.df.as_ref().clone().with_column(name, expr.into())?;
Ok(Self::new(df))
}
fn with_column_renamed(&self, old_name: &str, new_name: &str) -> PyResult<Self> {
let df = self
.df
.as_ref()
.clone()
.with_column_renamed(old_name, new_name)?;
Ok(Self::new(df))
}
fn aggregate(&self, group_by: Vec<PyExpr>, aggs: Vec<PyExpr>) -> PyResult<Self> {
let group_by = group_by.into_iter().map(|e| e.into()).collect();
let aggs = aggs.into_iter().map(|e| e.into()).collect();
let df = self.df.as_ref().clone().aggregate(group_by, aggs)?;
Ok(Self::new(df))
}
#[pyo3(signature = (*exprs))]
fn sort(&self, exprs: Vec<PyExpr>) -> PyResult<Self> {
let exprs = exprs.into_iter().map(|e| e.into()).collect();
let df = self.df.as_ref().clone().sort(exprs)?;
Ok(Self::new(df))
}
#[pyo3(signature = (count, offset=0))]
fn limit(&self, count: usize, offset: usize) -> PyResult<Self> {
let df = self.df.as_ref().clone().limit(offset, Some(count))?;
Ok(Self::new(df))
}
fn collect(&self, py: Python) -> PyResult<Vec<PyObject>> {
let batches = wait_for_future(py, self.df.as_ref().clone().collect())?;
batches.into_iter().map(|rb| rb.to_pyarrow(py)).collect()
}
fn cache(&self, py: Python) -> PyResult<Self> {
let df = wait_for_future(py, self.df.as_ref().clone().cache())?;
Ok(Self::new(df))
}
fn collect_partitioned(&self, py: Python) -> PyResult<Vec<Vec<PyObject>>> {
let batches = wait_for_future(py, self.df.as_ref().clone().collect_partitioned())?;
batches
.into_iter()
.map(|rbs| rbs.into_iter().map(|rb| rb.to_pyarrow(py)).collect())
.collect()
}
#[pyo3(signature = (num=20))]
fn show(&self, py: Python, num: usize) -> PyResult<()> {
let df = self.df.as_ref().clone().limit(0, Some(num))?;
print_dataframe(py, df)
}
fn distinct(&self) -> PyResult<Self> {
let df = self.df.as_ref().clone().distinct()?;
Ok(Self::new(df))
}
fn join(
&self,
right: PyDataFrame,
join_keys: (Vec<&str>, Vec<&str>),
how: &str,
) -> PyResult<Self> {
let join_type = match how {
"inner" => JoinType::Inner,
"left" => JoinType::Left,
"right" => JoinType::Right,
"full" => JoinType::Full,
"semi" => JoinType::LeftSemi,
"anti" => JoinType::LeftAnti,
how => {
return Err(DataFusionError::Common(format!(
"The join type {how} does not exist or is not implemented"
))
.into());
}
};
let df = self.df.as_ref().clone().join(
right.df.as_ref().clone(),
join_type,
&join_keys.0,
&join_keys.1,
None,
)?;
Ok(Self::new(df))
}
#[pyo3(signature = (verbose=false, analyze=false))]
fn explain(&self, py: Python, verbose: bool, analyze: bool) -> PyResult<()> {
let df = self.df.as_ref().clone().explain(verbose, analyze)?;
print_dataframe(py, df)
}
fn logical_plan(&self) -> PyResult<PyLogicalPlan> {
Ok(self.df.as_ref().clone().logical_plan().clone().into())
}
fn optimized_logical_plan(&self) -> PyResult<PyLogicalPlan> {
Ok(self.df.as_ref().clone().into_optimized_plan()?.into())
}
fn execution_plan(&self, py: Python) -> PyResult<PyExecutionPlan> {
let plan = wait_for_future(py, self.df.as_ref().clone().create_physical_plan())?;
Ok(plan.into())
}
fn repartition(&self, num: usize) -> PyResult<Self> {
let new_df = self
.df
.as_ref()
.clone()
.repartition(Partitioning::RoundRobinBatch(num))?;
Ok(Self::new(new_df))
}
#[pyo3(signature = (*args, num))]
fn repartition_by_hash(&self, args: Vec<PyExpr>, num: usize) -> PyResult<Self> {
let expr = args.into_iter().map(|py_expr| py_expr.into()).collect();
let new_df = self
.df
.as_ref()
.clone()
.repartition(Partitioning::Hash(expr, num))?;
Ok(Self::new(new_df))
}
#[pyo3(signature = (py_df, distinct=false))]
fn union(&self, py_df: PyDataFrame, distinct: bool) -> PyResult<Self> {
let new_df = if distinct {
self.df
.as_ref()
.clone()
.union_distinct(py_df.df.as_ref().clone())?
} else {
self.df.as_ref().clone().union(py_df.df.as_ref().clone())?
};
Ok(Self::new(new_df))
}
fn union_distinct(&self, py_df: PyDataFrame) -> PyResult<Self> {
let new_df = self
.df
.as_ref()
.clone()
.union_distinct(py_df.df.as_ref().clone())?;
Ok(Self::new(new_df))
}
fn intersect(&self, py_df: PyDataFrame) -> PyResult<Self> {
let new_df = self
.df
.as_ref()
.clone()
.intersect(py_df.df.as_ref().clone())?;
Ok(Self::new(new_df))
}
fn except_all(&self, py_df: PyDataFrame) -> PyResult<Self> {
let new_df = self.df.as_ref().clone().except(py_df.df.as_ref().clone())?;
Ok(Self::new(new_df))
}
fn write_csv(&self, path: &str, py: Python) -> PyResult<()> {
wait_for_future(
py,
self.df
.as_ref()
.clone()
.write_csv(path, DataFrameWriteOptions::new(), None),
)?;
Ok(())
}
#[pyo3(signature = (
path,
compression="uncompressed",
compression_level=None
))]
fn write_parquet(
&self,
path: &str,
compression: &str,
compression_level: Option<u32>,
py: Python,
) -> PyResult<()> {
fn verify_compression_level(cl: Option<u32>) -> Result<u32, PyErr> {
cl.ok_or(PyValueError::new_err("compression_level is not defined"))
}
let compression_type = match compression.to_lowercase().as_str() {
"snappy" => Compression::SNAPPY,
"gzip" => Compression::GZIP(
GzipLevel::try_new(compression_level.unwrap_or(6))
.map_err(|e| PyValueError::new_err(format!("{e}")))?,
),
"brotli" => Compression::BROTLI(
BrotliLevel::try_new(verify_compression_level(compression_level)?)
.map_err(|e| PyValueError::new_err(format!("{e}")))?,
),
"zstd" => Compression::ZSTD(
ZstdLevel::try_new(verify_compression_level(compression_level)? as i32)
.map_err(|e| PyValueError::new_err(format!("{e}")))?,
),
"lz0" => Compression::LZO,
"lz4" => Compression::LZ4,
"lz4_raw" => Compression::LZ4_RAW,
"uncompressed" => Compression::UNCOMPRESSED,
_ => {
return Err(PyValueError::new_err(format!(
"Unrecognized compression type {compression}"
)));
}
};
let writer_properties = WriterProperties::builder()
.set_compression(compression_type)
.build();
wait_for_future(
py,
self.df.as_ref().clone().write_parquet(
path,
DataFrameWriteOptions::new(),
Option::from(writer_properties),
),
)?;
Ok(())
}
fn write_json(&self, path: &str, py: Python) -> PyResult<()> {
wait_for_future(
py,
self.df
.as_ref()
.clone()
.write_json(path, DataFrameWriteOptions::new()),
)?;
Ok(())
}
fn to_arrow_table(&self, py: Python) -> PyResult<PyObject> {
let batches = self.collect(py)?.to_object(py);
let schema: PyObject = self.schema().into_py(py);
Python::with_gil(|py| {
let table_class = py.import("pyarrow")?.getattr("Table")?;
let args = PyTuple::new(py, &[batches, schema]);
let table: PyObject = table_class.call_method1("from_batches", args)?.into();
Ok(table)
})
}
fn to_pandas(&self, py: Python) -> PyResult<PyObject> {
let table = self.to_arrow_table(py)?;
Python::with_gil(|py| {
let result = table.call_method0(py, "to_pandas")?;
Ok(result)
})
}
fn to_pylist(&self, py: Python) -> PyResult<PyObject> {
let table = self.to_arrow_table(py)?;
Python::with_gil(|py| {
let result = table.call_method0(py, "to_pylist")?;
Ok(result)
})
}
fn to_pydict(&self, py: Python) -> PyResult<PyObject> {
let table = self.to_arrow_table(py)?;
Python::with_gil(|py| {
let result = table.call_method0(py, "to_pydict")?;
Ok(result)
})
}
fn to_polars(&self, py: Python) -> PyResult<PyObject> {
let table = self.to_arrow_table(py)?;
Python::with_gil(|py| {
let dataframe = py.import("polars")?.getattr("DataFrame")?;
let args = PyTuple::new(py, &[table]);
let result: PyObject = dataframe.call1(args)?.into();
Ok(result)
})
}
fn count(&self, py: Python) -> PyResult<usize> {
Ok(wait_for_future(py, self.df.as_ref().clone().count())?)
}
}
fn print_dataframe(py: Python, df: DataFrame) -> PyResult<()> {
let batches = wait_for_future(py, df.collect())?;
let batches_as_string = pretty::pretty_format_batches(&batches);
let result = match batches_as_string {
Ok(batch) => format!("DataFrame()\n{batch}"),
Err(err) => format!("Error: {:?}", err.to_string()),
};
let print = py.import("builtins")?.getattr("print")?;
print.call1((result,))?;
Ok(())
}