You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "EeshanBembi (via GitHub)" <gi...@apache.org> on 2025/09/13 17:36:44 UTC

[PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

EeshanBembi opened a new pull request, #17553:
URL: https://github.com/apache/datafusion/pull/17553

   ## Summary
   
     Enables DataFusion to read directories containing CSV files with
     different numbers of columns by implementing schema union during
     inference.
   
     Previously, attempting to read multiple CSV files with different
     column counts would fail with:
     Arrow error: Csv error: incorrect number of fields for line 1,
     expected 17 got 20
   
     This was particularly problematic for evolving datasets where newer
     files include additional columns (e.g., railway services data where
     newer files added platform information).
   
     ## Changes
   
     - **Enhanced CSV schema inference**: Modified
     `infer_schema_from_stream` to create union schema from all files
     instead of rejecting files with different column counts
     - **Backward compatible**: Existing functionality unchanged,
     requires explicit opt-in via `truncated_rows(true)`
     - **Comprehensive testing**: Added unit tests for schema building
     logic and integration test with real CSV scenarios
   
     ## Usage
   
     ```rust
     // Read CSV directory with mixed column counts
     let df = ctx.read_csv(
         "path/to/csv/directory/",
         CsvReadOptions::new().truncated_rows(true)
     ).await?;
   ```
     Test Results
   
     - ✅ All existing tests pass (368/368 DataFusion lib tests)
     - ✅ All CSV functionality intact (125/125 CSV tests)
     - ✅ New integration test verifies fix with 3-column and 6-column
     CSV files
     - ✅ Schema inference creates union schema with proper null handling
   
     Example
   
     Before this fix:
     - services_2024.csv: 3 columns → ❌ Error when reading together
     - services_2025.csv: 6 columns → ❌ "incorrect number of fields"
   
     After this fix:
     - Both files → ✅ Union schema with 6 columns
     - Missing columns filled with nulls automatically
   
     Closes #17516


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3344500564

   > #17516
   
   Thanks @xudong963, this a further improvement for schema evolution instead of pure truncated_row. We can test internally after this PR merged, this should not affect our use cases.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "EeshanBembi (via GitHub)" <gi...@apache.org>.
EeshanBembi commented on code in PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#discussion_r2361243741


##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -560,21 +573,28 @@ impl CsvFormat {
                     })
                     .unzip();
             } else {
-                if fields.len() != column_type_possibilities.len() {
-                    return exec_err!(
-                            "Encountered unequal lengths between records on CSV file whilst inferring schema. \
-                             Expected {} fields, found {} fields at record {}",
-                            column_type_possibilities.len(),
-                            fields.len(),
-                            record_number + 1
-                        );
+                // Handle files with different numbers of columns by extending the schema
+                if fields.len() > column_type_possibilities.len() {
+                    // New columns found - extend our tracking structures
+                    for field in fields.iter().skip(column_type_possibilities.len()) {
+                        column_names.push(field.name().clone());
+                        let mut possibilities = HashSet::new();
+                        if records_read > 0 {
+                            possibilities.insert(field.data_type().clone());
+                        }
+                        column_type_possibilities.push(possibilities);
+                    }
+                }

Review Comment:
   The current implementation performs positional union (not union by name). Files must have columns in the same order, with later files potentially adding new columns at the end. This is consistent with CSV format which doesn't have inherent column naming, column names come from headers and are positional. Union by name would require a different approach and is not implemented in this PR.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "EeshanBembi (via GitHub)" <gi...@apache.org>.
EeshanBembi commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3348650594

   > I tried the reproducer from #17516 and it still fails on this PR:
   > 
   > Maybe I don't understand how to use it 🤔
   > 
   > ```sql
   > > create external table foo stored as csv location '/Users/andrewlamb/Downloads/services' options ('truncated_rows' true);
   > 0 row(s) fetched.
   > Elapsed 0.021 seconds.
   > 
   > > select * from foo limit 10;
   > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > ```
   > 
   > It also errors if I just try to read the directory directly:
   > 
   > ```sql
   > (venv) andrewlamb@Andrews-MacBook-Pro-3:~/Software/datafusion$ cargo run --bin datafusion-cli
   >     Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
   >      Running `target/debug/datafusion-cli`
   > DataFusion CLI v50.0.0
   > > select * from '/Users/andrewlamb/Downloads/services' limit 10;
   > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > ```
   > 
   > This PR seems like a step in the right direction to me, it just doesn't seem to fix the problem entirely
   > 
   > It sounds like (as follow on issues / PRs) we probably would need to:
   > 
   > 1. Enable schema merging for CSV by default (
   > 2. Implement schema merge using column names (not positions) which is how parquet works, and I think what users would expect.
   
   Hi Andrew! I've reproduced the exact scenario and found the issue. The PR is working correctly for
     external tables, but there's a subtle distinction:
   
     What Works ✅
   
     CREATE EXTERNAL TABLE foo STORED AS CSV LOCATION '/Users/andrewlamb/Downloads/services'
     OPTIONS ('truncated_rows' 'true');  -- Note: 'true' in quotes
     SELECT * FROM foo LIMIT 10;
   
     What Still Fails ❌
   
     SELECT * FROM '/Users/andrewlamb/Downloads/services' LIMIT 10;
   
     The Issue
   
     You were getting the error because:
     1. Direct file path queries (SELECT * FROM '/path') don't support CSV-specific options like
     truncated_rows - this is a separate limitation not addressed by this PR
     2. Option syntax: Make sure to use 'truncated_rows' 'true' (with quotes around true) not
     'truncated_rows' true
   
     Testing
   
     I created files with exactly 17 vs 20 columns and confirmed:
     - ✅ External table with OPTIONS ('truncated_rows' 'true') works perfectly - merges schemas and
     fills missing columns with NULL
     - ❌ Direct path queries still fail with the same error you saw
   
     Summary
   
     This PR does fix the core issue - CSV schema merging with different column counts works via external
      tables. The remaining limitation is that direct file path queries don't yet support format-specific
      options.
   
     If you think direct path query support is important for this PR, I'm happy to investigate adding 
     that functionality here - it would involve enhancing how DataFusion handles table resolution for
     file paths to pass through CSV-specific options. Otherwise, try the external table approach with
     proper option syntax and it should work!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "EeshanBembi (via GitHub)" <gi...@apache.org>.
EeshanBembi commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3363185863

   Hi @alamb — I just wanted to check if you had a chance to see my comment here:
   
   > > I tried the reproducer from #17516 and it still fails on this PR:
   > > Maybe I don't understand how to use it 🤔
   > > ```sql
   > > > create external table foo stored as csv location '/Users/andrewlamb/Downloads/services' options ('truncated_rows' true);
   > > 0 row(s) fetched.
   > > Elapsed 0.021 seconds.
   > > 
   > > > select * from foo limit 10;
   > > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > It also errors if I just try to read the directory directly:
   > > ```sql
   > > (venv) andrewlamb@Andrews-MacBook-Pro-3:~/Software/datafusion$ cargo run --bin datafusion-cli
   > >     Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
   > >      Running `target/debug/datafusion-cli`
   > > DataFusion CLI v50.0.0
   > > > select * from '/Users/andrewlamb/Downloads/services' limit 10;
   > > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > > ```
   > > 
   > > 
   > >     
   > >       
   > >     
   > > 
   > >       
   > >     
   > > 
   > >     
   > >   
   > > This PR seems like a step in the right direction to me, it just doesn't seem to fix the problem entirely
   > > It sounds like (as follow on issues / PRs) we probably would need to:
   > > 
   > > 1. Enable schema merging for CSV by default (
   > > 2. Implement schema merge using column names (not positions) which is how parquet works, and I think what users would expect.
   > 
   > Hi Andrew! I've reproduced the exact scenario and found the issue. The PR is working correctly for external tables, but there's a subtle distinction:
   > 
   > What Works ✅
   > 
   > CREATE EXTERNAL TABLE foo STORED AS CSV LOCATION '/Users/andrewlamb/Downloads/services' OPTIONS ('truncated_rows' 'true'); -- Note: 'true' in quotes SELECT * FROM foo LIMIT 10;
   > 
   > What Still Fails ❌
   > 
   > SELECT * FROM '/Users/andrewlamb/Downloads/services' LIMIT 10;
   > 
   > The Issue
   > 
   > You were getting the error because:
   > 
   > 1. Direct file path queries (SELECT * FROM '/path') don't support CSV-specific options like
   >    truncated_rows - this is a separate limitation not addressed by this PR
   > 2. Option syntax: Make sure to use 'truncated_rows' 'true' (with quotes around true) not
   >    'truncated_rows' true
   > 
   > Testing
   > 
   > I created files with exactly 17 vs 20 columns and confirmed:
   > 
   > * ✅ External table with OPTIONS ('truncated_rows' 'true') works perfectly - merges schemas and
   >   fills missing columns with NULL
   > * ❌ Direct path queries still fail with the same error you saw
   > 
   > Summary
   > 
   > This PR does fix the core issue - CSV schema merging with different column counts works via external tables. The remaining limitation is that direct file path queries don't yet support format-specific options.
   > 
   > If you think direct path query support is important for this PR, I'm happy to investigate adding that functionality here - it would involve enhancing how DataFusion handles table resolution for file paths to pass through CSV-specific options. Otherwise, try the external table approach with proper option syntax and it should work!
   
   
   
   
   Whenever you get a moment, I would really appreciate your thoughts. Thanks! 🙏


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey merged PR #17553:
URL: https://github.com/apache/datafusion/pull/17553


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3379539703

   I'll merge this as is since it is a step in the right direction, though I have edited the description to not close the issue given the discussions above


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3363962427

   > Hi @alamb — I just wanted to check if you had a chance to see my comment here:
   > 
   > > > I tried the reproducer from #17516 and it still fails on this PR:
   > > > Maybe I don't understand how to use it 🤔
   > > > ```sql
   > > > > create external table foo stored as csv location '/Users/andrewlamb/Downloads/services' options ('truncated_rows' true);
   > > > 0 row(s) fetched.
   > > > Elapsed 0.021 seconds.
   > > > 
   > > > > select * from foo limit 10;
   > > > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > > > ```
   > > > 
   > > > 
   > > >     
   > > >       
   > > >     
   > > > 
   > > >       
   > > >     
   > > > 
   > > >     
   > > >   
   > > > It also errors if I just try to read the directory directly:
   > > > ```sql
   > > > (venv) andrewlamb@Andrews-MacBook-Pro-3:~/Software/datafusion$ cargo run --bin datafusion-cli
   > > >     Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
   > > >      Running `target/debug/datafusion-cli`
   > > > DataFusion CLI v50.0.0
   > > > > select * from '/Users/andrewlamb/Downloads/services' limit 10;
   > > > Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   > > > ```
   > > > 
   > > > 
   > > >     
   > > >       
   > > >     
   > > > 
   > > >       
   > > >     
   > > > 
   > > >     
   > > >   
   > > > This PR seems like a step in the right direction to me, it just doesn't seem to fix the problem entirely
   > > > It sounds like (as follow on issues / PRs) we probably would need to:
   > > > 
   > > > 1. Enable schema merging for CSV by default (
   > > > 2. Implement schema merge using column names (not positions) which is how parquet works, and I think what users would expect.
   > > 
   > > 
   > > Hi Andrew! I've reproduced the exact scenario and found the issue. The PR is working correctly for external tables, but there's a subtle distinction:
   > > What Works ✅
   > > CREATE EXTERNAL TABLE foo STORED AS CSV LOCATION '/Users/andrewlamb/Downloads/services' OPTIONS ('truncated_rows' 'true'); -- Note: 'true' in quotes SELECT * FROM foo LIMIT 10;
   > > What Still Fails ❌
   > > SELECT * FROM '/Users/andrewlamb/Downloads/services' LIMIT 10;
   > > The Issue
   > > You were getting the error because:
   > > 
   > > 1. Direct file path queries (SELECT * FROM '/path') don't support CSV-specific options like
   > >    truncated_rows - this is a separate limitation not addressed by this PR
   > > 2. Option syntax: Make sure to use 'truncated_rows' 'true' (with quotes around true) not
   > >    'truncated_rows' true
   > > 
   > > Testing
   > > I created files with exactly 17 vs 20 columns and confirmed:
   > > 
   > > * ✅ External table with OPTIONS ('truncated_rows' 'true') works perfectly - merges schemas and
   > >   fills missing columns with NULL
   > > * ❌ Direct path queries still fail with the same error you saw
   > > 
   > > Summary
   > > This PR does fix the core issue - CSV schema merging with different column counts works via external tables. The remaining limitation is that direct file path queries don't yet support format-specific options.
   > > If you think direct path query support is important for this PR, I'm happy to investigate adding that functionality here - it would involve enhancing how DataFusion handles table resolution for file paths to pass through CSV-specific options. Otherwise, try the external table approach with proper option syntax and it should work!
   > 
   > Whenever you get a moment, I would really appreciate your thoughts. Thanks! 🙏
   
   The quotes around `true` didn't fix it; the `limit 10` you placed on your query prevented it from reading multiple files hence you didn't encounter the error. I don't think the quotes around `true` matters, e.g.
   
   ```sh
   Downloads$ cat truncate.csv
   a,b,c
   1,2,3
   1,2
   1
   1,2,3
   ```
   
   In CLI:
   
   ```sql
   > select * from '/Users/jeffrey/Downloads/truncate.csv';
   Error when processing CSV file Users/jeffrey/Downloads/truncate.csv
   caused by
   Arrow error: Csv error: Encountered unequal lengths between records on CSV file. Expected 3 records, found 2 records at line 3
   > create or replace external table foo stored as csv location '/Users/jeffrey/Downloads/truncate.csv' options ('truncated_rows' 'true');
   0 row(s) fetched.
   Elapsed 0.006 seconds.
   
   > select * from foo;
   +---+------+------+
   | a | b    | c    |
   +---+------+------+
   | 1 | 2    | 3    |
   | 1 | 2    | NULL |
   | 1 | NULL | NULL |
   | 1 | 2    | 3    |
   +---+------+------+
   4 row(s) fetched.
   Elapsed 0.009 seconds.
   
   > create or replace external table foo stored as csv location '/Users/jeffrey/Downloads/truncate.csv' options ('truncated_rows' true);
   0 row(s) fetched.
   Elapsed 0.006 seconds.
   
   > select * from foo;
   +---+------+------+
   | a | b    | c    |
   +---+------+------+
   | 1 | 2    | 3    |
   | 1 | 2    | NULL |
   | 1 | NULL | NULL |
   | 1 | 2    | 3    |
   +---+------+------+
   4 row(s) fetched.
   Elapsed 0.008 seconds.
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3347244624

   I tried the reproducer from https://github.com/apache/datafusion/issues/17516 and it still fails on this PR:
   
   Maybe I don't understand how to use it 🤔 
   
   ```sql
   > create external table foo stored as csv location '/Users/andrewlamb/Downloads/services' options ('truncated_rows' true);
   0 row(s) fetched.
   Elapsed 0.021 seconds.
   
   > select * from foo limit 10;
   Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   ```
   
   It also errors if I just try to read the directory directly:
   ```sql
   (venv) andrewlamb@Andrews-MacBook-Pro-3:~/Software/datafusion$ cargo run --bin datafusion-cli
       Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
        Running `target/debug/datafusion-cli`
   DataFusion CLI v50.0.0
   > select * from '/Users/andrewlamb/Downloads/services' limit 10;
   Arrow error: Csv error: incorrect number of fields for line 1, expected 17 got 20
   ```
   
   
   This PR seems like a step in the right direction to me, it just doesn't seem to fix the problem
   
   It sounds like (as follow on issues / PRs) we probably would need to:
   1. Enable schema merging for CSV by default (
   2. Implement schema merge using column names (not positions) which is how parquet works, and I think what users would expect. 
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3380850830

   Thank you @Jefffrey and @EeshanBembi 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#discussion_r2361380684


##########
datafusion/core/tests/csv_schema_fix_test.rs:
##########
@@ -0,0 +1,167 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Test for CSV schema inference with different column counts (GitHub issue #17516)
+
+use datafusion::error::Result;
+use datafusion::prelude::*;
+use std::fs;
+use tempfile::TempDir;
+
+#[tokio::test]
+async fn test_csv_schema_inference_different_column_counts() -> Result<()> {
+    // Create temporary directory for test files
+    let temp_dir = TempDir::new().expect("Failed to create temp dir");
+    let temp_path = temp_dir.path();
+
+    // Create CSV file 1 with 3 columns (simulating older railway services format)
+    let csv1_content = r#"service_id,route_type,agency_id
+1,bus,agency1
+2,rail,agency2
+3,bus,agency3
+"#;
+    fs::write(temp_path.join("services_2024.csv"), csv1_content)?;
+
+    // Create CSV file 2 with 6 columns (simulating newer railway services format)
+    let csv2_content = r#"service_id,route_type,agency_id,stop_platform_change,stop_planned_platform,stop_actual_platform
+4,rail,agency2,true,Platform A,Platform B
+5,bus,agency1,false,Stop 1,Stop 1
+6,rail,agency3,true,Platform C,Platform D
+"#;
+    fs::write(temp_path.join("services_2025.csv"), csv2_content)?;
+
+    // Create DataFusion context
+    let ctx = SessionContext::new();
+
+    // This should now work (previously would have failed with column count mismatch)
+    // Enable truncated_rows to handle files with different column counts
+    let df = ctx
+        .read_csv(
+            temp_path.to_str().unwrap(),
+            CsvReadOptions::new().truncated_rows(true),
+        )
+        .await
+        .expect("Should successfully read CSV directory with different column counts");
+
+    // Verify the schema contains all 6 columns (union of both files)
+    let df_clone = df.clone();
+    let schema = df_clone.schema();
+    assert_eq!(
+        schema.fields().len(),
+        6,
+        "Schema should contain all 6 columns"
+    );
+
+    // Check that we have all expected columns
+    let field_names: Vec<&str> =
+        schema.fields().iter().map(|f| f.name().as_str()).collect();
+    assert!(field_names.contains(&"service_id"));
+    assert!(field_names.contains(&"route_type"));
+    assert!(field_names.contains(&"agency_id"));
+    assert!(field_names.contains(&"stop_platform_change"));
+    assert!(field_names.contains(&"stop_planned_platform"));
+    assert!(field_names.contains(&"stop_actual_platform"));
+
+    // All fields should be nullable since they don't appear in all files
+    for field in schema.fields() {
+        assert!(
+            field.is_nullable(),
+            "Field {} should be nullable",
+            field.name()
+        );
+    }
+
+    // Verify we can actually read the data
+    let results = df.collect().await?;
+
+    // Calculate total rows across all batches
+    let total_rows: usize = results.iter().map(|batch| batch.num_rows()).sum();
+    assert_eq!(total_rows, 6, "Should have 6 total rows across all batches");
+
+    // All batches should have 6 columns (the union schema)
+    for batch in &results {
+        assert_eq!(batch.num_columns(), 6, "All batches should have 6 columns");
+        assert_eq!(
+            batch.schema().fields().len(),
+            6,
+            "Each batch should use the union schema with 6 fields"
+        );
+    }
+
+    // Verify the actual content of the data
+    // Since we don't know the exact order of rows, just verify the overall structure

Review Comment:
   I suggest using `assert_snapshot!()` macro to check the contents, see a reference here:
   
   https://github.com/apache/datafusion/blob/c1ca3c4d7c97c3c83b1c44fd7d0e3786da863572/datafusion/core/tests/sql/select.rs#L22-L51



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -560,21 +572,27 @@ impl CsvFormat {
                     })
                     .unzip();
             } else {
-                if fields.len() != column_type_possibilities.len() {
-                    return exec_err!(
-                            "Encountered unequal lengths between records on CSV file whilst inferring schema. \
-                             Expected {} fields, found {} fields at record {}",
-                            column_type_possibilities.len(),
-                            fields.len(),
-                            record_number + 1
-                        );

Review Comment:
   Would it be beneficial to keep this error message for when `truncated_rows` config is `false`? What does the error message look like right now if we read CSV files with differing column counts where this new behaviour is not enabled?



##########
datafusion/common/src/config.rs:
##########
@@ -2535,9 +2535,12 @@ config_namespace! {
         // The input regex for Nulls when loading CSVs.
         pub null_regex: Option<String>, default = None
         pub comment: Option<u8>, default = None
-        // Whether to allow truncated rows when parsing.
-        // By default this is set to false and will error if the CSV rows have different lengths.
-        // When set to true then it will allow records with less than the expected number of columns
+        /// Whether to allow CSV files with varying numbers of columns.
+        /// By default this is set to false and will error if the CSV rows have different lengths.
+        /// When set to true:
+        /// - Allows reading multiple CSV files with different column counts
+        /// - Creates a union schema during inference containing all columns found across files
+        /// - Files with fewer columns will have missing columns filled with null values

Review Comment:
   ```suggestion
           /// Whether to allow truncated rows when parsing, both within a single file and across files.
           ///
           /// When set to false (default), reading a single CSV file which has rows of different lengths will
           /// error; if reading multiple CSV files with different number of columns, it will also fail.
           ///
           /// When set to true, reading a single CSV file with rows of different lengths will pad the truncated
           /// rows with null values for the missing columns; if reading multiple CSV files with different number
           /// of columns, it creates a union schema containing all columns found across the files, and will
           /// pad any files missing columns with null values for their rows.
   ```
   
   Just to make it more obvious this config has a dual purpose.



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -560,21 +572,27 @@ impl CsvFormat {
                     })
                     .unzip();
             } else {
-                if fields.len() != column_type_possibilities.len() {
-                    return exec_err!(
-                            "Encountered unequal lengths between records on CSV file whilst inferring schema. \
-                             Expected {} fields, found {} fields at record {}",
-                            column_type_possibilities.len(),
-                            fields.len(),
-                            record_number + 1
-                        );
+                // Handle files with different numbers of columns by extending the schema
+                if fields.len() > column_type_possibilities.len() {
+                    // New columns found - extend our tracking structures
+                    for field in fields.iter().skip(column_type_possibilities.len()) {
+                        column_names.push(field.name().clone());
+                        let mut possibilities = HashSet::new();
+                        if records_read > 0 {
+                            possibilities.insert(field.data_type().clone());
+                        }
+                        column_type_possibilities.push(possibilities);
+                    }
                 }
 
-                column_type_possibilities.iter_mut().zip(&fields).for_each(
-                    |(possibilities, field)| {
-                        possibilities.insert(field.data_type().clone());
-                    },
-                );
+                // Update type possibilities for columns that exist in this file
+                // Only process fields that exist in both the current file and our tracking structures
+                for (field_idx, field) in fields.iter().enumerate() {
+                    if field_idx < column_type_possibilities.len() {
+                        column_type_possibilities[field_idx]
+                            .insert(field.data_type().clone());
+                    }
+                }

Review Comment:
   It might be less confusing if we keep the original code:
   
   ```rust
   column_type_possibilities.iter_mut().zip(&fields).for_each(
       |(possibilities, field)| {
           possibilities.insert(field.data_type().clone());
       },
   );
   ```
   
   But move it before the `Handle files with different numbers of columns by extending the schema` check (since zip will terminate on the shortest iterator), so we first extend possibilities for existing columns, then afterwards add the new columns.
   
   Another way could be to do both in a single iteration; something like
   
   ```
   for idx, field in enumerate(fields)
       if idx < len(possibilities)
           add_possibility
       else
           add_new_field
   ```
   
   Thoughts?



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -587,7 +605,10 @@ impl CsvFormat {
     }
 }
 
-fn build_schema_helper(names: Vec<String>, types: &[HashSet<DataType>]) -> Schema {
+pub(crate) fn build_schema_helper(
+    names: Vec<String>,
+    types: &[HashSet<DataType>],
+) -> Schema {

Review Comment:
   ```suggestion
   fn build_schema_helper(names: Vec<String>, types: &[HashSet<DataType>]) -> Schema {
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#discussion_r2347631214


##########
datafusion/datasource-csv/src/tests.rs:
##########


Review Comment:
   I feel this file can be included at the bottom of `datafusion/datasource-csv/src/file_format.rs` instead of being a separate file, given it unit tests the `build_schema_helper()` function only



##########
datafusion/core/tests/csv_schema_fix_test.rs:
##########
@@ -0,0 +1,110 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Test for CSV schema inference with different column counts (GitHub issue #17516)
+
+use datafusion::error::Result;
+use datafusion::prelude::*;
+use std::fs;
+use tempfile::TempDir;
+
+#[tokio::test]
+async fn test_csv_schema_inference_different_column_counts() -> Result<()> {
+    // Create temporary directory for test files
+    let temp_dir = TempDir::new().expect("Failed to create temp dir");
+    let temp_path = temp_dir.path();
+
+    // Create CSV file 1 with 3 columns (simulating older railway services format)
+    let csv1_content = r#"service_id,route_type,agency_id
+1,bus,agency1
+2,rail,agency2
+3,bus,agency3
+"#;
+    fs::write(temp_path.join("services_2024.csv"), csv1_content)?;
+
+    // Create CSV file 2 with 6 columns (simulating newer railway services format)
+    let csv2_content = r#"service_id,route_type,agency_id,stop_platform_change,stop_planned_platform,stop_actual_platform
+4,rail,agency2,true,Platform A,Platform B
+5,bus,agency1,false,Stop 1,Stop 1
+6,rail,agency3,true,Platform C,Platform D
+"#;
+    fs::write(temp_path.join("services_2025.csv"), csv2_content)?;
+
+    // Create DataFusion context
+    let ctx = SessionContext::new();
+
+    // This should now work (previously would have failed with column count mismatch)
+    // Enable truncated_rows to handle files with different column counts
+    let df = ctx
+        .read_csv(
+            temp_path.to_str().unwrap(), 
+            CsvReadOptions::new().truncated_rows(true)
+        )
+        .await
+        .expect("Should successfully read CSV directory with different column counts");
+
+    // Verify the schema contains all 6 columns (union of both files)
+    let df_clone = df.clone();
+    let schema = df_clone.schema();
+    assert_eq!(schema.fields().len(), 6, "Schema should contain all 6 columns");
+
+    // Check that we have all expected columns
+    let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
+    assert!(field_names.contains(&"service_id"));
+    assert!(field_names.contains(&"route_type"));
+    assert!(field_names.contains(&"agency_id"));
+    assert!(field_names.contains(&"stop_platform_change"));
+    assert!(field_names.contains(&"stop_planned_platform"));
+    assert!(field_names.contains(&"stop_actual_platform"));
+
+    // All fields should be nullable since they don't appear in all files
+    for field in schema.fields() {
+        assert!(
+            field.is_nullable(),
+            "Field {} should be nullable",
+            field.name()
+        );
+    }
+
+    // Verify we can actually read the data
+    let results = df.collect().await?;
+    
+    // Calculate total rows across all batches
+    let total_rows: usize = results.iter().map(|batch| batch.num_rows()).sum();
+    assert_eq!(total_rows, 6, "Should have 6 total rows across all batches");

Review Comment:
   I feel we should assert the actual row contents as well



##########
datafusion/core/tests/csv_schema_fix_test.rs:
##########
@@ -0,0 +1,110 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Test for CSV schema inference with different column counts (GitHub issue #17516)
+
+use datafusion::error::Result;
+use datafusion::prelude::*;
+use std::fs;
+use tempfile::TempDir;
+
+#[tokio::test]
+async fn test_csv_schema_inference_different_column_counts() -> Result<()> {
+    // Create temporary directory for test files
+    let temp_dir = TempDir::new().expect("Failed to create temp dir");
+    let temp_path = temp_dir.path();
+
+    // Create CSV file 1 with 3 columns (simulating older railway services format)
+    let csv1_content = r#"service_id,route_type,agency_id
+1,bus,agency1
+2,rail,agency2
+3,bus,agency3
+"#;
+    fs::write(temp_path.join("services_2024.csv"), csv1_content)?;
+
+    // Create CSV file 2 with 6 columns (simulating newer railway services format)
+    let csv2_content = r#"service_id,route_type,agency_id,stop_platform_change,stop_planned_platform,stop_actual_platform
+4,rail,agency2,true,Platform A,Platform B
+5,bus,agency1,false,Stop 1,Stop 1
+6,rail,agency3,true,Platform C,Platform D
+"#;
+    fs::write(temp_path.join("services_2025.csv"), csv2_content)?;
+
+    // Create DataFusion context
+    let ctx = SessionContext::new();
+
+    // This should now work (previously would have failed with column count mismatch)
+    // Enable truncated_rows to handle files with different column counts
+    let df = ctx
+        .read_csv(
+            temp_path.to_str().unwrap(), 
+            CsvReadOptions::new().truncated_rows(true)
+        )
+        .await
+        .expect("Should successfully read CSV directory with different column counts");
+
+    // Verify the schema contains all 6 columns (union of both files)
+    let df_clone = df.clone();
+    let schema = df_clone.schema();
+    assert_eq!(schema.fields().len(), 6, "Schema should contain all 6 columns");
+
+    // Check that we have all expected columns
+    let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
+    assert!(field_names.contains(&"service_id"));
+    assert!(field_names.contains(&"route_type"));
+    assert!(field_names.contains(&"agency_id"));
+    assert!(field_names.contains(&"stop_platform_change"));
+    assert!(field_names.contains(&"stop_planned_platform"));
+    assert!(field_names.contains(&"stop_actual_platform"));
+
+    // All fields should be nullable since they don't appear in all files
+    for field in schema.fields() {
+        assert!(
+            field.is_nullable(),
+            "Field {} should be nullable",
+            field.name()
+        );
+    }
+
+    // Verify we can actually read the data
+    let results = df.collect().await?;
+    
+    // Calculate total rows across all batches
+    let total_rows: usize = results.iter().map(|batch| batch.num_rows()).sum();
+    assert_eq!(total_rows, 6, "Should have 6 total rows across all batches");
+
+    // All batches should have 6 columns (the union schema)
+    for batch in &results {
+        assert_eq!(batch.num_columns(), 6, "All batches should have 6 columns");
+    }
+
+    // Verify that the union schema is being used correctly
+    // We should be able to find records from both files
+    println!("✅ Successfully read {} record batches with {} total rows", results.len(), total_rows);
+    
+    // Verify schema has all expected columns
+    for batch in &results {
+        assert_eq!(batch.schema().fields().len(), 6, "Each batch should use the union schema with 6 fields");
+    }
+
+    println!("✅ Successfully verified CSV schema inference fix!");
+    println!("   - Read {} files with different column counts (3 vs 6)", temp_dir.path().read_dir().unwrap().count());
+    println!("   - Inferred schema with {} columns", schema.fields().len());
+    println!("   - Processed {} total rows", total_rows);

Review Comment:
   Could we remove these prints, and keep the tests to assert statements only? To cut down on verbosity



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -497,7 +497,20 @@ impl FileFormat for CsvFormat {
 impl CsvFormat {
     /// Return the inferred schema reading up to records_to_read from a
     /// stream of delimited chunks returning the inferred schema and the
-    /// number of lines that were read
+    /// number of lines that were read.
+    ///
+    /// This method now supports CSV files with different numbers of columns.

Review Comment:
   ```suggestion
       /// This method can handle CSV files with different numbers of columns.
   ```



##########
datafusion/core/tests/csv_schema_fix_test.rs:
##########
@@ -0,0 +1,110 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Test for CSV schema inference with different column counts (GitHub issue #17516)
+
+use datafusion::error::Result;
+use datafusion::prelude::*;
+use std::fs;
+use tempfile::TempDir;
+
+#[tokio::test]
+async fn test_csv_schema_inference_different_column_counts() -> Result<()> {
+    // Create temporary directory for test files
+    let temp_dir = TempDir::new().expect("Failed to create temp dir");
+    let temp_path = temp_dir.path();
+
+    // Create CSV file 1 with 3 columns (simulating older railway services format)
+    let csv1_content = r#"service_id,route_type,agency_id
+1,bus,agency1
+2,rail,agency2
+3,bus,agency3
+"#;
+    fs::write(temp_path.join("services_2024.csv"), csv1_content)?;
+
+    // Create CSV file 2 with 6 columns (simulating newer railway services format)
+    let csv2_content = r#"service_id,route_type,agency_id,stop_platform_change,stop_planned_platform,stop_actual_platform
+4,rail,agency2,true,Platform A,Platform B
+5,bus,agency1,false,Stop 1,Stop 1
+6,rail,agency3,true,Platform C,Platform D
+"#;
+    fs::write(temp_path.join("services_2025.csv"), csv2_content)?;
+
+    // Create DataFusion context
+    let ctx = SessionContext::new();
+
+    // This should now work (previously would have failed with column count mismatch)
+    // Enable truncated_rows to handle files with different column counts
+    let df = ctx
+        .read_csv(
+            temp_path.to_str().unwrap(), 
+            CsvReadOptions::new().truncated_rows(true)

Review Comment:
   If we do decide to reuse this existing config option then we should update the documentation for it as we're now repurposing it for something different (albeit similar) in purpose



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -560,21 +573,28 @@ impl CsvFormat {
                     })
                     .unzip();
             } else {
-                if fields.len() != column_type_possibilities.len() {
-                    return exec_err!(
-                            "Encountered unequal lengths between records on CSV file whilst inferring schema. \
-                             Expected {} fields, found {} fields at record {}",
-                            column_type_possibilities.len(),
-                            fields.len(),
-                            record_number + 1
-                        );
+                // Handle files with different numbers of columns by extending the schema
+                if fields.len() > column_type_possibilities.len() {
+                    // New columns found - extend our tracking structures
+                    for field in fields.iter().skip(column_type_possibilities.len()) {
+                        column_names.push(field.name().clone());
+                        let mut possibilities = HashSet::new();
+                        if records_read > 0 {
+                            possibilities.insert(field.data_type().clone());
+                        }
+                        column_type_possibilities.push(possibilities);
+                    }
+                }
+                
+                // Update type possibilities for columns that exist in this file
+                // We take the minimum of fields.len() and column_type_possibilities.len() 
+                // to avoid index out of bounds when a file has fewer columns
+                let max_fields_to_process = fields.len().min(column_type_possibilities.len());

Review Comment:
   Is this minimum strictly necessary? Above we check that if `fields > column_type_possibilities` then `column_type_possibilities` is increased to match `fields`; if `fields < column_type_possibilities` then we only need to iterate over fields anyway



##########
datafusion/datasource-csv/src/file_format.rs:
##########
@@ -560,21 +573,28 @@ impl CsvFormat {
                     })
                     .unzip();
             } else {
-                if fields.len() != column_type_possibilities.len() {
-                    return exec_err!(
-                            "Encountered unequal lengths between records on CSV file whilst inferring schema. \
-                             Expected {} fields, found {} fields at record {}",
-                            column_type_possibilities.len(),
-                            fields.len(),
-                            record_number + 1
-                        );
+                // Handle files with different numbers of columns by extending the schema
+                if fields.len() > column_type_possibilities.len() {
+                    // New columns found - extend our tracking structures
+                    for field in fields.iter().skip(column_type_possibilities.len()) {
+                        column_names.push(field.name().clone());
+                        let mut possibilities = HashSet::new();
+                        if records_read > 0 {
+                            possibilities.insert(field.data_type().clone());
+                        }
+                        column_type_possibilities.push(possibilities);
+                    }
+                }

Review Comment:
   What happens if file A has columns t1, t3 but file B has columns t1, t2, t3?
   
   Do we only allow files having subset of columns of other files in the exact correct order?
   
   AKA we don't support union by name?



##########
datafusion/datasource-csv/src/tests.rs:
##########
@@ -0,0 +1,125 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#[cfg(test)]
+mod tests {
+    use crate::file_format::build_schema_helper;
+    use arrow::datatypes::DataType;
+    use std::collections::HashSet;
+
+    #[test]
+    fn test_build_schema_helper_different_column_counts() {
+        // Test the core schema building logic with different column counts
+        let mut column_names = vec!["col1".to_string(), "col2".to_string(), "col3".to_string()];
+        
+        // Simulate adding two more columns from another file
+        column_names.push("col4".to_string());
+        column_names.push("col5".to_string());
+        
+        let column_type_possibilities = vec![
+            {
+                let mut set = HashSet::new();
+                set.insert(DataType::Int64);
+                set
+            },

Review Comment:
   ```suggestion
               HashSet::from([DataType::Int64])
   ```
   
   FYI, applies for the rest too



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: Support reading CSV files with inconsistent column counts [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17553:
URL: https://github.com/apache/datafusion/pull/17553#issuecomment-3364010908

   I think the problem is the infer schema code runs for a certain number of input rows (configurable via `schema_infer_max_rec`); so if the schema changes across these rows, it gets picked up by this fixed code correctly. However if the schema changes for rows after this limit then we hit the error that @alamb encounters; this makes sense for the DuckDB example in the issue as the dataset is quite massive and it seems the later files change their number of columns, so our default schema inference (1000 rows) doesn't pick up this schema change.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org