4 our @ISA = qw(Exporter);
 
   6 our @EXPORT = qw(conv_i conv_date conv_dateq do_query selectrow_query do_statement
 
   7              dump_query quote_db_date
 
   8              selectfirst_hashref_query selectfirst_array_query
 
   9              selectall_hashref_query selectall_array_query
 
  11              prepare_execute_query prepare_query
 
  12              create_sort_spec does_table_exist
 
  18   my ($value, $default) = @_;
 
  19   return (defined($value) && "$value" ne "") ? $value * 1 : $default;
 
  24   return (defined($value) && "$value" ne "") ? $value : undef;
 
  29   if (defined($value) && "$value" ne "") {
 
  30     $value =~ s/\'/\'\'/g;
 
  37   $main::lxdebug->enter_sub(2);
 
  39   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
  41   dump_query(LXDebug->QUERY(), '', $query, @_);
 
  44   if (0 == scalar(@_)) {
 
  45     $result = $dbh->do($query)            || $form->dberror($query);
 
  47     $result = $dbh->do($query, undef, @_) || $form->dberror($query . " (" . join(", ", @_) . ")");
 
  50   $main::lxdebug->leave_sub(2);
 
  55 sub selectrow_query { &selectfirst_array_query }
 
  58   $main::lxdebug->enter_sub(2);
 
  60   my ($form, $sth, $query) = splice(@_, 0, 3);
 
  62   dump_query(LXDebug->QUERY(), '', $query, @_);
 
  65   if (0 == scalar(@_)) {
 
  66     $result = $sth->execute()   || $form->dberror($query);
 
  68     $result = $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
 
  71   $main::lxdebug->leave_sub(2);
 
  77   my ($level, $msg, $query) = splice(@_, 0, 3);
 
  79   my $self_filename = 'SL/DBUtils.pm';
 
  80   my $filename      = $self_filename;
 
  81   my ($caller_level, $line, $subroutine);
 
  82   while ($filename eq $self_filename) {
 
  83     (undef, $filename, $line, $subroutine) = caller $caller_level++;
 
  86   while ($query =~ /\?/) {
 
  87     my $value = shift || '';
 
  88     $value =~ s/\'/\\\'/g;
 
  89     $value = "'${value}'";
 
  90     $query =~ s/\?/$value/;
 
  93   $query =~ s/[\n\s]+/ /g;
 
  95   $msg .= " " if ($msg);
 
  97   my $info = "$subroutine called from $filename:$line\n";
 
  99   $main::lxdebug->message($level, $info . $msg . $query);
 
 105   return "NULL" unless defined $str;
 
 106   return "current_date" if $str =~ /current_date/;
 
 113   $main::lxdebug->enter_sub(2);
 
 115   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 117   dump_query(LXDebug->QUERY(), '', $query, @_);
 
 119   my $sth = $dbh->prepare($query) || $form->dberror($query);
 
 121   $main::lxdebug->leave_sub(2);
 
 126 sub prepare_execute_query {
 
 127   $main::lxdebug->enter_sub(2);
 
 129   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 131   dump_query(LXDebug->QUERY(), '', $query, @_);
 
 133   my $sth = $dbh->prepare($query) || $form->dberror($query);
 
 134   if (scalar(@_) != 0) {
 
 135     $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
 
 137     $sth->execute() || $form->dberror($query);
 
 140   $main::lxdebug->leave_sub(2);
 
 145 sub selectall_hashref_query {
 
 146   $main::lxdebug->enter_sub(2);
 
 148   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 150   dump_query(LXDebug->QUERY(), '', $query, @_);
 
 152   # this works back 'til at least DBI 1.46 on perl 5.8.4 on Debian Sarge (2004)
 
 153   my $result = $dbh->selectall_arrayref($query, { Slice => {} }, @_)
 
 154     or $form->dberror($query . (@_ ? " (" . join(", ", @_) . ")" : ''));
 
 156   $main::lxdebug->leave_sub(2);
 
 158   return wantarray ? @{ $result } : $result;
 
 161 sub selectall_array_query {
 
 162   $main::lxdebug->enter_sub(2);
 
 164   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 166   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 168   while (my ($value) = $sth->fetchrow_array()) {
 
 169     push(@result, $value);
 
 173   $main::lxdebug->leave_sub(2);
 
 178 sub selectfirst_hashref_query {
 
 179   $main::lxdebug->enter_sub(2);
 
 181   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 183   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 184   my $ref = $sth->fetchrow_hashref();
 
 187   $main::lxdebug->leave_sub(2);
 
 192 sub selectfirst_array_query {
 
 193   $main::lxdebug->enter_sub(2);
 
 195   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 197   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 198   my @ret = $sth->fetchrow_array();
 
 201   $main::lxdebug->leave_sub(2);
 
 206 sub selectall_as_map {
 
 207   $main::lxdebug->enter_sub(2);
 
 209   my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
 
 211   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 214   if ('' eq ref $value_col) {
 
 215     while (my $ref = $sth->fetchrow_hashref()) {
 
 216       $hash{$ref->{$key_col}} = $ref->{$value_col};
 
 219     while (my $ref = $sth->fetchrow_hashref()) {
 
 220       $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
 
 226   $main::lxdebug->leave_sub(2);
 
 231 sub create_sort_spec {
 
 232   $main::lxdebug->enter_sub(2);
 
 237   $params{defs}    || die;
 
 238   $params{default} || die;
 
 240   # The definition of valid columns to sort by.
 
 241   my $defs        = $params{defs};
 
 243   # The column name to sort by. Use the default column name if none was given.
 
 244   my %result      = ( 'column' => $params{column} || $params{default} );
 
 246   # Overwrite the column name with the default column name if the other one is not valid.
 
 247   $result{column} = $params{default} unless ($defs->{ $result{column} });
 
 249   # The sort direction. true means 'sort ascending', false means 'sort descending'.
 
 250   $result{dir}    = defined $params{dir}         ? $params{dir}
 
 251                   : defined $params{default_dir} ? $params{default_dir}
 
 253   $result{dir}    = $result{dir} ?     1 :      0;
 
 254   my $asc_desc    = $result{dir} ? 'ASC' : 'DESC';
 
 256   # Create the SQL code.
 
 257   my $cols        = $defs->{ $result{column} };
 
 258   $result{sql}    = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
 
 260   $main::lxdebug->leave_sub(2);
 
 265 sub does_table_exist {
 
 266   $main::lxdebug->enter_sub(2);
 
 274     my $sth = $dbh->table_info('', '', $table, 'TABLE');
 
 276       $result = $sth->fetchrow_hashref();
 
 281   $main::lxdebug->leave_sub(2);
 
 286 # add token to values.
 
 292 #    val => [ 23, 34, 17 ]
 
 295 #  will append to the given arrays:
 
 296 #   -> 'id IN (?, ?, ?)'
 
 297 #   -> (conv_i(23), conv_i(34), conv_i(17))
 
 300 #   - don't care if one or multiple values are given. singlewill result in 'col = ?'
 
 301 #   - pass escape routines
 
 302 #   - expand for future method
 
 303 #   - no need to type "push @where_tokens, 'id = ?'" over and over again
 
 305   my $tokens = shift() || [];
 
 306   my $values = shift() || [];
 
 308   my $col    = $params{col};
 
 309   my $val    = $params{val};
 
 310   my $method = $params{method} || '=';
 
 311   my $escape = $params{esc} || sub { $_ };
 
 313   $val = [ $val ] unless ref $val eq 'ARRAY';
 
 323       return scalar @_ >  1 ? sprintf '%s IN (%s)', $col, join ', ', ("?") x scalar @_
 
 324            : scalar @_ == 1 ? sprintf '%s = ?',     $col
 
 329   $method = $methods{$method} || $method;
 
 330   $escape = $escapes{$escape} || $escape;
 
 332   my $token = $method->($col, @{ $val });
 
 333   my @vals  = map { $escape->($_) } @{ $val };
 
 335   return unless $token;
 
 337   push @{ $tokens }, $token;
 
 338   push @{ $values }, @vals;
 
 340   return ($token, @vals);
 
 350 SL::DBUTils.pm: All about Databaseconections in Lx
 
 356   conv_i($str, $default)
 
 361   do_query($form, $dbh, $query)
 
 362   do_statement($form, $sth, $query)
 
 364   dump_query($level, $msg, $query)
 
 365   prepare_execute_query($form, $dbh, $query)
 
 367   my $all_results_ref       = selectall_hashref_query($form, $dbh, $query)
 
 368   my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
 
 370   my @first_result =  selectfirst_array_query($form, $dbh, $query);  # ==
 
 371   my @first_result =  selectrow_query($form, $dbh, $query);
 
 373   my %sort_spec = create_sort_spec(%params);
 
 377 DBUtils is the attempt to reduce the amount of overhead it takes to retrieve information from the database in Lx-Office. Previously it would take about 15 lines of code just to get one single integer out of the database, including failure procedures and importing the necessary packages. Debugging would take even more.
 
 379 Using DBUtils most database procedures can be reduced to defining the query, executing it, and retrieving the result. Let DBUtils handle the rest. Whenever there is a database operation not covered in DBUtils, add it here, rather than working around it in the backend code.
 
 381 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
 
 382   - $form is used for error handling only. It can be omitted in theory, but should not.
 
 383   - $dbh is a handle to the databe, as returned by the DBI::connect routine. If you don't have an active connectiong, you can query $form->get_standard_dbh() to get a generic no_auto connection. Don't forget to commit in this case!
 
 386 Every function here should accomplish the follwing things:
 
 387   - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
 
 388   - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
 
 389   - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
 
 391 Note that binding is not perfect here either...
 
 393 =head2 QUOTING FUNCTIONS
 
 399 =item conv_i STR,DEFAULT
 
 401 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
 
 405 Converts STR to a date string. If STR is emptry, returns undef.
 
 409 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
 
 411 =item quote_db_date STR
 
 413 Treats STR as a database date, quoting it. If STR equals current_date returns an escaped version which is treated as the current date by Postgres.
 
 414 Returns 'NULL' if STR is empty.
 
 418 =head2 QUERY FUNCTIONS
 
 422 =item do_query FORM,DBH,QUERY,ARRAY
 
 424 Uses DBI::do to execute QUERY on DBH using ARRAY for binding values. FORM is only needed for error handling, but should always be passed nevertheless. Use this for insertions or updates that don't need to be prepared.
 
 426 Returns the result of DBI::do which is -1 in case of an error and the number of affected rows otherwise.
 
 428 =item do_statement FORM,STH,QUERY,ARRAY
 
 430 Uses DBI::execute to execute QUERY on DBH using ARRAY for binding values. As with do_query, FORM is only used for error handling. If you are unsure what to use, refer to the documentation of DBI::do and DBI::execute.
 
 432 Returns the result of DBI::execute which is -1 in case of an error and the number of affected rows otherwise.
 
 434 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
 
 436 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
 
 440 =head2 RETRIEVAL FUNCTIONS
 
 444 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
 
 446 =item selectrow_query FORM,DBH,QUERY,ARRAY
 
 448 Prepares and executes a query using DBUtils functions, retireves the first row from the database, and returns it as an arrayref of the first row.
 
 450 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
 
 452 Prepares and executes a query using DBUtils functions, retireves the first row from the database, and returns it as a hashref of the first row.
 
 454 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
 
 456 Prepares and executes a query using DBUtils functions, retireves all data from the database, and returns it in hashref mode. This is slightly confusing, as the data structure will actually be a reference to an array, containing hashrefs for each row.
 
 458 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
 
 460 Prepares and executes a query using DBUtils functions, retireves all data from the database, and creates a hash from the results using KEY_COL as the column for the hash keys and VALUE_COL for its values.
 
 464 =head2 UTILITY FUNCTIONS
 
 468 =item create_sort_spec
 
 471     defs        => { },         # mandatory
 
 472     default     => 'name',      # mandatory
 
 482 This function simplifies the creation of SQL code for sorting
 
 483 columns. It uses a hashref of valid column names, the column name and
 
 484 direction requested by the user, the application defaults for the
 
 485 column name and the direction and returns the actual column name,
 
 486 direction and SQL code that can be used directly in a query.
 
 488 The parameter 'defs' is a hash reference. The keys are the column
 
 489 names as they may come from the application. The values are either
 
 490 scalars with SQL code or array references of SQL code. Example:
 
 492 'defs' => { 'customername' => 'lower(customer.name)',
 
 493             'address'      => [ 'lower(customer.city)', 'lower(customer.street)' ], }
 
 495 'default' is the default column name to sort by. It must be a key of
 
 496 'defs' and should not be come from user input.
 
 498 The 'column' parameter is the column name as requested by the
 
 499 application (e.g. if the user clicked on a column header in a
 
 500 report). If it is invalid then the 'default' parameter will be used
 
 503 'default_dir' is the default sort direction. A true value means 'sort
 
 504 ascending', a false one 'sort descending'. 'default_dir' defaults to
 
 507 The 'dir' parameter is the sort direction as requested by the
 
 508 application (e.g. if the user clicked on a column header in a
 
 509 report). If it is undefined then the 'default_dir' parameter will be
 
 514 =head2 DEBUG FUNCTIONS
 
 518 =item dump_query LEVEL,MSG,QUERY,ARRAY
 
 520 Dumps a query using LXDebug->message, using LEVEL for the debug-level of LXDebug. If MSG is given, it preceeds the QUERY dump in the logfiles. ARRAY is used to interpolate the '?' placeholders in QUERY, the resulting QUERY can be copy-pasted into a database frontend for debugging. Note that this method is also automatically called by each of the other QUERY FUNCTIONS, so there is in general little need to invoke it manually.
 
 528 =item Retrieving a whole table:
 
 530   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 531   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 533 =item Retrieving a single value:
 
 535   $query = qq|SELECT nextval('glid')|;
 
 536   ($new_id) = selectrow_query($form, $dbh, $query);
 
 538 =item Using binding values:
 
 540   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 541   do_query($form, $dbh, $query, $id);
 
 543 =item A more complicated example, using dynamic binding values:
 
 547   if ($form->{language_values} ne "") {
 
 548     $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
 550                   LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
 
 551     @values = (conv_i($form->{id}));
 
 553     $query = qq|SELECT id, description FROM language|;
 
 556   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
 560 =head1 MODULE AUTHORS
 
 562 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
 
 563 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 565 =head1 DOCUMENTATION AUTHORS
 
 567 Udo Spallek E<lt>udono@gmx.netE<gt>
 
 568 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 570 =head1 COPYRIGHT AND LICENSE
 
 572 Copyright 2007 by Lx-Office Community
 
 574 This program is free software; you can redistribute it and/or modify
 
 575 it under the terms of the GNU General Public License as published by
 
 576 the Free Software Foundation; either version 2 of the License, or
 
 577 (at your option) any later version.
 
 579 This program is distributed in the hope that it will be useful,
 
 580 but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 581 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 582 GNU General Public License for more details.
 
 583 You should have received a copy of the GNU General Public License
 
 584 along with this program; if not, write to the Free Software
 
 585 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.