Path: blob/main/crates/polars-python/src/lazyframe/serde.rs
7889 views
use std::io::{BufReader, BufWriter, Read};12use pyo3::prelude::*;34use super::PyLazyFrame;5use crate::exceptions::ComputeError;6use crate::file::get_file_like;7use crate::prelude::*;8use crate::utils::EnterPolarsExt;910#[pymethods]11#[allow(clippy::should_implement_trait)]12impl PyLazyFrame {13/// Serialize into binary data.14fn serialize_binary(&self, py: Python<'_>, py_f: Py<PyAny>) -> PyResult<()> {15let file = get_file_like(py_f, true)?;16let writer = BufWriter::new(file);17py.enter_polars(|| {18self.ldf19.read()20.logical_plan21.serialize_versioned(writer, Default::default())22})23}2425/// Serialize into a JSON string.26#[cfg(feature = "json")]27fn serialize_json(&self, py: Python<'_>, py_f: Py<PyAny>) -> PyResult<()> {28let file = get_file_like(py_f, true)?;29let writer = BufWriter::new(file);30py.enter_polars(|| {31serde_json::to_writer(writer, &self.ldf.read().logical_plan)32.map_err(|err| ComputeError::new_err(err.to_string()))33})34}3536/// Deserialize a file-like object containing binary data into a LazyFrame.37#[staticmethod]38fn deserialize_binary(py: Python<'_>, py_f: Py<PyAny>) -> PyResult<Self> {39let file = get_file_like(py_f, false)?;40let reader = BufReader::new(file);4142let lp: DslPlan = py.enter_polars(|| DslPlan::deserialize_versioned(reader))?;43Ok(LazyFrame::from(lp).into())44}4546/// Deserialize a file-like object containing JSON string data into a LazyFrame.47#[staticmethod]48#[cfg(feature = "json")]49fn deserialize_json(py: Python<'_>, py_f: Py<PyAny>) -> PyResult<Self> {50// it is faster to first read to memory and then parse: https://github.com/serde-rs/json/issues/16051// so don't bother with files.52let mut json = String::new();53get_file_like(py_f, false)?54.read_to_string(&mut json)55.unwrap();5657// SAFETY:58// We skipped the serializing/deserializing of the static in lifetime in `DataType`59// so we actually don't have a lifetime at all when serializing.6061// &str still has a lifetime. But it's ok, because we drop it immediately62// in this scope.63let json = unsafe { std::mem::transmute::<&'_ str, &'static str>(json.as_str()) };6465let lp = py.enter_polars(|| {66serde_json::from_str::<DslPlan>(json)67.map_err(|err| ComputeError::new_err(err.to_string()))68})?;69Ok(LazyFrame::from(lp).into())70}71}727374