6 @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
 
  15   my ($value, $default) = @_;
 
  16   return (defined($value) && "$value" ne "") ? $value * 1 : $default;
 
  21   return (defined($value) && "$value" ne "") ? $value : undef;
 
  26   if (defined($value) && "$value" ne "") {
 
  27     $value =~ s/\'/\'\'/g;
 
  34   $main::lxdebug->enter_sub(2);
 
  36   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
  38   dump_query(LXDebug::QUERY, '', $query, @_);
 
  40   if (0 == scalar(@_)) {
 
  41     $dbh->do($query) || $form->dberror($query);
 
  43     $dbh->do($query, undef, @_) ||
 
  44       $form->dberror($query . " (" . join(", ", @_) . ")");
 
  47   $main::lxdebug->leave_sub(2);
 
  50 sub selectrow_query { &selectfirst_array_query }
 
  53   $main::lxdebug->enter_sub(2);
 
  55   my ($form, $sth, $query) = splice(@_, 0, 3);
 
  57   dump_query(LXDebug::QUERY, '', $query, @_);
 
  59   if (0 == scalar(@_)) {
 
  60     $sth->execute() || $form->dberror($query);
 
  63       $form->dberror($query . " (" . join(", ", @_) . ")");
 
  66   $main::lxdebug->leave_sub(2);
 
  70   my ($level, $msg, $query) = splice(@_, 0, 3);
 
  72   my $filename = $self_filename = 'SL/DBUtils.pm';
 
  74   while ($filename eq $self_filename) {
 
  75     (undef, $filename, $line, $subroutine) = caller $caller_level++;
 
  78   while ($query =~ /\?/) {
 
  79     my $value = shift(@_);
 
  80     $value =~ s/\'/\\\'/g;
 
  81     $value = "'${value}'";
 
  82     $query =~ s/\?/$value/;
 
  85   $query =~ s/[\n\s]+/ /g;
 
  87   $msg .= " " if ($msg);
 
  89   my $info = "$subroutine called from $filename:$line\n";
 
  91   $main::lxdebug->message($level, $info . $msg . $query);
 
  97   return "NULL" unless defined $str;
 
  98   return "current_date" if $str =~ /current_date/;
 
 105   $main::lxdebug->enter_sub(2);
 
 107   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 109   dump_query(LXDebug::QUERY, '', $query, @_);
 
 111   my $sth = $dbh->prepare($query) || $form->dberror($query);
 
 113   $main::lxdebug->leave_sub(2);
 
 118 sub prepare_execute_query {
 
 119   $main::lxdebug->enter_sub(2);
 
 121   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 123   dump_query(LXDebug::QUERY, '', $query, @_);
 
 125   my $sth = $dbh->prepare($query) || $form->dberror($query);
 
 126   if (scalar(@_) != 0) {
 
 127     $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
 
 129     $sth->execute() || $form->dberror($query);
 
 132   $main::lxdebug->leave_sub(2);
 
 137 sub selectall_hashref_query {
 
 138   $main::lxdebug->enter_sub(2);
 
 140   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 142   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 144   while (my $ref = $sth->fetchrow_hashref()) {
 
 145     push(@{ $result }, $ref);
 
 149   $main::lxdebug->leave_sub(2);
 
 151   return wantarray ? @{ $result } : $result;
 
 154 sub selectall_array_query {
 
 155   $main::lxdebug->enter_sub(2);
 
 157   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 159   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 161   while (my ($value) = $sth->fetchrow_array()) {
 
 162     push(@result, $value);
 
 166   $main::lxdebug->leave_sub(2);
 
 171 sub selectfirst_hashref_query {
 
 172   $main::lxdebug->enter_sub(2);
 
 174   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 176   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 177   my $ref = $sth->fetchrow_hashref();
 
 180   $main::lxdebug->leave_sub(2);
 
 185 sub selectfirst_array_query {
 
 186   $main::lxdebug->enter_sub(2);
 
 188   my ($form, $dbh, $query) = splice(@_, 0, 3);
 
 190   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 191   my @ret = $sth->fetchrow_array();
 
 194   $main::lxdebug->leave_sub(2);
 
 199 sub selectall_as_map {
 
 200   $main::lxdebug->enter_sub(2);
 
 202   my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
 
 204   my $sth = prepare_execute_query($form, $dbh, $query, @_);
 
 207   if ('' eq ref $value_col) {
 
 208     while (my $ref = $sth->fetchrow_hashref()) {
 
 209       $hash{$ref->{$key_col}} = $ref->{$value_col};
 
 212     while (my $ref = $sth->fetchrow_hashref()) {
 
 213       $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
 
 219   $main::lxdebug->leave_sub(2);
 
 224 sub create_sort_spec {
 
 225   $main::lxdebug->enter_sub(2);
 
 230   $params{defs}    || die;
 
 231   $params{default} || die;
 
 233   # The definition of valid columns to sort by.
 
 234   my $defs        = $params{defs};
 
 236   # The column name to sort by. Use the default column name if none was given.
 
 237   my %result      = ( 'column' => $params{column} || $params{default} );
 
 239   # Overwrite the column name with the default column name if the other one is not valid.
 
 240   $result{column} = $params{default} unless ($defs->{ $result{column} });
 
 242   # The sort direction. true means 'sort ascending', false means 'sort descending'.
 
 243   $result{dir}    = defined $params{dir}         ? $params{dir}
 
 244                   : defined $params{default_dir} ? $params{default_dir}
 
 246   $result{dir}    = $result{dir} ?     1 :      0;
 
 247   my $asc_desc    = $result{dir} ? 'ASC' : 'DESC';
 
 249   # Create the SQL code.
 
 250   my $cols        = $defs->{ $result{column} };
 
 251   $result{sql}    = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
 
 253   $main::lxdebug->leave_sub(2);
 
 265 SL::DBUTils.pm: All about Databaseconections in Lx
 
 271   conv_i($str, $default)
 
 276   do_query($form, $dbh, $query)
 
 277   do_statement($form, $sth, $query)
 
 279   dump_query($level, $msg, $query)
 
 280   prepare_execute_query($form, $dbh, $query)
 
 282   my $all_results_ref       = selectall_hashref_query($form, $dbh, $query)
 
 283   my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
 
 285   my @first_result =  selectfirst_array_query($form, $dbh, $query);  # ==
 
 286   my @first_result =  selectrow_query($form, $dbh, $query);
 
 288   my %sort_spec = create_sort_spec(%params);
 
 292 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.
 
 294 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.
 
 296 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
 
 297   - $form is used for error handling only. It can be omitted in theory, but should not.
 
 298   - $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!
 
 301 Every function here should accomplish the follwing things:
 
 302   - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
 
 303   - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
 
 304   - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
 
 306 Note that binding is not perfect here either... 
 
 308 =head2 QUOTING FUNCTIONS
 
 314 =item conv_i STR,DEFAULT
 
 316 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
 
 320 Converts STR to a date string. If STR is emptry, returns undef.
 
 324 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
 
 326 =item quote_db_date STR
 
 328 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.
 
 329 Returns 'NULL' if STR is empty.
 
 333 =head2 QUERY FUNCTIONS
 
 337 =item do_query FORM,DBH,QUERY,ARRAY
 
 339 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.
 
 341 =item do_statement FORM,STH,QUERY,ARRAY
 
 343 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.
 
 345 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
 
 347 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
 
 351 =head2 RETRIEVAL FUNCTIONS
 
 355 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
 
 357 =item selectrow_query FORM,DBH,QUERY,ARRAY
 
 359 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. 
 
 361 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
 
 363 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. 
 
 365 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
 
 367 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.
 
 369 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
 
 371 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.
 
 375 =head2 UTILITY FUNCTIONS
 
 379 =item create_sort_spec
 
 382     defs        => { },         # mandatory
 
 383     default     => 'name',      # mandatory
 
 393 This function simplifies the creation of SQL code for sorting
 
 394 columns. It uses a hashref of valid column names, the column name and
 
 395 direction requested by the user, the application defaults for the
 
 396 column name and the direction and returns the actual column name,
 
 397 direction and SQL code that can be used directly in a query.
 
 399 The parameter 'defs' is a hash reference. The keys are the column
 
 400 names as they may come from the application. The values are either
 
 401 scalars with SQL code or array references of SQL code. Example:
 
 403 'defs' => { 'customername' => 'lower(customer.name)',
 
 404             'address'      => [ 'lower(customer.city)', 'lower(customer.street)' ], }
 
 406 'default' is the default column name to sort by. It must be a key of
 
 407 'defs' and should not be come from user input.
 
 409 The 'column' parameter is the column name as requested by the
 
 410 application (e.g. if the user clicked on a column header in a
 
 411 report). If it is invalid then the 'default' parameter will be used
 
 414 'default_dir' is the default sort direction. A true value means 'sort
 
 415 ascending', a false one 'sort descending'. 'default_dir' defaults to
 
 418 The 'dir' parameter is the sort direction as requested by the
 
 419 application (e.g. if the user clicked on a column header in a
 
 420 report). If it is undefined then the 'default_dir' parameter will be
 
 425 =head2 DEBUG FUNCTIONS
 
 429 =item dump_query LEVEL,MSG,QUERY,ARRAY
 
 431 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.
 
 439 =item Retrieving a whole table:
 
 441   $query = qq|SELECT id, pricegroup FROM pricegroup|;
 
 442   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
 
 444 =item Retrieving a single value:
 
 446   $query = qq|SELECT nextval('glid')|;
 
 447   ($new_id) = selectrow_query($form, $dbh, $query);
 
 449 =item Using binding values:
 
 451   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
 
 452   do_query($form, $dbh, $query, $id);
 
 454 =item A more complicated example, using dynamic binding values:
 
 458   if ($form->{language_values} ne "") {
 
 459     $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
 
 461                   LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
 
 462     @values = (conv_i($form->{id}));
 
 464     $query = qq|SELECT id, description FROM language|;
 
 467   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
 
 473 =head1 MODULE AUTHORS
 
 475 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
 
 476 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 478 =head1 DOCUMENTATION AUTHORS
 
 480 Udo Spallek E<lt>udono@gmx.netE<gt>
 
 481 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
 
 483 =head1 COPYRIGHT AND LICENSE
 
 485 Copyright 2007 by Lx-Office Community
 
 487 This program is free software; you can redistribute it and/or modify
 
 488 it under the terms of the GNU General Public License as published by
 
 489 the Free Software Foundation; either version 2 of the License, or
 
 490 (at your option) any later version.
 
 492 This program is distributed in the hope that it will be useful,
 
 493 but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 494 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 495 GNU General Public License for more details.
 
 496 You should have received a copy of the GNU General Public License
 
 497 along with this program; if not, write to the Free Software
 
 498 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.