Kosmetik.
[kivitendo-erp.git] / SL / DBUtils.pm
1 package SL::DBUtils;
2
3 require Exporter;
4 @ISA = qw(Exporter);
5
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
10              selectall_as_map
11              prepare_execute_query prepare_query
12              create_sort_spec);
13
14 sub conv_i {
15   my ($value, $default) = @_;
16   return (defined($value) && "$value" ne "") ? $value * 1 : $default;
17 }
18
19 sub conv_date {
20   my ($value) = @_;
21   return (defined($value) && "$value" ne "") ? $value : undef;
22 }
23
24 sub conv_dateq {
25   my ($value) = @_;
26   if (defined($value) && "$value" ne "") {
27     $value =~ s/\'/\'\'/g;
28     return "'$value'";
29   }
30   return "NULL";
31 }
32
33 sub do_query {
34   $main::lxdebug->enter_sub(2);
35
36   my ($form, $dbh, $query) = splice(@_, 0, 3);
37
38   dump_query(LXDebug::QUERY, '', $query, @_);
39
40   if (0 == scalar(@_)) {
41     $dbh->do($query) || $form->dberror($query);
42   } else {
43     $dbh->do($query, undef, @_) ||
44       $form->dberror($query . " (" . join(", ", @_) . ")");
45   }
46
47   $main::lxdebug->leave_sub(2);
48 }
49
50 sub selectrow_query { &selectfirst_array_query }
51
52 sub do_statement {
53   $main::lxdebug->enter_sub(2);
54
55   my ($form, $sth, $query) = splice(@_, 0, 3);
56
57   dump_query(LXDebug::QUERY, '', $query, @_);
58
59   if (0 == scalar(@_)) {
60     $sth->execute()   || $form->dberror($query);
61   } else {
62     $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
63   }
64
65   $main::lxdebug->leave_sub(2);
66 }
67
68 sub dump_query {
69   my ($level, $msg, $query) = splice(@_, 0, 3);
70
71   my $filename = $self_filename = 'SL/DBUtils.pm';
72   my $caller_level;
73   while ($filename eq $self_filename) {
74     (undef, $filename, $line, $subroutine) = caller $caller_level++;
75   }
76
77   while ($query =~ /\?/) {
78     my $value = shift(@_);
79     $value =~ s/\'/\\\'/g;
80     $value = "'${value}'";
81     $query =~ s/\?/$value/;
82   }
83
84   $query =~ s/[\n\s]+/ /g;
85
86   $msg .= " " if ($msg);
87
88   my $info = "$subroutine called from $filename:$line\n";
89
90   $main::lxdebug->message($level, $info . $msg . $query);
91 }
92
93 sub quote_db_date {
94   my ($str) = @_;
95
96   return "NULL" unless defined $str;
97   return "current_date" if $str =~ /current_date/;
98
99   $str =~ s/\'/\'\'/g;
100   return "'$str'";
101 }
102
103 sub prepare_query {
104   $main::lxdebug->enter_sub(2);
105
106   my ($form, $dbh, $query) = splice(@_, 0, 3);
107
108   dump_query(LXDebug::QUERY, '', $query, @_);
109
110   my $sth = $dbh->prepare($query) || $form->dberror($query);
111
112   $main::lxdebug->leave_sub(2);
113
114   return $sth;
115 }
116
117 sub prepare_execute_query {
118   $main::lxdebug->enter_sub(2);
119
120   my ($form, $dbh, $query) = splice(@_, 0, 3);
121
122   dump_query(LXDebug::QUERY, '', $query, @_);
123
124   my $sth = $dbh->prepare($query) || $form->dberror($query);
125   if (scalar(@_) != 0) {
126     $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
127   } else {
128     $sth->execute() || $form->dberror($query);
129   }
130
131   $main::lxdebug->leave_sub(2);
132
133   return $sth;
134 }
135
136 sub selectall_hashref_query {
137   $main::lxdebug->enter_sub(2);
138
139   my ($form, $dbh, $query) = splice(@_, 0, 3);
140
141   my $sth = prepare_execute_query($form, $dbh, $query, @_);
142   my $result = [];
143   while (my $ref = $sth->fetchrow_hashref()) {
144     push(@{ $result }, $ref);
145   }
146   $sth->finish();
147
148   $main::lxdebug->leave_sub(2);
149
150   return wantarray ? @{ $result } : $result;
151 }
152
153 sub selectall_array_query {
154   $main::lxdebug->enter_sub(2);
155
156   my ($form, $dbh, $query) = splice(@_, 0, 3);
157
158   my $sth = prepare_execute_query($form, $dbh, $query, @_);
159   my @result;
160   while (my ($value) = $sth->fetchrow_array()) {
161     push(@result, $value);
162   }
163   $sth->finish();
164
165   $main::lxdebug->leave_sub(2);
166
167   return @result;
168 }
169
170 sub selectfirst_hashref_query {
171   $main::lxdebug->enter_sub(2);
172
173   my ($form, $dbh, $query) = splice(@_, 0, 3);
174
175   my $sth = prepare_execute_query($form, $dbh, $query, @_);
176   my $ref = $sth->fetchrow_hashref();
177   $sth->finish();
178
179   $main::lxdebug->leave_sub(2);
180
181   return $ref;
182 }
183
184 sub selectfirst_array_query {
185   $main::lxdebug->enter_sub(2);
186
187   my ($form, $dbh, $query) = splice(@_, 0, 3);
188
189   my $sth = prepare_execute_query($form, $dbh, $query, @_);
190   my @ret = $sth->fetchrow_array();
191   $sth->finish();
192
193   $main::lxdebug->leave_sub(2);
194
195   return @ret;
196 }
197
198 sub selectall_as_map {
199   $main::lxdebug->enter_sub(2);
200
201   my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
202
203   my $sth = prepare_execute_query($form, $dbh, $query, @_);
204
205   my %hash;
206   if ('' eq ref $value_col) {
207     while (my $ref = $sth->fetchrow_hashref()) {
208       $hash{$ref->{$key_col}} = $ref->{$value_col};
209     }
210   } else {
211     while (my $ref = $sth->fetchrow_hashref()) {
212       $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
213     }
214   }
215
216   $sth->finish();
217
218   $main::lxdebug->leave_sub(2);
219
220   return %hash;
221 }
222
223 sub create_sort_spec {
224   $main::lxdebug->enter_sub(2);
225
226   my %params = @_;
227
228   # Safety check:
229   $params{defs}    || die;
230   $params{default} || die;
231
232   # The definition of valid columns to sort by.
233   my $defs        = $params{defs};
234
235   # The column name to sort by. Use the default column name if none was given.
236   my %result      = ( 'column' => $params{column} || $params{default} );
237
238   # Overwrite the column name with the default column name if the other one is not valid.
239   $result{column} = $params{default} unless ($defs->{ $result{column} });
240
241   # The sort direction. true means 'sort ascending', false means 'sort descending'.
242   $result{dir}    = defined $params{dir}         ? $params{dir}
243                   : defined $params{default_dir} ? $params{default_dir}
244                   :                                1;
245   $result{dir}    = $result{dir} ?     1 :      0;
246   my $asc_desc    = $result{dir} ? 'ASC' : 'DESC';
247
248   # Create the SQL code.
249   my $cols        = $defs->{ $result{column} };
250   $result{sql}    = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
251
252   $main::lxdebug->leave_sub(2);
253
254   return %result;
255 }
256
257 1;
258
259
260 __END__
261
262 =head1 NAME
263
264 SL::DBUTils.pm: All about Databaseconections in Lx
265
266 =head1 SYNOPSIS
267
268   use DBUtils;
269   
270   conv_i($str, $default)
271   conv_date($str)
272   conv_dateq($str)
273   quote_db_date($date)
274
275   do_query($form, $dbh, $query)
276   do_statement($form, $sth, $query)
277
278   dump_query($level, $msg, $query)
279   prepare_execute_query($form, $dbh, $query)
280
281   my $all_results_ref       = selectall_hashref_query($form, $dbh, $query)
282   my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
283   
284   my @first_result =  selectfirst_array_query($form, $dbh, $query);  # ==
285   my @first_result =  selectrow_query($form, $dbh, $query);
286   
287   my %sort_spec = create_sort_spec(%params);
288
289 =head1 DESCRIPTION
290
291 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.
292
293 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.
294
295 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
296   - $form is used for error handling only. It can be omitted in theory, but should not.
297   - $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!
298
299
300 Every function here should accomplish the follwing things:
301   - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
302   - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
303   - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
304
305 Note that binding is not perfect here either... 
306   
307 =head2 QUOTING FUNCTIONS
308
309 =over 4
310
311 =item conv_i STR
312
313 =item conv_i STR,DEFAULT
314
315 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
316
317 =item conv_date STR
318
319 Converts STR to a date string. If STR is emptry, returns undef.
320
321 =item conv_dateq STR
322
323 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
324
325 =item quote_db_date STR
326
327 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.
328 Returns 'NULL' if STR is empty.
329
330 =back
331
332 =head2 QUERY FUNCTIONS
333
334 =over 4
335
336 =item do_query FORM,DBH,QUERY,ARRAY
337
338 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.
339
340 =item do_statement FORM,STH,QUERY,ARRAY
341
342 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.
343
344 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
345
346 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
347
348 =back
349
350 =head2 RETRIEVAL FUNCTIONS
351
352 =over 4
353
354 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
355
356 =item selectrow_query FORM,DBH,QUERY,ARRAY
357
358 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. 
359
360 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
361
362 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. 
363
364 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
365
366 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.
367
368 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
369
370 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.
371
372 =back
373
374 =head2 UTILITY FUNCTIONS
375
376 =over 4
377
378 =item create_sort_spec
379
380   params:
381     defs        => { },         # mandatory
382     default     => 'name',      # mandatory
383     column      => 'name',
384     default_dir => 0|1,
385     dir         => 0|1,
386
387   returns hash:
388     column      => 'name',
389     dir         => 0|1,
390     sql         => 'SQL code',
391
392 This function simplifies the creation of SQL code for sorting
393 columns. It uses a hashref of valid column names, the column name and
394 direction requested by the user, the application defaults for the
395 column name and the direction and returns the actual column name,
396 direction and SQL code that can be used directly in a query.
397
398 The parameter 'defs' is a hash reference. The keys are the column
399 names as they may come from the application. The values are either
400 scalars with SQL code or array references of SQL code. Example:
401
402 'defs' => { 'customername' => 'lower(customer.name)',
403             'address'      => [ 'lower(customer.city)', 'lower(customer.street)' ], }
404
405 'default' is the default column name to sort by. It must be a key of
406 'defs' and should not be come from user input.
407
408 The 'column' parameter is the column name as requested by the
409 application (e.g. if the user clicked on a column header in a
410 report). If it is invalid then the 'default' parameter will be used
411 instead.
412
413 'default_dir' is the default sort direction. A true value means 'sort
414 ascending', a false one 'sort descending'. 'default_dir' defaults to
415 '1' if undefined.
416
417 The 'dir' parameter is the sort direction as requested by the
418 application (e.g. if the user clicked on a column header in a
419 report). If it is undefined then the 'default_dir' parameter will be
420 used instead.
421
422 =back
423
424 =head2 DEBUG FUNCTIONS
425
426 =over 4
427
428 =item dump_query LEVEL,MSG,QUERY,ARRAY
429
430 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.
431
432 =back
433
434 =head1 EXAMPLES
435
436 =over 4
437
438 =item Retrieving a whole table:
439
440   $query = qq|SELECT id, pricegroup FROM pricegroup|;
441   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
442
443 =item Retrieving a single value:
444
445   $query = qq|SELECT nextval('glid')|;
446   ($new_id) = selectrow_query($form, $dbh, $query);
447
448 =item Using binding values:
449
450   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
451   do_query($form, $dbh, $query, $id);
452
453 =item A more complicated example, using dynamic binding values:
454
455   my @values;
456     
457   if ($form->{language_values} ne "") {
458     $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
459                   FROM language l
460                   LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
461     @values = (conv_i($form->{id}));
462   } else {
463     $query = qq|SELECT id, description FROM language|;
464   }
465   
466   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
467
468 =back
469
470 =head1 SEE ALSO
471
472 =head1 MODULE AUTHORS
473
474 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
475 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
476  
477 =head1 DOCUMENTATION AUTHORS
478
479 Udo Spallek E<lt>udono@gmx.netE<gt>
480 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
481
482 =head1 COPYRIGHT AND LICENSE
483
484 Copyright 2007 by Lx-Office Community
485
486 This program is free software; you can redistribute it and/or modify
487 it under the terms of the GNU General Public License as published by
488 the Free Software Foundation; either version 2 of the License, or
489 (at your option) any later version.
490
491 This program is distributed in the hope that it will be useful,
492 but WITHOUT ANY WARRANTY; without even the implied warranty of
493 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
494 GNU General Public License for more details.
495 You should have received a copy of the GNU General Public License
496 along with this program; if not, write to the Free Software
497 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
498 =cut