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   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 152   while (my $ref = $sth->fetchrow_hashref()) {
 
 153     push(@{ $result }, $ref);
 
 157   $main::lxdebug->leave_sub(2);
 
 159   return wantarray ? @{ $result } : $result;
 
 162 sub selectall_array_query {
 
 163   $main::lxdebug->enter_sub(2);
 
 165   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 167   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 169   while (my ($value) = $sth->fetchrow_array()) {
 
 170     push(@result, $value);
 
 174   $main::lxdebug->leave_sub(2);
 
 179 sub selectfirst_hashref_query {
 
 180   $main::lxdebug->enter_sub(2);
 
 182   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 184   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 185   my $ref = $sth->fetchrow_hashref();
 
 188   $main::lxdebug->leave_sub(2);
 
 193 sub selectfirst_array_query {
 
 194   $main::lxdebug->enter_sub(2);
 
 196   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 198   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 199   my @ret = $sth->fetchrow_array();
 
 202   $main::lxdebug->leave_sub(2);
 
 207 sub selectall_as_map {
 
 208   $main::lxdebug->enter_sub(2);
 
 210   my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
 
 212   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 215   if ('' eq ref $value_col) {
 
 216     while (my $ref = $sth->fetchrow_hashref()) {
 
 217       $hash{$ref->{$key_col}} = $ref->{$value_col};
 
 220     while (my $ref = $sth->fetchrow_hashref()) {
 
 221       $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
 
 227   $main::lxdebug->leave_sub(2);
 
 232 sub create_sort_spec {
 
 233   $main::lxdebug->enter_sub(2);
 
 238   $params{defs}    || die;
 
 239   $params{default} || die;
 
 241   # The definition of valid columns to sort by.
 
 242   my $defs        = $params{defs};
 
 244   # The column name to sort by. Use the default column name if none was given.
 
 245   my %result      = ( 'column' => $params{column} || $params{default} );
 
 247   # Overwrite the column name with the default column name if the other one is not valid.
 
 248   $result{column} = $params{default} unless ($defs->{ $result{column} });
 
 250   # The sort direction. true means 'sort ascending', false means 'sort descending'.
 
 251   $result{dir}    = defined $params{dir}         ? $params{dir}
 
 252                   : defined $params{default_dir} ? $params{default_dir}
 
 254   $result{dir}    = $result{dir} ?     1 :      0;
 
 255   my $asc_desc    = $result{dir} ? 'ASC' : 'DESC';
 
 257   # Create the SQL code.
 
 258   my $cols        = $defs->{ $result{column} };
 
 259   $result{sql}    = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
 
 261   $main::lxdebug->leave_sub(2);
 
 266 sub does_table_exist {
 
 267   $main::lxdebug->enter_sub(2);
 
 275     my $sth = $dbh->table_info('', '', $table, 'TABLE');
 
 277       $result = $sth->fetchrow_hashref();
 
 282   $main::lxdebug->leave_sub(2);
 
 287 # add token to values.
 
 293 #    val => [ 23, 34, 17 ]
 
 296 #  will append to the given arrays:
 
 297 #   -> 'id IN (?, ?, ?)'
 
 298 #   -> (conv_i(23), conv_i(34), conv_i(17))
 
 301 #   - don't care if one or multiple values are given. singlewill result in 'col = ?'
 
 302 #   - pass escape routines
 
 303 #   - expand for future method
 
 304 #   - no need to type "push @where_tokens, 'id = ?'" over and over again
 
 306   my $tokens = shift() || [];
 
 307   my $values = shift() || [];
 
 309   my $col    = $params{col};
 
 310   my $val    = $params{val};
 
 311   my $method = $params{method} || '=';
 
 312   my $escape = $params{esc} || sub { $_ };
 
 314   $val = [ $val ] unless ref $val eq 'ARRAY';
 
 324       return scalar @_ >  1 ? sprintf '%s IN (%s)', $col, join ', ', ("?") x scalar @_
 
 325            : scalar @_ == 1 ? sprintf '%s = ?',     $col
 
 330   $method = $methods{$method} || $method;
 
 331   $escape = $escapes{$escape} || $escape;
 
 333   my $token = $method->($col, @{ $val });
 
 334   my @vals  = map { $escape->($_) } @{ $val };
 
 336   return unless $token;
 
 338   push @{ $tokens }, $token;
 
 339   push @{ $values }, @vals;
 
 341   return ($token, @vals);
 
 351 SL::DBUTils.pm: All about Databaseconections in Lx
 
 357   conv_i($str, $default)
 
 362   do_query($form, $dbh, $query)
 
 363   do_statement($form, $sth, $query)
 
 365   dump_query($level, $msg, $query)
 
 366   prepare_execute_query($form, $dbh, $query)
 
 368   my $all_results_ref       = selectall_hashref_query($form, $dbh, $query)
 
 369   my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
 
 371   my @first_result =  selectfirst_array_query($form, $dbh, $query);  # ==
 
 372   my @first_result =  selectrow_query($form, $dbh, $query);
 
 374   my %sort_spec = create_sort_spec(%params);
 
 378 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.
 
 380 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.
 
 382 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
 
 383   - $form is used for error handling only. It can be omitted in theory, but should not.
 
 384   - $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!
 
 387 Every function here should accomplish the follwing things:
 
 388   - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
 
 389   - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
 
 390   - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
 
 392 Note that binding is not perfect here either...
 
 394 =head2 QUOTING FUNCTIONS
 
 400 =item conv_i STR,DEFAULT
 
 402 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
 
 406 Converts STR to a date string. If STR is emptry, returns undef.
 
 410 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
 
 412 =item quote_db_date STR
 
 414 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.
 
 415 Returns 'NULL' if STR is empty.
 
 419 =head2 QUERY FUNCTIONS
 
 423 =item do_query FORM,DBH,QUERY,ARRAY
 
 425 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.
 
 427 Returns the result of DBI::do which is -1 in case of an error and the number of affected rows otherwise.
 
 429 =item do_statement FORM,STH,QUERY,ARRAY
 
 431 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.
 
 433 Returns the result of DBI::execute which is -1 in case of an error and the number of affected rows otherwise.
 
 435 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
 
 437 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
 
 441 =head2 RETRIEVAL FUNCTIONS
 
 445 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
 
 447 =item selectrow_query FORM,DBH,QUERY,ARRAY
 
 449 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.
 
 451 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
 
 453 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.
 
 455 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
 
 457 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.
 
 459 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
 
 461 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.
 
 465 =head2 UTILITY FUNCTIONS
 
 469 =item create_sort_spec
 
 472     defs        => { },         # mandatory
 
 473     default     => 'name',      # mandatory
 
 483 This function simplifies the creation of SQL code for sorting
 
 484 columns. It uses a hashref of valid column names, the column name and
 
 485 direction requested by the user, the application defaults for the
 
 486 column name and the direction and returns the actual column name,
 
 487 direction and SQL code that can be used directly in a query.
 
 489 The parameter 'defs' is a hash reference. The keys are the column
 
 490 names as they may come from the application. The values are either
 
 491 scalars with SQL code or array references of SQL code. Example:
 
 493 'defs' => { 'customername' => 'lower(customer.name)',
 
 494             'address'      => [ 'lower(customer.city)', 'lower(customer.street)' ], }
 
 496 'default' is the default column name to sort by. It must be a key of
 
 497 'defs' and should not be come from user input.
 
 499 The 'column' parameter is the column name as requested by the
 
 500 application (e.g. if the user clicked on a column header in a
 
 501 report). If it is invalid then the 'default' parameter will be used
 
 504 'default_dir' is the default sort direction. A true value means 'sort
 
 505 ascending', a false one 'sort descending'. 'default_dir' defaults to
 
 508 The 'dir' parameter is the sort direction as requested by the
 
 509 application (e.g. if the user clicked on a column header in a
 
 510 report). If it is undefined then the 'default_dir' parameter will be
 
 515 =head2 DEBUG FUNCTIONS
 
 519 =item dump_query LEVEL,MSG,QUERY,ARRAY
 
 521 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.
 
 529 =item Retrieving a whole table:
 
 531   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 532   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 534 =item Retrieving a single value:
 
 536   $query = qq|SELECT nextval('glid')|;
 
 537   ($new_id) = selectrow_query($form, $dbh, $query);
 
 539 =item Using binding values:
 
 541   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 542   do_query($form, $dbh, $query, $id);
 
 544 =item A more complicated example, using dynamic binding values:
 
 548   if ($form->{language_values} ne "") {
 
 549     $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
 551                   LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
 
 552     @values = (conv_i($form->{id}));
 
 554     $query = qq|SELECT id, description FROM language|;
 
 557   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
 561 =head1 MODULE AUTHORS
 
 563 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
 
 564 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 566 =head1 DOCUMENTATION AUTHORS
 
 568 Udo Spallek E<lt>udono@gmx.netE<gt>
 
 569 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 571 =head1 COPYRIGHT AND LICENSE
 
 573 Copyright 2007 by Lx-Office Community
 
 575 This program is free software; you can redistribute it and/or modify
 
 576 it under the terms of the GNU General Public License as published by
 
 577 the Free Software Foundation; either version 2 of the License, or
 
 578 (at your option) any later version.
 
 580 This program is distributed in the hope that it will be useful,
 
 581 but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 582 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 583 GNU General Public License for more details.
 
 584 You should have received a copy of the GNU General Public License
 
 585 along with this program; if not, write to the Free Software
 
 586 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.