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