IO/Search.pm untested

filter: Statementstmt 0.0% 0 / 140 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 49 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 309 CC 31 SCAR 44.1
CC
31
Cov
0%
_crit_sql
210.0
_build_sql
72.0
execute
20.0
CRAP 82.3
1 #
2 # $Id$
3 #
4  
5 package DBIx::IO::Search;
6  
7 use strict;
8  
9 use DBIx::IO::Table;
10  
11 =head1 NAME
12  
13 DBIx::IO::Search - query a database and generate SQL
14  
15  
16 =head1 SYNOPSIS
17  
18 use DBIx::IO::Search;
19  
20 $searcher = DBIx::IO::Search->new($dbh,$table_name,[$critlist,$sortlist,$parent_id_name,$connect_by,$start_with]);
21  
22 $critlist = $searcher->critlist();
23 $critlist = $searcher->critlist($critlist);
24  
25 $sortlist = $searcher->sortlist();
26 $sortlist = $searcher->sortlist($sortlist);
27  
28 $criteria = $searcher->add_crit($criteria);
29  
30 $criteria = $searcher->build_range_crit($field_name,$range_start,$range_end,[$logical_not]);
31  
32 $crit = $searcher->build_scalar_crit($field_name,$operator,$value);
33  
34 $crit = $searcher->build_list_crit($field_name,$value_list,[$logical_not]);
35  
36 $sth = $searcher->execute();
37  
38 $results = $searcher->results();
39  
40 $results = $searcher->fetchall();
41  
42 $results = $searcher->search([$critlist],[$sortlist]); # combines execute(), and fetchall()
43  
44  
45  
46 =head1 DESCRIPTION
47  
48 This class enables reports to be run on a particular table or view based on a set of criteria.
49 The criteria are stored in an array - $critlist where each criterion is one of 3 types depending on the operator:
50  
51 scalar - This type supports the <=, >=, =, !=, <, > and (NOT) LIKE operators; 1 scalar value is required for comparison.
52 A special value, NULL is recognized as meaning a NULL value. In this case, the operators '=' and '!='
53 are mapped to 'IS' and 'IS NOT' respectively. This criterion is represented as a hash ref with keys: COLUMN, OPERATOR, and VALUE,
54 which mean just what you'd think. The (NOT) LIKE operator allows wildcards `%' in the comparison value.
55  
56 range - This type is used for camparison of ranges using the 'BETWEEN' operator. It is represented as a hash ref with keys:
57 COLUMN, OPERATOR, START, END, which mean just what you'd think. OPERATOR has 2 allowed values: 'BETWEEN' and 'NOT BETWEEN'.
58  
59 list - This type is used for comparison with a list of values where any of the values can match for the criteria to be met.
60 The IN operator is used and the criterion is represented as a hash ref with keys: COLUMN, OPERATOR, LIST, which mean just what
61 you'd think. OPERATOR has 2 allowed values: 'IN' and 'NOT IN'. LIST must be an array ref of the values intended for
62 comparison.
63  
64 The result set is returned via results() or search(). The result set is an array ref where each element is a record represented by a hash ref
65 of column => value pairs (see fetchall_arrayref({}) in DBI); all columns are returned. If sorting is desired then
66 populate the sortlist attribute via new(), sortlist() or search(). $sortlist is an array ref of column_names where the
67 result set is returned sorted by these columns in order.
68  
69 For tables with a hierarchical relationship, START WITH and CONNECT BY clauses are required in the constructor
70 in order to reveal that relationship (review SELECT statements in an SQL reference). Normally SQL does not
71 support additional sorting of the results when these clauses are given. However,
72 if these clauses are given and sorting is desired, then sorting will be done at the top level of the hierarchy only.
73 In order for this to work, the table has to have a single column primary key.
74  
75 The criteria list can be given on construction, or through the crit_list() or search() methods. The list can be
76 built with individual criterion with add_crit(). Also, just to make things easier, there is a builder method for each type of criterion, which helps
77 to assemble the data into the required record format: build_scalar_crit(),
78 build_list_crit() and build_range_crit().
79  
80 The values in each criterion that are used for comparison are qualified automagically (see DBIx::IO::qualify()) and dates are assumed to
81 be normalized (see DBIx::IO::GenLib). This lets you build searches without having to worry about quoting text vs numbers.
82  
83 Some special values are recognized for dates: <int> hours, <int> days, <int> weeks, <int> months where <int> should be an appropriate
84 integer. These date formats allow values to be specified relative to now, e.g. an operator of '<' and a value of '2 weeks'
85 infer a value of any date less than 2 weeks from now.
86  
87 If a single table or view is not enough for reporting purposes, like needing to do a join with 2 or more tables, then ask your
88 friendly neighborhood DBA to create another view. If that doesn't work then write your own damn SQL! :<>
89  
90 Oracle users:
91 LOB columns won't be retreived because they aren't supported in DBD::Oracle (as of v1.19). LONG columns seem to work
92 fine though so if you can get away with using a LONG over a LOB, do that.
93 $DBIx::IO::GenLib::LONG_READ_LENGTH gives the limit size of a long that will be returned.
94  
95 =head1 METHOD DETAILS
96  
97  
98 =over 4
99  
100 =item C<new (constructer)>
101  
102 $searcher = DBIx::IO::Search->new($dbh,$table_name,[$critlist,$sortlist,$parent_id_name,$connect_by,$start_with]);
103  
104 Create a new $searcher based on $table_name. $critlist and/or $sortlist can be given on construction as well.
105 To express hierarchical relationships, include $parent_id_name or ($connect_by and/or $start_with).
106 The START WITH clause defaults to 'START WITH $parent_id_name IS NULL'.
107 The CONNECT BY clause defaults to 'CONNECT BY PRIOR ${table_name}_ID = $parent_id_name'.
108  
109 Return undef if error, return 0 if $table_name does not exist.
110  
111 =cut
112  
113 sub new
114 {
115 my ($caller,$dbh,$table_name,$critlist,$sortlist,$parent_id_name,$connect_by,$start_with) = @_;
116 my $class = ref($caller) || $caller;
117 $table_name || (warn("\$table_name not defined!"), return undef);
118 ref($dbh) || (warn("\$dbh doesn't appear to be valid"), return undef);
119 my $table;
120 unless ($table = new DBIx::IO::Table($dbh,undef,undef,$table_name))
121 {
122 defined($table) || (warn("Error getting column attributes for $table_name"),return undef);
123 #warn("No attributes found for $table_name");
124 return $table;
125 }
126 my $key_name = $table->key_name();
127 if ($parent_id_name)
128 {
129 $connect_by ||= "CONNECT BY PRIOR $key_name = $parent_id_name";
130 $start_with ||= "START WITH $parent_id_name IS NULL";
131 }
132  
133 my $self =
134 {
135 table_name => $table->name(),
136 key_name => $key_name,
137 dbh => $dbh,
138 critlist => $critlist,
139 sortlist => $sortlist,
140 parent_id_name => $parent_id_name,
141 connect_by => $connect_by,
142 start_with => $start_with,
143 column_types => $table->column_types(),
144 io => $table->{io},
145 pk => $table->pk(),
146 };
147 return bless($self,$class);
148 }
149  
150 =pod
151  
152 =item C<critlist>
153  
154 $critlist = $searcher->critlist();
155 $critlist = $searcher->critlist($critlist);
156  
157 Get or set $critlist.
158  
159 =cut
160 sub critlist
161 {
162 my ($self,$critlist) = @_;
163 return $self->{critlist} unless defined($critlist);
164 return $self->{critlist} = $critlist;
165 }
166  
167 =pod
168  
169 =item C<sortlist>
170  
171 $sortlist = $searcher->sortlist();
172 $sortlist = $searcher->sortlist($sortlist);
173  
174 Get or set $sortlist.
175  
176  
177 =cut
178 sub sortlist
179 {
180 my ($self,$sortlist) = @_;
181 return $self->{sortlist} unless defined($sortlist);
182 return $self->{sortlist} = $sortlist;
183 }
184  
185 =pod
186  
187 =item C<add_crit>
188  
189 $criteria = $searcher->add_crit($criteria);
190  
191 Add an assembled criterion to the criteria list.
192  
193 =cut
194 sub add_crit
195 {
196 my ($self,$crit) = @_;
197 $crit || ($self->{io}->_alert("\$crit not defined!"),return undef);
198 push(@{$self->{critlist}}, { %$crit });
199 return $crit;
200 }
201  
202 =pod
203  
204 =item C<build_range_crit>
205  
206 $criteria = $searcher->build_range_crit($field_name,$range_start,$range_end,[$logical_not]);
207  
208 Build a range criterion (for use with the 'BETWEEN' operator) by supplying the following arguments:
209  
210 $field_name -> name of the column that is restricted to the specified range.
211 $range_start -> scalar repesenting the beginning of the range.
212 $range_end -> scalar repesenting the ending of the range.
213 $logical_not -> if this is true the SQL expression looks like 'AND NOT BETWEEN ...'
214 (a little confusing since the default, undef is true).
215  
216 Returns the assembled criterion and adds it to $searcher.
217  
218 =cut
219 sub build_range_crit
220 {
221 my ($self,$field,$start,$end,$not) = @_;
222 return $self->add_crit({ COLUMN => $field, OPERATOR => ($not ? 'NOT ' : '') . 'BETWEEN', START => $start, END => $end });
223 }
224  
225 =pod
226  
227 =item C<build_scalar_crit>
228  
229 $crit = $searcher->build_scalar_crit($field_name,$operator,$value);
230  
231 Build a scalar criterion (for use with the <=, >=, =, !=, <, > operators) by providing the $field_name, an $operator and a single scalar $value.
232  
233 Returns the assembled criterion and adds it to $searcher.
234
235 =cut
236 sub build_scalar_crit
237 {
238 my ($self,$field,$operator,$value) = @_;
239 return $self->add_crit({ COLUMN => $field, OPERATOR => $operator, VALUE => $value });
240 }
241  
242 =pod
243  
244 =item C<build_list_crit>
245  
246 $crit = $searcher->build_list_crit($field_name,$value_list,$logical_not);
247  
248 Build a list criterion (for use with the IN operator) by providing:
249  
250 $field_name -> name of the column that is restricted to the specified $value_list
251 $value_list -> an array ref of values that the criterion is restricted to.
252 $logical_not -> if this is true the SQL expression looks like 'AND NOT IN ...'
253 (a little confusing since the default, undef is true).
254  
255 Returns the assembled criterion and adds it to $searcher.
256  
257 =cut
258 sub build_list_crit
259 {
260 my ($self,$field,$val_list,$not) = @_;
261 return $self->add_crit({ COLUMN => $field, OPERATOR => ($not ? 'NOT ' : '') . 'IN', LISTVALS => $val_list });
262 }
263  
264 =pod
265  
266 =item C<execute>
267  
268 $sth = $searcher->execute();
269  
270 Build an SQL statement from the list of criteria in $searcher and execute it.
271 Return the resulting statement handle (see DBI) or false if error.
272 Also see search() explained elsewhere.
273  
274 =cut
275 sub execute
276 {
277 my $self = shift;
278 if ($self->{connect_by})
279 {
280 # Hierarchical query
281 if (ref($self->{sortlist}))
282 {
283 # Hierarchical query needs sorting (which can only be done at the top level) so get the top level
284 # records and then pursue children in fetchall
285 if ($self->{second_pass})
286 {
287 $self->_build_sql($self->{start_with2},$self->{connect_by}) || ($self->{io}->_alert("Can't build SQL statement"), return undef);
288 }
289 else
290 {
291 $self->{first_pass} = 1;
292 $self->_build_sql($self->{start_with}) || ($self->{io}->_alert("Can't build SQL statement"), return undef);
293 }
294 }
295 else
296 {
297 $self->_build_sql($self->{start_with},$self->{connect_by}) || ($self->{io}->_alert("Can't build SQL statement"), return undef);
298 }
299 }
300 else
301 {
302 $self->_build_sql() || ($self->{io}->_alert("Can't build SQL statement"), return undef);
303 }
304 return $self->{sth} = $self->{io}->make_cursor($self->{sql});
305 }
306  
307 =pod
308  
309 =item C<results>
310  
311 $results = $searcher->results();
312  
313 After search() or fetchall() is called, an array of hashes representing the result set is stored in the object. This
314 method returns that result set.
315  
316 =cut
317 sub results
318 {
319 my $self = shift;
320 return $self->{results};
321 }
322  
323 =pod
324  
325 =item C<search>
326  
327 $results = $searcher->search([$critlist],[$sortlist]);
328  
329 Generate SQL, execute, and return the result set.
330 $critlist and $sortlist will override those already assigned to $searcher.
331  
332 Return false if error.
333 NOTE: The returned value could be true but also be an emtpy array ref with no rows returned.
334  
335 =cut
336 sub search
337 {
338 my ($self,$critlist,$sortlist) = @_;
339 $critlist && $self->critlist($critlist);
340 $sortlist && $self->sortlist($sortlist);
341 $self->execute() || ($self->{io}->_alert("execute() failed"), return undef);
342 return $self->fetchall();
343 }
344  
345 =pod
346  
347 =item C<fetchall>
348  
349 $results = $searcher->fetchall();
350  
351 After execute() is called, $searcher will contain a loaded statement handle. This method gets the result set,
352 stores it and returns it (see also the results() and search methods elsewhere).
353 Return false if error.
354 NOTE: The returned value could be true but also be an emtpy array ref with no rows returned.
355  
356 =cut
357  
358 sub fetchall
359 {
360 my $self = shift;
361 ref($self->{sth}) || ($self->{io}->_alert("statement handle not defined, did you call execute()?"), return undef);
362 my $results = $self->{sth}->fetchall_arrayref({});
363 $self->{sth}->err && ($self->{io}->_alert("Error in DBI fetching the results"), return undef);
364 my @fresults;
365 if ($self->{first_pass})
366 {
367 undef $self->{first_pass};
368 $self->{second_pass} = 1;
369 # Sorted hierarchical query: first pass (already done at this point) gets all (sorted) top level rows, now recurse into children (not sorted)
370 foreach my $result (@$results)
371 {
372 my $key_name = $self->{key_name};
373 $self->{start_with2} = "START WITH $key_name = " . $self->{io}->qualify($result->{$key_name},$key_name);
374 my $rv = $self->search() || ($self->{io}->_alert("Error in recursive hierarchy search()"), return undef);
375 push @fresults, @$rv;
376 }
377 undef $self->{second_pass};
378 $results = \@fresults;
379 }
380 return ($self->{results} = $results);
381 }
382  
383 # for each crit in $critlist, build an SQL statement based on the table and criteria.
384 sub _build_sql
385 {
386 my $self = shift;
387 return $self->{sql} if $self->{sql};
388 my ($start_with,$connect_by) = @_;
389 my $where;
390 my $level;
391 my $crit_num = 0;
392 if ($start_with)
393 {
394 if ($connect_by)
395 {
396 $level = 'LEVEL,';
397 }
398 else
399 {
400 # Hierarchical query that needs sorting so this is a first pass
401 $start_with =~ s/START WITH/WHERE/i;
402 $where .= "$start_with ";
403 $crit_num++;
404 }
405 }
406 if (ref($self->{critlist}))
407 {
408 foreach my $crit (@{$self->{critlist}})
409 {
410 $where .= ($crit_num ? "AND " : "WHERE ") . $self->_crit_sql($crit) . " ";
411 $crit_num++;
412 }
413 }
414 my $cols = $self->{io}->{select_cols} . ',';
415 $cols .= $level;
416 chop $cols;
417 $self->{sql} = "SELECT $cols FROM $self->{table_name} $self->{table_name} $where" ;
418 if ($connect_by)
419 {
420 $self->{sql} .= "$start_with $connect_by ";
421 }
422 else
423 {
424 $self->{sql} .= $self->{order_by} = ( ref($self->{sortlist}) ? " ORDER BY " . join(',', map("$self->{table_name}.$_",@{$self->{sortlist}})) : '');
425 }
426 $self->{where} = $where;
427 return $self->{sql};
428 }
429  
430  
431 # build SQL for an individual criterion.
432 sub _crit_sql
433 {
434 my ($self,$crit) = @_;
435 my $column = uc($crit->{COLUMN});
436 my $table_name = $self->{table_name};
437 ##at could remove whitespace
438 #$column =~ s/^\s*|\s*$//g; # remove leading and trailing whitespace
439 my $op = uc($crit->{OPERATOR});
440 if ($op =~ /BETWEEN/i)
441 {
442 ##at could parse dates
443 my $start = $self->{io}->qualify($crit->{START},$column); #,$UNKNOWN_DATE_FORMAT);
444 ##at could parse dates
445 my $end = $self->{io}->qualify($crit->{END},$column); #,$UNKNOWN_DATE_FORMAT);
446 return "$table_name.$column $op $start AND $end";
447 }
448 elsif ($op =~ /IN/i)
449 {
450 my $val_list;
451 foreach my $val (@{$crit->{LISTVALS}})
452 {
453 ##at could parse dates
454 $val_list .= $self->{io}->qualify($val,$column) . ","; # $UNKNOWN_DATE_FORMAT
455 }
456 chop $val_list;
457 return "$table_name.$column $op ($val_list)";
458 }
459 else
460 {
461 my $val = $crit->{VALUE};
462 my $isnull;
463 if ($val =~ /^NULL$/i)
464 {
465 if ($op =~ /\!\=/)
466 {
467 $op = 'IS NOT';
468 }
469 elsif ($op =~ /\=/)
470 {
471 $op = 'IS';
472 }
473 $isnull++;
474 }
475 elsif ($op =~ /LIKE/i)
476 {
477 $val = "\%\L$val\%" unless $val =~ /\%/;
478 ##at could parse dates
479 $val = $self->{io}->qualify($val,$column); # $UNKNOWN_DATE_FORMAT
480 $column = $self->{io}->lc_func("$table_name.$column");
481 return "$column $op $val";
482 }
483 ##at more flexibility for other date types??
484 if ($self->{io}->is_datetime($column))
485 {
486 if ($val =~ /(\d+)\s*hour/i)
487 {
488 my $offset = $1/24;
489 return "$table_name.$column $op SYSDATE - $offset";
490 }
491 elsif ($val =~ /(\d+)\s*day/i)
492 {
493 my $offset = $1;
494 return "$table_name.$column $op SYSDATE - $offset";
495 }
496 elsif ($val =~ /(\d+)\s*week/i)
497 {
498 my $offset = $1 * 7;
499 return "$table_name.$column $op SYSDATE - $offset";
500 }
501 elsif ($val =~ /(\d+)\s*month/i)
502 {
503 my $offset = $1 * 30;
504 return "$table_name.$column $op SYSDATE - $offset";
505 }
506 }
507 ##at could parse dates
508 $val = $self->{io}->qualify($val,$column) unless $isnull; # $UNKNOWN_DATE_FORMAT
509 return "$table_name.$column $op $val";
510 }
511 }
512  
513 =pod
514  
515 =back
516  
517 =cut
518  
519 1;
520  
521 __END__