csv-validation 0.0.15__tar.gz → 0.0.17__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.
@@ -45,7 +45,7 @@ jobs:
45
45
  uses: PyO3/maturin-action@v1
46
46
  with:
47
47
  target: ${{ matrix.platform.target }}
48
- args: --release --out dist --find-interpreter
48
+ args: --release --out dist -i python3.10
49
49
  sccache: ${{ !startsWith(github.ref, 'refs/tags/') }}
50
50
  manylinux: auto
51
51
  - name: Upload wheels
@@ -76,7 +76,7 @@ jobs:
76
76
  uses: PyO3/maturin-action@v1
77
77
  with:
78
78
  target: ${{ matrix.platform.target }}
79
- args: --release --out dist --find-interpreter
79
+ args: --release --out dist -i python3.10
80
80
  sccache: ${{ !startsWith(github.ref, 'refs/tags/') }}
81
81
  manylinux: musllinux_1_2
82
82
  - name: Upload wheels
@@ -98,10 +98,13 @@ jobs:
98
98
  - uses: actions/checkout@v4
99
99
  - uses: actions/setup-python@v5
100
100
  with:
101
- python-version: 3.x
101
+ python-version: '3.13'
102
102
  architecture: ${{ matrix.platform.target }}
103
103
  - name: Build wheels
104
104
  uses: PyO3/maturin-action@v1
105
+ env:
106
+ # Compile for newers versions using ABI stable version
107
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY: 1
105
108
  with:
106
109
  target: ${{ matrix.platform.target }}
107
110
  args: --release --out dist --find-interpreter
@@ -130,7 +133,7 @@ jobs:
130
133
  uses: PyO3/maturin-action@v1
131
134
  with:
132
135
  target: ${{ matrix.platform.target }}
133
- args: --release --out dist --find-interpreter
136
+ args: --release --out dist -i python3.10
134
137
  sccache: ${{ !startsWith(github.ref, 'refs/tags/') }}
135
138
  - name: Upload wheels
136
139
  uses: actions/upload-artifact@v4
@@ -83,7 +83,7 @@ dependencies = [
83
83
 
84
84
  [[package]]
85
85
  name = "csv_validation"
86
- version = "0.0.15"
86
+ version = "0.0.17"
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.15"
3
+ version = "0.0.17"
4
4
  edition = "2021"
5
5
  readme = "README.md"
6
6
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csv_validation
3
- Version: 0.0.15
3
+ Version: 0.0.17
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -94,11 +94,15 @@ columns:
94
94
  - Available formats:
95
95
  - `integer`: Validates any integer number (positive or negative)
96
96
  - `positive integer`: Validates positive integer numbers
97
- - `decimal/decimal point`: Validates any decimal number (positive or negative) using point as decimal separator
97
+ - `negative integer`: Validates negative integer numbers
98
+ - `decimal`/`decimal point`: Validates any decimal number (positive or negative) using point as decimal separator
99
+ - `negative decimal point`: Validates negative decimal numbers using point as decimal separator
98
100
  - `decimal comma`: Validates decimal numbers using comma as decimal separator
99
- - `positive decimal point/positive decimal`: Validates positive decimal numbers using point as decimal separator
101
+ - `positive decimal`/`positive decimal point`: Validates positive decimal numbers using point as decimal separator
100
102
  - `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
101
103
  - `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
104
+ - `decimal scientific comma`: Validates decimal numbers in scientific notation using comma as decimal separator
105
+ - `positive decimal scientific`: Validates positive decimal numbers in scientific notation
102
106
  - More formats will be added in upcoming versions
103
107
 
104
108
  3. **Minimum Value** (`min`)
@@ -289,6 +289,8 @@ fn get_regex_for_format(format: &str) -> PyResult<String> {
289
289
  "positive decimal point" | "positive decimal" => Ok(String::from("^$|^\\d+(\\.\\d+)?$")),
290
290
  "positive decimal comma" => Ok(String::from("^$|^\\d+(,\\d+)?$")),
291
291
  "decimal scientific" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$")),
292
+ "decimal scientific comma" => Ok(String::from("^$|^-?\\d+(\\,\\d+)?([eE][-+]?\\d+)?$")),
293
+ "positive decimal scientific" => Ok(String::from("^$|^\\d+(\\.\\d+)?([eE][-+]?\\d+)?$")),
292
294
  _ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
293
295
  }
294
296
  }
