Skip to main content

datafusion_datasource/
table_schema.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Helper struct to manage table schemas with partition columns
6
7use arrow::datatypes::{FieldRef, Fields, SchemaBuilder, SchemaRef};
8use std::sync::Arc;
9
10/// The overall schema for potentially partitioned data sources.
11///
12/// When reading partitioned data (such as Hive-style partitioning), a [`TableSchema`]
13/// consists of up to three parts:
14/// 1. **File schema**: The schema of the actual data files on disk
15/// 2. **Partition columns**: Columns whose values are encoded in the directory structure,
16///    but not stored in the files themselves
17/// 3. **Virtual columns**: Columns produced by the file reader (e.g. Parquet
18///    `row_number`) that are not stored in the files
19///
20/// The full table schema is composed in that order: file columns, then
21/// partition columns, then virtual columns. Consumers that need a different
22/// output ordering should use a projection on top of
23/// [`TableSchema::table_schema`].
24///
25/// # Example: Partitioned Table
26///
27/// Consider a table with the following directory structure:
28/// ```text
29/// /data/date=2025-10-10/region=us-west/data.parquet
30/// /data/date=2025-10-11/region=us-east/data.parquet
31/// ```
32///
33/// In this case:
34/// - **File schema**: The schema of `data.parquet` files (e.g., `[user_id, amount]`)
35/// - **Partition columns**: `[date, region]` extracted from the directory path
36/// - **Table schema**: The full schema combining both (e.g., `[user_id, amount, date, region]`)
37///
38/// # When to Use
39///
40/// Use `TableSchema` when:
41/// - Reading partitioned data sources (Parquet, CSV, etc. with Hive-style partitioning)
42/// - You need to efficiently access different schema representations without reconstructing them
43/// - You want to avoid repeatedly concatenating file and partition schemas
44///
45/// For non-partitioned data or when working with a single schema representation,
46/// working directly with Arrow's `Schema` or `SchemaRef` is simpler.
47///
48/// # Performance
49///
50/// This struct pre-computes and caches the full table schema, allowing cheap references
51/// to any representation without repeated allocations or reconstructions.
52#[derive(Debug, Clone)]
53pub struct TableSchema {
54    /// The schema of the data files themselves, without partition columns.
55    ///
56    /// For example, if your Parquet files contain `[user_id, amount]`,
57    /// this field holds that schema.
58    file_schema: SchemaRef,
59
60    /// Columns that are derived from the directory structure (partitioning scheme).
61    ///
62    /// For Hive-style partitioning like `/date=2025-10-10/region=us-west/`,
63    /// this contains the `date` and `region` fields.
64    ///
65    /// These columns are NOT present in the data files but are appended to each
66    /// row during query execution based on the file's location.
67    ///
68    /// Stored as [`Fields`] (an immutable `Arc<[FieldRef]>`) so that cloning a
69    /// `TableSchema` is cheap and the partition columns can be shared zero-copy
70    /// with an existing schema.
71    table_partition_cols: Fields,
72
73    /// Virtual columns that are generated by the reader rather than read from
74    /// the data files or the directory structure.
75    ///
76    /// For example, a Parquet reader may inject a `row_number` column whose
77    /// values are produced per file by the reader. Virtual column fields must
78    /// carry an arrow extension type (e.g. `RowNumber`, `RowGroupIndex`) so the
79    /// file reader can recognize them.
80    ///
81    /// Virtual columns are appended at the end of the table schema, after the
82    /// file columns and any partition columns (layout: `[file, partition,
83    /// virtual]`).
84    virtual_columns: Fields,
85
86    /// The complete table schema: file_schema columns, followed by partition
87    /// columns, followed by virtual columns.
88    ///
89    /// This is pre-computed during construction by concatenating the three
90    /// parts, so it can be returned as a cheap reference.
91    table_schema: SchemaRef,
92
93    /// Schema of file + partition columns, excluding virtual columns.
94    ///
95    /// Pre-computed during construction so [`Self::schema_without_virtual_columns`]
96    /// can return a cheap reference. When there are no virtual columns this
97    /// shares the same `Arc` as `table_schema`.
98    schema_without_virtual_columns: SchemaRef,
99}
100
101impl TableSchema {
102    /// Start building a [`TableSchema`] from its (required) file schema.
103    ///
104    /// Partition columns are optional and added with
105    /// [`TableSchemaBuilder::with_table_partition_cols`]; the full table schema
106    /// is computed once by [`TableSchemaBuilder::build`]. This is the preferred
107    /// way to construct a `TableSchema`.
108    ///
109    /// # Example
110    ///
111    /// ```
112    /// # use std::sync::Arc;
113    /// # use arrow::datatypes::{Schema, Field, DataType};
114    /// # use datafusion_datasource::TableSchema;
115    /// let file_schema = Arc::new(Schema::new(vec![
116    ///     Field::new("user_id", DataType::Int64, false),
117    ///     Field::new("amount", DataType::Float64, false),
118    /// ]));
119    ///
120    /// let table_schema = TableSchema::builder(file_schema)
121    ///     .with_table_partition_cols(vec![
122    ///         Arc::new(Field::new("date", DataType::Utf8, false)),
123    ///         Arc::new(Field::new("region", DataType::Utf8, false)),
124    ///     ])
125    ///     .build();
126    ///
127    /// // Table schema will have 4 columns: user_id, amount, date, region
128    /// assert_eq!(table_schema.table_schema().fields().len(), 4);
129    /// ```
130    pub fn builder(file_schema: SchemaRef) -> TableSchemaBuilder {
131        TableSchemaBuilder::new(file_schema)
132    }
133
134    /// Create a new TableSchema from a file schema and partition columns.
135    ///
136    /// This is a convenience for
137    /// `TableSchema::builder(file_schema).with_table_partition_cols(cols).build()`.
138    #[deprecated(
139        since = "55.0.0",
140        note = "use TableSchema::builder(file_schema).with_table_partition_cols(cols).build() (or TableSchema::from(file_schema) for no partition columns)"
141    )]
142    pub fn new(file_schema: SchemaRef, table_partition_cols: Vec<FieldRef>) -> Self {
143        TableSchemaBuilder::new(file_schema)
144            .with_table_partition_cols(table_partition_cols)
145            .build()
146    }
147
148    /// Create a new TableSchema with no partition columns.
149    #[deprecated(
150        since = "55.0.0",
151        note = "use TableSchema::from(file_schema) / file_schema.into()"
152    )]
153    pub fn from_file_schema(file_schema: SchemaRef) -> Self {
154        TableSchemaBuilder::new(file_schema).build()
155    }
156
157    /// Return a new `TableSchema` with `partition_cols` as its partition columns,
158    /// replacing any existing ones. Existing virtual columns are preserved.
159    #[deprecated(
160        since = "55.0.0",
161        note = "use TableSchema::builder(file_schema).with_table_partition_cols(cols).build()"
162    )]
163    pub fn with_table_partition_cols(self, partition_cols: Vec<FieldRef>) -> Self {
164        TableSchemaBuilder::new(self.file_schema)
165            .with_table_partition_cols(partition_cols)
166            .with_virtual_columns(self.virtual_columns)
167            .build()
168    }
169
170    /// Get the file schema (without partition columns).
171    ///
172    /// This is the schema of the actual data files on disk.
173    pub fn file_schema(&self) -> &SchemaRef {
174        &self.file_schema
175    }
176
177    /// Get the table partition columns.
178    ///
179    /// These are the columns derived from the directory structure that
180    /// will be appended to each row during query execution.
181    pub fn table_partition_cols(&self) -> &Fields {
182        &self.table_partition_cols
183    }
184
185    /// Get the virtual columns.
186    ///
187    /// Virtual columns are produced by the file reader (e.g. Parquet
188    /// `row_number`) and are not stored in the data files or derived from
189    /// partition paths.
190    pub fn virtual_columns(&self) -> &Fields {
191        &self.virtual_columns
192    }
193
194    /// Get the full table schema (file schema + partition columns + virtual columns).
195    ///
196    /// This is the complete schema that will be seen by queries. Fields appear
197    /// in the order: file columns, partition columns, virtual columns.
198    pub fn table_schema(&self) -> &SchemaRef {
199        &self.table_schema
200    }
201
202    /// Schema of columns that can be referenced by predicates pushed into the
203    /// file reader: file columns plus partition columns, excluding virtual
204    /// columns.
205    ///
206    /// Virtual columns are produced by the reader itself (e.g. Parquet
207    /// `row_number`) and cannot be referenced inside the reader's row filter,
208    /// so predicates that reference them must stay above the scan. Callers
209    /// deciding which filters to push down should check against this schema
210    /// rather than [`Self::table_schema`].
211    ///
212    /// When there are no virtual columns this returns the same schema as
213    /// [`Self::table_schema`].
214    pub fn schema_without_virtual_columns(&self) -> &SchemaRef {
215        &self.schema_without_virtual_columns
216    }
217}
218
219impl From<SchemaRef> for TableSchema {
220    fn from(schema: SchemaRef) -> Self {
221        TableSchemaBuilder::new(schema).build()
222    }
223}
224
225impl From<&SchemaRef> for TableSchema {
226    fn from(schema: &SchemaRef) -> Self {
227        TableSchemaBuilder::new(Arc::clone(schema)).build()
228    }
229}
230
231/// Builder for [`TableSchema`].
232///
233/// The file schema is the only required input; partition columns and virtual
234/// columns are optional. Unlike calling [`TableSchema`]'s setters repeatedly,
235/// the builder computes the concatenated table schema exactly once, in
236/// [`TableSchemaBuilder::build`].
237///
238/// ```
239/// # use std::sync::Arc;
240/// # use arrow::datatypes::{Schema, Field, DataType};
241/// # use datafusion_datasource::TableSchemaBuilder;
242/// # let file_schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
243/// let table_schema = TableSchemaBuilder::new(file_schema)
244///     .with_table_partition_cols(vec![Arc::new(Field::new("date", DataType::Utf8, false))])
245///     .build();
246/// assert_eq!(table_schema.table_partition_cols().len(), 1);
247/// ```
248#[derive(Debug, Clone)]
249pub struct TableSchemaBuilder {
250    file_schema: SchemaRef,
251    table_partition_cols: Fields,
252    virtual_columns: Fields,
253}
254
255impl TableSchemaBuilder {
256    /// Create a builder for a `TableSchema` over the given file schema, with no
257    /// partition or virtual columns yet.
258    pub fn new(file_schema: SchemaRef) -> Self {
259        Self {
260            file_schema,
261            table_partition_cols: Fields::empty(),
262            virtual_columns: Fields::empty(),
263        }
264    }
265
266    /// Set the partition columns, replacing any previously set.
267    ///
268    /// Accepts anything convertible into [`Fields`] (e.g. `Vec<FieldRef>` or an
269    /// existing schema's `Fields`, which is shared zero-copy).
270    pub fn with_table_partition_cols(
271        mut self,
272        table_partition_cols: impl Into<Fields>,
273    ) -> Self {
274        self.table_partition_cols = table_partition_cols.into();
275        self
276    }
277
278    /// Set the virtual columns, replacing any previously set.
279    ///
280    /// Virtual columns are produced by the file reader (e.g. Parquet
281    /// `row_number`) and appended at the end of the table schema. Each field
282    /// must carry an arrow virtual extension type so the reader can recognize
283    /// it.
284    ///
285    /// Accepts anything convertible into [`Fields`] (e.g. `Vec<FieldRef>`).
286    pub fn with_virtual_columns(mut self, virtual_columns: impl Into<Fields>) -> Self {
287        self.virtual_columns = virtual_columns.into();
288        self
289    }
290
291    /// Build the [`TableSchema`], computing the full
292    /// `file + partition + virtual` schema once.
293    pub fn build(self) -> TableSchema {
294        debug_assert!(
295            self.virtual_columns.iter().enumerate().all(|(i, v)| {
296                let name = v.name();
297                !self.file_schema.fields().iter().any(|f| f.name() == name)
298                    && !self.table_partition_cols.iter().any(|p| p.name() == name)
299                    && !self.virtual_columns[..i].iter().any(|w| w.name() == name)
300            }),
301            "virtual column name collides with an existing file, partition, or virtual column"
302        );
303
304        let mut builder = SchemaBuilder::from(self.file_schema.as_ref());
305        builder.extend(self.table_partition_cols.iter().cloned());
306        let (table_schema, schema_without_virtual_columns) =
307            if self.virtual_columns.is_empty() {
308                let schema = Arc::new(builder.finish());
309                (Arc::clone(&schema), schema)
310            } else {
311                let without_virtual = Arc::new(builder.finish());
312                let mut builder = SchemaBuilder::from(without_virtual.as_ref());
313                builder.extend(self.virtual_columns.iter().cloned());
314                (Arc::new(builder.finish()), without_virtual)
315            };
316        TableSchema {
317            file_schema: self.file_schema,
318            table_partition_cols: self.table_partition_cols,
319            virtual_columns: self.virtual_columns,
320            table_schema,
321            schema_without_virtual_columns,
322        }
323    }
324}
325
326impl From<SchemaRef> for TableSchemaBuilder {
327    fn from(schema: SchemaRef) -> Self {
328        TableSchemaBuilder::new(schema)
329    }
330}
331
332impl From<&SchemaRef> for TableSchemaBuilder {
333    fn from(schema: &SchemaRef) -> Self {
334        TableSchemaBuilder::new(Arc::clone(schema))
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::{TableSchema, TableSchemaBuilder};
341    use arrow::datatypes::{DataType, Field, Schema};
342    use std::sync::Arc;
343
344    #[test]
345    fn test_table_schema_creation() {
346        let file_schema = Arc::new(Schema::new(vec![
347            Field::new("user_id", DataType::Int64, false),
348            Field::new("amount", DataType::Float64, false),
349        ]));
350
351        let partition_cols = vec![
352            Arc::new(Field::new("date", DataType::Utf8, false)),
353            Arc::new(Field::new("region", DataType::Utf8, false)),
354        ];
355
356        let table_schema = TableSchema::builder(file_schema.clone())
357            .with_table_partition_cols(partition_cols.clone())
358            .build();
359
360        // Verify file schema
361        assert_eq!(table_schema.file_schema().as_ref(), file_schema.as_ref());
362
363        // Verify partition columns
364        assert_eq!(table_schema.table_partition_cols().len(), 2);
365        assert_eq!(table_schema.table_partition_cols()[0], partition_cols[0]);
366        assert_eq!(table_schema.table_partition_cols()[1], partition_cols[1]);
367
368        // Verify full table schema
369        let expected_fields = vec![
370            Field::new("user_id", DataType::Int64, false),
371            Field::new("amount", DataType::Float64, false),
372            Field::new("date", DataType::Utf8, false),
373            Field::new("region", DataType::Utf8, false),
374        ];
375        let expected_schema = Schema::new(expected_fields);
376        assert_eq!(table_schema.table_schema().as_ref(), &expected_schema);
377    }
378
379    #[test]
380    fn test_builder_with_partition_cols() {
381        let file_schema =
382            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
383
384        let table_schema = TableSchemaBuilder::new(Arc::clone(&file_schema))
385            .with_table_partition_cols(vec![
386                Arc::new(Field::new("country", DataType::Utf8, false)),
387                Arc::new(Field::new("year", DataType::Int32, false)),
388            ])
389            .build();
390
391        // File schema is preserved and the partition columns are appended.
392        assert_eq!(table_schema.file_schema().as_ref(), file_schema.as_ref());
393        assert_eq!(table_schema.table_partition_cols().len(), 2);
394        assert_eq!(table_schema.table_partition_cols()[0].name(), "country");
395        assert_eq!(table_schema.table_partition_cols()[1].name(), "year");
396
397        let expected_schema = Schema::new(vec![
398            Field::new("id", DataType::Int32, false),
399            Field::new("country", DataType::Utf8, false),
400            Field::new("year", DataType::Int32, false),
401        ]);
402        assert_eq!(table_schema.table_schema().as_ref(), &expected_schema);
403    }
404
405    #[test]
406    fn test_builder_with_table_partition_cols_replaces() {
407        // Calling the setter more than once replaces rather than appends.
408        let file_schema =
409            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
410
411        let table_schema = TableSchemaBuilder::new(file_schema)
412            .with_table_partition_cols(vec![Arc::new(Field::new(
413                "country",
414                DataType::Utf8,
415                false,
416            ))])
417            .with_table_partition_cols(vec![Arc::new(Field::new(
418                "city",
419                DataType::Utf8,
420                false,
421            ))])
422            .build();
423
424        assert_eq!(table_schema.table_partition_cols().len(), 1);
425        assert_eq!(table_schema.table_partition_cols()[0].name(), "city");
426    }
427
428    #[test]
429    fn test_builder_accepts_fields_zero_copy() {
430        // `with_table_partition_cols` accepts an existing schema's `Fields`
431        // directly (shared via `Arc`, no `Vec` round-trip).
432        let file_schema =
433            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
434        let partition_schema =
435            Schema::new(vec![Field::new("date", DataType::Utf8, false)]);
436
437        let table_schema = TableSchemaBuilder::new(file_schema)
438            .with_table_partition_cols(partition_schema.fields().clone())
439            .build();
440
441        assert_eq!(table_schema.table_partition_cols().len(), 1);
442        assert_eq!(table_schema.table_partition_cols()[0].name(), "date");
443    }
444
445    #[test]
446    #[expect(deprecated)]
447    fn test_deprecated_with_table_partition_cols_replaces() {
448        // The deprecated setter still works and replaces the partition columns.
449        // It is safe on a shared clone because partition columns are immutable.
450        let file_schema =
451            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
452        let original = TableSchema::builder(file_schema)
453            .with_table_partition_cols(vec![Arc::new(Field::new(
454                "country",
455                DataType::Utf8,
456                false,
457            ))])
458            .build();
459
460        let replaced =
461            original
462                .clone()
463                .with_table_partition_cols(vec![Arc::new(Field::new(
464                    "city",
465                    DataType::Utf8,
466                    false,
467                ))]);
468
469        assert_eq!(replaced.table_partition_cols().len(), 1);
470        assert_eq!(replaced.table_partition_cols()[0].name(), "city");
471
472        // The original is untouched.
473        assert_eq!(original.table_partition_cols().len(), 1);
474        assert_eq!(original.table_partition_cols()[0].name(), "country");
475    }
476
477    #[test]
478    fn test_builder_with_virtual_columns_layout() {
479        let file_schema = Arc::new(Schema::new(vec![
480            Field::new("user_id", DataType::Int64, false),
481            Field::new("amount", DataType::Float64, false),
482        ]));
483
484        let virtual_cols =
485            vec![Arc::new(Field::new("row_number", DataType::Int64, true))];
486
487        let partition_cols = vec![Arc::new(Field::new("date", DataType::Utf8, false))];
488
489        // Apply virtual columns and partition columns in either order on the
490        // builder; the resulting table schema should always be
491        // [file, partition, virtual].
492        let built_virtual_first = TableSchemaBuilder::new(Arc::clone(&file_schema))
493            .with_virtual_columns(virtual_cols.clone())
494            .with_table_partition_cols(partition_cols.clone())
495            .build();
496
497        let built_partition_first = TableSchemaBuilder::new(Arc::clone(&file_schema))
498            .with_table_partition_cols(partition_cols.clone())
499            .with_virtual_columns(virtual_cols.clone())
500            .build();
501
502        let expected = Schema::new(vec![
503            Field::new("user_id", DataType::Int64, false),
504            Field::new("amount", DataType::Float64, false),
505            Field::new("date", DataType::Utf8, false),
506            Field::new("row_number", DataType::Int64, true),
507        ]);
508
509        for ts in [built_virtual_first, built_partition_first] {
510            assert_eq!(ts.table_schema().as_ref(), &expected);
511            assert_eq!(ts.virtual_columns().len(), 1);
512            assert_eq!(ts.virtual_columns()[0].name(), "row_number");
513            assert_eq!(ts.table_partition_cols().len(), 1);
514            assert_eq!(ts.file_schema().fields().len(), 2);
515        }
516    }
517
518    #[test]
519    #[should_panic(expected = "virtual column name collides")]
520    #[cfg(debug_assertions)]
521    fn test_virtual_column_collides_with_file_schema_panics_in_debug() {
522        let file_schema = Arc::new(Schema::new(vec![Field::new(
523            "row_number",
524            DataType::Int64,
525            false,
526        )]));
527        let _ = TableSchemaBuilder::new(file_schema)
528            .with_virtual_columns(vec![Arc::new(Field::new(
529                "row_number",
530                DataType::Int64,
531                true,
532            ))])
533            .build();
534    }
535
536    #[test]
537    #[should_panic(expected = "virtual column name collides")]
538    #[cfg(debug_assertions)]
539    fn test_virtual_column_collides_with_partition_panics_in_debug() {
540        let file_schema = Arc::new(Schema::new(vec![Field::new(
541            "user_id",
542            DataType::Int64,
543            false,
544        )]));
545        let partition_cols =
546            vec![Arc::new(Field::new("row_number", DataType::Utf8, false))];
547        let _ = TableSchemaBuilder::new(file_schema)
548            .with_table_partition_cols(partition_cols)
549            .with_virtual_columns(vec![Arc::new(Field::new(
550                "row_number",
551                DataType::Int64,
552                true,
553            ))])
554            .build();
555    }
556
557    #[test]
558    #[should_panic(expected = "virtual column name collides")]
559    #[cfg(debug_assertions)]
560    fn test_duplicate_virtual_columns_panic_in_debug() {
561        let file_schema = Arc::new(Schema::new(vec![Field::new(
562            "user_id",
563            DataType::Int64,
564            false,
565        )]));
566        let _ = TableSchemaBuilder::new(file_schema)
567            .with_virtual_columns(vec![
568                Arc::new(Field::new("vc", DataType::Int64, true)),
569                Arc::new(Field::new("vc", DataType::Int64, true)),
570            ])
571            .build();
572    }
573
574    #[test]
575    #[should_panic(expected = "virtual column name collides")]
576    #[cfg(debug_assertions)]
577    fn test_partition_column_added_after_colliding_virtual_panics_in_debug() {
578        // Builder order is irrelevant: collision check runs in build().
579        let file_schema = Arc::new(Schema::new(vec![Field::new(
580            "user_id",
581            DataType::Int64,
582            false,
583        )]));
584        let _ = TableSchemaBuilder::new(file_schema)
585            .with_virtual_columns(vec![Arc::new(Field::new(
586                "row_number",
587                DataType::Int64,
588                true,
589            ))])
590            .with_table_partition_cols(vec![Arc::new(Field::new(
591                "row_number",
592                DataType::Utf8,
593                false,
594            ))])
595            .build();
596    }
597}