• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16989953990

15 Aug 2025 12:27PM UTC coverage: 87.855% (+0.2%) from 87.664%
16989953990

Pull #4226

github

web-flow
Merge 08d70c493 into fde6f426a
Pull Request #4226: Support converting TimestampTZ to and from duckdb

430 of 442 new or added lines in 15 files covered. (97.29%)

270 existing lines in 23 files now uncovered.

56314 of 64099 relevant lines covered (87.85%)

631227.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.55
/vortex-datafusion/src/persistent/format.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use std::any::Any;
5
use std::fmt::{Debug, Formatter};
6
use std::sync::Arc;
7

8
use async_trait::async_trait;
9
use datafusion::arrow::datatypes::{Schema, SchemaRef};
10
use datafusion::catalog::Session;
11
use datafusion::common::parsers::CompressionTypeVariant;
12
use datafusion::common::runtime::SpawnedTask;
13
use datafusion::common::stats::Precision;
14
use datafusion::common::{
15
    ColumnStatistics, DataFusionError, GetExt, Result as DFResult, Statistics,
16
    config_datafusion_err, not_impl_err,
17
};
18
use datafusion::datasource::file_format::file_compression_type::FileCompressionType;
19
use datafusion::datasource::file_format::{FileFormat, FileFormatFactory};
20
use datafusion::datasource::physical_plan::{
21
    FileScanConfig, FileScanConfigBuilder, FileSinkConfig, FileSource,
22
};
23
use datafusion::datasource::sink::DataSinkExec;
24
use datafusion::datasource::source::DataSourceExec;
25
use datafusion::logical_expr::dml::InsertOp;
26
use datafusion::physical_expr::LexRequirement;
27
use datafusion::physical_plan::ExecutionPlan;
28
use futures::{FutureExt, StreamExt as _, TryStreamExt as _, stream};
29
use itertools::Itertools;
30
use object_store::{ObjectMeta, ObjectStore};
31
use vortex::dtype::arrow::FromArrowType;
32
use vortex::dtype::{DType, Nullability, PType};
33
use vortex::error::{VortexExpect, VortexResult, vortex_err};
34
use vortex::file::VORTEX_FILE_EXTENSION;
35
use vortex::metrics::VortexMetrics;
36
use vortex::scalar::Scalar;
37
use vortex::session::VortexSession;
38
use vortex::stats;
39
use vortex::stats::{Stat, StatsSet};
40

41
use super::cache::VortexFileCache;
42
use super::sink::VortexSink;
43
use super::source::VortexSource;
44
use crate::PrecisionExt as _;
45
use crate::convert::TryToDataFusion;
46

47
/// Vortex implementation of a DataFusion [`FileFormat`].
48
pub struct VortexFormat {
49
    session: Arc<VortexSession>,
50
    file_cache: VortexFileCache,
51
    opts: VortexFormatOptions,
52
}
53

54
impl Debug for VortexFormat {
55
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
×
56
        f.debug_struct("VortexFormat")
×
57
            .field("opts", &self.opts)
×
58
            .finish()
×
59
    }
×
60
}
61

62
/// Options to configure the [`VortexFormat`].
63
#[derive(Debug)]
64
pub struct VortexFormatOptions {
65
    /// The size of the in-memory [`vortex::file::Footer`] cache.
66
    pub footer_cache_size_mb: usize,
67
    /// The size of the in-memory segment cache.
68
    pub segment_cache_size_mb: usize,
69
}
70

71
impl Default for VortexFormatOptions {
72
    fn default() -> Self {
20✔
73
        Self {
20✔
74
            footer_cache_size_mb: 64,
20✔
75
            segment_cache_size_mb: 0,
20✔
76
        }
20✔
77
    }
20✔
78
}
79

80
/// Minimal factory to create [`VortexFormat`] instances.
81
#[derive(Default, Debug)]
82
pub struct VortexFormatFactory {
83
    session: Arc<VortexSession>,
84
}
85

86
impl GetExt for VortexFormatFactory {
87
    fn get_ext(&self) -> String {
18✔
88
        VORTEX_FILE_EXTENSION.to_string()
18✔
89
    }
18✔
90
}
91

92
impl FileFormatFactory for VortexFormatFactory {
93
    #[allow(clippy::disallowed_types)]
94
    fn create(
3✔
95
        &self,
3✔
96
        _state: &dyn Session,
3✔
97
        format_options: &std::collections::HashMap<String, String>,
3✔
98
    ) -> DFResult<Arc<dyn FileFormat>> {
3✔
99
        if !format_options.is_empty() {
3✔
100
            return Err(config_datafusion_err!(
1✔
101
                "Vortex tables don't support any options"
1✔
102
            ));
1✔
103
        }
2✔
104

105
        Ok(Arc::new(VortexFormat::new(self.session.clone())))
2✔
106
    }
3✔
107

108
    fn default(&self) -> Arc<dyn FileFormat> {
×
109
        Arc::new(VortexFormat::default())
×
110
    }
×
111

112
    fn as_any(&self) -> &dyn Any {
×
113
        self
×
114
    }
×
115
}
116