@@ -347,7 +349,9 @@ struct CSVValidator {
347
349
  validations: Vec<ColumnValidations>,
348
350
  regex_map: HashMap<String, Regex>,
349
351
  separator: u8,
350
- decimal_separator: char
352
+ decimal_separator: char,
353
+ // Optional list of column names that compose a unique key constraint
354
+ unique_key_columns: Option<Vec<String>>
351
355
  }
352
356
 
353
357
  // Methods Exposed to Python
@@ -359,7 +363,8 @@ impl CSVValidator {
359
363
  validations: Vec::new(),
360
364
  regex_map: HashMap::new(),
361
365
  separator: DEFAULT_COLUMN_SEPARATOR,
362
- decimal_separator: DEFAULT_DECIMAL_SEPARATOR
366
+ decimal_separator: DEFAULT_DECIMAL_SEPARATOR,
367
+ unique_key_columns: None
363
368
  }
364
369
  }
365
370
 
@@ -406,7 +411,28 @@ impl CSVValidator {
406
411
  }
407
412
  }
408
413
 
409
- Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR })
414
+ // Parse optional root-level unique configuration (str or [str])
415
+ let config = YamlLoader::load_from_str(definition_string)
416
+ .map_err(|e| PyRuntimeError::new_err(format!("Invalid YAML format: {}", e)))?;
417
+ let unique_key_columns: Option<Vec<String>> = if !config.is_empty() {
418
+ let unique_yaml = &config[0]["unique"];
419
+ if unique_yaml.is_badvalue() {
420
+ None
421
+ } else if let Some(s) = unique_yaml.as_str() {
422
+ Some(vec![s.to_string()])
423
+ } else if let Some(vec) = unique_yaml.as_vec() {
424
+ let cols = vec.iter().map(|y| {
425
+ y.as_str()
426
+ .ok_or_else(|| PyRuntimeError::new_err("Invalid YAML: 'unique' array must contain only strings"))
427
+ .map(|s| s.to_string())
428
+ }).collect::<PyResult<Vec<String>>>()?;
429
+ if cols.is_empty() { None } else { Some(cols) }
430
+ } else {
431
+ return Err(PyRuntimeError::new_err("Invalid YAML: 'unique' must be a string or an array of strings"));
432
+ }
433
+ } else { None };
434
+
435
+ Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR, unique_key_columns })
410
436
  }
411
437
 
412
438
  #[pyo3(text_signature = "(self, separator)")]
