lib/OMOP/CSV/Validator.pm

filter: Statementstmt 72.0% 72 / 100 Branchbran 63.8% 23 / 36 Conditioncond 27.2% 3 / 11 MC/DCmcdc 16.6% 1 / 6 Subroutinesub 87.5% 14 / 16 Podpod 0.0% 0 / 5 totaltotal 64.9% 113 / 174 CC 26 SCAR 32.2
CC
26
Cov
67%
validate_csv_file
90.0
_build_schema
13.3
dotify_and_coerce_number
5.2
CRAP 25.0
« blib/lib/OMOP/CSV/Validator.pm ↑ Summary blib/script/reorder-csv.pl »
1 package OMOP::CSV::Validator;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use JSON::Validator;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Text::CSV_XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 our $VERSION = '0.03';
14  
15 =head1 NAME
16  
17 OMOP::CSV::Validator - Validates OMOP CDM CSV files against their expected data types
18  
19 =head1 SYNOPSIS
20  
21 use OMOP::CSV::Validator;
22  
23 my $validator = OMOP::CSV::Validator->new();
24  
25 # Load schemas from DDL
26 my $schemas = $validator->load_schemas_from_ddl($ddl_text);
27  
28 # Retrieve specific table schema for a CSV file
29 my $schema = $validator->get_schema_from_csv_filename($csv_file, $schemas);
30  
31 # Validate CSV file
32 my $errors = $validator->validate_csv_file($csv_file, $schema);
33 if (@$errors) {
34 print "Validation errors found:\n";
35 for my $err_info (@$errors) {
36 print "Row $err_info->{row}:\n";
37 for my $e (@{ $err_info->{errors} }) {
38 print " $e\n";
39 }
40 }
41 } else {
42 print "CSV is valid.\n";
43 }
44  
45 =head1 DESCRIPTION
46  
47 OMOP::CSV::Validator is a CLI tool and Perl module designed to validate OMOP Common Data Model (CDM) CSV files. It auto-generates JSON schemas from PostgreSQL DDL files and then validates CSV rows against those schemas.
48  
49 =head1 METHODS
50  
51 =cut
52  
53 ##########################################################################
54 # Constructor: new()
55 ##########################################################################
56 sub new {
57 1 ▶ my ( $class, %args ) = @_;
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
58 1 my $self = bless {}, $class;
59 1 return $self;
60 }
61  
62 ##########################################################################
63 # load_schemas_from_ddl($ddl_text)
64 #
65 # Parses all CREATE TABLE definitions from a PostgreSQL OMOP DDL
66 # and returns a hashref of JSON schemas keyed by table name (lowercase).
67 ##########################################################################
68 sub load_schemas_from_ddl {
69 1 ▶ my ( $self, $ddl_text ) = @_;
Subroutine load_schemas_from_ddl: called CC=1 SCAR=0.0
Pod undocumented
70 1 return $self->_ddl_to_json_schemas($ddl_text);
71 }
72  
73 ##########################################################################
74 # _ddl_to_json_schemas($ddl_text) - private
75 #
76 # Internal subroutine that iterates over all CREATE TABLE blocks.
77 ##########################################################################
78 sub _ddl_to_json_schemas {
79 1 ▶ my ( $self, $ddl_text ) = @_;
Subroutine _ddl_to_json_schemas: called CC=2 SCAR=6.9
80 1 my %schemas;
81 1 ▶ while (
Branch: 1 branch
BranchTrueFalseTotal
if ($ddl_text =~ / CREATE\s+TABLE\s+\S+\.(\w+)\s*\( # capture table name (after schema qualifier) (.*?) # capture everything inside parentheses \)\s*; # until the closing parenthesis and semicolon /gisx) 2 1 3
82 $ddl_text =~ /
83 CREATE\s+TABLE\s+\S+\.(\w+)\s*\( # capture table name (after schema qualifier)
84 (.*?) # capture everything inside parentheses
85 \)\s*; # until the closing parenthesis and semicolon
86 /gisx
87 )
88 {
89 2 my ( $table, $cols_block ) = ( lc $1, $2 );
90 2 $schemas{$table} = $self->_build_schema( $table, $cols_block );
91 }
92 1 return \%schemas;
93 }
94  
95 ##########################################################################
96 # _build_schema($table_name, $cols_block) - private
97 #
98 # Builds a JSON schema for one table from the column definitions.
99 ##########################################################################
100 sub _build_schema {
101 2 ▶ my ( $self, $table_name, $cols_block ) = @_;
Subroutine _build_schema: called CC=13 SCAR=25.9
102 2 my $schema = {
103 '$schema' => 'http://json-schema.org/draft-07/schema#',
104 title => $table_name,
105 type => 'object',
106 properties => {},
107 required => [],
108 additionalProperties => 0,
109 };
110  
111 2 for my $line ( grep /\S/, split /\n/, $cols_block ) {
112 24 $line =~ s/^\s+|\s+$//g;
113 24 $line =~ s/,$//;
114 24 ▶ next if $line =~ /^--/; # Skip comment lines
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^--/ 0 24 24
115  
116 24 ▶ if ( $line =~
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^(\w+)\s+([A-Za-z]+)(?:\((\d+(?:,\d+)?)\))?(?:\s+(NOT NULL))?/i) 24 0 24
117 /^(\w+)\s+([A-Za-z]+)(?:\((\d+(?:,\d+)?)\))?(?:\s+(NOT NULL))?/i )
118 {
119 24 my ( $col, $type, $length, $notnull ) =
120 ( lc $1, lc $2, $3, defined $4 );
121 24 my $prop = {};
122  
123 24 ▶ if ( $type =~ /int/ ) {
Branch: 5 branches
BranchTrueFalseTotal
if ($type =~ /int/) { } 15 9 24
elsif ($type =~ /numeric|real|double/) { } 1 8 9
elsif ($type eq 'date') { } 1 7 8
elsif ($type =~ /timestamp/) { } 2 5 7
elsif ($type eq 'varchar') { } 5 0 5
124 15 $prop->{type} = 'integer';
125 15 $prop->{_coerce} = 1;
126 }
127 elsif ( $type =~ /numeric|real|double/ ) {
128 1 $prop->{type} = 'number';
129 1 $prop->{_coerce} = 1;
130  
131 }
132 elsif ( $type eq 'date' ) {
133 1 $prop->{type} = 'string';
134 1 $prop->{format} = 'date';
135 }
136 elsif ( $type =~ /timestamp/ ) {
137 2 $prop->{type} = 'string';
138 2 $prop->{format} = 'date-time';
139 }
140 elsif ( $type eq 'varchar' ) {
141 5 $prop->{type} = 'string';
142 5 ▶ if ( defined $length ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $length) 5 0 5
143  
144 # Capture only the first number if a comma is present (e.g., varchar(10,2))
145 5 ▶ if ( $length =~ /^(\d+)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($length =~ /^(\d+)/) 5 0 5
146 5 $prop->{maxLength} = int($1);
147 }
148 }
149 }
150 else {
151 0 $prop->{type} = 'string';
152 }
153  
154 # If the column is not marked as NOT NULL, allow null values
155 24 ▶ unless ($notnull) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($notnull) 16 8 24
156 16 $prop->{type} = [ $prop->{type}, 'null' ];
157 }
158  
159 24 $schema->{properties}{$col} = $prop;
160 24 ▶ push @{ $schema->{required} }, $col if $notnull;
Branch: 1 branch
BranchTrueFalseTotal
if $notnull 8 16 24
161 }
162 }
163 2 return $schema;
164 }
165  
166 ##########################################################################
167 # get_schema_from_csv_filename($csv_filename, $schemas)
168 #
169 # Derives the table name from the CSV file's basename (e.g. PERSON.csv → person)
170 # and returns the corresponding schema from the provided hashref.
171 ##########################################################################
172 sub get_schema_from_csv_filename {
173 0 ▶ my ( $self, $csv_filename, $schemas ) = @_;
Subroutine get_schema_from_csv_filename: not called CC=1 SCAR=6.9
Pod undocumented
174 0 ( my $table = lc $csv_filename ) =~ s{^.*/}{}; # remove any path
175 0 $table =~ s/\.csv$//i; # remove .csv extension
176 0 return $schemas->{$table};
177 }
178  
179 ##########################################################################
180 # validate_csv_file($csv_file, $schema, $sep)
181 #
182 # Reads the CSV file, coerces numeric fields, and validates each row against
183 # the provided JSON schema. Returns an arrayref of error info (each entry is a
184 # hashref with keys 'row' and 'errors').
185 ##########################################################################
186 sub validate_csv_file {
187 0 ▶ my ( $self, $csv_file, $schema, $sep ) = @_;
Subroutine validate_csv_file: not called CC=9 SCAR=45.0
Pod undocumented
188 0 ▶ $sep //= ',';
Condition0%0/2
$sep //= ","
l!l
00
MC/DC0%0/1
$sep //= ","
$sep
Truth table0%0/2
A
A= $sep
Aresult
11
00
189  
190 0 my $csv_handle = path($csv_file)->openr_utf8;
191 0 ▶ my $csv =
Branch: 1 branch
BranchTrueFalseTotal
my $csv = "Text::CSV_XS"->new({"binary", 1, "sep_char", $sep, "auto_diag", 1, "blank_is_undef", 1}) or die 'Cannot use CSV: ' . "Text::CSV_XS"->error_diag 0 0 0
192 Text::CSV_XS->new(
193 { binary => 1, sep_char => $sep, auto_diag => 1, blank_is_undef => 1 } )
194 or die "Cannot use CSV: " . Text::CSV_XS->error_diag();
195  
196 0 my $header = $csv->getline($csv_handle);
197 0 $csv->column_names(@$header);
198  
199 0 my $records = $csv->getline_hr_all($csv_handle);
200 0 $csv_handle->close;
201  
202 0 my @errors;
203 0 my $validator = JSON::Validator->new;
204 0 $validator->schema($schema);
205  
206 0 for my $i ( 0 .. $#$records ) {
207 0 my $record = $records->[$i];
208  
209 # Coerce numeric fields according to the schema.
210 0 for my $col ( keys %{ $schema->{properties} } ) {
211 0 ▶ if ( exists $record->{$col} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $record->{$col}) 0 0 0
212 0 my $prop = $schema->{properties}->{$col};
213 0 ▶ if ( defined $prop->{_coerce} && $prop->{_coerce} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prop->{"_coerce"} and $prop->{"_coerce"}) 0 0 0
Condition0%0/3
defined $prop->{"_coerce"} and $prop->{"_coerce"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $prop->{"_coerce"} and $prop->{"_coerce"}
defined $prop->{"_coerce"} $prop->{"_coerce"}
Truth table0%0/3
A and B
A= defined $prop->{"_coerce"}B= $prop->{"_coerce"}
ABresult
0X0
100
111
214 $record->{$col} =
215 0 $self->dotify_and_coerce_number( $record->{$col} );
216 }
217 }
218 }
219  
220 # Validate
221 0 my $errs = [ $validator->validate($record) ];
222 0 ▶ if (@$errs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$errs) 0 0 0
223  
224 # row number excludes header → row index + 1
225 0 push @errors, { row => $i + 1, errors => $errs };
226 }
227 }
228 0 return \@errors;
229 }
230  
231 ##########################################################################
232 # dotify_and_coerce_number($val)
233 #
234 # Converts a CSV string value to a number if it looks numeric.
235 # Returns undef if the value is empty or "\N".
236 ##########################################################################
237 sub dotify_and_coerce_number {
238 48 ▶ my ( $self, $val ) = @_;
Subroutine dotify_and_coerce_number: called CC=5 SCAR=16.6
Pod undocumented
239 48 ▶ return undef unless ( defined $val && $val ne '' && $val ne '\\N' );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and $val ne "" and $val ne "\\N" 9 39 48
Condition50%3/6
defined $val and $val ne "" and $val ne "\\N"
!ll&&!rl&&r
0939
defined $val and $val ne ""
!ll&&!rl&&r
0048
MC/DC33%1/3
defined $val and $val ne "" and $val ne "\\N"
defined $val $val ne "" $val ne "\\N"
Truth table50%2/4
A and B and C
A= defined $valB= $val ne ""C= $val ne "\\N"
ABCresult
0XX0
10X0
1100
1111
240 39 ( my $tr_val = $val ) =~ tr/,/./;
241 39 ▶ return looks_like_number($tr_val) ? 0 + $tr_val : $val;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($tr_val) ? : 36 3 39
242 }
243  
244 =head1 AUTHOR
245  
246 Written by Manuel Rueda, PhD. Info about CNAG can be found at L<https://www.cnag.eu>.
247  
248 =head1 LICENSE
249  
250 This module is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
251  
252 =cut
253  
254 1 1;
« blib/lib/OMOP/CSV/Validator.pm ↑ Summary blib/script/reorder-csv.pl »