Databases
Read CSV records into vld types with the csv crate, every failing row reported with its line.

vld_data::csv reads the records of a csv reader into vld types: the header row names the fields, every row is validated, and every failing row is reported with its line, its cells and the issues.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["csv"] }
csv = "1"
FeatureModuleNotes
csvvld_data::csvcsv 1.x

Example

use vld_data::csv::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String => vld::string().min(2),
        pub zip: String => vld::string().len(5),   // "01234" stays text
        pub age: i64 => vld::number().int().min(18),
        pub score: f64 => vld::number().blank_as(0.0),
    }
}

let data = "name,zip,age,score\nAlice,01234,30,1.5\nB,123,12,\n";
match validate_all::<User, _>(csv::Reader::from_reader(data.as_bytes())) {
    Ok(users) => println!("imported {}", users.len()),
    Err(errors) => {
        for e in &errors {
            // line 3: validation error: ...
            eprintln!("{e}");
        }
    }
}

// Or row by row, keeping the good ones:
for row in rows::<User, _>(csv::Reader::from_reader(data.as_bytes())) {
    match row {
        Ok(user) => println!("{}", user.name),
        Err(RowError { line, record, error }) => eprintln!("line {line}: {record:?}: {error:?}"),
    }
}

API

  • rows::<T, R>(reader) — an iterator of Result<T, RowError>, one item per record.
  • validate_all::<T, R>(reader) — Ok(Vec<T>), or Err(Vec<RowError>) with every failing row.
  • RowError { line, record, error } — line is the 1-based line where the record starts (the header is line 1, a quoted multi-line cell keeps the start line); record holds the cells when the record was read; error is RowErrorKind::Validation(VldError) or RowErrorKind::Csv(csv::Error).

Gotchas

  • Cells are text, coerced like web query strings (vld::schema::coerce_text + parse_coerced): 30 is a number for vld::number() and stays "30" for vld::string(); 01234 is never a number.
  • An empty cell is "". A column that may be blank: .blank_as(default) (a missing column takes the default too).
  • A record with a different number of fields than the header row is a RowErrorKind::Csv error by default; with csv::ReaderBuilder::new().flexible(true) a short record lacks the missing keys (missing_field) and extra cells are ignored.
  • Header columns the schema does not know are ignored.
  • The reader needs a header row (has_headers(true), the default); without one the only item is an error at line 1.
  • A malformed record (invalid UTF-8, wrong field count) does not stop the iteration; an I/O error does.
  • Configure trimming, delimiters and quoting on csv::ReaderBuilder; the module only maps and validates.