|
1 # This program is free software: you can redistribute it and/or modify |
|
2 # it under the terms of the GNU General Public License as published by |
|
3 # the Free Software Foundation, either version 3 of the License, or |
|
4 # (at your option) any later version. |
|
5 # |
|
6 # This program is distributed in the hope that it will be useful, |
|
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
9 # GNU General Public License for more details. |
|
10 # |
|
11 # You should have received a copy of the GNU General Public License |
|
12 # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
13 |
|
14 package CrashTest::Plugin::Storage::Sql::Utils; |
|
15 use Mojo::Base -base; |
|
16 use Storable 'dclone'; |
|
17 |
|
18 has [ qw/instance app config/ ]; |
|
19 |
|
20 has qw/db/; |
|
21 |
|
22 sub new { |
|
23 my $self = shift->SUPER::new(@_); |
|
24 |
|
25 $self->db($self->instance->dbh->db); |
|
26 |
|
27 return $self; |
|
28 } |
|
29 |
|
30 sub build_query_from_search_string { |
|
31 my ($self, $search, $extra_columns, $extra_search_fields) = @_; |
|
32 |
|
33 my @values; |
|
34 |
|
35 # define a callback to collect values safely (without magic markers) |
|
36 my $cb = sub { |
|
37 my ($column, $this_op, $value) = @_; |
|
38 if($column->type eq "fuzzy") { |
|
39 if ( $this_op =~ /!|NOT/ ) { |
|
40 $this_op = " NOT ILIKE "; |
|
41 } else { |
|
42 $this_op = " ILIKE "; |
|
43 } |
|
44 $value = "%$value%"; |
|
45 } |
|
46 push @values, $value; |
|
47 return join('', $column->stringify, $this_op, '?'); |
|
48 }; |
|
49 |
|
50 my $search_fields = dclone($extra_search_fields); |
|
51 |
|
52 foreach my $k(keys %$search_fields) { |
|
53 $search_fields->{$k}->{callback} = $cb; |
|
54 } |
|
55 |
|
56 foreach my $extra_col(@$extra_columns) { |
|
57 $search_fields->{$extra_col->{id}} = { callback => $cb, name => $extra_col->{db_column} }; |
|
58 } |
|
59 |
|
60 my $parser = Search::QueryParser::SQL->new( |
|
61 columns => $search_fields, |
|
62 default_column => "function", |
|
63 strict => 1, |
|
64 ); |
|
65 |
|
66 my $query = $parser->parse($search, 1) |
|
67 or die "Error in query: " . $parser->err; |
|
68 |
|
69 # reset before calling dbi |
|
70 @values = (); |
|
71 my $dbi = $query->dbi(); |
|
72 |
|
73 return [ $dbi->[0], \@values ]; |
|
74 } |
|
75 |
|
76 1; |