blib/lib/DBIx/OptimalQuery.pm untested

filter: Statementstmt 0.0% 0 / 940 Branchbran 0.0% 0 / 402 Conditioncond 0.0% 0 / 190 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 30 totaltotal 0.0% 0 / 1603 CC 202 SCAR 67.0
CC
202
Cov
0%
create_where
2970.0
execute
552.0
create_order_by
272.0
CRAP 811.0
1 package DBIx::OptimalQuery::sth;
2  
3 use strict;
4 use warnings;
5 no warnings qw( uninitialized once );
6  
7 use DBI();
8 use Carp;
9 use Parse::RecDescent;
10 use Data::Dumper();
11  
12 sub Dumper {
13 local $Data::Dumper::Indent = 1;
14 local $Data::Dumper::SortKeys = 1;
15 Data::Dumper::Dumper(@_);
16 }
17  
18  
19 =comment
20 prepare a DBI sth from user defined selects, filters, sorts
21  
22 this constructor 'new' is called when a DBIx::OptimalQuery->prepare method
23 call is issued.
24  
25 my %opts = (
26 show => []
27 filter => ""
28 sort => ""
29 );
30  
31 $sth = $oq->prepare(%opts);
32 - same as -
33 $sth = DBIx::OptimalQuery::sth->new($oq,%opts);
34  
35 $sth->execute( limit => [0, 10]);
36 =cut
37 sub new {
38 my $class = shift;
39 my $oq = shift;
40 my %args = @_;
41  
42 $$oq{error_handler}->("DEBUG: \$sth = $class->new(\$oq,\n".Dumper(\%args).")\n") if $$oq{debug};
43  
44 my $sth = bless \%args, $class;
45 $sth->{oq} = $oq;
46 $sth->_normalize();
47 $sth->create_select();
48 $sth->create_where();
49 $sth->create_order_by();
50  
51 return $sth;
52 }
53  
54 sub get_lo_rec { $_[0]{limit}[0] }
55 sub get_hi_rec { $_[0]{limit}[1] }
56  
57 sub set_limit {
58 my ($sth, $limit) = @_;
59 $$sth{limit} = $limit;
60 return undef;
61 }
62  
63 # execute statement
64 # notice that we can't execute other child cursors
65 # because their bind params are dependant on
66 # their parent cursor value
67 sub execute {
68 my ($sth) = @_;
69 return undef if $$sth{_already_executed};
70 $$sth{_already_executed}=1;
71  
72 $$sth{oq}{error_handler}->("DEBUG: \$sth->execute()\n") if $$sth{oq}{debug};
73 return undef if $sth->count()==0;
74  
75 local $$sth{oq}{dbh}{LongReadLen};
76  
77 # build SQL for main cursor
78 { my $c = $sth->{cursors}->[0];
79 my @all_deps = (@{$c->{select_deps}}, @{$c->{where_deps}}, @{$c->{order_by_deps}});
80 my ($order) = @{ $sth->{oq}->_order_deps(\@all_deps) };
81 my @from_deps; push @from_deps, @$_ for @$order;
82  
83 # create from_sql, from_binds
84 # vars prefixed with old_ is used for supported non sql-92 joins
85 my ($from_sql, @from_binds, $old_join_sql, @old_join_binds );
86  
87 foreach my $from_dep (@from_deps) {
88 my ($sql, @binds) = @{ $sth->{oq}->{joins}->{$from_dep}->[1] };
89 push @from_binds, @binds if @binds;
90  
91 # if this is the driving table join
92 if (! $sth->{oq}->{joins}->{$from_dep}->[0]) {
93  
94 # alias it if not already aliased in sql
95 $from_sql .= $sql.' ';
96 $from_sql .= "$from_dep" unless $sql =~ /\b$from_dep\s*$/;
97 $from_sql .= "\n";
98 }
99
100
101 # if SQL-92 type join?
102 elsif (! defined $sth->{oq}->{joins}->{$from_dep}->[2]) {
103 $from_sql .= $sql."\n";
104 }
105
106 # old style join
107 else {
108 $from_sql .= ", ".$sql.' '.$from_dep."\n";
109 my ($sql, @binds) = @{ $sth->{oq}->{joins}->{$from_dep}->[2] };
110 $old_join_sql .= " AND " if $old_join_sql ne '';
111 $old_join_sql .= $sql;
112 push @old_join_binds, @binds;
113 }
114 }
115
116
117 # construct where clause
118 my $where;
119 { my @where;
120 push @where, '('.$old_join_sql.') ' if $old_join_sql;
121 push @where, '('.$c->{where_sql}.') ' if $c->{where_sql};
122 $where = ' WHERE '.join(' AND ', @where) if @where;
123 }
124
125 # generate sql and bind params
126 $$c{sql} = "SELECT ".join(',', @{ $c->{select_sql} })." FROM $from_sql $where ".
127 (($c->{order_by_sql}) ? "ORDER BY ".$c->{order_by_sql} : '');
128  
129 my @binds = (@{ $c->{select_binds} }, @from_binds, @old_join_binds,
130 @{$c->{where_binds}}, @{$c->{order_by_binds}} );
131 $$c{binds} = \@binds;
132  
133 # if clobs have been selected, find & set LongReadLen
134 if ($$sth{oq}{dbtype} eq 'Oracle' &&
135 $$sth{'oq'}{'AutoSetLongReadLen'} &&
136 scalar(@{$$c{'selected_lobs'}})) {
137  
138 my $maxlenlobsql = "SELECT greatest(".join(',',
139 map { "nvl(max(DBMS_LOB.GETLENGTH($_)),0)" } @{$$c{'selected_lobs'}}
140 ).") FROM (".$$c{'sql'}.")";
141  
142 my ($SetLongReadLen) = $$sth{oq}{dbh}->selectrow_array($maxlenlobsql, undef, @{$$c{'binds'}});
143  
144 if (! $$sth{oq}{dbh}{LongReadLen} || $SetLongReadLen > $$sth{oq}{dbh}{LongReadLen}) {
145 $$sth{oq}{dbh}{LongReadLen} = $SetLongReadLen;
146 }
147 }
148  
149 $sth->add_limit_sql();
150 }
151  
152  
153 # build children cursors
154 my $cursors = $sth->{cursors};
155 foreach my $i (1 .. $#$cursors) {
156 my $c = $sth->{cursors}->[$i];
157 my $sd = $c->{select_deps};
158  
159 # define sql and binds for joins for this child cursor
160 # in the following vars
161 my ($from_sql, @from_binds, $where_sql, @where_binds );
162  
163 # define vars for child cursor driving table
164 # these are handled differently since we aren't joining in parent deps
165 # they were precomputed in _normalize method when constructing $oq
166  
167 ($from_sql, @from_binds) =
168 @{ $sth->{oq}->{joins}->{$sd->[0]}->[3]->{new_cursor}->{sql} };
169 $where_sql = $sth->{oq}->{joins}->{$sd->[0]}->[3]->{new_cursor}->{'join'};
170 my $order_by_sql = '';
171 if ($sth->{oq}->{joins}->{$sd->[0]}->[3]->{new_cursor_order_by}) {
172 $order_by_sql = " ORDER BY ".$sth->{oq}->{joins}->{$sd->[0]}->[3]->{new_cursor_order_by};
173 }
174  
175 $from_sql .= "\n";
176  
177 # now join in all other deps normally for this cursor
178 foreach my $i (1 .. $#$sd) {
179 my $joinAlias = $sd->[$i];
180  
181 my ($sql, @binds) = @{ $sth->{oq}->{joins}->{$joinAlias}->[1] };
182  
183 # these will NOT be defined for sql-92 type joins
184 my ($joinWhereSql, @joinWhereBinds) =
185 @{ $sth->{oq}->{joins}->{$joinAlias}->[2] }
186 if defined $sth->{oq}->{joins}->{$joinAlias}->[2];
187  
188 # if SQL-92 type join?
189 if (! defined $joinWhereSql) {
190 $from_sql .= $sql."\n";
191 push @from_binds, @binds;
192 }
193  
194 # old style join
195 else {
196 $from_sql .= ",\n$sql $joinAlias";
197 push @from_binds, @binds;
198 if ($joinWhereSql) {
199 $where_sql .= " AND " if $where_sql;
200 $where_sql .= $joinWhereSql;
201 }
202 push @where_binds, @joinWhereBinds;
203 }
204 }
205  
206 # build child cursor sql
207 $c->{sql} = "
208 SELECT ".join(',', @{ $c->{select_sql} })."
209 FROM $from_sql
210 WHERE $where_sql
211 $order_by_sql ";
212 $c->{binds} = [ @{ $c->{select_binds} }, @from_binds, @where_binds ];
213  
214 # if clobs have been selected, find & set LongReadLen
215 if ($$sth{oq}{dbtype} eq 'Oracle' &&
216 $$sth{'oq'}{'AutoSetLongReadLen'} &&
217 scalar(@{$$c{'selected_lobs'}})) {
218 my ($SetLongReadLen) = $$sth{oq}{dbh}->selectrow_array("
219 SELECT greatest(".join(',',
220 map { "nvl(max(DBMS_LOB.GETLENGTH($_)),0)" } @{$$c{'selected_lobs'}}
221 ).")
222 FROM (".$$c{'sql'}.")", undef, @{$$c{'binds'}});
223 if (! $$sth{oq}{dbh}{LongReadLen} || $SetLongReadLen > $$sth{oq}{dbh}{LongReadLen}) {
224 $$sth{oq}{dbh}{LongReadLen} = $SetLongReadLen;
225 }
226 }
227 }
228  
229 eval {
230 my $c;
231  
232 # prepare all cursors
233 foreach $c (@$cursors) {
234 $c->{sth} = $sth->{oq}->{dbh}->prepare($c->{sql});
235 }
236 $c = $$cursors[0];
237 $c->{sth}->execute( @{ $c->{binds} } );
238 my @fieldnames = @{ $$c{select_field_order} };
239 my %rec;
240 my @bindcols = \( @rec{ @fieldnames } );
241 $c->{sth}->bind_columns(@bindcols);
242 $c->{bind_hash} = \%rec;
243 };
244 if ($@) {
245 die "Problem with SQL; $@\n";
246 }
247 return undef;
248 }
249  
250 # function to add limit sql
251 # $sth->add_limit_sql()
252 sub add_limit_sql {
253 my ($sth) = @_;
254  
255 $$sth{oq}{error_handler}->("DEBUG: \$sth->add_limit_sql()\n") if $$sth{oq}{debug};
256 my $lo_limit = $$sth{limit}[0] || 0;
257 my $hi_limit = $$sth{limit}[1] || $sth->count();
258 my $c = $sth->{cursors}->[0];
259  
260 if ($$sth{oq}{dbtype} eq 'Oracle') {
261 $c->{sql} = "
262 SELECT *
263 FROM (
264 SELECT tablernk1.*, rownum RANK
265 FROM (
266 ".$c->{sql}."
267 ) tablernk1
268 WHERE rownum <= ?
269 ) tablernk2
270 WHERE tablernk2.RANK >= ? ";
271 push @{$$c{binds}}, ($hi_limit, $lo_limit);
272 push @{$$c{select_field_order}}, "DBIXOQRANK";
273 }
274  
275 # sqlserver doesn't support limit/offset until Sql Server 2012 (which I don't have to test)
276 # the workaround is this ugly hack...
277 elsif ($$sth{oq}{dbtype} eq 'Microsoft SQL Server') {
278 die "missing required U_ID in select" unless exists $$sth{oq}{select}{U_ID};
279  
280 my $sql = $c->{sql};
281  
282 # extract order by sql, and binds in order by from sql
283 my $orderbysql;
284 if ($sql =~ s/\ (ORDER BY\ .*?)$//) {
285 $orderbysql = $1;
286 my $copy = $orderbysql;
287 my $bindCount = $copy =~ tr/,//;
288 if ($bindCount > 0) {
289 my @newBinds;
290 push @newBinds, pop @{$$c{binds}} for 1 .. $bindCount;
291 @{$$c{binds}} = (reverse @newBinds, @{$$c{binds}});
292 }
293 $orderbysql .= ", ".$$sth{oq}{select}{U_ID}[1][0];
294 } elsif (exists $$sth{oq}{select}{U_ID}) {
295 $orderbysql = " ORDER BY ".$$sth{oq}{select}{U_ID}[1][0];
296 }
297  
298 # remove first select keyword, and add new one with windowing
299 if ($sql =~ s/^(\s*SELECT\s*)//) {
300 my $limit = int($hi_limit - $lo_limit + 1);
301 my $lo_limit = int($lo_limit);
302  
303 # sqlserver doesn't allow placeholders for limit and offset here
304 $c->{sql} = "SELECT TOP $limit * FROM (SELECT ROW_NUMBER() OVER ($orderbysql) AS RANK, $sql) tablerank1 WHERE tablerank1.RANK >= $lo_limit";
305 unshift @{$$c{select_field_order}}, "DBIXOQRANK";
306 }
307 }
308  
309 elsif ($$sth{oq}{dbtype} eq 'Pg') {
310 my $a = $lo_limit - 1;
311 my $b = $hi_limit - $lo_limit + 1;
312 $c->{sql} .= "\nLIMIT ? OFFSET ?";
313 push @{$$c{binds}}, ($b, $a);
314 }
315  
316 else {
317 my $a = $lo_limit - 1;
318 my $b = $hi_limit - $lo_limit + 1;
319 $c->{sql} .= "\nLIMIT ?,?";
320 push @{$$c{binds}}, ($a, $b);
321 }
322  
323 return undef;
324 }
325  
326  
327 # normalize member variables
328 sub _normalize {
329 my $sth = shift;
330 $$sth{oq}{error_handler}->("DEBUG: \$sth->_normalize()\n") if $$sth{oq}{debug};
331  
332 # if show is not defined - then define it
333 if (! exists $sth->{show}) {
334 my @select;
335 foreach my $select (@{ $sth->{oq}->{'select'} } ) {
336 push @select, $select;
337 }
338 $sth->{show} = \@select;
339 }
340  
341 # define filter & sort if not defined
342 $sth->{'filter'} = "" if ! exists $sth->{'filter'};
343 $sth->{'sort'} = "" if ! exists $sth->{'sort'};
344 $sth->{'fetch_index'} = 0;
345 $sth->{'count'} = undef;
346 $sth->{'cursors'} = undef;
347  
348 return undef;
349 }
350  
351  
352  
353 # define @select & @select_binds, and add deps
354 sub create_select {
355 my $sth = shift;
356 $$sth{oq}{error_handler}->("DEBUG: \$sth->create_select()\n") if $$sth{oq}{debug};
357  
358
359 # find all of the columns that need to be shown
360 my %show;
361  
362 # find all deps to be used in select including cols marked always_select
363 my (@deps, @select_sql, @select_binds);
364 { my %deps;
365  
366 # add deps, @select, @select_binds for items in show
367 foreach my $show (@{ $sth->{show} }) {
368 $show{$show} = 1 if exists $sth->{'oq'}->{'select'}->{$show};
369 foreach my $dep (@{ $sth->{'oq'}->{'select'}->{$show}->[0] }) {
370 $deps{$dep} = 1;
371 }
372 }
373  
374 # add deps used in always_select
375 foreach my $colAlias (keys %{ $sth->{'oq'}->{'select'} }) {
376 if ($sth->{'oq'}->{'select'}->{$colAlias}->[3]->{always_select} ) {
377 $show{$colAlias} = 1;
378 $deps{$_} = 1 for @{ $sth->{'oq'}->{'select'}->{$colAlias}->[0] };
379 }
380 }
381 @deps = keys %deps;
382 }
383  
384 # order and index deps into appropriate cursors
385 my ($dep_order, $dep_idx) = @{ $sth->{oq}->_order_deps(\@deps) };
386  
387 # look though select again and add all cols with is_hidden option
388 # if all their deps have been fulfilled
389 foreach my $colAlias (keys %{ $sth->{'oq'}->{'select'} }) {
390 if ($sth->{'oq'}->{'select'}->{$colAlias}->[3]->{is_hidden}) {
391 my $deps = $sth->{'oq'}->{'select'}->{$colAlias}->[0];
392 my $all_deps_met = 1;
393 for (@$deps) {
394 if (! exists $dep_idx->{$_}) {
395 $all_deps_met = 0;
396 last;
397 }
398 }
399 $show{$colAlias} = 1 if $all_deps_met;
400 }
401 }
402  
403 # create main cursor structure & attach deps for main cursor
404 $sth->{'cursors'} = [ $sth->_get_main_cursor_template() ];
405 $sth->{'cursors'}->[0]->{'select_deps'} = $dep_order->[0];
406  
407 # unique counter that is used to uniquely identify cols in parent cursors
408 # to their children cursors
409 my $parent_bind_tag_idx = 0;
410  
411 # create other cursors (if they exist)
412 # and define how they join to their parent cursors
413 # by defining parent_join, parent_keys
414 foreach my $i (1 .. $#$dep_order) {
415 push @{ $sth->{'cursors'} }, $sth->_get_sub_cursor_template();
416 $sth->{'cursors'}->[$i]->{'select_deps'} = $dep_order->[$i];
417  
418 # add parent_join, parent_keys for this child cursor
419 my $driving_child_join_alias = $dep_order->[$i]->[0];
420 my $cursor_opts = $sth->{'oq'}->{'joins'}->{$driving_child_join_alias}->[3]->{new_cursor};
421 foreach my $part (@{ $cursor_opts->{'keys'} } ) {
422 my ($dep,$sql) = @$part;
423 my $key = 'DBIXOQMJK'.$parent_bind_tag_idx; $parent_bind_tag_idx++;
424 my $parent_cursor_idx = $dep_idx->{$dep};
425 die "could not find dep: $dep for new cursor" if $parent_cursor_idx eq '';
426 push @{ $sth->{'cursors'}->[$parent_cursor_idx]->{select_field_order} }, $key;
427 push @{ $sth->{'cursors'}->[$parent_cursor_idx]->{select_sql} }, "$dep.$sql AS $key";
428 push @{ $sth->{'cursors'}->[$i]->{'parent_keys'} }, $key;
429 }
430 $sth->{'cursors'}->[$i]->{'parent_join'} = $cursor_opts->{'join'};
431 }
432
433 # plug in select_sql, select_binds for cursors
434 foreach my $show (keys %show) {
435 my $select = $sth->{'oq'}->{'select'}->{$show};
436 next if ! $select;
437  
438 my $cursor = $sth->{'cursors'}->[$dep_idx->{$select->[0]->[0]}];
439  
440 my $select_sql;
441  
442 # if type is date then use specified date format
443 if (! $$select[3]{select_sql} && $$select[3]{date_format}) {
444 my @tmp = @{ $select->[1] }; $select_sql = \ @tmp; # need a real copy cause we are going to mutate it
445 if ($$sth{oq}{dbtype} eq 'Oracle' ||
446 $$sth{oq}{dbtype} eq 'Pg') {
447 $$select_sql[0] = "to_char(".$$select_sql[0].",'".$$select[3]{date_format}."')";
448 } elsif ($$sth{oq}{dbtype} eq 'mysql') {
449 $$select_sql[0] = "date_format(".$$select_sql[0].",'".$$select[3]{date_format}."')";
450 } else {
451 die "unsupported DB";
452 }
453 }
454  
455 # else just copy the select
456 else {
457 $select_sql = $select->[3]->{select_sql} || $select->[1];
458 }
459  
460 # remember if a lob is selected
461 if ($$sth{oq}{dbtype} eq 'Oracle' &&
462 $sth->{oq}->get_col_types('select')->{$show} eq 'clob') {
463 push @{ $cursor->{selected_lobs} }, $show;
464 #$select_sql->[0] = 'to_char('.$select_sql->[0].')';
465 }
466  
467 if ($select_sql->[0] ne '') {
468 push @{ $cursor->{select_field_order} }, $show;
469 push @{ $cursor->{select_sql} }, $select_sql->[0].' AS '.$show;
470 push @{ $cursor->{select_binds} }, @$select_sql[1 .. $#$select_sql];
471 }
472 }
473  
474 return undef;
475 }
476
477  
478  
479  
480 # template for the main cursor
481 sub _get_main_cursor_template {
482 { sth => undef,
483 sql => "",
484 binds => [],
485 selected_lobs => [],
486 select_field_order => [],
487 select_sql => [],
488 select_binds => [],
489 select_deps => [],
490 where_sql => "",
491 where_binds => [],
492 where_deps => [],
493 where_name => "",
494 order_by_sql => "",
495 order_by_binds => [],
496 order_by_deps => [],
497 order_by_name => []
498 };
499 }
500  
501 # template for explicitly defined additional cursors
502 sub _get_sub_cursor_template {
503 { sth => undef,
504 sql => "",
505 binds => [],
506 selected_lobs => [],
507 select_field_order => [],
508 select_sql => [],
509 select_deps => [],
510 select_binds => [],
511 parent_join => "",
512 parent_keys => [],
513 };
514 }
515  
516  
517  
518  
519
520
521  
522  
523 # modify cursor and add where clause data
524 sub create_where {
525 my $sth = shift;
526  
527 $$sth{oq}{error_handler}->("DEBUG: \$sth->create_where()\n") if $$sth{oq}{debug};
528 return undef if $sth->{'filter'} eq '' && $sth->{'hiddenFilter'} eq '' && $sth->{'forceFilter'} eq '';
529  
530 # this sub glues together a parsed expression
531 # basically is glues statements that look like:
532 # '(' { sql => '', binds => [], deps => [], name => '' } 'LIKE'
533 # { sql => '', binds => [], deps => [], name => '' } ')'
534 # and then returns a single hash
535 my $glue_exp = sub {
536 my @deps;
537 my $sql = '';
538 my @binds;
539 my $name;
540 foreach my $i (@_) {
541 if (! ref($i)) {
542 $sql .= $i.' ';
543 $name .= $i.' ';
544 } else {
545 push @deps, @{ $$i{deps} } if ref($$i{deps}) eq 'ARRAY';
546 push @binds, @{ $$i{binds} } if ref($$i{binds}) eq 'ARRAY';
547 $sql .= $$i{sql}.' ' if exists $$i{sql};
548 $name .= $$i{name}.' ' if exists $$i{name};
549 }
550 }
551 my $rv = { deps=> \@deps, sql => $sql,
552 binds => \@binds, name => $name};
553 return $rv;
554 };
555  
556 my %translations = (
557 '*default*' => sub { $_[2] },
558  
559 'compOp' => sub {
560 my $rv = { name => lc($_[2]), sql => uc($_[2]) };
561 if (uc($_[2]) eq 'CONTAINS') { $$rv{sql} = 'LIKE'; }
562 elsif (uc($_[2]) eq 'NOT CONTAINS') { $$rv{sql} = 'NOT LIKE'; }
563 return $rv;
564 },
565  
566 'colAlias' => sub {
567 my $oq = $_[0];
568 my $colAlias = $_[3];
569 die "could not find colAlias $colAlias" unless exists $$oq{select}{$colAlias};
570 my $deps = $$oq{select}{$colAlias}[0];
571 my @tmp = @{ $$oq{select}{$colAlias}[3]{filter_sql} || $$oq{select}{$colAlias}[1] };
572 my $sql = shift @tmp;
573 my $binds = \ @tmp;
574 my $name = $$oq{select}{$colAlias}[2];
575 my $rv = { colAlias => $colAlias, deps => $deps, sql => $sql, binds => $binds, name => '['.$name.']'};
576 return $rv;
577 },
578  
579 'bindVal' => sub {
580 my $val = $_[2];
581 my $nice = $val;
582 $nice = "'".$nice."'" if $nice !~ /^[\d\.\-]+/;
583 return { sql => '?', binds => [$val], name => $nice };
584 },
585  
586 'quotedString' => sub {
587 my ($v) = $_[2];
588 ($v=~s/^\'// && $v=~s/\'$//) || ($v=~s/^\"// && $v=~s/\"$//);
589 return $v;
590 },
591  
592 'exp' => sub {
593 my $oq = shift;
594 my $rule = shift;
595 return $glue_exp->(@_);
596 },
597  
598  
599 'comparisonExp' => sub {
600 my $oq = shift;
601 my $rule = shift;
602 my @token = @_;
603  
604 # if this is a comparison to null / not null
605 if ($token[2]{sql} eq '?' && $token[2]{binds}[0] eq '') {
606 pop @token; # remove the last token
607 my $op = $token[1]{sql};
608 if ($op =~ /NOT\ /i || $op =~ /\!/) {
609 $token[1]{sql} = 'is not null';
610 $token[1]{name} = 'is defined';
611 } else {
612 $token[1]{sql} = 'is null';
613 $token[1]{name} = 'is undefined';
614 }
615 }
616  
617 # if we are comparing 2 cols
618 elsif ($token[0]{colAlias} && $token[2]{colAlias}) {
619 my $t0 = $oq->get_col_type($token[0]{colAlias},'filter');
620 my $t1 = $oq->get_col_type($token[2]{colAlias},'filter');
621  
622 # if types are equal
623 if ($t0 ne $t1) {
624 if ($$oq{dbtype} eq 'Oracle') {
625 $token[0]{sql} = "TO_CHAR(".$token[0]{sql}.")" unless $t0 eq 'char';
626 $token[2]{sql} = "TO_CHAR(".$token[2]{sql}.")" unless $t1 eq 'char';
627 }
628 }
629 if ($token[1]{name} =~ /contains/) {
630 $token[0]{sql} = "UPPER(".$token[0]{sql}.")";
631 $token[2]{sql} = "UPPER(".$token[2]{sql}.")";
632  
633 if ($$oq{dbtype} eq 'Oracle' || $$oq{dbtype} eq 'SQLite') {
634 $token[2]{sql} = "'%'||".$token[2]{sql}."||'%'";
635 } else {
636 $token[2]{sql} = "CONCAT('%',".$token[2]{sql}.",'%')";
637 }
638 }
639 }
640  
641 # else we are comparing a column to a value
642 else {
643  
644 # add some code to support contains operator
645 # basically rewritten as a fuzzy search
646 if ($token[1]{name} =~ /contains/) {
647 if (! exists $$oq{select}{$token[0]{colAlias}}[3]{date_format}) {
648 $token[0]{sql} = 'UPPER('.$token[0]{sql}.')';
649 }
650 if ($token[2]{sql} eq '?') {
651 $token[2]{binds}[0] =~ s/\*/\%/g;
652 $token[2]{binds}[0] = '%'.uc($token[2]{binds}[0]).'%';
653 $token[2]{binds}[0] =~ s/\%\%/\%/g;
654 } else {
655 if (! exists $$oq{select}{$token[0]{colAlias}}[3]{date_format}) {
656 $token[2]{sql} = 'UPPER('.$token[2]{sql}.')';
657 }
658 }
659 }
660  
661 # if like search convert all * to wildcard %
662 elsif ($token[1]{sql} =~ /like/i && $token[2]{sql} eq '?') {
663 $token[2]{binds}[0] =~ s/\*/\%/g;
664 }
665  
666 # if lval is a date and we are doing a like comparison and rval is a value
667 # convert rval to a string using date_format
668 if (exists $$oq{select}{$token[0]{colAlias}}[3]{date_format} &&
669 $token[1]{sql} =~ /like/i && $token[2]{sql} eq '?') {
670 if ($$oq{dbtype} eq 'Oracle') {
671 $token[0]{sql} = "to_char(".$token[0]{sql}.",'".$$oq{select}{$token[0]{colAlias}}[3]{date_format}."')";
672 } elsif ($$oq{dbtype} eq 'mysql') {
673 $token[0]{sql} = "date_format(".$token[0]{sql}.",'".$$oq{select}{$token[0]{colAlias}}[3]{date_format}."')";
674 }
675 }
676
677  
678 # if lval is a date and we are doing a numerical comparison and rval is a value
679 # convert rval to a date using date_format
680 elsif (exists $$oq{select}{$token[0]{colAlias}}[3]{date_format} &&
681 $token[1]{sql} !~ /like/i && $token[2]{sql} eq '?') {
682 if ($$oq{dbtype} eq 'Oracle') {
683 $token[2]{sql} = "to_date(?,'".$$oq{select}{$token[0]{colAlias}}[3]{date_format}."')";
684 } elsif ($$oq{dbtype} eq 'mysql') {
685 $token[2]{sql} = "str_to_date(?,'".$$oq{select}{$token[0]{colAlias}}[3]{date_format}."')";
686 }
687 }
688  
689 # if this is a numerical compare expression and the left side
690 # is a number force the right side to also be a number
691 elsif ($token[1]{sql} =~ /\=|\<|\>/ &&
692 $oq->get_col_type($token[0]{colAlias},'filter') eq 'num') {
693 my $v = $token[2]{binds}[0];
694 $v =~ s/[^\d\.\-]//g;
695 $v = 0 unless $v =~ /^\-?(\d*\.\d+|\d+)$/;
696 $token[2]{binds}[0] = $v;
697 $token[2]{name} = $v;
698 }
699 }
700  
701 # if this field comes from a dep with new_cursor => 1
702 # token 0 is the left side of the expression realized as a hashref:
703 # { sql => '', binds => [], deps => [], name => '' }
704 # we need to add additional tokens if a filter is done on a field
705 # with an ancestor dependancy with option new_cursor => 1
706  
707 # get ancestor path from newest to oldest new_cursor dep
708 my @path = ( $$oq{select}{$token[0]{colAlias}}[0][0] );
709 { my $joinDep = $path[0];
710 while (1) {
711 my $parentDep = $$oq{joins}{$joinDep}[0][0];
712 if ($parentDep) {
713 push @path, $parentDep;
714 $joinDep = $parentDep;
715 } else {
716 last;
717 }
718 }
719 }
720  
721 # remove all oldest parents until we find a new_cursor (keep that one)
722 while (@path) {
723 if ($$oq{joins}{$path[-1]}[3]{new_cursor}) {
724 last;
725 } else {
726 pop @path;
727 }
728 }
729  
730 # if ancestors with new_cursor option exists
731 if (@path) {
732 @path = reverse @path;
733 my ($preSql, $postSql, @preBinds);
734 foreach my $joinDep (@path) {
735 my ($fromSql, @fromBinds) = @{ $$oq{joins}{$joinDep}[1] };
736  
737 # unwrap SQL-92 join and add join to where
738 $fromSql =~ s/^\s+//;
739 $fromSql =~ s/^LEFT\s*//i;
740 $fromSql =~ s/^OUTER\s*//i;
741 $fromSql =~ s/^JOIN\s*//i;
742  
743 my $corelatedJoin;
744 if ($fromSql =~ /^(.*)\bON\s*\((.*)\)\s*$/is) {
745 $fromSql = $1;
746 $corelatedJoin = $2;
747 } else {
748 die "could not parse for corelated join";
749 }
750  
751 if ($token[1]{sql} =~ s/\bNOT\b//) {
752 $preSql .= 'NOT ';
753 } elsif ($token[1]{sql} eq '!=') {
754 $token[1]{sql} = '=';
755 $preSql .= 'NOT ';
756 } elsif ($token[1]{sql} eq 'is null' ) {
757 $token[1]{sql} = 'is not null';
758 $preSql .= 'NOT ';
759 }
760 $preSql .= 'EXISTS ( SELECT 1 FROM '.$fromSql.' WHERE ('.$corelatedJoin.') AND ';
761 $postSql .= ')';
762 push @preBinds, @fromBinds;
763 }
764  
765 # update left expression deps and binds
766 $token[0]{deps} = $$oq{joins}{$path[0]}[0];
767 unshift @{ $token[0]{binds} }, @preBinds if @preBinds;
768  
769 # add new pre/post sql tokens
770 unshift @token, { sql => $preSql, name => '' };
771 push @token, { sql => $postSql, name => '' };
772  
773 }
774  
775 return $glue_exp->(@token);
776 },
777  
778 'namedFilter' => sub {
779 my $oq = $_[0];
780 my $namedFilterAlias = $_[2];
781 my $args = $_[4];
782 die "was expecting that namedFilter args would be an array ref"
783 unless ref($args) eq 'ARRAY';
784 my $r = $$oq{named_filters}{$namedFilterAlias};
785 my ($deps, $sql, $binds, $name);
786 if (ref($r) eq 'ARRAY') {
787 $deps= $$r[0];
788 my @tmp = @{ $$r[1] };
789 $sql = shift @tmp;
790 $binds = \@tmp;
791 $name = $$r[2];
792 } elsif (ref($r) eq 'HASH') {
793 die "could not find sql_generator for named_filter $namedFilterAlias"
794 unless ref($$r{sql_generator}) eq 'CODE';
795 ($deps, $binds, $name) = @{ $$r{sql_generator}->(@$args) };
796 $deps = [$deps] if ! ref $deps;
797 if (ref($binds) eq 'ARRAY') {
798 $sql = shift @$binds;
799 } else {
800 $sql = $binds;
801 $binds = [];
802 }
803 } else {
804 die "could not find named_filter $namedFilterAlias" unless ref $r;
805 }
806 return { deps => $deps, sql => '('.$sql.')', binds => $binds, name => $name };
807 }
808 );
809  
810  
811 my $c = $sth->{cursors}->[0];
812  
813 # add filter parts to cursor's where parts
814 if ($sth->{'filter'} ne '') {
815 my $filter = $$sth{oq}->parse($DBIx::OptimalQuery::filterGrammar, $sth->{'filter'}, \%translations)
816 or die "could not parse filter: ".$sth->{'filter'};
817  
818 push @{ $c->{where_deps} }, @{ $$filter{deps} };
819 $c->{where_sql} = $$filter{sql};
820 push @{ $c->{where_binds} }, @{ $$filter{binds} };
821 $c->{where_name} = $$filter{name};
822 }
823  
824 # add hidden filter parts to cursor's where parts
825 if ($sth->{'hiddenFilter'} ne '') {
826 my $hiddenFilter = $$sth{oq}->parse($DBIx::OptimalQuery::filterGrammar, $sth->{'hiddenFilter'}, \%translations)
827 or die "could not parse hiddenFilter: ".$sth->{'hiddenFilter'};
828 push @{ $c->{where_deps} }, @{ $$hiddenFilter{deps} };
829 $c->{where_sql} = '('.$c->{where_sql}.') AND ' if $c->{where_sql} ne '';
830 $c->{where_sql} .= '('.$$hiddenFilter{sql}.')';
831 push @{ $c->{where_binds} }, @{ $$hiddenFilter{binds} };
832 }
833  
834 # add system filter parts to cursor's where parts
835 if ($sth->{'forceFilter'} ne '') {
836 my $forceFilter = $$sth{oq}->parse($DBIx::OptimalQuery::filterGrammar, $sth->{'forceFilter'}, \%translations)
837 or die "could not parse forceFilter: ".$sth->{'forceFilter'};
838 push @{ $c->{where_deps} }, @{ $$forceFilter{deps} };
839 $c->{where_sql} = '('.$c->{where_sql}.') AND ' if $c->{where_sql} ne '';
840 $c->{where_sql} .= '('.$$forceFilter{sql}.')';
841 push @{ $c->{where_binds} }, @{ $$forceFilter{binds} };
842 }
843  
844 return undef;
845 }
846  
847  
848  
849  
850 # modify cursor and add order by data
851 sub create_order_by {
852 my $sth = shift;
853  
854 if ($sth->{'sort'} ne '') {
855 $$sth{oq}{error_handler}->("DEBUG: \$sth->create_order_by()\n") if $$sth{oq}{debug};
856 my %translations = (
857 '*default*' => sub { $_[2] },
858  
859 'expList' => sub {
860 my ($oq) = @_;
861 my (%deps, @sql, @binds, @nice);
862 die "was expecting an array ref!" unless ref($_[2]) eq 'ARRAY';
863 foreach my $sort (@{ $_[2] }) {
864 die "was expecting a hash ref!" unless ref($sort) eq 'HASH';
865 $deps{$_} = 1 for @{ $$sort{deps} };
866 push @sql, $$sort{sql};
867 push @binds, @{ $$sort{binds} };
868 push @nice, $$sort{nice};
869 }
870 my @deps = keys %deps;
871 return [ \@deps, join(', ', @sql), \@binds, \@nice ];
872 },
873  
874 'expression' => sub {
875 my $oq = $_[0];
876 my $def = $_[2];
877 my $sql_sort_opts_to_append = lc(join(' ', @{$_[3]}));
878  
879 if ($sql_sort_opts_to_append) {
880 $$def{sql} .= ' '.$sql_sort_opts_to_append;
881 $$def{nice} .= ($sql_sort_opts_to_append =~ /desc/) ?
882 ' (reverse)' : $sql_sort_opts_to_append;
883 }
884 return $def;
885 },
886  
887 'quotedString' => sub {
888 $_ = $_[2]; (s/^\'// && s/\'$//) || (s/^\"// && s/\"$//); $_;
889 },
890  
891 'namedSort' => sub {
892 my $oq = $_[0];
893 my $namedSortAlias = $_[2];
894 my $args = $_[4];
895 die "was expecting that namedSort args would be an array ref"
896 unless ref($args) eq 'ARRAY';
897 my $r = $$oq{named_sorts}{$namedSortAlias};
898 my ($deps, $sql, $binds, $nice);
899 if (ref($r) eq 'ARRAY') {
900 $deps = $$r[0];
901 my @tmp = @{ $$r[1] };
902 $sql = shift @tmp;
903 $binds = \ @tmp;
904 $nice = $$r[3];
905 } elsif (ref($r) eq 'HASH') {
906 die "could not find sql_generator for named_sort $namedSortAlias"
907 unless ref($$r{sql_generator}) eq 'CODE';
908 ($deps, $binds, $nice) = @{ $$r{sql_generator}->(@$args) };
909 $deps = [$deps] if ! ref $deps;
910 $sql = shift @$binds;
911 } else {
912 die "could not find named_sort $namedSortAlias" unless ref $r;
913 }
914 return { deps => $deps, sql => $sql, binds => $binds, nice => $nice };
915 },
916  
917 'colAlias' => sub {
918 my $oq = $_[0];
919 my $colAlias = $_[3];
920 die "could not find colAlias $colAlias"
921 unless exists $$oq{select}{$colAlias};
922 my $deps = $$oq{select}{$colAlias}[0];
923 my @tmp = @{
924 $$oq{select}{$colAlias}[3]{sort_sql} || $$oq{select}{$colAlias}[1] };
925 my $sql = shift @tmp;
926 my $binds = \@tmp;
927 die "could not find nice name" if $$oq{select}{$colAlias}[2] eq '';
928 my $nice = '['.$$oq{select}{$colAlias}[2].']';
929  
930 if ($$sth{oq}{dbtype} eq 'Oracle' &&
931 $sth->{oq}->get_col_types('select')->{$colAlias} eq 'clob' &&
932 $sql !~ /^cast\(/i) {
933 $sql = "cast($sql as varchar2(100))";
934 }
935 return { deps => $deps, sql => $sql, binds => $binds, nice => $nice };
936 }
937 );
938  
939 my $result = $$sth{oq}->parse($DBIx::OptimalQuery::sortGrammar, $sth->{'sort'}, \%translations)
940 or die "could not parse sort: ".$sth->{'sort'};
941  
942 my $c = $sth->{cursors}->[0];
943 ($c->{order_by_deps}, $c->{order_by_sql},
944 $c->{order_by_binds}, $c->{order_by_name}) = @$result;
945 }
946 return undef;
947 }
948  
949  
950  
951  
952  
953  
954  
955  
956  
957
958  
959  
960 # fetch next row or return undef when done
961 sub fetchrow_hashref {
962 my ($sth) = @_;
963 return undef unless $sth->count() > 0;
964 $sth->execute(); # execute if not already existed
965  
966 $$sth{oq}{error_handler}->("DEBUG: \$sth->fetchrow_hashref()\n") if $$sth{oq}{debug};
967  
968 my $cursors = $sth->{cursors};
969 my $c = $cursors->[0];
970  
971 # bind hash value to column data
972 my $rec = $$c{bind_hash};
973  
974 # fetch record
975 if (my $v = $c->{sth}->fetch()) {
976  
977 foreach my $i (0 .. $#$v) {
978  
979 # if col type is decimal auto trim 0s after decimal
980 if ($c->{sth}->{TYPE}->[$i] eq '3' && $$v[$i] =~ /\./) {
981 $$v[$i] =~ s/0+$//;
982 $$v[$i] =~ s/\.$//;
983 }
984 }
985
986 $sth->{'fetch_index'}++;
987  
988 # execute other cursors
989 foreach my $i (1 .. $#$cursors) {
990 $c = $cursors->[$i];
991  
992 $c->{sth}->execute( @{ $c->{binds} },
993 map { $$rec{$_} } @{ $c->{parent_keys} } );
994  
995 my $cols = $$c{select_field_order};
996 @$rec{ @$cols } = [];
997  
998 while (my @vals = $c->{sth}->fetchrow_array()) {
999 for (my $i=0; $i <= $#$cols; $i++) {
1000 push @{ $$rec{$$cols[$i]} }, $vals[$i];
1001 }
1002 }
1003 $c->{sth}->finish();
1004 }
1005 return $rec;
1006 } else {
1007 return undef;
1008 }
1009 }
1010  
1011 # finish sth
1012 sub finish {
1013 my ($sth) = @_;
1014 $$sth{oq}{error_handler}->("DEBUG: \$sth->finish()\n") if $$sth{oq}{debug};
1015 foreach my $c (@{$$sth{cursors}}) {
1016 $$c{sth}->finish() if $$c{sth};
1017 undef $$c{sth};
1018 }
1019 return undef;
1020 }
1021  
1022 # get count for sth
1023 sub count {
1024 my $sth = shift;
1025  
1026 # if count is not already defined, define it
1027 if (! defined $sth->{count}) {
1028 $$sth{oq}{error_handler}->("DEBUG: \$sth->count()\n") if $$sth{oq}{debug};
1029  
1030 my $c = $sth->{cursors}->[0];
1031  
1032 my $drivingTable = $c->{select_deps}->[0];
1033  
1034 # only need to join in driving table with
1035 # deps used in where clause
1036 my $deps = [ $drivingTable, @{$c->{where_deps}} ];
1037 ($deps) = @{ $sth->{oq}->_order_deps($deps) };
1038 my @from_deps; push @from_deps, @$_ for @$deps;
1039  
1040 # create from_sql, from_binds
1041 # vars prefixed with old_ is used for supported non sql-92 joins
1042 my ($from_sql, @from_binds, $old_join_sql, @old_join_binds );
1043 foreach my $from_dep (@from_deps) {
1044 my ($sql, @binds) = @{ $sth->{oq}->{joins}->{$from_dep}->[1] };
1045 push @from_binds, @binds if @binds;
1046  
1047 # if this is the driving table join
1048 if (! $sth->{oq}->{joins}->{$from_dep}->[0]) {
1049  
1050 # alias it if not already aliased in sql
1051 $sql .= " $from_dep" unless $sql =~ /\b$from_dep\s*$/;
1052 $from_sql .= $sql;
1053 }
1054  
1055 # if SQL-92 type join?
1056 elsif (! $sth->{oq}->{joins}->{$from_dep}->[2]) {
1057 $from_sql .= "\n".$sql;
1058 }
1059  
1060 # old style join
1061 else {
1062 $from_sql .= ",\n".$sql.' '.$from_dep;
1063 my ($sql, @binds) = @{ $sth->{oq}->{joins}->{$from_dep}->[2] };
1064 if ($sql) {
1065 $old_join_sql .= " AND " if $old_join_sql ne '';
1066 $old_join_sql .= $sql;
1067 }
1068 push @old_join_binds, @binds;
1069 }
1070 }
1071  
1072  
1073 # construct where clause
1074 my $where;
1075 { my @where;
1076 push @where, '('.$old_join_sql.') ' if $old_join_sql;
1077 push @where, '('.$c->{where_sql}.') ' if $c->{where_sql};
1078 $where = 'WHERE '.join(' AND ', @where) if @where;
1079 }
1080  
1081 # generate sql and bind params
1082 my $sql = "
1083 SELECT count(*)
1084 FROM (
1085 SELECT $drivingTable.*
1086 FROM $from_sql
1087 $where
1088 ) cnt_query";
1089 my @binds = (@from_binds, @old_join_binds, @{$c->{where_binds}});
1090  
1091 eval {
1092 ($sth->{count}) = $sth->{oq}->{dbh}->selectrow_array($sql, undef, @binds);
1093 }; if ($@) {
1094 die "Problem finding count for SQL:\n$sql\nBINDS:\n".join(',',@binds)."\n\n$@\n";
1095 }
1096 }
1097  
1098 return $sth->{count};
1099 }
1100  
1101 sub fetch_index { $_->{'fetch_index'} }
1102  
1103 sub filter_descr {
1104 my $sth = shift;
1105 return $sth->{cursors}->[0]->{'where_name'};
1106 }
1107  
1108 sub sort_descr {
1109 my $sth = shift;
1110 if (wantarray) {
1111 return @{ $sth->{cursors}->[0]->{'order_by_name'} };
1112 } else {
1113 return join(', ', @{ $sth->{cursors}->[0]->{'order_by_name'} });
1114 }
1115 }
1116  
1117  
1118  
1119  
1120  
1121  
1122  
1123  
1124  
1125  
1126  
1127  
1128  
1129  
1130  
1131  
1132  
1133  
1134  
1135  
1136  
1137  
1138  
1139  
1140  
1141  
1142  
1143  
1144  
1145  
1146  
1147  
1148  
1149  
1150  
1151  
1152  
1153  
1154  
1155 package DBIx::OptimalQuery;
1156  
1157 =comment
1158  
1159 use DBIx::OptimalQuery;
1160 my $oq = DBIx::OptimalQuery->new(
1161 select => {
1162 'alias' => [dep, sql, nice_name, { OPTIONS } ]
1163 }
1164  
1165 joins => {
1166 'alias' => [dep, join_sql, where_sql, { OPTIONS } ]
1167 }
1168  
1169 named_filters => {
1170 'name' => [dep, sql, nice]
1171 'name' => {
1172 sql_generator => sub {
1173 my %args = @_;
1174 return [dep, sql, name]
1175 }
1176 title => "text displayed on interactive filter"
1177 }
1178 },
1179  
1180 named_sorts => {
1181 'name' => [dep, sql, nice]
1182 'name' => { sql_generator => sub { return [dep, sql, name] } }
1183 },
1184  
1185
1186  
1187 debug => 0 | 1
1188 );
1189 =cut
1190  
1191 use strict;
1192 use Carp;
1193 use Data::Dumper;
1194 use DBI();
1195  
1196 sub new {
1197 my $class = shift;
1198 my %args = @_;
1199 my $oq = bless \%args, $class;
1200  
1201 $$oq{debug} || 0;
1202 $$oq{error_handler}->("DEBUG: $class->new(".Dumper(\%args).")\n") if $$oq{debug};
1203  
1204 die "BAD_PARAMS - must provide a dbh!"
1205 unless $oq->{'dbh'};
1206 die "BAD_PARAMS - must define a select key in call to constructor"
1207 unless ref($oq->{'select'}) eq 'HASH';
1208 die "BAD_PARAMS - must define a joins key in call to constructor"
1209 unless ref($oq->{'joins'}) eq 'HASH';
1210  
1211  
1212 $oq->_normalize();
1213  
1214 $$oq{dbtype} = $$oq{dbh}{Driver}{Name};
1215 $$oq{dbtype} = $$oq{dbh}->get_info(17) if $$oq{dbtype} eq 'ODBC';
1216  
1217 return $oq;
1218 }
1219  
1220  
1221  
1222  
1223  
1224  
1225  
1226  
1227  
1228  
1229  
1230 our $filterGrammar = <<'TILEND';
1231 start: exp /^$/
1232  
1233 exp:
1234 '(' exp ')' logicOp exp
1235 | '(' exp ')'
1236 | comparisonExp logicOp exp
1237 | comparisonExp
1238  
1239 comparisonExp:
1240 namedFilter
1241 | colAlias compOp colAlias
1242 | colAlias compOp bindVal
1243  
1244 bindVal: float | quotedString
1245  
1246 logicOp:
1247 /and/i
1248 | /or/i
1249  
1250 namedFilter: /\w+/ '(' namedFilterArg(s? /,/) ')'
1251  
1252 namedFilterArg: quotedString | float | unquotedIdentifier
1253  
1254 unquotedIdentifier: /\w+/
1255  
1256 colAlias: '[' /\w+/ ']'
1257  
1258 float:
1259 /\-?\d*\.?\d+/
1260 | /\-?\d+\.?\d*/
1261  
1262 quotedString:
1263 /'.*?'/
1264 | /".*?"/
1265  
1266 compOp:
1267 '<=' | '>=' | '=' | '!=' | '<' | '>' |
1268 /contains/i | /not\ contains/i | /like/i | /not\ like/i
1269  
1270 TILEND
1271  
1272  
1273 our $sortGrammar = <<'TILEND';
1274 start: expList /^$/
1275  
1276 expList: expression(s? /,/)
1277  
1278 expression:
1279 namedSort opt(?)
1280 | colAlias opt(?)
1281  
1282 opt: /desc/i
1283  
1284 namedSort: /\w+/ '(' namedSortArg(s? /,/) ')'
1285 namedSortArg: quotedString | float
1286  
1287 colAlias: '[' /\w+/ ']'
1288  
1289 float:
1290 /\-?\d*\.?\d+/
1291 | /\-?\d+\.?\d*/
1292  
1293 quotedString:
1294 /'.*?(?<!\\)'/
1295 | /".*?(?<!\\)"/
1296  
1297 TILEND
1298  
1299 our (%cached_parsers, $oq, $translations);
1300 sub translator_callback {
1301 return $$translations{$_[0]}->($oq, @_) if exists $$translations{$_[0]};
1302 return $$translations{'*default*'}->($oq, @_) if exists $$translations{'*default*'};
1303 return 1;
1304 }
1305  
1306 sub parse {
1307 local $oq = shift;
1308 my $grammar = shift;
1309 my $string = shift;
1310 local $translations = shift;
1311 my $start_rule = shift || 'start';
1312 local $::RD_AUTOACTION = 'DBIx::OptimalQuery::translator_callback(@item);';
1313 $cached_parsers{$grammar} ||= Parse::RecDescent->new($grammar);
1314 return $cached_parsers{$grammar}->$start_rule($string);
1315 }
1316  
1317  
1318  
1319  
1320  
1321  
1322 # normalize member variables
1323 sub _normalize {
1324 my $oq = shift;
1325 $$oq{error_handler}->("DEBUG: \$oq->_normalize()\n") if $$oq{debug};
1326  
1327 $oq->{'AutoSetLongReadLen'} = 1 unless exists $oq->{'AutoSetLongReadLen'};
1328  
1329 # make sure all option hash refs exist
1330 $oq->{'select'}->{$_}->[3] ||= {} for keys %{ $oq->{'select'} };
1331 $oq->{'joins' }->{$_}->[3] ||= {} for keys %{ $oq->{'joins'} };
1332  
1333  
1334 # since the sql & deps definitions can optionally be entered as arrays
1335 # turn all into arrays if not already
1336 for ( # key, index
1337 ['select', 0], ['select', 1],
1338 ['joins', 0], ['joins', 1], ['joins', 2],
1339 ['named_filters', 0], ['named_filters', 1],
1340 ['named_sorts', 0], ['named_sorts', 1] ) {
1341 my ($key, $i) = @$_;
1342 $oq->{$key} ||= {};
1343 foreach my $alias (keys %{ $oq->{$key} }) {
1344 if (ref($oq->{$key}->{$alias}) eq 'ARRAY' &&
1345 defined $oq->{$key}->{$alias}->[$i] &&
1346 ref($oq->{$key}->{$alias}->[$i]) ne 'ARRAY') {
1347 $oq->{$key}->{$alias}->[$i] = [$oq->{$key}->{$alias}->[$i]];
1348 }
1349 }
1350 }
1351  
1352 # make sure the following select options, if they exist are array references
1353 foreach my $col (keys %{ $oq->{'select'} }) {
1354 my $opts = $oq->{'select'}->{$col}->[3];
1355 foreach my $opt (qw( select_sql sort_sql filter_sql )) {
1356 $opts->{$opt} = [$opts->{$opt}]
1357 if exists $opts->{$opt} && ref($opts->{$opt}) ne 'ARRAY';
1358 }
1359  
1360 # make sure defined deps exist
1361 foreach my $dep (@{ $$oq{'select'}{$col}[0] }) {
1362 die "dep $dep for select $col does not exist"
1363 if defined $dep && ! exists $$oq{'joins'}{$dep};
1364 }
1365 }
1366  
1367 # look for new cursors and define parent child links if not already defined
1368 foreach my $join (keys %{ $oq->{'joins'} }) {
1369 my $opts = $oq->{'joins'}->{$join}->[3];
1370 if (exists $opts->{new_cursor}) {
1371 if (ref($opts->{new_cursor}) ne 'HASH') {
1372 $oq->_formulate_new_cursor($join);
1373 } else {
1374 die "could not find keys, join, and sql for new cursor in $join"
1375 unless exists $opts->{new_cursor}->{'keys'} &&
1376 exists $opts->{new_cursor}->{'join'} &&
1377 exists $opts->{new_cursor}->{'sql'};
1378 }
1379 }
1380  
1381 # make sure defined deps exist
1382 foreach my $dep (@{ $$oq{'joins'}{$join}[0] }) {
1383 die "dep $dep for join $join does not exist"
1384 if defined $dep && ! exists $$oq{'joins'}{$dep};
1385 }
1386 }
1387  
1388 # make sure deps for named_sorts exist
1389 foreach my $named_sort (keys %{ $$oq{'named_sorts'} }) {
1390 foreach my $dep (@{ $$oq{'named_sorts'}{$named_sort}->[0] }) {
1391 die "dep $dep for named_sort $named_sort does not exist"
1392 if defined $dep && ! exists $$oq{'joins'}{$dep};
1393 }
1394 }
1395  
1396 # make sure deps for named_filter exist
1397 foreach my $named_filter (keys %{ $$oq{'named_filters'} }) {
1398 if (ref($$oq{'named_filters'}{$named_filter}) eq 'ARRAY') {
1399 foreach my $dep (@{ $$oq{'named_filters'}{$named_filter}->[0] }) {
1400 die "dep $dep for named_sort $named_filter does not exist"
1401 if defined $dep && ! exists $$oq{'joins'}{$dep};
1402 }
1403 }
1404 }
1405  
1406 $oq->{'col_types'} = undef;
1407  
1408 return undef;
1409 }
1410  
1411  
1412  
1413  
1414  
1415  
1416  
1417 # defines how a child cursor joins to its parent cursor
1418 # by defining keys, join, sql in child cursor
1419 # called from the _normalize method
1420 sub _formulate_new_cursor {
1421 my $oq = shift;
1422 my $joinAlias = shift;
1423  
1424 $$oq{error_handler}->("DEBUG: \$oq->_formulate_new_cursor('$joinAlias')\n") if $$oq{debug};
1425  
1426 # vars to define
1427 my (@keys, $join, $sql, @sqlBinds);
1428  
1429 # get join definition
1430 my ($fromSql, @fromBinds) = @{ $oq->{joins}->{$joinAlias}->[1] };
1431  
1432 my ($whereSql, @whereBinds);
1433 ($whereSql, @whereBinds) = @{ $oq->{joins}->{$joinAlias}->[2] }
1434 if defined $oq->{joins}->{$joinAlias}->[2];
1435  
1436 # if NOT an SQL-92 type join
1437 if (defined $whereSql) {
1438 $whereSql =~ s/\(\+\)/\ /g; # remove outer join notation
1439 die "BAD_PARAMS - where binds not allowed in 'new_cursor' joins"
1440 if scalar(@whereBinds);
1441 }
1442  
1443 # else is SQL-92 so separate out joins from table definition
1444 # do this by making it a pre SQL-92 type join
1445 # by defining $whereSql
1446 # and removing join sql from $fromSql
1447 else {
1448 $_ = $fromSql;
1449 m/\G\s*left\b/sicg;
1450 m/\G\s*join\b/sicg;
1451  
1452 # parse inline view
1453 if (m/\G\s*\(/scg) {
1454 $fromSql = '(';
1455 my $p=1;
1456 my $q;
1457 while ($p > 0 && m/\G(.)/scg) {
1458 my $c = $1;
1459 if ($q) { $q = '' if $c eq $q; } # if end of quote
1460 elsif ($c eq "'" || $c eq '"') { $q = $c; } # if start of quote
1461 elsif ($c eq '(') { $p++; } # if left paren
1462 elsif ($c eq ')') { $p--; } # if right paren
1463 $fromSql .= $c;
1464 }
1465 }
1466  
1467 # parse table name
1468 elsif (m/\G\s*(\w+)\b/scg) {
1469 $fromSql = $1;
1470 }
1471  
1472 else {
1473 die "could not parse tablename";
1474 }
1475  
1476 # include alias if it exists
1477 if (m/\G\s*([\d\w\_]+)\s*/scg && lc($1) ne 'on') {
1478 $fromSql .= ' '.$1;
1479 m/\G\s*on\b/cgi;
1480 }
1481  
1482 # get the whereSql
1483 if (m/\G\s*\((.*)\)\s*$/cgs) {
1484 $whereSql = $1;
1485 }
1486 }
1487  
1488 # define sql & sqlBinds
1489 $sql = $fromSql;
1490 @sqlBinds = @fromBinds;
1491
1492 # parse $whereSql to create $join, and @keys
1493 foreach my $part (split /\b([\w\d\_]+\.[\w\d\_]+)\b/,$whereSql) {
1494 if ($part =~ /\b([\w\d\_]+)\.([\w\d\_]+)\b/) {
1495 my $dep = $1;
1496 my $sql = $2;
1497 if ($dep eq $joinAlias) {
1498 $join .= $part;
1499 } else {
1500 push @keys, [$dep, $sql];
1501 $join .= '?';
1502 }
1503 } else {
1504 $join .= $part;
1505 }
1506 }
1507  
1508 # fill in options
1509 $oq->{joins}->{$joinAlias}->[3]->{'new_cursor'} = {
1510 'keys' => \@keys, 'join' => $join, 'sql' => [$sql, @sqlBinds] };
1511  
1512 return undef;
1513 }
1514  
1515  
1516  
1517  
1518 # make sure the join counts are the same
1519 # throws exception with error when there is a problem
1520 # this can be an expensive wasteful operation and should not be done in a production env
1521 sub check_join_counts {
1522 my $oq = shift;
1523  
1524 $$oq{error_handler}->("DEBUG: \$oq->check_join_counts()\n") if $$oq{debug};
1525  
1526  
1527 # since driving table count is computed first this will get set first
1528 my $drivingTableCount;
1529  
1530 foreach my $join (keys %{ $oq->{joins} }) {
1531 my ($cursors) = @{ $oq->_order_deps($join) };
1532 my @deps = map { @$_ } @$cursors; # flatten deps in cursors
1533 my $drivingTable = $deps[0];
1534  
1535 # now create from clause
1536 my ($fromSql, @fromBinds, @whereSql, @whereBinds);
1537 foreach my $joinAlias (@deps) {
1538 my ($sql, @sqlBinds) = @{ $oq->{joins}->{$joinAlias}->[1] };
1539  
1540 # if this is the driving table
1541 if (! $oq->{joins}->{$joinAlias}->[0]) {
1542 # alias it if not already aliased in sql
1543 $fromSql .= " $joinAlias" unless $sql =~ /\b$joinAlias\s*$/;
1544 }
1545  
1546 # if NOT sql-92 join
1547 elsif (defined $oq->{joins}->{$joinAlias}->[2]) {
1548 $fromSql .= ",\n $sql $joinAlias";
1549 push @fromBinds, @sqlBinds;
1550 my ($where_sql, @where_sqlBinds) = @{ $oq->{joins}->{$joinAlias}->[2] };
1551 push @whereSql, $where_sql;
1552 push @whereBinds, @where_sqlBinds;
1553 }
1554  
1555 # else this is an SQL-92 type join
1556 else {
1557 $fromSql .= "\n$sql ";
1558 }
1559 }
1560  
1561 my $where = 'WHERE '.join(' AND ', @whereSql) if @whereSql;
1562  
1563 my $sql = "
1564 SELECT count(*)
1565 FROM (
1566 SELECT $drivingTable.*
1567 FROM $fromSql
1568 $where
1569 ) OPTIMALQUERYCNTCK ";
1570 my @binds = (@fromBinds,@whereBinds);
1571 my $count;
1572 eval { ($count) = $oq->{dbh}->selectrow_array($sql, undef, @binds); };
1573 die "Problem executing ERROR: $@\nSQL: $sql\nBINDS: ".join(',', @binds)."\n" if $@;
1574 $drivingTableCount = $count unless defined $drivingTableCount;
1575 confess "BAD_JOIN_COUNT - driving table $drivingTable count ".
1576 "($drivingTableCount) != driving table joined with $join".
1577 " count ($count)" if $count != $drivingTableCount;
1578 }
1579  
1580 return undef;
1581 }
1582  
1583  
1584  
1585 =comment
1586 $oq->get_col_type($alias,$context);
1587 =cut
1588 sub type_map {
1589 my $oq = shift;
1590 return {
1591 -1 => 'char',
1592 -4 => 'clob',
1593 -5 => 'num',
1594 -6 => 'num',
1595 -9 => 'char',
1596 0 => 'char',
1597 1 => 'char',
1598 3 => 'num', # is decimal type
1599 4 => 'num',
1600 6 => 'num', # float
1601 7 => 'num',
1602 8 => 'num',
1603 9 => 'date',
1604 11 => 'datetime',
1605 10 => 'char',
1606 12 => 'char',
1607 16 => 'date',
1608 30 => 'clob',
1609 40 => 'clob',
1610 91 => 'date',
1611 93 => 'date',
1612 95 => 'date',
1613 'INTEGER' => 'num',
1614 'TEXT' => 'char',
1615 'VARCHAR' => 'char',
1616 'varchar' => 'char'
1617 };
1618 }
1619  
1620 # $type = $oq->get_col_type($alias,$context);
1621 sub get_col_type {
1622 my $oq = shift;
1623 my $alias = shift;
1624 my $context = shift || 'default';
1625 $$oq{error_handler}->("DEBUG: \$oq->get_col_type($alias, $context)\n") if $$oq{debug};
1626  
1627 return $oq->{'select'}->{$alias}->[3]->{'col_type'} ||
1628 $oq->get_col_types($context)->{$alias};
1629 }
1630  
1631 #{ ColAlias => Type, .. } = $oq->get_col_types($context)
1632 # where $content in ('default','sort','filter','select')
1633 sub get_col_types {
1634 my $oq = shift;
1635 my $context = shift || 'default';
1636 $$oq{error_handler}->("DEBUG: \$oq->get_col_types($context)\n") if $$oq{debug};
1637 return $oq->{'col_types'}->{$context}
1638 if defined $oq->{'col_types'};
1639  
1640 $oq->{'col_types'} = {
1641 'default' => {}, 'sort' => {},
1642 'filter' => {}, 'select' => {} };
1643  
1644 my (%deps, @selectColTypeOrder, @selectColAliasOrder, @select, @selectBinds, @where);
1645 foreach my $selectAlias (keys %{ $oq->{'select'} } ) {
1646 my $s = $oq->{'select'}->{$selectAlias};
1647  
1648 # did user already define this type?
1649 if (exists $s->[3]->{'col_type'}) {
1650 $oq->{'col_types'}->{'default'}->{$selectAlias} = $s->[3]->{'col_type'};
1651 $oq->{'col_types'}->{'select' }->{$selectAlias} = $s->[3]->{'col_type'};
1652 $oq->{'col_types'}->{'filter' }->{$selectAlias} = $s->[3]->{'col_type'};
1653 $oq->{'col_types'}->{'sort' }->{$selectAlias} = $s->[3]->{'col_type'};
1654 }
1655  
1656 # else write sql to determine type with context
1657 else {
1658 $deps{$_} = 1 for @{ $s->[0] };
1659  
1660 foreach my $type (
1661 ['default', $s->[1]],
1662 ['select', $s->[3]->{'select_sql'}],
1663 ['filter', $s->[3]->{'filter_sql'}],
1664 ['sort', $s->[3]->{'sort_sql'}] ) {
1665 next if ! defined $type->[1];
1666 push @selectColTypeOrder, $type->[0];
1667 push @selectColAliasOrder, $selectAlias;
1668 my ($sql, @binds) = @{ $type->[1] };
1669 push @select, $sql;
1670 push @selectBinds, @binds;
1671  
1672 # this next one is needed for oracle so inline views don't get processed
1673 # kinda stupid if you ask me
1674 # don't bother though if there is binds
1675 # this isn't neccessary for mysql since an explicit limit is
1676 # defined latter
1677 if ($$oq{dbtype} eq 'Oracle' && $#binds == -1) {
1678 push @where, "to_char($sql) = NULL";
1679 }
1680 }
1681 }
1682 }
1683  
1684 # are there unknown deps?
1685 if (%deps) {
1686  
1687 # order and flatten deps
1688 my @deps = keys %deps;
1689 my ($deps) = @{ $oq->_order_deps(\@deps) };
1690  
1691  
1692 @deps = ();
1693 push @deps, @$_ for @$deps;
1694  
1695 # now create from clause
1696 my ($fromSql, @fromBinds);
1697 foreach my $joinAlias (@deps) {
1698 my ($sql, @sqlBinds) = @{ $oq->{joins}->{$joinAlias}->[1] };
1699 push @fromBinds, @sqlBinds;
1700  
1701 # if this is the driving table join
1702 if (! $oq->{joins}->{$joinAlias}->[0]) {
1703  
1704 # alias it if not already aliased in sql
1705 $fromSql .= $sql;
1706 $fromSql .= " $joinAlias" unless $sql =~ /\b$joinAlias\s*$/;
1707 }
1708  
1709 # if NOT sql-92 join
1710 elsif (defined $oq->{joins}->{$joinAlias}->[2]) {
1711 $fromSql .= ",\n $sql $joinAlias";
1712 }
1713  
1714 # else this is an SQL-92 type join
1715 else {
1716 $fromSql .= "\n$sql ";
1717 }
1718  
1719 }
1720  
1721 my $where = ' AND ' if @where;
1722 $where .= join("\nAND ", @where);
1723  
1724 my @binds = (@selectBinds, @fromBinds);
1725 my $sql = "
1726 SELECT ".join(',', @select)."
1727 FROM $fromSql";
1728  
1729 if ($$oq{dbtype} eq 'Oracle' || $$oq{dbtype} eq 'Microsoft SQL Server') {
1730 $sql .= "
1731 WHERE 1=2
1732 $where ";
1733 }
1734  
1735 elsif ($$oq{dbtype} eq 'mysql') {
1736 $sql .= "
1737 LIMIT 0 ";
1738 }
1739  
1740 my $sth;
1741 eval {
1742 local $oq->{dbh}->{PrintError} = 0;
1743 local $oq->{dbh}->{RaiseError} = 1;
1744 $sth = $oq->{dbh}->prepare($sql);
1745 $sth->execute(@binds);
1746 }; if ($@) {
1747 confess "SQL Error in get_col_types:\n$@\n$sql\n(".join(",",@binds).")";
1748 }
1749  
1750 # read types into col_types cache in object
1751 my $type_map = $oq->type_map();
1752 for (my $i=0; $i < scalar(@selectColAliasOrder); $i++) {
1753 my $name = $selectColAliasOrder[$i];
1754 my $type_code = $sth->{TYPE}->[$i];
1755  
1756 # remove parenthesis in type_code from sqlite
1757 $type_code =~ s/\([^\)]*\)//;
1758
1759 my $type = $type_map->{$type_code} or
1760 die "could not find type code: $type_code for col $name";
1761 $oq->{'col_types'}->{$selectColTypeOrder[$i]}->{$name} = $type;
1762  
1763 # set the type for select, filter, and sort to the default
1764 # unless they are already defined
1765 if ($selectColTypeOrder[$i] eq 'default') {
1766 $oq->{'col_types'}->{'select' }->{$name} ||= $type;
1767 $oq->{'col_types'}->{'filter' }->{$name} ||= $type;
1768 $oq->{'col_types'}->{'sort' }->{$name} ||= $type;
1769 }
1770 }
1771  
1772 $sth->finish();
1773 }
1774  
1775 return $oq->{'col_types'}->{$context};
1776 }
1777  
1778  
1779  
1780  
1781 # prepare an sth
1782 sub prepare {
1783 my $oq = shift;
1784 $$oq{error_handler}->("DEBUG: \$oq->prepare(".Dumper(\@_).")\n") if $$oq{debug};
1785 return DBIx::OptimalQuery::sth->new($oq,@_);
1786 }
1787  
1788  
1789  
1790 # returns ARRAYREF: [order,idx]
1791 # order is [ [dep1,dep2,dep3], [dep4,dep5,dep6] ], # cursor/dep order
1792 # idx is { dep1 => 0, dep4 => 1, .. etc .. } # index of what cursor dep is in
1793 sub _order_deps {
1794 my $oq = shift;
1795 $$oq{error_handler}->("DEBUG: \$oq->_order_deps(".Dumper(\@_).")\n") if $$oq{debug};
1796 my $deps = shift;
1797 $deps = [$deps] unless ref($deps) eq 'ARRAY';
1798  
1799 # @order is an array of array refs. Where each array ref represents deps
1800 # for a separate cursor
1801 # %idx is a hash of scalars where the hash key is the dep name and the
1802 # hash value is what index into order (which cursor number)
1803 # where you find the dep
1804 my (@order, %idx);
1805  
1806 # var to detect infinite recursion
1807 my $maxRecurse = 1000;
1808  
1809 # recursive function to order deps
1810 # each dep calls this again on all parent deps until all deps are fulfilled
1811 # then the dep is added
1812 # modfies @order & %idx
1813 my $place_missing_deps;
1814 $place_missing_deps = sub {
1815 my $dep = shift;
1816  
1817 # detect infinite recursion
1818 $maxRecurse--;
1819 die "BAD_JOINS - could not link joins to meet all deps" if $maxRecurse == 0;
1820  
1821 # recursion to make sure parent deps are added first
1822 if (defined $oq->{'joins'}->{$dep}->[0]) {
1823 foreach my $parent_dep (@{ $oq->{'joins'}->{$dep}->[0] } ) {
1824 $place_missing_deps->($parent_dep) if ! exists $idx{$parent_dep};
1825 }
1826 }
1827  
1828 # at this point all parent deps have been added,
1829 # now add this dep if it has not already been added
1830 if (! exists $idx{$dep}) {
1831  
1832 # add new cursor if dep is main driving table or has option new_cursor
1833 if (! defined $oq->{'joins'}->{$dep}->[0] ||
1834 exists $oq->{'joins'}->{$dep}->[3]->{new_cursor}) {
1835 push @order, [$dep];
1836 $idx{$dep} = $#order;
1837 }
1838  
1839 # place dep in @order & %idx
1840 # uses the same cursor as its parent dep
1841 # this is found by looking at the parent_idx
1842 else {
1843 my $parent_idx = $idx{$oq->{'joins'}->{$dep}->[0]->[0]} || 0;
1844 push @{ $order[ $parent_idx ] }, $dep;
1845 $idx{$dep} = $parent_idx;
1846 }
1847 }
1848 return undef;
1849 };
1850  
1851 $place_missing_deps->($_) for @$deps;
1852  
1853 return [\@order, \%idx];
1854 }
1855  
1856  
1857 1;