datafusion_datasource/
proto.rs1use std::sync::Arc;
21
22use chrono::{TimeZone, Utc};
23use datafusion_common::{DataFusionError, Result, internal_datafusion_err};
24use datafusion_proto_models::protobuf;
25use object_store::ObjectMeta;
26use object_store::path::Path;
27
28use crate::file_groups::FileGroup;
29use crate::{FileRange, PartitionedFile};
30
31impl TryFrom<&FileRange> for protobuf::FileRange {
32 type Error = DataFusionError;
33
34 fn try_from(range: &FileRange) -> Result<Self> {
35 Ok(protobuf::FileRange {
36 start: range.start,
37 end: range.end,
38 })
39 }
40}
41
42impl TryFrom<&protobuf::FileRange> for FileRange {
43 type Error = DataFusionError;
44
45 fn try_from(range: &protobuf::FileRange) -> Result<Self> {
46 Ok(FileRange {
47 start: range.start,
48 end: range.end,
49 })
50 }
51}
52
53impl TryFrom<&PartitionedFile> for protobuf::PartitionedFile {
54 type Error = DataFusionError;
55
56 fn try_from(file: &PartitionedFile) -> Result<Self> {
57 let last_modified = file.object_meta.last_modified;
58 let last_modified_ns = last_modified.timestamp_nanos_opt().ok_or_else(|| {
59 DataFusionError::Plan(format!(
60 "Invalid timestamp on PartitionedFile::ObjectMeta: {last_modified}"
61 ))
62 })? as u64;
63 Ok(protobuf::PartitionedFile {
64 arrow_schema: file
65 .arrow_schema
66 .as_ref()
67 .map(|s| s.as_ref().try_into())
68 .transpose()?,
69 path: file.object_meta.location.as_ref().to_owned(),
70 size: file.object_meta.size,
71 last_modified_ns,
72 partition_values: file
73 .partition_values
74 .iter()
75 .map(|v| v.try_into())
76 .collect::<Result<Vec<_>, _>>()?,
77 range: file.range.as_ref().map(TryInto::try_into).transpose()?,
78 statistics: file.statistics.as_ref().map(|s| s.as_ref().into()),
79 })
80 }
81}
82
83impl TryFrom<&protobuf::PartitionedFile> for PartitionedFile {
84 type Error = DataFusionError;
85
86 fn try_from(file: &protobuf::PartitionedFile) -> Result<Self> {
87 let mut pf = PartitionedFile::new_from_meta(ObjectMeta {
88 location: Path::parse(file.path.as_str()).map_err(|e| {
89 internal_datafusion_err!("Invalid object_store path: {e}")
90 })?,
91 last_modified: Utc.timestamp_nanos(file.last_modified_ns as i64),
92 size: file.size,
93 e_tag: None,
94 version: None,
95 })
96 .with_partition_values(
97 file.partition_values
98 .iter()
99 .map(|v| v.try_into())
100 .collect::<Result<Vec<_>, _>>()?,
101 );
102 if let Some(proto_schema) = file.arrow_schema.as_ref() {
103 pf = pf.with_arrow_schema(Arc::new(
104 proto_schema.try_into().map_err(DataFusionError::from)?,
105 ));
106 }
107 if let Some(range) = file.range.as_ref() {
108 let range = FileRange::try_from(range)?;
109 pf = pf.with_range(range.start, range.end);
110 }
111 if let Some(proto_stats) = file.statistics.as_ref() {
112 pf.statistics = Some(Arc::new(proto_stats.try_into()?));
116 }
117 Ok(pf)
118 }
119}
120
121impl TryFrom<&FileGroup> for protobuf::FileGroup {
122 type Error = DataFusionError;
123
124 fn try_from(group: &FileGroup) -> Result<Self> {
125 Ok(protobuf::FileGroup {
126 files: group
127 .files()
128 .iter()
129 .map(TryInto::try_into)
130 .collect::<Result<Vec<_>>>()?,
131 })
132 }
133}
134
135impl TryFrom<&protobuf::FileGroup> for FileGroup {
136 type Error = DataFusionError;
137
138 fn try_from(group: &protobuf::FileGroup) -> Result<Self> {
139 Ok(FileGroup::new(
140 group
141 .files
142 .iter()
143 .map(TryInto::try_into)
144 .collect::<Result<Vec<_>>>()?,
145 ))
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use arrow::datatypes::{DataType, Field, Schema};
152 use datafusion_common::{ScalarValue, Statistics};
153
154 use super::*;
155
156 #[test]
157 fn partitioned_file_roundtrip_preserves_all_fields() -> Result<()> {
158 let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
159 let pf = PartitionedFile::new_from_meta(ObjectMeta {
160 location: Path::parse("foo/bar.parquet")?,
161 last_modified: Utc.timestamp_nanos(1_000_000_000),
162 size: 1234,
163 e_tag: None,
164 version: None,
165 })
166 .with_partition_values(vec![ScalarValue::from("2024-01-01")])
167 .with_range(10, 20)
168 .with_arrow_schema(Arc::clone(&schema))
169 .with_statistics(Arc::new(Statistics::new_unknown(&schema)));
170
171 let encoded = protobuf::PartitionedFile::try_from(&pf)?;
172 let decoded = PartitionedFile::try_from(&encoded)?;
173
174 assert_eq!(decoded.object_meta.location, pf.object_meta.location);
175 assert_eq!(decoded.object_meta.size, pf.object_meta.size);
176 assert_eq!(
177 decoded.object_meta.last_modified,
178 pf.object_meta.last_modified
179 );
180 assert_eq!(decoded.partition_values, pf.partition_values);
181 assert_eq!(decoded.range, pf.range);
182 assert_eq!(decoded.arrow_schema.as_deref(), Some(schema.as_ref()));
183 assert_eq!(
186 pf.statistics.as_ref().unwrap().column_statistics.len(),
187 schema.fields().len() + pf.partition_values.len()
188 );
189 assert_eq!(decoded.statistics, pf.statistics);
190 Ok(())
191 }
192
193 #[test]
194 fn partitioned_file_path_roundtrip_percent_encoded() -> Result<()> {
195 let path_str = "foo/foo%2Fbar/baz%252Fqux";
199 let pf = PartitionedFile::new_from_meta(ObjectMeta {
200 location: Path::parse(path_str)?,
201 last_modified: Utc.timestamp_nanos(1_000),
202 size: 42,
203 e_tag: None,
204 version: None,
205 });
206
207 let encoded = protobuf::PartitionedFile::try_from(&pf)?;
208 assert_eq!(encoded.path, path_str);
209
210 let decoded = PartitionedFile::try_from(&encoded)?;
211 assert_eq!(decoded.object_meta.location.as_ref(), path_str);
212 assert_eq!(decoded.object_meta.location, pf.object_meta.location);
213 Ok(())
214 }
215
216 #[test]
217 fn partitioned_file_arrow_schema_roundtrip_preserves_metadata() -> Result<()> {
218 use std::collections::HashMap;
219
220 let arrow_schema = Arc::new(Schema::new_with_metadata(
221 vec![
222 Field::new("id", DataType::Int64, false),
223 Field::new("value", DataType::Utf8, true).with_metadata(HashMap::from([
224 ("field_meta".to_string(), "field_value".to_string()),
225 ])),
226 ],
227 HashMap::from([("schema_meta".to_string(), "schema_value".to_string())]),
228 ));
229 let pf = PartitionedFile::new("foo/bar.parquet", 10)
230 .with_arrow_schema(Arc::clone(&arrow_schema));
231
232 let encoded = protobuf::PartitionedFile::try_from(&pf)?;
233 assert!(encoded.arrow_schema.is_some());
234
235 let decoded = PartitionedFile::try_from(&encoded)?;
236 assert_eq!(decoded.arrow_schema.as_deref(), Some(arrow_schema.as_ref()));
237 Ok(())
238 }
239
240 #[test]
241 fn partitioned_file_from_proto_rejects_invalid_path() {
242 let proto = protobuf::PartitionedFile {
243 path: "foo//bar.parquet".to_string(),
244 ..Default::default()
245 };
246
247 let err = PartitionedFile::try_from(&proto).unwrap_err();
248 assert!(
249 err.to_string().contains("Invalid object_store path"),
250 "unexpected error: {err}"
251 );
252 }
253
254 #[test]
255 fn file_group_from_slice_matches_file_group() -> Result<()> {
256 let files = vec![
261 PartitionedFile::new("a.parquet", 1),
262 PartitionedFile::new("b.parquet", 2),
263 ];
264
265 let from_slice = protobuf::FileGroup::try_from(&files[..])?;
266 let from_group = protobuf::FileGroup::try_from(&FileGroup::new(files))?;
267
268 assert_eq!(from_slice, from_group);
269 assert_eq!(from_slice.files.len(), 2);
270 Ok(())
271 }
272
273 #[test]
274 fn file_group_roundtrip() -> Result<()> {
275 let group = FileGroup::new(vec![
276 PartitionedFile::new("a.parquet", 1),
277 PartitionedFile::new("b.parquet", 2),
278 ]);
279
280 let encoded = protobuf::FileGroup::try_from(&group)?;
281 let decoded = FileGroup::try_from(&encoded)?;
282
283 assert_eq!(decoded.len(), 2);
284 assert_eq!(
285 decoded.files()[1].object_meta.location,
286 group.files()[1].object_meta.location
287 );
288 Ok(())
289 }
290}