OpenInteract2/Action/CommonSearch.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« OpenInteract2/Setup/InitializeSPOPS.pm ↑ Summary OpenInteract2/SQLInstall.pm »
1 package OpenInteract2::Action::CommonSearch;
2  
3 # $Id: CommonSearch.pm,v 1.24 2005/03/18 04:09:49 lachoy Exp $
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use base qw( OpenInteract2::Action::Common );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Log::Log4perl qw( get_logger );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use OpenInteract2::Constants qw( :log );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use OpenInteract2::Context qw( CTX );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use OpenInteract2::Exception qw( oi_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 0 ▶use OpenInteract2::ResultsManage;
Subroutine BEGIN: called CC=1 SCAR=2.6
12 use SPOPS::Iterator::WrapList;
13  
14 $OpenInteract2::Action::CommonSearch::VERSION = sprintf("%d.%02d", q$Revision: 1.24 $ =~ /(\d+)\.(\d+)/);
15  
16 my ( $log );
17  
18 ########################################
19 # SEARCH FORM
20  
21 sub search_form {
22 my ( $self ) = @_;
23 $self->param( c_task => 'search_form' );
24 $self->_search_form_init_param;
25 my %tmpl_params = ();
26 $self->_search_form_customize( \%tmpl_params );
27 my $search_template = $self->param( 'c_search_form_template' );
28 return $self->generate_content(
29 \%tmpl_params, { name => $search_template } );
30 }
31  
32 sub _search_form_init_param {
33 my ( $self ) = @_;
34 unless ( $self->param( 'c_search_form_template' ) ) {
35 $self->add_error_key( 'action.error.no_template', 'c_search_form_template' );
36 die $self->execute({ task => 'common_error' }), "\n";
37 }
38 return undef;
39 }
40  
41  
42 ########################################
43 # SEARCH
44  
45 sub search {
46 my ( $self ) = @_;
47 $self->param( c_task => 'search' );
48 $self->_search_init_param;
49 $log ||= get_logger( LOG_ACTION );
50  
51 my %tmpl_params = ();
52  
53 my $is_paged = $self->param( 'c_search_results_paged' );
54 if ( $is_paged eq 'yes' ) {
55 %tmpl_params = $self->_search_retrieve_paged_results;
56 }
57  
58 # If we're not using paged results, then just run the normal
59 # search and get back an iterator, but run through it once so we
60 # can count up the results
61  
62 else {
63 $log->is_debug &&
64 $log->debug( "Search results not paged, using basic iterator" );
65 my $iter = eval {
66 $self->_search_build_and_run();
67 };
68 $self->_search_catch_errors( "$@" );
69 my $items = $iter->get_all();
70 $log->is_debug &&
71 $log->debug( scalar( @{ $items } ), " objects in iterator, ",
72 "recreating iterator" );
73 $tmpl_params{iterator} = SPOPS::Iterator::WrapList->new({
74 object_list => $items
75 });
76 $tmpl_params{total_hits} = scalar @{ $items };
77 $tmpl_params{page_num} = 1;
78 $tmpl_params{total_pages} = 1;
79 }
80  
81 $tmpl_params{search_criteria} = $self->param( 'c_search_criteria' );
82 my $results_template = $self->param( 'c_search_results_template' );
83 $self->_search_customize( \%tmpl_params );
84 return $self->generate_content(
85 \%tmpl_params, { name => $results_template } );
86 }
87  
88 sub _search_retrieve_paged_results {
89 my ( $self ) = @_;
90 $log->is_debug && $log->debug( "Search results will be paged" );
91 my %display = ();
92  
93 my $req = CTX->request;
94 my $search_id = $req->param( 'search_id' );
95 my $results = OpenInteract2::ResultsManage->new();
96  
97 # If the search has been run before, just set the ID
98  
99 if ( $search_id ) {
100 $log->is_debug &&
101 $log->debug( "Retrieving search for ID '$search_id'" );
102 $results->{search_id} = $search_id;
103 }
104  
105 # Otherwise, run the search and get an iterator back, then pass
106 # the iterator to ResultsManage so we can reuse the results
107  
108 else {
109 $log->is_debug &&
110 $log->debug( "Running search for the first time" );
111 my $iterator = eval {
112 $self->_search_build_and_run();
113 };
114 $self->_search_catch_errors( "$@" );
115 $results->save( $iterator );
116 $log->is_debug &&
117 $log->debug( "Got search ID from stored results '$results->{search_id}'" );
118 }
119  
120 if ( $results->{search_id} ) {
121 my $this_page = $req->param( 'page_num' ) || 1;
122 my $hits_per_page = $self->param( 'c_search_results_page_size' );
123 my ( $min, $max ) =
124 $results->find_page_boundaries( $this_page, $hits_per_page );
125 $display{iterator} = $results->retrieve({
126 min => $min,
127 max => $max,
128 return_type => 'iterator' });
129 $display{page_num} = $this_page;
130 $display{total_pages} = $results->find_total_page_count( $hits_per_page );
131 $display{total_hits} = $results->{num_records};
132 $display{search_id} = $results->{search_id};
133 $log->is_debug && $log->debug( "Search info: [min: $min] [max: $max] ",
134 "[records: $results->{num_records}]" );
135 }
136 else {
137 $log->warn( "No search ID from results, creating empty iterator" );
138 $display{iterator} = SPOPS::Iterator->from_list( [] );
139 }
140 return %display;
141 }
142  
143  
144 my %DEFAULTS = (
145 c_search_results_paged => 'yes',
146 c_search_results_page_size => 50,
147 c_search_results_cap => 0,
148 c_search_table_links => {},
149 c_search_fail_task => 'search_form',
150 c_search_results_cap_fail_task => 'search_form',
151 );
152  
153 sub _search_init_param {
154 my ( $self ) = @_;
155 $self->_common_set_defaults( \%DEFAULTS );
156  
157 my $has_error =
158 $self->_common_check_template_specified( 'c_search_results_template' );
159 $has_error += $self->_common_check_object_class;
160  
161 my $table_links = $self->param( 'c_search_table_links' );
162 if ( ref $table_links eq 'HASH' ) {
163 while ( my ( $table, $id_link ) = each %{ $table_links } ) {
164 if ( ref $id_link ne 'ARRAY' ) {
165 my $msg = join( '', "Misconfigured search: there should ",
166 "be multiple entries in the ",
167 "'c_search_table_links' section for table ",
168 "[$table] under action [", $self->name, "]" );
169 $self->param_add( error_msg => $msg );
170 $has_error++;
171 }
172 else {
173 my $num_id_links = scalar @{ $id_link };
174  
175 # NOTE: There's nothing except simplicity stopping us
176 # from making this arbitrarily complex (6, 8, ...)
177  
178 unless ( $num_id_links == 2 || $num_id_links == 4 ) {
179 $self->add_error_key( 'action.error.search_table_links',
180 $table, $self->name );
181 $has_error++;
182 }
183 }
184 }
185 }
186 if ( $has_error ) {
187 die $self->execute({ task => 'common_error' }), "\n";
188 }
189  
190 # Now we're dealing with valid data...
191  
192 my @all_fields = (
193 $self->param( 'c_search_fields_like' ),
194 $self->param( 'c_search_fields_exact' ),
195 $self->param( 'c_search_fields_left_exact' ),
196 $self->param( 'c_search_fields_right_exact' )
197 );
198 $self->param( c_search_fields => \@all_fields );
199 return undef;
200 }
201  
202 sub _search_catch_errors {
203 my ( $self, $caught ) = @_;
204 return unless ( $caught );
205 my ( $msg, $task );
206 if ( $caught =~ /^CAP: (.*)$/ ) {
207 $msg = $self->_msg( 'action.error.search_too_many_results', $1 );
208 $task = $self->param( 'c_search_results_cap_fail_task' );
209 }
210 else {
211 $msg = $caught;
212 $task = $self->param( 'c_search_fail_task' );
213 }
214 $self->add_error( $msg );
215 die $self->execute({ task => $task }), "\n";
216 }
217  
218 # Build the search and run it, returning an iterator
219  
220 sub _search_build_and_run {
221 my ( $self ) = @_;
222 $log ||= get_logger( LOG_ACTION );
223  
224 $self->_search_build_criteria;
225 $self->_search_build_where_clause;
226  
227 my $object_class = $self->param( 'c_object_class' );
228  
229 # TODO: This is kind of (!!!) yucky -- run the same search twice?
230  
231 my @tables = $self->param( 'c_search_query_tables' );
232 my $where = join( ' AND ', $self->param( 'c_search_query_where' ) );
233 my @values = $self->param( 'c_search_query_values' );
234 if ( my $num_limit_results = $self->param( 'c_search_results_cap' ) ) {
235 my $row = eval {
236 $object_class->db_select({
237 select => [ 'count(*)' ],
238 from => \@tables,
239 where => $where,
240 value => \@values,
241 return => 'single' })
242 };
243 if ( $row->[0] > $num_limit_results ) {
244 oi_error "CAP: $row->[0] > $num_limit_results";
245 }
246 }
247  
248 $self->_search_calculate_limit;
249 my $limit = $self->param( 'c_search_query_limit' );
250 my $order = $self->param( 'c_search_results_order' );
251 my $additional_params = $self->_search_additional_params || {};
252 my $iter = eval {
253 $object_class->fetch_iterator({
254 from => \@tables,
255 where => $where,
256 value => \@values,
257 limit => $limit,
258 order => $order,
259 %{ $additional_params } })
260 };
261 if ( $@ ) {
262 $log->warn( "Search failed: $@" );
263 oi_error $@;
264 }
265 $log->is_info &&
266 $log->info( "Got iterator from '$object_class' ok" );
267 return $iter;
268 }
269  
270  
271 # Grab the specified fields and values out of the form
272 # submitted. Fields with multiple values are saved as arrayrefs.
273  
274 sub _search_build_criteria {
275 my ( $self ) = @_;
276 $log ||= get_logger( LOG_ACTION );
277  
278 my $object_class = $self->param( 'c_object_class' );
279 my $object_table = $object_class->base_table;
280 my ( %search );
281  
282 # Go through each search field and assign a value. If the search
283 # field is a simple one (no table.field), then prepend the object
284 # table to the fieldname
285  
286 my $req = CTX->request;
287 my @search_fields = $self->param( 'c_search_fields' );
288 foreach my $field ( @search_fields ) {
289 next unless ( $field );
290 my @value = $req->param( $field );
291 next unless ( defined $value[0] and $value[0] ne '' );
292 my $full_field = _fq( $object_table, $field );
293 $log->is_debug &&
294 $log->debug( "Adding search criteria [$field] [@value]" );
295 $search{ $full_field } = ( scalar @value > 1 ) ? \@value : $value[0];
296 }
297 $self->param( c_search_criteria => \%search );
298 $self->_search_criteria_customize;
299 return $self;
300 }
301  
302  
303 # Build a WHERE clause -- parameters with multiple values are 'OR',
304 # everything else is 'AND'. Example:
305 #
306 # ( table.last_name LIKE '%win%' OR table.last_name LIKE '%smi%' )
307 # AND ( table.first_name LIKE '%john%' )
308  
309 sub _search_build_where_clause {
310 my ( $self ) = @_;
311 $log ||= get_logger( LOG_ACTION );
312  
313 my $criteria = $self->param( 'c_search_criteria' );
314  
315 # Find all our configured information
316  
317 my $object_class = $self->param( 'c_object_class' );
318 my $object_table = $object_class->base_table;
319 my %from_tables = ( $object_table => 1 );
320 my %exact_match = map { _fq( $object_table, $_ ) => 1 }
321 $self->param( 'c_search_fields_exact' );
322 my %left_exact_match = map { _fq( $object_table, $_ ) => 1 }
323 $self->param( 'c_search_fields_left_exact' );
324 my %right_exact_match = map { _fq( $object_table, $_ ) => 1 }
325 $self->param( 'c_search_fields_right_exact' );
326  
327 # Go through each of the criteria set -- note that each one must
328 # be a fully-qualified (table.field) fieldname or it is discarded.
329  
330 my ( @where, @value ) = ();
331 while ( my ( $field_name, $field_value ) = each %{ $criteria } ) {
332 $log->is_debug &&
333 $log->debug( "Adding criteria [$field_name: $field_value]" );
334 next unless ( defined $field_value );
335  
336 # Discard unqualified fieldnames. Note that this regex will
337 # greedily swallow everything to the last '.' to accommodate
338 # systems that use a 'db.table' syntax to refer to a table.
339  
340 my ( $this_table ) = $field_name =~ /^([\w\.]*)\./;
341 next unless ( $this_table );
342  
343 # Track the table used
344  
345 $from_tables{ $this_table }++;
346  
347 # Normalize into an arrayref
348  
349 my $value_list = ( ref $field_value )
350 ? $field_value : [ $field_value ];
351  
352 # Hold the items for this particular criterion, which will be
353 # joined with an 'OR'
354  
355 my @where_param = ();
356 foreach my $value ( @{ $value_list } ) {
357  
358 # Value must be defined and non-empty to be set
359  
360 next unless ( defined $value and $value ne '' );
361  
362 # Default is a LIKE match (see POD)
363  
364 my $oper = ( $exact_match{ $field_name } ) ? '=' : 'LIKE';
365 push @where_param, " $field_name $oper ? ";
366 my ( $search_value );
367 if ( $exact_match{ $field_name } ) {
368 $search_value = $value;
369 }
370 elsif ( $left_exact_match{ $field_name } ) {
371 $search_value = "$value%";
372 }
373 elsif ( $right_exact_match{ $field_name } ) {
374 $search_value = "%$value";
375 }
376 else {
377 $search_value = "%$value%";
378 }
379 push @value, $search_value;
380 $log->is_debug &&
381 $log->debug( "Clause [$field_name $oper $search_value]" );
382 }
383 push @where, '( ' . join( ' OR ', @where_param ) . ' )';
384 }
385  
386 # Generate any statements needed to link tables for searching.
387  
388 # DO NOT replace '@tables_used' in the foreach with 'keys
389 # %from_tables' since we may add items to %from_tables during the
390 # loop. Also don't do an 'each %table_links' and then check to see
391 # if the table is in %from_tables for the same reason.
392  
393 my $table_links = $self->param( 'c_search_table_links' );
394 my @tables_used = keys %from_tables;
395  
396 TABLE:
397 foreach my $link_table ( @tables_used ) {
398 next if ( $link_table eq $object_table );
399 my $id_link = $table_links->{ $link_table };
400 unless ( ref $id_link eq 'ARRAY' ) {
401 $log->warn( "No links for non-object table used [$link_table]; ",
402 "this is likely a bad thing..." );
403 next TABLE;
404 }
405  
406 # See POD for what the values in 'c_search_table_links' mean;
407 # there should be either two or four
408  
409 my $num_linking_fields = scalar @{ $id_link };
410 if ( $num_linking_fields == 2 ) {
411 my ( $object_field, $link_field ) = @{ $id_link };
412 $log->is_debug &&
413 $log->debug( "Linking [$link_table] with ",
414 "[$object_field = $link_field]" );
415 push @where, "$object_field = $link_field";
416 }
417  
418 # Remember to add the linking table to our FROM list!
419  
420 elsif ( $num_linking_fields == 4 ) {
421 my ( $from, $middle_from, $middle_to, $to ) = @{ $id_link };
422 $log->is_debug &&
423 $log->debug( "Linking [$from = $middle_from > ",
424 "$middle_to = $to]" );
425 push @where, "$from = $middle_from ",
426 "$middle_to = $to";
427 my ( $middle_table ) = $middle_from =~ /^([\w\.]*)\./; # greedy on purpose
428 $from_tables{ $middle_table }++;
429 }
430 }
431  
432 $self->param( c_search_query_tables => [ keys %from_tables ] );
433 $self->param( c_search_query_where => \@where );
434 $self->param( c_search_query_values => \@value );
435 $self->_search_query_customize;
436  
437 $log->is_debug &&
438 $log->debug( join( "\n",
439 "Built SQL chunks: ",
440 " FROM: " .
441 join( ', ', $self->param( 'c_search_query_tables' ) ),
442 " WHERE: " . join( ' AND ', $self->param( 'c_search_query_where' ) ),
443 " VALUES: " . join( ', ', $self->param( 'c_search_query_values' ) ),
444 ) );
445 return $self;
446 }
447  
448  
449 # TODO: Where do min and max get set...?
450  
451 sub _search_calculate_limit {
452 my ( $self ) = @_;
453 my ( $limit );
454 my ( $min, $max ) = ( $self->param( 'min' ), $self->param( 'max' ) );
455 if ( $min or $max ) {
456 if ( $min and $max ) { $limit = "$min,$max" }
457 elsif ( $max ) { $limit = $max }
458 }
459 $self->param( c_search_query_limit => $limit );
460 }
461  
462 sub _fq {
463 my ( $table, $field ) = @_;
464 return ( $field =~ /\./ ) ? $field : "$table.$field";
465 }
466  
467 # Take a list of fields and ensure that each one is fully-qualified
468  
469 sub _fq_fields {
470 my ( $self, $table, @fields ) = @_;
471 return map { _fq( $table, $_ ) } @fields;
472 }
473  
474 ########################################
475 # OVERRIDABLE
476  
477 sub _search_form_customize { return undef }
478 sub _search_additional_params { return undef }
479 sub _search_criteria_customize { return undef }
480 sub _search_query_customize { return undef }
481 sub _search_customize { return undef }
482  
483 1;
484  
485 __END__
« OpenInteract2/Setup/InitializeSPOPS.pm ↑ Summary OpenInteract2/SQLInstall.pm »