| 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.30'; | ||
| 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 | ||
| 182 | search logic. | ||
| 183 | |||
| 184 | -display_columns => {HASH} Associative array holding column names as | ||
| 185 | keys, and labels for display table as values, | ||
| 186 | -column_titles => {HASH} Associative array holding column names as keys, and titles | ||
| 187 | (anchor titles, a.k.a mouseovers) for display table as values; | ||
| 188 | has effect only when using -display_mode => 'table | ||
| 189 | -column_align => {HASH} Keyed on column name to specify the table cell | ||
| 190 | html align attribute when using -display_mode => 'table' | ||
| 191 | -numeric_columns => {HASH} Columns of numeric type should have a | ||
| 192 | true value in this hash, | ||
| 193 | -currency_columns => {HASH} Columns of monetary value should have a | ||
| 194 | true value in this hash, | ||
| 195 | -unsortable_columns => {HASH} Columns which the user should not be able | ||
| 196 | to sort by should have a true value in this hash, | ||
| 197 | -sortable_columns => {HASH} Columns which the user should only be able | ||
| 198 | to sort by should have a true value in this hash, | ||
| 199 | -pre_nondb_columns => [ARRAY] Columns to show left of database columns | ||
| 200 | in display table, | ||
| 201 | -post_nondb_columns => [ARRAY] Columns to show right of database columns | ||
| 202 | in display table, | ||
| 203 | (Note: Since no data from the database will be present for | ||
| 204 | -{pre,post}_nondb_columns columns, you should define | ||
| 205 | -columndata_closures for each column you list) | ||
| 206 | |||
| 207 | -optional_header => Optional HTML header to display just above search | ||
| 208 | result display table, | ||
| 209 | -optional_footer => Optional HTML footer to display just below search | ||
| 210 | result display table, | ||
| 211 | -href_extra_vars => {HASH} Extra CGI params to append to column sorting and | ||
| 212 | navigation links in search result display table. | ||
| 213 | If a key in the HASHREF has an undef value, will take the | ||
| 214 | value from an existing CGI param on request named the | ||
| 215 | same as key. | ||
| 216 | -href_extra_vars_qs => Extra CGI params (in query string form) to append to column sorting. | ||
| 217 | -form_extra_vars => {HASH} Extra CGI params to include in HTML as hidden | ||
| 218 | input fields. Note that the search widget itself doesn't | ||
| 219 | generate an HTML form, so if the search output is not | ||
| 220 | wrapped in an HTML form, these hidden inputs will be ignored | ||
| 221 | by browsers. The HASHREF has the same syntax as -href_extra_vars, | ||
| 222 | including the meaning of keys with undef values. | ||
| 223 | -action_uri => HTTP URI of script this is running under | ||
| 224 | (default: SCRIPT_NAME environment variable), | ||
| 225 | -page_range_nav_limit => Maximum number of pages to allow user to navigate to | ||
| 226 | before and after the current page in the result set | ||
| 227 | (default: 10) | ||
| 228 | -columndata_closures => {HASH} of (CODE): Reference to a hash containing a | ||
| 229 | code reference for each column which should be | ||
| 230 | passed through before displaying in result table. | ||
| 231 | Each closure will be passed 3 arguments: | ||
| 232 | $searchdispobj (the -display_class object), | ||
| 233 | $row (the current row from the result set) | ||
| 234 | $color (the current background color of this row) | ||
| 235 | and is (currently) expected to return an HTML table | ||
| 236 | cell (e.g. "<td>blah</td>") | ||
| 237 | -skip_utf8_decode => Boolean to control whether a utf8 decode is done on raw | ||
| 238 | (non- columndata_closure, non-numeric) data before displaying. | ||
| 239 | By default a utf8 decode is done in case there are utf8 chars | ||
| 240 | present, but if you know there will be no utf8 chars, enabling | ||
| 241 | this will increase performance. Has no effect when | ||
| 242 | -columndata_closures in effect for column. | ||
| 243 | (default: 0) | ||
| 244 | |||
| 245 | -display_mode => ('table'|'grid') Which of the default display modes | ||
| 246 | to use, table or grid. | ||
| 247 | (default: table) | ||
| 248 | -display_class => Actual class to use to display search results. | ||
| 249 | (default: CGI::Widget::DBI::Search::Display::Table) | ||
| 250 | -grid_columns => Maximum number of columns to render, if displaying | ||
| 251 | as grid | ||
| 252 | -browse_mode => If true, hides sorting and paging options from search | ||
| 253 | result display. Used by CGI::Widget::DBI::Browse. | ||
| 254 | |||
| 255 | =item Universal options | ||
| 256 | |||
| 257 | -no_persistent_object => Inform object that we are not running under a | ||
| 258 | persistent object framework (eg. Apache::Session): | ||
| 259 | disable all features which enhance performance | ||
| 260 | under a persistence framework, and enable features | ||
| 261 | necessary for smooth operation without persistence | ||
| 262 | (default: true) | ||
| 263 | |||
| 264 | =item CSS / Skinning options | ||
| 265 | |||
| 266 | -css_grid_class => (default: searchWidgetGridTable) | ||
| 267 | -css_grid_cell_class => (default: searchWidgetGridCell) | ||
| 268 | |||
| 269 | -css_table_class => (default: searchWidgetTableTable) | ||
| 270 | -css_table_row_class => (default: searchWidgetTableRow) | ||
| 271 | -css_table_header_row_class => (default: searchWidgetTableHeaderRow) | ||
| 272 | -css_table_cell_class => (default: searchWidgetTableCell) | ||
| 273 | -css_table_header_cell_class => (default: searchWidgetTableHeaderCell) | ||
| 274 | -css_table_unsortable_header_cell_class => (default: searchWidgetTableUnsortableHeaderCell) | ||
| 275 | |||
| 276 | -extra_grid_cell_attributes => {HASH} Static attributes to add to the grid table cell (<TD> element), | ||
| 277 | -OR- (CODE) Dynamic attributes to add to the grid table cell (<TD> element); the | ||
| 278 | anonymous sub takes two arguments: the display object and the results row | ||
| 279 | -extra_table_cell_attributes => {HASH} -OR- (CODE) Same as above except for table display_mode instead of grid | ||
| 280 | -extra_table_header_cell_attributes => {HASH} -OR- (CODE) Same as above except for table display_mode instead of grid | ||
| 281 | |||
| 282 | =back | ||
| 283 | |||
| 284 | =head1 PRIVATE METHODS | ||
| 285 | |||
| 286 | =over 4 | ||
| 287 | |||
| 288 | =item _set_defaults() | ||
| 289 | |||
| 290 | Sets necessary object variables from defaults in package constants, if not already set. | ||
| 291 | Called from search() method. | ||
| 292 | |||
| 293 | =cut | ||
| 294 | |||
| 295 | sub _set_defaults { | ||
| 296 | my ($self) = @_; | ||
| 297 | |||
| 298 | $self->{-dbi_connect_dsn} ||= DBI_CONNECT_DSN(); | ||
| 299 | # default to mysql dsn if no other was specified | ||
| 300 | $self->{-dbi_connect_dsn} ||= | ||
| 301 | 'DBI:mysql:database='.($self->{-sql_database}||'').';host='.($self->{-dbi_host}||''); | ||
| 302 | $self->{-dbi_user} ||= DBI_USER(); | ||
| 303 | $self->{-dbi_pass} ||= DBI_PASS(); | ||
| 304 | |||
| 305 | $self->{-show_total_numresults} = 1 | ||
| 306 | unless defined $self->{-show_total_numresults}; | ||
| 307 | $self->{-no_persistent_object} = 1 | ||
| 308 | unless defined $self->{-no_persistent_object}; | ||
| 309 | } | ||
| 310 | |||
| 311 | sub _find_sql_column_in_sql_columns { | ||
| 312 | my ($self, $alias_or_sql_column, $columns) = @_; | ||
| 313 | return (grep( | ||
| 314 | $_ eq $alias_or_sql_column || m/(?:as\s+|\.)$alias_or_sql_column\Z/i, | ||
| 315 | @$columns, | ||
| 316 | ))[0]; | ||
| 317 | } | ||
| 318 | |||
| 319 | sub _find_sql_column_in_sql_select_columns { | ||
| 320 | my ($self, $alias_or_sql_column) = @_; | ||
| 321 | return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, [$self->_columns_for_sql()]); | ||
| 322 | } | ||
| 323 | |||
| 324 | sub _find_sql_column_in_sql_retrieve_columns { | ||
| 325 | my ($self, $alias_or_sql_column) = @_; | ||
| 326 | return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, $self->{-sql_retrieve_columns}); | ||
| 327 | } | ||
| 328 | |||
| 329 | sub _find_sql_column_in_sql_search_columns { | ||
| 330 | my ($self, $alias_or_sql_column) = @_; | ||
| 331 | return _find_sql_column_in_sql_columns($self, $alias_or_sql_column, $self->{-sql_search_columns}); | ||
| 332 | } | ||
| 333 | |||
| 334 | sub _check_call_syntax { | ||
| 335 | my ($self) = @_; | ||
| 336 | # method call syntax checks | ||
| 337 | unless ($self->{-sql_table} | ||
| 338 | && ref $self->{-sql_retrieve_columns} eq 'ARRAY' | ||
| 339 | && (ref $self->{-dbh} && $self->{-dbh}->isa('DBI::db') | ||
| 340 | || $self->{-dbi_connect_dsn} | ||
| 341 | && defined $self->{-dbi_user} | ||
| 342 | && defined $self->{-dbi_pass})) { | ||
| 343 | $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|); | ||
| 344 | return undef; | ||
| 345 | } | ||
| 346 | return 1; | ||
| 347 | } | ||
| 348 | |||
| 349 | sub _connect_to_db { | ||
| 350 | my ($self) = @_; | ||
| 351 | return 2 if ref $self->{-dbh} && $self->{-dbh}->isa('DBI::db'); | ||
| 352 | eval { | ||
| 353 | $self->{-dbh} = DBI->connect($self->{-dbi_connect_dsn}, $self->{-dbi_user}, | ||
| 354 | $self->{-dbi_pass}, {'RaiseError' => 1}); | ||
| 355 | }; | ||
| 356 | if ($@) { | ||
| 357 | $self->log_error($@); | ||
| 358 | return undef; | ||
| 359 | } | ||
| 360 | return 1; | ||
| 361 | } | ||
| 362 | |||
| 363 | =back | ||
| 364 | |||
| 365 | =head1 METHODS | ||
| 366 | |||
| 367 | =over 4 | ||
| 368 | |||
| 369 | =item search([ $where_clause, $bind_params, $clobber ]) | ||
| 370 | |||
| 371 | Perform the search: runs the database query, and stores the matched results in an | ||
| 372 | object variable: 'results'. | ||
| 373 | |||
| 374 | Optional parameters $where_clause and $bind_params will override object | ||
| 375 | variables -where_clause and -bind_params. If $clobber is true, search results | ||
| 376 | from a previous execution will be deleted before running new search. | ||
| 377 | |||
| 378 | After this method executes, various internal object variables will be set, to | ||
| 379 | indicate the state of the search. Here are some useful ones: | ||
| 380 | |||
| 381 | (if -show_total_numresults is true) | ||
| 382 | page => current page in result set (0 indexed) | ||
| 383 | lastpage => last page in result set (0 indexed) | ||
| 384 | |||
| 385 | =cut | ||
| 386 | |||
| 387 | sub search { | ||
| 388 | my ($self, $where_clause, $bind_params, $clobber) = @_; | ||
| 389 | my $q = $self->{q}; | ||
| 390 | |||
| 391 | $self->_set_defaults(); | ||
| 392 | return undef unless $self->_check_call_syntax(); | ||
| 393 | |||
| 394 | # clobber old search results if desired | ||
| 395 | if ($clobber) { | ||
| 396 | delete $self->{-where_clause}; | ||
| 397 | delete $self->{-bind_params}; | ||
| 398 | delete $self->{'results'}; | ||
| 399 | } | ||
| 400 | |||
| 401 | # handle paging logic | ||
| 402 | my $old_page = $self->{'page'}; | ||
| 403 | $self->{'page'} = $q->param('search_startat') | ||
| 404 | if defined $q->param('search_startat'); | ||
| 405 | $self->{'page'} ||= 0; | ||
| 406 | |||
| 407 | # return cached results if page has not changed | ||
| 408 | if (defined $old_page && $self->{'page'} == $old_page && ref $self->{'results'} eq 'ARRAY') { | ||
| 409 | $self->warn('no page change, using cached results'); | ||
| 410 | return $self; | ||
| 411 | } | ||
| 412 | |||
| 413 | # read sortby column from cgi | ||
| 414 | $self->{'sortby'} = $q->param('sortby') if $q->param('sortby'); | ||
| 415 | $self->{'sort_reverse'} ||= {}; | ||
| 416 | $self->{'sort_reverse'}->{ $self->{'sortby'} } = $q->param('sort_reverse') | ||
| 417 | if defined $q->param('sort_reverse'); | ||
| 418 | |||
| 419 | $self->{-where_clause} = $where_clause if $where_clause; | ||
| 420 | $self->{-where_clause} =~ s/^\s*where//i if $self->{-where_clause}; | ||
| 421 | $self->{-bind_params} = $bind_params if ref $bind_params eq 'ARRAY'; | ||
| 422 | $self->{-max_results_per_page} ||= MAX_PER_PAGE; | ||
| 423 | $self->{-page_range_nav_limit} ||= PAGE_RANGE_NAV_LIMIT; | ||
| 424 | $self->{-limit_clause} = | ||
| 425 | ('LIMIT '.($self->{-max_results_per_page}*$self->{'page'}).','. | ||
| 426 | $self->{-max_results_per_page}); | ||
| 427 | $self->{-opt_precols_sql} ||= ''; | ||
| 428 | my $orig_opt_precols_sql = $self->{-opt_precols_sql}; | ||
| 429 | $self->{-opt_precols_sql} .= ' SQL_CALC_FOUND_ROWS ' | ||
| 430 | if $self->{-show_total_numresults} && $self->{-opt_precols_sql} !~ m/SQL_CALC_FOUND_ROWS/i; | ||
| 431 | |||
| 432 | my @orderby; | ||
| 433 | if (ref $self->{-default_orderby_columns} eq 'ARRAY') { | ||
| 434 | @orderby = @{ $self->{-default_orderby_columns} }; | ||
| 435 | } | ||
| 436 | if ($self->{'sortby'}) { | ||
| 437 | if (_find_sql_column_in_sql_select_columns($self, $self->{'sortby'})) { | ||
| 438 | @orderby = ($self->{'sortby'}, grep($_ ne $self->{'sortby'}, @orderby)); | ||
| 439 | } | ||
| 440 | } | ||
| 441 | $self->{-orderby_clause} = | ||
| 442 | 'ORDER BY '.join(',', map {$_.($self->{'sort_reverse'}->{$_} ? ' DESC' : '')} @orderby) | ||
| 443 | if @orderby; | ||
| 444 | # TODO: we should support a custom -orderby_clause and not just clobber it each time | ||
| 445 | |||
| 446 | |||
| 447 | $self->_build_sql(); | ||
| 448 | return $self if $self->{-dry_run}; | ||
| 449 | |||
| 450 | my $conn_code = $self->_connect_to_db(); | ||
| 451 | return undef if ! $conn_code; | ||
| 452 | |||
| 453 | my $should_disconnect = $conn_code == 1; | ||
| 454 | |||
| 455 | if ($self->{-sql_search_columns} && $self->{-sql_join_for_dataset}) { | ||
| 456 | eval { | ||
| 457 | # tmp_search_results may already exist even in production code, due to use of Apache::DBI | ||
| 458 | $self->{-dbh}->do('DROP TABLE IF EXISTS tmp_search_results'); | ||
| 459 | my @search_sql = (<<"SQL1",<<'SQL2',<<"SQL3"); | ||
| 460 | CREATE TEMPORARY TABLE tmp_search_results AS | ||
| 461 | @{[ $self->{'_sql_no_limit'} ]} LIMIT 0 | ||
| 462 | SQL1 | ||
| 463 | ALTER TABLE tmp_search_results ADD row_index INT AUTO_INCREMENT PRIMARY KEY FIRST | ||
| 464 | SQL2 | ||
| 465 | INSERT INTO tmp_search_results ( | ||
| 466 | @{[ join(',', map { $self->extract_alias_from_sql_column($_) } @{ $self->{-sql_search_columns} }) ]} | ||
| 467 | ) | ||
| 468 | @{[ $self->{'_sql'} ]} | ||
| 469 | SQL3 | ||
| 470 | my @bind_params = @{ $self->{-bind_params} || [] }; | ||
| 471 | $self->warn('SQL search statement: '.join(";\n", @search_sql) | ||
| 472 | ."\nbind params: ".join(', ', @bind_params)); | ||
| 473 | $self->{-dbh}->do(shift @search_sql, undef, @bind_params); | ||
| 474 | $self->{-dbh}->do(shift @search_sql); | ||
| 475 | $self->{-dbh}->do(shift @search_sql, undef, @bind_params); | ||
| 476 | $self->get_num_results(); | ||
| 477 | }; | ||
| 478 | if ($@) { | ||
| 479 | $self->log_error($@); | ||
| 480 | return undef; | ||
| 481 | } | ||
| 482 | $self->{-sql_search_columns} = undef; | ||
| 483 | $self->{-sql_table} = 'tmp_search_results '.$self->{-sql_join_for_dataset}; | ||
| 484 | $self->{-where_clause} = undef; | ||
| 485 | $self->{-bind_params} = undef; | ||
| 486 | $self->{-orderby_clause} = 'ORDER BY row_index'; | ||
| 487 | $self->{-opt_precols_sql} = $orig_opt_precols_sql; | ||
| 488 | $self->{-limit_clause} = undef; | ||
| 489 | $self->_build_sql(); | ||
| 490 | } | ||
| 491 | |||
| 492 | eval { | ||
| 493 | my $sth = $self->{-dbh}->prepare_cached( $self->{'_sql'} ); | ||
| 494 | |||
| 495 | my @bind_params = @{ $self->{-bind_params} || [] }; | ||
| 496 | $self->warn("SQL statement: $self->{'_sql'}; bind params: ".join(', ', @bind_params)); | ||
| 497 | $sth->execute(@bind_params); | ||
| 498 | |||
| 499 | $self->{'results'} = []; | ||
| 500 | if (ref $self->{-fetchrow_closure} eq 'CODE') { | ||
| 501 | my @row_data; | ||
| 502 | $sth->bind_columns | ||
| 503 | (map { \$row_data[$_] } 0..$#{$self->{-sql_retrieve_columns}}); | ||
| 504 | |||
| 505 | while ($sth->fetchrow_arrayref) { | ||
| 506 | push(@{$self->{'results'}}, $self->{-fetchrow_closure}->($self, @row_data)); | ||
| 507 | } | ||
| 508 | } else { | ||
| 509 | $self->{'results'} = $sth->fetchall_arrayref({}); | ||
| 510 | } | ||
| 511 | |||
| 512 | $sth->finish(); | ||
| 513 | |||
| 514 | $self->get_num_results(); | ||
| 515 | |||
| 516 | $self->{-dbh}->disconnect() if $should_disconnect; | ||
| 517 | }; | ||
| 518 | if ($@) { | ||
| 519 | $self->log_error("SQL statement: $self->{'_sql'}; bind params: ".join(', ', @{ $self->{-bind_params} || [] })); | ||
| 520 | $self->log_error($@); | ||
| 521 | return undef; | ||
| 522 | } | ||
| 523 | |||
| 524 | #$self->pagesort_results($self->{'page_sortby'}) if $self->{'page_sortby'}; | ||
| 525 | return $self; | ||
| 526 | } | ||
| 527 | |||
| 528 | sub _build_sql { | ||
| 529 | my ($self) = @_; | ||
| 530 | $self->{'_sql_no_limit'} = ( | ||
| 531 | 'SELECT '.$self->{-opt_precols_sql}.' '.join(',', $self->_columns_for_sql()). | ||
| 532 | ' FROM '.$self->{-sql_table}.' '. | ||
| 533 | ($self->{-where_clause} ? 'WHERE '.$self->{-where_clause} : '').' '. | ||
| 534 | ($self->{-orderby_clause}||'') | ||
| 535 | ); | ||
| 536 | $self->{'_sql'} = $self->{'_sql_no_limit'}.' '.($self->{-limit_clause}||''); | ||
| 537 | } | ||
| 538 | |||
| 539 | sub _columns_for_sql { | ||
| 540 | my ($self) = @_; | ||
| 541 | return $self->{-sql_search_columns} && $self->{-sql_join_for_dataset} | ||
| 542 | ? @{ $self->{-sql_search_columns} } : @{ $self->{-sql_retrieve_columns} }; | ||
| 543 | } | ||
| 544 | |||
| 545 | =item get_num_results() | ||
| 546 | |||
| 547 | Executes a SELECT COUNT() query with the current search parameters and stores result | ||
| 548 | in object variable: 'numresults'. Has no effect unless -show_total_numresults object | ||
| 549 | variable is true. As a side-effect, this method also sets the 'lastpage' object | ||
| 550 | variable which, no surprise, is the page number denoting the last page in the search | ||
| 551 | result set. | ||
| 552 | |||
| 553 | This is used for displaying total number of results found, and is | ||
| 554 | necessary to provide a last-page link to skip to the end of the search results. | ||
| 555 | |||
| 556 | =cut | ||
| 557 | |||
| 558 | sub get_num_results { | ||
| 559 | my ($self) = @_; | ||
| 560 | return if ! $self->{-show_total_numresults} || defined $self->{'numresults'}; | ||
| 561 | |||
| 562 | # read total number of results in search set (mysql only) | ||
| 563 | $self->{'numresults'} = @{ $self->{-dbh}->selectrow_arrayref('SELECT FOUND_ROWS()') || [] }[0]; | ||
| 564 | $self->{'lastpage'} = int(($self->{'numresults'} - 1) / $self->{-max_results_per_page}); | ||
| 565 | return $self->{'numresults'}; | ||
| 566 | } | ||
| 567 | |||
| 568 | =item pagesort_results($col, $reverse) | ||
| 569 | |||
| 570 | Sorts a single page of results by column $col. Reorders object variable 'results' | ||
| 571 | based on sort column $col and boolean $reverse parameters. | ||
| 572 | |||
| 573 | (note: method currently unused) | ||
| 574 | |||
| 575 | =cut | ||
| 576 | |||
| 577 | # sub pagesort_results { | ||
| 578 | # my ($self, $col, $reverse) = @_; | ||
| 579 | |||
| 580 | # # handle sorting by arbitrary data column | ||
| 581 | # if ($self->{'page_sortby'} and $reverse) { | ||
| 582 | # # toggle reverse flag if they clicked the current sort column | ||
| 583 | # $self->{'reverse_pagesort'}->{$self->{'page_sortby'}} = | ||
| 584 | # $self->{'reverse_pagesort'}->{$self->{'page_sortby'}} ? 0 : 1; | ||
| 585 | # @{$self->{'results'}} = reverse @{$self->{'results'}}; | ||
| 586 | # } else { | ||
| 587 | # # set new page_sortby column, and sort results array | ||
| 588 | # $self->{'page_sortby'} = $col; | ||
| 589 | # @{$self->{'results'}} = sort { | ||
| 590 | # ($self->{-numeric_columns}->{$self->{'page_sortby'}} || | ||
| 591 | # $self->{-currency_columns}->{$self->{'page_sortby'}} | ||
| 592 | # ? $a->{$self->{'page_sortby'}} <=> $b->{$self->{'page_sortby'}} | ||
| 593 | # : uc($a->{$self->{'page_sortby'}}) cmp uc($b->{$self->{'page_sortby'}})) | ||
| 594 | # } @{$self->{'results'}}; | ||
| 595 | # @{$self->{'results'}} = reverse @{$self->{'results'}} | ||
| 596 | # if $self->{'reverse_pagesort'}->{$self->{'page_sortby'}}; | ||
| 597 | # } | ||
| 598 | # } | ||
| 599 | |||
| 600 | =item append_where_clause($where_sql, [ $op ]) | ||
| 601 | |||
| 602 | Adds an SQL expression to the current -where_clause, if any. Optional $op specifies the | ||
| 603 | SQL operator to attach the expression with (default: AND). | ||
| 604 | |||
| 605 | =item append_bind_params(@bind_params) | ||
| 606 | |||
| 607 | Appends extra bind params to the end of the current list of -bind_params. | ||
| 608 | |||
| 609 | =cut | ||
| 610 | |||
| 611 | sub append_where_clause { | ||
| 612 | my ($self, $where_sql, $op) = @_; | ||
| 613 | return if ! $where_sql; | ||
| 614 | $op ||= 'AND'; | ||
| 615 | $self->{-where_clause} = ($self->{-where_clause} ? '( '.$self->{-where_clause}.' ) '.$op.' ' : '') . '( '.$where_sql.' )'; | ||
| 616 | } | ||
| 617 | |||
| 618 | sub append_bind_params { | ||
| 619 | my ($self, @bind_params) = @_; | ||
| 620 | return if ! @bind_params; | ||
| 621 | $self->{-bind_params} ||= []; | ||
| 622 | push(@{ $self->{-bind_params} }, @bind_params); | ||
| 623 | } | ||
| 624 | |||
| 625 | |||
| 626 | =item init_display_class([ $disp_cols ]) | ||
| 627 | |||
| 628 | Instantiates and initializes the desired display object. Returns it and sets in 'display' object variable. | ||
| 629 | This is called by display_results(), and does not normally need to be called directly. | ||
| 630 | |||
| 631 | =item display_results([ $disp_cols ]) | ||
| 632 | |||
| 633 | Displays an HTML table of data values stored in object variable 'results' (retrieved | ||
| 634 | from the most recent call to search() method). Optional variable $disp_cols overrides | ||
| 635 | object variable -display_columns. | ||
| 636 | |||
| 637 | =cut | ||
| 638 | |||
| 639 | sub init_display_class { | ||
| 640 | my ($self, $disp_cols) = @_; | ||
| 641 | unless (ref $self->{'results'} eq 'ARRAY' && | ||
| 642 | (ref $self->{-sql_table_columns} eq 'ARRAY' || | ||
| 643 | ref $self->{-sql_retrieve_columns} eq 'ARRAY')) { | ||
| 644 | $self->log_error(q|instance variables '-sql_table_columns' or '-sql_retrieve_columns', and data resultset 'results' (ARRAYs) are required|); | ||
| 645 | return undef; | ||
| 646 | } | ||
| 647 | |||
| 648 | $self->{-display_columns} = $disp_cols if ref $disp_cols eq 'HASH'; | ||
| 649 | $self->{-display_class} ||= ($self->{-display_mode}||'') eq 'grid' | ||
| 650 | ? 'CGI::Widget::DBI::Search::Display::Grid' | ||
| 651 | : 'CGI::Widget::DBI::Search::Display::Table'; | ||
| 652 | |||
| 653 | $self->{display} = $self->{-display_class}->new($self); | ||
| 654 | $self->transfer_display_settings(); | ||
| 655 | return $self->{display}; | ||
| 656 | } | ||
| 657 | |||
| 658 | sub display_results { | ||
| 659 | my ($self, $disp_cols) = @_; | ||
| 660 | return undef if ! $self->init_display_class($disp_cols); | ||
| 661 | return $self->{display}->display(); | ||
| 662 | } | ||
| 663 | |||
| 664 | =item transfer_display_settings() | ||
| 665 | |||
| 666 | Transfers all display-specific settings from search widget object to the | ||
| 667 | search display widget object. | ||
| 668 | |||
| 669 | =cut | ||
| 670 | |||
| 671 | sub transfer_display_settings { | ||
| 672 | my ($self) = @_; | ||
| 673 | foreach my $var ( | ||
| 674 | qw/results | ||
| 675 | numresults | ||
| 676 | page | ||
| 677 | lastpage | ||
| 678 | sortby | ||
| 679 | sort_reverse | ||
| 680 | /) { | ||
| 681 | $self->{display}->{$var} = $self->{$var} if defined $self->{$var}; | ||
| 682 | } | ||
| 683 | foreach my $var (keys %$self) { | ||
| 684 | $self->{display}->{$var} = $self->{$var} if substr($var, 0, 1) eq '-'; | ||
| 685 | } | ||
| 686 | } | ||
| 687 | |||
| 688 | sub sql_search_column_for_alias { | ||
| 689 | my ($self, $alias_or_sql_column) = @_; | ||
| 690 | my $sql_col = _find_sql_column_in_sql_search_columns($self, $alias_or_sql_column); | ||
| 691 | ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+$alias_or_sql_column\Z/i ) | ||
| 692 | if $sql_col && $sql_col =~ m/as\s+$alias_or_sql_column\Z/i; | ||
| 693 | return $sql_col || $alias_or_sql_column; | ||
| 694 | } | ||
| 695 | |||
| 696 | sub sql_column_for_alias { | ||
| 697 | my ($self, $alias_or_sql_column) = @_; | ||
| 698 | my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column); | ||
| 699 | ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+$alias_or_sql_column\Z/i ) | ||
| 700 | if $sql_col && $sql_col =~ m/as\s+$alias_or_sql_column\Z/i; | ||
| 701 | return $sql_col || $alias_or_sql_column; | ||
| 702 | } | ||
| 703 | |||
| 704 | sub sql_column_with_tbl_alias_for_alias { | ||
| 705 | my ($self, $alias_or_sql_column) = @_; | ||
| 706 | my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column); | ||
| 707 | $sql_col =~ s/\s+as\s+$alias_or_sql_column\Z//i if $sql_col; | ||
| 708 | return $sql_col || $alias_or_sql_column; | ||
| 709 | } | ||
| 710 | |||
| 711 | sub full_sql_column_for_alias { | ||
| 712 | my ($self, $alias_or_sql_column) = @_; | ||
| 713 | my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $alias_or_sql_column); | ||
| 714 | return $sql_col || $alias_or_sql_column; | ||
| 715 | } | ||
| 716 | |||
| 717 | sub sql_column_for_full_sql_column_with_alias { | ||
| 718 | my ($self, $full_sql_column) = @_; | ||
| 719 | my $sql_col = _find_sql_column_in_sql_retrieve_columns($self, $full_sql_column); | ||
| 720 | ($sql_col) = ( $sql_col =~ m/\A(.+)\s+as\s+.+\Z/i ) if $sql_col; | ||
| 721 | return $sql_col || $full_sql_column; | ||
| 722 | } | ||
| 723 | |||
| 724 | sub extract_alias_from_sql_column { | ||
| 725 | my ($self, $full_sql_column) = @_; | ||
| 726 | my ($alias) = ( $full_sql_column =~ m/\s+as\s+(.+)\Z/i ); | ||
| 727 | return $alias || $full_sql_column; | ||
| 728 | } | ||
| 729 | |||
| 730 | |||
| 731 | 1; | ||
| 732 | __END__ | ||