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
12 create_sort_spec does_table_exist
16 my ($value, $default) = @_;
17 return (defined($value) && "$value" ne "") ? $value * 1 : $default;
22 return (defined($value) && "$value" ne "") ? $value : undef;
27 if (defined($value) && "$value" ne "") {
28 $value =~ s/\'/\'\'/g;
35 $main::lxdebug->enter_sub(2);
37 my ($form, $dbh, $query) = splice(@_, 0, 3);
39 dump_query(LXDebug::QUERY, '', $query, @_);
42 if (0 == scalar(@_)) {
43 $result = $dbh->do($query) || $form->dberror($query);
45 $result = $dbh->do($query, undef, @_) || $form->dberror($query . " (" . join(", ", @_) . ")");
48 $main::lxdebug->leave_sub(2);
53 sub selectrow_query { &selectfirst_array_query }
56 $main::lxdebug->enter_sub(2);
58 my ($form, $sth, $query) = splice(@_, 0, 3);
60 dump_query(LXDebug::QUERY, '', $query, @_);
63 if (0 == scalar(@_)) {
64 $result = $sth->execute() || $form->dberror($query);
66 $result = $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
69 $main::lxdebug->leave_sub(2);
75 my ($level, $msg, $query) = splice(@_, 0, 3);
77 my $filename = $self_filename = 'SL/DBUtils.pm';
79 while ($filename eq $self_filename) {
80 (undef, $filename, $line, $subroutine) = caller $caller_level++;
83 while ($query =~ /\?/) {
84 my $value = shift(@_);
85 $value =~ s/\'/\\\'/g;
86 $value = "'${value}'";
87 $query =~ s/\?/$value/;
90 $query =~ s/[\n\s]+/ /g;
92 $msg .= " " if ($msg);
94 my $info = "$subroutine called from $filename:$line\n";
96 $main::lxdebug->message($level, $info . $msg . $query);
102 return "NULL" unless defined $str;
103 return "current_date" if $str =~ /current_date/;
110 $main::lxdebug->enter_sub(2);
112 my ($form, $dbh, $query) = splice(@_, 0, 3);
114 dump_query(LXDebug::QUERY, '', $query, @_);
116 my $sth = $dbh->prepare($query) || $form->dberror($query);
118 $main::lxdebug->leave_sub(2);
123 sub prepare_execute_query {
124 $main::lxdebug->enter_sub(2);
126 my ($form, $dbh, $query) = splice(@_, 0, 3);
128 dump_query(LXDebug::QUERY, '', $query, @_);
130 my $sth = $dbh->prepare($query) || $form->dberror($query);
131 if (scalar(@_) != 0) {
132 $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
134 $sth->execute() || $form->dberror($query);
137 $main::lxdebug->leave_sub(2);
142 sub selectall_hashref_query {
143 $main::lxdebug->enter_sub(2);
145 my ($form, $dbh, $query) = splice(@_, 0, 3);
147 my $sth = prepare_execute_query($form, $dbh, $query, @_);
149 while (my $ref = $sth->fetchrow_hashref()) {
150 push(@{ $result }, $ref);
154 $main::lxdebug->leave_sub(2);
156 return wantarray ? @{ $result } : $result;
159 sub selectall_array_query {
160 $main::lxdebug->enter_sub(2);
162 my ($form, $dbh, $query) = splice(@_, 0, 3);
164 my $sth = prepare_execute_query($form, $dbh, $query, @_);
166 while (my ($value) = $sth->fetchrow_array()) {
167 push(@result, $value);
171 $main::lxdebug->leave_sub(2);
176 sub selectfirst_hashref_query {
177 $main::lxdebug->enter_sub(2);
179 my ($form, $dbh, $query) = splice(@_, 0, 3);
181 my $sth = prepare_execute_query($form, $dbh, $query, @_);
182 my $ref = $sth->fetchrow_hashref();
185 $main::lxdebug->leave_sub(2);
190 sub selectfirst_array_query {
191 $main::lxdebug->enter_sub(2);
193 my ($form, $dbh, $query) = splice(@_, 0, 3);
195 my $sth = prepare_execute_query($form, $dbh, $query, @_);
196 my @ret = $sth->fetchrow_array();
199 $main::lxdebug->leave_sub(2);
204 sub selectall_as_map {
205 $main::lxdebug->enter_sub(2);
207 my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
209 my $sth = prepare_execute_query($form, $dbh, $query, @_);
212 if ('' eq ref $value_col) {
213 while (my $ref = $sth->fetchrow_hashref()) {
214 $hash{$ref->{$key_col}} = $ref->{$value_col};
217 while (my $ref = $sth->fetchrow_hashref()) {
218 $hash{$ref->{$key_col}} = { map { $_ => $ref->{$_} } @{ $value_col } };
224 $main::lxdebug->leave_sub(2);
229 sub create_sort_spec {
230 $main::lxdebug->enter_sub(2);
235 $params{defs} || die;
236 $params{default} || die;
238 # The definition of valid columns to sort by.
239 my $defs = $params{defs};
241 # The column name to sort by. Use the default column name if none was given.
242 my %result = ( 'column' => $params{column} || $params{default} );
244 # Overwrite the column name with the default column name if the other one is not valid.
245 $result{column} = $params{default} unless ($defs->{ $result{column} });
247 # The sort direction. true means 'sort ascending', false means 'sort descending'.
248 $result{dir} = defined $params{dir} ? $params{dir}
249 : defined $params{default_dir} ? $params{default_dir}
251 $result{dir} = $result{dir} ? 1 : 0;
252 my $asc_desc = $result{dir} ? 'ASC' : 'DESC';
254 # Create the SQL code.
255 my $cols = $defs->{ $result{column} };
256 $result{sql} = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
258 $main::lxdebug->leave_sub(2);
263 sub does_table_exist {
264 $main::lxdebug->enter_sub(2);
272 my $sth = $dbh->table_info('', '', $table, 'TABLE');
274 $result = $sth->fetchrow_hashref();
279 $main::lxdebug->leave_sub(2);
284 # add token to values.
290 # val => [ 23, 34, 17 ]
293 # will append to the given arrays:
294 # -> 'id IN (?, ?, ?)'
295 # -> (conv_i(23), conv_i(34), conv_i(17))
298 # - don't care if one or multiple values are given. singlewill result in 'col = ?'
299 # - pass escape routines
300 # - expand for future method
301 # - no need to type "push @where_tokens, 'id = ?'" over and over again
303 my $tokens = shift() || [];
304 my $values = shift() || [];
306 my $col = $params{col};
307 my $val = $params{val};
308 my $method = $params{method} || '=';
309 my $escape = $params{esc} || sub { $_ };
311 $val = [ $val ] unless ref $val eq 'ARRAY';
321 return scalar @_ > 1 ? sprintf '%s IN (%s)', $col, join ', ', ("?") x scalar @_
322 : scalar @_ == 1 ? sprintf '%s = ?', $col
327 $method = $methods{$method} || $method;
328 $escape = $escapes{$escape} || $escape;
330 my $token = $method->($col, @{ $val });
331 my @vals = map { $escape->($_) } @{ $val };
333 return unless $token;
335 push @{ $tokens }, $token;
336 push @{ $values }, @vals;
338 return ($token, @vals);
348 SL::DBUTils.pm: All about Databaseconections in Lx
354 conv_i($str, $default)
359 do_query($form, $dbh, $query)
360 do_statement($form, $sth, $query)
362 dump_query($level, $msg, $query)
363 prepare_execute_query($form, $dbh, $query)
365 my $all_results_ref = selectall_hashref_query($form, $dbh, $query)
366 my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
368 my @first_result = selectfirst_array_query($form, $dbh, $query); # ==
369 my @first_result = selectrow_query($form, $dbh, $query);
371 my %sort_spec = create_sort_spec(%params);
375 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.
377 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.
379 DBUtils relies heavily on two parameters which have to be passed to almost every function: $form and $dbh.
380 - $form is used for error handling only. It can be omitted in theory, but should not.
381 - $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!
384 Every function here should accomplish the follwing things:
385 - Easy debugging. Every handled query gets dumped via LXDebug, if specified there.
386 - Safe value binding. Although DBI is far from perfect in terms of binding, the rest of the bindings should happen here.
387 - Error handling. Should a query fail, an error message will be generated here instead of in the backend code invoking DBUtils.
389 Note that binding is not perfect here either...
391 =head2 QUOTING FUNCTIONS
397 =item conv_i STR,DEFAULT
399 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is given, returns undef.
403 Converts STR to a date string. If STR is emptry, returns undef.
407 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if STR is empty.
409 =item quote_db_date STR
411 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.
412 Returns 'NULL' if STR is empty.
416 =head2 QUERY FUNCTIONS
420 =item do_query FORM,DBH,QUERY,ARRAY
422 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.
424 Returns the result of DBI::do which is -1 in case of an error and the number of affected rows otherwise.
426 =item do_statement FORM,STH,QUERY,ARRAY
428 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.
430 Returns the result of DBI::execute which is -1 in case of an error and the number of affected rows otherwise.
432 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
434 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY is passed as binding values to execute.
438 =head2 RETRIEVAL FUNCTIONS
442 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
444 =item selectrow_query FORM,DBH,QUERY,ARRAY
446 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.
448 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
450 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.
452 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
454 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.
456 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
458 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.
462 =head2 UTILITY FUNCTIONS
466 =item create_sort_spec
469 defs => { }, # mandatory
470 default => 'name', # mandatory
480 This function simplifies the creation of SQL code for sorting
481 columns. It uses a hashref of valid column names, the column name and
482 direction requested by the user, the application defaults for the
483 column name and the direction and returns the actual column name,
484 direction and SQL code that can be used directly in a query.
486 The parameter 'defs' is a hash reference. The keys are the column
487 names as they may come from the application. The values are either
488 scalars with SQL code or array references of SQL code. Example:
490 'defs' => { 'customername' => 'lower(customer.name)',
491 'address' => [ 'lower(customer.city)', 'lower(customer.street)' ], }
493 'default' is the default column name to sort by. It must be a key of
494 'defs' and should not be come from user input.
496 The 'column' parameter is the column name as requested by the
497 application (e.g. if the user clicked on a column header in a
498 report). If it is invalid then the 'default' parameter will be used
501 'default_dir' is the default sort direction. A true value means 'sort
502 ascending', a false one 'sort descending'. 'default_dir' defaults to
505 The 'dir' parameter is the sort direction as requested by the
506 application (e.g. if the user clicked on a column header in a
507 report). If it is undefined then the 'default_dir' parameter will be
512 =head2 DEBUG FUNCTIONS
516 =item dump_query LEVEL,MSG,QUERY,ARRAY
518 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.
526 =item Retrieving a whole table:
528 $query = qq|SELECT id, pricegroup FROM pricegroup|;
529 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
531 =item Retrieving a single value:
533 $query = qq|SELECT nextval('glid')|;
534 ($new_id) = selectrow_query($form, $dbh, $query);
536 =item Using binding values:
538 $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
539 do_query($form, $dbh, $query, $id);
541 =item A more complicated example, using dynamic binding values:
545 if ($form->{language_values} ne "") {
546 $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
548 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)|;
549 @values = (conv_i($form->{id}));
551 $query = qq|SELECT id, description FROM language|;
554 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
560 =head1 MODULE AUTHORS
562 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
563 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
565 =head1 DOCUMENTATION AUTHORS
567 Udo Spallek E<lt>udono@gmx.netE<gt>
568 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
570 =head1 COPYRIGHT AND LICENSE
572 Copyright 2007 by Lx-Office Community
574 This program is free software; you can redistribute it and/or modify
575 it under the terms of the GNU General Public License as published by
576 the Free Software Foundation; either version 2 of the License, or
577 (at your option) any later version.
579 This program is distributed in the hope that it will be useful,
580 but WITHOUT ANY WARRANTY; without even the implied warranty of
581 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
582 GNU General Public License for more details.
583 You should have received a copy of the GNU General Public License
584 along with this program; if not, write to the Free Software
585 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.