blib/lib/Iterator/Records.pm

filter: Statementstmt 70.6% 253 / 358 Branchbran 61.1% 55 / 90 Conditioncond 71.4% 10 / 14 MC/DCmcdc 57.1% 4 / 7 Subroutinesub 71.6% 53 / 74 Podpod 90.9% 20 / 22 totaltotal 69.9% 395 / 565 CC 54 SCAR 15.2
CC
54
Cov
69%
open
20.0
__ANON__
13.1
select
12.0
CRAP 4.6
↑ Summary
1 package Iterator::Records;
2  
3 5 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use Iterator::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 #use Data::Dumper;
9  
10 =head1 NAME
11  
12 Iterator::Records - a simple iterator for arrayref record sources
13  
14 =head1 VERSION
15  
16 Version 0.02
17  
18 =cut
19  
20 5 our $VERSION = '0.02';
21  
22  
23 =head1 SYNOPSIS
24  
25 Iterator::Records uses L<Iterator::Simple> to work with iterators whose values are arrayrefs of named fields. These can be called I<record streams>.
26 A record stream can be seen as the same thing as a DBI retrieval, but without most of the machinery for DBI - and of course, a DBI query is one of the ways you
27 can build a record stream.
28  
29 The actual API of Iterator::Records isn't as simple or elegant as L<Iterator::Simple>, simply because there's more to keep track of. But the basic
30 approach is similar: an Iterator::Records object defines how to iterate something, then you use the iter() method to create an iterator from it.
31 The result is an Iterator::Simple iterator known to return records, i.e. arrayrefs of fields that match the field list specified.
32  
33 Note that the Iterator::Records object is an iterator *factory*, and the actual iterator itself is returned by the call to iter().
34  
35 use Iterator::Records;
36
37 my $spec = Iterator::Records->new (<something iterable>, ['field 1', 'field 2']);
38
39 my $iterator = $spec->iter();
40 while (my $row = $iterator->()) {
41 my ($field1, $field2) = @$row;
42 }
43
44 $iterator = $spec->iter_hash();
45 while (my $row = $iterator->()) {
46 print $row->{field 1};
47 }
48
49 my ($f1, $f2);
50 $iterator = $spec->iter_bind(\$f1, \$f2);
51 while ($iterator->()) {
52 print "$f1 - $f2\n";
53 }
54  
55 Note that the iterator itself is just an L<Iterator::Simple> iterator. Now hold on, though, because here's where things get interesting.
56  
57 my $recsource = Iterator::Records->new (sub { ... }, ['field 1', 'field 2']);
58 my $iterator = $recsource->select ("field 1")->iter;
59 while (my $row = $iterator->()) {
60 my ($field1) = @$row;
61 }
62
63 my @fields = $recsource->fields();
64 my $fields = $recsource->fields(); # Returns an arrayref in scalar context.
65
66 $rs = $recsource->where (sub { ... }, "field 1", "field 2");
67 $rs = $recsource->fixup ("field 1", sub { ... } );
68 $rs = $recsource->calc ("field 3", sub { ... } );
69 $rs = $rs->select ("field 2", "field 3", "field 1");
70 $rs = $rs->select (["field 2", "field 3", "field 1"]);
71
72 $rs = $recsource->transform (["where", ["field 1", "=", "x"]],
73 ["fixup", ["field 1, sub { ... }]]);
74  
75  
76 Since Iterator::Records is essentially a more generalized way of iterating DBI results, there are a few wrappers to make things easy.
77  
78 my $dbh = Iterator::Records::db->connect(--DBI syntax--);
79 my $dbh = Iterator::Records::db->open('sqlite file');
80 my $dbh = Iterator::Records::db->open(); # Defaults to an in-memory SQLite database
81
82 This is not the direct DBI handle; it's got simplified syntax as follows:
83  
84 my $value = $dbh->get ('select value from table where id=?', $id); # Single value retrieval in one whack.
85 $dbh->do ("insert ..."); # Regular insertion, just like in DBI, except simpler.
86 my $record = $dbh->insert ("insert ..."); # Calls last_insert_id ('', '', '', ''), which will likely fail except with SQLite.
87  
88 And then you have the actual iterator machinery.
89  
90 my $iter = $dbh->iterator ('select * from table')->iter();
91 my $sth = $dbh->prepare (--DBI syntax--);
92 my $iter = $sth->iter ($value1, $value2);
93 while ($iter->()) {
94 my ($field1, $field2) = @$_;
95 }
96
97 We can load an iterator into a table. If you have Data::Tab installed, it will make a Data::Tab with the column names from this iterator.
98 Otherwise, it will simply return an arrayref of arrayrefs by calling Iterator::Simple's "list" method.
99  
100 my $data = $recsource->table;
101
102 The "report" method returns an Iterator::Simple that applies an sprintf to each value in the record source. If you supply a list of fields to dedupe it will replace them with ""
103 if their value is the same as the previous row. This is useful for tabulated data where, for instance, the date may be the same from line to line and if so should only be
104 displayed once.
105  
106 my $report = $recsource->report ("%-20s %s", ["field 1"]); # Here, field 2 would not be deduped.
107 my $report = join ('\n', $recsource->report (...)->list);
108  
109 =cut
110  
111 5 ▶use Iterator::Records;
Subroutine BEGIN: called CC=1 SCAR=0.0
112  
113 =head1 BASIC ITERATION
114  
115 =head2 new (iterable, arrayref of fields)
116  
117 To specify an Iterator::Records from scratch, just take whatever iterable thing you have, and specify a list of fields in the resulting records.
118 If the iterable is anything but a coderef, Iterator::Records->iter will simply pass it straight to Iterator::Simple for iteration. If it's a coderef,
119 it will be called, and its return value will be passed to Iterator::Simple. This allows record streams to be reused.
120  
121 As an added bonus of this extra level of indirection, you can call "iter" with parameters that will be passed on to the coderef. This turns the
122 Iterator::Records object into a parameterizable iterator factory.
123  
124 =cut
125  
126 24 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
127 24 my ($class, $iterable, $fields) = @_;
128 24 my $self = bless ({}, $class);
129 24 ▶ croak "Iterator spec not iterable" unless Iterator::Simple::is_iterable($iterable);
Branch: 1 branch
BranchTrueFalseTotal
unless Iterator::Simple::is_iterable($iterable) 0 24 24
130 24 $self->{gen} = $iterable;
131 24 $self->{f} = $fields;
132 24 $self->{id} = '*';
133 24 $self;
134 }
135  
136 21 ▶sub fields { $_[0]->{f}; }
Subroutine fields: called CC=1 SCAR=0.0
Pod undocumented
137 0 ▶sub id {
Subroutine id: not called CC=2 SCAR=17.9
Pod undocumented
138 0 my $self = shift;
139 0 ▶ if (scalar @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 0 0 0
140 0 $self->{id} = shift;
141 }
142 0 $self->{id};
143 }
144  
145 =head2 iter, iter_hash, iter_bind
146  
147 Basic iteration of the record source returns an arrayref for each record. Alternatively, an iterator can be created which returns a hashref for each
148 record, with the field names keying the return values in each record. This is less efficient, but it's often handy. The third option is to bind a list
149 of scalar references that will be written automagically on each retrieval. The return value in this case is still the original arrayref record.
150  
151 =cut
152  
153 45 ▶sub iter {
Subroutine iter: called CC=2 SCAR=6.9
Pod documented
154 45 my $self = shift;
155 45 ▶ if (ref $self->{gen} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'gen'} eq 'CODE') { } 20 25 45
156 20 return Iterator::Simple::iter($self->{gen}->(@_));
157 } else {
158 25 return Iterator::Simple::iter($self->{gen});
159 }
160 }
161 2 ▶sub iter_hash {
Subroutine iter_hash: called CC=1 SCAR=0.0
Pod documented
162 2 my $self = shift;
163 2 my $iter = $self->iter();
164 6 ▶ Iterator::Simple::Iterator->new(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
165 6 ▶ if (my $rec = $iter->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 4 2 6
166 4 my $ret = {};
167 4 my $i = 0;
168 4 foreach my $f (@{$self->{f}}) {
169 8 $ret->{$f} = $rec->[$i++];
170 }
171 4 return $ret;
172 } else {
173 2 return undef;
174 }
175 2 });
176 }
177 2 ▶sub iter_bind {
Subroutine iter_bind: called CC=1 SCAR=0.0
Pod documented
178 2 my $self = shift;
179 2 my $iter = $self->iter();
180 2 my @fields = (@_);
181 6 ▶ Iterator::Simple::Iterator->new(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
182 6 ▶ if (my $rec = $iter->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 4 2 6
183 4 my $i = 0;
184 4 foreach my $f (@fields) {
185 8 $$f = $rec->[$i++];
186 }
187 4 return $rec;
188 } else {
189 2 return undef;
190 }
191 2 });
192 }
193  
194 =head1 TRANSMOGRIFIERS
195  
196 Since our record stream sources are very often provided by fairly simple drivers (like the filesystem walker in File::Org), it's not at all unusual to find ourselves
197 in a position where we want to modify them on the fly, either filtering out some of the records or modifying the records as they go through. There are four different
198 "transmogrifiers" for record streams: where, select, calc, and fixup. The "where" transmogrifier discards records that don't match a particular pattern; "select"
199 removes columns; "calc" adds a column that is calculated by an arbitrary coderef provided; and "fixup" applies a coderef to the record to modify individual field
200 values.
201  
202 Each transmogrifier takes an iterator I<specification>, not an iterator - and returns a new specification that can be iterated. The source stream will then be iterated
203 internally.
204  
205 =head2 where (sub { ... }, 'field 1', 'field 2')
206  
207 Filtration of records is not really any different from igrep - given a record stream, we provide a coderef that tells us to include or not to include. If fields
208 are specified, their values for the record to be examined will be passed to the coderef as its parameters; otherwise the entire record is provided as an arrayref
209 and the coderef can extract values on its own. The list of fields is not affected.
210  
211 =head2 select ('field 1', 'field 3')
212  
213 Returns a spec for a new iterator that includes only the fields listed, in the order listed.
214  
215 =head2 calc ('new field', sub { ... }, 'field 1', 'field 2')
216  
217 Returns a spec for a new iterator that includes a new field calculated by the coderef provided; as for "where", if fields are listed they will be passed into the
218 coderef as parameters, but otherwise the entire record will be passed in. The new field will appear at the end of the current field list.
219  
220 =head2 fixup (sub { ... })
221  
222 Returns a spec for a new iterator in which each record is first visited by the coderef provided. This is just an imap in more record-based form. The field
223 list is unchanged.
224  
225 =head2 dedupe ('field 1', 'field 2')
226  
227 Keeps track of the last values for field 1 and field 2; if the new value is a duplicate, passes an empty string through instead. Useful for reporting.
228 The field list is unchanged.
229  
230 =head2 rename ('field 1', 'new name', [more pairs])
231  
232 To rename a field (or more than one), use 'rename'. The record is not changed.
233  
234 =head2 transmogrify (['where', ...], ['calc', ...])
235  
236 Any sequence of transmogrifiers can be chained together in a single step using the L<transmogrify> method.
237  
238 =cut
239  
240 33 ▶sub _find_offsets {
Subroutine _find_offsets: called CC=3 SCAR=11.0
241 33 my $field_list = shift;
242 33 my $size = scalar @{$field_list}-1;
243 33 my @output;
244 33 foreach my $f (@_) {
245 49 my ($index) = grep { $field_list->[$_] eq $f } (0 .. $size);
246 49 ▶ croak "Unknown field '$f' used in transmogrifier" unless defined $index;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $index 1 48 49
247 48 push @output, $index;
248 }
249 32 @output;
250 }
251  
252 1 ▶sub where {
Subroutine where: called CC=1 SCAR=0.0
Pod documented
253 1 my $self = shift;
254 1 $self->transmogrify (['where', @_]);
255 }
256  
257 6 ▶sub _where {
Subroutine _where: called CC=2 SCAR=7.0
258 6 my $fields = shift;
259 6 my $tester = shift;
260 6 my @field_offsets = _find_offsets ($fields, @_);
261 6 my $parms = "";
262 6 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 6 0 6
263
264 6 my $sub = <<"EOF";
265 sub {
266 my \$rec = shift;
267 return \$rec if \$tester->($parms);
268 return undef;
269 }
270 EOF
271 #print STDERR $sub;
272 6 eval $sub;
273 }
274  
275 1 ▶sub select {
Subroutine select: called CC=1 SCAR=0.0
Pod documented
276 1 my $self = shift;
277 1 $self->transmogrify (['select', @_]);
278 }
279 3 ▶sub _select_fields {
Subroutine _select_fields: called CC=1 SCAR=0.0
280 3 shift;
281 3 \@_;
282 }
283 7 ▶sub _select {
Subroutine _select: called CC=2 SCAR=7.0
284 7 my $fields = shift;
285 7 my @field_offsets = _find_offsets ($fields, @_);
286 7 my $parms = "";
287 7 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 7 0 7
288
289 7 my $sub = <<"EOF";
290 sub {
291 my \$rec = shift;
292 return [$parms];
293 }
294 EOF
295 #print STDERR $sub;
296 7 eval $sub;
297 }
298  
299 1 ▶sub calc {
Subroutine calc: called CC=1 SCAR=0.0
Pod documented
300 1 my $self = shift;
301 1 $self->transmogrify (['calc', @_]);
302 }
303 4 ▶sub _calc_fields {
Subroutine _calc_fields: called CC=1 SCAR=0.0
304 4 my @fields = @{$_[0]};
305 4 push @fields, $_[2];
306 4 \@fields;
307 }
308 8 ▶sub _calc {
Subroutine _calc: called CC=2 SCAR=6.9
309 8 my $fields = shift;
310 8 my $calcer = shift;
311 8 shift; # The name of our output variable
312 8 my @field_offsets = _find_offsets ($fields, @_);
313 7 my $parms = "";
314 7 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 5 2 7
315
316 7 my $sub = <<"EOF";
317 sub {
318 my \$rec = shift;
319 return [@\$rec, \$calcer->($parms)];
320 }
321 EOF
322 #print STDERR $sub;
323 7 eval $sub;
324 }
325  
326 1 ▶sub fixup {
Subroutine fixup: called CC=1 SCAR=0.0
Pod documented
327 1 my $self = shift;
328 1 $self->transmogrify (['fixup', @_]);
329 }
330 2 ▶sub _fixup {
Subroutine _fixup: called CC=2 SCAR=7.0
331 2 my $fields = shift;
332 2 my $calcer = shift;
333 2 my @field_offsets = _find_offsets ($fields, @_);
334 2 my $output = '$rec->[' . shift(@field_offsets) . ']';
335 2 my $parms = "";
336 2 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 2 0 2
337
338 2 my $sub = <<"EOF";
339 sub {
340 my \$rec = shift;
341 \$rec = [@\$rec];
342 $output = \$calcer->($parms);
343 return \$rec;
344 }
345 EOF
346 #print STDERR $sub;
347 2 eval $sub;
348 }
349  
350 2 ▶sub dedupe {
Subroutine dedupe: called CC=1 SCAR=0.0
Pod documented
351 2 my $self = shift;
352 2 $self->transmogrify (['dedupe', @_]);
353 }
354 4 ▶sub _dedupe {
Subroutine _dedupe: called CC=1 SCAR=0.0
355 4 my $fields = shift;
356 4 my ($target) = _find_offsets ($fields, $_[0]);
357  
358 4 my $value = '$rec->[' . $target . ']';
359
360 4 my $last_value = ''; # Closures are magic.
361  
362 4 my $sub = <<"EOF";
363 sub {
364 my \$rec = shift;
365 my \$val = $value;
366 if (\$val eq \$last_value) {
367 \$rec = [@\$rec];
368 $value = '';
369 } else {
370 \$last_value = \$val;
371 }
372 return \$rec;
373 }
374 EOF
375 #print STDERR $sub;
376 4 eval $sub;
377 }
378  
379 1 ▶sub _gethashval_fields {
Subroutine _gethashval_fields: called CC=1 SCAR=0.0
380 1 my $fields = shift;
381 1 shift; # skip the name of the value bag.
382 1 my @fields = (@$fields, @_);
383 1 \@fields;
384 }
385  
386 2 ▶sub _gethashval {
Subroutine _gethashval: called CC=1 SCAR=0.0
387 2 my $fields = shift;
388 2 my ($fieldno) = Iterator::Records::_find_offsets ($fields, shift);
389 2 my $vals = "\$rec->[$fieldno]->{" . join ("}, \$rec->[$fieldno]->{", @_) . '}';
390
391 2 my $sub = <<"EOF";
392 sub {
393 my \$rec = shift;
394 return [@\$rec, $vals ];
395 }
396 EOF
397 #print STDERR $sub;
398 2 eval $sub;
399 }
400  
401 2 ▶sub _count {
Subroutine _count: called CC=2 SCAR=6.9
402 2 my $fields = shift;
403 2 shift; # The name of our output variable
404 2 my $count = shift;
405 2 ▶ $count = 0 unless defined $count;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $count 0 2 2
406 2 $count -= 1;
407 4 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
408 4 my $rec = shift;
409 4 $count += 1;
410 4 [@$rec, $count];
411 }
412 2 }
413  
414 3 ▶sub _limit {
Subroutine _limit: called CC=1 SCAR=0.0
415 3 my $fields = shift;
416 3 my $limit = shift;
417 3 my $count = 0;
418 8 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
419 8 ▶ return undef unless $count < $limit;
Branch: 1 branch
BranchTrueFalseTotal
unless $count < $limit 4 4 8
420 4 $count += 1;
421 4 shift();
422 }
423 3 }
424  
425 # The walker framework is *really* minimalistic. It basically looks exactly like _calc, but instead of returning just the parent record (to which, unlike calc, it can add fields),
426 # it can return a list of records and/or iterators to take the place of the parent record - which can include the parent record, so it's effectively an add-or-replace.
427 2 ▶sub _walk_fields {
Subroutine _walk_fields: called CC=2 SCAR=7.2
428 2 my $fields = shift;
429 2 shift; # skip the walker coderef
430 2 my $newfields = shift;
431 2 ▶ if (defined $newfields) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $newfields) 2 0 2
432 2 return [@$newfields, @$fields];
433 }
434 0 $fields;
435 }
436 4 ▶sub _walk {
Subroutine _walk: called CC=1 SCAR=0.0
437 4 my $fields = shift;
438 4 my $walker_factory = shift;
439 4 my $newfields = shift; # The (optional) arrayref of fields we're going to add
440 4 my @field_offsets = _find_offsets ($fields, @_);
441  
442 # The walker framework is unusual in that, instead of building a closure here, we are actually given a closure *factory* that will make it for us.
443 # This factory is given the fields for the input record, the new fields expected for the output record, the list of fields it's supposed to use,
444 # and the offsets of those fields in the input record.
445 # It returns a closure that takes the input record and returns a list of records and/or new iterators that ->transmogrify will buffer and return as appropriate.
446 4 $walker_factory->($fields, $newfields, \@_, \@field_offsets);
447 }
448  
449 0 ▶sub rename {
Subroutine rename: not called CC=1 SCAR=6.9
Pod documented
450 0 my $self = shift;
451 0 $self->transmogrify (['rename', @_]);
452 }
453 1 ▶sub _rename_fields {
Subroutine _rename_fields: called CC=4 SCAR=13.9
454 1 my $fields = shift;
455 1 my @fields = @$fields;
456 1 ▶ while (scalar @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 2 1 3
457 2 my $from = shift;
458 2 my $to = shift;
459 2 ▶ last unless defined $to;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $to 0 2 2
460 2 ▶ @fields = map { $_ eq $from ? $to : $_ } @fields;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $from ? : 2 4 6
461 }
462 1 \@fields;
463 }
464 3 ▶sub _no_change {
Subroutine _no_change: called CC=1 SCAR=0.0
465 3 ▶ sub { $_[0] }; # passes the record through as efficiently as possible
Subroutine __ANON__: called CC=1 SCAR=0.0
466 }
467  
468 5 our $transmogrifiers = {
469 'where' => [undef, \&_where],
470 'select' => [\&_select_fields, \&_select],
471 'calc' => [\&_calc_fields, \&_calc],
472 'fixup' => [undef, \&_fixup],
473 'dedupe' => [undef, \&_dedupe],
474 'rename' => [\&_rename_fields, \&_no_change],
475 'gethashval' => [\&_gethashval_fields, \&_gethashval],
476 'count' => [\&_calc_fields, \&_count],
477 'limit' => [undef, \&_limit],
478 'walk' => [\&_walk_fields, \&_walk],
479 };
480 19 ▶sub _find_transmogrifier { $_[0]->_find_core_transmogrifier ($_[1]); } # This is where you want to look up specialty transmogrifiers in subclasses.
Subroutine _find_transmogrifier: called CC=1 SCAR=0.0
481 19 ▶sub _find_core_transmogrifier {
Subroutine _find_core_transmogrifier: called CC=2 SCAR=6.9
482 19 ▶ croak "Unknown transmogrifier '" . $_[1] . "'" unless exists $transmogrifiers->{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$Iterator::Records::transmogrifiers{$_[1]} 1 18 19
483 18 @{$transmogrifiers->{$_[1]}};
484 }
485  
486 14 ▶sub transmogrify {
Subroutine transmogrify: called CC=3 SCAR=11.0
Pod documented
487 14 my $self = shift;
488
489 14 my $fieldlist = $self->fields();
490
491 # Convert the list of transmogrifier specs into a list of coderefs, and calculate the field list at each step.
492 14 my @tlist = ();
493 14 foreach my $t (@_) {
494 19 my ($transmog, @parms) = @$t;
495 19 my ($fielder, $coder) = $self->_find_transmogrifier ($transmog);
496 18 $coder->($fieldlist, @parms); # Run through one build just to check our input fields for correctness
497 17 push @tlist, [$coder, $fieldlist, [@parms]]; # Then save our builders so we can call them afresh on each iteration.
498 17 ▶ $fieldlist = $fielder->($fieldlist, @parms) if defined $fielder;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fielder 11 6 17
499 #print STDERR "field list is now " . Dumper($fieldlist);
500 }
501  
502 15 ▶ my $sub = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
503 15 my $in = $self->iter(@_); # Parameters are passed through to source iterator.
504  
505 15 my @buffer = ();
506 15 my $buffer_which;
507 my $subiterator;
508
509 15 my @reified_tlist = ();
510 15 foreach my $t (@tlist) {
511 23 my ($coder, $fieldlist, $parms) = @$t;
512 23 push @reified_tlist, $coder->($fieldlist, @$parms);
513 }
514 #my @reified_tlist = map { $_->() } @tlist;
515
516 61 ▶ sub {
Subroutine __ANON__: called CC=13 SCAR=25.8
517 61 SKIP:
518 my $rec = undef;
519 61 my $walked = 0; # Is this record one that came from a walker?
520 61 ▶ if (defined $subiterator) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subiterator) 3 58 61
521 3 $rec = $subiterator->();
522 3 ▶ if (not defined $rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $rec) { } 1 2 3
523 1 $subiterator = undef;
524 } else {
525 2 $walked = 1;
526 }
527 }
528
529 61 ▶ if (not defined $rec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rec) 59 2 61
530 59 ▶ if (scalar @buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @buffer) { } 2 57 59
531 2 $rec = shift @buffer;
532 2 ▶ if (ref $rec ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rec ne "ARRAY") 1 1 2
533 1 $subiterator = $rec->iter();
534 1 goto SKIP;
535 }
536 1 $walked = 1;
537 } else {
538 57 $rec = $in->();
539 }
540 }
541 60 ▶ return undef unless defined $rec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rec 14 46 60
542
543 46 my $which_t = 0;
544 46 foreach my $t (@reified_tlist) {
545 70 $which_t += 1;
546 70 ▶ next if ($walked and $which_t <= $buffer_which); # Skip the transmogrifiers that ran before the stage of this walk-originated record
Branch: 1 branch
BranchTrueFalseTotal
if $walked and $which_t <= $buffer_which 3 67 70
Condition66%2/3
$walked and $which_t <= $buffer_which
!ll&&!rl&&r
6703
MC/DC50%1/2
$walked and $which_t <= $buffer_which
$walked $which_t <= $buffer_which
Truth table66%2/3
A and B
A= $walkedB= $which_t <= $buffer_which
ABresult
0X0
100
111
547 67 my @things = $t->($rec);
548 67 ▶ goto SKIP unless defined $things[0]; # This is the shortcut used for "where" functionality.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $things[0] 7 60 67
549 60 ▶ if (ref ($things[0]) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $things[0] eq 'ARRAY') { } 60 0 60
550 60 $rec = shift @things;
551 60 ▶ if (@things) {
Branch: 1 branch
BranchTrueFalseTotal
if (@things) 2 58 60
552 2 push @buffer, @things;
553 2 $buffer_which = $which_t; # Tacit requirement: only one walker per transmogrifier list, with bad error otherwise
554 }
555 } else {
556 0 push @buffer, @things;
557 0 $buffer_which = $which_t;
558 0 goto SKIP;
559 }
560 }
561 39 $rec;
562 }
563 12 };
564
565 12 my $class = ref($self);
566 12 $class->new ($sub, $fieldlist); # 2019-02-23 - use class of source, not "Iterator::Records"
567 }
568  
569 =head1 LOADING AND REPORTING
570  
571 These are some handy utilities for dealing with record streams.
572  
573 =head2 load ([limit]), load_parms(parms...), load_lparms(limit, parms...), load_iter(iterator, [limit])
574  
575 The I<load> function simply loads the stream into an arrayref of arrayrefs. If I<limit> is specified, at most that many rows will be loaded; otherwise,
576 the iterator runs as long as it has data.
577  
578 Note that this is called directly on the definition of the stream, not on the resulting iterator. Consequently, I<load> can't be used to "page" through
579 an existing record stream - if you want to do that, you should look at L<Data::Tab>, which was written specifically to support the buffered reading of
580 record streams and manipulation of the resulting buffers.
581  
582 This form of C<load> can't be used on iterator factories that take parameters. If you have a factory that requires parameters, use C<load_parms>. Finally,
583 to use both a limit and parameters, use C<load_lparms>.
584  
585 All of these are just sugar for the core method C<load_iter>, which, given a started iterator and an optional limit, loads it.
586  
587 =cut
588  
589 19 ▶sub load_iter {
Subroutine load_iter: called CC=6 SCAR=17.9
Pod documented
590 19 my ($self, $i, $limit) = @_;
591
592 19 my @returns = ();
593 19 my $row;
594 19 ▶ while (((not defined $limit) or (defined $limit and $limit > 0)) and $row = $i->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (!defined($limit) || defined $limit && $limit > 0 and $row = &$i()) 49 19 68
Condition88%8/9
!defined($limit) || defined $limit && $limit > 0 and $row = &$i()
!ll&&!rl&&r
21749
not defined $limit or defined $limit and $limit > 0
l!l&&r!l&&!r
6332
defined $limit and $limit > 0
!ll&&!rl&&r
023
MC/DC75%3/4
!defined($limit) || defined $limit && $limit > 0 and $row = &$i()
not defined $limit defined $limit $limit > 0 $row = &$i()
Truth table66%4/6
not(A) or B and C and D
A= not defined $limitB= defined $limitC= $limit > 0D= $row = &$i()
ABCDresult
00XX0
010X0
1XX00
01100
1XX11
01111
595 49 ▶ $limit = $limit - 1 if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 3 46 49
596 49 push @returns, [@$row];
597 }
598 19 \@returns;
599 }
600  
601 16 ▶sub load {
Subroutine load: called CC=1 SCAR=0.0
Pod documented
602 16 my ($self, $limit) = @_;
603 16 $self->load_iter($self->iter(), $limit);
604 }
605 1 ▶sub load_parms {
Subroutine load_parms: called CC=1 SCAR=0.0
Pod documented
606 1 my $self = shift;
607 1 $self->load_iter($self->iter(@_));
608 }
609 1 ▶sub load_lparms {
Subroutine load_lparms: called CC=1 SCAR=0.0
Pod documented
610 1 my $self = shift;
611 1 my $limit = shift;
612 1 $self->load_iter($self->iter(@_), $limit);
613 }
614  
615 =head2 report (format, [dedupe list])
616  
617 The I<report> method is another retrieval method; that is, it returns an iterator when called. However, this iterator is not a record stream; instead,
618 it is a string iterator. Each record in the defined stream is passed through sprintf with the format provided. For convenience, if a list of columns
619 is provided, performs a dedupe transmogrification on the incoming records before formatting them.
620  
621 =cut
622  
623 1 ▶sub report {
Subroutine report: called CC=2 SCAR=7.0
Pod documented
624 1 my $self = shift;
625 1 my $format = shift;
626 1 ▶ if (scalar @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 0 1 1
627 0 my $self = $self->dedupe (@_);
628 }
629 1 my $iter = $self->iter();
630 3 ▶ Iterator::Simple::Iterator->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
631 3 ▶ if (my $rec = $iter->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 2 1 3
632 2 return sprintf ($format, @$rec);
633 } else {
634 1 return undef;
635 }
636 1 });
637 }
638  
639 =head2 table ([limit]), table_parms(parms...), table_lparms(limit, parms...), table_iter(iterator, [limit])
640  
641 The I<table> functions work just like the I<load> functions, but load the iterator into a L<Data::Org::Table>, if that module is installed.
642  
643 =cut
644  
645 0 ▶sub table_iter {
Subroutine table_iter: not called CC=2 SCAR=17.9
Pod documented
646 0 my $self = shift;
647
648 0 eval "use Data::Org::Table";
649 0 ▶ croak 'Data::Org::Table is not installed' if (@!);
Branch: 1 branch
BranchTrueFalseTotal
if @! 0 0 0
650  
651 0 Data::Org::Table->new ($self->load_iter(@_), $self->fields, 0);
652 }
653  
654 0 ▶sub table {
Subroutine table: not called CC=1 SCAR=6.9
Pod documented
655 0 my ($self, $limit) = @_;
656 0 $self->table_iter($self->iter(), $limit);
657 }
658 0 ▶sub table_parms {
Subroutine table_parms: not called CC=1 SCAR=6.9
Pod documented
659 0 my $self = shift;
660 0 $self->table_iter($self->iter(@_));
661 }
662 0 ▶sub table_lparms {
Subroutine table_lparms: not called CC=1 SCAR=6.9
Pod documented
663 0 my $self = shift;
664 0 my $limit = shift;
665 0 $self->table_iter($self->iter(@_), $limit);
666 }
667  
668 package Iterator::Records::db;
669 5 ▶use Iterator::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
670 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
671  
672 5 our $dbi_ok = 1;
673 5 our $sqlite_ok = 0;
674 0 ▶eval "use DBI;";
Subroutine BEGIN: called CC=1 SCAR=1.2
675 5 ▶$dbi_ok = 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 5 0 5
676 5 ▶if ($dbi_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Iterator::Records::db::dbi_ok) 0 5 5
677 5 ▶ use vars qw(@ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
678 0 @ISA = qw(DBI::db);
679
680 0 eval "use DBD::SQLite;";
681 0 ▶ $sqlite_ok = 1 unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 0 0 0
682 }
683  
684 =head2 open ([filename])
685  
686 The C<open> method opens an SQLite database file. Opens an in-memory file if no filename is provided.
687  
688 =cut
689  
690 0 ▶sub open {
Subroutine open: not called CC=4 SCAR=30.0
691 0 ▶ croak "DBI is not installed" unless $dbi_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $Iterator::Records::db::dbi_ok 0 0 0
692 0 ▶ croak "SQLite is not installed" unless $sqlite_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $Iterator::Records::db::sqlite_ok 0 0 0
693 0 my $class = shift;
694 0 ▶ my $file = shift || ':memory:';
Condition0%0/2
shift() || ':memory:'
l!l
00
MC/DC0%0/1
shift() || ':memory:'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
695 0 my $dbh = DBI->connect('dbi:SQLite:dbname=' . $file);
696 0 bless($dbh, $class);
697 0 $dbh;
698 }
699  
700 0 ▶sub open_dbh {
Subroutine open_dbh: not called CC=2 SCAR=17.9
701 0 ▶ croak "DBI is not installed" unless $dbi_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $Iterator::Records::db::dbi_ok 0 0 0
702 0 my $class = shift;
703 0 my $dbh = shift;
704 0 bless ($dbh, $class);
705 0 $dbh;
706 }
707  
708 =head2 connect(...)
709  
710 The C<connect> method is just the DBI connect method; we get it via inheritance.
711  
712 =head2 get (query, [parms])
713  
714 The C<get> method takes some SQL, executes it with the parameters passed in (if any), retrieves the first row, and returns
715 the value of the first field of that row.
716  
717 =cut
718  
719 0 ▶sub get {
Subroutine get: not called CC=1 SCAR=6.9
720 0 my $self = shift;
721 0 my $query = shift;
722 0 my $sth = $self->prepare($query);
723 0 $sth->execute(@_);
724 0 my $row = $sth->fetchrow_arrayref;
725 0 $row->[0];
726 }
727  
728 =head2 select
729  
730 The C<select> method retrieves an array of arrayrefs for the rows returned from the query.
731 In scalar mode, returns the arrayref from C<fetchall_arrayref>.
732  
733 =cut
734  
735 0 ▶sub select {
Subroutine select: not called CC=3 SCAR=24.8
736 0 my $self = shift;
737 0 my $query = shift;
738 0 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 0 0
739 0 my $sth = $self->prepare($query);
740 0 $sth->execute(@_);
741 0 my $ret = $sth->fetchall_arrayref;
742 0 ▶ return wantarray ? @$ret : $ret;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
743 }
744  
745 =head2 select_one
746  
747 The C<select_one> method runs a query and returns the first row as an arrayref.
748  
749 =cut
750  
751 0 ▶sub select_one {
Subroutine select_one: not called CC=1 SCAR=6.9
752 0 my $self = shift;
753 0 my $query = shift;
754 0 my $sth = $self->prepare($query);
755 0 $sth->execute(@_);
756 0 $sth->fetchrow_arrayref;
757 }
758  
759  
760 =head2 iterator (query, [parms), itparms (query, fields)
761  
762 This is the actual reason for putting this into the Iterator::Records namespace - given a query against the database, we return
763 an iterator factory for iterators over the rows of the query. Like C<select>, the basic C<iterator> call will assemble a query
764 and execute it. It will then ask DBI for the names of the fields in the query and use that information to build an C<Iterator::Records> object
765 that, when iterated, will return the query results. If iterated again, it will run a new query.
766  
767 If you want to have parameterized queries instead, use C<itparms>, then pass parameters to the factory it creates. In this case, since
768 the query can't be run in advance, you have to provide the field names you expect. (They don't have to match the ones the database will give
769 you, though, in this case.)
770  
771 =cut
772  
773 # Here's the subtle part. We have to execute the query once to get the field names from the DBI driver. So the first time the iterator factory
774 # is called, it should return an iterator over *that instance*. But the next time, it has to create a new one.
775 # 2019-04-23 - turns out SQLite is perfectly capable of returning NAMES after the prepare but before execute - not all drivers can, but SQLite can. So this is largely unnecessary.
776 0 ▶sub iterator {
Subroutine iterator: not called CC=1 SCAR=6.9
777 0 my $self = shift;
778 0 my $query = shift;
779 0 my $sth = $self->prepare($query);
780 0 $sth->execute(@_);
781 0 my $names = $sth->{NAME};
782 0 my $first_time = 1;
783 0 ▶ my $factory = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
784 0 ▶ if ($first_time) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first_time) { } 0 0 0
785 0 $first_time = 0;
786 } else {
787 0 $sth = $self->prepare($query);
788 0 $sth->execute(@_);
789 }
790 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
791 0 $sth->fetchrow_arrayref;
792 }
793 0 };
794 0 Iterator::Records->new ($factory, $names);
795 }
796  
797 0 ▶sub itparms {
Subroutine itparms: not called CC=2 SCAR=17.9
798 0 my $self = shift;
799 0 my $query = shift;
800 0 my $fields = shift;
801 0 my $sth = $self->prepare($query);
802 0 ▶ $fields = $sth->{NAME} unless defined $fields;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fields 0 0 0
803
804 0 ▶ my $factory = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
805 0 $sth->execute(@_);
806 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
807 0 $sth->fetchrow_arrayref;
808 }
809 0 };
810 0 Iterator::Records->new ($factory, $fields);
811 }
812  
813 =head2 insert
814  
815 The C<insert> command calls C<last_insert_id> after the insertion, and returns that value. Just a little shorthand. Since retrieval of the ID for the last
816 row inserted is very database-specific, it may not work for your particular configuration.
817  
818 =cut
819  
820 0 ▶sub insert {
Subroutine insert: not called CC=1 SCAR=6.9
821 0 my $self = shift;
822 0 my $query = shift;
823 0 my $sth = $self->prepare($query);
824 0 $sth->execute(@_);
825 0 $self->last_insert_id('', '', '', '');
826 }
827  
828 =head2 load_table (table, iterator), load_sql (insert query, iterator)
829  
830 For bulk loading, we have single-call methods C<load_table> and C<load_sql>. The former will build an appropriate insert query for the table in question using the iterator's field list.
831 The second takes an arbitrary insert query, then executes it on each record coming from the iterator. This method can take either an L<Iterator::Records> object, or any coderef or activated
832 iterator that returns arrayrefs; if given the latter it will simply pass them to the execute call.
833  
834 Each returns the number of rows inserted.
835  
836 =cut
837  
838 0 ▶sub load_table {
Subroutine load_table: not called CC=1 SCAR=6.9
839 0 my ($self, $table, $iterator) = @_;
840 0 my $fields = $iterator->fields();
841 0 my @inserts = map { '?' } @$fields;
842 0 my $sql = "insert into $table values (" . join (', ', @inserts) . ')';
843 0 $self->load_sql ($sql, $iterator->iter()); # TODO: an error in our SQL will show this line. Do better.
844 }
845  
846 0 ▶sub load_sql {
Subroutine load_sql: not called CC=3 SCAR=24.8
847 0 my ($self, $query, $iterator) = @_;
848 0 ▶ croak "Source for bulk load not iterable" unless Iterator::Simple::is_iterable($iterator);
Branch: 1 branch
BranchTrueFalseTotal
unless Iterator::Simple::is_iterable($iterator) 0 0 0
849 0 my $iter = Iterator::Simple::iter($iterator);
850 0 my $sth = $self->prepare($query);
851 0 my $count = 0;
852 0 ▶ while (my $rec = $iter->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) 0 0 0
853 0 $count += 1;
854 0 $sth->execute(@$rec);
855 }
856 0 $count;
857 }
858  
859 =head2 do
860  
861 The C<do> command works a little differently from the standard API; DBI's version wants a hashref of attributes that I never use
862 and regularly screw up.
863  
864 =cut
865  
866 0 ▶sub do {
Subroutine do: not called CC=1 SCAR=6.9
867 0 my $self = shift;
868 0 my $query = shift;
869 0 my $sth = $self->prepare($query);
870 0 $sth->execute(@_);
871 }
872  
873 package Iterator::Records::st;
874 5 ▶use vars qw(@ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
875 5 @ISA = qw(DBI::st);
876  
877 # We don't actually have anything to override in the statement, but it has to be defined or the DBI machinery won't work.
878  
879  
880 =head1 AUTHOR
881  
882 Michael Roberts, C<< <michael at cpan.org> >>
883  
884 =head1 BUGS
885  
886 Please report any bugs or feature requests to C<bug-Iterator-Records at rt.cpan.org>, or through
887 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Iterator-Records>. I will be notified, and then you'll
888 automatically be notified of progress on your bug as I make changes.
889  
890  
891  
892  
893 =head1 SUPPORT
894  
895 You can find documentation for this module with the perldoc command.
896  
897 perldoc Iterator::Records
898  
899  
900 You can also look for information at:
901  
902 =over 4
903  
904 =item * RT: CPAN's request tracker (report bugs here)
905  
906 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Iterator-Records>
907  
908 =item * AnnoCPAN: Annotated CPAN documentation
909  
910 L<http://annocpan.org/dist/Iterator-Records>
911  
912 =item * CPAN Ratings
913  
914 L<http://cpanratings.perl.org/d/Iterator-Records>
915  
916 =item * Search CPAN
917  
918 L<http://search.cpan.org/dist/Iterator-Records/>
919  
920 =back
921  
922  
923 =head1 ACKNOWLEDGEMENTS
924  
925  
926 =head1 LICENSE AND COPYRIGHT
927  
928 Copyright 2015 Michael Roberts.
929  
930 This program is free software; you can redistribute it and/or modify it
931 under the terms of the the Artistic License (2.0). You may obtain a
932 copy of the full license at:
933  
934 L<http://www.perlfoundation.org/artistic_license_2_0>
935  
936 Any use, modification, and distribution of the Standard or Modified
937 Versions is governed by this Artistic License. By using, modifying or
938 distributing the Package, you accept this license. Do not use, modify,
939 or distribute the Package, if you do not accept this license.
940  
941 If your Modified Version has been derived from a Modified Version made
942 by someone other than you, you are nevertheless required to ensure that
943 your Modified Version complies with the requirements of this license.
944  
945 This license does not grant you the right to use any trademark, service
946 mark, tradename, or logo of the Copyright Holder.
947  
948 This license includes the non-exclusive, worldwide, free-of-charge
949 patent license to make, have made, use, offer to sell, sell, import and
950 otherwise transfer the Package with respect to any patent claims
951 licensable by the Copyright Holder that are necessarily infringed by the
952 Package. If you institute patent litigation (including a cross-claim or
953 counterclaim) against any party alleging that the Package constitutes
954 direct or contributory patent infringement, then this Artistic License
955 to you shall terminate on the date that such litigation is filed.
956  
957 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
958 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
959 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
960 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
961 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
962 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
963 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
964 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
965  
966  
967 =cut
968  
969 5 1; # End of Iterator::Records
↑ Summary