blib/lib/Iterator/Records.pm

filter: Statementstmt 8.1% 21 / 259 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 14.2% 8 / 56 Podpod n/a totaltotal 7.2% 29 / 399 CC 44 SCAR 34.4
CC
44
Cov
6%
__ANON__
182.0
load_iter
42.0
_rename_fields
20.0
CRAP 31.1
↑ Summary
1 package Iterator::Records;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Iterator::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Iterator::Records - a simple iterator for arrayref record sources
13  
14 =head1 VERSION
15  
16 Version 0.01
17  
18 =cut
19  
20 our $VERSION = '0.01';
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 1 ▶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 sub new {
127 0 ▶ my ($class, $iterable, $fields) = @_;
Subroutine new: not called CC=2 SCAR=17.9
128 0 my $self = bless ({}, $class);
129 0 ▶ croak "Iterator spec not iterable" unless Iterator::Simple::is_iterable($iterable);
Branch: 1 branch
BranchTrueFalseTotal
unless Iterator::Simple::is_iterable($iterable) 0 0 0
130 0 $self->{gen} = $iterable;
131 0 $self->{f} = $fields;
132 0 $self->{id} = '*';
133 0 $self;
134 }
135  
136 0 ▶sub fields { $_[0]->{f}; }
Subroutine fields: not called CC=1 SCAR=6.9
137 sub id {
138 0 ▶ my $self = shift;
Subroutine id: not called CC=2 SCAR=17.9
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 sub iter {
154 0 ▶ my $self = shift;
Subroutine iter: not called CC=2 SCAR=17.9
155 0 ▶ if (ref $self->{gen} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'gen'} eq 'CODE') { } 0 0 0
156 0 return Iterator::Simple::iter($self->{gen}->(@_));
157 } else {
158 0 return Iterator::Simple::iter($self->{gen});
159 }
160 }
161 sub iter_hash {
162 0 ▶ my $self = shift;
Subroutine iter_hash: not called CC=1 SCAR=6.9
163 0 my $iter = $self->iter();
164 Iterator::Simple::Iterator->new(sub {
165 0 ▶ if (my $rec = $iter->()) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 0 0 0
166 0 my $ret = {};
167 0 my $i = 0;
168 0 foreach my $f (@{$self->{f}}) {
169 0 $ret->{$f} = $rec->[$i++];
170 }
171 0 return $ret;
172 } else {
173 0 return undef;
174 }
175 0 });
176 }
177 sub iter_bind {
178 0 ▶ my $self = shift;
Subroutine iter_bind: not called CC=1 SCAR=6.9
179 0 my $iter = $self->iter();
180 0 my @fields = (@_);
181 Iterator::Simple::Iterator->new(sub {
182 0 ▶ if (my $rec = $iter->()) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 0 0 0
183 0 my $i = 0;
184 0 foreach my $f (@fields) {
185 0 $$f = $rec->[$i++];
186 }
187 0 return $rec;
188 } else {
189 0 return undef;
190 }
191 0 });
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 sub _find_offsets {
241 0 ▶ my $field_list = shift;
Subroutine _find_offsets: not called CC=3 SCAR=24.8
242 0 my $size = scalar @{$field_list}-1;
243 0 my @output;
244 0 foreach my $f (@_) {
245 0 my ($index) = grep { $field_list->[$_] eq $f } (0 .. $size);
246 0 ▶ croak "Unknown field '$f' used in transmogrifier" unless defined $index;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $index 0 0 0
247 0 push @output, $index;
248 }
249 0 @output;
250 }
251  
252 sub where {
253 0 ▶ my $self = shift;
Subroutine where: not called CC=1 SCAR=6.9
254 0 $self->transmogrify (['where', @_]);
255 }
256  
257 sub _where {
258 0 ▶ my $fields = shift;
Subroutine _where: not called CC=2 SCAR=17.9
259 0 my $tester = shift;
260 0 my @field_offsets = _find_offsets ($fields, @_);
261 0 my $parms = "";
262 0 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 0 0 0
263
264 0 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 0 eval $sub;
273 }
274  
275 sub select {
276 0 ▶ my $self = shift;
Subroutine select: not called CC=1 SCAR=6.9
277 0 $self->transmogrify (['select', @_]);
278 }
279 sub _select_fields {
280 0 ▶ shift;
Subroutine _select_fields: not called CC=1 SCAR=6.9
281 0 \@_;
282 }
283 sub _select {
284 0 ▶ my $fields = shift;
Subroutine _select: not called CC=2 SCAR=17.9
285 0 my @field_offsets = _find_offsets ($fields, @_);
286 0 my $parms = "";
287 0 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 0 0 0
288
289 0 my $sub = <<"EOF";
290 sub {
291 my \$rec = shift;
292 return [$parms];
293 }
294 EOF
295 #print STDERR $sub;
296 0 eval $sub;
297 }
298  
299 sub calc {
300 0 ▶ my $self = shift;
Subroutine calc: not called CC=1 SCAR=6.9
301 0 $self->transmogrify (['calc', @_]);
302 }
303 sub _calc_fields {
304 0 ▶ my @fields = @{$_[0]};
Subroutine _calc_fields: not called CC=1 SCAR=6.9
305 0 push @fields, $_[2];
306 0 \@fields;
307 }
308 sub _calc {
309 0 ▶ my $fields = shift;
Subroutine _calc: not called CC=2 SCAR=17.9
310 0 my $calcer = shift;
311 0 shift; # The name of our output variable
312 0 my @field_offsets = _find_offsets ($fields, @_);
313 0 my $parms = "";
314 0 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 0 0 0
315
316 0 my $sub = <<"EOF";
317 sub {
318 my \$rec = shift;
319 return [@\$rec, \$calcer->($parms)];
320 }
321 EOF
322 #print STDERR $sub;
323 0 eval $sub;
324 }
325  
326 sub fixup {
327 0 ▶ my $self = shift;
Subroutine fixup: not called CC=1 SCAR=6.9
328 0 $self->transmogrify (['fixup', @_]);
329 }
330 sub _fixup {
331 0 ▶ my $fields = shift;
Subroutine _fixup: not called CC=2 SCAR=17.9
332 0 my $calcer = shift;
333 0 my @field_offsets = _find_offsets ($fields, @_);
334 0 my $output = '$rec->[' . shift(@field_offsets) . ']';
335 0 my $parms = "";
336 0 ▶ $parms = '$rec->[' . join ('], $rec->[', @field_offsets) . ']' if scalar @field_offsets;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @field_offsets 0 0 0
337
338 0 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 0 eval $sub;
348 }
349  
350 sub dedupe {
351 0 ▶ my $self = shift;
Subroutine dedupe: not called CC=1 SCAR=6.9
352 0 $self->transmogrify (['dedupe', @_]);
353 }
354 sub _dedupe {
355 0 ▶ my $fields = shift;
Subroutine _dedupe: not called CC=1 SCAR=6.9
356 0 my ($target) = _find_offsets ($fields, $_[0]);
357  
358 0 my $value = '$rec->[' . $target . ']';
359
360 0 my $last_value = ''; # Closures are magic.
361  
362 0 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 0 eval $sub;
377 }
378  
379 sub _gethashval_fields {
380 0 ▶ my $fields = shift;
Subroutine _gethashval_fields: not called CC=1 SCAR=6.9
381 0 shift; # skip the name of the value bag.
382 0 my @fields = (@$fields, @_);
383 0 \@fields;
384 }
385  
386 sub _gethashval {
387 0 ▶ my $fields = shift;
Subroutine _gethashval: not called CC=1 SCAR=6.9
388 0 my ($fieldno) = Iterator::Records::_find_offsets ($fields, shift);
389 0 my $vals = "\$rec->[$fieldno]->{" . join ("}, \$rec->[$fieldno]->{", @_) . '}';
390
391 0 my $sub = <<"EOF";
392 sub {
393 my \$rec = shift;
394 return [@\$rec, $vals ];
395 }
396 EOF
397 #print STDERR $sub;
398 0 eval $sub;
399 }
400  
401 sub _count {
402 0 ▶ my $fields = shift;
Subroutine _count: not called CC=2 SCAR=17.9
403 0 shift; # The name of our output variable
404 0 my $count = shift;
405 0 ▶ $count = 0 unless defined $count;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $count 0 0 0
406 0 $count -= 1;
407 sub {
408 0 ▶ my $rec = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
409 0 $count += 1;
410 0 [@$rec, $count];
411 }
412 0 }
413  
414 sub _limit {
415 0 ▶ my $fields = shift;
Subroutine _limit: not called CC=1 SCAR=6.9
416 0 my $limit = shift;
417 0 my $count = 0;
418 sub {
419 0 ▶ return undef unless $count < $limit;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless $count < $limit 0 0 0
420 0 $count += 1;
421 0 shift();
422 }
423 0 }
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 sub _walk_fields {
428 0 ▶ my $fields = shift;
Subroutine _walk_fields: not called CC=2 SCAR=17.9
429 0 shift; # skip the walker coderef
430 0 my $newfields = shift;
431 0 ▶ if (defined $newfields) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $newfields) 0 0 0
432 0 return [@$newfields, @$fields];
433 }
434 0 $fields;
435 }
436 sub _walk {
437 0 ▶ my $fields = shift;
Subroutine _walk: not called CC=1 SCAR=6.9
438 0 my $walker_factory = shift;
439 0 my $newfields = shift; # The (optional) arrayref of fields we're going to add
440 0 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 0 $walker_factory->($fields, $newfields, \@_, \@field_offsets);
447 }
448  
449 sub rename {
450 0 ▶ my $self = shift;
Subroutine rename: not called CC=1 SCAR=6.9
451 0 $self->transmogrify (['rename', @_]);
452 }
453 sub _rename_fields {
454 0 ▶ my $fields = shift;
Subroutine _rename_fields: not called CC=4 SCAR=30.0
455 0 my @fields = @$fields;
456 0 ▶ while (scalar @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 0 0 0
457 0 my $from = shift;
458 0 my $to = shift;
459 0 ▶ last unless defined $to;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $to 0 0 0
460 0 ▶ @fields = map { $_ eq $from ? $to : $_ } @fields;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $from ? : 0 0 0
461 }
462 0 \@fields;
463 }
464 sub _no_change {
465 0 ▶ sub { $_[0] }; # passes the record through as efficiently as possible
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine _no_change: not called CC=1 SCAR=6.9
466 }
467  
468 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 0 ▶sub _find_transmogrifier { $_[0]->_find_core_transmogrifier ($_[1]); } # This is where you want to look up specialty transmogrifiers in subclasses.
Subroutine _find_transmogrifier: not called CC=1 SCAR=6.9
481 sub _find_core_transmogrifier {
482 0 ▶ croak "Unknown transmogrifier '" . $_[1] . "'" unless exists $transmogrifiers->{$_[1]};
Subroutine _find_core_transmogrifier: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$Iterator::Records::transmogrifiers{$_[1]} 0 0 0
483 0 @{$transmogrifiers->{$_[1]}};
484 }
485  
486 sub transmogrify {
487 0 ▶ my $self = shift;
Subroutine transmogrify: not called CC=3 SCAR=24.8
488
489 0 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 0 my @tlist = ();
493 0 foreach my $t (@_) {
494 0 my ($transmog, @parms) = @$t;
495 0 my ($fielder, $coder) = $self->_find_transmogrifier ($transmog);
496 0 $coder->($fieldlist, @parms); # Run through one build just to check our input fields for correctness
497 0 push @tlist, [$coder, $fieldlist, [@parms]]; # Then save our builders so we can call them afresh on each iteration.
498 0 ▶ $fieldlist = $fielder->($fieldlist, @parms) if defined $fielder;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fielder 0 0 0
499 #print STDERR "field list is now " . Dumper($fieldlist);
500 }
501  
502 my $sub = sub {
503 0 ▶ my $in = $self->iter(@_); # Parameters are passed through to source iterator.
Subroutine __ANON__: not called CC=2 SCAR=17.9
504  
505 0 my @buffer = ();
506 0 my $buffer_which;
507 my $subiterator;
508
509 0 my @reified_tlist = ();
510 0 foreach my $t (@tlist) {
511 0 my ($coder, $fieldlist, $parms) = @$t;
512 0 push @reified_tlist, $coder->($fieldlist, @$parms);
513 }
514 #my @reified_tlist = map { $_->() } @tlist;
515
516 sub {
517 0 ▶ SKIP:
Subroutine __ANON__: not called CC=13 SCAR=52.0
518 my $rec = undef;
519 0 my $walked = 0; # Is this record one that came from a walker?
520 0 ▶ if (defined $subiterator) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subiterator) 0 0 0
521 0 $rec = $subiterator->();
522 0 ▶ if (not defined $rec) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $rec) { } 0 0 0
523 0 $subiterator = undef;
524 } else {
525 0 $walked = 1;
526 }
527 }
528
529 0 ▶ if (not defined $rec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rec) 0 0 0
530 0 ▶ if (scalar @buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @buffer) { } 0 0 0
531 0 $rec = shift @buffer;
532 0 ▶ if (ref $rec ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rec ne "ARRAY") 0 0 0
533 0 $subiterator = $rec->iter();
534 0 goto SKIP;
535 }
536 0 $walked = 1;
537 } else {
538 0 $rec = $in->();
539 }
540 }
541 0 ▶ return undef unless defined $rec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rec 0 0 0
542
543 0 my $which_t = 0;
544 0 foreach my $t (@reified_tlist) {
545 0 $which_t += 1;
546 0 ▶ 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 0 0 0
Condition0%0/3
$walked and $which_t <= $buffer_which
!ll&&!rl&&r
000
MC/DC0%0/2
$walked and $which_t <= $buffer_which
$walked $which_t <= $buffer_which
Truth table0%0/3
A and B
A= $walkedB= $which_t <= $buffer_which
ABresult
0X0
100
111
547 0 my @things = $t->($rec);
548 0 ▶ goto SKIP unless defined $things[0]; # This is the shortcut used for "where" functionality.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $things[0] 0 0 0
549 0 ▶ if (ref ($things[0]) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $things[0] eq 'ARRAY') { } 0 0 0
550 0 $rec = shift @things;
551 0 ▶ if (@things) {
Branch: 1 branch
BranchTrueFalseTotal
if (@things) 0 0 0
552 0 push @buffer, @things;
553 0 $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 0 $rec;
562 }
563 0 };
564
565 0 my $class = ref($self);
566 0 $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 sub load_iter {
590 0 ▶ my ($self, $i, $limit) = @_;
Subroutine load_iter: not called CC=6 SCAR=37.4
591
592 0 my @returns = ();
593 0 my $row;
594 0 ▶ 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()) 0 0 0
Condition0%0/9
!defined($limit) || defined $limit && $limit > 0 and $row = &$i()
!ll&&!rl&&r
000
not defined $limit or defined $limit and $limit > 0
l!l&&r!l&&!r
000
defined $limit and $limit > 0
!ll&&!rl&&r
000
MC/DC0%0/4
!defined($limit) || defined $limit && $limit > 0 and $row = &$i()
not defined $limit defined $limit $limit > 0 $row = &$i()
Truth table0%0/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 0 ▶ $limit = $limit - 1 if defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit 0 0 0
596 0 push @returns, [@$row];
597 }
598 0 \@returns;
599 }
600  
601 sub load {
602 0 ▶ my ($self, $limit) = @_;
Subroutine load: not called CC=1 SCAR=6.9
603 0 $self->load_iter($self->iter(), $limit);
604 }
605 sub load_parms {
606 0 ▶ my $self = shift;
Subroutine load_parms: not called CC=1 SCAR=6.9
607 0 $self->load_iter($self->iter(@_));
608 }
609 sub load_lparms {
610 0 ▶ my $self = shift;
Subroutine load_lparms: not called CC=1 SCAR=6.9
611 0 my $limit = shift;
612 0 $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 sub report {
624 0 ▶ my $self = shift;
Subroutine report: not called CC=2 SCAR=17.9
625 0 my $format = shift;
626 0 ▶ if (scalar @_) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 0 0 0
627 0 my $self = $self->dedupe (@_);
628 }
629 0 my $iter = $self->iter();
630 Iterator::Simple::Iterator->new(sub {
631 0 ▶ if (my $rec = $iter->()) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if (my $rec = &$iter()) { } 0 0 0
632 0 return sprintf ($format, @$rec);
633 } else {
634 0 return undef;
635 }
636 0 });
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 sub table_iter {
646 0 ▶ my $self = shift;
Subroutine table_iter: not called CC=2 SCAR=17.9
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 sub table {
655 0 ▶ my ($self, $limit) = @_;
Subroutine table: not called CC=1 SCAR=6.9
656 0 $self->table_iter($self->iter(), $limit);
657 }
658 sub table_parms {
659 0 ▶ my $self = shift;
Subroutine table_parms: not called CC=1 SCAR=6.9
660 0 $self->table_iter($self->iter(@_));
661 }
662 sub table_lparms {
663 0 ▶ my $self = shift;
Subroutine table_lparms: not called CC=1 SCAR=6.9
664 0 my $limit = shift;
665 0 $self->table_iter($self->iter(@_), $limit);
666 }
667  
668 package Iterator::Records::db;
669 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=2.6
670 use Iterator::Simple;
671 use Carp;
672 use vars qw(@ISA);
673 @ISA = qw(DBI::db);
674  
675 =head2 open ([filename])
676  
677 The C<open> method opens an SQLite database file. Opens an in-memory file if no filename is provided.
678  
679 =cut
680  
681 sub open {
682 my $class = shift;
683 my $file = shift || ':memory:';
684 my $dbh = DBI->connect('dbi:SQLite:dbname=' . $file);
685 bless($dbh, $class);
686 $dbh;
687 }
688  
689 sub open_dbh {
690 my $class = shift;
691 my $dbh = shift;
692 bless ($dbh, $class);
693 $dbh;
694 }
695  
696 =head2 connect(...)
697  
698 The C<connect> method is just the DBI connect method; we get it via inheritance.
699  
700 =head2 get (query, [parms])
701  
702 The C<get> method takes some SQL, executes it with the parameters passed in (if any), retrieves the first row, and returns
703 the value of the first field of that row.
704  
705 =cut
706  
707 sub get {
708 my $self = shift;
709 my $query = shift;
710 my $sth = $self->prepare($query);
711 $sth->execute(@_);
712 my $row = $sth->fetchrow_arrayref;
713 $row->[0];
714 }
715  
716 =head2 select
717  
718 The C<select> method retrieves an array of arrayrefs for the rows returned from the query.
719 In scalar mode, returns the arrayref from C<fetchall_arrayref>.
720  
721 =cut
722  
723 sub select {
724 my $self = shift;
725 my $query = shift;
726 return unless defined wantarray;
727 my $sth = $self->prepare($query);
728 $sth->execute(@_);
729 my $ret = $sth->fetchall_arrayref;
730 return wantarray ? @$ret : $ret;
731 }
732  
733 =head2 select_one
734  
735 The C<select_one> method runs a query and returns the first row as an arrayref.
736  
737 =cut
738  
739 sub select_one {
740 my $self = shift;
741 my $query = shift;
742 my $sth = $self->prepare($query);
743 $sth->execute(@_);
744 $sth->fetchrow_arrayref;
745 }
746  
747  
748 =head2 iterator (query, [parms), itparms (query, fields)
749  
750 This is the actual reason for putting this into the Iterator::Records namespace - given a query against the database, we return
751 an iterator factory for iterators over the rows of the query. Like C<select>, the basic C<iterator> call will assemble a query
752 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
753 that, when iterated, will return the query results. If iterated again, it will run a new query.
754  
755 If you want to have parameterized queries instead, use C<itparms>, then pass parameters to the factory it creates. In this case, since
756 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
757 you, though, in this case.)
758  
759 =cut
760  
761 # 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
762 # is called, it should return an iterator over *that instance*. But the next time, it has to create a new one.
763 # 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.
764 sub iterator {
765 my $self = shift;
766 my $query = shift;
767 my $sth = $self->prepare($query);
768 $sth->execute(@_);
769 my $names = $sth->{NAME};
770 my $first_time = 1;
771 my $factory = sub {
772 if ($first_time) {
773 $first_time = 0;
774 } else {
775 $sth = $self->prepare($query);
776 $sth->execute(@_);
777 }
778 sub {
779 $sth->fetchrow_arrayref;
780 }
781 };
782 Iterator::Records->new ($factory, $names);
783 }
784  
785 sub itparms {
786 my $self = shift;
787 my $query = shift;
788 my $fields = shift;
789 my $sth = $self->prepare($query);
790 $fields = $sth->{NAME} unless defined $fields;
791
792 my $factory = sub {
793 $sth->execute(@_);
794 sub {
795 $sth->fetchrow_arrayref;
796 }
797 };
798 Iterator::Records->new ($factory, $fields);
799 }
800  
801 =head2 insert
802  
803 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
804 row inserted is very database-specific, it may not work for your particular configuration.
805  
806 =cut
807  
808 sub insert {
809 my $self = shift;
810 my $query = shift;
811 my $sth = $self->prepare($query);
812 $sth->execute(@_);
813 $self->last_insert_id('', '', '', '');
814 }
815  
816 =head2 load_table (table, iterator), load_sql (insert query, iterator)
817  
818 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.
819 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
820 iterator that returns arrayrefs; if given the latter it will simply pass them to the execute call.
821  
822 Each returns the number of rows inserted.
823  
824 =cut
825  
826 sub load_table {
827 my ($self, $table, $iterator) = @_;
828 my $fields = $iterator->fields();
829 my @inserts = map { '?' } @$fields;
830 my $sql = "insert into $table values (" . join (', ', @inserts) . ')';
831 $self->load_sql ($sql, $iterator->iter()); # TODO: an error in our SQL will show this line. Do better.
832 }
833  
834 sub load_sql {
835 my ($self, $query, $iterator) = @_;
836 croak "Source for bulk load not iterable" unless Iterator::Simple::is_iterable($iterator);
837 my $iter = Iterator::Simple::iter($iterator);
838 my $sth = $self->prepare($query);
839 my $count = 0;
840 while (my $rec = $iter->()) {
841 $count += 1;
842 $sth->execute(@$rec);
843 }
844 $count;
845 }
846  
847 =head2 do
848  
849 The C<do> command works a little differently from the standard API; DBI's version wants a hashref of attributes that I never use
850 and regularly screw up.
851  
852 =cut
853  
854 sub do {
855 my $self = shift;
856 my $query = shift;
857 my $sth = $self->prepare($query);
858 $sth->execute(@_);
859 }
860  
861 package Iterator::Records::st;
862 use vars qw(@ISA);
863 @ISA = qw(DBI::st);
864  
865 # We don't actually have anything to override in the statement, but it has to be defined or the DBI machinery won't work.
866  
867  
868 =head1 AUTHOR
869  
870 Michael Roberts, C<< <michael at cpan.org> >>
871  
872 =head1 BUGS
873  
874 Please report any bugs or feature requests to C<bug-Iterator-Records at rt.cpan.org>, or through
875 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Iterator-Records>. I will be notified, and then you'll
876 automatically be notified of progress on your bug as I make changes.
877  
878  
879  
880  
881 =head1 SUPPORT
882  
883 You can find documentation for this module with the perldoc command.
884  
885 perldoc Iterator::Records
886  
887  
888 You can also look for information at:
889  
890 =over 4
891  
892 =item * RT: CPAN's request tracker (report bugs here)
893  
894 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Iterator-Records>
895  
896 =item * AnnoCPAN: Annotated CPAN documentation
897  
898 L<http://annocpan.org/dist/Iterator-Records>
899  
900 =item * CPAN Ratings
901  
902 L<http://cpanratings.perl.org/d/Iterator-Records>
903  
904 =item * Search CPAN
905  
906 L<http://search.cpan.org/dist/Iterator-Records/>
907  
908 =back
909  
910  
911 =head1 ACKNOWLEDGEMENTS
912  
913  
914 =head1 LICENSE AND COPYRIGHT
915  
916 Copyright 2015 Michael Roberts.
917  
918 This program is free software; you can redistribute it and/or modify it
919 under the terms of the the Artistic License (2.0). You may obtain a
920 copy of the full license at:
921  
922 L<http://www.perlfoundation.org/artistic_license_2_0>
923  
924 Any use, modification, and distribution of the Standard or Modified
925 Versions is governed by this Artistic License. By using, modifying or
926 distributing the Package, you accept this license. Do not use, modify,
927 or distribute the Package, if you do not accept this license.
928  
929 If your Modified Version has been derived from a Modified Version made
930 by someone other than you, you are nevertheless required to ensure that
931 your Modified Version complies with the requirements of this license.
932  
933 This license does not grant you the right to use any trademark, service
934 mark, tradename, or logo of the Copyright Holder.
935  
936 This license includes the non-exclusive, worldwide, free-of-charge
937 patent license to make, have made, use, offer to sell, sell, import and
938 otherwise transfer the Package with respect to any patent claims
939 licensable by the Copyright Holder that are necessarily infringed by the
940 Package. If you institute patent litigation (including a cross-claim or
941 counterclaim) against any party alleging that the Package constitutes
942 direct or contributory patent infringement, then this Artistic License
943 to you shall terminate on the date that such litigation is filed.
944  
945 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
946 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
947 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
948 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
949 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
950 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
951 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
952 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
953  
954  
955 =cut
956  
957 1; # End of Iterator::Records
↑ Summary