csv-validation 0.0.16__tar.gz → 0.0.18__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.16 → csv_validation-0.0.18}/.github/workflows/CI.yml +7 -4
- {csv_validation-0.0.16 → csv_validation-0.0.18}/Cargo.lock +13 -3
- {csv_validation-0.0.16 → csv_validation-0.0.18}/Cargo.toml +2 -1
- csv_validation-0.0.18/PKG-INFO +340 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/README.md +69 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/build.sh +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/pyproject.toml +6 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/src/lib.rs +162 -3
- csv_validation-0.0.18/test/duplicated_unique_keys.csv +6 -0
- csv_validation-0.0.16/PKG-INFO +0 -8
- {csv_validation-0.0.16 → csv_validation-0.0.18}/.gitignore +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/LICENSE +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/MANIFEST.in +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/csv_validation.pyi +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/test/empty_values.csv +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/test/test_file.csv +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/test/test_file.csv.gz +0 -0
- {csv_validation-0.0.16 → csv_validation-0.0.18}/test/test_validations.yml +0 -0
|
@@ -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
|
|
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
|
|
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
|
|
@@ -102,6 +102,9 @@ jobs:
|
|
|
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
|
|
@@ -117,7 +120,7 @@ jobs:
|
|
|
117
120
|
strategy:
|
|
118
121
|
matrix:
|
|
119
122
|
platform:
|
|
120
|
-
- runner: macos-
|
|
123
|
+
- runner: macos-14
|
|
121
124
|
target: x86_64
|
|
122
125
|
- runner: macos-14
|
|
123
126
|
target: aarch64
|
|
@@ -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
|
|
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,13 +83,14 @@ dependencies = [
|
|
|
83
83
|
|
|
84
84
|
[[package]]
|
|
85
85
|
name = "csv_validation"
|
|
86
|
-
version = "0.0.
|
|
86
|
+
version = "0.0.18"
|
|
87
87
|
dependencies = [
|
|
88
88
|
"csv",
|
|
89
89
|
"flate2",
|
|
90
90
|
"log",
|
|
91
91
|
"pyo3",
|
|
92
92
|
"pyo3-log",
|
|
93
|
+
"redb",
|
|
93
94
|
"regex",
|
|
94
95
|
"serde",
|
|
95
96
|
"simple_logger",
|
|
@@ -174,9 +175,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
|
|
174
175
|
|
|
175
176
|
[[package]]
|
|
176
177
|
name = "libc"
|
|
177
|
-
version = "0.2.
|
|
178
|
+
version = "0.2.178"
|
|
178
179
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
179
|
-
checksum = "
|
|
180
|
+
checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
|
|
180
181
|
|
|
181
182
|
[[package]]
|
|
182
183
|
name = "log"
|
|
@@ -333,6 +334,15 @@ dependencies = [
|
|
|
333
334
|
"proc-macro2",
|
|
334
335
|
]
|
|
335
336
|
|
|
337
|
+
[[package]]
|
|
338
|
+
name = "redb"
|
|
339
|
+
version = "3.1.0"
|
|
340
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
341
|
+
checksum = "ae323eb086579a3769daa2c753bb96deb95993c534711e0dbe881b5192906a06"
|
|
342
|
+
dependencies = [
|
|
343
|
+
"libc",
|
|
344
|
+
]
|
|
345
|
+
|
|
336
346
|
[[package]]
|
|
337
347
|
name = "regex"
|
|
338
348
|
version = "1.11.1"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "csv_validation"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.18"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
|
|
@@ -19,3 +19,4 @@ regex = "1.11.1"
|
|
|
19
19
|
simple_logger = "5.0.0"
|
|
20
20
|
yaml-rust2 = "0.10.0"
|
|
21
21
|
serde = { version = "1.0.218", features = ["derive"] }
|
|
22
|
+
redb = "3.1.0"
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: csv_validation
|
|
3
|
+
Version: 0.0.18
|
|
4
|
+
Classifier: Programming Language :: Rust
|
|
5
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
6
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Summary: Blazing fast format validations for your CSV files
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
11
|
+
Project-URL: Homepage, https://github.com/charro/csv_validation
|
|
12
|
+
|
|
13
|
+
# CSV Validation Library
|
|
14
|
+
|
|
15
|
+
Blazing fast format validations for your CSV files
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- ✨ Validate both plain and gzipped CSV files
|
|
22
|
+
- 🔍 Multiple validation types supported:
|
|
23
|
+
- Correct column name and order
|
|
24
|
+
- Regular expressions
|
|
25
|
+
- Well-known formats (integer, decimal, etc.)
|
|
26
|
+
- Minimum/Maximum numerical value checks
|
|
27
|
+
- Value set validation (allowed values)
|
|
28
|
+
- 🦀 + 🐍 Rust lib with Python bindings included
|
|
29
|
+
- 📝 Detailed validation summaries with sample invalid values
|
|
30
|
+
- 🚀 High performance with optimizations like regex pre-compilation
|
|
31
|
+
- 📊 Support for large CSV files
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
### Python
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install csv_validation
|
|
39
|
+
```
|
|
40
|
+
```bash
|
|
41
|
+
poetry add csv_validation
|
|
42
|
+
```
|
|
43
|
+
```bash
|
|
44
|
+
uv add csv_validation
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Usage
|
|
48
|
+
|
|
49
|
+
### Python
|
|
50
|
+
|
|
51
|
+
#### You can provide a file with the validation rules
|
|
52
|
+
```python
|
|
53
|
+
from csv_validation import CSVValidator
|
|
54
|
+
|
|
55
|
+
validator = CSVValidator.from_file("validation_rules.yaml")
|
|
56
|
+
is_valid = validator.validate("data.csv")
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
#### You can also create a validator from a string
|
|
60
|
+
```python
|
|
61
|
+
validation_rules = """
|
|
62
|
+
columns:
|
|
63
|
+
- name: Name
|
|
64
|
+
regex: ^[A-Za-z\s]{2,50}$
|
|
65
|
+
- name: Age
|
|
66
|
+
format: positive_integer
|
|
67
|
+
max: 120
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
validator = CSVValidator.from_string(validation_rules)
|
|
71
|
+
# Optionally set a custom column separator
|
|
72
|
+
validator.set_separator(";") # Default is comma (,)
|
|
73
|
+
|
|
74
|
+
# Validate a CSV file
|
|
75
|
+
is_valid = validator.validate("data.csv")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Validation Definition Format
|
|
79
|
+
|
|
80
|
+
Create a small, easy-to-read YAML file with your validation rules. Example:
|
|
81
|
+
|
|
82
|
+
```yaml
|
|
83
|
+
columns:
|
|
84
|
+
- name: Name
|
|
85
|
+
regex: ^[A-Za-z\s]{2,50}$ # Letters and spaces, 2-50 characters
|
|
86
|
+
- name: Family Name
|
|
87
|
+
regex: ^[A-Za-z\s'-]{2,50}$ # Letters, spaces, hyphens and apostrophes
|
|
88
|
+
- name: Age
|
|
89
|
+
format: positive_integer # Using predefined format instead of custom regex
|
|
90
|
+
max: 120
|
|
91
|
+
- name: Salary
|
|
92
|
+
format: integer # Allows negative integers too
|
|
93
|
+
min: 20000
|
|
94
|
+
- name: Email
|
|
95
|
+
regex: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # Standard email format
|
|
96
|
+
- name: Phone
|
|
97
|
+
regex: ^\+?[0-9]{10,15}$ # International phone format with optional +
|
|
98
|
+
- name: Status
|
|
99
|
+
values: [active, inactive, pending, suspended] # Only these values are allowed
|
|
100
|
+
- name: Gender
|
|
101
|
+
values: [M, F, NB, O] # M: Male, F: Female, NB: Non-Binary, O: Other
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Validation Types
|
|
105
|
+
|
|
106
|
+
1. **Regular Expression** (`regex`)
|
|
107
|
+
- Validate fields against custom regex patterns
|
|
108
|
+
|
|
109
|
+
2. **Format** (`format`)
|
|
110
|
+
- Predefined formats for common validations (This is the recommended way to validate numeric fields)
|
|
111
|
+
- In the background, the library uses regex patterns to validate formats.
|
|
112
|
+
- Available formats:
|
|
113
|
+
- `integer`: Validates any integer number (positive or negative)
|
|
114
|
+
- `positive integer`: Validates positive integer numbers
|
|
115
|
+
- `negative integer`: Validates negative integer numbers
|
|
116
|
+
- `decimal`/`decimal point`: Validates any decimal number (positive or negative) using point as decimal separator
|
|
117
|
+
- `negative decimal point`: Validates negative decimal numbers using point as decimal separator
|
|
118
|
+
- `decimal comma`: Validates decimal numbers using comma as decimal separator
|
|
119
|
+
- `positive decimal`/`positive decimal point`: Validates positive decimal numbers using point as decimal separator
|
|
120
|
+
- `positive decimal comma`: Validates positive decimal numbers using comma as decimal separator
|
|
121
|
+
- `decimal scientific`: Validates decimal numbers in scientific notation (e.g. 23.02e-12)
|
|
122
|
+
- `decimal scientific comma`: Validates decimal numbers in scientific notation using comma as decimal separator
|
|
123
|
+
- `positive decimal scientific`: Validates positive decimal numbers in scientific notation
|
|
124
|
+
- More formats will be added in upcoming versions
|
|
125
|
+
|
|
126
|
+
3. **Minimum Value** (`min`)
|
|
127
|
+
- Check if numeric fields are greater than or equal to a specified value
|
|
128
|
+
|
|
129
|
+
4. **Maximum Value** (`max`)
|
|
130
|
+
- Check if numeric fields are less than or equal to a specified value
|
|
131
|
+
|
|
132
|
+
5. **Value Set** (`values`)
|
|
133
|
+
- Ensure fields only contain values from a predefined set
|
|
134
|
+
|
|
135
|
+
6. **Extra** (`extra`)
|
|
136
|
+
- Extra validations that normally complement one of the other types
|
|
137
|
+
- Available extras:
|
|
138
|
+
- `non_empty`: Validates that field contains at least one character
|
|
139
|
+
|
|
140
|
+
You can add as many validation types as you want for the same column, but take into account that the
|
|
141
|
+
column only will be considered correct if all the validations are OK.
|
|
142
|
+
|
|
143
|
+
## Global Validations
|
|
144
|
+
|
|
145
|
+
### empty_not_ok
|
|
146
|
+
|
|
147
|
+
Empty values (empty string '') are considered correct and accepted by default.
|
|
148
|
+
However, if your data must always have some content,
|
|
149
|
+
you can add a global `empty_not_ok` flag at the root level of your YAML definition to automatically
|
|
150
|
+
add the `extra: non_empty` validation to all columns:
|
|
151
|
+
|
|
152
|
+
```yaml
|
|
153
|
+
empty_not_ok: true
|
|
154
|
+
columns:
|
|
155
|
+
- name: Column1
|
|
156
|
+
# other validations...
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Unique Key (Duplicate Rows) Validation
|
|
160
|
+
|
|
161
|
+
You can enforce uniqueness across one or more columns by adding a root-level `unique` field in your YAML definition. This enables a memory-efficient duplicate detection that scales to very large files.
|
|
162
|
+
|
|
163
|
+
- Accepts a single column name (string) or a list of column names (array of strings).
|
|
164
|
+
- Works with both plain and gzipped CSV files.
|
|
165
|
+
- Uses a high-performant disk-backed key-value store (redb) under the hood to keep memory usage low.
|
|
166
|
+
|
|
167
|
+
Examples:
|
|
168
|
+
|
|
169
|
+
```yaml
|
|
170
|
+
# Single-column unique key
|
|
171
|
+
unique: ID
|
|
172
|
+
columns:
|
|
173
|
+
- name: ID
|
|
174
|
+
format: positive integer
|
|
175
|
+
- name: Name
|
|
176
|
+
regex: ^[A-Za-z\s]{2,50}$
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
```yaml
|
|
180
|
+
# Composite unique key across multiple columns
|
|
181
|
+
unique: [isin, date, score_provider]
|
|
182
|
+
columns:
|
|
183
|
+
- name: isin
|
|
184
|
+
regex: ^[A-Z0-9]{12}$
|
|
185
|
+
- name: date
|
|
186
|
+
regex: ^\d{4}-\d{2}-\d{2}$
|
|
187
|
+
- name: score_provider
|
|
188
|
+
values: [sp1, sp2, sp3]
|
|
189
|
+
- name: score
|
|
190
|
+
format: decimal
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
What you will see in the summary:
|
|
194
|
+
- Always shows the number of duplicate key groups found.
|
|
195
|
+
- If there are more than 100 duplicate groups, only the first 100 are displayed as a sample (with their occurrence counts), and the total number is indicated.
|
|
196
|
+
- If no duplicates are found, it reports: "Duplicates found: 0".
|
|
197
|
+
|
|
198
|
+
Sample output (composite key):
|
|
199
|
+
|
|
200
|
+
```
|
|
201
|
+
UNIQUE KEY: column(s): ["isin", "date", "score_provider"]
|
|
202
|
+
|
|
203
|
+
DUPLICATED KEYS (groups found: 134)
|
|
204
|
+
--------------------------------------------------
|
|
205
|
+
Showing first 100 of 134 duplicate key groups:
|
|
206
|
+
- (isin='US0004026250', date='2025-10-01', score_provider='sp1') -> occurrences: 3
|
|
207
|
+
- (isin='US5949181045', date='2025-10-01', score_provider='sp2') -> occurrences: 4
|
|
208
|
+
... up to 100 lines ...
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
If none:
|
|
212
|
+
|
|
213
|
+
```
|
|
214
|
+
UNIQUE KEYS CHECK
|
|
215
|
+
--------------------------------------------------
|
|
216
|
+
- No Duplicates found
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Performance note: Duplicate detection stores only the unique keys on disk and keeps a tiny in-memory summary used for printing the report. This allows validating huge datasets with minimal RAM usage.
|
|
220
|
+
|
|
221
|
+
### Column Separator
|
|
222
|
+
|
|
223
|
+
By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
|
|
224
|
+
|
|
225
|
+
```python
|
|
226
|
+
validator = CSVValidator.from_file("rules.yml")
|
|
227
|
+
validator.set_separator(";") # Use semicolon as separator
|
|
228
|
+
validator.set_separator("\t") # Use tab as separator
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Decimal Separator
|
|
232
|
+
|
|
233
|
+
By default, the library uses point (.) as the decimal separator. You can change this using the `set_decimal_separator` method:
|
|
234
|
+
|
|
235
|
+
```python
|
|
236
|
+
validator = CSVValidator.from_file("rules.yml")
|
|
237
|
+
validator.set_decimal_separator(",") # Use comma
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Error Handling
|
|
241
|
+
|
|
242
|
+
The library provides detailed validation reports through Python's logging system. When a validation fails, you'll get information about:
|
|
243
|
+
- Which columns failed validation
|
|
244
|
+
- What type of validation failed
|
|
245
|
+
- Sample of invalid values
|
|
246
|
+
- Number of rows that failed each validation
|
|
247
|
+
|
|
248
|
+
### Example of validation report
|
|
249
|
+
|
|
250
|
+
```
|
|
251
|
+
VALIDATIONS SUMMARY
|
|
252
|
+
==================================================
|
|
253
|
+
FILE: /test.csv
|
|
254
|
+
Rows: 232230 | Columns: 5
|
|
255
|
+
|
|
256
|
+
CORRECT COLUMNS: 3/5
|
|
257
|
+
--------------------------------------------------
|
|
258
|
+
- County: [✔] OK
|
|
259
|
+
✔ - RegularExpression { expression: "^.*$", alias: "regex" }
|
|
260
|
+
- City: [✔] OK
|
|
261
|
+
✔ - RegularExpression { expression: "^.*$", alias: "regex" }
|
|
262
|
+
- Model Year: [✔] OK
|
|
263
|
+
✔ - RegularExpression { expression: "^[0-9]+$", alias: "regex" }
|
|
264
|
+
✔ - Min(1999.0)
|
|
265
|
+
✔ - Max(2025.78)
|
|
266
|
+
|
|
267
|
+
WRONG COLUMNS: 2/5
|
|
268
|
+
--------------------------------------------------
|
|
269
|
+
- State: [✖] FAIL
|
|
270
|
+
✖ - Values(["WA", "OR", "NY", "DC", "CA", "TX", "FL", "OK", "MO", "KS", "VA", "MA", "MO", "NC", "IL", "AL", "WY", "CO", "PA", "WI", "MD", "NV", "AZ"])
|
|
271
|
+
"Wrong Rows: 93 | Sample: 'GA','NJ','CT','NJ','CT','CT','CT','NE','CT','NH'"
|
|
272
|
+
- Postal Code: [✖] FAIL
|
|
273
|
+
✔ - RegularExpression { expression: "^$|^-?\\d+$", alias: "integer" }
|
|
274
|
+
✖ - RegularExpression { expression: "^.+$", alias: "non_empty" }
|
|
275
|
+
"Wrong Rows: 4 | Sample: '','','',''"
|
|
276
|
+
|
|
277
|
+
VALIDATION RESULT
|
|
278
|
+
--------------------------------------------------
|
|
279
|
+
[✖] FAIL: File DOESN'T match all validations
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## Development
|
|
283
|
+
|
|
284
|
+
### Prerequisites
|
|
285
|
+
|
|
286
|
+
- Rust 2021 edition or later
|
|
287
|
+
- Python 3.6+ (for Python bindings)
|
|
288
|
+
- Cargo and standard Rust tooling
|
|
289
|
+
|
|
290
|
+
### Building from Source (Rust version)
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
# Clone the repository
|
|
294
|
+
git clone https://github.com/charro/csv_validation
|
|
295
|
+
cd csv_validation
|
|
296
|
+
|
|
297
|
+
# Build the project
|
|
298
|
+
cargo build --release
|
|
299
|
+
|
|
300
|
+
# Run tests
|
|
301
|
+
cargo test
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## Dependencies
|
|
305
|
+
|
|
306
|
+
- `csv`: CSV parsing
|
|
307
|
+
- `flate2`: Compression support
|
|
308
|
+
- `pyo3`: Python bindings
|
|
309
|
+
- `regex`: Regular expression support
|
|
310
|
+
- `yaml-rust2`: YAML parsing
|
|
311
|
+
- `redb`: Disk-backed key-value storage used for memory-efficient duplicate detection
|
|
312
|
+
- Various utilities for logging and serialization
|
|
313
|
+
|
|
314
|
+
## License
|
|
315
|
+
|
|
316
|
+
MIT License
|
|
317
|
+
|
|
318
|
+
Copyright (c) 2024 CSV Validation Contributors
|
|
319
|
+
|
|
320
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
321
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
322
|
+
in the Software without restriction, including without limitation the rights
|
|
323
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
324
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
325
|
+
furnished to do so, subject to the following conditions:
|
|
326
|
+
|
|
327
|
+
The above copyright notice and this permission notice shall be included in all
|
|
328
|
+
copies or substantial portions of the Software.
|
|
329
|
+
|
|
330
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
331
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
332
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
333
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
334
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
335
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
336
|
+
SOFTWARE.
|
|
337
|
+
|
|
338
|
+
## Contributing
|
|
339
|
+
|
|
340
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -25,6 +25,12 @@ This is a Python lib with a Rust core that will allow you to validate huge CSV f
|
|
|
25
25
|
```bash
|
|
26
26
|
pip install csv_validation
|
|
27
27
|
```
|
|
28
|
+
```bash
|
|
29
|
+
poetry add csv_validation
|
|
30
|
+
```
|
|
31
|
+
```bash
|
|
32
|
+
uv add csv_validation
|
|
33
|
+
```
|
|
28
34
|
|
|
29
35
|
## Usage
|
|
30
36
|
|
|
@@ -138,6 +144,68 @@ columns:
|
|
|
138
144
|
# other validations...
|
|
139
145
|
```
|
|
140
146
|
|
|
147
|
+
### Unique Key (Duplicate Rows) Validation
|
|
148
|
+
|
|
149
|
+
You can enforce uniqueness across one or more columns by adding a root-level `unique` field in your YAML definition. This enables a memory-efficient duplicate detection that scales to very large files.
|
|
150
|
+
|
|
151
|
+
- Accepts a single column name (string) or a list of column names (array of strings).
|
|
152
|
+
- Works with both plain and gzipped CSV files.
|
|
153
|
+
- Uses a high-performant disk-backed key-value store (redb) under the hood to keep memory usage low.
|
|
154
|
+
|
|
155
|
+
Examples:
|
|
156
|
+
|
|
157
|
+
```yaml
|
|
158
|
+
# Single-column unique key
|
|
159
|
+
unique: ID
|
|
160
|
+
columns:
|
|
161
|
+
- name: ID
|
|
162
|
+
format: positive integer
|
|
163
|
+
- name: Name
|
|
164
|
+
regex: ^[A-Za-z\s]{2,50}$
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
```yaml
|
|
168
|
+
# Composite unique key across multiple columns
|
|
169
|
+
unique: [isin, date, score_provider]
|
|
170
|
+
columns:
|
|
171
|
+
- name: isin
|
|
172
|
+
regex: ^[A-Z0-9]{12}$
|
|
173
|
+
- name: date
|
|
174
|
+
regex: ^\d{4}-\d{2}-\d{2}$
|
|
175
|
+
- name: score_provider
|
|
176
|
+
values: [sp1, sp2, sp3]
|
|
177
|
+
- name: score
|
|
178
|
+
format: decimal
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
What you will see in the summary:
|
|
182
|
+
- Always shows the number of duplicate key groups found.
|
|
183
|
+
- If there are more than 100 duplicate groups, only the first 100 are displayed as a sample (with their occurrence counts), and the total number is indicated.
|
|
184
|
+
- If no duplicates are found, it reports: "Duplicates found: 0".
|
|
185
|
+
|
|
186
|
+
Sample output (composite key):
|
|
187
|
+
|
|
188
|
+
```
|
|
189
|
+
UNIQUE KEY: column(s): ["isin", "date", "score_provider"]
|
|
190
|
+
|
|
191
|
+
DUPLICATED KEYS (groups found: 134)
|
|
192
|
+
--------------------------------------------------
|
|
193
|
+
Showing first 100 of 134 duplicate key groups:
|
|
194
|
+
- (isin='US0004026250', date='2025-10-01', score_provider='sp1') -> occurrences: 3
|
|
195
|
+
- (isin='US5949181045', date='2025-10-01', score_provider='sp2') -> occurrences: 4
|
|
196
|
+
... up to 100 lines ...
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
If none:
|
|
200
|
+
|
|
201
|
+
```
|
|
202
|
+
UNIQUE KEYS CHECK
|
|
203
|
+
--------------------------------------------------
|
|
204
|
+
- No Duplicates found
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Performance note: Duplicate detection stores only the unique keys on disk and keeps a tiny in-memory summary used for printing the report. This allows validating huge datasets with minimal RAM usage.
|
|
208
|
+
|
|
141
209
|
### Column Separator
|
|
142
210
|
|
|
143
211
|
By default, the library uses comma (,) as the column separator. You can change this using the `set_separator` method:
|
|
@@ -228,6 +296,7 @@ cargo test
|
|
|
228
296
|
- `pyo3`: Python bindings
|
|
229
297
|
- `regex`: Regular expression support
|
|
230
298
|
- `yaml-rust2`: YAML parsing
|
|
299
|
+
- `redb`: Disk-backed key-value storage used for memory-efficient duplicate detection
|
|
231
300
|
- Various utilities for logging and serialization
|
|
232
301
|
|
|
233
302
|
## License
|
|
File without changes
|
|
@@ -11,5 +11,11 @@ classifiers = [
|
|
|
11
11
|
"Programming Language :: Python :: Implementation :: PyPy",
|
|
12
12
|
]
|
|
13
13
|
dynamic = ["version"]
|
|
14
|
+
description = "Blazing fast format validations for your CSV files"
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
"Homepage" = "https://github.com/charro/csv_validation"
|
|
19
|
+
|
|
14
20
|
[tool.maturin]
|
|
15
21
|
features = ["pyo3/extension-module"]
|
|
@@ -14,11 +14,27 @@ use regex::Regex;
|
|
|
14
14
|
use yaml_rust2::{Yaml, YamlLoader};
|
|
15
15
|
use serde::{Deserialize, Serialize};
|
|
16
16
|
use crate::Validation::{RegularExpression};
|
|
17
|
+
use redb::{Database, ReadableTable, TableDefinition};
|
|
17
18
|
|
|
18
19
|
const MAX_SAMPLE_SIZE:u16 = 10;
|
|
19
20
|
const DEFAULT_COLUMN_SEPARATOR:u8 = b',';
|
|
20
21
|
const DEFAULT_DECIMAL_SEPARATOR:char = '.';
|
|
21
22
|
|
|
23
|
+
const DUPLICATES_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("duplicates");
|
|
24
|
+
|
|
25
|
+
// A simple guard to ensure the temp file is deleted when it goes out of scope.
|
|
26
|
+
struct CleanupGuard {
|
|
27
|
+
path: String,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
impl Drop for CleanupGuard {
|
|
31
|
+
fn drop(&mut self) {
|
|
32
|
+
if Path::new(&self.path).exists() {
|
|
33
|
+
let _ = std::fs::remove_file(&self.path);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
22
38
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
23
39
|
enum Validation {
|
|
24
40
|
RegularExpression { expression: String, alias: String },
|
|
@@ -349,7 +365,9 @@ struct CSVValidator {
|
|
|
349
365
|
validations: Vec<ColumnValidations>,
|
|
350
366
|
regex_map: HashMap<String, Regex>,
|
|
351
367
|
separator: u8,
|
|
352
|
-
decimal_separator: char
|
|
368
|
+
decimal_separator: char,
|
|
369
|
+
// Optional list of column names that compose a unique key constraint
|
|
370
|
+
unique_key_columns: Option<Vec<String>>
|
|
353
371
|
}
|
|
354
372
|
|
|
355
373
|
// Methods Exposed to Python
|
|
@@ -361,7 +379,8 @@ impl CSVValidator {
|
|
|
361
379
|
validations: Vec::new(),
|
|
362
380
|
regex_map: HashMap::new(),
|
|
363
381
|
separator: DEFAULT_COLUMN_SEPARATOR,
|
|
364
|
-
decimal_separator: DEFAULT_DECIMAL_SEPARATOR
|
|
382
|
+
decimal_separator: DEFAULT_DECIMAL_SEPARATOR,
|
|
383
|
+
unique_key_columns: None
|
|
365
384
|
}
|
|
366
385
|
}
|
|
367
386
|
|
|
@@ -408,7 +427,28 @@ impl CSVValidator {
|
|
|
408
427
|
}
|
|
409
428
|
}
|
|
410
429
|
|
|
411
|
-
|
|
430
|
+
// Parse optional root-level unique configuration (str or [str])
|
|
431
|
+
let config = YamlLoader::load_from_str(definition_string)
|
|
432
|
+
.map_err(|e| PyRuntimeError::new_err(format!("Invalid YAML format: {}", e)))?;
|
|
433
|
+
let unique_key_columns: Option<Vec<String>> = if !config.is_empty() {
|
|
434
|
+
let unique_yaml = &config[0]["unique"];
|
|
435
|
+
if unique_yaml.is_badvalue() {
|
|
436
|
+
None
|
|
437
|
+
} else if let Some(s) = unique_yaml.as_str() {
|
|
438
|
+
Some(vec![s.to_string()])
|
|
439
|
+
} else if let Some(vec) = unique_yaml.as_vec() {
|
|
440
|
+
let cols = vec.iter().map(|y| {
|
|
441
|
+
y.as_str()
|
|
442
|
+
.ok_or_else(|| PyRuntimeError::new_err("Invalid YAML: 'unique' array must contain only strings"))
|
|
443
|
+
.map(|s| s.to_string())
|
|
444
|
+
}).collect::<PyResult<Vec<String>>>()?;
|
|
445
|
+
if cols.is_empty() { None } else { Some(cols) }
|
|
446
|
+
} else {
|
|
447
|
+
return Err(PyRuntimeError::new_err("Invalid YAML: 'unique' must be a string or an array of strings"));
|
|
448
|
+
}
|
|
449
|
+
} else { None };
|
|
450
|
+
|
|
451
|
+
Ok(CSVValidator { validations, regex_map, separator: DEFAULT_COLUMN_SEPARATOR, decimal_separator: DEFAULT_DECIMAL_SEPARATOR, unique_key_columns })
|
|
412
452
|
}
|
|
413
453
|
|
|
414
454
|
#[pyo3(text_signature = "(self, separator)")]
|
|
@@ -473,9 +513,75 @@ impl CSVValidator {
|
|
|
473
513
|
let mut is_valid_file = true;
|
|
474
514
|
let mut validated_rows = 0;
|
|
475
515
|
|
|
516
|
+
// Prepare unique key tracking if requested
|
|
517
|
+
let mut unique_key_indices: Option<Vec<usize>> = None;
|
|
518
|
+
let mut duplicated_keys_pretty_counts: HashMap<String, usize> = HashMap::new();
|
|
519
|
+
if let Some(unique_cols) = &self.unique_key_columns {
|
|
520
|
+
// Build header -> index map
|
|
521
|
+
let headers: Vec<String> = rdr.headers().unwrap().iter().map(|s| String::from(s)).collect();
|
|
522
|
+
let mut idxs = Vec::with_capacity(unique_cols.len());
|
|
523
|
+
for col in unique_cols {
|
|
524
|
+
match headers.iter().position(|h| h == col) {
|
|
525
|
+
Some(i) => idxs.push(i),
|
|
526
|
+
None => return Err(PyRuntimeError::new_err(format!("Unique key column '{}' not found among CSV headers", col)))
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
unique_key_indices = Some(idxs);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// If unique key validation is enabled, prepare a temporary redb database
|
|
533
|
+
let mut _cleanup_guard: Option<CleanupGuard> = None;
|
|
534
|
+
let mut redb_db: Option<Database> = None;
|
|
535
|
+
let mut redb_txn: Option<redb::WriteTransaction> = None;
|
|
536
|
+
if unique_key_indices.is_some() {
|
|
537
|
+
let db_path = "_temp_redb.db";
|
|
538
|
+
_cleanup_guard = Some(CleanupGuard { path: db_path.to_string() });
|
|
539
|
+
let db = Database::create(db_path).map_err(|e| PyRuntimeError::new_err(format!("Failed to open redb: {}", e)))?;
|
|
540
|
+
let write_txn = db.begin_write().map_err(|e| PyRuntimeError::new_err(format!("Failed to begin transaction: {}", e)))?;
|
|
541
|
+
redb_txn = Some(write_txn);
|
|
542
|
+
redb_db = Some(db);
|
|
543
|
+
}
|
|
544
|
+
|
|
476
545
|
// Iterate over the CSV file and validate each row
|
|
477
546
|
for result in rdr.records() {
|
|
478
547
|
let record = result.unwrap();
|
|
548
|
+
|
|
549
|
+
// Unique key check (single-pass)
|
|
550
|
+
if let Some(indices) = &unique_key_indices {
|
|
551
|
+
// Build raw and pretty keys
|
|
552
|
+
let mut raw_parts: Vec<String> = Vec::with_capacity(indices.len());
|
|
553
|
+
let mut pretty_parts: Vec<String> = Vec::with_capacity(indices.len());
|
|
554
|
+
if let Some(unique_cols) = &self.unique_key_columns {
|
|
555
|
+
for (i, idx) in indices.iter().enumerate() {
|
|
556
|
+
let val = record.get(*idx).unwrap_or("");
|
|
557
|
+
raw_parts.push(val.to_string());
|
|
558
|
+
let col_name = &unique_cols[i];
|
|
559
|
+
pretty_parts.push(format!("{}='{}'", col_name, val));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
let raw_key = raw_parts.join("\u{1F}"); // Use non-printable unit separator
|
|
563
|
+
let pretty_key = format!("({})", pretty_parts.join(", "));
|
|
564
|
+
|
|
565
|
+
if let Some(write_txn) = redb_txn.as_mut() {
|
|
566
|
+
// Open table per iteration to avoid lifetime issues
|
|
567
|
+
let mut table = write_txn
|
|
568
|
+
.open_table(DUPLICATES_TABLE)
|
|
569
|
+
.map_err(|e| PyRuntimeError::new_err(format!("Failed to open table: {}", e)))?;
|
|
570
|
+
let exists = table
|
|
571
|
+
.get(raw_key.as_str())
|
|
572
|
+
.map_err(|e| PyRuntimeError::new_err(format!("DB Read Error: {}", e)))?
|
|
573
|
+
.is_some();
|
|
574
|
+
if exists {
|
|
575
|
+
let dup_count = duplicated_keys_pretty_counts.get(&pretty_key).cloned().unwrap_or(1) + 1;
|
|
576
|
+
duplicated_keys_pretty_counts.insert(pretty_key, dup_count);
|
|
577
|
+
is_valid_file = false;
|
|
578
|
+
} else {
|
|
579
|
+
table
|
|
580
|
+
.insert(raw_key.as_str(), &[] as &[u8])
|
|
581
|
+
.map_err(|e| PyRuntimeError::new_err(format!("DB Insert Error: {}", e)))?;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
479
585
|
for next_column in zip(record.iter(), self.validations.iter()) {
|
|
480
586
|
let value = next_column.0;
|
|
481
587
|
let _column_name = &next_column.1.column_name;
|
|
@@ -501,6 +607,15 @@ impl CSVValidator {
|
|
|
501
607
|
validated_rows = validated_rows + 1;
|
|
502
608
|
}
|
|
503
609
|
|
|
610
|
+
// Commit and clean up redb resources if used
|
|
611
|
+
if let Some(write_txn) = redb_txn.take() {
|
|
612
|
+
write_txn
|
|
613
|
+
.commit()
|
|
614
|
+
.map_err(|e| PyRuntimeError::new_err(format!("Failed to commit transaction: {}", e)))?;
|
|
615
|
+
}
|
|
616
|
+
// Explicitly drop the DB to release file handles before guard deletes the file
|
|
617
|
+
drop(redb_db);
|
|
618
|
+
|
|
504
619
|
// Fill the ColumnValidationSummary for each column
|
|
505
620
|
let mut column_validation_summaries = Vec::new();
|
|
506
621
|
for column_validation in &self.validations {
|
|
@@ -525,6 +640,31 @@ impl CSVValidator {
|
|
|
525
640
|
info!("FILE: {}", file_path);
|
|
526
641
|
info!("Rows: {} | Columns: {}", validation_process_summary.total_rows, validation_process_summary.total_columns);
|
|
527
642
|
|
|
643
|
+
let mut unique_validation_ok = true;
|
|
644
|
+
// If there are duplicated keys, report them first
|
|
645
|
+
if let Some(_) = &self.unique_key_columns {
|
|
646
|
+
info!("UNIQUE KEY: column(s): {:?}", &self.unique_key_columns);
|
|
647
|
+
if !duplicated_keys_pretty_counts.is_empty() {
|
|
648
|
+
info!("");
|
|
649
|
+
let total = duplicated_keys_pretty_counts.len();
|
|
650
|
+
info!("DUPLICATED KEYS (groups found: {})", total);
|
|
651
|
+
info!("--------------------------------------------------");
|
|
652
|
+
let sample_limit: usize = 100;
|
|
653
|
+
if total > sample_limit {
|
|
654
|
+
info!("Showing first {} of {} duplicate key groups:", sample_limit, total);
|
|
655
|
+
}
|
|
656
|
+
for (key, count) in duplicated_keys_pretty_counts.iter().take(100) {
|
|
657
|
+
info!(" - {} -> occurrences: {}", key, count);
|
|
658
|
+
}
|
|
659
|
+
unique_validation_ok = false;
|
|
660
|
+
} else {
|
|
661
|
+
info!("");
|
|
662
|
+
info!("UNIQUE KEYS CHECK");
|
|
663
|
+
info!("--------------------------------------------------");
|
|
664
|
+
info!(" - No duplicates found");
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
528
668
|
let correct_columns = validation_process_summary.correct_columns.len();
|
|
529
669
|
let wrong_columns = validation_process_summary.wrong_columns.len();
|
|
530
670
|
|
|
@@ -554,6 +694,9 @@ impl CSVValidator {
|
|
|
554
694
|
}
|
|
555
695
|
}
|
|
556
696
|
|
|
697
|
+
// Adding other validation results before returning the final result
|
|
698
|
+
is_valid_file = is_valid_file && unique_validation_ok;
|
|
699
|
+
|
|
557
700
|
info!("");
|
|
558
701
|
info!("VALIDATION RESULT");
|
|
559
702
|
info!("--------------------------------------------------");
|
|
@@ -768,6 +911,22 @@ mod tests {
|
|
|
768
911
|
assert!(!validator.validate("test/empty_values.csv").unwrap());
|
|
769
912
|
}
|
|
770
913
|
|
|
914
|
+
#[test]
|
|
915
|
+
fn test_unique_key_validation() {
|
|
916
|
+
let definition_with_non_empty_column = String::from("
|
|
917
|
+
unique: First Column
|
|
918
|
+
columns:
|
|
919
|
+
- name: First Column
|
|
920
|
+
- name: Second Column
|
|
921
|
+
");
|
|
922
|
+
let validator = CSVValidator::from_string(&definition_with_non_empty_column).unwrap();
|
|
923
|
+
|
|
924
|
+
// Validation is OK as there are no duplicated keys
|
|
925
|
+
assert!(validator.validate("test/empty_values.csv").unwrap());
|
|
926
|
+
// Validation is not OK as the first column contains the value 456 twice
|
|
927
|
+
assert!(!validator.validate("test/duplicated_unique_keys.csv").unwrap());
|
|
928
|
+
}
|
|
929
|
+
|
|
771
930
|
#[test]
|
|
772
931
|
fn test_csv_validator_invalid_format() {
|
|
773
932
|
let definition = String::from("
|
csv_validation-0.0.16/PKG-INFO
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: csv_validation
|
|
3
|
-
Version: 0.0.16
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|