| 1 | package HTML::ReportWriter; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use DBI; | ||
| 5 | use CGI; | ||
| 6 | use HTML::ReportWriter::PagingAndSorting; | ||
| 7 | |||
| 8 | our $VERSION = '1.5.1'; | ||
| 9 | |||
| 10 | =head1 NAME | ||
| 11 | |||
| 12 | HTML::ReportWriter - Simple OO interface to generate pageable, sortable HTML tabular reports | ||
| 13 | |||
| 14 | =head1 SYNOPSIS | ||
| 15 | |||
| 16 | #!/usr/bin/perl -w | ||
| 17 | |||
| 18 | use strict; | ||
| 19 | use HTML::ReportWriter; | ||
| 20 | use CGI; | ||
| 21 | use Template; | ||
| 22 | use DBI; | ||
| 23 | |||
| 24 | my $dbh = DBI->connect('DBI:mysql:foo', 'bar', 'baz'); | ||
| 25 | |||
| 26 | # The simplest possible method of calling RW... | ||
| 27 | my $report = HTML::ReportWriter->new({ | ||
| 28 | DBH => $dbh, | ||
| 29 | DEFAULT_SORT => 'name', | ||
| 30 | SQL_FRAGMENT => 'FROM person AS p, addresses AS a WHERE a.person_id = p.id', | ||
| 31 | COLUMNS => [ 'name', 'address1', 'address2', 'city', 'state', 'zip' ], | ||
| 32 | }); | ||
| 33 | |||
| 34 | $report->draw(); | ||
| 35 | |||
| 36 | =head1 DESCRIPTION | ||
| 37 | |||
| 38 | This module generates an HTML tabular report. The first row of the table is the header, | ||
| 39 | which will contain column names, and if the columns are sortable, the name will link back | ||
| 40 | to the cgi, and will allow for changing of the sort. Below the table of results is a paging | ||
| 41 | table, which shows the current page, along with I<n> other pages of the total result set, | ||
| 42 | and includes links to the first, previous, next and last pages in the result set. | ||
| 43 | |||
| 44 | HTML::Reportwriter also supports column grouping, allowing for reports to display datasets like | ||
| 45 | the following: | ||
| 46 | |||
| 47 | +------------+---------------+-------+ | ||
| 48 | | | | 1 | | ||
| 49 | | | test +-------+ | ||
| 50 | | foo | | 2 | | ||
| 51 | | +---------------+-------+ | ||
| 52 | | | test2 | 3 | | ||
| 53 | +------------+---------------+-------+ | ||
| 54 | |||
| 55 | =head1 METHODS | ||
| 56 | |||
| 57 | =over | ||
| 58 | |||
| 59 | =item B<new($options)> | ||
| 60 | |||
| 61 | Accepts the same arguments as L<HTML::ReportWriter::PagingAndSorting>, plus the following: | ||
| 62 | |||
| 63 | =over | ||
| 64 | |||
| 65 | =item DBH | ||
| 66 | A database handle that has connected to the database that the report is to be run against. | ||
| 67 | |||
| 68 | =item SQL_FRAGMENT | ||
| 69 | An SQL fragment starting from the FROM clause, continued through the end of the where clause. In | ||
| 70 | the case of MySQL and/or other databases that support them, GROUP BY and HAVING clauses may also be | ||
| 71 | added to the SQL fragment. | ||
| 72 | |||
| 73 | =item COLUMNS | ||
| 74 | Column definitions for what is to be selected. A column definition consists of one of two formats, either | ||
| 75 | a simple one-element array reference or an array reference of hash references containing the following four | ||
| 76 | elements: | ||
| 77 | |||
| 78 | get - the string used in the get variable to determine the sorted column | ||
| 79 | sql - the sql statement that will select the data from the database | ||
| 80 | display - What should be displayed in the column's table header | ||
| 81 | sortable - whether or not a sorting link should be generated for the column | ||
| 82 | order - (optional) sql that will be used to order by the specified column. If not present, then the value of sql is used | ||
| 83 | group - (optional) true or false. If true, the column will be grouped after the results are retrieved. | ||
| 84 | hide_column - (optional) true or false. If true, the column will not be drawn to the screen. This is useful if you | ||
| 85 | want to pull data for some other column's draw_func. | ||
| 86 | draw_func - (optional) code ref, may not be used if group is true. code ref to a function which takes two parameters. | ||
| 87 | param 1: the data from the column being rendered | ||
| 88 | param 2: the hashref containing the data from the rest of the row | ||
| 89 | returns: the string that should be displayed as the cell contents when that column is drawn | ||
| 90 | |||
| 91 | These definitions can be arbitrarily complex. For example: | ||
| 92 | |||
| 93 | COLUMNS => [ | ||
| 94 | { | ||
| 95 | get => 'username', | ||
| 96 | sql => 'jp.username', | ||
| 97 | display => 'Username', | ||
| 98 | sortable => 1, | ||
| 99 | group => 1, | ||
| 100 | }, | ||
| 101 | { | ||
| 102 | get => 'date', | ||
| 103 | sql => 'DATE_FORMAT(l.created, \'%m/%e/%Y\') AS date', | ||
| 104 | display => 'Date', | ||
| 105 | sortable => 1, | ||
| 106 | order => 'l.created', | ||
| 107 | }, | ||
| 108 | { | ||
| 109 | get => 'type', | ||
| 110 | sql => "IF(l.deleted = 'yes', 'delete', 'add') AS type", | ||
| 111 | display => 'Type', | ||
| 112 | sortable => 1, | ||
| 113 | }, | ||
| 114 | { | ||
| 115 | sql => "l.id", | ||
| 116 | hide_column => 1, | ||
| 117 | }, | ||
| 118 | { | ||
| 119 | get => 'successful', | ||
| 120 | sql => "l.successful", | ||
| 121 | display => 'Successful', | ||
| 122 | sortable => 1, | ||
| 123 | draw_func => sub { my ($data, $cols) = @_; my $lid = $cols->{'id'}; my $color = ($data eq 'no' ? 'red' : ($data eq 'yes' ? 'green' : 'black')); return "<a style=\"color: $color;\" href=\"#\" onClick=\"popup('/cgi-bin/reports/message.cgi?id=$lid'); return false;\">$data</a>"; }, | ||
| 124 | }, | ||
| 125 | ] | ||
| 126 | |||
| 127 | and | ||
| 128 | |||
| 129 | COLUMNS => [ 'name', 'address', 'age' ] | ||
| 130 | |||
| 131 | are both valid definitions. Additionally, you can combine scalar and hashref-filled arrayrefs, like | ||
| 132 | |||
| 133 | COLUMNS => [ | ||
| 134 | 'name', | ||
| 135 | 'age', | ||
| 136 | { | ||
| 137 | get => 'birthday', | ||
| 138 | sql => 'DATE_FORMAT(birthday, \'%m/%e/%Y\') AS birthday', | ||
| 139 | display => 'Birthday', | ||
| 140 | sortable => 1, | ||
| 141 | order => 'birthday', | ||
| 142 | }, | ||
| 143 | ] | ||
| 144 | |||
| 145 | |||
| 146 | If you are going to use complex sql structures in a column definiton (for example, the | ||
| 147 | DATE_FORMAT and IF statements above), it is STRONGLY recommended that you use a column alias (for example, the | ||
| 148 | 'AS date' in the date column example) in order to ensure proper functionality. This module has not been tested | ||
| 149 | with unaliased complex sql column definitions. | ||
| 150 | |||
| 151 | NOTE: If you use formatting that would change a numeric-type column into a string-type column (for example the | ||
| 152 | date columns above), you should use the order attribute to ensure proper ordering. For example using DATE_FORMAT | ||
| 153 | as shown above results in the integer-style date column being treated as a string (20041010120000 becomes | ||
| 154 | '10-10-2004'), which would cause '10-10-2004' to sort before '10-02-2004'. draw_func is intended to provide you | ||
| 155 | with a simple alternative to things like DATE_FORMAT -- you can now do the formatting outside the SQL. | ||
| 156 | |||
| 157 | =item DEBUG | ||
| 158 | Will cause useful debugging messages to be printed using the warn facility. default: 0 | ||
| 159 | |||
| 160 | =item COLUMN_SORT_DEFAULT | ||
| 161 | If the simplified version of the COLUMNS definition is used (COLUMNS => [ 'foo', 'bar' ]), then this variable | ||
| 162 | determines whether the table header will allow sorting of any columns. It is global in scope; that is, either | ||
| 163 | every column is sortable, or every column is not. If the hashref method is used to define columns, this variable | ||
| 164 | will be ignored. | ||
| 165 | |||
| 166 | =item MYSQL_MAJOR_VERSION | ||
| 167 | Currently either 3, 4 or 5. Determines which method of determining num_results is used. In MySQL 4 a new method | ||
| 168 | was added which makes the process much more efficient. Defaults to 4 since it's been the stable release for well | ||
| 169 | over a year. | ||
| 170 | |||
| 171 | =item CGI_OBJECT | ||
| 172 | A handle to a CGI object. Since it is very unlikely that a report will ever be just a static report with no | ||
| 173 | user interaction, it is assumed that the coder will want to instantiate their own CGI object in order to allow | ||
| 174 | the user to interact with the report. Use of this argument will prevent needless creation of additional CGI objects. | ||
| 175 | |||
| 176 | =item PAGE_TITLE | ||
| 177 | The title of the current page. Defaults to "HTML::ReportWriter v${VERSION} generated report". | ||
| 178 | |||
| 179 | =item CSS | ||
| 180 | The CSS style applied to the page. Can be an external stylesheet reference or an inline style. Has a default inline | ||
| 181 | style that I won't waste space listing here. | ||
| 182 | |||
| 183 | =item HTML_HEADER | ||
| 184 | The first thing that will appear in the body of the HTML document. Unrestricted, can be anything at all. I recommend | ||
| 185 | placing self-referential forms here to allow the user to interact with the report (for example, setting date ranges). | ||
| 186 | See B<EXAMPLES> below for ideas. | ||
| 187 | |||
| 188 | =item HTML_FOOTER | ||
| 189 | Last thing that appears in the body of the page. Defaults to: '<center><div id="footer"><p align="center">This report | ||
| 190 | was generated using <a href="http://search.cpan.org/~opiate/">HTML::ReportWriter</a> version ' . $VERSION . '.</p></div> | ||
| 191 | </center>'; | ||
| 192 | |||
| 193 | =item LANGUAGE_TOKENS | ||
| 194 | A list of language tokens that can be used to replace the default English text. | ||
| 195 | |||
| 196 | =item EXPORT_VARIABLE | ||
| 197 | Defaults to 'exportto'. This variable, if passed in via a GET or POST parameter, and set equal to a supported export method, | ||
| 198 | will cause the report to be exported. Set EXPORT_VARIABLE to '' to disable exporting. Currently supported formats: | ||
| 199 | |||
| 200 | =over | ||
| 201 | |||
| 202 | =item * | ||
| 203 | excel: Reports are exported without paging. Sorting is maintained. Grouping of results is disabled. | ||
| 204 | |||
| 205 | =back | ||
| 206 | |||
| 207 | =item REPORT_TABLE_WIDTH | ||
| 208 | Default: 800. The width of the table containing the report output. | ||
| 209 | |||
| 210 | =item DOCTYPE | ||
| 211 | Default: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> | ||
| 212 | Set to '' if you do not want to have a doctype declared. | ||
| 213 | |||
| 214 | =back | ||
| 215 | |||
| 216 | The return of this function is a reference to the object. Calling draw after the object's initialization will draw the page. | ||
| 217 | |||
| 218 | Note with regards to DEFAULT_SORT: the string used to specify the default sort must match the B<get> parameter of the COLUMNS | ||
| 219 | definition if you use a hashref COLUMN definition. | ||
| 220 | |||
| 221 | =cut | ||
| 222 | |||
| 223 | sub new | ||
| 224 | { | ||
| 225 | my ($pkg, $args) = @_; | ||
| 226 | |||
| 227 | my @paging_args = ( | ||
| 228 | 'RESULTS_PER_PAGE', | ||
| 229 | 'PAGES_IN_LIST', | ||
| 230 | 'PAGE_VARIABLE', | ||
| 231 | 'SORT_VARIABLE', | ||
| 232 | 'DEFAULT_SORT', | ||
| 233 | 'PREV_HTML', | ||
| 234 | 'NEXT_HTML', | ||
| 235 | 'FIRST_HTML', | ||
| 236 | 'LAST_HTML', | ||
| 237 | 'ASC_HTML', | ||
| 238 | 'DESC_HTML', | ||
| 239 | ); | ||
| 240 | my $paging_args = {}; | ||
| 241 | |||
| 242 | # check for required arguments | ||
| 243 | if(!defined($args->{'DBH'})) | ||
| 244 | { | ||
| 245 | die 'Argument \'DBH\' is required'; | ||
| 246 | } | ||
| 247 | elsif(!defined($args->{'SQL_FRAGMENT'})) | ||
| 248 | { | ||
| 249 | die 'Argument \'SQL_FRAGMENT\' is required'; | ||
| 250 | } | ||
| 251 | elsif(!defined($args->{'COLUMNS'}) || ref($args->{'COLUMNS'}) ne 'ARRAY') | ||
| 252 | { | ||
| 253 | die 'Argument \'COLUMNS\' is required, and must be an array reference'; | ||
| 254 | } | ||
| 255 | |||
| 256 | # define reasonable defaults for arguments if a value is not provided | ||
| 257 | $args->{'COLUMN_SORT_DEFAULT'} = 1 if !defined $args->{'COLUMN_SORT_DEFAULT'}; | ||
| 258 | |||
| 259 | # this switch controls whether count(*) is used, or for MySQL the more efficient SQL_CALC_FOUND_ROWS | ||
| 260 | # when getting the total number of results for pagination. | ||
| 261 | $args->{'MYSQL_MAJOR_VERSION'} = 4 if !defined $args->{'MYSQL_MAJOR_VERSION'}; | ||
| 262 | if($args->{'DBH'}->{'Driver'}->{'Name'} ne 'mysql') | ||
| 263 | { | ||
| 264 | # we almost certainly cannot use SQL_CALC_FOUND_ROWS if the DBMS is not MySQL | ||
| 265 | $args->{'MYSQL_MAJOR_VERSION'} = 3; | ||
| 266 | } | ||
| 267 | |||
| 268 | $args->{'DEBUG'} = 0 if !defined $args->{'DEBUG'}; | ||
| 269 | |||
| 270 | # html format specifiers | ||
| 271 | $args->{'DOCTYPE'} = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' if !defined $args->{'DOCTYPE'}; | ||
| 272 | $args->{'REPORT_TABLE_WIDTH'} = '800' if !defined $args->{'REPORT_TABLE_WIDTH'}; | ||
| 273 | |||
| 274 | $args->{'EXPORT_VARIABLE'} = 'exportto' if !defined $args->{'EXPORT_VARIABLE'}; | ||
| 275 | |||
| 276 | $args->{'LANGUAGE_TOKENS'} = { | ||
| 277 | display_token => 'Displaying Results $1 to $2 of $3', | ||
| 278 | export_data_to => 'Export this data to', | ||
| 279 | export_report_data => 'Exported Report Data', | ||
| 280 | export_value => 'Excel', | ||
| 281 | no_results => 'There are no results to display.', | ||
| 282 | } if !defined $args->{'LANGUAGE_TOKENS'}; | ||
| 283 | |||
| 284 | # check for simplified column definition, and make sure the COLUMNS array isn't empty | ||
| 285 | # if the simplified definition is used, change it to the complex one. | ||
| 286 | if(@{$args->{'COLUMNS'}}) | ||
| 287 | { | ||
| 288 | $args->{'FIELDS'} = []; | ||
| 289 | my $grouping_allowed = 1; | ||
| 290 | my $size = @{$args->{'COLUMNS'}} - 1; | ||
| 291 | |||
| 292 | foreach my $index (0..$size) | ||
| 293 | { | ||
| 294 | if(ref($args->{'COLUMNS'}->[$index]) eq 'SCALAR' || ref($args->{'COLUMNS'}->[$index]) eq '') | ||
| 295 | { | ||
| 296 | my $str = $args->{'COLUMNS'}->[$index]; | ||
| 297 | $args->{'COLUMNS'}->[$index] = { | ||
| 298 | 'sql' => $str, | ||
| 299 | 'get' => $str, | ||
| 300 | 'display' => ucfirst($str), | ||
| 301 | 'sortable' => ($args->{'COLUMN_SORT_DEFAULT'} ? 1 : 0), | ||
| 302 | }; | ||
| 303 | } | ||
| 304 | |||
| 305 | if(defined($args->{'COLUMNS'}->[$index]->{'group'}) && $args->{'COLUMNS'}->[$index]->{'group'} && defined($args->{'COLUMNS'}->[$index]->{'draw_func'}) && $args->{'COLUMNS'}->[$index]->{'draw_func'}) | ||
| 306 | { | ||
| 307 | die 'You cannot define a draw_func for a grouped column'; | ||
| 308 | } | ||
| 309 | |||
| 310 | # enforce the fact that grouping is only allowed at the beginning of a column list | ||
| 311 | if(!defined($args->{'COLUMNS'}->[$index]->{'group'}) || !$args->{'COLUMNS'}->[$index]->{'group'}) | ||
| 312 | { | ||
| 313 | # interesting efficiency question: is it faster to reassign in a safe situation, | ||
| 314 | # or would it be more efficient if there were a check to prevent reassignment? | ||
| 315 | $grouping_allowed = 0; | ||
| 316 | } | ||
| 317 | elsif(defined($args->{'COLUMNS'}->[$index]->{'group'}) && $args->{'COLUMNS'}->[$index]->{'group'}) | ||
| 318 | { | ||
| 319 | if(!$grouping_allowed) | ||
| 320 | { | ||
| 321 | die 'Grouped columns must be defined at the beginning of the column list'; | ||
| 322 | } | ||
| 323 | } | ||
| 324 | |||
| 325 | # construct a list of fields with group set if it is a grouped column | ||
| 326 | my $col = $args->{'COLUMNS'}->[$index]->{'sql'}; | ||
| 327 | $col =~ s/^.+ AS (.+)$/$1/i; | ||
| 328 | $col =~ s/^[a-zA-Z0-9]+\.//; | ||
| 329 | push @{$args->{'FIELDS'}}, { | ||
| 330 | 'field' => $col, | ||
| 331 | 'group' => (defined($args->{'COLUMNS'}->[$index]->{'group'}) && $args->{'COLUMNS'}->[$index]->{'group'}), | ||
| 332 | 'draw_func' => (defined($args->{'COLUMNS'}->[$index]->{'draw_func'}) ? $args->{'COLUMNS'}->[$index]->{'draw_func'} : undef), | ||
| 333 | 'hide_column' => (defined($args->{'COLUMNS'}->[$index]->{'hide_column'}) && $args->{'COLUMNS'}->[$index]->{'hide_column'}), | ||
| 334 | }; | ||
| 335 | } | ||
| 336 | } | ||
| 337 | else | ||
| 338 | { | ||
| 339 | die 'COLUMNS can not be a blank array ref'; | ||
| 340 | } | ||
| 341 | |||
| 342 | # create a CGI object if we haven't been given one | ||
| 343 | if(!defined($args->{'CGI_OBJECT'}) || !UNIVERSAL::isa($args->{'CGI_OBJECT'}, "CGI")) | ||
| 344 | { | ||
| 345 | $args->{'CGI_OBJECT'} = new CGI; | ||
| 346 | warn "Creating new CGI object"; | ||
| 347 | } | ||
| 348 | |||
| 349 | # I want to modularize this somehow... when that happens, this will need to be fixed. | ||
| 350 | $args->{'EXPORT'} = $args->{'CGI_OBJECT'}->param($args->{'EXPORT_VARIABLE'}); | ||
| 351 | if(!defined($args->{'EXPORT'}) || $args->{'EXPORT'} ne 'excel') | ||
| 352 | { | ||
| 353 | $args->{'EXPORT'} = ''; | ||
| 354 | } | ||
| 355 | |||
| 356 | # set up the arguments for the paging module, and delete them from the main arg list, | ||
| 357 | # since we don't really care about them | ||
| 358 | foreach my $key (@paging_args) | ||
| 359 | { | ||
| 360 | if(defined $args->{$key}) | ||
| 361 | { | ||
| 362 | $paging_args->{$key} = $args->{$key}; | ||
| 363 | delete $args->{$key}; | ||
| 364 | } | ||
| 365 | } | ||
| 366 | |||
| 367 | # the paging module also gets a CGI_OBJECT, and a copy of the COLUMNS setup | ||
| 368 | $paging_args->{'CGI_OBJECT'} = $args->{'CGI_OBJECT'}; | ||
| 369 | $paging_args->{'SORTABLE_COLUMNS'} = $args->{'COLUMNS'}; | ||
| 370 | $paging_args->{'LANGUAGE_TOKENS'} = $args->{'LANGUAGE_TOKENS'}; | ||
| 371 | |||
| 372 | # instantiate our paging object | ||
| 373 | $args->{'PAGING_OBJECT'} = HTML::ReportWriter::PagingAndSorting->new($paging_args); | ||
| 374 | |||
| 375 | # default HTML-related arguments | ||
| 376 | if(!defined $args->{'PAGE_TITLE'}) | ||
| 377 | { | ||
| 378 | $args->{'PAGE_TITLE'} = "HTML::ReportWriter v${VERSION} generated report"; | ||
| 379 | } | ||
| 380 | if(!defined $args->{'HTML_HEADER'}) | ||
| 381 | { | ||
| 382 | $args->{'HTML_HEADER'} = ''; | ||
| 383 | } | ||
| 384 | if(!defined $args->{'HTML_FOOTER'}) | ||
| 385 | { | ||
| 386 | $args->{'HTML_FOOTER'} = '<center><div id="footer"><p align="center">This report was generated using <a href="http://search.cpan.org/~opiate/">HTML::ReportWriter</a> version ' . $VERSION . '.</p></div></center>'; | ||
| 387 | } | ||
| 388 | if(!defined $args->{'CSS'}) | ||
| 389 | { | ||
| 390 | $args->{'CSS'} = "<style type=\"text/css\">\n\n#footer {\n clear: both;\n padding: 5px;\n margin-top: 5px;\n border: 1px solid gray;\n background-color: rgb(213, 219, 225);\n width: 600px;\n}\n\n.paging-table {\n border: 0px solid black;\n}\n.paging-td {\n padding: 4px;\n font-weight: none;\n color: #555555;\n}\n.paging-a {\n color: black;\n font-weight: bold;\n text-decoration: none;\n}\n\n#idtable {\n border: 1px solid #666;\n}\n\n#idtable tbody tr td {\n padding: 3px 8px;\n font-size: 8pt;\n border: 0px solid black;\n border-left: 1px solid #c9c9c9;\n text-align: center;\n}\n\n#idtable tbody tr td.table_even {\n background-color: #eee;\n}\n\n#idtable tbody tr td.table_odd {\n background-color: #fff;\n}\n\n#idtable tbody tr.sortable-header-tr td {\n background-color: #bbb;\n}\n</style>\n"; | ||
| 391 | } | ||
| 392 | |||
| 393 | my $self = bless $args, $pkg; | ||
| 394 | |||
| 395 | return $self; | ||
| 396 | } | ||
| 397 | |||
| 398 | =item B<draw()> | ||
| 399 | |||
| 400 | Renders the page. | ||
| 401 | This function takes one optional parameter, i<disable_output>. If the results are not being exported to a non-HTML format, and if | ||
| 402 | i<disable_output> evaluates to false then this function writes the HTTP header and the page text to STDOUT (the only behaviour prior | ||
| 403 | to version 1.5.0). If the parameter evaluates to true, the function does not print anything to STDOUT. In either of those cases, the | ||
| 404 | text of the HTML page is returned by B<draw()>. | ||
| 405 | |||
| 406 | If the results are being exported (to e.g. Excel), then the output will always be sent to STDOUT regardless of the value of | ||
| 407 | disable_output, and the function will return success or failure of the export. | ||
| 408 | |||
| 409 | =cut | ||
| 410 | |||
| 411 | sub draw | ||
| 412 | { | ||
| 413 | eval | ||
| 414 | { | ||
| 415 | use Template; | ||
| 416 | }; | ||
| 417 | |||
| 418 | if($@) | ||
| 419 | { | ||
| 420 | die "The draw function can not be utilized unless the module Template (template-toolkit.org) is installed"; | ||
| 421 | } | ||
| 422 | |||
| 423 | my $self = shift; | ||
| 424 | my( $disable_output ) = @_; | ||
| 425 | my $to_return = ''; | ||
| 426 | |||
| 427 | my $results = $self->get_results(); | ||
| 428 | |||
| 429 | if($self->{'EXPORT'}) | ||
| 430 | { | ||
| 431 | my $method = 'export_to_' . $self->{'EXPORT'}; | ||
| 432 | |||
| 433 | if(exists &$method) | ||
| 434 | { | ||
| 435 | return $self->$method($results); | ||
| 436 | } | ||
| 437 | else | ||
| 438 | { | ||
| 439 | die "export method $method does not exist"; | ||
| 440 | } | ||
| 441 | } | ||
| 442 | else | ||
| 443 | { | ||
| 444 | my $template = Template->new(); | ||
| 445 | my $url = $self->{'CGI_OBJECT'}->url( -absolute => 1, -query => 1 ); | ||
| 446 | |||
| 447 | my $vars = { | ||
| 448 | 'version' => $VERSION, | ||
| 449 | 'css' => $self->{'CSS'}, | ||
| 450 | 'html_header' => $self->{'HTML_HEADER'}, | ||
| 451 | 'html_footer' => $self->{'HTML_FOOTER'}, | ||
| 452 | 'page_title' => $self->{'PAGE_TITLE'}, | ||
| 453 | 'sorting' => $self->{'PAGING_OBJECT'}->get_sortable_table_header(), | ||
| 454 | 'fields' => $self->{'FIELDS'}, | ||
| 455 | 'draw_row' => \&draw_row, | ||
| 456 | 'row_counter' => [], # this will be populated as draw_row runs | ||
| 457 | 'export_link' => ($self->{'EXPORT_VARIABLE'} ? $url . ($url =~ /\?/ ? "&" : "?") . "$self->{'EXPORT_VARIABLE'}=excel" : ''), | ||
| 458 | 'report_table_width' => $self->{'REPORT_TABLE_WIDTH'}, | ||
| 459 | 'doctype' => $self->{'DOCTYPE'}, | ||
| 460 | }; | ||
| 461 | |||
| 462 | # grouping could be a costly operation, so only do it if necessary | ||
| 463 | if(defined($self->{'FIELDS'}->[0]->{'group'}) && $self->{'FIELDS'}->[0]->{'group'}) | ||
| 464 | { | ||
| 465 | $vars->{'results'} = $self->group_results($results); | ||
| 466 | } | ||
| 467 | else | ||
| 468 | { | ||
| 469 | $vars->{'results'} = $results; | ||
| 470 | } | ||
| 471 | |||
| 472 | # paging can only be drawn after we have the result set pulled | ||
| 473 | $vars->{'paging'} = $self->{'PAGING_OBJECT'}->get_paging_table(); | ||
| 474 | |||
| 475 | $vars = { %{ $self->{'LANGUAGE_TOKENS'}}, %$vars }; | ||
| 476 | |||
| 477 | $template->process(\*DATA, $vars, \$to_return) || warn "Template processing failed: " . $template->error(); | ||
| 478 | |||
| 479 | if( !defined $disable_output || !$disable_output ) | ||
| 480 | { | ||
| 481 | print $self->{'CGI_OBJECT'}->header; | ||
| 482 | print "$to_return"; | ||
| 483 | } | ||
| 484 | } | ||
| 485 | |||
| 486 | return $to_return; | ||
| 487 | } | ||
| 488 | |||
| 489 | =item B<export_to_excel()> | ||
| 490 | =cut | ||
| 491 | |||
| 492 | sub export_to_excel | ||
| 493 | { | ||
| 494 | eval | ||
| 495 | { | ||
| 496 | use Spreadsheet::SimpleExcel; | ||
| 497 | }; | ||
| 498 | |||
| 499 | if($@) | ||
| 500 | { | ||
| 501 | die "You cannot use this feature unless SpreadSheet::SimpleExcel is installed"; | ||
| 502 | } | ||
| 503 | |||
| 504 | my $self = shift; | ||
| 505 | my ($results) = @_; | ||
| 506 | |||
| 507 | my @header = map { $_->{'display'} } @{$self->{'COLUMNS'}}; | ||
| 508 | |||
| 509 | my $i = 0; | ||
| 510 | foreach my $field ( @{$self->{'COLUMNS'}} ) | ||
| 511 | { | ||
| 512 | if( "$field->{'hide_column'}" eq "1" ) | ||
| 513 | { | ||
| 514 | map { splice( @$_, $i, 1) } @$results; | ||
| 515 | } | ||
| 516 | $i++; | ||
| 517 | } | ||
| 518 | binmode(\*STDOUT); | ||
| 519 | |||
| 520 | # create a new instance | ||
| 521 | my $excel = Spreadsheet::SimpleExcel->new(); | ||
| 522 | |||
| 523 | # add worksheets | ||
| 524 | $excel->add_worksheet('Exported Report Data',{-headers => \@header, -data => $results}); | ||
| 525 | |||
| 526 | # create the spreadsheet | ||
| 527 | return $excel->output(); | ||
| 528 | } | ||
| 529 | |||
| 530 | =item B<draw_row()> | ||
| 531 | |||
| 532 | This function is magical. One day, when I am feeling brave, I will comment it. What ever happened to the nice textbook | ||
| 533 | recursive functions they taught in CS class? | ||
| 534 | |||
| 535 | It is internal to HTML::ReportWriter, and shouldn't need to be overridden. If you want to customize the look and feel of the | ||
| 536 | report, you can use the draw_func option to the columns to override the appearance of a given element, and you can customize | ||
| 537 | the stylesheet at creation-time (see new()). | ||
| 538 | |||
| 539 | =cut | ||
| 540 | |||
| 541 | sub draw_row | ||
| 542 | { | ||
| 543 | my($fields, $results, $row_counter, $print, $open, $depth) = @_; | ||
| 544 | my $rowspan = 0; | ||
| 545 | my $output = ''; | ||
| 546 | |||
| 547 | if(ref($results) ne 'ARRAY') | ||
| 548 | { | ||
| 549 | $results = [ $results ]; | ||
| 550 | } | ||
| 551 | |||
| 552 | foreach my $res (@$results) | ||
| 553 | { | ||
| 554 | ++$row_counter->[$depth]; | ||
| 555 | |||
| 556 | # We're dealing with a simple result set right now | ||
| 557 | if(!defined($res->{'HTML::ReportWriter group column'})) | ||
| 558 | { | ||
| 559 | ++$rowspan; | ||
| 560 | |||
| 561 | if(!$open) | ||
| 562 | { | ||
| 563 | $output .= '<tr>'; | ||
| 564 | } | ||
| 565 | |||
| 566 | foreach my $field (@$fields) | ||
| 567 | { | ||
| 568 | my $fname = $field->{'field'}; | ||
| 569 | |||
| 570 | if(exists($res->{$fname}) && !$field->{'hide_column'}) | ||
| 571 | { | ||
| 572 | $output .= '<td class="' . ($row_counter->[$depth] % 2 ? 'table_odd' : 'table_even') . "\">"; | ||
| 573 | if(ref($field->{'draw_func'}) eq 'CODE') | ||
| 574 | { | ||
| 575 | $output .= $field->{'draw_func'}->($res->{$fname}, $res); | ||
| 576 | } | ||
| 577 | else | ||
| 578 | { | ||
| 579 | $output .= (defined($res->{$fname}) ? $res->{$fname} : ''); | ||
| 580 | } | ||
| 581 | $output .= "</td>"; | ||
| 582 | } | ||
| 583 | } | ||
| 584 | $output .= "</tr>\n"; | ||
| 585 | |||
| 586 | if($open) | ||
| 587 | { | ||
| 588 | $open = 0; | ||
| 589 | } | ||
| 590 | |||
| 591 | } | ||
| 592 | |||
| 593 | # now we're dealing with a grouped row | ||
| 594 | else | ||
| 595 | { | ||
| 596 | my ($crowspan, $coutput) = draw_row($fields, $res->{'rows'}, $row_counter, 0, 1, $depth + 1); | ||
| 597 | $rowspan += $crowspan; | ||
| 598 | |||
| 599 | if(!$open) | ||
| 600 | { | ||
| 601 | $output .= '<tr>'; | ||
| 602 | } | ||
| 603 | |||
| 604 | $output .= '<td class="' . ($row_counter->[$depth] % 2 ? 'table_odd' : 'table_even') . '" rowspan="' . $crowspan . '">' | ||
| 605 | . $res->{'HTML::ReportWriter group column'} . '</td>' . $coutput; | ||
| 606 | |||
| 607 | if($open) | ||
| 608 | { | ||
| 609 | $open = 0; | ||
| 610 | } | ||
| 611 | } | ||
| 612 | } | ||
| 613 | |||
| 614 | if($print) | ||
| 615 | { | ||
| 616 | return $output; | ||
| 617 | } | ||
| 618 | else | ||
| 619 | { | ||
| 620 | return ($rowspan, $output); | ||
| 621 | } | ||
| 622 | } | ||
| 623 | |||
| 624 | =item B<group_results()> | ||
| 625 | |||
| 626 | Internal method -- groups a result set if necessary. | ||
| 627 | |||
| 628 | =cut | ||
| 629 | |||
| 630 | sub group_results | ||
| 631 | { | ||
| 632 | my ($self, $data) = @_; | ||
| 633 | |||
| 634 | my $results = []; | ||
| 635 | |||
| 636 | # code below relies on the fact that having two refs $p and $q, setting $p = $q makes them refer to the same memory location. | ||
| 637 | # thus, I am using $p as a pointer to my current depth in the results data structure. | ||
| 638 | foreach my $href (@$data) | ||
| 639 | { | ||
| 640 | my $p = $results; | ||
| 641 | my $current_element_number = -1; | ||
| 642 | |||
| 643 | # process each field separately, and move the pointer as we go along | ||
| 644 | # this will be a little slow; if anyone has an idea for improving its performance, please share. | ||
| 645 | foreach my $f (@{$self->{'FIELDS'}}) | ||
| 646 | { | ||
| 647 | if(defined($f->{'group'}) && $f->{'group'}) | ||
| 648 | { | ||
| 649 | my $val = $href->{$f->{'field'}}; | ||
| 650 | |||
| 651 | my $found = -1; | ||
| 652 | my $size = scalar @{$p}; | ||
| 653 | |||
| 654 | if($size) | ||
| 655 | { | ||
| 656 | foreach my $index (0..($size-1)) | ||
| 657 | { | ||
| 658 | if($p->[$index]->{'HTML::ReportWriter group column'} eq $val) | ||
| 659 | { | ||
| 660 | $found = $index; | ||
| 661 | last; | ||
| 662 | } | ||
| 663 | } | ||
| 664 | } | ||
| 665 | |||
| 666 | if($found != -1) | ||
| 667 | { | ||
| 668 | $p = $p->[$found]->{'rows'}; | ||
| 669 | } | ||
| 670 | else | ||
| 671 | { | ||
| 672 | $p->[$size] = { | ||
| 673 | 'HTML::ReportWriter group column' => $val, | ||
| 674 | 'rows' => [], | ||
| 675 | }; | ||
| 676 | $p = $p->[$size]->{'rows'}; | ||
| 677 | } | ||
| 678 | } | ||
| 679 | else | ||
| 680 | { | ||
| 681 | if($current_element_number == -1) | ||
| 682 | { | ||
| 683 | my $size = @{$p}; | ||
| 684 | $p->[$size] = {}; | ||
| 685 | $current_element_number = $size; | ||
| 686 | } | ||
| 687 | |||
| 688 | $p->[$current_element_number]->{$f->{'field'}} = $href->{$f->{'field'}}; | ||
| 689 | } | ||
| 690 | } | ||
| 691 | } | ||
| 692 | |||
| 693 | return $results; | ||
| 694 | } | ||
| 695 | |||
| 696 | =item B<get_results()> | ||
| 697 | |||
| 698 | Internal method -- generates the result set used by draw(). | ||
| 699 | |||
| 700 | =cut | ||
| 701 | |||
| 702 | sub get_results | ||
| 703 | { | ||
| 704 | my $self = shift; | ||
| 705 | my $loop_counter = 0; | ||
| 706 | my $results = []; | ||
| 707 | |||
| 708 | # assume no paging if we are exporting the results | ||
| 709 | if($self->{'EXPORT'}) | ||
| 710 | { | ||
| 711 | my $sql = 'SELECT ' | ||
| 712 | . join(', ', map { $_->{'sql'} } @{$self->{'COLUMNS'}}) | ||
| 713 | . ' ' . $self->{'SQL_FRAGMENT'}; | ||
| 714 | my $sort = $self->{'PAGING_OBJECT'}->get_sort($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 715 | |||
| 716 | if($self->{'DEBUG'}) | ||
| 717 | { | ||
| 718 | warn "Executing SQL: $sql $sort"; | ||
| 719 | } | ||
| 720 | |||
| 721 | my $sth = $self->{'DBH'}->prepare("$sql $sort"); | ||
| 722 | $sth->execute(); | ||
| 723 | $results = $sth->fetchall_arrayref; | ||
| 724 | $sth->finish; | ||
| 725 | } | ||
| 726 | elsif($self->{'MYSQL_MAJOR_VERSION'} >= 4) | ||
| 727 | { | ||
| 728 | my $sql = 'SELECT SQL_CALC_FOUND_ROWS ' | ||
| 729 | . join(', ', map { $_->{'sql'} } @{$self->{'COLUMNS'}}) | ||
| 730 | . ' ' . $self->{'SQL_FRAGMENT'}; | ||
| 731 | my $sort = $self->{'PAGING_OBJECT'}->get_sort($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 732 | my $limit = $self->{'PAGING_OBJECT'}->get_limit($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 733 | |||
| 734 | if($self->{'DEBUG'}) | ||
| 735 | { | ||
| 736 | warn "Executing SQL: $sql $sort $limit"; | ||
| 737 | } | ||
| 738 | |||
| 739 | my $sth = $self->{'DBH'}->prepare("$sql $sort $limit"); | ||
| 740 | $sth->execute(); | ||
| 741 | my ($count) = $self->{'DBH'}->selectrow_array('SELECT FOUND_ROWS() AS num'); | ||
| 742 | |||
| 743 | my $status = $self->{'PAGING_OBJECT'}->num_results($count); | ||
| 744 | |||
| 745 | # if $count is 0, then there are no results and the check should be skipped. Else, if there are rows and num_results | ||
| 746 | # returns false, then we've somehow paged past the end of the result set. Get back on track here. | ||
| 747 | while(!$status && $count) | ||
| 748 | { | ||
| 749 | $limit = $self->{'PAGING_OBJECT'}->get_limit($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 750 | |||
| 751 | $sth->finish; | ||
| 752 | |||
| 753 | if($self->{'DEBUG'}) | ||
| 754 | { | ||
| 755 | warn "Executing SQL: $sql $sort $limit"; | ||
| 756 | } | ||
| 757 | |||
| 758 | $sth = $self->{'DBH'}->prepare("$sql $sort $limit"); | ||
| 759 | $sth->execute(); | ||
| 760 | ($count) = $self->{'DBH'}->selectrow_array('SELECT FOUND_ROWS() AS num'); | ||
| 761 | |||
| 762 | $status = $self->{'PAGING_OBJECT'}->num_results($count); | ||
| 763 | |||
| 764 | # if we aren't back on track in 3 loops, we've got a problem | ||
| 765 | if(++$loop_counter == 3) | ||
| 766 | { | ||
| 767 | die "Unrecoverable error -- is the result set changing?"; | ||
| 768 | } | ||
| 769 | } | ||
| 770 | |||
| 771 | while(my $href = $sth->fetchrow_hashref) | ||
| 772 | { | ||
| 773 | push @$results, $href; | ||
| 774 | } | ||
| 775 | } | ||
| 776 | elsif($self->{'MYSQL_MAJOR_VERSION'} < 4) | ||
| 777 | { | ||
| 778 | # MySQL 3.23 requires the use of a count query -- SQL_CALC_FOUND_ROWS had not yet been implemented | ||
| 779 | my $countsql = 'SELECT count(*) ' . $self->{'SQL_FRAGMENT'}; | ||
| 780 | |||
| 781 | if($self->{'DEBUG'}) | ||
| 782 | { | ||
| 783 | warn "Executing SQL: $countsql"; | ||
| 784 | } | ||
| 785 | |||
| 786 | my $sth = $self->{'DBH'}->prepare("$countsql"); | ||
| 787 | $sth->execute(); | ||
| 788 | my ($count) = $sth->fetchrow_array; | ||
| 789 | $sth->finish; | ||
| 790 | |||
| 791 | # We won't bother checking the status, cause we're just now generating the limit clause, so it is not likely | ||
| 792 | # the result set could have changed. | ||
| 793 | $self->{'PAGING_OBJECT'}->num_results($count); | ||
| 794 | |||
| 795 | my $sql = 'SELECT ' . join(', ', map { $_->{'sql'} } @{$self->{'COLUMNS'}}) . ' ' . $self->{'SQL_FRAGMENT'}; | ||
| 796 | my $sort = $self->{'PAGING_OBJECT'}->get_sort($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 797 | my $limit = $self->{'PAGING_OBJECT'}->get_limit($self->{'DBH'}->{'Driver'}->{'Name'}); | ||
| 798 | |||
| 799 | if($self->{'DEBUG'}) | ||
| 800 | { | ||
| 801 | warn "Executing SQL: $sql $sort $limit"; | ||
| 802 | } | ||
| 803 | |||
| 804 | $sth = $self->{'DBH'}->prepare("$sql $sort $limit"); | ||
| 805 | $sth->execute(); | ||
| 806 | |||
| 807 | while(my $href = $sth->fetchrow_hashref) | ||
| 808 | { | ||
| 809 | push @{$results}, $href; | ||
| 810 | } | ||
| 811 | } | ||
| 812 | else | ||
| 813 | { | ||
| 814 | die "this should never happen"; | ||
| 815 | } | ||
| 816 | |||
| 817 | return $results; | ||
| 818 | } | ||
| 819 | |||
| 820 | =back | ||
| 821 | |||
| 822 | =head1 A NOTE ABOUT GROUPING | ||
| 823 | |||
| 824 | Grouping is done in code after the database returns its dataset. Grouping breaks sortability | ||
| 825 | (or vice-versa depending on your point of view) to a small degree, and for large datasets grouping | ||
| 826 | can produce unexpected results across pages. | ||
| 827 | |||
| 828 | In particular, if a group of 6 rows of data spans two pages (say 3 results on page 1 and 3 results | ||
| 829 | on page 2), then only three results will show on page 1. For this reason, it is recommended on pages | ||
| 830 | that have highly-constrained result sets (1 page of results), or where paging is disabled. | ||
| 831 | |||
| 832 | Additionally, it is strongly recommended that authors using this module consider which columns really | ||
| 833 | need to be sortable when using grouping. Based on limited testing and experience, if sorting is | ||
| 834 | necessary, I recommend only allowing sorting on the grouped columns. I also recommend making the | ||
| 835 | default sort == the first grouped column. | ||
| 836 | |||
| 837 | When you sort by an ungrouped column, the grouped columns are still grouped, despite the fact that | ||
| 838 | they may appear adjacent. Order of the rows is preserved. For example, assume the following dataset | ||
| 839 | was sorted by the third column and grouped by the first: | ||
| 840 | |||
| 841 | test foo 5 | ||
| 842 | test2 quux 4 | ||
| 843 | test bar 3 | ||
| 844 | test2 bat 2 | ||
| 845 | test baz 1 | ||
| 846 | |||
| 847 | Output would be: | ||
| 848 | |||
| 849 | +-------+------+---+ | ||
| 850 | | | foo | 5 | | ||
| 851 | | +------+---+ | ||
| 852 | | test | bar | 3 | | ||
| 853 | | +------+---+ | ||
| 854 | | | baz | 1 | | ||
| 855 | +-------+------+---+ | ||
| 856 | | | quux | 4 | | ||
| 857 | | test2 +------+---+ | ||
| 858 | | | bat | 2 | | ||
| 859 | +-------+------+---+ | ||
| 860 | |||
| 861 | One restriction on grouped columns is that they must appear at the beginning of the column list: | ||
| 862 | |||
| 863 | COLUMNS => [ | ||
| 864 | { | ||
| 865 | get => 'username', | ||
| 866 | sql => 'jp.username', | ||
| 867 | display => 'Username', | ||
| 868 | sortable => 1, | ||
| 869 | group => 1, | ||
| 870 | }, | ||
| 871 | { | ||
| 872 | get => 'date', | ||
| 873 | sql => 'DATE_FORMAT(l.created, \'%m/%e/%Y\') AS date', | ||
| 874 | display => 'Date', | ||
| 875 | sortable => 1, | ||
| 876 | order => 'l.created', | ||
| 877 | }, | ||
| 878 | ] | ||
| 879 | |||
| 880 | is correct, whereas: | ||
| 881 | |||
| 882 | COLUMNS => [ | ||
| 883 | { | ||
| 884 | get => 'username', | ||
| 885 | sql => 'jp.username', | ||
| 886 | display => 'Username', | ||
| 887 | sortable => 1, | ||
| 888 | }, | ||
| 889 | { | ||
| 890 | get => 'date', | ||
| 891 | sql => 'DATE_FORMAT(l.created, \'%m/%e/%Y\') AS date', | ||
| 892 | display => 'Date', | ||
| 893 | sortable => 1, | ||
| 894 | order => 'l.created', | ||
| 895 | group => 1, | ||
| 896 | }, | ||
| 897 | ] | ||
| 898 | |||
| 899 | will result in die() being called. | ||
| 900 | |||
| 901 | =head1 USING HTML::ReportWriter WITH OTHER DATASOURCES | ||
| 902 | |||
| 903 | While it is my hope that I will eventually be able to add any datasource that someone | ||
| 904 | could want to this package, I know that in the meantime, some people are left hanging. As | ||
| 905 | a result of the recent separation of data retrieval into the get_results() method, you can | ||
| 906 | now add support for any data retrieval method you wish: either subclass HTML::ReportWriter | ||
| 907 | and override get_results, or modify your created object like | ||
| 908 | |||
| 909 | $report->{'get_results'} = \&data_retrieval_func(); | ||
| 910 | |||
| 911 | If you override the function, your new function should take no parameters, rely on $self to | ||
| 912 | provide necessary paging and sorting information, and return an arrayref consisting of | ||
| 913 | hashrefs containing { column => value } pairs for each column that is passed in to new using | ||
| 914 | COLUMNS. I haven't tested this, but see no reason why it should not work. | ||
| 915 | |||
| 916 | Please do not rely on this as anything more than a temporary fix -- I expect that the internals | ||
| 917 | of the module will change somewhat dramatically when I finally decide on a method of abstracting | ||
| 918 | data retrieval. Suggestions welcome on how to abstract data retrieval. | ||
| 919 | |||
| 920 | Update: overriding this function will cause breakage unless either (1) Your function is modified to | ||
| 921 | take exports into account, or (2) You disable export functionality in your report. | ||
| 922 | |||
| 923 | =head1 TODO | ||
| 924 | |||
| 925 | =over | ||
| 926 | |||
| 927 | =item * | ||
| 928 | write tests for the module | ||
| 929 | |||
| 930 | =item * | ||
| 931 | support for other databases (help greatly appreciated) | ||
| 932 | |||
| 933 | =item * | ||
| 934 | implement export feature supporting export to PDF for the results | ||
| 935 | |||
| 936 | =item * | ||
| 937 | overrides for shading behaviour and line drawing between cells. | ||
| 938 | |||
| 939 | =item * | ||
| 940 | I am debating the addition of support for query prefixes, like DISTINCT (which should appear before | ||
| 941 | the list of data to be selected). This could also be used for extensions like MySQL's SQL_NO_CACHE | ||
| 942 | directives. Feedback welcome. | ||
| 943 | |||
| 944 | =back | ||
| 945 | |||
| 946 | =head1 EXAMPLES | ||
| 947 | |||
| 948 | Data: the following statements can be reloaded into a mysql database and the resulting tables | ||
| 949 | can be used in conjunction with the scripts below to demo the features of the reportwriter. | ||
| 950 | The data should be imported into a DB named testing, and have a root user with a blank password, | ||
| 951 | or else you need to edit the DBI->connect statements below. I'd recommend never having a blank root | ||
| 952 | password, personally. | ||
| 953 | |||
| 954 | CREATE TABLE log ( | ||
| 955 | userid int(10) default NULL, | ||
| 956 | activity char(24) default NULL, | ||
| 957 | created timestamp(14) NOT NULL | ||
| 958 | ) TYPE=MyISAM; | ||
| 959 | |||
| 960 | INSERT INTO log VALUES (1,'test',20050124064258); | ||
| 961 | INSERT INTO log VALUES (1,'test2',20050124064301); | ||
| 962 | INSERT INTO log VALUES (1,'test3',20050124064303); | ||
| 963 | INSERT INTO log VALUES (1,'test4',20050124064305); | ||
| 964 | INSERT INTO log VALUES (2,'test4',20050124064308); | ||
| 965 | INSERT INTO log VALUES (3,'test5',20050124064313); | ||
| 966 | INSERT INTO log VALUES (2,'test6',20050124064317); | ||
| 967 | INSERT INTO log VALUES (2,'test7',20050124064319); | ||
| 968 | |||
| 969 | CREATE TABLE people ( | ||
| 970 | name char(25) default NULL, | ||
| 971 | age int(2) default NULL, | ||
| 972 | birthday timestamp(14) NOT NULL, | ||
| 973 | phone_number char(10) default NULL, | ||
| 974 | active int(1) default '1' | ||
| 975 | ) TYPE=MyISAM; | ||
| 976 | |||
| 977 | INSERT INTO people VALUES ('Barney Rubble',20,19700101000000,'9724443456',1); | ||
| 978 | INSERT INTO people VALUES ('Fred Flintstone',25,19700401000000,'9725551212',1); | ||
| 979 | INSERT INTO people VALUES ('wilma',25,19700401000000,'9725551212',1); | ||
| 980 | INSERT INTO people VALUES ('dino',25,19700401000000,'9725551212',1); | ||
| 981 | INSERT INTO people VALUES ('bambam',25,19700401000000,'9725551212',1); | ||
| 982 | INSERT INTO people VALUES ('george',25,19700401000000,'9725551212',1); | ||
| 983 | INSERT INTO people VALUES ('elroy',25,19700401000000,'9725551212',1); | ||
| 984 | INSERT INTO people VALUES ('judy',25,19700401000000,'9725551212',1); | ||
| 985 | INSERT INTO people VALUES ('jane',25,19700401000000,'9725551212',1); | ||
| 986 | INSERT INTO people VALUES ('disco',25,19700401000000,'9725551212',1); | ||
| 987 | INSERT INTO people VALUES ('tango',25,19700401000000,'9725551212',1); | ||
| 988 | INSERT INTO people VALUES ('foxtrot',25,19700401000000,'9725551212',1); | ||
| 989 | INSERT INTO people VALUES ('waltz',25,19700401000000,'9725551212',1); | ||
| 990 | INSERT INTO people VALUES ('swing',25,19700401000000,'9725551212',1); | ||
| 991 | INSERT INTO people VALUES ('i',25,19700401000000,'9725551212',1); | ||
| 992 | INSERT INTO people VALUES ('am',25,19700401000000,'9725551212',1); | ||
| 993 | INSERT INTO people VALUES ('not',25,19700401000000,'9725551212',1); | ||
| 994 | INSERT INTO people VALUES ('feeling',25,19700401000000,'9725551212',1); | ||
| 995 | INSERT INTO people VALUES ('creative',25,19700401000000,'9725551212',1); | ||
| 996 | INSERT INTO people VALUES ('right',25,19700401000000,'9725551212',1); | ||
| 997 | INSERT INTO people VALUES ('now',25,19700401000000,'9725551212',1); | ||
| 998 | INSERT INTO people VALUES ('so',25,19700401000000,'9725551212',1); | ||
| 999 | INSERT INTO people VALUES ('the',25,19700401000000,'9725551212',1); | ||
| 1000 | INSERT INTO people VALUES ('sample',25,19700401000000,'9725551212',1); | ||
| 1001 | INSERT INTO people VALUES ('data',25,19700401000000,'9725551212',1); | ||
| 1002 | INSERT INTO people VALUES ('sucks.',25,19700401000000,'9725551212',1); | ||
| 1003 | INSERT INTO people VALUES ('sorry',25,19700401000000,'9725551212',1); | ||
| 1004 | INSERT INTO people VALUES ('about',25,19700401000000,'9725551212',1); | ||
| 1005 | INSERT INTO people VALUES ('that!',25,19700401000000,'9725551212',1); | ||
| 1006 | INSERT INTO people VALUES (':)',25,19700401000000,'9725551212',1); | ||
| 1007 | |||
| 1008 | CREATE TABLE user ( | ||
| 1009 | id int(10) default NULL, | ||
| 1010 | name char(15) default NULL, | ||
| 1011 | groupid int(1) default NULL | ||
| 1012 | ) TYPE=MyISAM; | ||
| 1013 | |||
| 1014 | INSERT INTO user VALUES (1,'zeus',3); | ||
| 1015 | INSERT INTO user VALUES (2,'apollo',2); | ||
| 1016 | INSERT INTO user VALUES (3,'mercury',3); | ||
| 1017 | |||
| 1018 | Example 1, a simple non-interactive report, like one that might be used to show phonebook | ||
| 1019 | entries: | ||
| 1020 | |||
| 1021 | #!/usr/bin/perl -w | ||
| 1022 | |||
| 1023 | use strict; | ||
| 1024 | use HTML::ReportWriter; | ||
| 1025 | use DBI; | ||
| 1026 | |||
| 1027 | my $dbh = DBI->connect('DBI:mysql:host=localhost:database=testing', 'root', ''); | ||
| 1028 | |||
| 1029 | my $sql_fragment = 'FROM people WHERE active = 1'; | ||
| 1030 | |||
| 1031 | my $report = HTML::ReportWriter->new({ | ||
| 1032 | DBH => $dbh, | ||
| 1033 | SQL_FRAGMENT => $sql_fragment, | ||
| 1034 | DEFAULT_SORT => 'birthday', | ||
| 1035 | COLUMNS => [ | ||
| 1036 | 'name', | ||
| 1037 | 'age', | ||
| 1038 | 'birthday', | ||
| 1039 | { | ||
| 1040 | get => 'phone', | ||
| 1041 | sql => 'phone_number', | ||
| 1042 | display => 'Phone Number', | ||
| 1043 | sortable => 0, | ||
| 1044 | }, | ||
| 1045 | ], | ||
| 1046 | }); | ||
| 1047 | |||
| 1048 | $report->draw(); | ||
| 1049 | |||
| 1050 | Example 2, an interactive report allowing the user to select data within a date range. | ||
| 1051 | |||
| 1052 | #!/usr/bin/perl -w | ||
| 1053 | |||
| 1054 | use strict; | ||
| 1055 | use CGI; | ||
| 1056 | use HTML::ReportWriter; | ||
| 1057 | use DBI; | ||
| 1058 | |||
| 1059 | my $dbh = DBI->connect('DBI:mysql:host=localhost:database=testing', 'root', ''); | ||
| 1060 | my $co = CGI->new(); | ||
| 1061 | |||
| 1062 | # set defaults if there is not a setting for date1 or date2 | ||
| 1063 | my $date1 = $co->param('date1') || '20050101000000'; | ||
| 1064 | my $date2 = $co->param('date2') || '20050201000000'; | ||
| 1065 | |||
| 1066 | my $sql_fragment = 'FROM log AS l, user AS u WHERE l.userid = u.id AND u.groupid = ' | ||
| 1067 | . $dbh->quote(3) . ' AND l.created BETWEEN ' | ||
| 1068 | . $dbh->quote($date1) . ' AND ' . $dbh->quote($date2); | ||
| 1069 | |||
| 1070 | my $report = HTML::ReportWriter->new({ | ||
| 1071 | DBH => $dbh, | ||
| 1072 | CGI_OBJECT => $co, | ||
| 1073 | SQL_FRAGMENT => $sql_fragment, | ||
| 1074 | DEFAULT_SORT => 'date', | ||
| 1075 | HTML_HEADER => '<form method="get"><table><tr><td colspan="3">Show results from:</td></tr><tr> | ||
| 1076 | <td><input type="text" name="date1" value="' . $date1 . '" /></td> | ||
| 1077 | <td> to </td> | ||
| 1078 | <td><input type="text" name="date2" value="' . $date2 . '" /></td></tr> | ||
| 1079 | <tr><td colspan="3" align="center"><input type="submit" /></td></tr></table></form>', | ||
| 1080 | PAGE_TITLE => 'Log Activity for Group ' . 'foo', | ||
| 1081 | COLUMNS => [ | ||
| 1082 | 'name', | ||
| 1083 | 'activity', | ||
| 1084 | { | ||
| 1085 | get => 'date', | ||
| 1086 | sql => 'DATE_FORMAT(l.created, \'%m/%e/%Y\') AS date', | ||
| 1087 | display => 'Date', | ||
| 1088 | sortable => 1, | ||
| 1089 | }, | ||
| 1090 | ], | ||
| 1091 | }); | ||
| 1092 | |||
| 1093 | $report->draw(); | ||
| 1094 | |||
| 1095 | Caveats for Example 2: | ||
| 1096 | |||
| 1097 | =over | ||
| 1098 | |||
| 1099 | =item * | ||
| 1100 | By using the short form of the column definitions, you are asserting that there is only | ||
| 1101 | one column named 'name' and one column named 'activity' in both the log and user tables combined. You'd get an | ||
| 1102 | SQL error otherwise for having an ambiguous column reference. | ||
| 1103 | |||
| 1104 | =item * | ||
| 1105 | Assumption is that the user enters the date in as a MySQL timestamp in the form. I got lazy as I was writing this | ||
| 1106 | example. Also, the form would probably not look great, because the table is not formatted, nor does it have an | ||
| 1107 | alignment on the page -- the report would be centered and the form left-justified. Making things pretty is left | ||
| 1108 | as an exercise for the reader. | ||
| 1109 | |||
| 1110 | =back | ||
| 1111 | |||
| 1112 | =head1 BUGS | ||
| 1113 | |||
| 1114 | None are known about at this time. | ||
| 1115 | |||
| 1116 | Please report any additional bugs discovered to the author. | ||
| 1117 | |||
| 1118 | =head1 SEE ALSO | ||
| 1119 | |||
| 1120 | This module relies on L<DBI>, L<Template> and L<CGI>. | ||
| 1121 | The paging/sorting module also relies on L<POSIX> and L<List::MoreUtils>. | ||
| 1122 | Exporting to Excel uses L<Spreadsheet::SimpleExcel>. | ||
| 1123 | |||
| 1124 | =head1 AUTHOR | ||
| 1125 | |||
| 1126 | Shane Allen E<lt>opiate@gmail.comE<gt> | ||
| 1127 | |||
| 1128 | =head1 ACKNOWLEDGEMENTS | ||
| 1129 | |||
| 1130 | =over | ||
| 1131 | |||
| 1132 | =item * | ||
| 1133 | PagingAndSorting was developed during my employ at HRsmart, Inc. L<http://www.hrsmart.com> and its | ||
| 1134 | public release was graciously approved. | ||
| 1135 | |||
| 1136 | =item * | ||
| 1137 | Robert Egert was an early adopter, and made signifigant contributions in the form of suggestions and | ||
| 1138 | bug reports. | ||
| 1139 | |||
| 1140 | =item * | ||
| 1141 | Mark Stosberg made several contributions including documentation corrections and PostgreSQL support. | ||
| 1142 | |||
| 1143 | =item * | ||
| 1144 | Steven Mackenzie contributed a patch to add support for SQLite. | ||
| 1145 | |||
| 1146 | =back | ||
| 1147 | |||
| 1148 | =head1 COPYRIGHT | ||
| 1149 | |||
| 1150 | Copyright 2004, Shane Allen. All rights reserved. | ||
| 1151 | |||
| 1152 | This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | ||
| 1153 | |||
| 1154 | =cut | ||
| 1155 | |||
| 1156 | __DATA__ |