Search.pm

filter: Statementstmt 100% 6 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 8 / 8 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« TEST/TestCase.pm ↑ Summary Search/Display/TEST/Grid.pm »
1 package CGI::Widget::DBI::Search;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 3 ▶use base qw/ CGI::Widget::DBI::Search::Base /;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 use vars qw/ $VERSION /;
7 $CGI::Widget::DBI::Search::VERSION = '0.31';
8  
9 use DBI;
10 use CGI::Widget::DBI::Search::Display::Table;
11 use CGI::Widget::DBI::Search::Display::Grid;
12  
13 # --------------------- USER CUSTOMIZABLE VARIABLES ------------------------
14  
15 # default values - these can be overridden by method parameters
16 use constant MAX_PER_PAGE => 20;
17 use constant PAGE_RANGE_NAV_LIMIT => 10;
18  
19 use constant SQL_DATABASE => '';
20  
21 use constant DBI_CONNECT_HOST => 'localhost';
22 #use constant DBI_CONNECT_DSN => 'DBI:mysql:database='.SQL_DATABASE().';host='.DBI_CONNECT_HOST();
23 use constant DBI_CONNECT_DSN => '';
24 use constant DBI_USER => '';
25 use constant DBI_PASS => '';
26  
27 # --------------------- END USER CUSTOMIZABLE VARIABLES --------------------
28  
29  
30 # VARS_TO_KEEP and cleanup() method not called anywhere; commented out
31  
32 # instance variables to keep across http requests
33 # NOTE: closure variables should NOT be kept! Storable cannot handle CODE refs
34 # use constant VARS_TO_KEEP => {# vars beginning with '-' are object config vars, set by programmer
35 # -sql_table => 1, -sql_table_columns => 1, -sql_retrieve_columns => 1,
36 # -pre_nondb_columns => 1, -post_nondb_columns => 1, -action_uri => 1,
37 # -display_columns => 1, -unsortable_columns => 1, -sortable_columns => 1, -default_orderby_columns => 1,
38 # -column_align => 1, -numeric_columns => 1, -currency_columns => 1,
39 # -optional_header => 1, -optional_footer => 1, -href_extra_vars => 1, -href_extra_vars_qs => 1,
40 # -where_clause => 1, -bind_params => 1, -opt_precols_sql => 1,
41 # -max_results_per_page => 1, -page_range_nav_limit => 1, -show_total_numresults => 1,
42 # -no_persistent_object => 1, -display_mode => 1, -display_class => 1,
43 # -grid_columns => 1, -browse_mode => 1,
44 # # vars not beginning with '-' are instance vars, set by methods in class
45 # results => 1, numresults => 1, page => 1, lastpage => 1, sortby => 1,
46 # page_sortby => 1, reverse_pagesort => 1,
47 # };
48  
49 # sub cleanup {
50 # my ($self) = @_;
51 # # delete instance variables not set to keep across http requests
52 # while (my ($k, $v) = each %$self) {
53 # delete $self->{$k} unless VARS_TO_KEEP->{$k};
54 # }
55 # }
56  
57 =head1 NAME
58  
59 CGI::Widget::DBI::Search - Database search widget
60  
61 =head1 SYNOPSIS
62  
63 use CGI;
64 use CGI::Widget::DBI::Search;
65  
66 my $q = CGI->new;
67 my $ws = CGI::Widget::DBI::Search->new(q => $q);
68  
69 # database connection info
70 $ws->{-dbi_connect_dsn} = 'DBI:Pg:dbname=my_pg_database;host=localhost';
71 $ws->{-dbi_user} = 'pguser';
72 $ws->{-dbi_pass} = 'pgpass';
73  
74 # what table to use in the SQL query FROM clause
75 $ws->{-sql_table} = 'table1 t1 inner join table2 t2 using (key_col)';
76  
77 # optional WHERE clause
78 $ws->{-where_clause} = 't1.filter = ? OR t2.filter != ?';
79 # bind params needed for WHERE clause
80 $ws->{-bind_params} = [ $filter, $inverse_filter ];
81  
82 # what columns to retrieve from query
83 $ws->{-sql_retrieve_columns} =
84 [ qw/t1.id t1.name t2.long_description/, '(t1.price + t2.price) AS total_price'];
85 # what columns to display in search results (with header name)
86 $ws->{-display_columns} =
87 { id => "ID", name => "Name", long_description => "Description", total_price => "Price" };
88  
89 $ws->{-numeric_columns} = { id => 1 };
90 $ws->{-currency_columns} = { total_price => 1 };
91 $ws->{-column_align} = { name => 'center' };
92  
93 #$ws->{-show_total_numresults} = 1; # set by default
94  
95 # execute database search
96 $ws->search();
97  
98 # output search results to browser
99 print $q->header;
100 print $q->start_html;
101  
102 # show search results as HTML
103 print $ws->display_results();
104  
105 print $q->end_html;
106  
107 =head1 DESCRIPTION
108  
109 Encapsulates a DBI search in a Perl class, including all SQL statements
110 required for performing the search, query results, HTML display methods,
111 and multi-column, sortable result set displayed page-by-page
112 (using HTML navigation links).
113  
114 =head1 CONSTRUCTOR
115  
116 =over 4
117  
118 =item new(@config_options)
119  
120 Creates and initializes a new CGI::Widget::DBI::Search object.
121 Possible configuration options:
122  
123 =item Database connection options
124  
125 -dbi_connect_dsn => DBI data source name (full connection string)
126 -dbi_user => database username
127 -dbi_pass => database password
128 -dbi_host => host to connect to database (overridden by -dbi_connect_dsn)
129 -sql_database => database to connect to (overridden by -dbi_connect_dsn)
130  
131 =item Database retrieval options
132  
133 -sql_table => Database table(s) to query,
134 -sql_table_columns => [ARRAY] List of all columns in sql_table,
135 -sql_retrieve_columns => [ARRAY] List of columns for retrieval,
136 -sql_search_columns => [ARRAY] (optional) List of columns to retrieve in
137 initial search, results to be saved to a temporary table.
138 (has no effect without -sql_join_for_dataset)
139 -sql_join_for_dataset => (optional) SQL join clause which will be appended -
140 in the FROM clause - to the temporary table generated
141 with columns from -sql_search_columns.
142 (has no effect without -sql_search_columns)
143 -opt_precols_sql => Optional SQL code to insert between 'SELECT' and
144 columns to retrieve (-sql_retrieve_columns).
145 This is commonly something like 'DISTINCT',
146 -where_clause => Literal SQL WHERE clause to use in SELECT state-
147 ment sent to database (may contain placeholders),
148 -default_orderby_columns => [ARRAY] Default list of columns to use in ORDER BY
149 clause. If 'sortby' cgi param is passed (e.g. from
150 user clicking a column sort link), it will always be
151 the first column in the ORDER BY clause, with these
152 coming after it.
153 -bind_params => [ARRAY] If -where_clause used placeholders ("?"),
154 this must be the ordered values to use for them,
155 -fetchrow_closure => (CODE) A code ref to execute upon retrieving a
156 single row of data from database. First arg to
157 closure will be calling object; subsequent args
158 will be the values of the retrieved row of data.
159 The closure's return value will be push()d onto the
160 object's results array, which is unique to a search.
161 It should be a hash reference with a key for each
162 column returned in the search, and values with the
163 search field values.
164 -dry_run => Do a dry run: just build SQL without actually running
165 it and building 'results' array. SQL statement that
166 would have been executed is in '_sql' object variable
167  
168  
169 =item Search result display options
170  
171 The following settings affect display of search results, but also affect
172 the search logic (SQL query executed).
173  
174 -max_results_per_page => Maximum number of database records to display on a
175 single page of search result display table
176 (default: 20)
177 -show_total_numresults => Show total number of records found by most recent
178 search, with First/Last page navigation links
179 (default: true)
180  
181 The following settings only affect display of search results, not the search logic.
182  
183 -display_columns => {HASH} Associative array holding column names as
184 keys, and labels for display table as values,
185 -column_titles => {HASH} Associative array holding column names as keys, and titles
186 (anchor titles, a.k.a mouseovers) for display table as values;
187 has effect only when using -display_mode => 'table
188 -column_align => {HASH} Keyed on column name to specify the table cell
189 html align attribute when using -display_mode => 'table'
190 -numeric_columns => {HASH} Columns of numeric type should have a
191 true value in this hash,
192 -currency_columns => {HASH} Columns of monetary value should have a
193 true value in this hash,
194 -unsortable_columns => {HASH} Columns which the user should not be able
195 to sort by should have a true value in this hash,
196 -sortable_columns => {HASH} Columns which the user should only be able
197 to sort by should have a true value in this hash,
198 -pre_nondb_columns => [ARRAY] Columns to show left of database columns
199 in display table,
200 -post_nondb_columns => [ARRAY] Columns to show right of database columns
201 in display table,
202 (Note: Since no data from the database will be present for
203 -{pre,post}_nondb_columns columns, you should define
204 -columndata_closures for each column you list)
205  
206 -optional_header => Optional HTML header to display just above search
207 result display table,
208 -optional_footer => Optional HTML footer to display just below search
209 result display table,
210 -href_extra_vars => {HASH} Extra CGI params to append to column sorting and
211 navigation links in search result display table.
212 If a key in the HASHREF has an undef value, will take the
213 value from an existing CGI param on request named the
214 same as key.
215 -href_extra_vars_qs => Extra CGI params (in query string form) to append to column sorting.
216 -form_extra_vars => {HASH} Extra CGI params to include in HTML as hidden
217 input fields. Note that the search widget itself doesn't
218 generate an HTML form, so if the search output is not
219 wrapped in an HTML form, these hidden inputs will be ignored
220 by browsers. The HASHREF has the same syntax as -href_extra_vars,
221 including the meaning of keys with undef values.
222 -action_uri => HTTP URI of script this is running under
223 (default: SCRIPT_NAME environment variable),
224 -action_uri_js_function => Optional javascript function call as action URI syntax. If this
225 is set, it overrides -action_uri and all navigation and sort links
226 become function calls to this function, with a single argument which
227 contains a JSON hash with all active search params. Note also, when
228 this is set, params -href_extra_vars will be converted to JSON
229 key/values and passed in the function call argument, but
230 -href_extra_vars_qs and -form_extra_vars will be ignored.
231 -page_range_nav_limit => Maximum number of pages to allow user to navigate to
232 before and after the current page in the result set
233 (default: 10)
234 -page_nav_link_onclick => Optional javascript code to call as onclick event when user clicks a
235 page navigation link (e.g. First, Prev, Next, Last, or page number)
236 -columndata_closures => {HASH} of (CODE): Reference to a hash containing a
237 code reference for each column which should be
238 passed through before displaying in result table.
239 Each closure will be passed 3 arguments:
240 $searchdispobj (the -display_class object),
241 $row (the current row from the result set)
242 $color (the current background color of this row)
243 and is (currently) expected to return an HTML table
244 cell (e.g. "<td>blah</td>")
245 -skip_utf8_decode => Boolean to control whether a utf8 decode is done on raw
246 (non- columndata_closure, non-numeric) data before displaying.
247 By default a utf8 decode is done in case there are utf8 chars
248 present, but if you know there will be no utf8 chars, enabling
249 this will increase performance. Has no effect when
250 -columndata_closures in effect for column.
251 (default: 0)
252  
253 -display_mode => ('table'|'grid') Which of the default display modes
254 to use, table or grid.
255 (default: table)
256 -display_class => Actual class to use to display search results.
257 (default: CGI::Widget::DBI::Search::Display::Table)
258 -grid_columns => Maximum number of columns to render, if displaying
259 as grid
260 -browse_mode => If true, hides sorting and paging options from search
261 result display. Used by CGI::Widget::DBI::Browse.
262  
263 =item Universal options
264  
265 -no_persistent_object => Inform object that we are not running under a
266 persistent object framework (eg. Apache::Session):
267 disable all features which enhance performance
268 under a persistence framework, and enable features
269 necessary for smooth operation without persistence
270 (default: true)
271  
272 =item CSS / Skinning options
273  
274 Note: these should really be named -html_... instead of -css_..., but leaving as-is for legacy code.
275  
276 -css_grid_id => (default: searchWidgetGridId)
277 -css_grid_class => (default: searchWidgetGridTable)
278 -css_grid_cell_class => (default: searchWidgetGridCell)
279  
280 -css_table_id => (default: searchWidgetTableId)
281 -css_table_class => (default: searchWidgetTableTable)
282 -css_table_row_class => (default: searchWidgetTableRow)
283 -css_table_header_row_class => (default: searchWidgetTableHeaderRow)
284 -css_table_cell_class => (default: searchWidgetTableCell)
285 -css_table_header_cell_class => (default: searchWidgetTableHeaderCell)
286 -css_table_unsortable_header_cell_class => (default: searchWidgetTableUnsortableHeaderCell)
287  
288 -extra_grid_cell_attributes => {HASH} Static attributes to add to the grid table cell (<TD> element),
289 -OR- (CODE) Dynamic attributes to add to the grid table cell (<TD> element); the
290 anonymous sub takes two arguments: the display object and the results row
291 -extra_table_cell_attributes => {HASH} -OR- (CODE) Same as above except for table display_mode instead of grid
292 -extra_table_header_cell_attributes => {HASH} -OR- (CODE) Same as above except for table display_mode instead of grid
293  
294 These can be configured for non-English apps (i18n):
295  
296 -i18n_translation_strings => {HASH} English-to-other-language hash used for user-visible words;
297 current strings displayed: Previous, Next, First, Last, At first page, At last page,
298 Skip to page, result, results, of, displayed, Sort by, Sort field,
299 (and if using Browse widget): Top, all results, Show all items in this category
300  
301 =back
302  
303 =head1 PRIVATE METHODS
304  
305 =over 4
306  
307 =item _set_defaults()
308  
309 Sets necessary object variables from defaults in package constants, if not already set.
310 Called from search() method.
311  
312 =cut
313  
314 sub _set_defaults {
315 my ($self) = @_;
316  
317 $self->{-dbi_connect_dsn} ||= DBI_CONNECT_DSN();
318 # default to mysql dsn if no other was specified
319 $self->{-dbi_connect_dsn} ||=
320 'DBI:mysql:database='.($self->{-sql_database}||'').';host='.($self->{-dbi_host}||'');
321 $self->{-dbi_user} ||= DBI_USER();
322 $self->{-dbi_pass} ||= DBI_PASS();
323  
324 $self->{-show_total_numresults} = 1
325 unless defined $self->{-show_total_numresults};
326 $self->{-no_persistent_object} = 1
327 unless defined $self->{-no_persistent_object};
328 }
329  
330 sub _find_sql_column_in_sql_columns {
331 my ($self, $alias_or_sql_column, $columns) = @_;
332 return (grep(
333 $_ eq $alias_or_sql_column || m/(?:as\s+|\.)$alias_or_sql_column\Z/i,
334 @$columns,
335 ))[0];
336 }
337  
338 sub _find_sql_column_in_sql_select_columns {
339 my ($self, $alias_or_sql_column) = @_;
340 return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, [$self->_columns_for_sql()]);
341 }
342  
343 sub _find_sql_column_in_sql_retrieve_columns {
344 my ($self, $alias_or_sql_column) = @_;
345 return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, $self->{-sql_retrieve_columns});
346 }
347  
348 sub _find_sql_column_in_sql_search_columns {
349 my ($self, $alias_or_sql_column) = @_;
350 return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, $self->{-sql_search_columns});
351 }
352  
353 sub _check_call_syntax {
354 my ($self) = @_;
355 # method call syntax checks
356 unless ($self->{-sql_table}
357 && ref $self->{-sql_retrieve_columns} eq 'ARRAY'
358 && (ref $self->{-dbh} && $self->{-dbh}->isa('DBI::db')
359 || $self->{-dbi_connect_dsn}
360 && defined $self->{-dbi_user}
361 && defined $self->{-dbi_pass})) {
362 $self->log_error(q|instance variables '-sql_table' (SCALAR), '-sql_retrieve_columns' (ARRAY); '-dbh' or '-dbi_connect_dsn' and '-dbi_user' and '-dbi_pass' (SCALARs) are required|);
363 return undef;
364 }
365 return 1;
366 }
367  
368 sub _connect_to_db {
369 my ($self) = @_;
370 return 2 if ref $self->{-dbh} && $self->{-dbh}->isa('DBI::db');
371 eval {
372 $self->{-dbh} = DBI->connect($self->{-dbi_connect_dsn}, $self->{-dbi_user},
373 $self->{-dbi_pass}, {'RaiseError' => 1});
374 };
375 if ($@) {
376 $self->log_error($@);
377 return undef;
378 }
379 return 1;
380 }
381  
382 =back
383  
384 =head1 METHODS
385  
386 =over 4
387  
388 =item search([ $where_clause, $bind_params, $clobber ])
389  
390 Perform the search: runs the database query, and stores the matched results in an
391 object variable: 'results'.
392  
393 Optional parameters $where_clause and $bind_params will override object
394 variables -where_clause and -bind_params. If $clobber is true, search results
395 from a previous execution will be deleted before running new search.
396  
397 After this method executes, various internal object variables will be set, to
398 indicate the state of the search. Here are some useful ones:
399  
400 (if -show_total_numresults is true)
401 page => current page in result set (0 indexed)
402 lastpage => last page in result set (0 indexed)
403  
404 =cut
405  
406 sub search {
407 my ($self, $where_clause, $bind_params, $clobber) = @_;
408 my $q = $self->{q};
409  
410 $self->_set_defaults();
411 return undef unless $self->_check_call_syntax();
412  
413 # clobber old search results if desired
414 if ($clobber) {
415 delete $self->{-where_clause};
416 delete $self->{-bind_params};
417 delete $self->{'results'};
418 }
419  
420 # handle paging logic
421 my $old_page = $self->{'page'};
422 $self->{'page'} = $q->param('search_startat')
423 if defined $q->param('search_startat');
424 $self->{'page'} ||= 0;
425  
426 # return cached results if page has not changed
427 if (defined $old_page && $self->{'page'} == $old_page && ref $self->{'results'} eq 'ARRAY') {
428 $self->warn('no page change, using cached results');
429 return $self;
430 }
431  
432 # read sortby column from cgi
433 $self->{'sortby'} = $q->param('sortby') if $q->param('sortby');
434 $self->{'sort_reverse'} ||= {};
435 $self->{'sort_reverse'}->{ $self->{'sortby'} } = $q->param('sort_reverse')
436 if defined $q->param('sort_reverse');
437  
438 $self->{-where_clause} = $where_clause if $where_clause;
439 $self->{-where_clause} =~ s/^\s*where//i if $self->{-where_clause};
440 $self->{-bind_params} = $bind_params if ref $bind_params eq 'ARRAY';
441 $self->{-max_results_per_page} ||= MAX_PER_PAGE;
442 $self->{-page_range_nav_limit} ||= PAGE_RANGE_NAV_LIMIT;
443 $self->{-limit_clause} =
444 ('LIMIT '.($self->{-max_results_per_page}*$self->{'page'}).','.
445 $self->{-max_results_per_page});
446 $self->{-opt_precols_sql} ||= '';
447 my $orig_opt_precols_sql = $self->{-opt_precols_sql};
448 $self->{-opt_precols_sql} .= ' SQL_CALC_FOUND_ROWS '
449 if $self->{-show_total_numresults} && $self->{-opt_precols_sql} !~ m/SQL_CALC_FOUND_ROWS/i;
450  
451 my @orderby;
452 if (ref $self->{-default_orderby_columns} eq 'ARRAY') {
453 @orderby = @{ $self->{-default_orderby_columns} };
454 }
455 if ($self->{'sortby'}) {
456 if (_find_sql_column_in_sql_select_columns($self, $self->{'sortby'})) {
457 @orderby = ($self->{'sortby'}, grep($_ ne $self->{'sortby'}, @orderby));
458 }
459 }
460 $self->{-orderby_clause} =
461 'ORDER BY '.join(',', map {$_.($self->{'sort_reverse'}->{$_} ? ' DESC' : '')} @orderby)
462 if @orderby;
463 # TODO: we should support a custom -orderby_clause and not just clobber it each time
464  
465  
466 $self->_build_sql();
467 return $self if $self->{-dry_run};
468  
469 my $conn_code = $self->_connect_to_db();
470 return undef if ! $conn_code;
471  
472 my $should_disconnect = $conn_code == 1;
473  
474 if ($self->{-sql_search_columns} && $self->{-sql_join_for_dataset}) {
475 eval {
476 # tmp_search_results may already exist even in production code, due to use of Apache::DBI
477 $self->{-dbh}->do('DROP TABLE IF EXISTS tmp_search_results');
478 my @search_sql = (<<"SQL1",<<'SQL2',<<"SQL3");
479 CREATE TEMPORARY TABLE tmp_search_results AS
480 @{[ $self->{'_sql_no_limit'} ]} LIMIT 0
481 SQL1
482 ALTER TABLE tmp_search_results ADD row_index INT AUTO_INCREMENT PRIMARY KEY FIRST
483 SQL2
484 INSERT INTO tmp_search_results (
485 @{[ join(',', map { $self->extract_alias_from_sql_column($_) } @{ $self->{-sql_search_columns} }) ]}
486 )
487 @{[ $self->{'_sql'} ]}
488 SQL3
489 my @bind_params = @{ $self->{-bind_params} || [] };
490 $self->warn('SQL search statement: '.join(";\n", @search_sql)
491 ."\nbind params: ".join(', ', @bind_params));
492 $self->{-dbh}->do(shift @search_sql, undef, @bind_params);
493 $self->{-dbh}->do(shift @search_sql);
494 $self->{-dbh}->do(shift @search_sql, undef, @bind_params);
495 $self->get_num_results();
496 };
497 if ($@) {
498 $self->log_error($@);
499 return undef;
500 }
501 $self->{-sql_search_columns} = undef;
502 $self->{-sql_table} = 'tmp_search_results '.$self->{-sql_join_for_dataset};
503 $self->{-where_clause} = undef;
504 $self->{-bind_params} = undef;
505 $self->{-orderby_clause} = 'ORDER BY row_index';
506 $self->{-opt_precols_sql} = $orig_opt_precols_sql;
507 $self->{-limit_clause} = undef;
508 $self->_build_sql();
509 }
510  
511 eval {
512 my $sth = $self->{-dbh}->prepare_cached( $self->{'_sql'} );
513  
514 my @bind_params = @{ $self->{-bind_params} || [] };
515 $self->warn("SQL statement: $self->{'_sql'}; bind params: ".join(', ', @bind_params));
516 $sth->execute(@bind_params);
517  
518 $self->{'results'} = [];
519 if (ref $self->{-fetchrow_closure} eq 'CODE') {
520 my @row_data;
521 $sth->bind_columns
522 (map { \$row_data[$_] } 0..$#{$self->{-sql_retrieve_columns}});
523  
524 while ($sth->fetchrow_arrayref) {
525 push(@{$self->{'results'}}, $self->{-fetchrow_closure}->($self, @row_data));
526 }
527 } else {
528 $self->{'results'} = $sth->fetchall_arrayref({});
529 }
530  
531 $sth->finish();
532  
533 $self->get_num_results();
534  
535 $self->{-dbh}->disconnect() if $should_disconnect;
536 };
537 if ($@) {
538 $self->log_error("SQL statement: $self->{'_sql'}; bind params: ".join(', ', @{ $self->{-bind_params} || [] }));
539 $self->log_error($@);
540 return undef;
541 }
542  
543 #$self->pagesort_results($self->{'page_sortby'}) if $self->{'page_sortby'};
544 return $self;
545 }
546  
547 sub _build_sql {
548 my ($self) = @_;
549 $self->{'_sql_no_limit'} = (
550 'SELECT '.$self->{-opt_precols_sql}.' '.join(',', $self->_columns_for_sql()).
551 ' FROM '.$self->{-sql_table}.' '.
552 ($self->{-where_clause} ? 'WHERE '.$self->{-where_clause} : '').' '.
553 ($self->{-orderby_clause}||'')
554 );
555 $self->{'_sql'} = $self->{'_sql_no_limit'}.' '.($self->{-limit_clause}||'');
556 }
557  
558 sub _columns_for_sql {
559 my ($self) = @_;
560 return $self->{-sql_search_columns} && $self->{-sql_join_for_dataset}
561 ? @{ $self->{-sql_search_columns} } : @{ $self->{-sql_retrieve_columns} };
562 }
563  
564 =item get_num_results()
565  
566 Executes a SELECT COUNT() query with the current search parameters and stores result
567 in object variable: 'numresults'. Has no effect unless -show_total_numresults object
568 variable is true. As a side-effect, this method also sets the 'lastpage' object
569 variable which, no surprise, is the page number denoting the last page in the search
570 result set.
571  
572 This is used for displaying total number of results found, and is
573 necessary to provide a last-page link to skip to the end of the search results.
574  
575 =cut
576  
577 sub get_num_results {
578 my ($self) = @_;
579 return if ! $self->{-show_total_numresults} || defined $self->{'numresults'};
580  
581 # read total number of results in search set (mysql only)
582 $self->{'numresults'} = @{ $self->{-dbh}->selectrow_arrayref('SELECT FOUND_ROWS()') || [] }[0];
583 $self->{'lastpage'} = int(($self->{'numresults'} - 1) / $self->{-max_results_per_page});
584 return $self->{'numresults'};
585 }
586  
587 =item pagesort_results($col, $reverse)
588  
589 Sorts a single page of results by column $col. Reorders object variable 'results'
590 based on sort column $col and boolean $reverse parameters.
591  
592 (note: method currently unused)
593  
594 =cut
595  
596 # sub pagesort_results {
597 # my ($self, $col, $reverse) = @_;
598  
599 # # handle sorting by arbitrary data column
600 # if ($self->{'page_sortby'} and $reverse) {
601 # # toggle reverse flag if they clicked the current sort column
602 # $self->{'reverse_pagesort'}->{$self->{'page_sortby'}} =
603 # $self->{'reverse_pagesort'}->{$self->{'page_sortby'}} ? 0 : 1;
604 # @{$self->{'results'}} = reverse @{$self->{'results'}};
605 # } else {
606 # # set new page_sortby column, and sort results array
607 # $self->{'page_sortby'} = $col;
608 # @{$self->{'results'}} = sort {
609 # ($self->{-numeric_columns}->{$self->{'page_sortby'}} ||
610 # $self->{-currency_columns}->{$self->{'page_sortby'}}
611 # ? $a->{$self->{'page_sortby'}} <=> $b->{$self->{'page_sortby'}}
612 # : uc($a->{$self->{'page_sortby'}}) cmp uc($b->{$self->{'page_sortby'}}))
613 # } @{$self->{'results'}};
614 # @{$self->{'results'}} = reverse @{$self->{'results'}}
615 # if $self->{'reverse_pagesort'}->{$self->{'page_sortby'}};
616 # }
617 # }
618  
619 =item append_where_clause($where_sql, [ $op ])
620  
621 Adds an SQL expression to the current -where_clause, if any. Optional $op specifies the
622 SQL operator to attach the expression with (default: AND).
623  
624 =item append_bind_params(@bind_params)
625  
626 Appends extra bind params to the end of the current list of -bind_params.
627  
628 =cut
629  
630 sub append_where_clause {
631 my ($self, $where_sql, $op) = @_;
632 return if ! $where_sql;
633 $op ||= 'AND';
634 $self->{-where_clause} = ($self->{-where_clause} ? '( '.$self->{-where_clause}.' ) '.$op.' ' : '') . '( '.$where_sql.' )';
635 }
636  
637 sub append_bind_params {
638 my ($self, @bind_params) = @_;
639 return if ! @bind_params;
640 $self->{-bind_params} ||= [];
641 push(@{ $self->{-bind_params} }, @bind_params);
642 }
643  
644  
645 =item init_display_class([ $disp_cols ])
646  
647 Instantiates and initializes the desired display object. Returns it and sets in 'display' object variable.
648 This is called by display_results(), and does not normally need to be called directly.
649  
650 =item display_results([ $disp_cols ])
651  
652 Displays an HTML table of data values stored in object variable 'results' (retrieved
653 from the most recent call to search() method). Optional variable $disp_cols overrides
654 object variable -display_columns.
655  
656 =cut
657  
658 sub init_display_class {
659 my ($self, $disp_cols) = @_;
660 unless (ref $self->{'results'} eq 'ARRAY' &&
661 (ref $self->{-sql_table_columns} eq 'ARRAY' ||
662 ref $self->{-sql_retrieve_columns} eq 'ARRAY')) {
663 $self->log_error(q|instance variables '-sql_table_columns' or '-sql_retrieve_columns', and data resultset 'results' (ARRAYs) are required|);
664 return undef;
665 }
666  
667 $self->{-display_columns} = $disp_cols if ref $disp_cols eq 'HASH';
668 $self->{-display_class} ||= ($self->{-display_mode}||'') eq 'grid'
669 ? 'CGI::Widget::DBI::Search::Display::Grid'
670 : 'CGI::Widget::DBI::Search::Display::Table';
671  
672 $self->{display} = $self->{-display_class}->new($self);
673 $self->transfer_display_settings();
674 return $self->{display};
675 }
676  
677 sub display_results {
678 my ($self, $disp_cols) = @_;
679 return undef if ! $self->init_display_class($disp_cols);
680 return $self->{display}->display();
681 }
682  
683 =item translate($string)
684  
685 Translation method: just looks up $string in -i18n_translation_strings hash, and if a hit is found returns it;
686 otherwise returns $string.
687  
688 =item transfer_display_settings()
689  
690 Transfers all display-specific settings from search widget object to the
691 search display widget object.
692  
693 =cut
694  
695 sub transfer_display_settings {
696 my ($self) = @_;
697 foreach my $var (
698 qw/results
699 numresults
700 page
701 lastpage
702 sortby
703 sort_reverse
704 /) {
705 $self->{display}->{$var} = $self->{$var} if defined $self->{$var};
706 }
707 foreach my $var (keys %$self) {
708 $self->{display}->{$var} = $self->{$var} if substr($var, 0, 1) eq '-';
709 }
710 }
711  
712 sub sql_search_column_for_alias {
713 my ($self, $alias_or_sql_column) = @_;
714 my $sql_col = _find_sql_column_in_sql_search_columns($self, $alias_or_sql_column);
715 ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+$alias_or_sql_column\Z/i )
716 if $sql_col && $sql_col =~ m/as\s+$alias_or_sql_column\Z/i;
717 return $sql_col || $alias_or_sql_column;
718 }
719  
720 sub sql_column_for_alias {
721 my ($self, $alias_or_sql_column) = @_;
722 my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column);
723 ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+$alias_or_sql_column\Z/i )
724 if $sql_col && $sql_col =~ m/as\s+$alias_or_sql_column\Z/i;
725 return $sql_col || $alias_or_sql_column;
726 }
727  
728 sub sql_column_with_tbl_alias_for_alias {
729 my ($self, $alias_or_sql_column) = @_;
730 my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column);
731 $sql_col =~ s/\s+as\s+$alias_or_sql_column\Z//i if $sql_col;
732 return $sql_col || $alias_or_sql_column;
733 }
734  
735 sub full_sql_column_for_alias {
736 my ($self, $alias_or_sql_column) = @_;
737 my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column);
738 return $sql_col || $alias_or_sql_column;
739 }
740  
741 sub sql_column_for_full_sql_column_with_alias {
742 my ($self, $full_sql_column) = @_;
743 my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $full_sql_column);
744 ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+.+\Z/i ) if $sql_col;
745 return $sql_col || $full_sql_column;
746 }
747  
748 sub extract_alias_from_sql_column {
749 my ($self, $full_sql_column) = @_;
750 my ($alias) = ( $full_sql_column =~ m/\s+as\s+(.+)\Z/i );
751 return $alias || $full_sql_column;
752 }
753  
754  
755 1;
756 __END__
« TEST/TestCase.pm ↑ Summary Search/Display/TEST/Grid.pm »