6 our @ISA = qw(Exporter);
8 our @EXPORT = qw(conv_i conv_date conv_dateq do_query selectrow_query do_statement
9 dump_query quote_db_date like
10 selectfirst_hashref_query selectfirst_array_query
11 selectall_hashref_query selectall_array_query selectcol_array_query
14 prepare_execute_query prepare_query
15 create_sort_spec does_table_exist
21 my ($value, $default) = @_;
22 return (defined($value) && "$value" ne "") ? $value * 1 : $default;
27 my ($value, $default) = @_;
28 return !defined $value && defined $default ? $default
35 return undef if !defined $value;
36 $value = trim($value);
37 return $value eq "" ? undef : $value;
42 if (defined($value) && "$value" ne "") {
43 $value =~ s/\'/\'\'/g;
50 $main::lxdebug->enter_sub(2);
52 my ($form, $dbh, $query) = splice(@_, 0, 3);
54 dump_query(LXDebug->QUERY(), '', $query, @_);
57 if (0 == scalar(@_)) {
58 $result = $dbh->do($query) || $form->dberror($query);
60 $result = $dbh->do($query, undef, @_) || $form->dberror($query . " (" . join(", ", @_) . ")");
63 $main::lxdebug->leave_sub(2);
68 sub selectrow_query { &selectfirst_array_query }
71 $main::lxdebug->enter_sub(2);
73 my ($form, $sth, $query) = splice(@_, 0, 3);
75 dump_query(LXDebug->QUERY(), '', $query, @_);
78 if (0 == scalar(@_)) {
79 $result = $sth->execute() || $form->dberror($query);
81 $result = $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
84 $main::lxdebug->leave_sub(2);
90 my ($level, $msg, $query) = splice(@_, 0, 3);
92 my $self_filename = 'SL/DBUtils.pm';
93 my $filename = $self_filename;
94 my ($caller_level, $line, $subroutine);
95 while ($filename =~ m{$self_filename$}) {
96 (undef, $filename, $line, $subroutine) = caller $caller_level++;
99 while ($query =~ /\?/) {
100 my $value = shift || '';
101 $value =~ s/\'/\\\'/g;
102 $value = "'${value}'";
103 $query =~ s/\?/$value/;
106 $query =~ s/[\n\s]+/ /g;
108 $msg .= " " if ($msg);
110 my $info = "$subroutine called from $filename:$line\n";
112 $main::lxdebug->message($level, $info . $msg . $query);
118 return "NULL" unless defined $str;
119 return "current_date" if $str =~ /current_date/;
126 $main::lxdebug->enter_sub(2);
128 my ($form, $dbh, $query) = splice(@_, 0, 3);
130 dump_query(LXDebug->QUERY(), '', $query, @_);
132 my $sth = $dbh->prepare($query) || $form->dberror($query);
134 $main::lxdebug->leave_sub(2);
139 sub prepare_execute_query {
140 $main::lxdebug->enter_sub(2);
142 my ($form, $dbh, $query) = splice(@_, 0, 3);
144 dump_query(LXDebug->QUERY(), '', $query, @_);
146 my $sth = $dbh->prepare($query) || $form->dberror($query);
147 if (scalar(@_) != 0) {
148 $sth->execute(@_) || $form->dberror($query . " (" . join(", ", @_) . ")");
150 $sth->execute() || $form->dberror($query);
153 $main::lxdebug->leave_sub(2);
158 sub selectall_hashref_query {
159 $main::lxdebug->enter_sub(2);
161 my ($form, $dbh, $query) = splice(@_, 0, 3);
163 dump_query(LXDebug->QUERY(), '', $query, @_);
165 # this works back 'til at least DBI 1.46 on perl 5.8.4 on Debian Sarge (2004)
166 my $result = $dbh->selectall_arrayref($query, { Slice => {} }, @_)
167 or $form->dberror($query . (@_ ? " (" . join(", ", @_) . ")" : ''));
169 $main::lxdebug->leave_sub(2);
171 return wantarray ? @{ $result } : $result;
174 sub selectall_array_query { goto &selectcol_array_query; }
176 sub selectcol_array_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 @result = @{ $dbh->selectcol_arrayref($sth) };
185 $main::lxdebug->leave_sub(2);
190 sub selectfirst_hashref_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 $ref = $sth->fetchrow_hashref();
199 $main::lxdebug->leave_sub(2);
204 sub selectfirst_array_query {
205 $main::lxdebug->enter_sub(2);
207 my ($form, $dbh, $query) = splice(@_, 0, 3);
209 my $sth = prepare_execute_query($form, $dbh, $query, @_);
210 my @ret = $sth->fetchrow_array();
213 $main::lxdebug->leave_sub(2);
218 sub selectall_as_map {
219 $main::lxdebug->enter_sub(2);
221 my ($form, $dbh, $query, $key_col, $value_col) = splice(@_, 0, 5);
223 my $sth = prepare_execute_query($form, $dbh, $query, @_);
226 if ('' eq ref $value_col) {
227 while (my $ref = $sth->fetchrow_hashref()) {
228 $hash{$ref->{$key_col} // ''} = $ref->{$value_col};
231 while (my $ref = $sth->fetchrow_hashref()) {
232 $hash{$ref->{$key_col} // ''} = { map { $_ => $ref->{$_} } @{ $value_col } };
238 $main::lxdebug->leave_sub(2);
244 $main::lxdebug->enter_sub(2);
246 my ($form, $dbh, $query, $key_col) = splice(@_, 0, 4);
248 my $sth = prepare_execute_query($form, $dbh, $query, @_);
251 while (my $ref = $sth->fetchrow_arrayref()) {
252 push @ids, $ref->[$key_col];
257 $main::lxdebug->leave_sub(2);
262 sub create_sort_spec {
263 $main::lxdebug->enter_sub(2);
268 $params{defs} || die;
269 $params{default} || die;
271 # The definition of valid columns to sort by.
272 my $defs = $params{defs};
274 # The column name to sort by. Use the default column name if none was given.
275 my %result = ( 'column' => $params{column} || $params{default} );
277 # Overwrite the column name with the default column name if the other one is not valid.
278 $result{column} = $params{default} unless ($defs->{ $result{column} });
280 # The sort direction. true means 'sort ascending', false means 'sort descending'.
281 $result{dir} = defined $params{dir} ? $params{dir}
282 : defined $params{default_dir} ? $params{default_dir}
284 $result{dir} = $result{dir} ? 1 : 0;
285 my $asc_desc = $result{dir} ? 'ASC' : 'DESC';
287 # Create the SQL code.
288 my $cols = $defs->{ $result{column} };
289 $result{sql} = join ', ', map { "${_} ${asc_desc}" } @{ ref $cols eq 'ARRAY' ? $cols : [ $cols ] };
291 $main::lxdebug->leave_sub(2);
296 sub does_table_exist {
297 $main::lxdebug->enter_sub(2);
305 my $sth = $dbh->table_info('', '', $table, 'TABLE');
307 $result = $sth->fetchrow_hashref();
312 $main::lxdebug->leave_sub(2);
317 # add token to values.
323 # val => [ 23, 34, 17 ]
326 # will append to the given arrays:
327 # -> 'id IN (?, ?, ?)'
328 # -> (conv_i(23), conv_i(34), conv_i(17))
331 # - don't care if one or multiple values are given. singlewill result in 'col = ?'
332 # - pass escape routines
333 # - expand for future method
334 # - no need to type "push @where_tokens, 'id = ?'" over and over again
336 my $tokens = shift() || [];
337 my $values = shift() || [];
339 my $col = $params{col};
340 my $val = $params{val};
341 my $escape = $params{esc} || sub { $_ };
342 my $method = $params{esc} =~ /^start|end|substr$/ ? 'ILIKE' : $params{method} || '=';
344 $val = [ $val ] unless ref $val eq 'ARRAY';
350 start => sub { trim($_[0]) . '%' },
351 end => sub { '%' . trim($_[0]) },
352 substr => sub { like($_[0]) },
355 my $_long_token = sub {
359 return scalar @_ ? join ' OR ', ("$col $op ?") x scalar @_,
367 return scalar @_ > 1 ? sprintf '%s IN (%s)', $col, join ', ', ("?") x scalar @_
368 : scalar @_ == 1 ? sprintf '%s = ?', $col
371 map({ $_ => $_long_token->($_) } qw(LIKE ILIKE >= <= > <)),
374 $method = $methods{$method} || $method;
375 $escape = $escapes{$escape} || $escape;
377 my $token = $method->($col, @{ $val });
378 my @vals = map { $escape->($_) } @{ $val };
380 return unless $token;
382 push @{ $tokens }, $token;
383 push @{ $values }, @vals;
385 return ($token, @vals);
391 return "%" . SL::Util::trim($string // '') . "%";
394 sub role_is_superuser {
395 my ($dbh, $login) = @_;
396 my ($is_superuser) = $dbh->selectrow_array(qq|SELECT usesuper FROM pg_user WHERE usename = ?|, undef, $login);
398 return $is_superuser;
410 SL::DBUtils.pm: All about database connections in kivitendo
416 conv_i($str, $default)
421 my $dbh = SL::DB->client->dbh;
423 do_query($form, $dbh, $query)
424 do_statement($form, $sth, $query)
426 dump_query($level, $msg, $query)
427 prepare_execute_query($form, $dbh, $query)
429 my $all_results_ref = selectall_hashref_query($form, $dbh, $query)
430 my $first_result_hash_ref = selectfirst_hashref_query($form, $dbh, $query);
432 my @first_result = selectfirst_array_query($form, $dbh, $query);
433 my @first_result = selectrow_query($form, $dbh, $query);
435 my @values = selectcol_array_query($form, $dbh, $query);
437 my %sort_spec = create_sort_spec(%params);
441 DBUtils provides wrapper functions for low level database retrieval. It saves
442 you the trouble of mucking around with statement handles for small database
443 queries and does exception handling in the common cases for you.
445 Query and retrieval functions share the parameter scheme:
447 query_or_retrieval(C<FORM, DBH, QUERY[, BINDVALUES]>)
453 C<FORM> is used for error handling only. It can be omitted in theory, but should
454 not. In most cases you will call it with C<$::form>.
458 C<DBH> is a handle to the database, as returned by the C<DBI::connect> routine.
459 If you don't have an active connection, you can use
460 C<SL::DB->client->dbh> or get a C<Rose::DB::Object> handle from any RDBO class with
461 C<<SL::DB::Part->new->db->dbh>>. In both cases the handle will have AutoCommit set.
463 See C<PITFALLS AND CAVEATS> for common errors.
467 C<QUERY> must be exactly one query. You don't need to include the terminal
468 C<;>. There must be no tainted data interpolated into the string. Instead use
469 the DBI placeholder syntax.
473 All additional parameters will be used as C<BINDVALUES> for the query. Note
474 that DBI can't bind arrays to a C<id IN (?)>, so you will need to generate a
475 statement with exactly one C<?> for each bind value. DBI can however bind
476 DateTime objects, and you should always pass these for date selections.
480 =head1 PITFALLS AND CAVEATS
484 As mentioned above, there are two sources of database handles in the program:
485 C<<$::form->get_standard_dbh>> and C<<SL::DB::Object->new->db->dbh>>. It's easy
486 to produce deadlocks when using both of them. To reduce the likelyhood of
487 locks, try to obey these rules:
493 In a controller that uses Rose objects, never use C<get_standard_dbh>.
497 In backend code, that has no preference, always accept the database handle as a
498 parameter from the controller.
504 C<DBUtils> is one of the last modules in the program to use C<@EXPORT> instead
505 of C<@EXPORT_OK>. This means it will flood your namespace with its functions,
506 causing potential clashes. When writing new code, always either export nothing
510 DBUtils::selectall_hashref_query(...)
512 or export only what you need:
514 use SL::DBUtils qw(selectall_hashref_query);
515 selectall_hashref_query(...)
520 Since it is really easy to write something like
522 my $all_parts = selectall_hashref_query($::form, $dbh, 'SELECT * FROM parts');
524 people do so from time to time. When writing code, consider this a ticking
525 timebomb. Someone out there has a database with 1mio parts in it, and this
526 statement just gobbled up 2GB of memory and timeouted the request.
528 Parts may be the obvious example, but the same applies to customer, vendors,
529 records, projects or custom variables.
532 =head1 QUOTING FUNCTIONS
538 =item conv_i STR,DEFAULT
540 Converts STR to an integer. If STR is empty, returns DEFAULT. If no DEFAULT is
541 given, returns undef.
545 Converts STR to a date string. If STR is emptry, returns undef.
549 Database version of conv_date. Quotes STR before returning. Returns 'NULL' if
552 =item quote_db_date STR
554 Treats STR as a database date, quoting it. If STR equals current_date returns
555 an escaped version which is treated as the current date by Postgres.
557 Returns C<'NULL'> if STR is empty.
561 Turns C<STR> into an argument suitable for SQL's C<LIKE> and C<ILIKE>
562 operators by Trimming the string C<STR> (removes leading and trailing
563 whitespaces) and prepending and appending C<%>.
567 =head1 QUERY FUNCTIONS
571 =item do_query FORM,DBH,QUERY,ARRAY
573 Uses DBI::do to execute QUERY on DBH using ARRAY for binding values. FORM is
574 only needed for error handling, but should always be passed nevertheless. Use
575 this for insertions or updates that don't need to be prepared.
577 Returns the result of DBI::do which is -1 in case of an error and the number of
578 affected rows otherwise.
580 =item do_statement FORM,STH,QUERY,ARRAY
582 Uses DBI::execute to execute QUERY on DBH using ARRAY for binding values. As
583 with do_query, FORM is only used for error handling. If you are unsure what to
584 use, refer to the documentation of DBI::do and DBI::execute.
586 Returns the result of DBI::execute which is -1 in case of an error and the
587 number of affected rows otherwise.
589 =item prepare_execute_query FORM,DBH,QUERY,ARRAY
591 Prepares and executes QUERY on DBH using DBI::prepare and DBI::execute. ARRAY
592 is passed as binding values to execute.
596 =head1 RETRIEVAL FUNCTIONS
600 =item selectfirst_array_query FORM,DBH,QUERY,ARRAY
602 =item selectrow_query FORM,DBH,QUERY,ARRAY
604 Prepares and executes a query using DBUtils functions, retrieves the first row
605 from the database, and returns it as an arrayref of the first row.
607 =item selectfirst_hashref_query FORM,DBH,QUERY,ARRAY
609 Prepares and executes a query using DBUtils functions, retrieves the first row
610 from the database, and returns it as a hashref of the first row.
612 =item selectall_hashref_query FORM,DBH,QUERY,ARRAY
614 Prepares and executes a query using DBUtils functions, retrieves all data from
615 the database, and returns it in hashref mode. This is slightly confusing, as
616 the data structure will actually be a reference to an array, containing
617 hashrefs for each row.
620 =item selectall_array_query FORM,DBH,QUERY,ARRAY
622 Deprecated, see C<selectcol_array_query>
624 =item selectcol_array_query FORM,DBH,QUERY,ARRAY
626 Prepares and executes a query using DBUtils functions, retrieves the values of
627 the first result column and returns the values as an array.
629 =item selectall_as_map FORM,DBH,QUERY,KEY_COL,VALUE_COL,ARRAY
631 Prepares and executes a query using DBUtils functions, retrieves all data from
632 the database, and creates a hash from the results using KEY_COL as the column
633 for the hash keys and VALUE_COL for its values.
637 =head1 UTILITY FUNCTIONS
641 =item create_sort_spec
644 defs => { }, # mandatory
645 default => 'name', # mandatory
655 This function simplifies the creation of SQL code for sorting
656 columns. It uses a hashref of valid column names, the column name and
657 direction requested by the user, the application defaults for the
658 column name and the direction and returns the actual column name,
659 direction and SQL code that can be used directly in a query.
661 The parameter 'defs' is a hash reference. The keys are the column
662 names as they may come from the application. The values are either
663 scalars with SQL code or array references of SQL code. Example:
666 customername => 'lower(customer.name)',
667 address => [ 'lower(customer.city)', 'lower(customer.street)' ],
670 'default' is the default column name to sort by. It must be a key of
671 'defs' and should not be come from user input.
673 The 'column' parameter is the column name as requested by the
674 application (e.g. if the user clicked on a column header in a
675 report). If it is invalid then the 'default' parameter will be used
678 'default_dir' is the default sort direction. A true value means 'sort
679 ascending', a false one 'sort descending'. 'default_dir' defaults to
682 The 'dir' parameter is the sort direction as requested by the
683 application (e.g. if the user clicked on a column header in a
684 report). If it is undefined then the 'default_dir' parameter will be
689 =head1 DEBUG FUNCTIONS
693 =item dump_query LEVEL,MSG,QUERY,ARRAY
695 Dumps a query using LXDebug->message, using LEVEL for the debug-level of
696 LXDebug. If MSG is given, it preceeds the QUERY dump in the logfiles. ARRAY is
697 used to interpolate the '?' placeholders in QUERY, the resulting QUERY can be
698 copy-pasted into a database frontend for debugging. Note that this method is
699 also automatically called by each of the other QUERY FUNCTIONS, so there is in
700 general little need to invoke it manually.
708 =item Retrieving a whole table:
710 $query = qq|SELECT id, pricegroup FROM pricegroup|;
711 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
713 =item Retrieving a single value:
715 $query = qq|SELECT nextval('glid')|;
716 ($new_id) = selectrow_query($form, $dbh, $query);
718 =item Retrieving all values from a column:
720 $query = qq|SELECT id FROM units|;
721 @units = selectcol_array_query($form, $dbh, $query);
723 =item Using binding values:
725 $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
726 do_query($form, $dbh, $query, $id);
728 =item A more complicated example, using dynamic binding values:
732 if ($form->{language_values} ne "") {
734 SELECT l.id, l.description, tr.translation, tr.longdescription
736 LEFT JOIN translation tr ON (tr.language_id = l.id AND tr.parts_id = ?)
738 @values = (conv_i($form->{id}));
740 $query = qq|SELECT id, description FROM language|;
743 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
747 =head1 MODULE AUTHORS
749 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
750 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
752 =head1 DOCUMENTATION AUTHORS
754 Udo Spallek E<lt>udono@gmx.netE<gt>
755 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>
757 =head1 COPYRIGHT AND LICENSE
759 Copyright 2007 by kivitendo Community
761 This program is free software; you can redistribute it and/or modify
762 it under the terms of the GNU General Public License as published by
763 the Free Software Foundation; either version 2 of the License, or
764 (at your option) any later version.
766 This program is distributed in the hope that it will be useful,
767 but WITHOUT ANY WARRANTY; without even the implied warranty of
768 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
769 GNU General Public License for more details.
770 You should have received a copy of the GNU General Public License
771 along with this program; if not, write to the Free Software
772 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.