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 $sth->execute(@$values);
124 my $results = $sth->fetchall_arrayref( {} );
132 $data_id_in_table = &InsertInTable($tablename,$data_hashref);
137 and returns the id of the row inserted
141 my ($tablename,$data) = @_;
142 my $dbh = C4::Context->dbh;
143 my ($keys,$values)=_filter_hash($tablename,$data,0);
144 my $query = qq{ INSERT INTO $tablename SET }.join(", ",@$keys);
146 $debug && warn $query, join(",",@$values);
147 my $sth = $dbh->prepare_cached($query);
148 $sth->execute( @$values);
150 return $dbh->last_insert_id(undef, undef, $tablename, undef);
157 $status = &UpdateInTable($tablename,$data_hashref);
162 and returns the status of the operation
166 my ($tablename,$data) = @_;
167 my @field_ids=GetPrimaryKeys($tablename);
168 my @ids=@$data{@field_ids};
169 my $dbh = C4::Context->dbh;
170 my ($keys,$values)=_filter_hash($tablename,$data,0);
172 qq{ UPDATE $tablename
173 SET }.join(",",@$keys).qq{
174 WHERE }.join (" AND
",map{ "$_=?
" }@field_ids);
175 $debug && warn $query, join(",",@$values,@ids);
177 my $sth = $dbh->prepare_cached($query);
178 return $sth->execute( @$values,@ids);
186 $status = &DeleteInTable($tablename,$data_hashref);
191 and returns the status of the operation
195 my ($tablename,$data) = @_;
196 my $dbh = C4::Context->dbh;
197 my ($keys,$values)=_filter_fields($tablename,$data,1);
199 my $query = do { local $"=') AND (';
200 qq{ DELETE FROM
$tablename WHERE
(@
$keys)};
202 $debug && warn $query, join(",",@
$values);
203 my $sth = $dbh->prepare_cached($query);
204 return $sth->execute( @
$values);
208 =head2 GetPrimaryKeys
212 @primarykeys = &GetPrimaryKeys($tablename)
216 Get the Primary Key field names of the table
219 sub GetPrimaryKeys
($) {
221 my $hash_columns=_get_columns
($tablename);
222 return grep { $$hash_columns{$_}{'Key'} =~/PRI/i} keys %$hash_columns;
229 _get_columns($tablename)
234 Returns a hashref of all the fieldnames of the table
242 sub _get_columns
($) {
244 my $dbh=C4
::Context
->dbh;
245 my $sth=$dbh->prepare_cached(qq{SHOW COLUMNS FROM
$tablename });
247 my $columns= $sth->fetchall_hashref(qw(Field));
250 =head2 _filter_columns
254 _filter_columns($tablename,$research, $filtercolumns)
260 - indicator on purpose whether all fields should be returned or only non Primary keys
261 - array_ref to columns to limit to
263 Returns an array of all the fieldnames of the table
264 If it is not for research purpose, filter primary keys
268 sub _filter_columns
($$;$) {
269 my ($tablename,$research, $filtercolumns)=@_;
271 return (@
$filtercolumns);
274 my $columns=_get_columns
($tablename);
276 return keys %$columns;
279 return grep {my $column=$_; any
{$_ ne $column }GetPrimaryKeys
($tablename) } keys %$columns;
283 =head2 _filter_fields
293 - a string or a hashref (containing, fieldnames and datatofilter) or an arrayref to one of those elements
294 - an indicator of operation whether it is a wide research or a narrow one
295 - an array ref to columns to restrict string filter to.
297 Returns a ref of key array to use in SQL functions
298 and a ref to value array
303 my ($tablename,$filter_input,$searchtype,$filtercolumns)=@_;
306 if (ref($filter_input) eq "HASH"){
307 my ($keys, $values) = _filter_hash
($tablename,$filter_input, $searchtype);
309 my $stringkey="(".join (") AND (",@
$keys).")";
310 return [$stringkey],$values;
315 } elsif (ref($filter_input) eq "ARRAY"){
316 foreach my $element_data (@
$filter_input){
317 my ($localkeys,$localvalues)=_filter_fields
($tablename,$element_data,$searchtype,$filtercolumns);
319 @
$localkeys=grep{defined($_) && $_ !~/^\W*$/}@
$localkeys;
325 push @values, @$localvalues;
330 return _filter_string($tablename,$filter_input,$searchtype,$filtercolumns);
333 return (\@keys,\@values);
337 my ($tablename,$filter_input, $searchtype)=@_;
339 my $columns= _get_columns($tablename);
340 my @columns_filtered= _filter_columns($tablename,$searchtype);
342 #Filter Primary Keys of table
343 my $elements=join "|",@columns_filtered;
344 foreach my $field (grep {/\b($elements)\b/} keys %$filter_input){
345 ## supposed to be a hash of simple values, hashes of arrays could be implemented
346 $$filter_input{$field}=format_date_in_iso($$filter_input{$field}) if ($$columns{$field}{Type}=~/date/ && $$filter_input{$field} !~C4::Dates->regexp("iso
"));
347 my ($tmpkeys, $localvalues)=_Process_Operands($$filter_input{$field},"$tablename.$field",$searchtype,$columns);
349 push @values, @$localvalues;
350 push @keys, @$tmpkeys;
354 return (\@keys,\@values);
362 my ($tablename,$filter_input, $searchtype,$filtercolumns)=@_;
363 return () unless($filter_input);
364 my @operands=split / /,$filter_input;
365 my @columns_filtered= _filter_columns($tablename,$searchtype,$filtercolumns);
366 my $columns= _get_columns($tablename);
369 foreach my $operand (@operands){
370 foreach my $field (@columns_filtered){
371 my ($tmpkeys, $localvalues)=_Process_Operands($operand,"$tablename.$field",$searchtype,$columns);
373 push @values,@$localvalues;
374 push @localkeys,@$tmpkeys;
378 my $sql= join (' OR ', @localkeys);
382 return (\@keys,\@values);
388 sub _Process_Operands{
389 my ($operand, $field, $searchtype,$columns)=@_;
393 push @tmpkeys, " $field = ?
";
394 push @values, $operand;
395 unless ($searchtype){
396 return \@tmpkeys,\@values;
398 if ($searchtype eq "start_with
"){
399 my $col_field=(index($field,".")>0?substr($field, index($field,".")+1):$field);
400 if ($field=~/(?<!zip)code|(?<!card)number/ ){
401 push @tmpkeys,(" $field= '' ","$field IS NULL
");
402 } elsif ($$columns{$col_field}{Type}=~/varchar|text/i){
403 push @tmpkeys,(" $field LIKE ?
","$field LIKE ?
");
404 my @localvaluesextended=("\
% $operand\
%","$operand\
%") ;
405 push @values,@localvaluesextended;
408 push @localkeys,qq{ (}.join(" OR
",@tmpkeys).qq{) };
409 return (\@localkeys,\@values);