csv-validation 0.0.11__tar.gz → 0.0.12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -83,7 +83,7 @@ dependencies = [
83
83
 
84
84
  [[package]]
85
85
  name = "csv_validation"
86
- version = "0.0.11"
86
+ version = "0.0.12"
87
87
  dependencies = [
88
88
  "csv",
89
89
  "flate2",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "csv_validation"
3
- version = "0.0.11"
3
+ version = "0.0.12"
4
4
  edition = "2021"
5
5
 
6
6
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -0,0 +1 @@
1
+ include csv_validation.pyi
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csv_validation
3
- Version: 0.0.11
3
+ Version: 0.0.12
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -12,17 +12,18 @@ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
12
12
 
13
13
  Blazing fast format validations for your CSV files
14
14
 
15
- This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in few minutes for really huge files) using a minimal amount of memory.
15
+ This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in a few minutes for really huge files) using a minimal amount of memory.
16
16
 
17
17
  ## Features
18
18
 
19
19
  - ✨ Validate both plain and gzipped CSV files
20
20
  - 🔍 Multiple validation types supported:
21
+ - Correct column name and order
21
22
  - Regular expressions
22
- - Minimum/Maximum value checks
23
+ - Well-known formats (integer, decimal, etc.)
24
+ - Minimum/Maximum numerical value checks
23
25
  - Value set validation (allowed values)
24
- - Column name and order validation
25
- - 🐍 Python bindings included
26
+ - 🦀 + 🐍 Rust lib with Python bindings included
26
27
  - 📝 Detailed validation summaries with sample invalid values
27
28
  - 🚀 High performance with optimizations like regex pre-compilation
28
29
  - 📊 Support for large CSV files
@@ -68,7 +69,7 @@ is_valid = validator.validate("data.csv")
68
69
 
69
70
  ### Validation Definition Format
70
71
 
71
- Create a small, easy to read YAML file with your validation rules. Example:
72
+ Create a small, easy-to-read YAML file with your validation rules. Example:
72
73
 
73
74
  ```yaml
74
75
  columns:
@@ -98,12 +99,17 @@ columns:
98
99
  - Validate fields against custom regex patterns
99
100
 
100
101
  2. **Format** (`format`)
101
- - Predefined formats for common validations
102
+ - Predefined formats for common validations (This is the recommended way to validate numeric fields)
103
+ - In the background, the library uses regex patterns to validate formats.
102
104
  - Available formats:
103
105
  - `integer`: Validates any integer number (positive or negative)
104
- - `positive_integer`: Validates positive integer numbers
106
+ - `positive integer`: Validates positive integer numbers
107
+ - `decimal`: Validates any decimal number (positive or negative) using point as decimal separator
108
+ - `positive decimal point/positive decimal`: Validates positive decimal numbers using point as decimal separator
109
+ - `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
110
+ - `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
105
111
  - `non_empty`: Validates that field contains at least one character
106
- - More formats will be added in next versions
112
+ - More formats will be added in upcoming versions
107
113
 
108
114
  3. **Minimum Value** (`min`)
109
115
  - Check if numeric fields are greater than or equal to a specified value
@@ -114,6 +120,9 @@ columns:
114
120
  5. **Value Set** (`values`)
115
121
  - Ensure fields only contain values from a predefined set
116
122
 
123
+ You can add as many validations as you want for the same column, but take into account that the
124
+ column only will be considered correct if all the validations are OK.
125
+
117
126
  ## Global Validations
118
127
 
119
128
  ### empty_not_ok
@@ -130,17 +139,7 @@ columns:
130
139
  # other validations...
131
140
  ```
132
141
 
133
- ### Supported Formats
134
-
135
- - `integer`: Any integer number (positive or negative)
136
- - `positive integer`: Any positive integer number
137
- - `decimal`: Any decimal number (positive or negative)
138
- - `positive decimal point`: Any positive decimal number using point as decimal separator
139
- - `positive decimal comma`: Any positive decimal number using comma as decimal separator
140
- - `decimal scientific`: Any decimal number in scientific notation
141
- - `non_empty`: Any non-empty value
142
-
143
- ### Column Separators
142
+ ### Column Separator
144
143
 
145
144
  By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
146
145
 
