2 # Generates a csv with the table generated by the execution of an arbitrary sql
3 # The sql can be an argument of the program, if no argument is supplied then it
4 # reads its sql from stdin.
13 use Tarificador::Helper;
14 use Tarificador::Logger;
16 my $logger = Tarificador::Logger->new('/dev/stderr');
17 my $helper = Tarificador::Helper->new
19 '<header>' => "$0: [SQL]\r This program use an arbitrary sql to execute on"
20 . "the db, fetch a table and display it as a csv (comma separate value),"
21 . "yea I know that the query `EXPORT' can do this job but I never"
22 . "managed to get it work.\r if the sql if not provided as an argument"
23 . "then it is readed from stdin",
24 '-h -help' =>'Shows help and exit',
25 '-u --db_user' => "Specify the db_user, if this option is not "
26 . "specified then the environment variable DB_NAME is read for fetch "
27 . 'its value, if it does not exist then the program exit with a db error.',
28 '-p --db_passwd' =>"Specify the db_passwd, if this option is not "
29 . "specified then the environment variable DB_PASSWD is read for fetch "
30 . 'its value, if it does not exist then the program exit with a db error.',
31 '-n --db_name' => "Specify the db_name, if this option is not "
32 . "specified then the environment variable DB_NAME is read for fetch "
33 . 'its value, if it does not exist then the program exit with a db error.',
34 '-d --debug' => "Shows debug information, each time you use this "
35 . "option the verbosity level increase by one showing more information.",
38 my %db_data = ( 'db_user' => undef, 'db_passwd' => undef, 'db_name' => undef);
42 GetOptions ('help|h' => sub { $helper->show;exit 1; }
43 , 'db_user|u' => \$db_data{'db_user'}
44 , 'db_passwd|p' => \$db_data{'db_passwd'}
45 , 'db_name|n' => \$db_data{'db_name'}
46 , 'debug|d+' => \$loglevel
49 $logger->level($loglevel);
50 $logger->write(1, "Entering debugging mode (". $logger->level(). ")\n");
52 @db_data{sort keys %db_data}
53 = map { ( ! defined $db_data{$_} and $ENV{uc()} ) ? $ENV{uc()} : undef}
56 croak "ERROR: I need a db_name" unless $db_data{db_name};
57 croak "ERROR: I need a db_user!!" unless $db_data{db_user};
58 croak "ERROR: I need a db_passwd!!" unless $db_data{db_passwd};
61 # if there are no args then read sql from stdin
66 $_ =~ s/^[[:space:]]*/ /g;
73 croak 'Error no sql' unless $sql;
75 $logger->write(1, join(' : ' ,
76 map { "$_ => " . ($db_data{$_} ? $db_data{$_} : undef) }
77 keys %db_data), "\n");
79 my $dbh = DBI->connect("DBI:mysql:$db_data{db_name}", "$db_data{db_user}",
80 "$db_data{db_passwd}", {PrintError => 0, RaiseError => 1})
83 $logger->write(1, "Executing `$sql'\n");
85 my $sth = $dbh->prepare($sql);
89 print join (',', map { $_ ? $_ : ''} @$row), "\n"
90 while ($row = $sth->fetchrow_arrayref());