Skip to main content

datafusion_datasource/
projection.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
5use std::sync::Arc;
6
7use arrow::datatypes::{Schema, SchemaRef};
8use datafusion_common::{
9    Result, ScalarValue,
10    tree_node::{Transformed, TransformedResult, TreeNode},
11};
12use datafusion_physical_expr::{
13    expressions::{Column, Literal},
14    projection::{ProjectionExpr, ProjectionExprs},
15};
16use datafusion_physical_expr_adapter::rewrite::rewrite_input_file_name_in_projection;
17use futures::{FutureExt, StreamExt};
18use itertools::Itertools;
19
20use crate::{
21    PartitionedFile, TableSchema,
22    file_stream::{FileOpenFuture, FileOpener},
23};
24
25/// A file opener that handles applying a projection on top of an inner opener.
26///
27/// This includes handling partition columns.
28///
29/// Any projection pushed down will be split up into:
30/// - Simple column indices / column selection
31/// - A remainder projection that this opener applies on top of it
32///
33/// This is meant to simplify projection pushdown for sources like CSV
34/// that can only handle "simple" column selection.
35pub struct ProjectionOpener {
36    inner: Arc<dyn FileOpener>,
37    projection: ProjectionExprs,
38    input_schema: SchemaRef,
39    partition_columns: Vec<PartitionColumnIndex>,
40}
41
42impl ProjectionOpener {
43    pub fn try_new(
44        projection: SplitProjection,
45        inner: Arc<dyn FileOpener>,
46        file_schema: &Schema,
47    ) -> Result<Arc<dyn FileOpener>> {
48        Ok(Arc::new(ProjectionOpener {
49            inner,
50            projection: projection.remapped_projection,
51            input_schema: Arc::new(file_schema.project(&projection.file_indices)?),
52            partition_columns: projection.partition_columns,
53        }))
54    }
55}
56
57impl FileOpener for ProjectionOpener {
58    fn open(&self, partitioned_file: PartitionedFile) -> Result<FileOpenFuture> {
59        let partition_values = partitioned_file.partition_values.clone();
60
61        // Modify any references to partition columns in the projection expressions
62        // and substitute them with literal values from PartitionedFile.partition_values
63        let projection = if self.partition_columns.is_empty() {
64            self.projection.clone()
65        } else {
66            inject_partition_columns_into_projection(
67                &self.projection,
68                &self.partition_columns,
69                partition_values,
70            )
71        };
72        // Replace `input_file_name()` with a per-file literal if present.
73        let projection = rewrite_input_file_name_in_projection(
74            projection,
75            partitioned_file.object_meta.location.as_ref(),
76        )?;
77        let projector = projection.make_projector(&self.input_schema)?;
78
79        let inner = self.inner.open(partitioned_file)?;
80
81        Ok(async move {
82            let stream = inner.await?;
83            let stream = stream.map(move |batch| {
84                let batch = batch?;
85                let batch = projector.project_batch(&batch)?;
86                Ok(batch)
87            });
88            Ok(stream.boxed())
89        }
90        .boxed())
91    }
92}
93
94#[derive(Debug, Clone, Copy)]
95pub struct PartitionColumnIndex {
96    /// The index of this partition column in the remainder projection (>= num_file_columns)
97    pub in_remainder_projection: usize,
98    /// The index of this partition column in the partition_values array
99    pub in_partition_values: usize,
100}
101
102fn inject_partition_columns_into_projection(
103    projection: &ProjectionExprs,
104    partition_columns: &[PartitionColumnIndex],
105    partition_values: Vec<ScalarValue>,
106) -> ProjectionExprs {
107    // Pre-create all literals for partition columns to avoid cloning ScalarValues multiple times.
108    let partition_literals: Vec<Arc<Literal>> = partition_values
109        .into_iter()
110        .map(|value| Arc::new(Literal::new(value)))
111        .collect();
112
113    let projections = projection
114        .iter()
115        .map(|projection| {
116            let expr = Arc::clone(&projection.expr)
117                .transform(|expr| {
118                    let original_expr = Arc::clone(&expr);
119                    if let Some(column) = expr.downcast_ref::<Column>() {
120                        // Check if this column index corresponds to a partition column
121                        if let Some(pci) = partition_columns
122                            .iter()
123                            .find(|pci| pci.in_remainder_projection == column.index())
124                        {
125                            let literal =
126                                Arc::clone(&partition_literals[pci.in_partition_values]);
127                            return Ok(Transformed::yes(literal));
128                        }
129                    }
130                    Ok(Transformed::no(original_expr))
131                })
132                .data()
133                .expect("infallible transform");
134            ProjectionExpr::new(expr, projection.alias.clone())
135        })
136        .collect_vec();
137    ProjectionExprs::new(projections)
138}
139
140/// At a high level the goal of SplitProjection is to take a ProjectionExprs meant to be applied to the table schema
141/// and split that into:
142/// - The projection indices into the file schema (file_indices)
143/// - The projection indices into the partition values (partition_value_indices), which pre-compute both the index into the table schema
144///   and the index into the partition values array
145/// - A remapped projection that can be applied after the file projection is applied
146///   This remapped projection has the following properties:
147///     - Column indices referring to file columns are remapped to [0..file_indices.len())
148///     - Column indices referring to partition columns are remapped to [file_indices.len()..)
149///
150///   This allows the ProjectionOpener to easily identify which columns in the remapped projection
151///   refer to partition columns and substitute them with literals from the partition values.
152#[derive(Debug, Clone)]
153pub struct SplitProjection {
154    /// The original projection this [`SplitProjection`] was derived from
155    pub source: ProjectionExprs,
156    /// Column indices to read from file (public for file sources)
157    pub file_indices: Vec<usize>,
158    /// Pre-computed partition column mappings (internal, used by ProjectionOpener)
159    pub(crate) partition_columns: Vec<PartitionColumnIndex>,
160    /// The remapped projection (internal, used by ProjectionOpener)
161    pub(crate) remapped_projection: ProjectionExprs,
162}
163
164impl SplitProjection {
165    pub fn unprojected(table_schema: &TableSchema) -> Self {
166        let projection = ProjectionExprs::from_indices(
167            &(0..table_schema.table_schema().fields().len()).collect_vec(),
168            table_schema.table_schema(),
169        );
170        Self::new(table_schema.file_schema(), &projection)
171    }
172
173    /// Creates a new [`SplitProjection`] by splitting a projection into
174    /// simple file column indices and a remainder projection that is applied after reading the file.
175    ///
176    /// In other words: we get a `Vec<usize>` projection that is meant to be applied on top of `file_schema`
177    /// and a remainder projection that is applied to the result of that first projection.
178    ///
179    /// Here `file_schema` is expected to be the *logical* schema of the file, that is the
180    /// table schema minus any partition columns.
181    /// Partition columns are always expected to be at the end of the table schema.
182    /// Note that `file_schema` is *not* the physical schema of the file.
183    pub fn new(logical_file_schema: &Schema, projection: &ProjectionExprs) -> Self {
184        let num_file_schema_columns = logical_file_schema.fields().len();
185
186        // Collect all unique columns and classify as file or partition
187        let mut file_columns = Vec::new();
188        let mut partition_columns = Vec::new();
189        let mut all_columns = std::collections::HashMap::new();
190
191        // Extract all unique column references (index -> name)
192        for proj_expr in projection {
193            proj_expr
194                .expr
195                .apply(|expr| {
196                    if let Some(column) = expr.downcast_ref::<Column>() {
197                        all_columns
198                            .entry(column.index())
199                            .or_insert_with(|| column.name().to_string());
200                    }
201                    Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
202                })
203                .expect("infallible apply");
204        }
205
206        // Sort by index and classify into file vs partition columns
207        let mut sorted_columns: Vec<_> = all_columns
208            .into_iter()
209            .map(|(idx, name)| (name, idx))
210            .collect();
211        sorted_columns.sort_by_key(|(_, idx)| *idx);
212
213        // Separate file and partition columns, assigning final indices
214        // Pre-create all remapped columns to avoid duplicate Arc'd expressions
215        let mut column_mapping =
216            std::collections::HashMap::with_capacity(sorted_columns.len());
217        let mut file_idx = 0;
218        let mut partition_idx = 0;
219
220        for (name, original_index) in sorted_columns {
221            let new_index = if original_index < num_file_schema_columns {
222                // File column: gets index [0..num_file_columns)
223                file_columns.push(original_index);
224                let idx = file_idx;
225                file_idx += 1;
226                idx
227            } else {
228                // Partition column: gets index [num_file_columns..)
229                partition_columns.push(original_index);
230                let idx = file_idx + partition_idx;
231                partition_idx += 1;
232                idx
233            };
234
235            // Pre-create the remapped column so all references can share the same Arc
236            let new_column: Arc<dyn datafusion_physical_plan::PhysicalExpr> =
237                Arc::new(Column::new(&name, new_index));
238            column_mapping.insert(original_index, new_column);
239        }
240
241        // Single tree transformation: remap all column references using pre-created columns
242        let remapped_projection = projection
243            .iter()
244            .map(|proj_expr| {
245                let expr = Arc::clone(&proj_expr.expr)
246                    .transform(|expr| {
247                        let original_expr = Arc::clone(&expr);
248                        if let Some(column) = expr.downcast_ref::<Column>()
249                            && let Some(new_column) = column_mapping.get(&column.index())
250                        {
251                            return Ok(Transformed::yes(Arc::clone(new_column)));
252                        }
253                        Ok(Transformed::no(original_expr))
254                    })
255                    .data()
256                    .expect("infallible transform");
257                ProjectionExpr::new(expr, proj_expr.alias.clone())
258            })
259            .collect_vec();
260
261        // Pre-compute partition column mappings for ProjectionOpener
262        let num_file_columns = file_columns.len();
263        let partition_column_mappings = partition_columns
264            .iter()
265            .enumerate()
266            .map(|(partition_idx, &table_index)| PartitionColumnIndex {
267                in_remainder_projection: num_file_columns + partition_idx,
268                in_partition_values: table_index - num_file_schema_columns,
269            })
270            .collect_vec();
271
272        Self {
273            source: projection.clone(),
274            file_indices: file_columns,
275            partition_columns: partition_column_mappings,
276            remapped_projection: ProjectionExprs::from(remapped_projection),
277        }
278    }
279}
280
281#[cfg(test)]
282mod test {
283    use std::sync::Arc;
284
285    use arrow::array::{AsArray, RecordBatch, record_batch};
286    use arrow::datatypes as arrow_schema;
287    use arrow::datatypes::{DataType, Field, SchemaRef};
288    use datafusion_common::{DFSchema, ScalarValue, config::ConfigOptions};
289    use datafusion_expr::{
290        Expr, ScalarUDF, col, execution_props::ExecutionProps,
291        physical_planning_context::PhysicalPlanningContext,
292    };
293    use datafusion_functions::core::input_file_name::InputFileNameFunc;
294    use datafusion_physical_expr::{
295        ScalarFunctionExpr, create_physical_exprs, projection::ProjectionExpr,
296    };
297    use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
298    use futures::{FutureExt, StreamExt};
299    use itertools::Itertools;
300
301    use super::*;
302
303    struct StaticBatchOpener {
304        batch: RecordBatch,
305    }
306
307    impl FileOpener for StaticBatchOpener {
308        fn open(&self, _partitioned_file: PartitionedFile) -> Result<FileOpenFuture> {
309            let batch = self.batch.clone();
310            Ok(async move { Ok(futures::stream::iter([Ok(batch)]).boxed()) }.boxed())
311        }
312    }
313
314    fn create_projection_exprs<'a>(
315        exprs: impl IntoIterator<Item = &'a Expr>,
316        schema: &SchemaRef,
317    ) -> ProjectionExprs {
318        let df_schema = DFSchema::try_from(Arc::clone(schema)).unwrap();
319        let physical_exprs = create_physical_exprs(
320            exprs,
321            &df_schema,
322            &ExecutionProps::default(),
323            &PhysicalPlanningContext::default(),
324        )
325        .unwrap();
326        let projection_exprs = physical_exprs
327            .into_iter()
328            .enumerate()
329            .map(|(i, e)| ProjectionExpr::new(Arc::clone(&e), format!("col{i}")))
330            .collect_vec();
331        ProjectionExprs::from(projection_exprs)
332    }
333
334    fn input_file_name_expr() -> Arc<dyn PhysicalExpr> {
335        Arc::new(ScalarFunctionExpr::new(
336            "input_file_name",
337            Arc::new(ScalarUDF::from(InputFileNameFunc::new())),
338            vec![],
339            Arc::new(Field::new("input_file_name", DataType::Utf8, true)),
340            Arc::new(ConfigOptions::default()),
341        ))
342    }
343
344    #[tokio::test]
345    async fn test_projection_opener_rewrites_input_file_name_with_partitions() {
346        let file_schema = Schema::new(vec![Field::new("value", DataType::Int32, false)]);
347        let projection = ProjectionExprs::new([
348            ProjectionExpr::new(Arc::new(Column::new("value", 0)), "value"),
349            ProjectionExpr::new(Arc::new(Column::new("part", 1)), "part"),
350            ProjectionExpr::new(input_file_name_expr(), "file_name"),
351        ]);
352        let split = SplitProjection::new(&file_schema, &projection);
353        let input_batch =
354            record_batch!(("value", Int32, vec![10, 20])).expect("input batch");
355
356        let opener = ProjectionOpener::try_new(
357            split,
358            Arc::new(StaticBatchOpener { batch: input_batch }),
359            &file_schema,
360        )
361        .expect("projection opener");
362
363        let mut file = PartitionedFile::new("part=west/data.csv", 100);
364        file.partition_values = vec![ScalarValue::from("west")];
365        let mut stream = opener
366            .open(file)
367            .expect("open projection")
368            .await
369            .expect("inner stream");
370        let batch = stream
371            .next()
372            .await
373            .expect("one projected batch")
374            .expect("projected batch");
375        assert!(stream.next().await.is_none());
376
377        assert_eq!(batch.schema().field(0).name(), "value");
378        assert_eq!(batch.schema().field(1).name(), "part");
379        assert_eq!(batch.schema().field(2).name(), "file_name");
380
381        let values = batch
382            .column(0)
383            .as_primitive::<arrow::datatypes::Int32Type>();
384        assert_eq!(values.value(0), 10);
385        assert_eq!(values.value(1), 20);
386
387        let parts = batch.column(1).as_string::<i32>();
388        assert_eq!(parts.value(0), "west");
389        assert_eq!(parts.value(1), "west");
390
391        let file_names = batch.column(2).as_string::<i32>();
392        assert_eq!(file_names.value(0), "part=west/data.csv");
393        assert_eq!(file_names.value(1), "part=west/data.csv");
394    }
395
396    #[test]
397    fn test_split_projection_with_partition_columns() {
398        use arrow::array::AsArray;
399        use arrow::datatypes::Field;
400        // Simulate the avro_exec_with_partition test scenario:
401        // file_schema has 3 fields
402        let file_schema = Arc::new(Schema::new(vec![
403            Field::new("id", DataType::Int32, false),
404            Field::new("bool_col", DataType::Boolean, false),
405            Field::new("tinyint_col", DataType::Int8, false),
406        ]));
407
408        // table_schema has 4 fields (3 file + 1 partition)
409        let table_schema = Arc::new(Schema::new(vec![
410            Field::new("id", DataType::Int32, false),
411            Field::new("bool_col", DataType::Boolean, false),
412            Field::new("tinyint_col", DataType::Int8, false),
413            Field::new("date", DataType::Utf8, false), // partition column at index 3
414        ]));
415
416        // projection indices: [0, 1, 3, 2]
417        // This should select: id (0), bool_col (1), date (3-partition), tinyint_col (2)
418        let projection_indices = vec![0, 1, 3, 2];
419
420        // Create projection expressions from indices using the table schema
421        let projection =
422            ProjectionExprs::from_indices(&projection_indices, &table_schema);
423
424        // Call SplitProjection to separate file and partition columns
425        let split = SplitProjection::new(&file_schema, &projection);
426
427        // The file_indices should be [0, 1, 2] (all file columns needed)
428        assert_eq!(split.file_indices, vec![0, 1, 2]);
429
430        // Should have 1 partition column at in_partition_values index 0
431        assert_eq!(split.partition_columns.len(), 1);
432        assert_eq!(split.partition_columns[0].in_partition_values, 0);
433
434        // Now create a batch with only the file columns
435        let file_batch = record_batch!(
436            ("id", Int32, vec![4]),
437            ("bool_col", Boolean, vec![true]),
438            ("tinyint_col", Int8, vec![0])
439        )
440        .unwrap();
441
442        // After the fix, the remainder projection should have remapped indices:
443        // - File columns: [0, 1, 2] (unchanged since they're already in order)
444        // - Partition column: [3] (stays at index 3, which is >= num_file_columns)
445        // So the remainder expects input columns [0, 1, 2] and references column [3] for partition
446
447        // Verify that we can inject partition columns and apply the projection
448        let partition_values = vec![ScalarValue::from("2021-10-26")];
449
450        // Create partition column mapping
451        let partition_columns = vec![PartitionColumnIndex {
452            in_remainder_projection: 3, // partition column is at index 3 in remainder
453            in_partition_values: 0,     // first partition value
454        }];
455
456        // Inject partition columns (replaces Column(3) with Literal)
457        let injected_projection = inject_partition_columns_into_projection(
458            &split.remapped_projection,
459            &partition_columns,
460            partition_values,
461        );
462
463        // Now the projection should work on the file batch
464        let projector = injected_projection
465            .make_projector(&file_batch.schema())
466            .unwrap();
467        let result = projector.project_batch(&file_batch).unwrap();
468
469        // Verify the output has the correct column order: id, bool_col, date, tinyint_col
470        assert_eq!(result.num_columns(), 4);
471        assert_eq!(
472            result
473                .column(0)
474                .as_primitive::<arrow::datatypes::Int32Type>()
475                .value(0),
476            4
477        );
478        assert!(result.column(1).as_boolean().value(0));
479        assert_eq!(result.column(2).as_string::<i32>().value(0), "2021-10-26");
480        assert_eq!(
481            result
482                .column(3)
483                .as_primitive::<arrow::datatypes::Int8Type>()
484                .value(0),
485            0
486        );
487    }
488
489    // ========================================================================
490    // Comprehensive Test Suite for SplitProjection
491    // ========================================================================
492
493    // Helper to create test schemas with file and partition columns
494    fn create_test_schemas(
495        file_cols: usize,
496        partition_cols: usize,
497    ) -> (SchemaRef, SchemaRef) {
498        use arrow::datatypes::Field;
499
500        let file_fields: Vec<_> = (0..file_cols)
501            .map(|i| Field::new(format!("col_{i}"), DataType::Int32, false))
502            .collect();
503
504        let mut table_fields = file_fields.clone();
505        table_fields.extend(
506            (0..partition_cols)
507                .map(|i| Field::new(format!("part_{i}"), DataType::Utf8, false)),
508        );
509
510        (
511            Arc::new(Schema::new(file_fields)),
512            Arc::new(Schema::new(table_fields)),
513        )
514    }
515
516    // ========================================================================
517    // Partition Column Handling Tests
518    // ========================================================================
519
520    #[test]
521    fn test_split_projection_only_file_columns() {
522        let (file_schema, table_schema) = create_test_schemas(3, 2);
523        // Select only file columns [0, 1, 2]
524        let projection = ProjectionExprs::from_indices(&[0, 1, 2], &table_schema);
525
526        let split = SplitProjection::new(&file_schema, &projection);
527
528        assert_eq!(split.file_indices, vec![0, 1, 2]);
529        assert_eq!(split.partition_columns.len(), 0);
530    }
531
532    #[test]
533    fn test_split_projection_only_partition_columns() {
534        let (file_schema, table_schema) = create_test_schemas(3, 2);
535        // Select only partition columns [3, 4]
536        let projection = ProjectionExprs::from_indices(&[3, 4], &table_schema);
537
538        let split = SplitProjection::new(&file_schema, &projection);
539
540        assert_eq!(split.file_indices, Vec::<usize>::new());
541        assert_eq!(split.partition_columns.len(), 2);
542        assert_eq!(split.partition_columns[0].in_partition_values, 0);
543        assert_eq!(split.partition_columns[1].in_partition_values, 1);
544    }
545
546    #[test]
547    fn test_split_projection_multiple_partition_columns() {
548        let (file_schema, table_schema) = create_test_schemas(2, 3);
549        // File cols: 0, 1; Partition cols: 2, 3, 4
550        // Select: [0, 2, 4, 1, 3] (mixed file and partition)
551        let projection = ProjectionExprs::from_indices(&[0, 2, 4, 1, 3], &table_schema);
552
553        let split = SplitProjection::new(&file_schema, &projection);
554
555        assert_eq!(split.file_indices, vec![0, 1]);
556        assert_eq!(split.partition_columns.len(), 3);
557        assert_eq!(split.partition_columns[0].in_partition_values, 0);
558        assert_eq!(split.partition_columns[1].in_partition_values, 1);
559        assert_eq!(split.partition_columns[2].in_partition_values, 2);
560
561        // Verify remapped projection has correct indices
562        // File columns should be at [0, 1], partition columns at [2, 3, 4]
563        assert_eq!(split.remapped_projection.iter().count(), 5);
564    }
565
566    #[test]
567    fn test_split_projection_partition_columns_reverse_order() {
568        let (file_schema, table_schema) = create_test_schemas(2, 2);
569        // File cols: 0, 1; Partition cols: 2, 3
570        // Select: [3, 2] (partitions in reverse)
571        let projection = ProjectionExprs::from_indices(&[3, 2], &table_schema);
572
573        let split = SplitProjection::new(&file_schema, &projection);
574
575        assert_eq!(split.file_indices, Vec::<usize>::new());
576        assert_eq!(split.partition_columns.len(), 2);
577        assert_eq!(split.partition_columns[0].in_partition_values, 0);
578        assert_eq!(split.partition_columns[1].in_partition_values, 1);
579    }
580
581    #[test]
582    fn test_split_projection_interleaved_file_and_partition() {
583        let (file_schema, table_schema) = create_test_schemas(3, 3);
584        // File cols: 0, 1, 2; Partition cols: 3, 4, 5
585        // Select: [0, 3, 1, 4, 2, 5] (alternating)
586        let projection =
587            ProjectionExprs::from_indices(&[0, 3, 1, 4, 2, 5], &table_schema);
588
589        let split = SplitProjection::new(&file_schema, &projection);
590
591        assert_eq!(split.file_indices, vec![0, 1, 2]);
592        assert_eq!(split.partition_columns.len(), 3);
593        assert_eq!(split.partition_columns[0].in_partition_values, 0);
594        assert_eq!(split.partition_columns[1].in_partition_values, 1);
595        assert_eq!(split.partition_columns[2].in_partition_values, 2);
596    }
597
598    #[test]
599    fn test_split_projection_expression_with_file_and_partition_columns() {
600        use arrow::datatypes::Field;
601
602        // Create schemas: 2 file columns, 1 partition column
603        let file_schema = Arc::new(Schema::new(vec![
604            Field::new("file_a", DataType::Int32, false),
605            Field::new("file_b", DataType::Int32, false),
606        ]));
607        let table_schema = Arc::new(Schema::new(vec![
608            Field::new("file_a", DataType::Int32, false),
609            Field::new("file_b", DataType::Int32, false),
610            Field::new("part_c", DataType::Int32, false),
611        ]));
612
613        // Create expression: file_a + part_c
614        let exprs = [col("file_a") + col("part_c")];
615        let projection = create_projection_exprs(exprs.iter(), &table_schema);
616
617        let split = SplitProjection::new(&file_schema, &projection);
618
619        // Should extract both columns
620        assert_eq!(split.file_indices, vec![0]);
621        assert_eq!(split.partition_columns.len(), 1);
622        assert_eq!(split.partition_columns[0].in_partition_values, 0);
623    }
624
625    // ========================================================================
626    // Category 4: Boundary Conditions
627    // ========================================================================
628
629    #[test]
630    fn test_split_projection_boundary_last_file_column() {
631        let (file_schema, table_schema) = create_test_schemas(3, 2);
632        // Last file column is index 2
633        let projection = ProjectionExprs::from_indices(&[2], &table_schema);
634
635        let split = SplitProjection::new(&file_schema, &projection);
636
637        assert_eq!(split.file_indices, vec![2]);
638        assert_eq!(split.partition_columns.len(), 0);
639    }
640
641    #[test]
642    fn test_split_projection_boundary_first_partition_column() {
643        let (file_schema, table_schema) = create_test_schemas(3, 2);
644        // First partition column is index 3
645        let projection = ProjectionExprs::from_indices(&[3], &table_schema);
646
647        let split = SplitProjection::new(&file_schema, &projection);
648
649        assert_eq!(split.file_indices, Vec::<usize>::new());
650        assert_eq!(split.partition_columns.len(), 1);
651        assert_eq!(split.partition_columns[0].in_partition_values, 0);
652    }
653
654    // ========================================================================
655    // Category 6: Integration Tests
656    // ========================================================================
657
658    #[test]
659    fn test_inject_partition_columns_multiple_partitions() {
660        let data =
661            record_batch!(("col_0", Int32, vec![1]), ("col_1", Int32, vec![2])).unwrap();
662
663        // Create projection that references file columns and partition columns
664        let (file_schema, table_schema) = create_test_schemas(2, 2);
665        // Projection: [0, 2, 1, 3] = [file_0, part_0, file_1, part_1]
666        let projection = ProjectionExprs::from_indices(&[0, 2, 1, 3], &table_schema);
667        let split = SplitProjection::new(&file_schema, &projection);
668
669        // Create partition column mappings
670        let partition_columns = vec![
671            PartitionColumnIndex {
672                in_remainder_projection: 2, // First partition column at index 2
673                in_partition_values: 0,
674            },
675            PartitionColumnIndex {
676                in_remainder_projection: 3, // Second partition column at index 3
677                in_partition_values: 1,
678            },
679        ];
680
681        let partition_values =
682            vec![ScalarValue::from("part_a"), ScalarValue::from("part_b")];
683
684        let injected = inject_partition_columns_into_projection(
685            &split.remapped_projection,
686            &partition_columns,
687            partition_values,
688        );
689
690        // Apply projection
691        let projector = injected.make_projector(&data.schema()).unwrap();
692        let result = projector.project_batch(&data).unwrap();
693
694        assert_eq!(result.num_columns(), 4);
695        assert_eq!(
696            result
697                .column(0)
698                .as_primitive::<arrow::datatypes::Int32Type>()
699                .value(0),
700            1
701        );
702        assert_eq!(result.column(1).as_string::<i32>().value(0), "part_a");
703        assert_eq!(
704            result
705                .column(2)
706                .as_primitive::<arrow::datatypes::Int32Type>()
707                .value(0),
708            2
709        );
710        assert_eq!(result.column(3).as_string::<i32>().value(0), "part_b");
711    }
712}