@@ -150,6 +149,15 @@ validator.set_separator(";") # Use semicolon as separator
150
149
  validator.set_separator("\t") # Use tab as separator
151
150
  ```
152
151
 
152
+ ### Decimal Separator
153
+
154
+ By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
155
+
156
+ ```python
157
+ validator = CSVValidator.from_file("rules.yml")
158
+ validator.set_decimal_separator(",") # Use comma
159
+ ```
160
+
153
161
  ## Error Handling
154
162
 
155
163
  The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
@@ -2,17 +2,18 @@
2
2
 
3
3
  Blazing fast format validations for your CSV files
4
4
 
5
- This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in few minutes for really huge files) using a minimal amount of memory.
5
+ This is a Python lib with a Rust core that will allow you to validate huge CSV files (GBs) in seconds (or in a few minutes for really huge files) using a minimal amount of memory.
6
6
 
7
7
  ## Features
8
8
 
9
9
  - ✨ Validate both plain and gzipped CSV files
10
10
  - 🔍 Multiple validation types supported:
11
+ - Correct column name and order
11
12
  - Regular expressions
12
- - Minimum/Maximum value checks
13
+ - Well-known formats (integer, decimal, etc.)
14
+ - Minimum/Maximum numerical value checks
13
15
  - Value set validation (allowed values)
14
- - Column name and order validation
15
- - 🐍 Python bindings included
16
+ - 🦀 + 🐍 Rust lib with Python bindings included
16
17
  - 📝 Detailed validation summaries with sample invalid values
17
18
  - 🚀 High performance with optimizations like regex pre-compilation
18
19
  - 📊 Support for large CSV files
@@ -58,7 +59,7 @@ is_valid = validator.validate("data.csv")
58
59
 
59
60
  ### Validation Definition Format
60
61
 
61
- Create a small, easy to read YAML file with your validation rules. Example:
62
+ Create a small, easy-to-read YAML file with your validation rules. Example:
62
63
 
63
64
  ```yaml
64
65
  columns:
@@ -88,12 +89,17 @@ columns:
88
89
  - Validate fields against custom regex patterns
89
90
 
90
91
  2. **Format** (`format`)
91
- - Predefined formats for common validations
92
+ - Predefined formats for common validations (This is the recommended way to validate numeric fields)
93
+ - In the background, the library uses regex patterns to validate formats.
92
94
  - Available formats:
93
95
  - `integer`: Validates any integer number (positive or negative)
94
- - `positive_integer`: Validates positive integer numbers
96
+ - `positive integer`: Validates positive integer numbers
97
+ - `decimal`: Validates any decimal number (positive or negative) using point as decimal separator
98
+ - `positive decimal point/positive decimal`: Validates positive decimal numbers using point as decimal separator
99
+ - `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
100
+ - `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
95
101
  - `non_empty`: Validates that field contains at least one character
96
- - More formats will be added in next versions
102
+ - More formats will be added in upcoming versions
97
103
 
98
104
  3. **Minimum Value** (`min`)
99
105
  - Check if numeric fields are greater than or equal to a specified value
@@ -104,6 +110,9 @@ columns:
104
110
  5. **Value Set** (`values`)
105
111
  - Ensure fields only contain values from a predefined set
106
112
 
113
+ You can add as many validations as you want for the same column, but take into account that the
114
+ column only will be considered correct if all the validations are OK.
115
+
107
116
  ## Global Validations
108
117
 
109
118
  ### empty_not_ok
@@ -120,17 +129,7 @@ columns:
120
129
  # other validations...
121
130
  ```
122
131
 
123
- ### Supported Formats
124
-
125
- - `integer`: Any integer number (positive or negative)
126
- - `positive integer`: Any positive integer number
127
- - `decimal`: Any decimal number (positive or negative)
128
- - `positive decimal point`: Any positive decimal number using point as decimal separator
129
- - `positive decimal comma`: Any positive decimal number using comma as decimal separator
130
- - `decimal scientific`: Any decimal number in scientific notation
131
- - `non_empty`: Any non-empty value
132
-
133
- ### Column Separators
132
+ ### Column Separator
134
133
 
135
134
  By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
136
135
 
@@ -140,6 +139,15 @@ validator.set_separator(";") # Use semicolon as separator
140
139
  validator.set_separator("\t") # Use tab as separator
141
140
  ```
