blib/lib/DBIx/PivotQuery.pm

filter: Statementstmt 85.7% 120 / 140 Branchbran 72.5% 29 / 40 Conditioncond 72.4% 21 / 29 MC/DCmcdc 52.9% 9 / 17 Subroutinesub 85.7% 12 / 14 Podpod 60.0% 3 / 5 totaltotal 79.1% 194 / 245 CC 40 SCAR 26.1
CC
40
Cov
81%
partial_order
30.0
pivot_list
18.7
pivot_by
14.4
CRAP 13.7
↑ Summary
1 package DBIx::PivotQuery;
2 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 4 ▶use Filter::signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use vars '$VERSION';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 $VERSION = '0.01';
11  
12 4 ▶use vars qw(@EXPORT_OK);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 @EXPORT_OK = qw(pivot_by pivot_list pivot_sql);
14  
15 =head1 NAME
16  
17 DBIx::PivotQuery - create pivot tables from queries
18  
19 =head1 SYNOPSIS
20  
21 use DBIx::PivotQuery 'pivot_by';
22 my $rows = pivot_by(
23 dbh => $dbh,
24 columns => ['month'],
25 rows => ['region'],
26 aggregate => ['sum(amount) as amount'],
27 sql => <<'SQL');
28 select
29 month(date) as report_month
30 , region
31 , amount
32 from mytable
33 SQL
34  
35 The above code returns a data structure roughly like
36  
37 # [
38 # ['region','1','2',...,'11','12'],
39 # ['East', 0, 0 ,..., 10, 20 ],
40 # ['North', 0, 1 ,..., 10, 20 ],
41 # ['South', 0, 3 ,..., 10, 5 ],
42 # ['West', 0, 6 ,..., 8, 20 ],
43 # ]
44  
45 =head1 FUNCTIONS
46  
47 # This should maybe return a duck-type statement handle so that people
48 # can fetch row-by-row to their hearts content
49 # row-by-row still means we need to know all values for the column key :-/
50  
51 =head2 C<< pivot_by >>
52  
53 my $l = pivot_by(
54 dbh => $test_dbh,
55 rows => ['region'],
56 columns => ['date'],
57 aggregate => ['sum(amount) as amount'],
58 placeholder_values => [],
59 subtotals => 1,
60 sql => <<'SQL',
61 select
62 region
63 , "date"
64 , amount
65 , customer
66 from mytable
67 SQL
68 );
69  
70 Transforms the SQL given and returns an AoA pivot table according to
71 C<rows>, C<columns> and C<aggregate>.
72  
73 The last word (<c>\w+</c>) of each element of C<aggregate> will be used as the
74 aggregate column name unless C<aggregate_columns> is given.
75  
76 Supplying C<undef> for a column name in C<rows> will create an empty cell
77 in that place. This is convenient when creating subtotals.
78  
79 =head3 Options
80  
81 =over 4
82  
83 =item B<headers>
84  
85 headers => 1,
86  
87 Whether to include the headers as the first row
88  
89 =back
90  
91 Subtotals are calculated by repeatedly running the query. For optimization, you
92 could first select the relevant (aggregated)
93 rows into a temporary table and then create the subtotals from that temporary
94 table if query performance is an issue:
95  
96 select foo, sum(bar) as bar, baz
97 into #tmp_query
98 from mytable
99 where year = ?
100  
101 select foo, bar, baz from #tmp_query
102  
103 =cut
104  
105 5 ▶sub pivot_by( %options ) {
Subroutine pivot_by: called CC=14 SCAR=26.7
Pod documented
106 croak "Need an SQL string in option 'sql'"
107 5 ▶ unless $options{sql};
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"sql"} 0 5 5
108 croak "Need a database handle in option 'dbh'"
109 5 ▶ unless $options{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"dbh"} 0 5 5
110 5 ▶ $options{ placeholder_values } ||= [];
Condition50%1/2
$options{"placeholder_values"} ||= []
l!l
50
MC/DC0%0/1
$options{"placeholder_values"} ||= []
$options{"placeholder_values"}
Truth table50%1/2
A
A= $options{"placeholder_values"}
Aresult
11
00
111 5 ▶ $options{ rows } ||= [];
Condition50%1/2
$options{"rows"} ||= []
l!l
50
MC/DC0%0/1
$options{"rows"} ||= []
$options{"rows"}
Truth table50%1/2
A
A= $options{"rows"}
Aresult
11
00
112  
113 5 ▶ if( $options{ subtotals } and ! ref $options{ subtotals }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"subtotals"} and not ref $options{"subtotals"}) 1 4 5
Condition66%2/3
$options{"subtotals"} and not ref $options{"subtotals"}
!ll&&!rl&&r
401
MC/DC50%1/2
$options{"subtotals"} and not ref $options{"subtotals"}
$options{"subtotals"} not ref $options{"subtotals"}
Truth table66%2/3
A and not(B)
A= $options{"subtotals"}B= not ref $options{"subtotals"}
ABresult
0X0
100
111
114 1 $options{ subtotals } = [@{ $options{rows}}];
115 };
116  
117 5 my $subtotals = delete $options{ subtotals };
118  
119 5 my $result = simple_pivot_by( %options );
120  
121 5 ▶ if( $subtotals ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subtotals) 1 4 5
122 1 for my $i ( reverse 0..$#$subtotals ) {
123 2 $subtotals->[$i] = undef;
124 2 my $s = simple_pivot_by(
125 %options,
126 rows => $subtotals,
127 headers => 0
128 );
129  
130 # Now splice our subtotals into the list
131 # Wherever the subtotals key changes, insert the subtotal
132 2 ▶ my $p = $options{ headers } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$options{'headers'} ? : 2 0 2
133 2 my $last;
134 2 ▶ while( @$s and $p < @$result ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$s and $p < @$result) 14 2 16
Condition66%2/3
@$s and $p < @$result
!ll&&!rl&&r
0214
MC/DC50%1/2
@$s and $p < @$result
@$s $p < @$result
Truth table66%2/3
A and B
A= @$sB= $p < @$result
ABresult
0X0
100
111
135 14 my $curr = join "\0", @{ $result->[$p] }[0..$i-1];
136 14 ▶ $last ||= $curr;
Condition100%3/3
$last ||= $curr
l!l&&r!l&&!r
419
MC/DC100%2/2
$last ||= $curr
$last $curr
Truth table100%3/3
A ||= B
A= $lastB= $curr
ABresult
1X1
011
000
137 14 ▶ if( $last ne $curr ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last ne $curr) 3 11 14
138 3 splice @$result, $p, 0, shift @$s;
139 3 $p++;
140 3 $last = join "\0", @{ $result->[$p] }[0..$i-1];
141 };
142 14 $p++;
143 };
144  
145 # Whatever remains will just be appended
146 2 push @$result, @$s;
147 };
148 };
149  
150 5 $result;
151 }
152  
153 7 ▶sub simple_pivot_by( %options ) {
Subroutine simple_pivot_by: called CC=3 SCAR=11.4
Pod undocumented
154 7 my $sql = pivot_sql( %options );
155 7 my $sth = $options{ dbh }->prepare( $sql );
156 7 $sth->execute( @{$options{ placeholder_values }} );
157 7 my $rows = $sth->fetchall_arrayref({});
158 7 my @aggregate_columns;
159 7 ▶ if( exists $options{ aggregate_columns }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{'aggregate_columns'}) { } 0 7 7
160 0 @aggregate_columns = @{ $options{ aggregate_columns }};
161 } else {
162 7 ▶ @aggregate_columns = map {/(\w+)\w*$/ ? $1 : $_ } @{ $options{ aggregate }};
Branch: 1 branch
BranchTrueFalseTotal
/(\w+)\w*$/ ? : 7 0 7
163 };
164 7 pivot_list( %options, aggregate => \@aggregate_columns, list => $rows );
165 }
166  
167 # Takes an AoA and derives the total order from it if possible
168 # Returns the total order of the keys. Not every key is expected to be available
169 # in every row
170 0 ▶sub partial_order( $comparator, $keygen, @list ) {
Subroutine partial_order: not called CC=5 SCAR=34.0
Pod undocumented
171 0 my %sort;
172 my %keys;
173  
174 0 for my $row (@list) {
175 0 my $last_key;
176 0 for my $col (@$row) {
177 # This approach doesn't have the transitive property
178 # We need to place items in arrays resp. on a float lattice
179 # $sort{ $item } = (max( $sort_after($item ) - min( $sort_before($item)) / 2
180 0 my $key = $keygen->( $col );
181 0 $keys{ $key } = 1;
182 0 ▶ if( defined $last_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $last_key) { } 0 0 0
183 0 for my $cmp (["$last_key\0$key",-1],
184 ["$key\0$last_key",1],
185 ) {
186 0 my ($k,$v) = @$cmp;
187 0 $sort{$k} = $v;
188 }
189 } else {
190 0 $last_key = $key;
191 };
192 }
193 }
194  
195 0 sort { $sort{ $a } <=> $sort{$b} } keys %keys;
196 }
197  
198 # Pivots an AoH (no AoA support yet!?)
199 # The list must already be sorted by @rows, @columns
200 # At least one line must contain all column values (!)
201  
202 =head2 C<< pivot_list >>
203  
204 my $l = pivot_list(
205 list => @AoH,
206 columns => ['date'],
207 rows => ['region'],
208 aggregate => ['amount'],
209 );
210  
211 The rows of C<@$l> are then plain arrays not hashes.
212 The first row of C<@$l> will contain the column titles.
213  
214 The column titles are built from joining the pivot column values by C<$;> .
215  
216 =over 4
217  
218 =item B<headers>
219  
220 headers => 1,
221  
222 Whether to include the headers as the first row
223  
224 =back
225  
226 =cut
227  
228 10 ▶sub pivot_list( %options ) {
Subroutine pivot_list: called CC=18 SCAR=29.3
Pod documented
229 10 my @rows;
230 my %colnum;
231 10 my %rownum;
232  
233 10 ▶ if( ! exists $options{ headers }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options{"headers"}) 6 4 10
234 6 $options{ headers } = 1;
235 };
236  
237 10 ▶ my @key_cols = @{ $options{ columns } || [] };
Condition100%2/2
$options{'columns'} || []
l!l
91
MC/DC100%1/1
$options{'columns'} || []
$options{'columns'}
Truth table100%2/2
A
A= $options{'columns'}
Aresult
11
00
238 10 ▶ my @key_rows = @{ $options{ rows } || [] };
Condition100%2/2
$options{'rows'} || []
l!l
91
MC/DC100%1/1
$options{'rows'} || []
$options{'rows'}
Truth table100%2/2
A
A= $options{'rows'}
Aresult
11
00
239 10 ▶ my @aggregates = @{ $options{ aggregate } || [] };
Condition50%1/2
$options{'aggregate'} || []
l!l
100
MC/DC0%0/1
$options{'aggregate'} || []
$options{'aggregate'}
Truth table50%1/2
A
A= $options{'aggregate'}
Aresult
11
00
240 10 my @colhead;
241  
242 # Now we need to determine the numbers for all the columns
243 10 ▶ if( $options{ sort_columns } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'sort_columns'}) { } 0 10 10
244 # If we have a user-supplied sorting function, use that:
245 0 ▶ @colnum{ sort( sub { $options{ sort_columns }->($a,$b) }, keys %colnum )}
Subroutine __ANON__: not called CC=1 SCAR=6.9
246 = (@key_rows)..((@key_rows)+(keys %colnum)-1);
247 0 for( keys %colnum ) {
248 0 $colhead[ $colnum{ $_ }] = $_;
249 };
250 } else {
251 # We assume that the first row contains all columns in order.
252 # Following lines may skip values or have additional columns which
253 # will be appended. This could be smarter by introducing a partial
254 # order in the hope that everything will work out in the end.
255 10 my $col = @key_rows;
256 10 for my $cell (@{ $options{ list }}) {
257 147 my $colkey = join $;, @{ $cell }{ @key_cols };
258 147 ▶ if( ! exists $colnum{ $colkey }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $colnum{$colkey}) 48 99 147
259 48 ▶ $colnum{ $colkey } ||= $col++;
Condition66%2/3
$colnum{$colkey} ||= $col++
l!l&&r!l&&!r
0471
MC/DC50%1/2
$colnum{$colkey} ||= $col++
$colnum{$colkey} $col++
Truth table66%2/3
A ||= B
A= $colnum{$colkey}B= $col++
ABresult
1X1
011
000
260 48 push @colhead, $colkey;
261 };
262 };
263 }
264  
265 10 my @effective_key_rows = grep { defined $_ } @key_rows; # remove placeholders
266  
267 10 ▶ if( ! @colhead) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@colhead) 0 10 10
268 0 @colhead = $aggregates[0];
269 };
270  
271 10 my $last_row;
272 my @row;
273 10 for my $cell (@{ $options{ list }}) {
274 147 my $colkey = join $;, @{ $cell }{ @key_cols };
275 147 my $rowkey = join $;, @{ $cell }{ @effective_key_rows };
276  
277 147 ▶ if( defined $last_row and $rowkey ne $last_row ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $last_row and $rowkey ne $last_row) 37 110 147
Condition100%3/3
defined $last_row and $rowkey ne $last_row
!ll&&!rl&&r
1010037
MC/DC100%2/2
defined $last_row and $rowkey ne $last_row
defined $last_row $rowkey ne $last_row
Truth table100%3/3
A and B
A= defined $last_rowB= $rowkey ne $last_row
ABresult
0X0
100
111
278 37 push @rows, [splice @row, 0];
279 };
280  
281 # We should have %row instead, but how to name the
282 # columns and rows that are values now?!
283 # prefix "pivot_" ?
284 # Allow the user to supply names?
285 # Expect the user to rename the keys?
286 147 ▶ if( ! @row ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@row) 47 100 147
287 47 ▶ @row = map { defined $_ ? $cell->{$_} : undef } @key_rows;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 70 10 80
288 };
289  
290 147 my %cellv = %$cell;
291 147 @cellv{ @aggregates } = @{$cell}{@aggregates};
292 #$row[ $colnum{ $colkey }] = \%cellv;
293 147 $row[ $colnum{ $colkey }] = $cell->{ $aggregates[0] };
294 147 $last_row = $rowkey;
295 };
296 10 ▶ if(@row) {
Branch: 1 branch
BranchTrueFalseTotal
if (@row) 10 0 10
297 10 push @rows, \@row;
298 };
299  
300 unshift @rows, [ @key_rows, @colhead ]
301 10 ▶ if $options{ headers };
Branch: 1 branch
BranchTrueFalseTotal
if $options{"headers"} 7 3 10
302  
303 \@rows
304 10 }
305  
306 =head2 C<< pivot_sql >>
307  
308 pivot_sql(
309 columns => ['date'],
310 rows => ['region'],
311 aggregate => ['sum(amount) as amount'],
312 sql => <<'SQL' );
313 select
314 "date"
315 , region
316 , amount
317 from mytable
318 SQL
319  
320 Creates SQL around a subselect that aggregates the given
321 columns.
322  
323 The SQL created by the call above would be
324  
325 select "region"
326 , "date"
327 , sum(amount) as amount
328 from (
329 select
330 "date"
331 , region
332 , amount
333 from mytable
334 ) foo
335 group by "region, "date"
336 order by "region", "date"
337  
338 Note that the values in the C<columns> and C<rows> options will be automatically
339 enclosed in double quotes.
340  
341 This function is convenient if you want to ccreate ad-hoc pivot queries instead
342 of setting up the appropriate views in the database.
343  
344 If you want to produce subtotals, this function can be called
345 with the elements removed successively from C<$options{rows}> or
346 C<$options{columns}> for computing row or column totals.
347  
348 =cut
349  
350 8 ▶sub pivot_sql( %options ) {
Subroutine pivot_sql: called CC=4 SCAR=14.1
Pod documented
351 8 ▶ my @columns = (grep { defined $_ } @{ $options{ rows } || [] }, @{ $options{ columns } || []});
Condition50%2/4
$options{'rows'} || []
l!l
80
$options{'columns'} || []
l!l
80
MC/DC0%0/1
$options{'rows'} || []
$options{'rows'}
MC/DC0%0/1
$options{'columns'} || []
$options{'columns'}
Truth table50%1/2
A
A= $options{'rows'}
Aresult
11
00
Truth table50%1/2
A
A= $options{'columns'}
Aresult
11
00
352 8 my $qcolumns = join "\n , ", @columns, @{ $options{ aggregate }};
353 8 my $keycolumns = join "\n , ", @columns;
354 8 my $clauses = '';
355 8 ▶ if($keycolumns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keycolumns) 8 0 8
356 8 $clauses = join "\n",
357 "group by $keycolumns",
358 "order by $keycolumns",
359 };
360  
361 return <<SQL
362 select
363 $qcolumns
364 from (
365 $options{sql}
366 ) foo
367 $clauses
368 SQL
369 8 }
370 4 1;
371  
372 =head1 Unsupported features
373  
374 Currently only one aggregate value is allowed.
375  
376 Row aggregates ("totals") are not supported yet. Row aggregates will
377 mean heavy rewriting of the SQL to wrap the aggregate function over the column
378 names of the query.
379  
380 =head1 SEE ALSO
381  
382 L<DBI>
383  
384 =head1 REPOSITORY
385  
386 The public repository of this module is
387 L<http://github.com/Corion/DBIx-PivotQuery>.
388  
389 =head1 SUPPORT
390  
391 The public support forum of this module is
392 L<https://perlmonks.org/>.
393  
394 =head1 BUG TRACKER
395  
396 Please report bugs in this module via the RT CPAN bug queue at
397 L<https://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-PivotQuery>
398 or via mail to L<dbix-pivotquery-Bugs@rt.cpan.org>.
399  
400 =head1 AUTHOR
401  
402 Max Maischein C<corion@cpan.org>
403  
404 =head1 COPYRIGHT (c)
405  
406 Copyright 2017 by Max Maischein C<corion@cpan.org>.
407  
408 =head1 LICENSE
409  
410 This module is released under the same terms as Perl itself.
411  
412 =cut
↑ Summary