IS NOT? NULL support
[dbsrgits/SQL-Abstract-2.0-ish.git] / lib / SQL / Abstract / AST / v1.pm
1 use MooseX::Declare;
2
3 class SQL::Abstract::AST::v1 extends SQL::Abstract {
4
5   use Carp qw/croak/;
6   use Data::Dump qw/pp/;
7
8   use Moose::Util::TypeConstraints;
9   use MooseX::Types::Moose qw/ArrayRef Str Int Ref HashRef/;
10   use MooseX::AttributeHelpers;
11   use SQL::Abstract::Types qw/AST/;
12   use Devel::PartialDump qw/dump/;
13
14   clean;
15
16   # set things that are valid in where clauses
17   override _build_expr_dispatch_table {
18     return { 
19       %{super()},
20       in => $self->can('_in'),
21       not_in => $self->can('_in'),
22       between => $self->can('_between'),
23       not_between => $self->can('_between'),
24       and => $self->can('_recurse_where'),
25       or => $self->can('_recurse_where'),
26       map { +"$_" => $self->can("_$_") } qw/
27         value
28         name
29         true
30         false
31         expr
32       /
33     };
34   }
35
36   method _select(AST $ast) {
37     # Default to requiring columns and from.
38     # DB specific ones (i.e. mysql/Pg) can not require the FROM part with a bit
39     # of refactoring
40     
41     for (qw/columns tablespec/) {
42       confess "'$_' is required in select AST with " . dump ($ast)
43         unless exists $ast->{$_};
44     }
45    
46     # Check that columns is a -list
47     confess "'columns' should be an array ref, not " . dump($ast->{columns})
48       unless is_ArrayRef($ast->{columns});
49
50     my $cols = $self->_list({-type => 'list', args => $ast->{columns} });
51
52     my @output = (
53       SELECT => $cols
54     );
55
56     push @output, FROM => $self->dispatch($ast->{tablespec})
57       if exists $ast->{tablespec};
58
59     if (exists $ast->{where}) {
60       my $sub_ast = $ast->{where};
61
62       confess "$_ option is not an AST: " . dump($sub_ast)
63         unless is_AST($sub_ast);
64
65       push @output, "WHERE", $self->_expr($sub_ast);
66     }
67
68     for (qw/group_by having order_by/) {
69       if (exists $ast->{$_}) {
70         my $sub_ast = $ast->{$_};
71
72         confess "$_ option is not an AST or an ArrayRef: " . dump($sub_ast)
73           unless is_AST($sub_ast) || is_ArrayRef($sub_ast);;
74
75         my $meth = "__$_";
76         push @output, $self->$meth($sub_ast);
77       }
78     }
79
80     return join(' ', @output);
81   }
82
83   method _join(HashRef $ast) {
84
85     # TODO: Validate join type
86     my $type = $ast->{join_type} || "";
87   
88     my @output = $self->dispatch($ast->{lhs});
89
90     push @output, uc $type if $type;
91     push @output, "JOIN", $self->dispatch($ast->{rhs});
92
93     push @output, 
94         exists $ast->{on}
95       ? ('ON', '(' . $self->_expr( $ast->{on} ) . ')' )
96       : ('USING', '(' .$self->dispatch($ast->{using} 
97                         || croak "No 'on' or 'uinsg' clause passed to join cluase: " .
98                                  dump($ast) 
99                         ) .
100                   ')' );
101
102     return join(" ", @output);
103       
104   }
105
106   method _ordering(AST $ast) {
107  
108     my $output = $self->_expr($ast->{expr});
109
110     $output .= " " . uc $1
111       if $ast->{direction} && 
112          ( $ast->{direction} =~ /^(asc|desc)$/i 
113            || confess "Unknown ordering direction " . dump($ast)
114          );
115
116     return $output;
117   }
118
119   method _name(AST $ast) {
120     my @names = @{$ast->{args}};
121
122     my $sep = $self->name_separator;
123     my $quote = $self->is_quoting 
124               ? $self->quote_chars
125               : [ '' ];
126
127     my $join = $quote->[-1] . $sep . $quote->[0];
128
129     # We dont want to quote * in [qw/me */]: `me`.* is the desired output there
130     # This means you can't have a field called `*`. I am willing to accept this
131     # situation, cos thats a really stupid thing to want.
132     my $post;
133     $post = pop @names if $names[-1] eq '*';
134
135     my $ret;
136     $ret = $quote->[0] . 
137            join( $join, @names ) . 
138            $quote->[-1]
139       if @names;
140
141     $ret = $ret 
142          ? $ret . $sep . $post
143          : $post
144       if defined $post;
145
146
147     return $ret;
148   }
149
150
151   method _list(AST $ast) {
152     return "" unless $ast->{args};
153
154     my @items = is_ArrayRef($ast->{args})
155               ? @{$ast->{args}}
156               : $ast->{args};
157
158     return join(
159       $self->list_separator,
160       map { $self->dispatch($_) } @items);
161   }
162
163   # TODO: I think i want to parameterized AST type to get better validation
164   method _alias(AST $ast) {
165     
166     # TODO: Maybe we want qq{ AS "$as"} here
167     return $self->dispatch($ast->{ident}) . " AS " . $ast->{as};
168
169   }
170
171   method _value(AST $ast) {
172
173     $self->add_bind($ast->{value});
174     return "?";
175   }
176
177   # Not dispatchable to.
178   method __having($args) {
179     return "HAVING " . $self->_list({-type => 'list', args => $args});
180   }
181
182   method __group_by($args) {
183     return "GROUP BY " . $self->_list({-type => 'list', args => $args});
184   }
185
186   method __order_by($args) {
187     return "ORDER BY " . $self->_list({-type => 'list', args => $args});
188   }
189
190
191   # Perhaps badly named. handles 'and' and 'or' clauses
192   method _recurse_where(AST $ast) {
193
194     my $op = $ast->{op};
195
196     my $OP = uc $op;
197     my $prio = $SQL::Abstract::PRIO{$op};
198
199     my $dispatch_table = $self->expr_dispatch_table;
200
201     my @output;
202     foreach ( @{$ast->{args}} ) {
203       croak "invalid component in where clause: $_" unless is_AST($_);
204
205       if ($_->{-type} eq 'expr' && $_->{op} =~ /^(and|or)$/) {
206         my $sub_prio = $SQL::Abstract::PRIO{$1}; 
207
208         if ($sub_prio == $prio) {
209           # When the element below has same priority, i.e. 'or' as a child of
210           # 'or', dont produce extra brackets
211           push @output, $self->_recurse_where($_);
212         } else {
213           push @output, '(' . $self->_recurse_where($_) . ')';
214         }
215       } else {
216         push @output, $self->_expr($_);
217       }
218     }
219
220     return join(" $OP ", @output);
221   }
222
223   method _expr(AST $ast) {
224     my $op = $ast->{-type};
225
226     $op = $ast->{op} if $op eq 'expr';
227
228     if (my $code = $self->lookup_expr_dispatch($op)) { 
229       
230       return $code->($self, $ast);
231
232     }
233     croak "'$op' is not a valid AST type in an expression with " . dump($ast)
234       if $ast->{-type} ne 'expr';
235
236     # This is an attempt to do some form of validation on function names. This
237     # might end up being a bad thing.
238     croak "'$op' is not a valid operator in an expression with " . dump($ast)
239       if $op =~ /\W/;
240
241     return $self->_generic_function_op($ast);
242    
243   }
244
245   method _binop(AST $ast) {
246     my ($lhs, $rhs) = @{$ast->{args}};
247     my $op = $ast->{op};
248
249     # IS NOT? NULL
250     if ($rhs->{-type} eq 'value' && !defined $rhs->{value} &&
251         ($op eq '==' || $op eq '!='))
252     {
253       return $self->_expr($lhs) .
254              ($op eq '==' ? " IS " : " IS NOT ") .
255              "NULL";
256     }
257
258     join (' ', $self->_expr($lhs), 
259                $self->binop_mapping($op) || croak("Unknown binary operator $op"),
260                $self->_expr($rhs)
261     );
262   }
263
264   method _generic_function_op(AST $ast) {
265     my $op = $ast->{op};
266
267     return "$op(" . $self->_list($ast) . ")";
268   }
269
270   method _in(AST $ast) {
271   
272     my ($field,@values) = @{$ast->{args}};
273
274     my $not = ($ast->{op} =~ /^not_/) ? " NOT" : "";
275
276     return $self->_false unless @values;
277
278     return $self->_expr($field) .
279            $not . 
280            " IN (" .
281            join(", ", map { $self->dispatch($_) } @values ) .
282            ")";
283   }
284
285   method _between(AST $ast) {
286   
287     my ($field,@values) = @{$ast->{args}};
288
289     my $not = ($ast->{op} =~ /^not_/) ? " NOT" : "";
290     croak "between requires 3 arguments: " . dump($ast)
291       unless @values == 2;
292
293     # The brackets are to work round an issue with SQL::A::Test
294     return "(" .
295            $self->_expr($field) .
296            $not . 
297            " BETWEEN " .
298            join(" AND ", map { $self->dispatch($_) } @values ) .
299            ")";
300   }
301
302   # 'constants' that are portable across DBs
303   method _false($ast?) { "0 = 1" }
304   method _true($ast?) { "1 = 1" }
305
306 }