it would help if I actually enabled with for non-select statements
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / ExtraClauses.pm
1 package SQL::Abstract::ExtraClauses;
2
3 use strict;
4 use warnings;
5 use if $] < '5.010', 'MRO::Compat';
6 use mro 'c3';
7 use base qw(SQL::Abstract::Clauses);
8
9 BEGIN { *puke = \&SQL::Abstract::puke }
10
11 sub register_defaults {
12   my $self = shift;
13   $self->next::method(@_);
14   my @clauses = $self->clauses_of('select');
15   my @before_setop;
16   CLAUSE: foreach my $idx (0..$#clauses) {
17     if ($clauses[$idx] eq 'order_by') {
18       @before_setop = @clauses[0..$idx-1];
19       splice(@clauses, $idx, 0, qw(setop group_by having));
20       last CLAUSE;
21     }
22   }
23   die "Huh?" unless @before_setop;
24   $self->clauses_of(select => 'with', @clauses);
25   $self->clause_expanders(
26     'select.group_by', sub {
27       $_[0]->_expand_maybe_list_expr($_[2], -ident)
28     },
29     'select.having', sub { $_[0]->expand_expr($_[2]) },
30   );
31   foreach my $thing (qw(join from_list)) {
32     $self->expander($thing => "_expand_${thing}")
33          ->renderer($thing => "_render_${thing}")
34   }
35   $self->op_expander(as => '_expand_op_as');
36   $self->expander(as => '_expand_op_as');
37   $self->renderer(as => '_render_as');
38   $self->expander(alias => sub {
39     my ($self, undef, $args) = @_;
40     if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
41       $args = $alias;
42     }
43     +{ -alias => [
44         map $self->expand_expr($_, -ident),
45         ref($args) eq 'ARRAY' ? @{$args} : $args
46       ]
47     }
48   });
49   $self->renderer(alias => '_render_alias');
50
51   $self->clauses_of(update => sub {
52     my ($self, @clauses) = @_;
53     splice(@clauses, 2, 0, 'from');
54     @clauses;
55   });
56
57   $self->clauses_of(delete => sub {
58     my ($self, @clauses) = @_;
59     splice(@clauses, 1, 0, 'using');
60     @clauses;
61   });
62
63   $self->clause_expanders(
64     'update.from' => '_expand_select_clause_from',
65     'delete.using' => sub {
66       +(using => $_[0]->_expand_from_list(undef, $_[2]));
67     },
68     'insert.rowvalues' => sub {
69       +(from => $_[0]->expand_expr({ -values => $_[2] }));
70     },
71     'insert.select' => sub {
72       +(from => $_[0]->expand_expr({ -select => $_[2] }));
73     },
74   );
75
76   # set ops
77   $self->wrap_expander(select => sub {
78     my $orig = shift;
79     sub {
80       my $self = shift;
81       my $exp = $self->$orig(@_);
82       return $exp unless my $setop = (my $sel = $exp->{-select})->{setop};
83       if (my @keys = grep $sel->{$_}, @before_setop) {
84         my %inner; @inner{@keys} = delete @{$sel}{@keys};
85         unshift @{(values(%$setop))[0]{queries}},
86           { -select => \%inner };
87       }
88       return $exp;
89     }
90   });
91   my $expand_setop = sub {
92     my ($self, $setop, $args) = @_;
93     +{ "-${setop}" => {
94          %$args,
95          queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
96     } };
97   };
98   $self->expanders(map +($_ => $expand_setop), qw(union intersect except));
99
100   $self->clause_renderer('select.setop' => sub {
101     my ($self, undef, $setop) = @_;
102     $self->render_aqt($setop);
103   });
104
105   $self->renderer($_ => sub {
106     my ($self, $setop, $args) = @_;
107     $self->join_query_parts(
108       ' '.$self->format_keyword(join '_', $setop, ($args->{type}||())).' ',
109       @{$args->{queries}}
110     );
111   }) for qw(union intersect except);
112
113   my $setop_expander = sub {
114     my ($self, $setop, $args) = @_;
115     my ($op, $type) = split '_', $setop;
116     +(setop => $self->expand_expr({
117       "-${op}" => {
118         ($type ? (type => $type) : ()),
119         queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
120       }
121     }));
122   };
123
124   $self->clause_expanders(
125     map +($_ => $setop_expander),
126       map "select.${_}",
127         map +($_, "${_}_all", "${_}_distinct"),
128           qw(union intersect except)
129   );
130
131   $self->clause_expander('select.with' => my $with_expander = sub {
132     my ($self, $name, $with) = @_;
133     my (undef, $type) = split '_', $name;
134     if (ref($with) eq 'HASH') {
135       return +{
136         %$with,
137         queries => [
138           map +[
139             $self->expand_expr({ -alias => $_->[0] }, -ident),
140             $self->expand_expr($_->[1]),
141           ], @{$with->{queries}}
142         ]
143       }
144     }
145     my @with = @$with;
146     my @exp;
147     while (my ($alias, $query) = splice @with, 0, 2) {
148       push @exp, [
149         $self->expand_expr({ -alias => $alias }, -ident),
150         $self->expand_expr($query)
151       ];
152     }
153     return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
154   });
155   $self->clause_expander('select.with_recursive', $with_expander);
156   $self->clause_renderer('select.with' => my $with_renderer = sub {
157     my ($self, undef, $with) = @_;
158     my $q_part = $self->join_query_parts(', ',
159       map {
160         my ($alias, $query) = @$_;
161         $self->join_query_parts(' ',
162             $alias,
163             $self->format_keyword('as'),
164             $query,
165         )
166       } @{$with->{queries}}
167     );
168     return $self->join_query_parts(' ',
169       $self->format_keyword(join '_', 'with', ($with->{type}||'')),
170       $q_part,
171     );
172   });
173   foreach my $stmt (qw(insert update delete)) {
174     $self->clauses_of($stmt => 'with', $self->clauses_of($stmt));
175     $self->clause_expander("${stmt}.$_", $with_expander)
176       for qw(with with_recursive);
177     $self->clause_renderer("${stmt}.with", $with_renderer);
178   }
179
180   return $self;
181 }
182
183 sub _expand_select_clause_from {
184   my ($self, undef, $from) = @_;
185   +(from => $self->_expand_from_list(undef, $from));
186 }
187
188 sub _expand_from_list {
189   my ($self, undef, $args) = @_;
190   if (ref($args) eq 'HASH') {
191     return $args if $args->{-from_list};
192     return { -from_list => [ $self->expand_expr($args) ] };
193   }
194   my @list;
195   my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
196   while (my $entry = shift @args) {
197     if (!ref($entry) and $entry =~ /^-(.*)/) {
198       if ($1 eq 'as') {
199         $list[-1] = $self->expand_expr({ -as => [
200           $list[-1], map +(ref($_) eq 'ARRAY' ? @$_ : $_), shift(@args)
201         ]});
202         next;
203       }
204       $entry = { $entry => shift @args };
205     }
206     my $aqt = $self->expand_expr($entry, -ident);
207     if ($aqt->{-join} and not $aqt->{-join}{from}) {
208       $aqt->{-join}{from} = pop @list;
209     }
210     push @list, $aqt;
211   }
212   return { -from_list => \@list };
213 }
214
215 sub _expand_join {
216   my ($self, undef, $args) = @_;
217   my %proto = (
218     ref($args) eq 'HASH'
219       ? %$args
220       : (to => $args->[0], @{$args}[1..$#$args])
221   );
222   if (my $as = delete $proto{as}) {
223     $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
224   }
225   if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
226     $proto{using} = [
227       map [ $self->expand_expr($_, -ident) ],
228         ref($using) eq 'ARRAY' ? @$using: $using
229     ];
230   }
231   my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
232               sort keys %proto;
233   return +{ -join => \%ret };
234 }
235
236 sub _render_from_list {
237   my ($self, undef, $list) = @_;
238   return $self->join_query_parts(', ', @$list);
239 }
240
241 sub _render_join {
242   my ($self, undef, $args) = @_;
243
244   my @parts = (
245     $args->{from},
246     $self->format_keyword(join '_', ($args->{type}||()), 'join'),
247     (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
248     ($args->{on} ? (
249       $self->format_keyword('on') ,
250       $args->{on},
251     ) : ()),
252     ($args->{using} ? (
253       $self->format_keyword('using'),
254       '(', $args->{using}, ')',
255     ) : ()),
256   );
257   return $self->join_query_parts(' ', @parts);
258 }
259
260 sub _expand_op_as {
261   my ($self, undef, $vv, $k) = @_;
262   my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
263   $k ||= shift @vv;
264   my $ik = $self->expand_expr($k, -ident);
265   return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
266     if @vv == 1 and ref($vv[0]) eq 'HASH';
267
268   my @as = map $self->expand_expr($_, -ident), @vv;
269   return { -as => [ $ik, { -alias => \@as } ] };
270 }
271
272 sub _render_as {
273   my ($self, undef, $args) = @_;
274   my ($thing, $alias) = @$args;
275   return $self->join_query_parts(
276     ' ',
277     $thing,
278     $self->format_keyword('as'),
279     $alias,
280   );
281 }
282
283 sub _render_alias {
284   my ($self, undef, $args) = @_;
285   my ($as, @cols) = @$args;
286   return (@cols
287     ? $self->join_query_parts('',
288          $as,
289          '(',
290          $self->join_query_parts(
291            ', ',
292            @cols
293          ),
294          ')',
295       )
296     : $self->render_aqt($as)
297   );
298 }
299
300 sub _expand_update_clause_target {
301   my ($self, undef, $target) = @_;
302   +(target => $self->_expand_from_list(undef, $target));
303 }
304
305 1;