blib/lib/DBIx/Report/Excel.pm

filter: Statementstmt 100% 98 / 98 Branchbran 75.0% 15 / 20 Conditioncond 66.6% 6 / 9 MC/DCmcdc 20.0% 1 / 5 Subroutinesub 100% 16 / 16 Podpod 100% 5 / 5 totaltotal 92.1% 141 / 153 CC 17 SCAR 10.7
CC
17
Cov
94%
write
5.2
__parse_comments
4.0
__page_name
4.0
CRAP 2.9
↑ Summary
1 package DBIx::Report::Excel;
2  
3 2 ▶use 5.008008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 our $VERSION = '0.4';
8  
9 =head1 NAME
10  
11 DBIx::Report::Excel - creating Excel reports from SQL statements
12  
13 =head1 SYNOPSIS
14  
15 use DBIx::Report::Excel;
16 my $report = DBIx::Report::Excel->new (
17 "SQLite.xls",
18 sql => 'SELECT first_n, last_n FROM people',
19 dbh => DBI->connect("dbi:SQLite:dbname=testdb","","")
20 );
21 $report->write();
22 $report->close();
23  
24  
25 =head1 DESCRIPTION
26  
27 DBIx::Report::Excel's goal is to make creating reports in Excel from
28 databases easy. It's aimed at SQL developers and/or DBA's who don't
29 know much about Perl programming. I.e. most of the information needed
30 to create Excel file is provided directly in SQL statement (script)
31 itself.
32  
33 If SQL script contains multiple statements, resulting Excel file is
34 formatted as multi-page spreadsheet with each result set on it's own
35 worksheet.
36  
37 =head2 FORMATTING EXCEL WORKSHEETS
38  
39 =head3 COLUMNS
40  
41 B<Column names> on each worksheet are defined from table column names
42 or aliases provided by 'AS' directive in SQL statement.
43  
44 Excel column names are defined from parsing of SQL statement, not from
45 actual name of columns in table(s). If SQL staements does not
46 explicitly have column names or aliases listed (as for example, in
47 case of SELECT * query), Excel columns will have generic names
48 'Column+<number>'. See L<EXAMPLES> below
49  
50  
51 =head3 EMBEDDING YAML IN SQL COMMENT BLOCK
52  
53 All additional directives for formatting Excel output are provided as
54 YAML structure, embedded in SQL comment blocks. Supported comment style
55 is C-style 'slash and asterisk' (C</* ... */>) comments. ANSI 'double
56 hyphen' (C<-- ...>) comment style is not supported in this version.
57  
58 Slash and asterisk C-style (C</* ... */>) includes multi-line
59 comment blocks conforming to YAML specifications.
60  
61 YAML statements embedded in multiline comment block must start from
62 the beginning of each new line. All spaces are significant during YAML
63 processing. Statement indentation must correspond to YAML
64 specifications.
65  
66  
67 YAML directives must have separators C<---> at start and at the
68 end. Seaparator can be written either on the same line with commetn
69 start/end or on its own line. Extra spaces between comment start/end
70 and separator are ignored if separator is written on the same
71 line. (See EXAMPLES 3 and 4 below).
72  
73  
74 =head3 COMMENTS INSIDE YAML BLOCK
75  
76 To isolate actual comments from YAML processing, use YAML comments
77 (lines starting with hash symbol C<#>) inside SQL comment blocks:-
78  
79 /*
80 # This comment is not processed by YAML parser.
81 ---
82 title: My Worksheet Name
83 ---
84 */
85  
86 =head3 YAML KEYWORDS
87  
88 =head4 title:
89  
90 Only one keyword is suported in this version: 'title'. It defines
91 Excel worksheet name. If no workshet name is provided, then worksheet
92 is created with generic name 'Sheet+<number>'.
93  
94 =cut
95  
96 =head1 DEPENDENCIES
97  
98 This module uses following Perl modules:
99  
100 Data::Tabular::Dumper
101 Data::Tabular::Dumper::Excel
102 SQL::Parser
103 SQL::Script
104 YAML
105  
106 =cut
107  
108 # --------------------------------------------------------------------------------
109 2 ▶use Data::Tabular::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
110 2 ▶use Data::Tabular::Dumper::Excel;
Subroutine BEGIN: called CC=1 SCAR=0.0
111 2 ▶use SQL::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
112 2 ▶use SQL::Script;
Subroutine BEGIN: called CC=1 SCAR=0.0
113 2 ▶use YAML;
Subroutine BEGIN: called CC=1 SCAR=0.0
114 # --------------------------------------------------------------------------------
115  
116 2 require Exporter;
117  
118 2 our @ISA = qw(Exporter);
119  
120 =head2 EXPORT
121  
122 None.
123  
124 =cut
125  
126 2 our @EXPORT = qw( &write );
127  
128 =head1 METHODS
129  
130 =head2 new()
131  
132 use DBIx::Report::Excel;
133  
134 my $report = DBIx::Report::Excel->new( "Excel.xls" );
135  
136 Method new() creates new instance of Excel report object. It takes one
137 required parameter- output Excel file name, and two optitonal parameters:
138 database connection handler (dbh) and SQL query text (sql):
139  
140 my $report = DBIx::Report::Excel->new(
141 "Excel.xls",
142 dbh => DBI->connect("dbi:SQLite:dbname=testdb","",""),
143 sql => 'SELECT * FROM names',
144 );
145  
146 =cut
147  
148 1 ▶sub new {
Subroutine new: called CC=3 SCAR=11.1
Pod documented
149 1 my $type = shift;
150 1 my $self = {};
151 1 my ($filename, %params) = @_;
152 1 $self->{'filename'} = $filename;
153 1 $self->{'excel'} = Data::Tabular::Dumper->open (Excel => [ $self->{'filename'} ] );
154 1 ▶ $self->{'dbh'} = $params{'dbh'} || undef; # DB handler
Condition50%1/2
$params{'dbh'} || undef
l!l
01
MC/DC0%0/1
$params{'dbh'} || undef
$params{'dbh'}
Truth table50%1/2
A
A= $params{'dbh'}
Aresult
11
00
155 1 ▶ $self->{'sql'} = $params{'sql'} || undef; # SQL text
Condition50%1/2
$params{'sql'} || undef
l!l
01
MC/DC0%0/1
$params{'sql'} || undef
$params{'sql'}
Truth table50%1/2
A
A= $params{'sql'}
Aresult
11
00
156 1 $self->{'worksheet'} = 0;
157 1 $self->{'worksheets'} = undef; # List of all crated worksheets
158 1 bless $self, $type;
159 }
160 # --------------------------------------------------------------------------------
161  
162  
163 =head2 dbh()
164  
165 $report->dbh(
166 DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;options=$options",
167 $username,
168 $password,
169 {AutoCommit => 0, RaiseError => 1, PrintError => 0}
170 )
171 );
172  
173 Sets database handler if it was not set by new() method. It also gives
174 ability to change Db connection on the fly to query different
175 databases in one report.
176  
177 =cut
178  
179 5 ▶sub dbh {
Subroutine dbh: called CC=2 SCAR=6.9
Pod documented
180 5 my $self = shift;
181 5 ▶ if (@_) { $self->{dbh} = shift }
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 4 5
182 5 return $self->{dbh};
183 }
184  
185 =head2 sql()
186  
187 Defines SQL query for the report. Can contain either single SQL
188 statement or multiple queris separated by semicolon followed by a new line
189 (C<;\s*\n>). Each separate query will produce its own workseet in multipage
190 Excel workbook.
191  
192 An example:
193  
194 $report->sql(
195 qq{
196 /*---
197 title: People Names
198 ---*/
199  
200 SELECT first_name as "First Name",
201 last_name as "Family name"
202 FROM people
203  
204 });
205  
206 =cut
207  
208 5 ▶sub sql {
Subroutine sql: called CC=2 SCAR=6.9
Pod documented
209 5 my $self = shift;
210 5 ▶ if (@_) { $self->{sql} = shift }
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 4 5
211 5 return $self->{sql};
212 }
213 # --------------------------------------------------------------------------------
214  
215 =head2 write()
216  
217 Creates and writes new Excel worksheet for each SQL query (or multiple
218 worksheets when several SQL queries, joined by C<;\n>).
219  
220 Can accept one optional parameter: SQL statement string.
221  
222 An example:
223  
224 $report->sql("SELECT first_name, last_name FROM people");
225 $report->write();
226  
227 $report->write("SELECT f_name, color from fruits");
228  
229 =cut
230  
231 4 ▶sub write {
Subroutine write: called CC=5 SCAR=16.4
Pod documented
232 4 my $self = shift;
233  
234 4 ▶ carp::croak("Database handler is not defined. Can not run query.")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->dbh 0 4 4
235 unless $self->dbh();
236  
237 4 ▶ $self->{'sql'} = shift || $self->{'sql'};
Condition66%2/3
shift() || $self->{'sql'}
l!l&&r!l&&!r
310
MC/DC0%0/2
shift() || $self->{'sql'}
shift() $self->{'sql'}
Truth table66%2/3
A || B
A= shift()B= $self->{'sql'}
ABresult
1X1
011
000
238  
239 4 ▶ carp::croak("Can not run query: you doid not give me any SQL query text.")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->sql 0 4 4
240 unless $self->sql();
241  
242 # Split SQL into separate statements
243 4 my $statements = SQL::Script->new( split_by => qr/;\s*\n/ );
244  
245 4 for my $sql ( @{$statements->split_sql(\$self->{'sql'})} ) {
246 5 $self->{'data'} = $self->__new_page($sql);
247 }
248  
249 4 return $self->{'data'};
250 }
251  
252 =head2 close()
253  
254 Cleanly close Excel file.
255  
256 =cut
257  
258 1 ▶sub close {
Subroutine close: called CC=1 SCAR=0.0
Pod documented
259 1 my $self = shift;
260 1 $self->{'excel'}->close();
261 }
262 # --------------------------------------------------------------------------------
263  
264 =head1 PRIVATE METHODS
265  
266 =head3 __new_page()
267  
268 Adds new workseet to Excel workbook. This method is called for each
269 separate SQL SELECT statement by write(). If SQL script passed to
270 write(0 contains several SQL statements, then __new_page() is called
271 for each of them.
272  
273 =cut
274  
275 5 ▶sub __new_page {
Subroutine __new_page: called CC=3 SCAR=11.0
276 5 my $self = shift;
277 5 my ($sql) = shift;
278  
279 5 my $page_name = $self->__page_name(__parse_comments($sql));
280 5 $self->{'excel'}->page_start( $page_name );
281  
282 5 $self->{'data'} = $self->{'dbh'}->selectall_arrayref($sql);
283  
284 5 ▶ return unless scalar @{ $self->{ data } };
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$self->{"data"};} 0 5 5
285  
286 # ----------------------------------------
287 # Define column names.
288 5 my $parser = SQL::Parser->new();
289 5 $parser->parse($sql);
290  
291 5 ▶ if ( scalar @{$parser->structure->{'column_defs'}} == scalar @{$self->{'data'}->[0]} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$parser->structure->{'column_defs'};} == scalar @{$self->{'data'}[0];}) { } 3 2 5
292 # i.e. column number in SQL statement
293 # same as number of actually selected
294 # columns (it's not "SELECT *")
295 3 $self->{'excel'}->fields($parser->structure->{'org_col_names'});
296 } else { # i.e. SELECT *
297 2 $self->{'excel'}->fields( [map {"Column" . $_} (1..scalar @{$self->{'data'}->[0]})])
298 }
299  
300 5 $self->{'excel'}->dump( $self->{'data'} );
301 5 return $self->{'data'};
302 }
303 # --------------------------------------------------------------------------------
304  
305 =head3 __page_name()
306  
307 Get a worksheet name from SQL. Parses YAML structure embedded in SQL
308 comment block. If no such thig provided worksheet will have name
309 'Sheet+<number>'.
310  
311 =cut
312  
313 5 ▶sub __page_name {
Subroutine __page_name: called CC=4 SCAR=13.9
314 5 my $self = shift;
315 5 my ($yaml) = @_;
316  
317 5 ▶ my $page_name = $yaml->{'title'} || "Sheet" . $self->{'worksheet'};
Condition100%2/2
$yaml->{'title'} || 'Sheet' . $self->{'worksheet'}
l!l
32
MC/DC100%1/1
$yaml->{'title'} || 'Sheet' . $self->{'worksheet'}
$yaml->{'title'}
Truth table100%2/2
A
A= $yaml->{'title'}
Aresult
11
00
318  
319 5 ▶ if ( $self->{'worksheets'} ) { # if worksheet with this name exists
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"worksheets"}) 4 1 5
320 # already, give new sheet generic
321 # name
322 $page_name = "Sheet" . $self->{'worksheet'}
323 4 ▶ if scalar (grep {/^$page_name$/} @{$self->{'worksheets'}}) == 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar grep({/^$page_name$/;} @{$$self{"worksheets"};}) == 1 0 4 4
324 }
325  
326 5 $self->{'worksheet'}++;
327 5 push @{$self->{'worksheets'}}, $page_name;
328  
329 5 return $page_name;
330 }
331 # --------------------------------------------------------------------------------
332  
333 =head3 __parse_comments()
334  
335 Extract all comments from SQL statement and parses them with YAML
336 parser. Returns parsed hash.
337  
338 =cut
339  
340 5 ▶sub __parse_comments {
Subroutine __parse_comments: called CC=4 SCAR=13.9
341 5 my ($text) = @_;
342 5 my @lines = split /\n+/, $text;
343 5 my @comments;
344 5 my $comment_block = undef;
345 LINES:
346 5 for (@lines) {
347 # push @comments, $1, next LINES if /^\s*-- (.*)$/; # -- ... TODO
348 18 ▶ push @comments, $1, next LINES if /^\s*\/\* (.*)\*\/\s*$/; # /* ...*/
Branch: 1 branch
BranchTrueFalseTotal
if m[^\s*/\* (.*)\*/\s*$] 0 18 18
349 18 ▶ if (/\/\*/../\*\//) {
Branch: 1 branch
BranchTrueFalseTotal
if (m[/\*] .. m[\*/]) 13 5 18
350 13 s/(\/\*+\s*)//;
351 13 s/(\s*\*+\/)//;
352 13 push @comments, $_;
353 }
354 }
355 5 push @comments, "\n\n";
356 5 return YAML::Load(join "\n", @comments);
357 }
358 # --------------------------------------------------------------------------------
359  
360 2 1;
361 __END__
↑ Summary