Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-python/src/lazyframe/serde.rs
7889 views
1
use std::io::{BufReader, BufWriter, Read};
2
3
use pyo3::prelude::*;
4
5
use super::PyLazyFrame;
6
use crate::exceptions::ComputeError;
7
use crate::file::get_file_like;
8
use crate::prelude::*;
9
use crate::utils::EnterPolarsExt;
10
11
#[pymethods]
12
#[allow(clippy::should_implement_trait)]
13
impl PyLazyFrame {
14
/// Serialize into binary data.
15
fn serialize_binary(&self, py: Python<'_>, py_f: Py<PyAny>) -> PyResult<()> {
16
let file = get_file_like(py_f, true)?;
17
let writer = BufWriter::new(file);
18
py.enter_polars(|| {
19
self.ldf
20
.read()
21
.logical_plan
22
.serialize_versioned(writer, Default::default())
23
})
24
}
25
26
/// Serialize into a JSON string.
27
#[cfg(feature = "json")]
28
fn serialize_json(&self, py: Python<'_>, py_f: Py<PyAny>) -> PyResult<()> {
29
let file = get_file_like(py_f, true)?;
30
let writer = BufWriter::new(file);
31
py.enter_polars(|| {
32
serde_json::to_writer(writer, &self.ldf.read().logical_plan)
33
.map_err(|err| ComputeError::new_err(err.to_string()))
34
})
35
}
36
37
/// Deserialize a file-like object containing binary data into a LazyFrame.
38
#[staticmethod]
39
fn deserialize_binary(py: Python<'_>, py_f: Py<PyAny>) -> PyResult<Self> {
40
let file = get_file_like(py_f, false)?;
41
let reader = BufReader::new(file);
42
43
let lp: DslPlan = py.enter_polars(|| DslPlan::deserialize_versioned(reader))?;
44
Ok(LazyFrame::from(lp).into())
45
}
46
47
/// Deserialize a file-like object containing JSON string data into a LazyFrame.
48
#[staticmethod]
49
#[cfg(feature = "json")]
50
fn deserialize_json(py: Python<'_>, py_f: Py<PyAny>) -> PyResult<Self> {
51
// it is faster to first read to memory and then parse: https://github.com/serde-rs/json/issues/160
52
// so don't bother with files.
53
let mut json = String::new();
54
get_file_like(py_f, false)?
55
.read_to_string(&mut json)
56
.unwrap();
57
58
// SAFETY:
59
// We skipped the serializing/deserializing of the static in lifetime in `DataType`
60
// so we actually don't have a lifetime at all when serializing.
61
62
// &str still has a lifetime. But it's ok, because we drop it immediately
63
// in this scope.
64
let json = unsafe { std::mem::transmute::<&'_ str, &'static str>(json.as_str()) };
65
66
let lp = py.enter_polars(|| {
67
serde_json::from_str::<DslPlan>(json)
68
.map_err(|err| ComputeError::new_err(err.to_string()))
69
})?;
70
Ok(LazyFrame::from(lp).into())
71
}
72
}
73
74