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)
80 - data_hashref : will be considered as an AND of all the data searched
81 - data_array_ref on hashrefs : Will be considered as an OR of Datahasref elements
83 $orderby is an arrayref of hashref with fieldnames as key and 0 or 1 as values (ASCENDING or DESCENDING order)
84 $limit is an array ref on 2 values
85 $columns_out is an array ref on field names is used to limit results on those fields (* by default)
86 $filtercolums is an array ref on field names : is used to limit expansion of research for strings
87 $searchtype is string Can be "wide" or "exact"
92 my ($tablename,$filters,$orderby, $limit, $columns_out, $filter_columns,$searchtype) = @_;
93 # $searchtype||="start_with";
94 my $dbh = C4::Context->dbh;
96 my $sql = do { local $"=', ';
97 qq{ SELECT @$columns_out from $tablename}
101 my ($keys,$values)=_filter_fields($tablename,$filters,$searchtype,$filter_columns);
103 my @criteria=grep{defined($_) && $_ !~/^\W$/ }@$keys;
105 $sql.= do { local $"=') AND (';
106 qq{ WHERE (@criteria) }
111 #Order by desc by default
112 my @orders=map{ "$_".($$orderby{$_}? " DESC" : "") } keys %$orderby;
113 $sql.= do { local $"=', ';
114 qq{ ORDER BY @orders}
118 $sql.=qq{ LIMIT }.join(",",@$limit);
121 $debug && $values && warn $sql," ",join(",",@$values);
122 $sth = $dbh->prepare_cached($sql);
123 eval{$sth->execute(@$values)};
124 warn $@ if ($@ && $debug);
125 my $results = $sth->fetchall_arrayref( {} );
133 $data_id_in_table = &InsertInTable($tablename,$data_hashref);
138 and returns the id of the row inserted
142 my ($tablename,$data) = @_;
143 my $dbh = C4::Context->dbh;
144 my ($keys,$values)=_filter_hash($tablename,$data,0);
145 my $query = qq{ INSERT INTO $tablename SET }.join(", ",@$keys);
147 $debug && warn $query, join(",",@$values);
148 my $sth = $dbh->prepare_cached($query);
149 eval{$sth->execute(@$values)};
150 warn $@ if ($@ && $debug);
152 return $dbh->last_insert_id(undef, undef, $tablename, undef);
159 $status = &UpdateInTable($tablename,$data_hashref);
164 and returns the status of the operation
168 my ($tablename,$data) = @_;
169 my @field_ids=GetPrimaryKeys($tablename);
170 my @ids=@$data{@field_ids};
171 my $dbh = C4::Context->dbh;
172 my ($keys,$values)=_filter_hash($tablename,$data,0);
174 qq{ UPDATE $tablename
175 SET }.join(",",@$keys).qq{
176 WHERE }.join (" AND ",map{ "$_=?" }@field_ids);
177 $debug && warn $query, join(",",@$values,@ids);
179 my $sth = $dbh->prepare_cached($query);
181 eval{$result=$sth->execute(@$values,@ids)};
182 warn $@ if ($@ && $debug);
190 $status = &DeleteInTable($tablename,$data_hashref);
195 and returns the status of the operation
199 my ($tablename,$data) = @_;
200 my $dbh = C4::Context->dbh;
201 my ($keys,$values)=_filter_fields($tablename,$data,1);
203 my $query = do { local $"=') AND (';
204 qq{ DELETE FROM $tablename WHERE (@$keys)};
206 $debug && warn $query, join(",",@$values);
207 my $sth = $dbh->prepare_cached($query);
209 eval{$result=$sth->execute(@$values)};
210 warn $@ if ($@ && $debug);
215 =head2 GetPrimaryKeys
219 @primarykeys = &GetPrimaryKeys($tablename)
223 Get the Primary Key field names of the table
226 sub GetPrimaryKeys($) {
228 my $hash_columns=_get_columns($tablename);
229 return grep { $$hash_columns{$_}{'Key'} =~/PRI/i} keys %$hash_columns;
236 _get_columns($tablename)
241 Returns a hashref of all the fieldnames of the table
249 sub _get_columns($) {
251 my $dbh=C4::Context->dbh;
252 my $sth=$dbh->prepare_cached(qq{SHOW COLUMNS FROM $tablename });
254 my $columns= $sth->fetchall_hashref(qw(Field));
257 =head2 _filter_columns
261 _filter_columns($tablename,$research, $filtercolumns)
267 - indicator on purpose whether all fields should be returned or only non Primary keys
268 - array_ref to columns to limit to
270 Returns an array of all the fieldnames of the table
271 If it is not for research purpose, filter primary keys
275 sub _filter_columns ($$;$) {
276 my ($tablename,$research, $filtercolumns)=@_;
278 return (@$filtercolumns);
281 my $columns=_get_columns($tablename);
283 return keys %$columns;
286 return grep {my $column=$_; any {$_ ne $column }GetPrimaryKeys($tablename) } keys %$columns;
290 =head2 _filter_fields
300 - a string or a hashref (containing, fieldnames and datatofilter) or an arrayref to one of those elements
301 - an indicator of operation whether it is a wide research or a narrow one
302 - an array ref to columns to restrict string filter to.
304 Returns a ref of key array to use in SQL functions
305 and a ref to value array
310 my ($tablename,$filter_input,$searchtype,$filtercolumns)=@_;
313 if (ref($filter_input) eq "HASH"){
314 my ($keys, $values) = _filter_hash($tablename,$filter_input, $searchtype);
316 my $stringkey="(".join (") AND (",@$keys).")";
317 return [$stringkey],$values;
322 } elsif (ref($filter_input) eq "ARRAY"){
323 foreach my $element_data (@$filter_input){
324 my ($localkeys,$localvalues)=_filter_fields($tablename,$element_data,$searchtype,$filtercolumns);
326 @$localkeys=grep{defined($_) && $_ !~/^\W*$/}@$localkeys;
332 push @values, @$localvalues;
337 return _filter_string($tablename,$filter_input,$searchtype,$filtercolumns);
340 return (\@keys,\@values);
344 my ($tablename,$filter_input, $searchtype)=@_;
346 my $columns= _get_columns($tablename);
347 my @columns_filtered= _filter_columns($tablename,$searchtype);
349 #Filter Primary Keys of table
350 my $elements=join "|",@columns_filtered;
351 foreach my $field (grep {/\b($elements)\b/} keys %$filter_input){
352 ## supposed to be a hash of simple values, hashes of arrays could be implemented
353 $$filter_input{$field}=format_date_in_iso($$filter_input{$field}) if ($$columns{$field}{Type}=~/date/ && $$filter_input{$field} !~C4::Dates->regexp("iso"));
354 my ($tmpkeys, $localvalues)=_Process_Operands($$filter_input{$field},"$tablename.$field",$searchtype,$columns);
356 push @values, @$localvalues;
357 push @keys, @$tmpkeys;
361 return (\@keys,\@values);
369 my ($tablename,$filter_input, $searchtype,$filtercolumns)=@_;
370 return () unless($filter_input);
371 my @operands=split / /,$filter_input;
372 my @columns_filtered= _filter_columns($tablename,$searchtype,$filtercolumns);
373 my $columns= _get_columns($tablename);
376 foreach my $operand (@operands){
377 foreach my $field (@columns_filtered){
378 my ($tmpkeys, $localvalues)=_Process_Operands($operand,"$tablename.$field",$searchtype,$columns);
380 push @values,@$localvalues;
381 push @localkeys,@$tmpkeys;
385 my $sql= join (' OR ', @localkeys);
389 return (\@keys,\@values);
395 sub _Process_Operands{
396 my ($operand, $field, $searchtype,$columns)=@_;
400 push @tmpkeys, " $field = ? ";
401 push @values, $operand;
402 unless ($searchtype){
403 return \@tmpkeys,\@values;
405 if ($searchtype eq "start_with"){
406 my $col_field=(index($field,".")>0?substr($field, index($field,".")+1):$field);
407 if ($field=~/(?<!zip)code|(?<!card)number/ ){
408 push @tmpkeys,(" $field= '' ","$field IS NULL");
409 } elsif ($$columns{$col_field}{Type}=~/varchar|text/i){
410 push @tmpkeys,(" $field LIKE ? ","$field LIKE ?");
411 my @localvaluesextended=("\% $operand\%","$operand\%") ;
412 push @values,@localvaluesextended;
415 push @localkeys,qq{ (}.join(" OR ",@tmpkeys).qq{) };
416 return (\@localkeys,\@values);