--- sql2xls.cgi 2008/11/03 18:44:42 6 +++ sql2xls.cgi 2008/11/03 20:32:44 13 @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/perl -T use warnings; use strict; @@ -22,6 +22,23 @@ You can also run script from command line, and it will produce C<< sql_reports.xls >> file. +If run within directory, it will use files in it to produce file. + +When called as CGI, directory name can be appended to name of script +to produce report for any sub-directory within directory where +C is installed. + +=head1 INSTALLATION + +Only required file is this script C<< sql2xls.cgi >> + +If your server is configured to execute C<.cgi> files, you can +drop this script anywhere, but you can also add something like + + ScriptAlias /xls-reports /srv/SQL2XLS/sql2xls.cgi + +in Apache's virtual host configuration to get nice URLs + =head1 AUTHOR Dobrica Pavlinusic, dpavlin@rot13.org @@ -31,25 +48,35 @@ use Spreadsheet::WriteExcel; use DBI; use CGI::Carp qw(fatalsToBrowser); -use CGI qw(path_translated); use Encode qw/decode/; use Data::Dump qw/dump/; # edit following to set defaults -my $dsn = 'DBI:Pg:dbname='; -my $database = 'template1'; -my $user = 'dpavlin'; -my $passwd = ''; -my $path = 'sql_reports.xls'; +our $dsn = 'DBI:Pg:dbname='; +our $database = 'template1'; +our $user = 'dpavlin'; +our $passwd = ''; +our $path = 'sql_reports.xls'; -my $db_encoding = 'iso-8859-2'; -my $xls_date_format = 'dd.mm.yyyy'; +our $db_encoding = 'iso-8859-2'; +our $xls_date_format = 'dd.mm.yyyy'; -my $debug = 1; +our $debug = 1; -my $sql_dir = path_translated || '.'; +my $sql_dir = $ENV{SCRIPT_FILENAME} || '.'; $sql_dir =~ s,/[^/]+$,,; +my $config_path = "$sql_dir/config.pl"; +warn "# using $config_path\n"; +require $config_path if -e $config_path; + +my $reports_path = $ENV{PATH_INFO}; +$reports_path =~ s/\.\.//g; # some protection against path exploits +$reports_path ||= shift @ARGV; # for CLI invocation +$sql_dir .= "/$reports_path" if -e "$sql_dir/$reports_path"; + +warn "# reading SQL queries from $sql_dir\n" if $debug; + opendir(DIR, $sql_dir) || die "can't opendir $sql_dir: $!"; my @sql_files = sort grep { /\.sql$/i && -f "$sql_dir/$_" } readdir(DIR); closedir DIR; @@ -81,12 +108,13 @@ $sheet_name =~ s/\.sql//; # Add a worksheet - my $worksheet = $workbook->addworksheet($sheet_name); + warn "# clipping sheet name '$sheet_name' to 31 char limit\n" if length $sheet_name > 31; + my $worksheet = $workbook->addworksheet( substr($sheet_name,0,31) ); print STDERR "working on $sql_file\n" if ($debug); - open(SQL,$sql_file) || die "can't open sql file '$sql_file': $!"; - my $comment; + open(SQL,"$sql_dir/$sql_file") || die "can't open sql file '$sql_dir/$sql_file': $!"; + my $comment = ''; my $sql = ""; while() { chomp; @@ -114,6 +142,9 @@ my $fmt_comment = $workbook->addformat(); # Add a format $fmt_comment->set_bold(); + $comment =~ s/^\s+//; + $comment =~ s/\s+$//; + $worksheet->write($row, 0, _c($comment), $fmt_comment); $row+=2; }