Jefffrey commented on code in PR #10361:
URL: https://github.com/apache/arrow-rs/pull/10361#discussion_r3718756509


##########
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:
   I do wonder if this regex should be changed as it seems to go beyond the 
scope of this PR, as it impacts our inference logic



-- 
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]

Reply via email to