117
impl Default for VortexFormat {
118
    fn default() -> Self {
18✔
119
        Self::new(Arc::new(VortexSession::default()))
18✔
120
    }
18✔
121
}
122

123
impl VortexFormat {
124
    /// Create a new instance of the [`VortexFormat`].
125
    pub fn new(session: Arc<VortexSession>) -> Self {
20✔
126
        let opts = VortexFormatOptions::default();
20✔
127
        Self {
20✔
128
            session: session.clone(),
20✔
129
            file_cache: VortexFileCache::new(
20✔
130
                opts.footer_cache_size_mb,
20✔
131
                opts.segment_cache_size_mb,
20✔
132
                session,
20✔
133
            ),
20✔
134
            opts,
20✔
135
        }
20✔
136
    }
20✔
137

138
    /// Return the format specific configuration
139
    pub fn options(&self) -> &VortexFormatOptions {
×
140
        &self.opts
×
141
    }
×
142
}
143

144
#[async_trait]
145
impl FileFormat for VortexFormat {
146
    fn as_any(&self) -> &dyn Any {
×
147
        self
×
148
    }
×
149

150
    fn compression_type(&self) -> Option<FileCompressionType> {
×
151
        None
×
152
    }
×
153

154
    fn get_ext(&self) -> String {
22✔
155
        VORTEX_FILE_EXTENSION.to_string()
22✔
156
    }
22✔
157

158
    fn get_ext_with_compression(
×
159
        &self,
×
160
        file_compression_type: &FileCompressionType,
×
161
    ) -> DFResult<String> {
×
162
        match file_compression_type.get_variant() {
×
163
            CompressionTypeVariant::UNCOMPRESSED => Ok(self.get_ext()),
×
164
            _ => Err(DataFusionError::Internal(
×
165
                "Vortex does not support file level compression.".into(),
×
166
            )),
×
167
        }
168
    }
×
169

170
    async fn infer_schema(
171
        &self,
172
        state: &dyn Session,
173
        store: &Arc<dyn ObjectStore>,
174
        objects: &[ObjectMeta],
175
    ) -> DFResult<SchemaRef> {
2✔
176
        let mut file_schemas = stream::iter(objects.iter().cloned())
177
            .map(|o| {
2✔
178
                let store = store.clone();
2✔
179
                let cache = self.file_cache.clone();
2✔
180
                SpawnedTask::spawn(async move {
2✔
181
                    let vxf = cache.try_get(&o, store).await?;
2✔
182
                    let inferred_schema = vxf.dtype().to_arrow_schema()?;
2✔
183
                    VortexResult::Ok((o.location, inferred_schema))
2✔
184
                })
2✔
185
                .map(|f| f.vortex_expect("Failed to spawn infer_schema"))
2✔
186
            })
2✔
187
            .buffer_unordered(state.config_options().execution.meta_fetch_concurrency)
188
            .try_collect::<Vec<_>>()
189
            .await
UNCOV
190
            .map_err(|e| DataFusionError::Execution(format!("Failed to infer schema: {e}")))?;
×
191

192
        // Get consistent order of schemas for `Schema::try_merge`, as some filesystems don't have deterministic listing orders
UNCOV
193
        file_schemas.sort_by(|(l1, _), (l2, _)| l1.cmp(l2));
×
194
        let file_schemas = file_schemas.into_iter().map(|(_, schema)| schema);
195

196
        Ok(Arc::new(Schema::try_merge(file_schemas)?))
197
    }
2✔
198

199
    #[tracing::instrument(skip_all, fields(location = object.location.as_ref()))]
200
    async fn infer_stats(
201
        &self,
202
        _state: &dyn Session,
203
        store: &Arc<dyn ObjectStore>,
204
        table_schema: SchemaRef,
205
        object: &ObjectMeta,
206
    ) -> DFResult<Statistics> {
207
        let object = object.clone();
208
        let store = store.clone();
209
        let cache = self.file_cache.clone();
210
        SpawnedTask::spawn(async move {
28✔
211
            let vxf = cache.try_get(&object, store.clone()).await.map_err(|e| {
28✔
UNCOV
212
                DataFusionError::Execution(format!(
×
213
                    "Failed to open Vortex file {}: {e}",
×
214
                    object.location
×
215
                ))
×
216
            })?;
×
217

218
            let struct_dtype = vxf
28✔
219
                .dtype()
28✔
220
                .as_struct()
28✔
221
                .vortex_expect("dtype is not a struct");
28✔
222

223
            // Evaluate the statistics for each column that we are able to return to DataFusion.
224
            let Some(file_stats) = vxf.file_stats() else {
28✔
225
                // If the file has no column stats, the best we can do is return a row count.
226
                return Ok(Statistics {
227
                    num_rows: Precision::Exact(
UNCOV
228
                        usize::try_from(vxf.row_count())
×
229
                            .map_err(|_| vortex_err!("Row count overflow"))
×
230
                            .vortex_expect("Row count overflow"),
×
231
                    ),
UNCOV
232
                    total_byte_size: Precision::Absent,
×
233
                    column_statistics: vec![ColumnStatistics::default(); struct_dtype.nfields()],
×
234
                });
235
            };
236

237
            let stats = table_schema
28✔
238
                .fields()
28✔
239
                .iter()
28✔
240
                .map(|field| struct_dtype.find(field.name()))
168✔
241
                .map(|idx| match idx {
168✔
UNCOV
242
                    None => StatsSet::default(),
×
243
                    Some(id) => file_stats[id].clone(),
168✔
244
                })
168✔
245
                .collect_vec();
28✔
246

247
            let total_byte_size = stats
28✔
248
                .iter()
28✔
249
                .map(|stats_set| {
168✔
250
                    stats_set
168✔
251
                        .get_as::<usize>(Stat::UncompressedSizeInBytes, &PType::U64.into())
168✔
252
                        .unwrap_or_else(|| stats::Precision::inexact(0_usize))
168✔
253
                })
168✔
254
                .fold(stats::Precision::exact(0_usize), |acc, stats_set| {
168✔
255
                    acc.zip(stats_set).map(|(acc, stats_set)| acc + stats_set)
168✔
256
                });
168✔
257

258
            // Sum up the total byte size across all the columns.
259
            let total_byte_size = total_byte_size.to_df();
28✔
260

261
            let column_statistics = stats
28✔
262
                .into_iter()
28✔
263
                .zip(table_schema.fields().iter())
28✔
264
                .map(|(stats_set, field)| {
168✔
265
                    let null_count = stats_set.get_as::<usize>(Stat::NullCount, &PType::U64.into());
168✔
266
                    let min = stats_set.get(Stat::Min).and_then(|n| {
168✔
267
                        n.map(|n| {
168✔
268
                            Scalar::new(
168✔
269
                                Stat::Min
168✔
270
                                    .dtype(&DType::from_arrow(field.as_ref()))
168✔
271
                                    .vortex_expect("must have a valid dtype"),
168✔
272
                                n,
168✔
273
                            )
168✔
274
                            .try_to_df()
168✔
275
                            .ok()
168✔
276
                        })
168✔
277
                        .transpose()
168✔
278
                    });
168✔
279

280
                    let max = stats_set.get(Stat::Max).and_then(|n| {
168✔
281
                        n.map(|n| {
168✔
282
                            Scalar::new(
168✔
283
                                Stat::Max
168✔
284
                                    .dtype(&DType::from_arrow(field.as_ref()))
168✔
285
                                    .vortex_expect("must have a valid dtype"),
168✔
286
                                n,
168✔
287
                            )
168✔
288
                            .try_to_df()
168✔
289
                            .ok()
168✔
290
                        })
168✔
291
                        .transpose()
168✔
292
                    });
168✔
293

294
                    ColumnStatistics {
295
                        null_count: null_count.to_df(),
168✔
296
                        max_value: max.to_df(),
168✔
297
                        min_value: min.to_df(),
168✔
298
                        sum_value: Precision::Absent,
168✔
299
                        distinct_count: stats_set
168✔
300
                            .get_as::<bool>(
168✔
301
                                Stat::IsConstant,
168✔
302
                                &DType::Bool(Nullability::NonNullable),
168✔
303
                            )
304
                            .and_then(|is_constant| {
168✔
UNCOV
305
                                is_constant.as_exact().map(|_| Precision::Exact(1))
×
306
                            })
×
307
                            .unwrap_or(Precision::Absent),
168✔
308
                    }
309
                })
168✔
310
                .collect::<Vec<_>>();
28✔
311

312
            Ok(Statistics {
313
                num_rows: Precision::Exact(
314
                    usize::try_from(vxf.row_count())
28✔
315
                        .map_err(|_| vortex_err!("Row count overflow"))
28✔
316
                        .vortex_expect("Row count overflow"),
28✔
317
                ),
318
                total_byte_size,
28✔
319
                column_statistics,
28✔
320
            })
321
        })
28✔
322
        .await
323
        .vortex_expect("Failed to spawn infer_stats")
324
    }
325

326
    async fn create_physical_plan(
327
        &self,
328
        _state: &dyn Session,
329
        file_scan_config: FileScanConfig,
330
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
180✔
331
        if file_scan_config
332
            .file_groups
333
            .iter()
334
            .flat_map(|fg| fg.files())
182✔
335
            .any(|f| f.range.is_some())
182✔
336
        {
337
            return not_impl_err!("File level partitioning isn't implemented yet for Vortex");
338
        }
339

340
        if !file_scan_config.table_partition_cols.is_empty() {
341
            return not_impl_err!("Hive style partitioning isn't implemented yet for Vortex");
342
        }
343

344
        if !file_scan_config.output_ordering.is_empty() {
345
            return not_impl_err!("Vortex doesn't support output ordering");
346
        }
347

348
        let source = VortexSource::new(self.file_cache.clone(), self.session.metrics().clone());
349
        Ok(DataSourceExec::from_data_source(
350
            FileScanConfigBuilder::from(file_scan_config)
351
                .with_source(Arc::new(source))
352
                .build(),
353
        ))
354
    }
180✔
355

356
    async fn create_writer_physical_plan(
357
        &self,
358
        input: Arc<dyn ExecutionPlan>,
359
        _state: &dyn Session,
360
        conf: FileSinkConfig,
361
        order_requirements: Option<LexRequirement>,
362
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
2✔
363
        if conf.insert_op != InsertOp::Append {
364
            return not_impl_err!("Overwrites are not implemented yet for Vortex");
365
        }
366

367
        if !conf.table_partition_cols.is_empty() {
368
            return not_impl_err!("Hive style partitioning isn't implemented yet for Vortex");
369
        }
370

371
        let schema = conf.output_schema().clone();
372
        let sink = Arc::new(VortexSink::new(conf, schema));
373

374
        Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
375
    }
2✔
376

377
    fn file_source(&self) -> Arc<dyn FileSource> {
180✔
378
        Arc::new(VortexSource::new(
180✔
379
            self.file_cache.clone(),
180✔
380
            VortexMetrics::default(),
180✔
381
        ))
180✔
382
    }
180✔
383
}
384

