peterxcli commented on code in PR #10361:
URL: https://github.com/apache/arrow-rs/pull/10361#discussion_r3651890416
##########
arrow-csv/src/reader/mod.rs:
##########
@@ -351,6 +351,85 @@ impl Format {
self
}
+ /// Infer format settings from the CSV records in `reader`
+ ///
+ /// This currently infers whether the first record is a header. Up to
+ /// `max_records` records after the first record are inspected; if `None`,
all
+ /// records are read. Detection is conservative and returns no header when
the
+ /// sampled records do not provide type evidence.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use arrow_csv::reader::Format;
+ /// use std::io::Cursor;
+ ///
+ /// let csv = "name,count\nalice,1\nbob,2\n";
+ /// let format = Format::default().infer_format(Cursor::new(csv),
Some(10))?;
+ /// let (schema, records_read) = format.infer_schema(Cursor::new(csv),
None)?;
+ ///
+ /// assert_eq!(schema.field(0).name(), "name");
+ /// assert_eq!(records_read, 2);
+ /// # Ok::<_, arrow_schema::ArrowError>(())
+ /// ```
+ pub fn infer_format<R: Read>(
+ mut self,
+ reader: R,
+ max_records: Option<usize>,
+ ) -> Result<Self, ArrowError> {
+ self.header = self.infer_header(reader, max_records)?;
+ Ok(self)
+ }
+
+ /// Infer whether the first CSV record is a header
+ ///
+ /// Inspects up to `max_records` records after the first record. Returns
`true`
+ /// when a value in the first record is text while the remaining values in
the
+ /// same column have a consistent non-text type.
+ fn infer_header<R: Read>(
+ &self,
+ reader: R,
+ max_records: Option<usize>,
+ ) -> Result<bool, ArrowError> {
+ let mut format = self.clone();
+ format.header = false;
+ let mut csv_reader = format.build_reader(reader);
+
+ let mut first_record = StringRecord::new();
+ if !csv_reader
+ .read_record(&mut first_record)
+ .map_err(map_csv_error)?
+ {
+ return Ok(false);
+ }
+
+ let mut first_types = vec![InferredDataType::default();
first_record.len()];
+ for (value, inferred) in first_record.iter().zip(&mut first_types) {
+ if !self.null_regex.is_null(value) {
+ inferred.update(value);
+ }
+ }
Review Comment:
If the file start with `+1\n...`, then it would be consider as header
instead of value because the current regex parser can reconginize and lead the
`+1` fallback to `utf+8`.
https://github.com/apache/arrow-rs/blob/d77010352ddf8706ac6e54a853ed67c7823a148b/arrow-csv/src/reader/mod.rs#L189-L190
for example:
```rust
let csv = "+1\n2\n3\n";
let explicit_schema = Arc::new(Schema::new(vec![Field::new(
"value",
DataType::Int64,
false,
)]));
let explicit_rows: usize = ReaderBuilder::new(explicit_schema)
.build(Cursor::new(csv))
.unwrap()
.map(|batch| batch.unwrap().num_rows())
.sum();
assert_eq!(explicit_rows, 3);
let format = Format::default()
.infer_format(Cursor::new(csv), None)
.unwrap();
let (schema, _) = format.infer_schema(Cursor::new(csv), None).unwrap();
// Would fail
assert_eq!(schema.field(0).name(), "column_1");
}
```
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]