csv-validation 0.0.11__tar.gz → 0.0.13__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.
- {csv_validation-0.0.11 → csv_validation-0.0.13}/Cargo.lock +1 -14
- {csv_validation-0.0.11 → csv_validation-0.0.13}/Cargo.toml +2 -2
- csv_validation-0.0.13/MANIFEST.in +1 -0
- csv_validation-0.0.13/PKG-INFO +8 -0
- csv_validation-0.0.11/PKG-INFO → csv_validation-0.0.13/README.md +69 -32
- csv_validation-0.0.13/csv_validation.pyi +13 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/src/lib.rs +184 -36
- csv_validation-0.0.11/README.md +0 -208
- {csv_validation-0.0.11 → csv_validation-0.0.13}/.github/workflows/CI.yml +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/.gitignore +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/LICENSE +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/build.sh +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/pyproject.toml +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/test/empty_values.csv +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/test/test_file.csv +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/test/test_file.csv.gz +0 -0
- {csv_validation-0.0.11 → csv_validation-0.0.13}/test/test_validations.yml +0 -0
|
@@ -83,7 +83,7 @@ dependencies = [
|
|
|
83
83
|
|
|
84
84
|
[[package]]
|
|
85
85
|
name = "csv_validation"
|
|
86
|
-
version = "0.0.
|
|
86
|
+
version = "0.0.13"
|
|
87
87
|
dependencies = [
|
|
88
88
|
"csv",
|
|
89
89
|
"flate2",
|
|
@@ -92,7 +92,6 @@ dependencies = [
|
|
|
92
92
|
"pyo3-log",
|
|
93
93
|
"regex",
|
|
94
94
|
"serde",
|
|
95
|
-
"serde_json",
|
|
96
95
|
"simple_logger",
|
|
97
96
|
"yaml-rust2",
|
|
98
97
|
]
|
|
@@ -389,18 +388,6 @@ dependencies = [
|
|
|
389
388
|
"syn",
|
|
390
389
|
]
|
|
391
390
|
|
|
392
|
-
[[package]]
|
|
393
|
-
name = "serde_json"
|
|
394
|
-
version = "1.0.140"
|
|
395
|
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
396
|
-
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
|
|
397
|
-
dependencies = [
|
|
398
|
-
"itoa",
|
|
399
|
-
"memchr",
|
|
400
|
-
"ryu",
|
|
401
|
-
"serde",
|
|
402
|
-
]
|
|
403
|
-
|
|
404
391
|
[[package]]
|
|
405
392
|
name = "simple_logger"
|
|
406
393
|
version = "5.0.0"
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "csv_validation"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.13"
|
|
4
4
|
edition = "2021"
|
|
5
|
+
readme = "README.md"
|
|
5
6
|
|
|
6
7
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
7
8
|
[lib]
|
|
@@ -15,7 +16,6 @@ log = "0.4.26"
|
|
|
15
16
|
pyo3 = "0.23.3"
|
|
16
17
|
pyo3-log = "0.12.1"
|
|
17
18
|
regex = "1.11.1"
|
|
18
|
-
serde_json = "1.0.140"
|
|
19
19
|
simple_logger = "5.0.0"
|
|
20
20
|
yaml-rust2 = "0.10.0"
|
|
21
21
|
serde = { version = "1.0.218", features = ["derive"] }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
include csv_validation.pyi
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: csv_validation
|
|
3
|
+
Version: 0.0.13
|
|
4
|
+
Classifier: Programming Language :: Rust
|
|
5
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
6
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.8
|
|
@@ -1,28 +1,19 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: csv_validation
|
|
3
|
-
Version: 0.0.11
|
|
4
|
-
Classifier: Programming Language :: Rust
|
|
5
|
-
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
6
|
-
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
7
|
-
License-File: LICENSE
|
|
8
|
-
Requires-Python: >=3.8
|
|
9
|
-
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
10
|
-
|
|
11
1
|
# CSV Validation Library
|
|
12
2
|
|
|
13
3
|
Blazing fast format validations for your CSV files
|
|
14
4
|
|
|
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.
|
|
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.
|
|
16
6
|
|
|
17
7
|
## Features
|
|
18
8
|
|
|
19
9
|
- ✨ Validate both plain and gzipped CSV files
|
|
20
10
|
- 🔍 Multiple validation types supported:
|
|
11
|
+
- Correct column name and order
|
|
21
12
|
- Regular expressions
|
|
22
|
-
-
|
|
13
|
+
- Well-known formats (integer, decimal, etc.)
|
|
14
|
+
- Minimum/Maximum numerical value checks
|
|
23
15
|
- Value set validation (allowed values)
|
|
24
|
-
|
|
25
|
-
- 🐍 Python bindings included
|
|
16
|
+
- 🦀 + 🐍 Rust lib with Python bindings included
|
|
26
17
|
- 📝 Detailed validation summaries with sample invalid values
|
|
27
18
|
- 🚀 High performance with optimizations like regex pre-compilation
|
|
28
19
|
- 📊 Support for large CSV files
|
|
@@ -68,7 +59,7 @@ is_valid = validator.validate("data.csv")
|
|
|
68
59
|
|
|
69
60
|
### Validation Definition Format
|
|
70
61
|
|
|
71
|
-
Create a small, easy
|
|
62
|
+
Create a small, easy-to-read YAML file with your validation rules. Example:
|
|
72
63
|
|
|
73
64
|
```yaml
|
|
74
65
|
columns:
|
|
@@ -98,12 +89,17 @@ columns:
|
|
|
98
89
|
- Validate fields against custom regex patterns
|
|
99
90
|
|
|
100
91
|
2. **Format** (`format`)
|
|
101
|
-
- 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.
|
|
102
94
|
- Available formats:
|
|
103
95
|
- `integer`: Validates any integer number (positive or negative)
|
|
104
|
-
- `
|
|
105
|
-
- `
|
|
106
|
-
|
|
96
|
+
- `positive integer`: Validates positive integer numbers
|
|
97
|
+
- `decimal/decimal point`: Validates any decimal number (positive or negative) using point as decimal separator
|
|
98
|
+
- `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
|
|
100
|
+
- `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
|
|
101
|
+
- `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
|
|
102
|
+
- More formats will be added in upcoming versions
|
|
107
103
|
|
|
108
104
|
3. **Minimum Value** (`min`)
|
|
109
105
|
- Check if numeric fields are greater than or equal to a specified value
|
|
@@ -114,6 +110,14 @@ columns:
|
|
|
114
110
|
5. **Value Set** (`values`)
|
|
115
111
|
- Ensure fields only contain values from a predefined set
|
|
116
112
|
|
|
113
|
+
6. **Extra** (`extra`)
|
|
114
|
+
- Extra validations that normally complement one of the other types
|
|
115
|
+
- Available extras:
|
|
116
|
+
- `non_empty`: Validates that field contains at least one character
|
|
117
|
+
|
|
118
|
+
You can add as many validation types as you want for the same column, but take into account that the
|
|
119
|
+
column only will be considered correct if all the validations are OK.
|
|
120
|
+
|
|
117
121
|
## Global Validations
|
|
118
122
|
|
|
119
123
|
### empty_not_ok
|
|
@@ -121,7 +125,7 @@ columns:
|
|
|
121
125
|
Empty values (empty string '') are considered correct and accepted by default.
|
|
122
126
|
However, if your data must always have some content,
|
|
123
127
|
you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
|
|
124
|
-
add the `
|
|
128
|
+
add the `extra: non_empty` validation to all columns:
|
|
125
129
|
|
|
126
130
|
```yaml
|
|
127
131
|
empty_not_ok: true
|
|
@@ -130,17 +134,7 @@ columns:
|
|
|
130
134
|
# other validations...
|
|
131
135
|
```
|
|
132
136
|
|
|
133
|
-
###
|
|
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
|
|
137
|
+
### Column Separator
|
|
144
138
|
|
|
145
139
|
By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
|
|
146
140
|
|
|
@@ -150,6 +144,15 @@ validator.set_separator(";") # Use semicolon as separator
|
|
|
150
144
|
validator.set_separator("\t") # Use tab as separator
|
|
151
145
|
```
|
|
152
146
|
|
|
147
|
+
### Decimal Separator
|
|
148
|
+
|
|
149
|
+
By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
validator = CSVValidator.from_file("rules.yml")
|
|
153
|
+
validator.set_decimal_separator(",") # Use comma
|
|
154
|
+
```
|
|
155
|
+
|
|
153
156
|
## Error Handling
|
|
154
157
|
|
|
155
158
|
The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
|
|
@@ -158,6 +161,40 @@ The library provides detailed validation reports through Python's logging system
|
|
|
158
161
|
- Sample of invalid values
|
|
159
162
|
- Number of rows that failed each validation
|
|
160
163
|
|
|
164
|
+
### Example of validation report
|
|
165
|
+
|
|
166
|
+
```
|
|
167
|
+
VALIDATIONS SUMMARY
|
|
168
|
+
==================================================
|
|
169
|
+
FILE: /test.csv
|
|
170
|
+
Rows: 232230 | Columns: 5
|
|
171
|
+
|
|
172
|
+
CORRECT COLUMNS: 3/5
|
|
173
|
+
--------------------------------------------------
|
|
174
|
+
- County: [✔] OK
|
|
175
|
+
✔ - RegularExpression { expression: "^.*$", alias: "regex" }
|
|
176
|
+
- City: [✔] OK
|
|
177
|
+
✔ - RegularExpression { expression: "^.*$", alias: "regex" }
|
|
178
|
+
- Model Year: [✔] OK
|
|
179
|
+
✔ - RegularExpression { expression: "^[0-9]+$", alias: "regex" }
|
|
180
|
+
✔ - Min(1999.0)
|
|
181
|
+
✔ - Max(2025.78)
|
|
182
|
+
|
|
183
|
+
WRONG COLUMNS: 2/5
|
|
184
|
+
--------------------------------------------------
|
|
185
|
+
- State: [✖] FAIL
|
|
186
|
+
✖ - Values(["WA", "OR", "NY", "DC", "CA", "TX", "FL", "OK", "MO", "KS", "VA", "MA", "MO", "NC", "IL", "AL", "WY", "CO", "PA", "WI", "MD", "NV", "AZ"])
|
|
187
|
+
"Wrong Rows: 93 | Sample: 'GA','NJ','CT','NJ','CT','CT','CT','NE','CT','NH'"
|
|
188
|
+
- Postal Code: [✖] FAIL
|
|
189
|
+
✔ - RegularExpression { expression: "^$|^-?\\d+$", alias: "integer" }
|
|
190
|
+
✖ - RegularExpression { expression: "^.+$", alias: "non_empty" }
|
|
191
|
+
"Wrong Rows: 4 | Sample: '','','',''"
|
|
192
|
+
|
|
193
|
+
VALIDATION RESULT
|
|
194
|
+
--------------------------------------------------
|
|
195
|
+
[✖] FAIL: File DOESN'T match all validations
|
|
196
|
+
```
|
|
197
|
+
|
|
161
198
|
## Development
|
|
162
199
|
|
|
163
200
|
### Prerequisites
|
|
@@ -215,4 +252,4 @@ SOFTWARE.
|
|
|
215
252
|
|
|
216
253
|
## Contributing
|
|
217
254
|
|
|
218
|
-
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
255
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -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
|
|
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)? {
|
|
@@ -211,6 +231,15 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
|
|
|
211
231
|
alias: format.to_string()
|
|
212
232
|
})
|
|
213
233
|
}
|
|
234
|
+
"extra" => {
|
|
235
|
+
let extra = value.as_str()
|
|
236
|
+
.ok_or_else(|| PyRuntimeError::new_err("Extra must be a string"))?;
|
|
237
|
+
let regex_for_extra = get_regex_for_extra(extra)?;
|
|
238
|
+
Ok(Validation::RegularExpression {
|
|
239
|
+
expression: regex_for_extra,
|
|
240
|
+
alias: extra.to_string()
|
|
241
|
+
})
|
|
242
|
+
}
|
|
214
243
|
_ => Err(PyRuntimeError::new_err(format!("Unknown validation: {key}")))
|
|
215
244
|
}?;
|
|
216
245
|
|
|
@@ -232,10 +261,7 @@ fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>>
|
|
|
232
261
|
let empty_not_ok =
|
|
233
262
|
config[0]["empty_not_ok"].as_bool().map_or(false, |value| value);
|
|
234
263
|
if empty_not_ok {
|
|
235
|
-
let non_empty_validation =
|
|
236
|
-
expression: String::from("^.+$"),
|
|
237
|
-
alias: String::from("non_empty")
|
|
238
|
-
};
|
|
264
|
+
let non_empty_validation = validation_for_non_empty();
|
|
239
265
|
for column_validations in column_validations.iter_mut() {
|
|
240
266
|
column_validations.validations.push(non_empty_validation.clone());
|
|
241
267
|
}
|
|
@@ -256,16 +282,35 @@ fn get_regex_for_format(format: &str) -> PyResult<String> {
|
|
|
256
282
|
match format {
|
|
257
283
|
"integer" => Ok(String::from("^$|^-?\\d+$")),
|
|
258
284
|
"positive integer" => Ok(String::from("^$|^\\d+$")),
|
|
259
|
-
"decimal" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?$")),
|
|
285
|
+
"decimal" | "decimal point" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?$")),
|
|
286
|
+
"decimal comma" => Ok(String::from("^$|^-?\\d+(,\\d+)?$")),
|
|
260
287
|
"positive decimal point" | "positive decimal" => Ok(String::from("^$|^\\d+(\\.\\d+)?$")),
|
|
261
288
|
"positive decimal comma" => Ok(String::from("^$|^\\d+(,\\d+)?$")),
|
|
262
289
|
"decimal scientific" => Ok(String::from("^$|^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$")),
|
|
263
|
-
"non_empty" => Ok(String::from("^.+$")),
|
|
264
290
|
_ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
|
|
265
291
|
}
|
|
266
292
|
}
|
|
267
293
|
|
|
294
|
+
fn get_regex_for_extra(extra: &str) -> PyResult<String> {
|
|
295
|
+
match extra {
|
|
296
|
+
"non_empty" => Ok(regex_for_non_empty()),
|
|
297
|
+
_ => Err(PyRuntimeError::new_err(format!("Unknown extra: {extra}")))
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
fn validation_for_non_empty() -> Validation {
|
|
302
|
+
RegularExpression {
|
|
303
|
+
expression: regex_for_non_empty(),
|
|
304
|
+
alias: String::from("non_empty")
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
fn regex_for_non_empty() -> String {
|
|
309
|
+
String::from("^.+$")
|
|
310
|
+
}
|
|
311
|
+
|
|
268
312
|
fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
|
|
313
|
+
info!("Validating column names and order...");
|
|
269
314
|
let expected_column_names = validations.iter()
|
|
270
315
|
.map(|v| v.column_name.clone())
|
|
271
316
|
.collect::<Vec<String>>();
|
|
@@ -317,12 +362,28 @@ impl CSVValidator {
|
|
|
317
362
|
}
|
|
318
363
|
|
|
319
364
|
#[staticmethod]
|
|
365
|
+
#[pyo3(text_signature = "(definition_path)")]
|
|
366
|
+
/// Create a new CSVValidator from a YAML file with the validation definition.
|
|
367
|
+
///
|
|
368
|
+
/// Args:
|
|
369
|
+
/// definition_path (str): The path to the YAML file with the validation definition.
|
|
370
|
+
///
|
|
371
|
+
/// Returns:
|
|
372
|
+
/// a CSVValidation instance
|
|
320
373
|
fn from_file(definition_path: &str) -> PyResult<Self> {
|
|
321
374
|
let definition_string = fs::read_to_string(definition_path)?;
|
|
322
375
|
Self::from_string(&definition_string)
|
|
323
376
|
}
|
|
324
377
|
|
|
325
378
|
#[staticmethod]
|
|
379
|
+
#[pyo3(text_signature = "(definition_string)")]
|
|
380
|
+
/// Create a new CSVValidator from a YAML string with the validation definition.
|
|
381
|
+
///
|
|
382
|
+
/// Args:
|
|
383
|
+
/// definition_string (str): A string with the YAML validations definition.
|
|
384
|
+
///
|
|
385
|
+
/// Returns:
|
|
386
|
+
/// a CSVValidation instance
|
|
326
387
|
fn from_string(definition_string: &str) -> PyResult<Self> {
|
|
327
388
|
let validations = get_validations(definition_string)?;
|
|
328
389
|
let mut regex_map = HashMap::new();
|
|
@@ -346,6 +407,13 @@ impl CSVValidator {
|
|
|
346
407
|
Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR })
|
|
347
408
|
}
|
|
348
409
|
|
|
410
|
+
#[pyo3(text_signature = "(self, separator)")]
|
|
411
|
+
/// Set the CSV separator (also known as delimiter):
|
|
412
|
+
///
|
|
413
|
+
/// The separator is ',' by default. If your file has a different one, you can modify it here.
|
|
414
|
+
///
|
|
415
|
+
/// Args:
|
|
416
|
+
/// separator (str): A string with only one character that is the CSV file separator.
|
|
349
417
|
fn set_separator(&mut self, separator: String) -> PyResult<()> {
|
|
350
418
|
if separator.len() == 1 {
|
|
351
419
|
self.separator = separator.chars().next().unwrap() as u8;
|
|
@@ -356,6 +424,14 @@ impl CSVValidator {
|
|
|
356
424
|
}
|
|
357
425
|
}
|
|
358
426
|
|
|
427
|
+
#[pyo3(text_signature = "(self, decimal_separator)")]
|
|
428
|
+
/// Set the decimal number separator
|
|
429
|
+
///
|
|
430
|
+
/// The default decimals separator for float numbers is '.'.
|
|
431
|
+
/// If your file uses a different one, you can modify it here.
|
|
432
|
+
///
|
|
433
|
+
/// Args:
|
|
434
|
+
/// decimal_separator (str): A string with only one character that is the decimal separator.
|
|
359
435
|
fn set_decimal_separator(&mut self, decimal_separator: String) -> PyResult<()> {
|
|
360
436
|
if decimal_separator.len() == 1 {
|
|
361
437
|
self.decimal_separator = decimal_separator.chars().next().unwrap();
|
|
@@ -366,6 +442,15 @@ impl CSVValidator {
|
|
|
366
442
|
}
|
|
367
443
|
}
|
|
368
444
|
|
|
445
|
+
#[pyo3(text_signature = "(self, file_path)")]
|
|
446
|
+
/// Validates the CSV file against the validations defined in this CSVValidator.
|
|
447
|
+
/// When finished, it will log a comprehensive summary with the details of the Validation.
|
|
448
|
+
///
|
|
449
|
+
/// Args:
|
|
450
|
+
/// file_path (str): The path with the CSV file to validate.
|
|
451
|
+
///
|
|
452
|
+
/// Returns:
|
|
453
|
+
/// bool: True if the file fully complies with all the validations, False otherwise
|
|
369
454
|
fn validate(&self, file_path: &str) -> PyResult<bool> {
|
|
370
455
|
// Build the CSV reader
|
|
371
456
|
let mut rdr = get_reader_from(file_path, self.separator)?;
|
|
@@ -375,7 +460,7 @@ impl CSVValidator {
|
|
|
375
460
|
info!("Columns names and order are correct");
|
|
376
461
|
}
|
|
377
462
|
else {
|
|
378
|
-
error!("Expected columns !=
|
|
463
|
+
error!("Expected columns != File columns. Cannot continue with rest of the validations");
|
|
379
464
|
return Ok(false);
|
|
380
465
|
}
|
|
381
466
|
|
|
@@ -383,6 +468,8 @@ impl CSVValidator {
|
|
|
383
468
|
let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
|
|
384
469
|
let mut is_valid_file = true;
|
|
385
470
|
let mut validated_rows = 0;
|
|
471
|
+
|
|
472
|
+
// Iterate over the CSV file and validate each row
|
|
386
473
|
for result in rdr.records() {
|
|
387
474
|
let record = result.unwrap();
|
|
388
475
|
for next_column in zip(record.iter(), self.validations.iter()) {
|
|
@@ -420,45 +507,57 @@ impl CSVValidator {
|
|
|
420
507
|
column_validation_summaries.push(column_validation_summary);
|
|
421
508
|
}
|
|
422
509
|
|
|
423
|
-
|
|
424
|
-
|
|
510
|
+
let validation_process_summary =
|
|
511
|
+
&self.create_validation_process_summary(column_validation_summaries, validated_rows, file_path);
|
|
512
|
+
|
|
513
|
+
// TODO: Decide how to return the results of the validations in JSON
|
|
514
|
+
//let _validation_result_json = serde_json::to_string(&validation_process_summary).unwrap();
|
|
425
515
|
|
|
426
|
-
|
|
516
|
+
info!("");
|
|
427
517
|
info!("VALIDATIONS SUMMARY");
|
|
428
|
-
info!("
|
|
429
|
-
info!("
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
518
|
+
info!("==================================================");
|
|
519
|
+
info!("FILE: {}", file_path);
|
|
520
|
+
info!("Rows: {} | Columns: {}", validation_process_summary.total_rows, validation_process_summary.total_columns);
|
|
521
|
+
|
|
522
|
+
let correct_columns = validation_process_summary.correct_columns.len();
|
|
523
|
+
let wrong_columns = validation_process_summary.wrong_columns.len();
|
|
524
|
+
|
|
525
|
+
info!("");
|
|
526
|
+
info!("CORRECT COLUMNS: {}/{}", correct_columns, validation_process_summary.total_columns);
|
|
527
|
+
info!("--------------------------------------------------");
|
|
528
|
+
for column_validation_summary in &validation_process_summary.correct_columns {
|
|
529
|
+
info!(" - {}: [✔] OK", column_validation_summary.column_name);
|
|
530
|
+
for validation_summary in column_validation_summary.validation_summaries.iter() {
|
|
531
|
+
info!(" ✔ - {:?}", validation_summary.validation);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
info!("");
|
|
536
|
+
info!("WRONG COLUMNS: {}/{}", wrong_columns, validation_process_summary.total_columns);
|
|
537
|
+
info!("--------------------------------------------------");
|
|
538
|
+
for column_validation_summary in &validation_process_summary.wrong_columns {
|
|
539
|
+
info!(" - {}: [✖] FAIL", column_validation_summary.column_name);
|
|
540
|
+
for validation_summary in column_validation_summary.validation_summaries.iter() {
|
|
440
541
|
if validation_summary.wrong_rows > 0 {
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
542
|
+
info!(" ✖ - {:?}", validation_summary.validation);
|
|
543
|
+
info!(" {:?}", validation_summary.get_wrong_values_details());
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
info!(" ✔ - {:?}", validation_summary.validation);
|
|
446
547
|
}
|
|
447
548
|
}
|
|
448
549
|
}
|
|
449
550
|
|
|
551
|
+
info!("");
|
|
552
|
+
info!("VALIDATION RESULT");
|
|
553
|
+
info!("--------------------------------------------------");
|
|
450
554
|
if is_valid_file {
|
|
451
|
-
info!("OK
|
|
555
|
+
info!("[✔] OK - File matches the validations");
|
|
452
556
|
}
|
|
453
557
|
else {
|
|
454
|
-
info!("
|
|
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
|
-
}
|
|
558
|
+
info!("[✖] FAIL: File DOESN'T match all validations");
|
|
461
559
|
}
|
|
560
|
+
info!("");
|
|
462
561
|
Ok(is_valid_file)
|
|
463
562
|
}
|
|
464
563
|
}
|
|
@@ -503,6 +602,40 @@ impl CSVValidator {
|
|
|
503
602
|
Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
|
|
504
603
|
}
|
|
505
604
|
}
|
|
605
|
+
|
|
606
|
+
fn create_validation_process_summary(&self, column_validation_summaries: Vec<ColumnValidationsSummary>, validated_rows: usize, file_path: &str) -> FileValidationSummary {
|
|
607
|
+
let total_rows = validated_rows;
|
|
608
|
+
let total_columns = column_validation_summaries.len();
|
|
609
|
+
|
|
610
|
+
let mut failed_columns = HashSet::new();
|
|
611
|
+
let mut correct_columns = vec![];
|
|
612
|
+
let mut wrong_columns = vec![];
|
|
613
|
+
for column_validation_summary in column_validation_summaries {
|
|
614
|
+
for validation_summary in &column_validation_summary.validation_summaries {
|
|
615
|
+
if validation_summary.wrong_rows > 0 {
|
|
616
|
+
let column_name = &column_validation_summary.column_name;
|
|
617
|
+
if !failed_columns.contains(column_name) {
|
|
618
|
+
failed_columns.insert(column_name.clone());
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if failed_columns.contains(&column_validation_summary.column_name) {
|
|
624
|
+
wrong_columns.push(column_validation_summary);
|
|
625
|
+
}
|
|
626
|
+
else {
|
|
627
|
+
correct_columns.push(column_validation_summary);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
FileValidationSummary {
|
|
632
|
+
file_path: file_path.parse().unwrap(),
|
|
633
|
+
total_rows,
|
|
634
|
+
total_columns,
|
|
635
|
+
correct_columns,
|
|
636
|
+
wrong_columns
|
|
637
|
+
}
|
|
638
|
+
}
|
|
506
639
|
}
|
|
507
640
|
|
|
508
641
|
/// A Python module implemented in Rust.
|
|
@@ -614,6 +747,21 @@ mod tests {
|
|
|
614
747
|
assert!(!validator.validate("test/empty_values.csv").unwrap());
|
|
615
748
|
}
|
|
616
749
|
|
|
750
|
+
#[test]
|
|
751
|
+
fn test_extra_non_empty_column() {
|
|
752
|
+
let definition_with_non_empty_column = String::from("
|
|
753
|
+
columns:
|
|
754
|
+
- name: First Column
|
|
755
|
+
format: positive integer
|
|
756
|
+
extra: non_empty
|
|
757
|
+
- name: Second Column
|
|
758
|
+
values: ['A', 'B', 'C']
|
|
759
|
+
");
|
|
760
|
+
let validator = CSVValidator::from_string(&definition_with_non_empty_column).unwrap();
|
|
761
|
+
// Validation is not OK as the second column contains empty values
|
|
762
|
+
assert!(!validator.validate("test/empty_values.csv").unwrap());
|
|
763
|
+
}
|
|
764
|
+
|
|
617
765
|
#[test]
|
|
618
766
|
fn test_csv_validator_invalid_format() {
|
|
619
767
|
let definition = String::from("
|
csv_validation-0.0.11/README.md
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
# CSV Validation Library
|
|
2
|
-
|
|
3
|
-
Blazing fast format validations for your CSV files
|
|
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.
|
|
6
|
-
|
|
7
|
-
## Features
|
|
8
|
-
|
|
9
|
-
- ✨ Validate both plain and gzipped CSV files
|
|
10
|
-
- 🔍 Multiple validation types supported:
|
|
11
|
-
- Regular expressions
|
|
12
|
-
- Minimum/Maximum value checks
|
|
13
|
-
- Value set validation (allowed values)
|
|
14
|
-
- Column name and order validation
|
|
15
|
-
- 🐍 Python bindings included
|
|
16
|
-
- 📝 Detailed validation summaries with sample invalid values
|
|
17
|
-
- 🚀 High performance with optimizations like regex pre-compilation
|
|
18
|
-
- 📊 Support for large CSV files
|
|
19
|
-
|
|
20
|
-
## Installation
|
|
21
|
-
|
|
22
|
-
### Python
|
|
23
|
-
|
|
24
|
-
```bash
|
|
25
|
-
pip install csv_validation
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
## Usage
|
|
29
|
-
|
|
30
|
-
### Python
|
|
31
|
-
|
|
32
|
-
#### You can provide a file with the validation rules
|
|
33
|
-
```python
|
|
34
|
-
from csv_validation import CSVValidator
|
|
35
|
-
|
|
36
|
-
validator = CSVValidator.from_file("validation_rules.yaml")
|
|
37
|
-
is_valid = validator.validate("data.csv")
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
#### You can also create a validator from a string
|
|
41
|
-
```python
|
|
42
|
-
validation_rules = """
|
|
43
|
-
columns:
|
|
44
|
-
- name: Name
|
|
45
|
-
regex: ^[A-Za-z\s]{2,50}$
|
|
46
|
-
- name: Age
|
|
47
|
-
format: positive_integer
|
|
48
|
-
max: 120
|
|
49
|
-
"""
|
|
50
|
-
|
|
51
|
-
validator = CSVValidator.from_string(validation_rules)
|
|
52
|
-
# Optionally set a custom column separator
|
|
53
|
-
validator.set_separator(";") # Default is comma (,)
|
|
54
|
-
|
|
55
|
-
# Validate a CSV file
|
|
56
|
-
is_valid = validator.validate("data.csv")
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
### Validation Definition Format
|
|
60
|
-
|
|
61
|
-
Create a small, easy to read YAML file with your validation rules. Example:
|
|
62
|
-
|
|
63
|
-
```yaml
|
|
64
|
-
columns:
|
|
65
|
-
- name: Name
|
|
66
|
-
regex: ^[A-Za-z\s]{2,50}$ # Letters and spaces, 2-50 characters
|
|
67
|
-
- name: Family Name
|
|
68
|
-
regex: ^[A-Za-z\s'-]{2,50}$ # Letters, spaces, hyphens and apostrophes
|
|
69
|
-
- name: Age
|
|
70
|
-
format: positive_integer # Using predefined format instead of custom regex
|
|
71
|
-
max: 120
|
|
72
|
-
- name: Salary
|
|
73
|
-
format: integer # Allows negative integers too
|
|
74
|
-
min: 20000
|
|
75
|
-
- name: Email
|
|
76
|
-
regex: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # Standard email format
|
|
77
|
-
- name: Phone
|
|
78
|
-
regex: ^\+?[0-9]{10,15}$ # International phone format with optional +
|
|
79
|
-
- name: Status
|
|
80
|
-
values: [active, inactive, pending, suspended] # Only these values are allowed
|
|
81
|
-
- name: Gender
|
|
82
|
-
values: [M, F, NB, O] # M: Male, F: Female, NB: Non-Binary, O: Other
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
## Validation Types
|
|
86
|
-
|
|
87
|
-
1. **Regular Expression** (`regex`)
|
|
88
|
-
- Validate fields against custom regex patterns
|
|
89
|
-
|
|
90
|
-
2. **Format** (`format`)
|
|
91
|
-
- Predefined formats for common validations
|
|
92
|
-
- Available formats:
|
|
93
|
-
- `integer`: Validates any integer number (positive or negative)
|
|
94
|
-
- `positive_integer`: Validates positive integer numbers
|
|
95
|
-
- `non_empty`: Validates that field contains at least one character
|
|
96
|
-
- More formats will be added in next versions
|
|
97
|
-
|
|
98
|
-
3. **Minimum Value** (`min`)
|
|
99
|
-
- Check if numeric fields are greater than or equal to a specified value
|
|
100
|
-
|
|
101
|
-
4. **Maximum Value** (`max`)
|
|
102
|
-
- Check if numeric fields are less than or equal to a specified value
|
|
103
|
-
|
|
104
|
-
5. **Value Set** (`values`)
|
|
105
|
-
- Ensure fields only contain values from a predefined set
|
|
106
|
-
|
|
107
|
-
## Global Validations
|
|
108
|
-
|
|
109
|
-
### empty_not_ok
|
|
110
|
-
|
|
111
|
-
Empty values (empty string '') are considered correct and accepted by default.
|
|
112
|
-
However, if your data must always have some content,
|
|
113
|
-
you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
|
|
114
|
-
add the `format: non_empty` validation to all columns:
|
|
115
|
-
|
|
116
|
-
```yaml
|
|
117
|
-
empty_not_ok: true
|
|
118
|
-
columns:
|
|
119
|
-
- name: Column1
|
|
120
|
-
# other validations...
|
|
121
|
-
```
|
|
122
|
-
|
|
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
|
|
134
|
-
|
|
135
|
-
By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
|
|
136
|
-
|
|
137
|
-
```python
|
|
138
|
-
validator = CSVValidator.from_file("rules.yml")
|
|
139
|
-
validator.set_separator(";") # Use semicolon as separator
|
|
140
|
-
validator.set_separator("\t") # Use tab as separator
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
## Error Handling
|
|
144
|
-
|
|
145
|
-
The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
|
|
146
|
-
- Which columns failed validation
|
|
147
|
-
- What type of validation failed
|
|
148
|
-
- Sample of invalid values
|
|
149
|
-
- Number of rows that failed each validation
|
|
150
|
-
|
|
151
|
-
## Development
|
|
152
|
-
|
|
153
|
-
### Prerequisites
|
|
154
|
-
|
|
155
|
-
- Rust 2021 edition or later
|
|
156
|
-
- Python 3.6+ (for Python bindings)
|
|
157
|
-
- Cargo and standard Rust tooling
|
|
158
|
-
|
|
159
|
-
### Building from Source (Rust version)
|
|
160
|
-
|
|
161
|
-
```bash
|
|
162
|
-
# Clone the repository
|
|
163
|
-
git clone https://github.com/charro/csv_validation
|
|
164
|
-
cd csv_validation
|
|
165
|
-
|
|
166
|
-
# Build the project
|
|
167
|
-
cargo build --release
|
|
168
|
-
|
|
169
|
-
# Run tests
|
|
170
|
-
cargo test
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
## Dependencies
|
|
174
|
-
|
|
175
|
-
- `csv`: CSV parsing
|
|
176
|
-
- `flate2`: Compression support
|
|
177
|
-
- `pyo3`: Python bindings
|
|
178
|
-
- `regex`: Regular expression support
|
|
179
|
-
- `yaml-rust2`: YAML parsing
|
|
180
|
-
- Various utilities for logging and serialization
|
|
181
|
-
|
|
182
|
-
## License
|
|
183
|
-
|
|
184
|
-
MIT License
|
|
185
|
-
|
|
186
|
-
Copyright (c) 2024 CSV Validation Contributors
|
|
187
|
-
|
|
188
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
189
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
190
|
-
in the Software without restriction, including without limitation the rights
|
|
191
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
192
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
193
|
-
furnished to do so, subject to the following conditions:
|
|
194
|
-
|
|
195
|
-
The above copyright notice and this permission notice shall be included in all
|
|
196
|
-
copies or substantial portions of the Software.
|
|
197
|
-
|
|
198
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
199
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
200
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
201
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
202
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
203
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
204
|
-
SOFTWARE.
|
|
205
|
-
|
|
206
|
-
## Contributing
|
|
207
|
-
|
|
208
|
-
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|