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