142
141
 
142
+ ### Decimal Separator
143
+
144
+ By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
145
+
146
+ ```python
147
+ validator = CSVValidator.from_file("rules.yml")
148
+ validator.set_decimal_separator(",") # Use comma
149
+ ```
150
+
143
151
  ## Error Handling
144
152
 
145
153
  The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
@@ -0,0 +1,13 @@
1
+ class CSVValidator:
2
+
3
+ @staticmethod
4
+ def from_file(definition_path: str) -> CSVValidator: ...
5
+
6
+ @staticmethod
7
+ def from_string(definition_string: str) -> CSVValidator: ...
8
+
9
+ def set_separator(self, separator: str): ...
10
+
11
+ def set_decimal_separator(self, decimal_separator: str): ...
12
+
13
+ def validate(self, file_path: str) -> bool: ...
@@ -76,6 +76,26 @@ struct ColumnValidationsSummary {
76
76
  validation_summaries: Vec<ValidationSummary>
77
77
  }
78
78
 
79
+ #[derive(Serialize, Deserialize)]
80
+ struct FileValidationSummary {
81
+ file_path: String,
82
+ total_rows: usize,
83
+ total_columns: usize,
84
+ correct_columns: Vec<ColumnValidationsSummary>,
85
+ wrong_columns: Vec<ColumnValidationsSummary>
86
+ }
87
+
88
+ impl ValidationSummary {
89
+ fn get_wrong_values_details(&self) -> String {
90
+ let wrong_samples = &self.wrong_values_sample
91
+ .iter()
92
+ .map(|s| format!("'{}'", s))
93
+ .collect::<Vec<String>>()
94
+ .join(",");
95
+ format!("Wrong Rows: {} | Sample: {}", self.wrong_rows, wrong_samples)
96
+ }
97
+ }
98
+
79
99
  fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashMap<String, Vec<ValidationSummary>> {
80
100
  let mut validation_summaries_map = HashMap::new();
81
101
  for validation in validations {
@@ -107,7 +127,7 @@ fn regex_escape(text: &str) -> String {
107
127
  escaped
108
128
  }
109
129
 
110
- /// Infers the file compression type and returns the corresponding buffered reader
130
+ /// Infers the file compression status and returns the corresponding buffered reader
111
131
  fn get_reader_from(path: &str, separator: u8) -> PyResult<Reader<Box<dyn Read>>> {
112
132
  let buf_reader = BufReader::new(File::open(Path::new(path))?);
113
133
  if is_gzip_file(path)? {
@@ -266,6 +286,7 @@ fn get_regex_for_format(format: &str) -> PyResult<String> {
266
286
  }
267
287
 
268
288
  fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
289
+ info!("Validating column names and order...");
269
290
  let expected_column_names = validations.iter()
270
291
  .map(|v| v.column_name.clone())
271
292
  .collect::<Vec<String>>();
@@ -317,12 +338,28 @@ impl CSVValidator {
317
338
  }
318
339
 
319
340
  #[staticmethod]
341
+ #[pyo3(text_signature = "(definition_path)")]
342
+ /// Create a new CSVValidator from a YAML file with the validation definition.
343
+ ///
344
+ /// Args:
345
+ /// definition_path (str): The path to the YAML file with the validation definition.
346
+ ///
347
+ /// Returns:
348
+ /// a CSVValidation instance
320
349
  fn from_file(definition_path: &str) -> PyResult<Self> {
321
350
  let definition_string = fs::read_to_string(definition_path)?;
322
351
  Self::from_string(&definition_string)
323
352
  }
324
353
 
325
354
  #[staticmethod]
355
+ #[pyo3(text_signature = "(definition_string)")]
356
+ /// Create a new CSVValidator from a YAML string with the validation definition.
357
+ ///
358
+ /// Args:
359
+ /// definition_string (str): A string with the YAML validations definition.
360
+ ///
361
+ /// Returns:
362
+ /// a CSVValidation instance
326
363
  fn from_string(definition_string: &str) -> PyResult<Self> {
327
364
  let validations = get_validations(definition_string)?;
328
365
  let mut regex_map = HashMap::new();
@@ -346,6 +383,13 @@ impl CSVValidator {
346
383
  Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR })
347
384
  }
348
385
 
386
+ #[pyo3(text_signature = "(self, separator)")]
387
+ /// Set the CSV separator (also known as delimiter):
388
+ ///
389
+ /// The separator is ',' by default. If your file has a different one, you can modify it here.
390
+ ///
391
+ /// Args:
392
+ /// separator (str): A string with only one character that is the CSV file separator.
349
393
  fn set_separator(&mut self, separator: String) -> PyResult<()> {
350
394
  if separator.len() == 1 {
351
395
  self.separator = separator.chars().next().unwrap() as u8;
@@ -356,6 +400,14 @@ impl CSVValidator {
356
400
  }
357
401
  }
358
402
 
403
+ #[pyo3(text_signature = "(self, decimal_separator)")]
404
+ /// Set the decimal number separator
405
+ ///
406
+ /// The default decimals separator for float numbers is '.'.
407
+ /// If your file uses a different one, you can modify it here.
408
+ ///
409
+ /// Args:
410
+ /// decimal_separator (str): A string with only one character that is the decimal separator.
359
411
  fn set_decimal_separator(&mut self, decimal_separator: String) -> PyResult<()> {
360
412
  if decimal_separator.len() == 1 {
361
413
  self.decimal_separator = decimal_separator.chars().next().unwrap();
@@ -366,6 +418,15 @@ impl CSVValidator {
366
418
  }
367
419
  }
368
420
 
421
+ #[pyo3(text_signature = "(self, file_path)")]
422
+ /// Validates the CSV file against the validations defined in this CSVValidator.
423
+ /// When finished, it will log a comprehensive summary with the details of the Validation.
424
+ ///
425
+ /// Args:
426
+ /// file_path (str): The path with the CSV file to validate.
427
+ ///
428
+ /// Returns:
429
+ /// bool: True if the file fully complies with all the validations, False otherwise
369
430
  fn validate(&self, file_path: &str) -> PyResult<bool> {
370
431
  // Build the CSV reader
371
432
  let mut rdr = get_reader_from(file_path, self.separator)?;
@@ -375,7 +436,7 @@ impl CSVValidator {
375
436
  info!("Columns names and order are correct");
376
437
  }
377
438
  else {
378
- error!("Expected columns != CSV file columns. Cannot continue with the validations");
439
+ error!("Expected columns != File columns. Cannot continue with rest of the validations");
379
440
  return Ok(false);
380
441
  }
381
442
 
@@ -383,6 +444,8 @@ impl CSVValidator {
383
444
  let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
384
445
  let mut is_valid_file = true;
385
446
  let mut validated_rows = 0;
447
+
448
+ // Iterate over the CSV file and validate each row
386
449
  for result in rdr.records() {
387
450
  let record = result.unwrap();
388
451
  for next_column in zip(record.iter(), self.validations.iter()) {
@@ -420,45 +483,57 @@ impl CSVValidator {
420
483
  column_validation_summaries.push(column_validation_summary);
421
484
  }
422
485
 
423
- // TODO: Decide how to return the results of the validations
424
- let _validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
486
+ let validation_process_summary =
487
+ &self.create_validation_process_summary(column_validation_summaries, validated_rows, file_path);
425
488
 
426
- let mut failed_columns = HashMap::new();
489
+ // TODO: Decide how to return the results of the validations in JSON
490
+ //let _validation_result_json = serde_json::to_string(&validation_process_summary).unwrap();
491
+
492
+ info!("");
427
493
  info!("VALIDATIONS SUMMARY");
428
- info!("==================================================================================");
429
- info!("Rows: {} | Columns: {}", validated_rows, column_validation_summaries.len());
430
- for column_validation_summary in column_validation_summaries {
431
- info!("Column: '{}'", column_validation_summary.column_name);
432
- for validation_summary in column_validation_summary.validation_summaries {
433
- let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
434
- format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
435
- } else {
436
- String::from("" )
437
- };
438
- info!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
439
- validation_summary.wrong_rows, wrong_values_sample);
494
+ info!("==================================================");
495
+ info!("FILE: {}", file_path);
496
+ info!("Rows: {} | Columns: {}", validation_process_summary.total_rows, validation_process_summary.total_columns);
497
+
498
+ let correct_columns = validation_process_summary.correct_columns.len();
499
+ let wrong_columns = validation_process_summary.wrong_columns.len();
500
+
501
+ info!("");
502
+ info!("CORRECT COLUMNS: {}/{}", correct_columns, validation_process_summary.total_columns);
503
+ info!("--------------------------------------------------");
504
+ for column_validation_summary in &validation_process_summary.correct_columns {
505
+ info!(" - {}: [✔] OK", column_validation_summary.column_name);
506
+ for validation_summary in column_validation_summary.validation_summaries.iter() {
507
+ info!(" ✔ - {:?}", validation_summary.validation);
508
+ }
509
+ }
510
+
511
+ info!("");
512
+ info!("WRONG COLUMNS: {}/{}", wrong_columns, validation_process_summary.total_columns);
513
+ info!("--------------------------------------------------");
514
+ for column_validation_summary in &validation_process_summary.wrong_columns {
515
+ info!(" - {}: [✖] FAIL", column_validation_summary.column_name);
516
+ for validation_summary in column_validation_summary.validation_summaries.iter() {
440
517
  if validation_summary.wrong_rows > 0 {
441
- let column_name = &column_validation_summary.column_name;
442
- if !failed_columns.contains_key(column_name) {
443
- failed_columns.insert(column_name.clone(), vec!());
444
- }
445
- failed_columns.get_mut(column_name).unwrap().push(validation_summary);
518
+ info!(" ✖ - {:?}", validation_summary.validation);
519
+ info!(" {:?}", validation_summary.get_wrong_values_details());
520
+ }
521
+ else {
522
+ info!(" ✔ - {:?}", validation_summary.validation);
446
523
  }
447
524
  }
448
525
  }
449
526
 
527
+ info!("");
528
+ info!("VALIDATION RESULT");
529
+ info!("--------------------------------------------------");
450
530
  if is_valid_file {
451
- info!("OK: File matches the validations");
531
+ info!("[✔] OK - File matches the validations");
452
532
  }
453
533
  else {
454
- info!("NO OK: File DOESN'T match validations. Failed Validations:");
455
- for (column_name, failed_validations) in failed_columns.into_iter() {
456
- info!("COLUMN '{}' :", column_name);
457
- for validation_summary in failed_validations {
458
- info!("\tValidation {:?} => Wrong Rows: {}", validation_summary.validation, validation_summary.wrong_rows)
459
- }
460
- }
534
+ info!("[✖] FAIL: File DOESN'T match all validations");
461
535
  }
536
+ info!("");
462
537
  Ok(is_valid_file)
463
538
  }
464
539
  }
@@ -503,6 +578,40 @@ impl CSVValidator {
503
578
  Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
504
579
  }
505
580
  }
581
+
582
+ fn create_validation_process_summary(&self, column_validation_summaries: Vec<ColumnValidationsSummary>, validated_rows: usize, file_path: &str) -> FileValidationSummary {
583
+ let total_rows = validated_rows;
584
+ let total_columns = column_validation_summaries.len();
585
+
586
+ let mut failed_columns = HashSet::new();
587
+ let mut correct_columns = vec![];
588
+ let mut wrong_columns = vec![];
589
+ for column_validation_summary in column_validation_summaries {
590
+ for validation_summary in &column_validation_summary.validation_summaries {
591
+ if validation_summary.wrong_rows > 0 {
592
+ let column_name = &column_validation_summary.column_name;
593
+ if !failed_columns.contains(column_name) {
594
+ failed_columns.insert(column_name.clone());
595
+ }
596
+ }
597
+ }
598
+
599
+ if failed_columns.contains(&column_validation_summary.column_name) {
600
+ wrong_columns.push(column_validation_summary);
601
+ }
602
+ else {
603
+ correct_columns.push(column_validation_summary);
604
+ }
605
+ }
606
+
607
+ FileValidationSummary {
608
+ file_path: file_path.parse().unwrap(),
609
+ total_rows,
610
+ total_columns,
611
+ correct_columns,
612
+ wrong_columns
613
+ }
614
+ }
506
615
  }
507
616
 
508
617
  /// A Python module implemented in Rust.
File without changes