Vergessener Lauf von locales.pl
[kivitendo-erp.git] / SL / DBUtils.pm
index da38640..a3b9826 100644 (file)
@@ -7,6 +7,7 @@ require Exporter;
              dump_query quote_db_date
              selectfirst_hashref_query selectfirst_array_query
              selectall_hashref_query selectall_array_query
+             selectall_as_map
              prepare_execute_query prepare_query);
 
 sub conv_i {
@@ -67,6 +68,12 @@ sub do_statement {
 sub dump_query {
   my ($level, $msg, $query) = splice(@_, 0, 3);
 
+  my $filename = $self_filename = 'SL/DBUtils.pm';
+  my $caller_level;
+  while ($filename eq $self_filename) {
+    (undef, $filename, $line, $subroutine) = caller $caller_level++;
+  }
+
   while ($query =~ /\?/) {
     my $value = shift(@_);
     $value =~ s/\'/\\\'/g;
@@ -78,7 +85,9 @@ sub dump_query {
 
   $msg .= " " if ($msg);
 
-  $main::lxdebug->message($level, $msg . $query);
+  my $info = "$subroutine called from $filename:$line\n";
+
+  $main::lxdebug->message($level, $info . $msg . $query);
 }
 
 sub quote_db_date {
@@ -87,7 +96,7 @@ sub quote_db_date {
   return "NULL" unless defined $str;
   return "current_date" if $str =~ /current_date/;
 
-  $str =~ s/'/''/g;
+  $str =~ s/\'/\'\'/g;
   return "'$str'";
 }
 
@@ -138,7 +147,7 @@ sub selectall_hashref_query {
 
   $main::lxdebug->leave_sub(2);
 
-  return $result;
+  return wantarray ? @{ $result } : $result;
 }
 
 sub selectall_array_query {
@@ -186,6 +195,31 @@ sub selectfirst_array_query {
   return @ret;
 }
 
+sub selectall_as_map {
+  $main::lxdebug->enter_sub(2);
+
+  my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
+
+  my $sth = prepare_execute_query($form, $dbh, $query, @_);
+
+  my %hash;
+  if ('' eq ref $value_col) {
+    while (my $ref = $sth->fetchrow_hashref()) {
+      $hash{$ref->{$key_col}} = $ref->{$value_col};
+    }
+  } else {
+    while (my $ref = $sth->fetchrow_hashref()) {
+      $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
+    }
+  }
+
+  $sth->finish();
+
+  $main::lxdebug->leave_sub(2);
+
+  return %hash;
+}
+
 1;
 
 
@@ -296,6 +330,10 @@ Prepares and executes a query using DBUtils functions, retireves the first row f
 
 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.
 
+=item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
+
+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.
+
 =back
 
 =head2 DEBUG FUNCTIONS