blib/lib/DBIx/Spreadsheet.pm

filter: Statementstmt 52.9% 72 / 136 Branchbran 16.6% 6 / 36 Conditioncond 18.7% 3 / 16 MC/DCmcdc 20.0% 2 / 10 Subroutinesub 75.0% 15 / 20 Podpod 16.6% 1 / 6 totaltotal 44.2% 99 / 224 CC 31 SCAR 46.9
CC
31
Cov
43%
nasty_cell_fixup
306.0
import_data
30.0
gen_colname
8.1
CRAP 109.1
« Makefile.PL ↑ Summary
1 #!perl
2 package DBIx::Spreadsheet;
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Getopt::Long;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use Spreadsheet::Read;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Text::CleanFragment;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 4 ▶use Moo 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use Filter::signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 4 our $VERSION = '0.04';
16  
17 =head1 NAME
18  
19 DBIx::Spreadsheet - Query a spreadsheet with SQL
20  
21 =head1 SYNOPSIS
22  
23 my $sheet = DBIx::Spreadsheet->new( file => 'workbook.xlsx' );
24 my $dbh = $sheet->dbh;
25  
26 my @rows = $dbh->selectall_arrayref(<<'SQL');
27 select *
28 from sheet_1
29 where foo = 'bar'
30 SQL
31  
32 This module reads a workbook and makes the contained spreadsheets available
33 as tables. It assumes that the first row of a spreadsheet are the column
34 names. Empty column names will be replaced by C<col_$number>. The sheet and
35 column names will be sanitized by L<Text::CleanFragment> so they are
36 conveniently usable.
37  
38 =head1 WARNING
39  
40 The parsing and reformatting of cell values is very hacky. Don't expect
41 too much consistency between C<ods> and C<xlsx> cell formats. I try to
42 make these consistent, but this is currently a pile of value-specific hacks.
43  
44 =head1 METHODS
45  
46 =head2 C<< DBIx::Spreadsheet->new >>
47  
48 my $wb = DBIx::Spreadsheet->new(
49 file => 'workboook.ods',
50 );
51  
52 =head3 Options
53  
54 =over 4
55  
56 =item *
57  
58 B<file> - name of the workbook file. The file will be read using L<Spreadsheet::Read>
59 using the options in C<spreadsheet_options>.
60  
61 =cut
62  
63 4 has 'file' => (
64 is => 'ro',
65 );
66  
67 =item *
68  
69 B<spreadsheet> - a premade L<Spreadsheet::Read> object
70  
71 =cut
72  
73 4 has 'spreadsheet' => (
74 is => 'lazy',
75 default => \&_read_file,
76 );
77  
78 =item *
79  
80 B<spreadsheet_options> - options for the L<Spreadsheet::Read> object
81  
82 =back
83  
84 =cut
85  
86 has 'spreadsheet_options' => (
87 is => 'lazy',
88 default => sub { {
89 1 ▶ dtfmt => 'yyyy-mm-dd',
Subroutine __ANON__: called CC=1 SCAR=0.0
90 } },
91 4 );
92  
93 =head2 C<< ->dbh >>
94  
95 my $dbh = $wb->dbh;
96  
97 Returns the database handle to access the sheets.
98  
99 =cut
100  
101 ▶has 'dbh' => (
Subroutine __ANON__: called CC=1 SCAR=1.2
102 is => 'lazy',
103 1 default => sub( $self ) { $self->_import_data; $self->{dbh} },
104 4 );
105  
106 =head2 C<< ->tables >>
107  
108 my $tables = $wb->tables;
109  
110 Arrayref containing the names of the tables. These are usually the names
111 of the sheets.
112  
113 =cut
114  
115 ▶has 'tables' => (
Subroutine __ANON__: not called CC=1 SCAR=6.9
116 is => 'lazy',
117 0 default => sub( $self ) { $self->_import_data; $self->{tables} },
118 4 );
119  
120 1 ▶sub _read_file( $self, $filename=$self->file ) {
Subroutine _read_file: called CC=2 SCAR=6.9
121 return
122 Spreadsheet::Read->new(
123 $filename,
124 attr => 1,
125 1 %{ $self->spreadsheet_options }
126 );
127 };
128  
129 4 our $table_000;
130  
131 4 our %charmap = (
132 '+' => 'plus',
133 '%' => 'perc',
134 );
135  
136 23 ▶sub gen_colname( $self, $org_name, $colposition=1, $seen={} ) {
Subroutine gen_colname: called CC=8 SCAR=20.9
Pod undocumented
137 23 ▶ $org_name = !defined($org_name) ? "" : $org_name;
Branch: 1 branch
BranchTrueFalseTotal
!defined($org_name) ? : 0 23 23
138  
139 23 my $name = $org_name;
140  
141 23 my $chars = quotemeta join "", sort keys %charmap;
142 23 $name =~ s/([$chars])/_$charmap{ $1 }_/g; # replace + and % with names
143 23 $name =~ s/([-.])/_/g; # replace . and - to _
144 23 $name = clean_fragment( $name );
145  
146 23 ▶ if( $org_name =~ /^\s*$/ or $name =~ /^\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($org_name =~ /^\s*$/ or $name =~ /^\s*$/) 14 9 23
Condition100%3/3
$org_name =~ /^\s*$/ or $name =~ /^\s*$/
l!l&&r!l&&!r
1139
MC/DC100%2/2
$org_name =~ /^\s*$/ or $name =~ /^\s*$/
$org_name =~ /^\s*$/ $name =~ /^\s*$/
Truth table100%3/3
A or B
A= $org_name =~ /^\s*$/B= $name =~ /^\s*$/
ABresult
1X1
011
000
147 14 $name = sprintf "col_%d", $colposition;
148 };
149  
150 # Welcome quadratical complexity. If you look at this line for performance
151 # reasons, this, together with the call from ->gen_colnames implies that
152 # we have quadratical runtime on the number of colliding column names. This
153 # will happen especially if there is a named column inserted before unnamed
154 # columns, and that named column collides with the generated name of an
155 # unnamed column. So don't do that.
156 23 my $counter = 1;
157 23 ▶ if( $seen->{ $name }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen->{$name}) 3 20 23
158 3 my $newname = $name .= "_" . ($counter++);
159 3 ▶ while( $seen->{ $newname }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen->{$newname}) 0 3 3
160 0 $newname = $name .= "_" . ($counter++);
161 };
162 3 $name = $newname;
163 };
164 23 return $name
165 }
166  
167 0 ▶sub gen_tablename( $self, $org_name, $seen={}) {
Subroutine gen_tablename: not called CC=2 SCAR=17.9
Pod undocumented
168 0 $self->gen_colname( $org_name, 0, $seen );
169 }
170  
171 ▶sub gen_colnames( $self, @colnames ) {
Subroutine gen_colnames: called CC=2 SCAR=6.9
Pod undocumented
172 8 my %seen;
173 8 my $i = 1;
174 8 my @res;
175 8 for my $name (@colnames) {
176 23 $name = $self->gen_colname( $name, $i++, \%seen );
177 23 $seen{ $name }++;
178 23 push @res, qq("$name");
179 };
180 return @res
181 8 }
182  
183 # The nasty fixup until I clean up Spreadsheet::ReadSXC to allow for the raw
184 # values
185 ▶sub nasty_cell_fixup( $self, $value, $source_type, $attr ) {
Subroutine nasty_cell_fixup: not called CC=17 SCAR=57.2
Pod undocumented
186 0 ▶ return $value if ! defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
187 # use Data::Dumper; $Data::Dumper::Useqq = 1;
188  
189 # We treat the different spreadsheet sources differently. This should
190 # become more feature-oriented, like:
191 # if( xlsx ) { +reformat_date_from_excel_date, +reformat_number
192  
193 0 ▶ my $t = $attr->{type} // '';
Condition0%0/2
$attr->{"type"} // ""
l!l
00
MC/DC0%0/1
$attr->{"type"} // ""
$attr->{"type"}
Truth table0%0/2
A
A= $attr->{"type"}
Aresult
11
00
194 0 ▶ my $f = $attr->{format} // '';
Condition0%0/2
$attr->{"format"} // ""
l!l
00
MC/DC0%0/1
$attr->{"format"} // ""
$attr->{"format"}
Truth table0%0/2
A
A= $attr->{"format"}
Aresult
11
00
195  
196 0 ▶ if( $source_type eq 'xlsx' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($source_type eq 'xlsx') { } 0 0 0
elsif ($source_type eq 'ods') { } 0 0 0
197 0 ▶ if( $f =~ m!DD! ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f =~ /DD/) 0 0 0
198 # it's still a date, no matter what the type says
199 0 $t = 'date';
200 };
201  
202 0 ▶ if( $t eq 'date' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($t eq 'date') { } 0 0 0
elsif ($t eq 'currency') { } 0 0 0
elsif ($t eq 'numeric' and $f =~ /\.00/) { } 0 0 0
203 # Reformat the Excel-date (number of days since 1900-01-01
204 0 require Spreadsheet::ParseExcel::Utility;
205  
206 0 $value = Spreadsheet::ParseExcel::Utility::ExcelFmt( 'yyyy-mm-dd', $value );
207  
208 } elsif( $t eq 'currency') {
209 # Hard-format back to random currency format, as that's
210 # what I have. This should rather be a string operation
211 0 $value = sprintf '%0.2f', $value;
212  
213 ▶ } elsif( $t eq 'numeric' and $f =~ m!\.00!) {
Condition0%0/3
$t eq "numeric" and $f =~ /\.00/
!ll&&!rl&&r
000
MC/DC0%0/2
$t eq "numeric" and $f =~ /\.00/
$t eq "numeric" $f =~ /\.00/
Truth table0%0/3
A and B
A= $t eq "numeric"B= $f =~ /\.00/
ABresult
0X0
100
111
214 # Hard-format back to random currency format, as that's
215 # what I have. This should rather be a string operation
216 0 $value = sprintf '%0.2f', $value;
217 }
218  
219 } elsif( $source_type eq 'ods' ) {
220 # Fix up German locale formatted numbers, as that's what I have
221 0 ▶ if( $t eq 'currency') {
Branch: 3 branches
BranchTrueFalseTotal
if ($t eq 'currency') { } 0 0 0
elsif ($t eq 'date' and $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/) { } 0 0 0
elsif ($t eq 'date' and $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/) { } 0 0 0
222 0 ▶ if( $value =~ /^([+-]?)([0-9\.]+(,\d+))?(\s*\x{20ac}|€)?$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /^([+-]?)([0-9\.]+(,\d+))?(\s*\x{20ac}|\342\202\254)?$/) 0 0 0
223 # Fix up formatted number
224 0 $value =~ s![^\d\.\,+-]!!g;
225 0 $value =~ s!\.!!g;
226 0 $value =~ s!,!.!g;
227 };
228  
229 # Hard-format back to random currency format, as that's
230 # what I have. This should rather be a string operation
231 0 $value = sprintf '%0.2f', $value;
232  
233 # Fix up German locale formatted dates, as that's what I have
234 ▶ } elsif( $t eq 'date'
Condition0%0/3
$t eq "date" and $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$t eq "date" and $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/
$t eq "date" $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/
Truth table0%0/3
A and B
A= $t eq "date"B= $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/
ABresult
0X0
100
111
235 and $value =~ /^([0123]?\d)\.([01]\d)\.(\d\d)$/ ) {
236 0 $value = "20$3-$2-$1";
237  
238 # Fix up German locale formatted dates, as that's what I have
239 ▶ } elsif( $t eq 'date'
Condition0%0/3
$t eq "date" and $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$t eq "date" and $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/
$t eq "date" $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/
Truth table0%0/3
A and B
A= $t eq "date"B= $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/
ABresult
0X0
100
111
240 and $value =~ /^([0123]?\d)\.([01]\d)\.(20\d\d)$/ ) {
241 0 $value = "$3-$2-$1";
242 }
243 } else {
244 # Don't know
245 0 die "Unknown spreadsheet type '$source_type'";
246 }
247  
248  
249 0 return $value
250 }
251  
252 4 our $month_num = qr!(?<month>0?[1-9]|1[012])!x;
253 4 our $month = qr!($month_num|[A-Z][a-z]{2})!x;
254 4 our $day_num2 = qr!(?<day>0[1-9]|1[0-9]|2[0-9]|3[01])!x;
255 4 our $day = qr!(?<day>[1-9]|$day_num2)!x;
256 4 our $year = qr!(?<year>[1-9]\d|[1-9]\d\d\d)!x;
257 4 our $looks_like_date =
258 qr!^\s*(
259 |(?:$month \s* / \s* $day \s* / \s* $year)
260 |(?:$month \s* - \s* $day \s* - \s* $year)
261 |(?:$day_num2 \s* \. \s* $month \s* \. \s* $year)
262 |(?:$year \s* -? \s* $month_num \s* -? \s* $day_num2 )
263 )\s*$!x;
264  
265 ▶sub import_data( $self, $book ) {
Subroutine import_data: not called CC=5 SCAR=34.0
Pod undocumented
266 0 my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:',undef,undef,{AutoCommit => 1, RaiseError => 1,PrintError => 0});
267 0 $dbh->sqlite_create_module(perl => "DBD::SQLite::VirtualTable::PerlData");
268  
269 0 my @tables;
270 0 my $i = 0;
271 0 my %seen;
272 0 for my $table_name ($book->sheets) {
273 0 my $sheet = $book->sheet( $table_name );
274  
275 # We could try to identify the column types here more closely
276 my $source_type = $book->[0]->{type}
277 0 ▶ or die "No spreadsheet type found in spreadsheet?!";
Branch: 1 branch
BranchTrueFalseTotal
my $source_type = $book->[0]{"type"} or die "No spreadsheet type found in spreadsheet?!" 0 0 0
278  
279 my $data = [map {
280 0 my $rownum = $_;
281 my @row = map {
282 0 my $v;
283 0 ▶ if( $rownum == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rownum == 1) { } 0 0 0
284 # This is a column heading
285 0 $v = $sheet->cell($_,$rownum);
286 } else {
287 0 my $c = $_;
288 # unformatted
289 0 $v = $sheet->cell($c,$rownum);
290 0 my $a;
291 0 ▶ if( defined $sheet->{attr}->[$c]->[$rownum]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sheet->{"attr"}[$c][$rownum]) 0 0 0
292 0 $a = $sheet->attr($c,$rownum);
293 };
294 0 $v = $self->nasty_cell_fixup( $v, $source_type, $a );
295  
296 # use formatted if things look like a date
297 #my $label = Spreadsheet::Read::cr2cell($_,$rownum);
298 #my $fv = $sheet->cell($label);
299 #
300 #if( defined $v ) {
301 # if( $v =~ /^\d+$/ and $fv =~ m!$looks_like_date! ) {
302 # $v = $fv
303 # };
304 #};
305 }
306 0 $v
307 } 1..$sheet->maxcol;
308  
309 \@row
310 0 } 1..$sheet->maxrow ];
311 #my $data = [$sheet->rows($_)];
312 0 my $colnames = shift @{$data};
313  
314 0 my $sql_name = $self->gen_tablename( $table_name, \%seen );
315  
316 # Fix up duplicate columns, empty column names
317 0 $colnames = join ",", $self->gen_colnames( @$colnames );
318 0 {;
319 #no strict 'refs';
320 # Later, find the first non-empty row, instead of blindly taking the first row
321 #${main::}{$tablevar} = \$data;
322 };
323 0 local $table_000 = $data;
324 0 my $tablevar = __PACKAGE__ . '::table_000';
325 0 my $sql = qq(CREATE VIRTUAL TABLE temp."$sql_name" USING perl($colnames, arrayrefs="$tablevar"););
326 0 $dbh->do($sql);
327 0 push @tables, { sheet => $table_name, table => $sql_name };
328 };
329  
330 0 return $dbh, \@tables;
331 }
332  
333 =head2 C<< ->table_names >>
334  
335 print "The sheets are available as\n";
336 for my $mapping ($foo->table_names) {
337 printf "Sheet: %s Table name: %s\n", $mapping->{sheet}, $mapping->{table};
338 };
339  
340 Returns the mapping of sheet names and generated/cleaned-up table names.
341 This may be convenient if you want to help your users find the table names that
342 they can use.
343  
344 If you want to list all available table names, consider using the L<DBI>
345 catalog methods instead:
346  
347 my $table_names = $dbh->table_info(undef,"TABLE,VIEW",undef,undef)
348 ->fetchall_arrayref(Slice => {});
349 print $_->{TABLE_NAME}, "\n"
350 for @$table_names;
351  
352 =cut
353  
354 ▶sub table_names( $self ) {
Subroutine table_names: not called CC=1 SCAR=6.9
Pod documented
355 0 @{ $self->tables }
356 }
357  
358 ▶sub _import_data( $self ) {
Subroutine _import_data: called CC=1 SCAR=2.6
359 1 my( $dbh, $tables ) = $self->import_data( $self->spreadsheet );
360 0 $self->{dbh} = $dbh;
361 0 $self->{tables} = $tables;
362 }
363  
364 4 1;
365  
366 =head1 SUPPORTED FILE TYPES
367  
368 This module supports the same file types as L<Spreadsheet::Read>. The following
369 modules need to be installed to read the various file types:
370  
371 =over 4
372  
373 =item *
374  
375 L<Text::CSV_XS> - CSV files
376  
377 =item *
378  
379 L<Spreadsheet::ParseXLS> - Excel XLS files
380  
381 =item *
382  
383 L<Spreadsheet::ParseXLSX> - Excel XLSX files
384  
385 =item *
386  
387 L<Spreadsheet::ParseSXC> - Staroffice / Libre Office SXC or ODS files
388  
389 =back
390  
391 =head1 TO DO
392  
393 =over 4
394  
395 =item *
396  
397 Create DBD so direct usage with L<DBI> becomes possible
398  
399 my $dbh = DBI->connect('dbi:Spreadsheet:filename=workbook.xlsx,start_row=2');
400  
401 DBIx::Spreadsheet will provide the underlying glue.
402  
403 =back
404  
405 =head1 SEE ALSO
406  
407 L<DBD::CSV>
408  
409 =head1 REPOSITORY
410  
411 The public repository of this module is
412 L<https://github.com/Corion/DBIx-Spreadsheet>.
413  
414 =head1 SUPPORT
415  
416 The public support forum of this module is
417 L<https://perlmonks.org/>.
418  
419 =head1 BUG TRACKER
420  
421 Please report bugs in this module via the RT CPAN bug queue at
422 L<https://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-Spreadsheet>
423 or via mail to L<dbix-spreadsheet-Bugs@rt.cpan.org>.
424  
425 =head1 AUTHOR
426  
427 Max Maischein C<corion@cpan.org>
428  
429 =head1 COPYRIGHT (c)
430  
431 Copyright 2019 by Max Maischein C<corion@cpan.org>.
432  
433 =head1 LICENSE
434  
435 This module is released under the same terms as Perl itself.
436  
437 =cut
« Makefile.PL ↑ Summary