csv-validation 0.0.6__tar.gz → 0.0.7__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.6 → csv_validation-0.0.7}/Cargo.lock +1 -1
- {csv_validation-0.0.6 → csv_validation-0.0.7}/Cargo.toml +1 -1
- csv_validation-0.0.7/LICENSE +21 -0
- csv_validation-0.0.7/PKG-INFO +177 -0
- csv_validation-0.0.7/README.md +167 -0
- csv_validation-0.0.7/src/lib.rs +540 -0
- csv_validation-0.0.6/PKG-INFO +0 -7
- csv_validation-0.0.6/src/lib.rs +0 -374
- {csv_validation-0.0.6 → csv_validation-0.0.7}/.github/workflows/CI.yml +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/.gitignore +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/build.sh +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/pyproject.toml +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/test/test_file.csv +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/test/test_file.csv.gz +0 -0
- {csv_validation-0.0.6 → csv_validation-0.0.7}/test/test_validations.yml +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 CSV Validation Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: csv_validation
|
|
3
|
+
Version: 0.0.7
|
|
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
|
+
# CSV Validation
|
|
12
|
+
|
|
13
|
+
Blazing fast format validations for your CSV files
|
|
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.
|
|
16
|
+
|
|
17
|
+
## Features
|
|
18
|
+
|
|
19
|
+
- ✨ Validate both plain and gzipped CSV files
|
|
20
|
+
- 🔍 Multiple validation types supported:
|
|
21
|
+
- Regular expressions
|
|
22
|
+
- Minimum/Maximum value checks
|
|
23
|
+
- Value set validation (allowed values)
|
|
24
|
+
- Column name and order validation
|
|
25
|
+
- 🐍 Python bindings included
|
|
26
|
+
- 📝 Detailed validation summaries with sample invalid values
|
|
27
|
+
- 🚀 High performance with optimizations like regex pre-compilation
|
|
28
|
+
- 📊 Support for large CSV files
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
### Python
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install csv_validation
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
### Python
|
|
41
|
+
|
|
42
|
+
#### You can provide a file with the validation rules
|
|
43
|
+
```python
|
|
44
|
+
from csv_validation import CSVValidator
|
|
45
|
+
|
|
46
|
+
validator = CSVValidator.from_file("validation_rules.yaml")
|
|
47
|
+
is_valid = validator.validate("data.csv")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
#### You can also create a validator from a string
|
|
51
|
+
```python
|
|
52
|
+
validation_rules = """
|
|
53
|
+
columns:
|
|
54
|
+
- name: Name
|
|
55
|
+
regex: ^[A-Za-z\s]{2,50}$
|
|
56
|
+
- name: Age
|
|
57
|
+
format: positive_integer
|
|
58
|
+
max: 120
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
validator = CSVValidator.from_string(validation_rules)
|
|
62
|
+
is_valid = validator.validate("data.csv")
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Validation Definition Format
|
|
66
|
+
|
|
67
|
+
Create a small, easy to read YAML file with your validation rules. Example:
|
|
68
|
+
|
|
69
|
+
```yaml
|
|
70
|
+
columns:
|
|
71
|
+
- name: Name
|
|
72
|
+
regex: ^[A-Za-z\s]{2,50}$ # Letters and spaces, 2-50 characters
|
|
73
|
+
- name: Family Name
|
|
74
|
+
regex: ^[A-Za-z\s'-]{2,50}$ # Letters, spaces, hyphens and apostrophes
|
|
75
|
+
- name: Age
|
|
76
|
+
format: positive_integer # Using predefined format instead of custom regex
|
|
77
|
+
max: 120
|
|
78
|
+
- name: Salary
|
|
79
|
+
format: integer # Allows negative integers too
|
|
80
|
+
min: 20000
|
|
81
|
+
- name: Email
|
|
82
|
+
regex: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # Standard email format
|
|
83
|
+
- name: Phone
|
|
84
|
+
regex: ^\+?[0-9]{10,15}$ # International phone format with optional +
|
|
85
|
+
- name: Status
|
|
86
|
+
values: [active, inactive, pending, suspended] # Only these values are allowed
|
|
87
|
+
- name: Gender
|
|
88
|
+
values: [M, F, NB, O] # M: Male, F: Female, NB: Non-Binary, O: Other
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Validation Types
|
|
92
|
+
|
|
93
|
+
1. **Regular Expression** (`regex`)
|
|
94
|
+
- Validate fields against custom regex patterns
|
|
95
|
+
|
|
96
|
+
2. **Format** (`format`)
|
|
97
|
+
- Predefined formats for common validations
|
|
98
|
+
- Available formats:
|
|
99
|
+
- `integer`: Validates any integer number (positive or negative)
|
|
100
|
+
- `positive_integer`: Validates positive integer numbers
|
|
101
|
+
- More formats will be added in next versions
|
|
102
|
+
|
|
103
|
+
3. **Minimum Value** (`min`)
|
|
104
|
+
- Check if numeric fields are greater than or equal to a specified value
|
|
105
|
+
|
|
106
|
+
4. **Maximum Value** (`max`)
|
|
107
|
+
- Check if numeric fields are less than or equal to a specified value
|
|
108
|
+
|
|
109
|
+
5. **Value Set** (`values`)
|
|
110
|
+
- Ensure fields only contain values from a predefined set
|
|
111
|
+
|
|
112
|
+
## Output
|
|
113
|
+
|
|
114
|
+
The validation process provides detailed feedback including:
|
|
115
|
+
- Overall validation status (true/false)
|
|
116
|
+
- Number of invalid rows per validation rule
|
|
117
|
+
- Sample of invalid values for debugging
|
|
118
|
+
- Detailed logging for troubleshooting
|
|
119
|
+
|
|
120
|
+
## Development
|
|
121
|
+
|
|
122
|
+
### Prerequisites
|
|
123
|
+
|
|
124
|
+
- Rust 2021 edition or later
|
|
125
|
+
- Python 3.6+ (for Python bindings)
|
|
126
|
+
- Cargo and standard Rust tooling
|
|
127
|
+
|
|
128
|
+
### Building from Source
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
# Clone the repository
|
|
132
|
+
git clone https://github.com/charro/csv_validation
|
|
133
|
+
cd csv_validation
|
|
134
|
+
|
|
135
|
+
# Build the project
|
|
136
|
+
cargo build --release
|
|
137
|
+
|
|
138
|
+
# Run tests
|
|
139
|
+
cargo test
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Dependencies
|
|
143
|
+
|
|
144
|
+
- `csv`: CSV parsing
|
|
145
|
+
- `flate2`: Compression support
|
|
146
|
+
- `pyo3`: Python bindings
|
|
147
|
+
- `regex`: Regular expression support
|
|
148
|
+
- `yaml-rust2`: YAML parsing
|
|
149
|
+
- Various utilities for logging and serialization
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
MIT License
|
|
154
|
+
|
|
155
|
+
Copyright (c) 2024 CSV Validation Contributors
|
|
156
|
+
|
|
157
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
158
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
159
|
+
in the Software without restriction, including without limitation the rights
|
|
160
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
161
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
162
|
+
furnished to do so, subject to the following conditions:
|
|
163
|
+
|
|
164
|
+
The above copyright notice and this permission notice shall be included in all
|
|
165
|
+
copies or substantial portions of the Software.
|
|
166
|
+
|
|
167
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
168
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
169
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
170
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
171
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
172
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
173
|
+
SOFTWARE.
|
|
174
|
+
|
|
175
|
+
## Contributing
|
|
176
|
+
|
|
177
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# CSV Validation
|
|
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
|
+
is_valid = validator.validate("data.csv")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Validation Definition Format
|
|
56
|
+
|
|
57
|
+
Create a small, easy to read YAML file with your validation rules. Example:
|
|
58
|
+
|
|
59
|
+
```yaml
|
|
60
|
+
columns:
|
|
61
|
+
- name: Name
|
|
62
|
+
regex: ^[A-Za-z\s]{2,50}$ # Letters and spaces, 2-50 characters
|
|
63
|
+
- name: Family Name
|
|
64
|
+
regex: ^[A-Za-z\s'-]{2,50}$ # Letters, spaces, hyphens and apostrophes
|
|
65
|
+
- name: Age
|
|
66
|
+
format: positive_integer # Using predefined format instead of custom regex
|
|
67
|
+
max: 120
|
|
68
|
+
- name: Salary
|
|
69
|
+
format: integer # Allows negative integers too
|
|
70
|
+
min: 20000
|
|
71
|
+
- name: Email
|
|
72
|
+
regex: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # Standard email format
|
|
73
|
+
- name: Phone
|
|
74
|
+
regex: ^\+?[0-9]{10,15}$ # International phone format with optional +
|
|
75
|
+
- name: Status
|
|
76
|
+
values: [active, inactive, pending, suspended] # Only these values are allowed
|
|
77
|
+
- name: Gender
|
|
78
|
+
values: [M, F, NB, O] # M: Male, F: Female, NB: Non-Binary, O: Other
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Validation Types
|
|
82
|
+
|
|
83
|
+
1. **Regular Expression** (`regex`)
|
|
84
|
+
- Validate fields against custom regex patterns
|
|
85
|
+
|
|
86
|
+
2. **Format** (`format`)
|
|
87
|
+
- Predefined formats for common validations
|
|
88
|
+
- Available formats:
|
|
89
|
+
- `integer`: Validates any integer number (positive or negative)
|
|
90
|
+
- `positive_integer`: Validates positive integer numbers
|
|
91
|
+
- More formats will be added in next versions
|
|
92
|
+
|
|
93
|
+
3. **Minimum Value** (`min`)
|
|
94
|
+
- Check if numeric fields are greater than or equal to a specified value
|
|
95
|
+
|
|
96
|
+
4. **Maximum Value** (`max`)
|
|
97
|
+
- Check if numeric fields are less than or equal to a specified value
|
|
98
|
+
|
|
99
|
+
5. **Value Set** (`values`)
|
|
100
|
+
- Ensure fields only contain values from a predefined set
|
|
101
|
+
|
|
102
|
+
## Output
|
|
103
|
+
|
|
104
|
+
The validation process provides detailed feedback including:
|
|
105
|
+
- Overall validation status (true/false)
|
|
106
|
+
- Number of invalid rows per validation rule
|
|
107
|
+
- Sample of invalid values for debugging
|
|
108
|
+
- Detailed logging for troubleshooting
|
|
109
|
+
|
|
110
|
+
## Development
|
|
111
|
+
|
|
112
|
+
### Prerequisites
|
|
113
|
+
|
|
114
|
+
- Rust 2021 edition or later
|
|
115
|
+
- Python 3.6+ (for Python bindings)
|
|
116
|
+
- Cargo and standard Rust tooling
|
|
117
|
+
|
|
118
|
+
### Building from Source
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
# Clone the repository
|
|
122
|
+
git clone https://github.com/charro/csv_validation
|
|
123
|
+
cd csv_validation
|
|
124
|
+
|
|
125
|
+
# Build the project
|
|
126
|
+
cargo build --release
|
|
127
|
+
|
|
128
|
+
# Run tests
|
|
129
|
+
cargo test
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Dependencies
|
|
133
|
+
|
|
134
|
+
- `csv`: CSV parsing
|
|
135
|
+
- `flate2`: Compression support
|
|
136
|
+
- `pyo3`: Python bindings
|
|
137
|
+
- `regex`: Regular expression support
|
|
138
|
+
- `yaml-rust2`: YAML parsing
|
|
139
|
+
- Various utilities for logging and serialization
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT License
|
|
144
|
+
|
|
145
|
+
Copyright (c) 2024 CSV Validation Contributors
|
|
146
|
+
|
|
147
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
148
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
149
|
+
in the Software without restriction, including without limitation the rights
|
|
150
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
151
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
152
|
+
furnished to do so, subject to the following conditions:
|
|
153
|
+
|
|
154
|
+
The above copyright notice and this permission notice shall be included in all
|
|
155
|
+
copies or substantial portions of the Software.
|
|
156
|
+
|
|
157
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
158
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
159
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
160
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
161
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
162
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
163
|
+
SOFTWARE.
|
|
164
|
+
|
|
165
|
+
## Contributing
|
|
166
|
+
|
|
167
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
use crate::Validation::Values;
|
|
2
|
+
use std::collections::{HashMap, HashSet};
|
|
3
|
+
use std::fs;
|
|
4
|
+
use std::fs::File;
|
|
5
|
+
use std::io::{BufReader, Read};
|
|
6
|
+
use std::iter::zip;
|
|
7
|
+
use std::path::Path;
|
|
8
|
+
use csv::Reader;
|
|
9
|
+
use flate2::bufread::GzDecoder;
|
|
10
|
+
use log::{debug, error, info};
|
|
11
|
+
use pyo3::exceptions::{PyRuntimeError};
|
|
12
|
+
use pyo3::prelude::*;
|
|
13
|
+
use regex::Regex;
|
|
14
|
+
use yaml_rust2::YamlLoader;
|
|
15
|
+
use serde::{Deserialize, Serialize};
|
|
16
|
+
use crate::Validation::{RegularExpression};
|
|
17
|
+
|
|
18
|
+
const MAX_SAMPLE_SIZE:u16 = 10;
|
|
19
|
+
|
|
20
|
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
21
|
+
enum Validation {
|
|
22
|
+
RegularExpression { expression: String, alias: String },
|
|
23
|
+
Min(f64),
|
|
24
|
+
Max(f64),
|
|
25
|
+
Values(Vec<String>),
|
|
26
|
+
None
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
#[derive(Clone)]
|
|
30
|
+
struct ColumnValidations {
|
|
31
|
+
column_name: String,
|
|
32
|
+
validations: Vec<Validation>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#[derive(Serialize, Deserialize)]
|
|
36
|
+
struct ValidationSummary {
|
|
37
|
+
validation: Validation,
|
|
38
|
+
wrong_rows: usize,
|
|
39
|
+
wrong_values_sample: Vec<String>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#[derive(Serialize, Deserialize)]
|
|
43
|
+
struct ColumnValidationsSummary {
|
|
44
|
+
column_name: String,
|
|
45
|
+
validation_summaries: Vec<ValidationSummary>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashMap<String, Vec<ValidationSummary>> {
|
|
49
|
+
let mut validation_summaries_map = HashMap::new();
|
|
50
|
+
for validation in validations {
|
|
51
|
+
let mut validation_summaries = Vec::new();
|
|
52
|
+
for column_validation in &validation.validations {
|
|
53
|
+
let validation_summary =
|
|
54
|
+
ValidationSummary{validation: (*column_validation).clone(), wrong_rows: 0, wrong_values_sample: Vec::new()};
|
|
55
|
+
validation_summaries.push(validation_summary);
|
|
56
|
+
}
|
|
57
|
+
validation_summaries_map.insert(validation.column_name.clone(), validation_summaries);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
validation_summaries_map
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
|
|
64
|
+
match validation {
|
|
65
|
+
RegularExpression { expression: exp, alias: _ } => {
|
|
66
|
+
let regex = regex_map.get(exp).unwrap();
|
|
67
|
+
Ok(regex.is_match(value))
|
|
68
|
+
},
|
|
69
|
+
Validation::Min(min) => {
|
|
70
|
+
match value.parse::<f64>() {
|
|
71
|
+
Ok(value) => Ok(value >= *min),
|
|
72
|
+
Err(_) => Ok(false)
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
Validation::Max(max) => {
|
|
76
|
+
match value.parse::<f64>() {
|
|
77
|
+
Ok(value) => Ok(value <= *max),
|
|
78
|
+
Err(_) => Ok(false)
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
Validation::Values(values) => {
|
|
82
|
+
let regex_str = get_regex_string_for_values(values);
|
|
83
|
+
let regex = regex_map.get(®ex_str).unwrap();
|
|
84
|
+
Ok(regex.is_match(value))
|
|
85
|
+
}
|
|
86
|
+
Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
fn get_regex_string_for_values(values: &Vec<String>) -> String {
|
|
91
|
+
values.join("|")
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// Infers the file compression type and returns the corresponding buffered reader
|
|
95
|
+
fn get_reader_from(path: &str) -> PyResult<Reader<Box<dyn Read>>> {
|
|
96
|
+
let buf_reader = BufReader::new(File::open(Path::new(path))?);
|
|
97
|
+
if is_gzip_file(path)? {
|
|
98
|
+
debug!("File is gzipped");
|
|
99
|
+
let read_capacity = 10 * 1024_usize.pow(2);
|
|
100
|
+
let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
|
|
101
|
+
Ok(Reader::from_reader(Box::new(reader)))
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
Ok(Reader::from_reader(Box::new(buf_reader)))
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
fn is_gzip_file(path: &str) -> PyResult<bool> {
|
|
109
|
+
let mut bytes = [0u8; 2];
|
|
110
|
+
File::open(Path::new(path))?.read_exact(&mut bytes)?;
|
|
111
|
+
Ok(bytes[0] == 0x1f && bytes[1] == 0x8b)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>> {
|
|
115
|
+
// Read the YAML definition with the validations
|
|
116
|
+
let config = YamlLoader::load_from_str(definition_string)
|
|
117
|
+
.map_err(|e| PyRuntimeError::new_err(format!("Invalid YAML format: {}", e)))?;
|
|
118
|
+
|
|
119
|
+
if config.is_empty() {
|
|
120
|
+
return Err(PyRuntimeError::new_err("Empty YAML definition"));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
let columns = &config[0]["columns"];
|
|
124
|
+
if !columns.is_array() {
|
|
125
|
+
return Err(PyRuntimeError::new_err("Invalid YAML: 'columns' key must be an array"));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let columns_vec = columns.as_vec()
|
|
129
|
+
.ok_or_else(|| PyRuntimeError::new_err("Invalid YAML: 'columns' must be an array"))?;
|
|
130
|
+
|
|
131
|
+
if columns_vec.is_empty() {
|
|
132
|
+
return Err(PyRuntimeError::new_err("No columns defined in YAML"));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let mut column_names = vec![];
|
|
136
|
+
let mut column_validations = vec![];
|
|
137
|
+
|
|
138
|
+
for column in columns_vec {
|
|
139
|
+
let column_def = column.as_hash()
|
|
140
|
+
.ok_or_else(|| PyRuntimeError::new_err("Invalid YAML: each column must be a mapping"))?;
|
|
141
|
+
|
|
142
|
+
let mut column_name = "";
|
|
143
|
+
let mut validations = vec![];
|
|
144
|
+
|
|
145
|
+
for validation_definition in column_def.iter() {
|
|
146
|
+
let key = validation_definition.0.as_str()
|
|
147
|
+
.ok_or_else(|| PyRuntimeError::new_err("Invalid YAML: validation key must be a string"))?;
|
|
148
|
+
let value = validation_definition.1;
|
|
149
|
+
|
|
150
|
+
let validation = match key {
|
|
151
|
+
"name" => {
|
|
152
|
+
column_name = value.as_str()
|
|
153
|
+
.ok_or_else(|| PyRuntimeError::new_err("Column name must be a string"))?;
|
|
154
|
+
column_names.push(column_name);
|
|
155
|
+
Ok(Validation::None)
|
|
156
|
+
}
|
|
157
|
+
"regex" => {
|
|
158
|
+
let expr = value.as_str()
|
|
159
|
+
.ok_or_else(|| PyRuntimeError::new_err("Regex must be a string"))?;
|
|
160
|
+
Ok(Validation::RegularExpression {
|
|
161
|
+
expression: String::from(expr),
|
|
162
|
+
alias: String::from("regex")
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
"min" => {
|
|
166
|
+
let num = value.as_i64()
|
|
167
|
+
.ok_or_else(|| PyRuntimeError::new_err("Min value must be a number"))?;
|
|
168
|
+
Ok(Validation::Min(num as f64))
|
|
169
|
+
}
|
|
170
|
+
"max" => {
|
|
171
|
+
let num = value.as_i64()
|
|
172
|
+
.ok_or_else(|| PyRuntimeError::new_err("Max value must be a number"))?;
|
|
173
|
+
Ok(Validation::Max(num as f64))
|
|
174
|
+
}
|
|
175
|
+
"values" => {
|
|
176
|
+
let values = value.as_vec()
|
|
177
|
+
.ok_or_else(|| PyRuntimeError::new_err("Values must be an array"))?
|
|
178
|
+
.iter()
|
|
179
|
+
.map(|v| v.as_str()
|
|
180
|
+
.ok_or_else(|| PyRuntimeError::new_err("Each value in values array must be a string"))
|
|
181
|
+
.map(String::from))
|
|
182
|
+
.collect::<Result<Vec<String>, _>>()?;
|
|
183
|
+
Ok(Validation::Values(values))
|
|
184
|
+
}
|
|
185
|
+
"format" => {
|
|
186
|
+
let format = value.as_str()
|
|
187
|
+
.ok_or_else(|| PyRuntimeError::new_err("Format must be a string"))?;
|
|
188
|
+
let regex_for_format = get_regex_for_format(format)?;
|
|
189
|
+
Ok(Validation::RegularExpression {
|
|
190
|
+
expression: regex_for_format,
|
|
191
|
+
alias: format.to_string()
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
_ => Err(PyRuntimeError::new_err(format!("Unknown validation: {key}")))
|
|
195
|
+
}?;
|
|
196
|
+
|
|
197
|
+
if key != "name" {
|
|
198
|
+
validations.push(validation);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if column_name.is_empty() {
|
|
203
|
+
return Err(PyRuntimeError::new_err("Each column must have a name"));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
let new_validations = ColumnValidations { column_name: column_name.to_string(), validations };
|
|
207
|
+
column_validations.push(new_validations);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
Ok(column_validations)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
fn get_regex_for_format(format: &str) -> PyResult<String> {
|
|
214
|
+
match format {
|
|
215
|
+
"integer" => Ok(String::from("^-?\\d+$")),
|
|
216
|
+
"positive_integer" => Ok(String::from("^\\d+$")),
|
|
217
|
+
_ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
|
|
222
|
+
let expected_column_names = validations.iter()
|
|
223
|
+
.map(|v| v.column_name.clone())
|
|
224
|
+
.collect::<Vec<String>>();
|
|
225
|
+
debug!("Expected Column Names: {:?}", expected_column_names);
|
|
226
|
+
|
|
227
|
+
let headers: Vec<String> = reader.headers().unwrap().iter().map(|s| String::from(s) ).collect();
|
|
228
|
+
debug!("Actual Column Names: {:?}", headers);
|
|
229
|
+
|
|
230
|
+
if expected_column_names != headers {
|
|
231
|
+
if expected_column_names.len() != headers.len() {
|
|
232
|
+
let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
|
|
233
|
+
let headers_set: HashSet<String> = headers.iter().cloned().collect();
|
|
234
|
+
debug!("File headers not in expected columns: {:?}", headers_set.difference(&expected_columns_set));
|
|
235
|
+
debug!("Columns in expected columns not in file headers: {:?}", expected_columns_set.difference(&headers_set));
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
for (expected_column, header) in zip(expected_column_names, headers) {
|
|
239
|
+
if expected_column != header {
|
|
240
|
+
debug!("{:?} != {:?}", expected_column, header);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return Ok(false)
|
|
245
|
+
}
|
|
246
|
+
Ok(true)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
#[pyclass]
|
|
250
|
+
struct CSVValidator {
|
|
251
|
+
validations: Vec<ColumnValidations>,
|
|
252
|
+
regex_map: HashMap<String, Regex>
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#[pymethods]
|
|
256
|
+
impl CSVValidator {
|
|
257
|
+
#[new]
|
|
258
|
+
fn new() -> Self {
|
|
259
|
+
CSVValidator {
|
|
260
|
+
validations: Vec::new(),
|
|
261
|
+
regex_map: HashMap::new()
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
#[staticmethod]
|
|
266
|
+
fn from_file(definition_path: &str) -> PyResult<Self> {
|
|
267
|
+
let definition_string = fs::read_to_string(definition_path)?;
|
|
268
|
+
Self::from_string(&definition_string)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
#[staticmethod]
|
|
272
|
+
fn from_string(definition_string: &str) -> PyResult<Self> {
|
|
273
|
+
let validations = get_validations(definition_string)?;
|
|
274
|
+
let mut regex_map = HashMap::new();
|
|
275
|
+
|
|
276
|
+
// Pre-Compile and save all Regex expressions
|
|
277
|
+
for column_validation in &validations {
|
|
278
|
+
for validation in &column_validation.validations {
|
|
279
|
+
match validation {
|
|
280
|
+
RegularExpression { expression, alias: _ } => {
|
|
281
|
+
regex_map.insert(expression.to_string(), Regex::new(expression.as_str()).unwrap());
|
|
282
|
+
},
|
|
283
|
+
Values(values) => {
|
|
284
|
+
let regex_str = get_regex_string_for_values(values);
|
|
285
|
+
regex_map.insert(regex_str.clone(), Regex::new(regex_str.as_str()).unwrap());
|
|
286
|
+
},
|
|
287
|
+
_ => continue
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
Ok(CSVValidator { validations, regex_map })
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
fn validate(&self, file_path: &str) -> PyResult<bool> {
|
|
296
|
+
// Build the CSV reader
|
|
297
|
+
let mut rdr = get_reader_from(file_path)?;
|
|
298
|
+
|
|
299
|
+
// First validation: Ensure column names and order are exactly as expected
|
|
300
|
+
if validate_column_names(&mut rdr, &self.validations)? {
|
|
301
|
+
info!("Columns names and order are correct");
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
error!("Expected columns != Real columns");
|
|
305
|
+
return Ok(false);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Second validation: If column names match, check if also the values match the validations
|
|
309
|
+
let mut validation_summaries_map = build_validation_summaries_map(&self.validations);
|
|
310
|
+
let mut is_valid_file = true;
|
|
311
|
+
for result in rdr.records() {
|
|
312
|
+
let record = result.unwrap();
|
|
313
|
+
for next_column in zip(record.iter(), self.validations.iter()) {
|
|
314
|
+
let value = next_column.0;
|
|
315
|
+
let _column_name = &next_column.1.column_name;
|
|
316
|
+
for validation in &next_column.1.validations {
|
|
317
|
+
let valid = apply_validation(value, validation, &self.regex_map)?;
|
|
318
|
+
if !valid {
|
|
319
|
+
let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
|
|
320
|
+
let validation_summary = validation_summary_list
|
|
321
|
+
.iter_mut()
|
|
322
|
+
.find(|val_sum|
|
|
323
|
+
std::mem::discriminant(&val_sum.validation) == std::mem::discriminant(validation)).unwrap();
|
|
324
|
+
validation_summary.wrong_rows += 1;
|
|
325
|
+
if validation_summary.wrong_values_sample.len() < MAX_SAMPLE_SIZE as usize {
|
|
326
|
+
validation_summary.wrong_values_sample.push(value.to_string());
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
is_valid_file = is_valid_file && valid;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Fill the ColumnValidationSummary for each column
|
|
335
|
+
let mut column_validation_summaries = Vec::new();
|
|
336
|
+
for column_validation in &self.validations {
|
|
337
|
+
let validation_summary_for_column =
|
|
338
|
+
validation_summaries_map.remove(&column_validation.column_name).unwrap();
|
|
339
|
+
let column_validation_summary = ColumnValidationsSummary {
|
|
340
|
+
column_name: column_validation.column_name.clone(),
|
|
341
|
+
validation_summaries: validation_summary_for_column
|
|
342
|
+
};
|
|
343
|
+
column_validation_summaries.push(column_validation_summary);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// TODO: Decide how to return the results of the validations
|
|
347
|
+
let _validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
|
|
348
|
+
|
|
349
|
+
debug!("VALIDATIONS SUMMARY");
|
|
350
|
+
debug!("==================================================================================");
|
|
351
|
+
for column_validation_summary in column_validation_summaries {
|
|
352
|
+
debug!("Column: '{}'", column_validation_summary.column_name);
|
|
353
|
+
for validation_summary in column_validation_summary.validation_summaries {
|
|
354
|
+
let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
|
|
355
|
+
format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
|
|
356
|
+
} else {
|
|
357
|
+
String::from("" )
|
|
358
|
+
};
|
|
359
|
+
debug!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
|
|
360
|
+
validation_summary.wrong_rows, wrong_values_sample);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if is_valid_file {
|
|
365
|
+
info!("OK: File matches the validations");
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
info!("NO OK: File DOESN'T match validations");
|
|
369
|
+
}
|
|
370
|
+
Ok(is_valid_file)
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Keep the existing functions for backward compatibility
|
|
375
|
+
#[pyfunction]
|
|
376
|
+
fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
|
|
377
|
+
info!("Validating file {} against definition file {}", path, definition_path);
|
|
378
|
+
let validator = CSVValidator::from_file(definition_path)?;
|
|
379
|
+
validator.validate(path)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
#[pyfunction]
|
|
383
|
+
fn validate(path: &str, definition_string: String) -> PyResult<bool> {
|
|
384
|
+
debug!("Validating file {} against definition:\n {}", path, definition_string);
|
|
385
|
+
let validator = CSVValidator::from_string(&definition_string)?;
|
|
386
|
+
validator.validate(path)
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/// A Python module implemented in Rust.
|
|
390
|
+
#[pymodule]
|
|
391
|
+
fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
392
|
+
pyo3_log::init();
|
|
393
|
+
m.add_class::<CSVValidator>()?;
|
|
394
|
+
m.add_function(wrap_pyfunction!(validate, m)?)?;
|
|
395
|
+
m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
|
|
396
|
+
Ok(())
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
#[cfg(test)]
|
|
400
|
+
mod tests {
|
|
401
|
+
use simple_logger::SimpleLogger;
|
|
402
|
+
use crate::{validate, validate_with_file, CSVValidator};
|
|
403
|
+
|
|
404
|
+
#[test]
|
|
405
|
+
fn init_logger() {
|
|
406
|
+
SimpleLogger::new().init().unwrap();
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
#[test]
|
|
410
|
+
fn test_validate_csv_with_file() {
|
|
411
|
+
assert!(validate_with_file("test/test_file.csv", "test/test_validations.yml").unwrap());
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
#[test]
|
|
415
|
+
fn test_validate_csv_gz_with_file() {
|
|
416
|
+
assert!(validate_with_file("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
#[test]
|
|
420
|
+
fn test_wrong_headers() {
|
|
421
|
+
let definition = String::from("
|
|
422
|
+
columns:
|
|
423
|
+
- name: First Column
|
|
424
|
+
- name: Second Column
|
|
425
|
+
- name: Wrong Column
|
|
426
|
+
- name: Expected Column Not In File
|
|
427
|
+
");
|
|
428
|
+
assert!(!validate("test/test_file.csv", definition).unwrap());
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
#[test]
|
|
432
|
+
fn test_format_validation() {
|
|
433
|
+
let definition = String::from("
|
|
434
|
+
columns:
|
|
435
|
+
- name: First Column
|
|
436
|
+
- name: Second Column
|
|
437
|
+
- name: Third Column
|
|
438
|
+
format: integer
|
|
439
|
+
");
|
|
440
|
+
assert!(validate("test/test_file.csv", definition).unwrap());
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
#[test]
|
|
444
|
+
fn test_validate_csv() {
|
|
445
|
+
let definition = String::from("
|
|
446
|
+
columns:
|
|
447
|
+
- name: First Column
|
|
448
|
+
regex: ^.+$
|
|
449
|
+
- name: Second Column
|
|
450
|
+
values: [one_value, or_another]
|
|
451
|
+
- name: Third Column
|
|
452
|
+
regex: ^-?[0-9]+$
|
|
453
|
+
min: -23
|
|
454
|
+
max: 2000
|
|
455
|
+
");
|
|
456
|
+
|
|
457
|
+
assert!(validate("test/test_file.csv", definition).unwrap());
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
#[test]
|
|
461
|
+
fn test_csv_validator_from_file() {
|
|
462
|
+
let validator = CSVValidator::from_file("test/test_validations.yml").unwrap();
|
|
463
|
+
assert!(validator.validate("test/test_file.csv").unwrap());
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
#[test]
|
|
467
|
+
fn test_csv_validator_from_string() {
|
|
468
|
+
let definition = String::from("
|
|
469
|
+
columns:
|
|
470
|
+
- name: First Column
|
|
471
|
+
regex: ^.+$
|
|
472
|
+
- name: Second Column
|
|
473
|
+
regex: ^.+$
|
|
474
|
+
- name: Third Column
|
|
475
|
+
regex: ^-?[0-9]+$
|
|
476
|
+
min: -23
|
|
477
|
+
max: 2000
|
|
478
|
+
");
|
|
479
|
+
let validator = CSVValidator::from_string(&definition).unwrap();
|
|
480
|
+
assert!(validator.validate("test/test_file.csv").unwrap());
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
#[test]
|
|
484
|
+
fn test_csv_validator_reuse() {
|
|
485
|
+
// Test that we can reuse the same validator for multiple files
|
|
486
|
+
let validator = CSVValidator::from_file("test/test_validations.yml").unwrap();
|
|
487
|
+
assert!(validator.validate("test/test_file.csv").unwrap());
|
|
488
|
+
assert!(validator.validate("test/test_file.csv.gz").unwrap());
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
#[test]
|
|
492
|
+
fn test_csv_validator_all_validation_types() {
|
|
493
|
+
let definition = String::from("
|
|
494
|
+
columns:
|
|
495
|
+
- name: Name
|
|
496
|
+
regex: ^[A-Za-z\\s]{2,50}$
|
|
497
|
+
- name: Age
|
|
498
|
+
format: positive_integer
|
|
499
|
+
min: 0
|
|
500
|
+
max: 120
|
|
501
|
+
- name: Status
|
|
502
|
+
values: [active, inactive, pending]
|
|
503
|
+
");
|
|
504
|
+
let validator = CSVValidator::from_string(&definition).unwrap();
|
|
505
|
+
// This should fail as test_file.csv doesn't match these validations
|
|
506
|
+
assert!(!validator.validate("test/test_file.csv").unwrap());
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
#[test]
|
|
510
|
+
fn test_csv_validator_invalid_format() {
|
|
511
|
+
let definition = String::from("
|
|
512
|
+
columns:
|
|
513
|
+
- name: First Column
|
|
514
|
+
format: unknown_format # This format doesn't exist
|
|
515
|
+
");
|
|
516
|
+
assert!(CSVValidator::from_string(&definition).is_err());
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
#[test]
|
|
520
|
+
fn test_csv_validator_invalid_file() {
|
|
521
|
+
let validator = CSVValidator::from_file("test/test_validations.yml").unwrap();
|
|
522
|
+
assert!(validator.validate("nonexistent_file.csv").is_err());
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
#[test]
|
|
526
|
+
fn test_csv_validator_invalid_yaml() {
|
|
527
|
+
let definition = String::from("
|
|
528
|
+
invalid:
|
|
529
|
+
yaml:
|
|
530
|
+
format
|
|
531
|
+
");
|
|
532
|
+
assert!(CSVValidator::from_string(&definition).is_err());
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
#[test]
|
|
536
|
+
fn test_csv_validator_empty_definition() {
|
|
537
|
+
let definition = String::from("");
|
|
538
|
+
assert!(CSVValidator::from_string(&definition).is_err());
|
|
539
|
+
}
|
|
540
|
+
}
|
csv_validation-0.0.6/PKG-INFO
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: csv_validation
|
|
3
|
-
Version: 0.0.6
|
|
4
|
-
Classifier: Programming Language :: Rust
|
|
5
|
-
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
6
|
-
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
7
|
-
Requires-Python: >=3.8
|
csv_validation-0.0.6/src/lib.rs
DELETED
|
@@ -1,374 +0,0 @@
|
|
|
1
|
-
use crate::Validation::Values;
|
|
2
|
-
use std::collections::{HashMap, HashSet};
|
|
3
|
-
use std::fs;
|
|
4
|
-
use std::fs::File;
|
|
5
|
-
use std::io::{BufReader, Read};
|
|
6
|
-
use std::iter::zip;
|
|
7
|
-
use std::path::Path;
|
|
8
|
-
use csv::Reader;
|
|
9
|
-
use flate2::bufread::GzDecoder;
|
|
10
|
-
use log::{debug, error, info};
|
|
11
|
-
use pyo3::exceptions::{PyRuntimeError};
|
|
12
|
-
use pyo3::prelude::*;
|
|
13
|
-
use regex::Regex;
|
|
14
|
-
use yaml_rust2::YamlLoader;
|
|
15
|
-
use serde::{Deserialize, Serialize};
|
|
16
|
-
use crate::Validation::{RegularExpression};
|
|
17
|
-
|
|
18
|
-
const MAX_SAMPLE_SIZE:u16 = 10;
|
|
19
|
-
|
|
20
|
-
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
21
|
-
enum Validation {
|
|
22
|
-
RegularExpression { expression: String, alias: String },
|
|
23
|
-
Min(f64),
|
|
24
|
-
Max(f64),
|
|
25
|
-
Values(Vec<String>),
|
|
26
|
-
None
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
struct ColumnValidations {
|
|
30
|
-
column_name: String,
|
|
31
|
-
validations: Vec<Validation>
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
#[derive(Serialize, Deserialize)]
|
|
35
|
-
struct ValidationSummary {
|
|
36
|
-
validation: Validation,
|
|
37
|
-
wrong_rows: usize,
|
|
38
|
-
wrong_values_sample: Vec<String>
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
#[derive(Serialize, Deserialize)]
|
|
42
|
-
struct ColumnValidationsSummary {
|
|
43
|
-
column_name: String,
|
|
44
|
-
validation_summaries: Vec<ValidationSummary>
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
#[pyfunction]
|
|
48
|
-
fn validate_with_file(path: &str, definition_path: &str) -> PyResult<bool> {
|
|
49
|
-
info!("Validating file {} against definition file {}", path, definition_path);
|
|
50
|
-
let definition_string = fs::read_to_string(definition_path)?;
|
|
51
|
-
validate(path, definition_string)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/// Validate that CSV file complies with a validations definition file
|
|
55
|
-
#[pyfunction]
|
|
56
|
-
fn validate(path: &str, definition_string: String) -> PyResult<bool> {
|
|
57
|
-
debug!("Validating file {} against definition:\n {}", path, definition_string);
|
|
58
|
-
let validations = get_validations(definition_string.as_str())?;
|
|
59
|
-
|
|
60
|
-
// Pre-Compile and save all Regex expressions to save time in execution
|
|
61
|
-
let mut regex_map = HashMap::new();
|
|
62
|
-
for column_validation in &validations {
|
|
63
|
-
for validation in &column_validation.validations {
|
|
64
|
-
match validation {
|
|
65
|
-
RegularExpression { expression, alias: _ } => {
|
|
66
|
-
regex_map.insert(expression.to_string(), Regex::new(expression.as_str()).unwrap());
|
|
67
|
-
},
|
|
68
|
-
Values(values) => {
|
|
69
|
-
let regex_str = get_regex_string_for_values(values);
|
|
70
|
-
regex_map.insert(regex_str.clone(), Regex::new(regex_str.as_str()).unwrap());
|
|
71
|
-
},
|
|
72
|
-
_ => continue
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Build the CSV reader
|
|
78
|
-
let mut rdr = get_reader_from(path)?;
|
|
79
|
-
|
|
80
|
-
// First validation: Ensure column names and order are exactly as expected
|
|
81
|
-
if validate_column_names(&mut rdr, &validations)? {
|
|
82
|
-
info!("Columns names and order are correct");
|
|
83
|
-
}
|
|
84
|
-
else {
|
|
85
|
-
error!("Expected columns != Real columns");
|
|
86
|
-
return Ok(false);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// Second validation: If column names match, check if also the values match the validations
|
|
90
|
-
let mut validation_summaries_map = build_validation_summaries_map(&validations);
|
|
91
|
-
let mut is_valid_file = true;
|
|
92
|
-
for result in rdr.records() {
|
|
93
|
-
let record = result.unwrap();
|
|
94
|
-
for next_column in zip(record.iter(), validations.iter()) {
|
|
95
|
-
let value = next_column.0;
|
|
96
|
-
let _column_name = &next_column.1.column_name;
|
|
97
|
-
for validation in &next_column.1.validations {
|
|
98
|
-
let valid = apply_validation(value, validation, ®ex_map)?;
|
|
99
|
-
if !valid {
|
|
100
|
-
let validation_summary_list = validation_summaries_map.get_mut(_column_name).unwrap();
|
|
101
|
-
let validation_summary = validation_summary_list
|
|
102
|
-
.iter_mut()
|
|
103
|
-
.find(|val_sum|
|
|
104
|
-
std::mem::discriminant(&val_sum.validation) == std::mem::discriminant(validation)).unwrap();
|
|
105
|
-
validation_summary.wrong_rows += 1;
|
|
106
|
-
if validation_summary.wrong_values_sample.len() < MAX_SAMPLE_SIZE as usize {
|
|
107
|
-
validation_summary.wrong_values_sample.push(value.to_string());
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
is_valid_file = is_valid_file && valid;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// Fill the ColumnValidationSummary for each column
|
|
116
|
-
let mut column_validation_summaries = Vec::new();
|
|
117
|
-
for column_validation in &validations {
|
|
118
|
-
let validation_summary_for_column =
|
|
119
|
-
validation_summaries_map.remove(&column_validation.column_name).unwrap();
|
|
120
|
-
let column_validation_summary = ColumnValidationsSummary {
|
|
121
|
-
column_name: column_validation.column_name.clone(),
|
|
122
|
-
validation_summaries: validation_summary_for_column
|
|
123
|
-
};
|
|
124
|
-
column_validation_summaries.push(column_validation_summary);
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
let validation_result_json = serde_json::to_string(&column_validation_summaries).unwrap();
|
|
128
|
-
|
|
129
|
-
debug!("VALIDATIONS SUMMARY");
|
|
130
|
-
debug!("==================================================================================");
|
|
131
|
-
for column_validation_summary in column_validation_summaries {
|
|
132
|
-
debug!("Column: '{}'", column_validation_summary.column_name);
|
|
133
|
-
for validation_summary in column_validation_summary.validation_summaries {
|
|
134
|
-
let wrong_values_sample = if validation_summary.wrong_values_sample.len() > 0 {
|
|
135
|
-
format!(" | Wrong Values Sample: {:?}", validation_summary.wrong_values_sample)
|
|
136
|
-
} else {
|
|
137
|
-
String::from("" )
|
|
138
|
-
};
|
|
139
|
-
debug!("\tValidation {:?} => Wrong Rows: {}{}", validation_summary.validation,
|
|
140
|
-
validation_summary.wrong_rows, wrong_values_sample);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
if is_valid_file {
|
|
145
|
-
info!("OK: File matches the validations");
|
|
146
|
-
}
|
|
147
|
-
else {
|
|
148
|
-
info!("NO OK: File DOESN'T match validations");
|
|
149
|
-
}
|
|
150
|
-
Ok(is_valid_file)
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
fn build_validation_summaries_map(validations: &Vec<ColumnValidations>) -> HashMap<String, Vec<ValidationSummary>> {
|
|
154
|
-
let mut validation_summaries_map = HashMap::new();
|
|
155
|
-
for validation in validations {
|
|
156
|
-
let mut validation_summaries = Vec::new();
|
|
157
|
-
for column_validation in &validation.validations {
|
|
158
|
-
let validation_summary =
|
|
159
|
-
ValidationSummary{validation: (*column_validation).clone(), wrong_rows: 0, wrong_values_sample: Vec::new()};
|
|
160
|
-
validation_summaries.push(validation_summary);
|
|
161
|
-
}
|
|
162
|
-
validation_summaries_map.insert(validation.column_name.clone(), validation_summaries);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
validation_summaries_map
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
fn apply_validation(value: &str, validation: &Validation, regex_map: &HashMap<String, Regex>) -> PyResult<bool> {
|
|
169
|
-
match validation {
|
|
170
|
-
RegularExpression { expression: exp, alias: _ } => {
|
|
171
|
-
let regex = regex_map.get(exp).unwrap();
|
|
172
|
-
Ok(regex.is_match(value))
|
|
173
|
-
},
|
|
174
|
-
Validation::Min(min) => {
|
|
175
|
-
match value.parse::<f64>() {
|
|
176
|
-
Ok(value) => Ok(value >= *min),
|
|
177
|
-
Err(_) => Ok(false)
|
|
178
|
-
}
|
|
179
|
-
},
|
|
180
|
-
Validation::Max(max) => {
|
|
181
|
-
match value.parse::<f64>() {
|
|
182
|
-
Ok(value) => Ok(value <= *max),
|
|
183
|
-
Err(_) => Ok(false)
|
|
184
|
-
}
|
|
185
|
-
},
|
|
186
|
-
Validation::Values(values) => {
|
|
187
|
-
let regex_str = get_regex_string_for_values(values);
|
|
188
|
-
let regex = regex_map.get(®ex_str).unwrap();
|
|
189
|
-
Ok(regex.is_match(value))
|
|
190
|
-
}
|
|
191
|
-
Validation::None => Err(PyRuntimeError::new_err("'None' validation has no implementation"))
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
fn get_regex_string_for_values(values: &Vec<String>) -> String {
|
|
196
|
-
values.join("|")
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/// Infers the file compression type and returns the corresponding buffered reader
|
|
200
|
-
fn get_reader_from(path: &str) -> PyResult<Reader<Box<dyn Read>>> {
|
|
201
|
-
let buf_reader = BufReader::new(File::open(Path::new(path))?);
|
|
202
|
-
if is_gzip_file(path)? {
|
|
203
|
-
debug!("File is gzipped");
|
|
204
|
-
let read_capacity = 10 * 1024_usize.pow(2);
|
|
205
|
-
let reader = BufReader::with_capacity(read_capacity, GzDecoder::new(buf_reader));
|
|
206
|
-
Ok(Reader::from_reader(Box::new(reader)))
|
|
207
|
-
}
|
|
208
|
-
else {
|
|
209
|
-
Ok(Reader::from_reader(Box::new(buf_reader)))
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
fn is_gzip_file(path: &str) -> PyResult<bool> {
|
|
214
|
-
let mut bytes = [0u8; 2];
|
|
215
|
-
File::open(Path::new(path))?.read_exact(&mut bytes)?;
|
|
216
|
-
Ok(bytes[0] == 0x1f && bytes[1] == 0x8b)
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
fn get_validations(definition_string: &str) -> PyResult<Vec<ColumnValidations>> {
|
|
220
|
-
// Read the YAML definition with the validations
|
|
221
|
-
let config = YamlLoader::load_from_str(definition_string).unwrap();
|
|
222
|
-
// Get the column names list and each associated validation
|
|
223
|
-
let columns = &config[0]["columns"];
|
|
224
|
-
let mut column_names = vec![];
|
|
225
|
-
let mut column_validations = vec![];
|
|
226
|
-
for column in columns.as_vec().unwrap() {
|
|
227
|
-
let column_def = column.as_hash().unwrap();
|
|
228
|
-
let mut column_name = "";
|
|
229
|
-
let mut validations = vec![];
|
|
230
|
-
for validation_definition in column_def.iter() {
|
|
231
|
-
let key = validation_definition.0.as_str().unwrap();
|
|
232
|
-
let value = validation_definition.1;
|
|
233
|
-
let validation = match key {
|
|
234
|
-
"name" => {
|
|
235
|
-
column_name = value.as_str().unwrap();
|
|
236
|
-
column_names.push(column_name);
|
|
237
|
-
Ok(Validation::None)
|
|
238
|
-
}
|
|
239
|
-
"regex" => { Ok(Validation::RegularExpression { expression: String::from(value.as_str().unwrap()), alias: String::from("regex") }) }
|
|
240
|
-
"min" => { Ok(Validation::Min(value.as_i64().unwrap() as f64)) }
|
|
241
|
-
"max" => { Ok(Validation::Max(value.as_i64().unwrap() as f64)) }
|
|
242
|
-
"values" => {
|
|
243
|
-
Ok(Validation::Values(value.as_vec().unwrap()
|
|
244
|
-
.iter()
|
|
245
|
-
.map(|v| String::from(v.as_str().unwrap()))
|
|
246
|
-
.collect()
|
|
247
|
-
))
|
|
248
|
-
}
|
|
249
|
-
"format" => {
|
|
250
|
-
let format = value.as_str().unwrap();
|
|
251
|
-
let regex_for_format = get_regex_for_format(format)?;
|
|
252
|
-
Ok(Validation::RegularExpression { expression: regex_for_format, alias: format.to_string() })
|
|
253
|
-
}
|
|
254
|
-
_ => Err(PyRuntimeError::new_err(format!("Unknown validation: {key}")))
|
|
255
|
-
}?;
|
|
256
|
-
|
|
257
|
-
if key != "name" {
|
|
258
|
-
validations.push(validation);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
}
|
|
262
|
-
let new_validations = ColumnValidations { column_name: column_name.to_string(), validations: validations };
|
|
263
|
-
column_validations.push(new_validations);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
Ok(column_validations)
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
fn get_regex_for_format(format: &str) -> PyResult<String> {
|
|
270
|
-
match format {
|
|
271
|
-
"integer" => Ok(String::from("^-?\\d+$")),
|
|
272
|
-
"positive integer" => Ok(String::from("^\\d+$")),
|
|
273
|
-
_ => Err(PyRuntimeError::new_err(format!("Unknown format: {format}")))
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
fn validate_column_names(reader: &mut Reader<Box<dyn Read>>, validations: &Vec<ColumnValidations>) -> PyResult<bool> {
|
|
278
|
-
let expected_column_names = validations.iter()
|
|
279
|
-
.map(|v| v.column_name.clone())
|
|
280
|
-
.collect::<Vec<String>>();
|
|
281
|
-
debug!("Expected Column Names: {:?}", expected_column_names);
|
|
282
|
-
|
|
283
|
-
let headers: Vec<String> = reader.headers().unwrap().iter().map(|s| String::from(s) ).collect();
|
|
284
|
-
debug!("Actual Column Names: {:?}", headers);
|
|
285
|
-
|
|
286
|
-
if expected_column_names != headers {
|
|
287
|
-
if expected_column_names.len() != headers.len() {
|
|
288
|
-
let expected_columns_set: HashSet<String> = expected_column_names.iter().cloned().collect();
|
|
289
|
-
let headers_set: HashSet<String> = headers.iter().cloned().collect();
|
|
290
|
-
debug!("File headers not in expected columns: {:?}", headers_set.difference(&expected_columns_set));
|
|
291
|
-
debug!("Columns in expected columns not in file headers: {:?}", expected_columns_set.difference(&headers_set));
|
|
292
|
-
}
|
|
293
|
-
else {
|
|
294
|
-
for (expected_column, header) in zip(expected_column_names, headers) {
|
|
295
|
-
if expected_column != header {
|
|
296
|
-
debug!("{:?} != {:?}", expected_column, header);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
return Ok(false)
|
|
301
|
-
}
|
|
302
|
-
Ok(true)
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/// A Python module implemented in Rust.
|
|
306
|
-
#[pymodule]
|
|
307
|
-
fn csv_validation(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
308
|
-
pyo3_log::init();
|
|
309
|
-
m.add_function(wrap_pyfunction!(validate, m)?)?;
|
|
310
|
-
m.add_function(wrap_pyfunction!(validate_with_file, m)?)?;
|
|
311
|
-
Ok(())
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
#[cfg(test)]
|
|
315
|
-
mod tests {
|
|
316
|
-
use simple_logger::SimpleLogger;
|
|
317
|
-
use crate::{validate, validate_with_file};
|
|
318
|
-
|
|
319
|
-
#[test]
|
|
320
|
-
fn init_logger() {
|
|
321
|
-
SimpleLogger::new().init().unwrap();
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
#[test]
|
|
325
|
-
fn test_validate_csv_with_file() {
|
|
326
|
-
assert!(validate_with_file("test/test_file.csv", "test/test_validations.yml").unwrap());
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
#[test]
|
|
330
|
-
fn test_validate_csv_gz_with_file() {
|
|
331
|
-
assert!(validate_with_file("test/test_file.csv.gz", "test/test_validations.yml").unwrap());
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
#[test]
|
|
335
|
-
fn test_wrong_headers() {
|
|
336
|
-
let definition = String::from("
|
|
337
|
-
columns:
|
|
338
|
-
- name: First Column
|
|
339
|
-
- name: Second Column
|
|
340
|
-
- name: Wrong Column
|
|
341
|
-
- name: Expected Column Not In File
|
|
342
|
-
");
|
|
343
|
-
assert!(!validate("test/test_file.csv", definition).unwrap());
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
#[test]
|
|
347
|
-
fn test_format_validation() {
|
|
348
|
-
let definition = String::from("
|
|
349
|
-
columns:
|
|
350
|
-
- name: First Column
|
|
351
|
-
- name: Second Column
|
|
352
|
-
- name: Third Column
|
|
353
|
-
format: integer
|
|
354
|
-
");
|
|
355
|
-
assert!(validate("test/test_file.csv", definition).unwrap());
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
#[test]
|
|
359
|
-
fn test_validate_csv() {
|
|
360
|
-
let definition = String::from("
|
|
361
|
-
columns:
|
|
362
|
-
- name: First Column
|
|
363
|
-
regex: ^.+$
|
|
364
|
-
- name: Second Column
|
|
365
|
-
values: [one_value, or_another]
|
|
366
|
-
- name: Third Column
|
|
367
|
-
regex: ^-?[0-9]+$
|
|
368
|
-
min: -23
|
|
369
|
-
max: 2000
|
|
370
|
-
");
|
|
371
|
-
|
|
372
|
-
assert!(validate("test/test_file.csv", definition).unwrap());
|
|
373
|
-
}
|
|
374
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|