da38640c9244af6665e3116c89a6963aa5645c1c
[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              prepare_execute_query prepare_query);
11
12 sub conv_i {
13   my ($value, $default) = @_;
14   return (defined($value) && "$value" ne "") ? $value * 1 : $default;
15 }
16
17 sub conv_date {
18   my ($value) = @_;
19   return (defined($value) && "$value" ne "") ? $value : undef;
20 }
21
22 sub conv_dateq {
23   my ($value) = @_;
24   if (defined($value) && "$value" ne "") {
25     $value =~ s/\'/\'\'/g;
26     return "'$value'";
27   }
28   return "NULL";
29 }
30
31 sub do_query {
32   $main::lxdebug->enter_sub(2);
33
34   my ($form, $dbh, $query) = splice(@_, 0, 3);
35
36   dump_query(LXDebug::QUERY, '', $query, @_);
37
38   if (0 == scalar(@_)) {
39     $dbh->do($query) || $form->dberror($query);
40   } else {
41     $dbh->do($query, undef, @_) ||
42       $form->dberror($query . " (" . join(", ", @_) . ")");
43   }
44
45   $main::lxdebug->leave_sub(2);
46 }
47
48 sub selectrow_query { &selectfirst_array_query }
49
50 sub do_statement {
51   $main::lxdebug->enter_sub(2);
52
53   my ($form, $sth, $query) = splice(@_, 0, 3);
54
55   dump_query(LXDebug::QUERY, '', $query, @_);
56
57   if (0 == scalar(@_)) {
58     $sth->execute() || $form->dberror($query);
59   } else {
60     $sth->execute(@_) ||
61       $form->dberror($query . " (" . join(", ", @_) . ")");
62   }
63
64   $main::lxdebug->leave_sub(2);
65 }
66
67 sub dump_query {
68   my ($level, $msg, $query) = splice(@_, 0, 3);
69
70   while ($query =~ /\?/) {
71     my $value = shift(@_);
72     $value =~ s/\'/\\\'/g;
73     $value = "'${value}'";
74     $query =~ s/\?/$value/;
75   }
76
77   $query =~ s/[\n\s]+/ /g;
78
79   $msg .= " " if ($msg);
80
81   $main::lxdebug->message($level, $msg . $query);
82 }
83
84 sub quote_db_date {
85   my ($str) = @_;
86
87   return "NULL" unless defined $str;
88   return "current_date" if $str =~ /current_date/;
89
90   $str =~ s/'/''/g;
91   return "'$str'";
92 }
93
94 sub prepare_query {
95   $main::lxdebug->enter_sub(2);
96
97   my ($form, $dbh, $query) = splice(@_, 0, 3);
98
99   dump_query(LXDebug::QUERY, '', $query, @_);
100
101   my $sth = $dbh->prepare($query) || $form->dberror($query);
102
103   $main::lxdebug->leave_sub(2);
104
105   return $sth;
106 }
107
108 sub prepare_execute_query {
109   $main::lxdebug->enter_sub(2);
110
111   my ($form, $dbh, $query) = splice(@_, 0, 3);
112
113   dump_query(LXDebug::QUERY, '', $query, @_);
114
115   my $sth = $dbh->prepare($query) || $form->dberror($query);
116   if (scalar(@_) != 0) {
117     $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
118   } else {
119     $sth->execute() || $form->dberror($query);
120   }
121
122   $main::lxdebug->leave_sub(2);
123
124   return $sth;
125 }
126
127 sub selectall_hashref_query {
128   $main::lxdebug->enter_sub(2);
129
130   my ($form, $dbh, $query) = splice(@_, 0, 3);
131
132   my $sth = prepare_execute_query($form, $dbh, $query, @_);
133   my $result = [];
134   while (my $ref = $sth->fetchrow_hashref()) {
135     push(@{ $result }, $ref);
136   }
137   $sth->finish();
138
139   $main::lxdebug->leave_sub(2);
140
141   return $result;
142 }
143
144 sub selectall_array_query {
145   $main::lxdebug->enter_sub(2);
146
147   my ($form, $dbh, $query) = splice(@_, 0, 3);
148
149   my $sth = prepare_execute_query($form, $dbh, $query, @_);
150   my @result;
151   while (my ($value) = $sth->fetchrow_array()) {
152     push(@result, $value);
153   }
154   $sth->finish();
155
156   $main::lxdebug->leave_sub(2);
157
158   return @result;
159 }
160
161 sub selectfirst_hashref_query {
162   $main::lxdebug->enter_sub(2);
163
164   my ($form, $dbh, $query) = splice(@_, 0, 3);
165
166   my $sth = prepare_execute_query($form, $dbh, $query, @_);
167   my $ref = $sth->fetchrow_hashref();
168   $sth->finish();
169
170   $main::lxdebug->leave_sub(2);
171
172   return $ref;
173 }
174
175 sub selectfirst_array_query {
176   $main::lxdebug->enter_sub(2);
177
178   my ($form, $dbh, $query) = splice(@_, 0, 3);
179
180   my $sth = prepare_execute_query($form, $dbh, $query, @_);
181   my @ret = $sth->fetchrow_array();
182   $sth->finish();
183
184   $main::lxdebug->leave_sub(2);
185
186   return @ret;
187 }
188
189 1;
190
191
192 __END__
193
194 =head1 NAME
195
196 SL::DBUTils.pm: All about Databaseconections in Lx
197
198 =head1 SYNOPSIS
199
200   use DBUtils;
201   
202   conv_i($str, $default)
203   conv_date($str)
204   conv_dateq($str)
205   quote_db_date($date)
206
207   do_query($form, $dbh, $query)
208   do_statement($form, $sth, $query)
209
210   dump_query($level, $msg, $query)
211   prepare_execute_query($form, $dbh, $query)
212
213   my $all_results_ref       = selectall_hashref_query($form, $dbh, $query)
214   my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
215   
216   my @first_result =  selectfirst_array_query($form, $dbh, $query);  # ==
217   my @first_result =  selectrow_query($form, $dbh, $query);
218   
219     
220 =head1 DESCRIPTION
221
222 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.
223
224 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.
225
226 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
227   - $form is used for error handling only. It can be omitted in theory, but should not.
228   - $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!
229
230
231 Every function here should accomplish the follwing things:
232   - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
233   - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
234   - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
235
236 Note that binding is not perfect here either... 
237   
238 =head2 QUOTING FUNCTIONS
239
240 =over 4
241
242 =item conv_i STR
243
244 =item conv_i STR,DEFAULT
245
246 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
247
248 =item conv_date STR
249
250 Converts STR to a date string. If STR is emptry, returns undef.
251
252 =item conv_dateq STR
253
254 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
255
256 =item quote_db_date STR
257
258 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.
259 Returns 'NULL' if STR is empty.
260
261 =back
262
263 =head2 QUERY FUNCTIONS
264
265 =over 4
266
267 =item do_query FORM,DBH,QUERY,ARRAY
268
269 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.
270
271 =item do_statement FORM,STH,QUERY,ARRAY
272
273 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.
274
275 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
276
277 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
278
279 =back
280
281 =head2 RETRIEVAL FUNCTIONS
282
283 =over 4
284
285 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
286
287 =item selectrow_query FORM,DBH,QUERY,ARRAY
288
289 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. 
290
291 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
292
293 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. 
294
295 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
296
297 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.
298
299 =back
300
301 =head2 DEBUG FUNCTIONS
302
303 =over 4
304
305 =item dump_query LEVEL,MSG,QUERY,ARRAY
306
307 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.
308
309 =back
310
311 =head1 EXAMPLES
312
313 =over 4
314
315 =item Retrieving a whole table:
316
317   $query = qq|SELECT id, pricegroup FROM pricegroup|;
318   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
319
320 =item Retrieving a single value:
321
322   $query = qq|SELECT nextval('glid')|;
323   ($new_id) = selectrow_query($form, $dbh, $query);
324
325 =item Using binding values:
326
327   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
328   do_query($form, $dbh, $query, $id);
329
330 =item A more complicated example, using dynamic binding values:
331
332   my @values;
333     
334   if ($form->{language_values} ne "") {
335     $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
336                   FROM language l
337                   LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
338     @values = (conv_i($form->{id}));
339   } else {
340     $query = qq|SELECT id, description FROM language|;
341   }
342   
343   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
344
345 =back
346
347 =head1 SEE ALSO
348
349 =head1 MODULE AUTHORS
350
351 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
352 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
353  
354 =head1 DOCUMENTATION AUTHORS
355
356 Udo Spallek E<lt>udono@gmx.netE<gt>
357 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
358
359 =head1 COPYRIGHT AND LICENSE
360
361 Copyright 2007 by Lx-Office Community
362
363 This program is free software; you can redistribute it and/or modify
364 it under the terms of the GNU General Public License as published by
365 the Free Software Foundation; either version 2 of the License, or
366 (at your option) any later version.
367
368 This program is distributed in the hope that it will be useful,
369 but WITHOUT ANY WARRANTY; without even the implied warranty of
370 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
371 GNU General Public License for more details.
372 You should have received a copy of the GNU General Public License
373 along with this program; if not, write to the Free Software
374 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
375 =cut