3 # Copyright 2009 Biblibre SARL
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use List::MoreUtils qw(first_value any);
25 use C4::Dates qw(format_date_in_iso);
29 use vars qw($VERSION @ISA @EXPORT_OK %EXPORT_TAGS);
32 # set the version for version checking
43 %EXPORT_TAGS = ( all =>[qw( InsertInTable DeleteInTable SearchInTable UpdateInTable GetPrimaryKeys)]
52 C4::SQLHelper - Perl Module containing convenience functions for SQL Handling
60 This module contains routines for adding, modifying and Searching Data in MysqlDB
73 $hashref = &SearchInTable($tablename,$data, $orderby, $limit, $columns_out, $filtercolumns, $searchtype);
77 $tablename Name of the table (string)
82 - data_hashref : will be considered as an AND of all the data searched
84 - data_array_ref on hashrefs : Will be considered as an OR of Datahasref elements
86 $orderby is an arrayref of hashref with fieldnames as key and 0 or 1 as values (ASCENDING or DESCENDING order)
88 $limit is an array ref on 2 values in order to limit results to MIN..MAX
90 $columns_out is an array ref on field names is used to limit results on those fields (* by default)
92 $filtercolums is an array ref on field names : is used to limit expansion of research for strings
94 $searchtype is string Can be "start_with" or "exact"
99 my ($tablename,$filters,$orderby, $limit, $columns_out, $filter_columns,$searchtype) = @_;
100 # $searchtype||="start_with";
101 my $dbh = C4::Context->dbh;
102 $columns_out||=["*"];
103 my $sql = do { local $"=', ';
104 qq{ SELECT @$columns_out from $tablename}
108 my ($keys,$values)=_filter_fields($tablename,$filters,$searchtype,$filter_columns);
110 my @criteria=grep{defined($_) && $_ !~/^\W$/ }@$keys;
112 $sql.= do { local $"=') AND (';
113 qq{ WHERE (@criteria) }
118 #Order by desc by default
119 my @orders=map{ "$_".($$orderby{$_}? " DESC" : "") } keys %$orderby;
120 $sql.= do { local $"=', ';
121 qq{ ORDER BY @orders}
125 $sql.=qq{ LIMIT }.join(",",@$limit);
128 $debug && $values && warn $sql," ",join(",",@$values);
129 $sth = $dbh->prepare_cached($sql);
130 eval{$sth->execute(@$values)};
131 warn $@ if ($@ && $debug);
132 my $results = $sth->fetchall_arrayref( {} );
140 $data_id_in_table = &InsertInTable($tablename,$data_hashref);
145 and returns the id of the row inserted
149 my ($tablename,$data) = @_;
150 my $dbh = C4::Context->dbh;
151 my ($keys,$values)=_filter_hash($tablename,$data,0);
152 my $query = qq{ INSERT INTO $tablename SET }.join(", ",@$keys);
154 $debug && warn $query, join(",",@$values);
155 my $sth = $dbh->prepare_cached($query);
156 eval{$sth->execute(@$values)};
157 warn $@ if ($@ && $debug);
159 return $dbh->last_insert_id(undef, undef, $tablename, undef);
166 $status = &UpdateInTable($tablename,$data_hashref);
171 and returns the status of the operation
175 my ($tablename,$data) = @_;
176 my @field_ids=GetPrimaryKeys($tablename);
177 my @ids=@$data{@field_ids};
178 my $dbh = C4::Context->dbh;
179 my ($keys,$values)=_filter_hash($tablename,$data,0);
181 qq{ UPDATE $tablename
182 SET }.join(",",@$keys).qq{
183 WHERE }.join (" AND ",map{ "$_=?" }@field_ids);
184 $debug && warn $query, join(",",@$values,@ids);
186 my $sth = $dbh->prepare_cached($query);
188 eval{$result=$sth->execute(@$values,@ids)};
189 warn $@ if ($@ && $debug);
197 $status = &DeleteInTable($tablename,$data_hashref);
202 and returns the status of the operation
206 my ($tablename,$data) = @_;
207 my $dbh = C4::Context->dbh;
208 my ($keys,$values)=_filter_fields($tablename,$data,1);
210 my $query = do { local $"=') AND (';
211 qq{ DELETE FROM $tablename WHERE (@$keys)};
213 $debug && warn $query, join(",",@$values);
214 my $sth = $dbh->prepare_cached($query);
216 eval{$result=$sth->execute(@$values)};
217 warn $@ if ($@ && $debug);
222 =head2 GetPrimaryKeys
226 @primarykeys = &GetPrimaryKeys($tablename)
230 Get the Primary Key field names of the table
233 sub GetPrimaryKeys($) {
235 my $hash_columns=_get_columns($tablename);
236 return grep { $$hash_columns{$_}{'Key'} =~/PRI/i} keys %$hash_columns;
243 _get_columns($tablename)
248 Returns a hashref of all the fieldnames of the table
256 sub _get_columns($) {
258 my $dbh=C4::Context->dbh;
259 my $sth=$dbh->prepare_cached(qq{SHOW COLUMNS FROM $tablename });
261 my $columns= $sth->fetchall_hashref(qw(Field));
264 =head2 _filter_columns
268 _filter_columns($tablename,$research, $filtercolumns)
274 - indicator on purpose whether all fields should be returned or only non Primary keys
275 - array_ref to columns to limit to
277 Returns an array of all the fieldnames of the table
278 If it is not for research purpose, filter primary keys
282 sub _filter_columns ($$;$) {
283 my ($tablename,$research, $filtercolumns)=@_;
285 return (@$filtercolumns);
288 my $columns=_get_columns($tablename);
290 return keys %$columns;
293 return grep {my $column=$_; any {$_ ne $column }GetPrimaryKeys($tablename) } keys %$columns;
297 =head2 _filter_fields
307 - a string or a hashref (containing, fieldnames and datatofilter) or an arrayref to one of those elements
308 - an indicator of operation whether it is a wide research or a narrow one
309 - an array ref to columns to restrict string filter to.
311 Returns a ref of key array to use in SQL functions
312 and a ref to value array
317 my ($tablename,$filter_input,$searchtype,$filtercolumns)=@_;
320 if (ref($filter_input) eq "HASH"){
321 my ($keys, $values) = _filter_hash($tablename,$filter_input, $searchtype);
323 my $stringkey="(".join (") AND (",@$keys).")";
324 return [$stringkey],$values;
329 } elsif (ref($filter_input) eq "ARRAY"){
330 foreach my $element_data (@$filter_input){
331 my ($localkeys,$localvalues)=_filter_fields($tablename,$element_data,$searchtype,$filtercolumns);
333 @$localkeys=grep{defined($_) && $_ !~/^\W*$/}@$localkeys;
339 push @values, @$localvalues;
344 my ($keys, $values) = _filter_string($tablename,$filter_input, $searchtype,$filtercolumns);
346 my $stringkey="(".join (") AND (",@$keys).")";
347 return [$stringkey],$values;
354 return (\@keys,\@values);
358 my ($tablename,$filter_input, $searchtype)=@_;
360 my $columns= _get_columns($tablename);
361 my @columns_filtered= _filter_columns($tablename,$searchtype);
363 #Filter Primary Keys of table
364 my $elements=join "|",@columns_filtered;
365 foreach my $field (grep {/\b($elements)\b/} keys %$filter_input){
366 ## supposed to be a hash of simple values, hashes of arrays could be implemented
367 $$filter_input{$field}=format_date_in_iso($$filter_input{$field}) if ($$columns{$field}{Type}=~/date/ && $$filter_input{$field} !~C4::Dates->regexp("iso"));
368 my ($tmpkeys, $localvalues)=_Process_Operands($$filter_input{$field},"$tablename.$field",$searchtype,$columns);
370 push @values, @$localvalues;
371 push @keys, @$tmpkeys;
375 return (\@keys,\@values);
383 my ($tablename,$filter_input, $searchtype,$filtercolumns)=@_;
384 return () unless($filter_input);
385 my @operands=split / /,$filter_input;
386 my @columns_filtered= _filter_columns($tablename,$searchtype,$filtercolumns);
387 my $columns= _get_columns($tablename);
389 foreach my $operand (@operands){
391 foreach my $field (@columns_filtered){
392 my ($tmpkeys, $localvalues)=_Process_Operands($operand,"$tablename.$field",$searchtype,$columns);
394 push @values,@$localvalues;
395 push @localkeys,@$tmpkeys;
398 my $sql= join (' OR ', @localkeys);
403 return (\@keys,\@values);
409 sub _Process_Operands{
410 my ($operand, $field, $searchtype,$columns)=@_;
414 push @tmpkeys, " $field = ? ";
415 push @values, $operand;
416 #By default, exact search
417 unless ($searchtype){
418 return \@tmpkeys,\@values;
420 if ($searchtype eq "contain"){
421 my $col_field=(index($field,".")>0?substr($field, index($field,".")+1):$field);
422 if ($field=~/(?<!zip)code|(?<!card)number/ ){
423 push @tmpkeys,(" $field= '' ","$field IS NULL");
424 } elsif ($$columns{$col_field}{Type}=~/varchar|text/i){
425 push @tmpkeys,(" $field LIKE ? ");
426 my @localvaluesextended=("\%$operand\%") ;
427 push @values,@localvaluesextended;
430 if ($searchtype eq "start_with"){
431 my $col_field=(index($field,".")>0?substr($field, index($field,".")+1):$field);
432 if ($field=~/(?<!zip)code|(?<!card)number/ ){
433 push @tmpkeys,(" $field= '' ","$field IS NULL");
434 } elsif ($$columns{$col_field}{Type}=~/varchar|text/i){
435 push @tmpkeys,(" $field LIKE ? ","$field LIKE ?");
436 my @localvaluesextended=("\% $operand\%","$operand\%") ;
437 push @values,@localvaluesextended;
440 push @localkeys,qq{ (}.join(" OR ",@tmpkeys).qq{) };
441 return (\@localkeys,\@values);