Skip to main content

polars_io/parquet/write/
key_value_metadata.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::sync::Arc;
4
5use polars_error::PolarsResult;
6use polars_parquet::write::KeyValue;
7#[cfg(feature = "python")]
8use polars_utils::python_function::PythonObject;
9#[cfg(feature = "python")]
10use pyo3::{Py, PyAny};
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize, de, ser};
13
14/// Context that can be used to construct custom file-level key value metadata for a Parquet file.
15pub struct ParquetMetadataContext<'a> {
16    pub arrow_schema: &'a str,
17}
18
19/// Key/value pairs that can be attached to a Parquet file as file-level metadata.
20#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
22#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
23pub enum KeyValueMetadata {
24    /// Static key value metadata.
25    Static(
26        #[cfg_attr(
27            feature = "serde",
28            serde(
29                serialize_with = "serialize_vec_key_value",
30                deserialize_with = "deserialize_vec_key_value"
31            )
32        )]
33        #[cfg_attr(
34            feature = "dsl-schema",
35            schemars(with = "Vec<(String, Option<String>)>")
36        )]
37        Vec<KeyValue>,
38    ),
39    /// Rust function to dynamically compute key value metadata.
40    #[cfg_attr(feature = "dsl-schema", schemars(skip))]
41    DynamicRust(RustKeyValueMetadataFunction),
42    /// Python function to dynamically compute key value metadata.
43    #[cfg(feature = "python")]
44    DynamicPython(python_impl::PythonKeyValueMetadataFunction),
45}
46
47#[cfg(feature = "serde")]
48fn serialize_vec_key_value<S>(kv: &[KeyValue], serializer: S) -> Result<S::Ok, S::Error>
49where
50    S: ser::Serializer,
51{
52    kv.iter()
53        .map(|item| (&item.key, item.value.as_ref()))
54        .collect::<Vec<_>>()
55        .serialize(serializer)
56}
57
58#[cfg(feature = "serde")]
59fn deserialize_vec_key_value<'de, D>(deserializer: D) -> Result<Vec<KeyValue>, D::Error>
60where
61    D: de::Deserializer<'de>,
62{
63    let data = Vec::<(String, Option<String>)>::deserialize(deserializer)?;
64    let result = data
65        .into_iter()
66        .map(|(key, value)| KeyValue { key, value })
67        .collect::<Vec<_>>();
68    Ok(result)
69}
70
71impl KeyValueMetadata {
72    /// Create a key value metadata object from a static key value mapping.
73    pub fn from_static(kv: Vec<(String, String)>) -> Self {
74        Self::Static(
75            kv.into_iter()
76                .map(|(key, value)| KeyValue {
77                    key,
78                    value: Some(value),
79                })
80                .collect(),
81        )
82    }
83
84    /// Create a key value metadata object from a Python function.
85    #[cfg(feature = "python")]
86    pub fn from_py_function(py_object: Py<PyAny>) -> Self {
87        Self::DynamicPython(python_impl::PythonKeyValueMetadataFunction(Arc::new(
88            PythonObject(py_object),
89        )))
90    }
91
92    /// Turn the metadata into the key/value pairs to write to the Parquet file.
93    /// The context is used to dynamically construct key/value pairs.
94    pub fn collect(&self, ctx: ParquetMetadataContext) -> PolarsResult<Vec<KeyValue>> {
95        match self {
96            Self::Static(kv) => Ok(kv.clone()),
97            Self::DynamicRust(func) => Ok(func.0(ctx)),
98            #[cfg(feature = "python")]
99            Self::DynamicPython(py_func) => py_func.call(ctx),
100        }
101    }
102
103    /// Whether the metadata may set `key`; dynamic metadata is only known when the file is finished.
104    pub fn may_contain(&self, key: &str) -> bool {
105        match self {
106            Self::Static(kv) => kv.iter().any(|kv| kv.key == key),
107            Self::DynamicRust(_) => true,
108            #[cfg(feature = "python")]
109            Self::DynamicPython(_) => true,
110        }
111    }
112}
113
114#[derive(Clone)]
115pub struct RustKeyValueMetadataFunction(
116    Arc<dyn Fn(ParquetMetadataContext) -> Vec<KeyValue> + Send + Sync>,
117);
118
119impl Debug for RustKeyValueMetadataFunction {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        write!(
122            f,
123            "key value metadata function at 0x{:016x}",
124            self.0.as_ref() as *const _ as *const () as usize
125        )
126    }
127}
128
129impl Eq for RustKeyValueMetadataFunction {}
130
131impl PartialEq for RustKeyValueMetadataFunction {
132    fn eq(&self, other: &Self) -> bool {
133        Arc::ptr_eq(&self.0, &other.0)
134    }
135}
136
137impl Hash for RustKeyValueMetadataFunction {
138    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
139        state.write_usize(Arc::as_ptr(&self.0) as *const () as usize);
140    }
141}
142
143#[cfg(feature = "serde")]
144impl Serialize for RustKeyValueMetadataFunction {
145    fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
146    where
147        S: serde::Serializer,
148    {
149        use serde::ser::Error;
150        Err(S::Error::custom(format!("cannot serialize {self:?}")))
151    }
152}
153
154#[cfg(feature = "serde")]
155impl<'de> Deserialize<'de> for RustKeyValueMetadataFunction {
156    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
157    where
158        D: serde::Deserializer<'de>,
159    {
160        use serde::de::Error;
161        Err(D::Error::custom(
162            "cannot deserialize RustKeyValueMetadataFn",
163        ))
164    }
165}
166
167#[cfg(feature = "python")]
168mod python_impl {
169    use std::hash::Hash;
170    use std::sync::Arc;
171
172    use polars_error::{PolarsResult, to_compute_err};
173    use polars_parquet::write::KeyValue;
174    use polars_utils::python_function::PythonObject;
175    use pyo3::types::PyAnyMethods;
176    use pyo3::{PyResult, Python, pyclass};
177    use serde::{Deserialize, Serialize};
178
179    use super::ParquetMetadataContext;
180
181    #[derive(Clone, Debug, PartialEq, Eq)]
182    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
183    #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
184    pub struct PythonKeyValueMetadataFunction(
185        #[cfg(feature = "python")]
186        #[cfg_attr(
187            feature = "serde",
188            serde(
189                serialize_with = "PythonObject::serialize_with_pyversion",
190                deserialize_with = "PythonObject::deserialize_with_pyversion"
191            )
192        )]
193        #[cfg_attr(feature = "dsl-schema", schemars(with = "Vec<u8>"))]
194        pub Arc<polars_utils::python_function::PythonFunction>,
195    );
196
197    impl PythonKeyValueMetadataFunction {
198        pub fn call(&self, ctx: ParquetMetadataContext) -> PolarsResult<Vec<KeyValue>> {
199            let ctx = PythonParquetMetadataContext::from_key_value_metadata_context(ctx);
200            Python::attach(|py| {
201                let args = (ctx,);
202                let out: Vec<(String, String)> =
203                    self.0.call1(py, args)?.into_bound(py).extract()?;
204                let result = out
205                    .into_iter()
206                    .map(|item| KeyValue {
207                        key: item.0,
208                        value: Some(item.1),
209                    })
210                    .collect::<Vec<_>>();
211                PyResult::Ok(result)
212            })
213            .map_err(to_compute_err)
214        }
215    }
216
217    impl Hash for PythonKeyValueMetadataFunction {
218        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
219            state.write_usize(Arc::as_ptr(&self.0) as *const () as usize);
220        }
221    }
222
223    #[pyclass]
224    pub struct PythonParquetMetadataContext {
225        #[pyo3(get)]
226        arrow_schema: String,
227    }
228
229    impl PythonParquetMetadataContext {
230        pub fn from_key_value_metadata_context(ctx: ParquetMetadataContext) -> Self {
231            Self {
232                arrow_schema: ctx.arrow_schema.to_string(),
233            }
234        }
235    }
236}