@@ -471,9 +497,51 @@ impl CSVValidator {
471
497
  let mut is_valid_file = true;
472
498
  let mut validated_rows = 0;
473
499
 
500
+ // Prepare unique key tracking if requested
501
+ let mut unique_key_indices: Option<Vec<usize>> = None;
502
+ let mut unique_key_counts: HashMap<String, usize> = HashMap::new();
503
+ let mut duplicated_keys_pretty_counts: HashMap<String, usize> = HashMap::new();
504
+ if let Some(unique_cols) = &self.unique_key_columns {
505
+ // Build header -> index map
506
+ let headers: Vec<String> = rdr.headers().unwrap().iter().map(|s| String::from(s)).collect();
507
+ let mut idxs = Vec::with_capacity(unique_cols.len());
508
+ for col in unique_cols {
509
+ match headers.iter().position(|h| h == col) {
510
+ Some(i) => idxs.push(i),
511
+ None => return Err(PyRuntimeError::new_err(format!("Unique key column '{}' not found among CSV headers", col)))
512
+ }
513
+ }
514
+ unique_key_indices = Some(idxs);
515
+ }
516
+
474
517
  // Iterate over the CSV file and validate each row
475
518
  for result in rdr.records() {
476
519
  let record = result.unwrap();
520
+
521
+ // Unique key check (single-pass)
522
+ if let Some(indices) = &unique_key_indices {
523
+ // Build raw and pretty keys
524
+ let mut raw_parts: Vec<String> = Vec::with_capacity(indices.len());
525
+ let mut pretty_parts: Vec<String> = Vec::with_capacity(indices.len());
526
+ if let Some(unique_cols) = &self.unique_key_columns {
527
+ for (i, idx) in indices.iter().enumerate() {
528
+ let val = record.get(*idx).unwrap_or("");
529
+ raw_parts.push(val.to_string());
530
+ let col_name = &unique_cols[i];
531
+ pretty_parts.push(format!("{}='{}'", col_name, val));
532
+ }
533
+ }
534
+ let raw_key = raw_parts.join("\u{1F}"); // Use non-printable unit separator
535
+ let pretty_key = format!("({})", pretty_parts.join(", "));
536
+ let new_count = unique_key_counts.get(&raw_key).cloned().unwrap_or(0) + 1;
537
+ unique_key_counts.insert(raw_key, new_count);
538
+ if new_count >= 2 {
539
+ let dup_count = duplicated_keys_pretty_counts.get(&pretty_key).cloned().unwrap_or(1) + 1;
540
+ // Store occurrences as the actual total occurrences
541
+ duplicated_keys_pretty_counts.insert(pretty_key, dup_count);
542
+ is_valid_file = false;
543
+ }
544
+ }
477
545
  for next_column in zip(record.iter(), self.validations.iter()) {
478
546
  let value = next_column.0;
479
547
  let _column_name = &next_column.1.column_name;
@@ -523,6 +591,26 @@ impl CSVValidator {
523
591
  info!("FILE: {}", file_path);
524
592
  info!("Rows: {} | Columns: {}", validation_process_summary.total_rows, validation_process_summary.total_columns);
525
593
 
594
+ let mut unique_validation_ok = true;
595
+ // If there are duplicated keys, report them first
596
+ if let Some(_) = &self.unique_key_columns {
597
+ info!("UNIQUE KEY: column(s): {:?}", &self.unique_key_columns);
598
+ if !duplicated_keys_pretty_counts.is_empty() {
599
+ info!("");
600
+ info!("DUPLICATED KEYS");
601
+ info!("--------------------------------------------------");
602
+ for (key, count) in duplicated_keys_pretty_counts.iter() {
603
+ info!(" - {} -> occurrences: {}", key, count);
604
+ }
605
+ unique_validation_ok = false;
606
+ } else {
607
+ info!("");
608
+ info!("UNIQUE KEYS CHECK");
609
+ info!("--------------------------------------------------");
610
+ info!(" - No duplicates found");
611
+ }
612
+ }
613
+
526
614
  let correct_columns = validation_process_summary.correct_columns.len();
527
615
  let wrong_columns = validation_process_summary.wrong_columns.len();
528
616
 
@@ -552,6 +640,9 @@ impl CSVValidator {
552
640
  }
553
641
  }
554
642
 
643
+ // Adding other validation results before returning the final result
644
+ is_valid_file = is_valid_file && unique_validation_ok;
645
+
555
646
  info!("");
556
647
  info!("VALIDATION RESULT");
557
648
  info!("--------------------------------------------------");
@@ -766,6 +857,22 @@ mod tests {
766
857
  assert!(!validator.validate("test/empty_values.csv").unwrap());
767
858
  }
768
859
 
860
+ #[test]
861
+ fn test_unique_key_validation() {
862
+ let definition_with_non_empty_column = String::from("
863
+ unique: First Column
864
+ columns:
865
+ - name: First Column
866
+ - name: Second Column
867
+ ");
868
+ let validator = CSVValidator::from_string(&definition_with_non_empty_column).unwrap();
869
+
870
+ // Validation is OK as there are no duplicated keys
871
+ assert!(validator.validate("test/empty_values.csv").unwrap());
872
+ // Validation is not OK as the first column contains the value 456 twice
873
+ assert!(!validator.validate("test/duplicated_unique_keys.csv").unwrap());
874
+ }
875
+
769
876
  #[test]
770
877
  fn test_csv_validator_invalid_format() {
771
878
  let definition = String::from("
@@ -0,0 +1,6 @@
1
+ First Column,Second Column
2
+ 123,A
3
+ 12,B
4
+ 456,
5
+ 789,C
6
+ 456,other
File without changes