385
#[cfg(test)]
386
mod tests {
387
    use datafusion::execution::SessionStateBuilder;
388
    use datafusion::prelude::SessionContext;
389
    use tempfile::TempDir;
390

391
    use super::*;
392
    use crate::persistent::register_vortex_format_factory;
393

394
    #[tokio::test]
395
    async fn create_table() {
1✔
396
        let dir = TempDir::new().unwrap();
1✔
397

398
        let factory: VortexFormatFactory = Default::default();
1✔
399
        let mut session_state_builder = SessionStateBuilder::new().with_default_features();
1✔
400
        register_vortex_format_factory(factory, &mut session_state_builder);
1✔
401
        let session = SessionContext::new_with_state(session_state_builder.build());
1✔
402

403
        let df = session
1✔
404
            .sql(&format!(
1✔
405
                "CREATE EXTERNAL TABLE my_tbl \
1✔
406
                (c1 VARCHAR NOT NULL, c2 INT NOT NULL) \
1✔
407
                STORED AS vortex LOCATION '{}'",
1✔
408
                dir.path().to_str().unwrap()
1✔
409
            ))
1✔
410
            .await
1✔
411
            .unwrap();
1✔
412

413
        assert_eq!(df.count().await.unwrap(), 0);
1✔
414
    }
1✔
415

416
    #[tokio::test]
417
    #[should_panic]
418
    async fn fail_table_config() {
1✔
419
        let dir = TempDir::new().unwrap();
1✔
420

421
        let factory: VortexFormatFactory = Default::default();
1✔
422
        let mut session_state_builder = SessionStateBuilder::new().with_default_features();
1✔
423
        register_vortex_format_factory(factory, &mut session_state_builder);
1✔
424
        let session = SessionContext::new_with_state(session_state_builder.build());
1✔
425

426
        session
1✔
427
            .sql(&format!(
1✔
428
                "CREATE EXTERNAL TABLE my_tbl \
1✔
429
                (c1 VARCHAR NOT NULL, c2 INT NOT NULL) \
1✔
430
                STORED AS vortex LOCATION '{}' \
1✔
431
                OPTIONS( some_key 'value' );",
1✔
432
                dir.path().to_str().unwrap()
1✔
433
            ))
1✔
434
            .await
1✔
435
            .unwrap()
1✔
436
            .collect()
1✔
437
            .await
1✔
438
            .unwrap();
1✔
439
    }
1✔
440
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc