extract setop expansion
[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
91   $sqla->clause_renderer('select.setop' => $self->cb(sub {
92     my ($self, undef, $setop) = @_;
93     $self->render_aqt($setop);
94   }));
95
96   foreach my $setop (qw(union intersect except)) {
97     $sqla->expander($setop => $self->cb('_expand_setop'));
98     $sqla->renderer($setop => $self->cb('_render_setop'));
99   }
100
101   my $setop_expander = $self->cb(sub {
102     my ($self, $setop, $args) = @_;
103     my ($op, $type) = split '_', $setop;
104     +(setop => $self->expand_expr({
105       "-${op}" => {
106         ($type ? (type => $type) : ()),
107         queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
108       }
109     }));
110   });
111
112   $sqla->clause_expanders(
113     map +($_ => $setop_expander),
114       map "select.${_}",
115         map +($_, "${_}_all", "${_}_distinct"),
116           qw(union intersect except)
117   );
118
119   my $w_exp = $self->cb('_expand_with');
120   my $w_rdr = $self->cb('_render_with');
121   $sqla->clause_expander('select.with' => $w_exp);
122   $sqla->clause_expander('select.with_recursive' => $w_exp);
123   $sqla->clause_renderer('select.with' => $w_rdr);
124
125   foreach my $stmt (qw(insert update delete)) {
126     $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
127     $sqla->clause_expander("${stmt}.$_" => $w_exp)
128       for qw(with with_recursive);
129     $sqla->clause_renderer("${stmt}.with" => $w_rdr);
130   }
131
132   $sqla->expander(cast => $self->cb('_expand_cast'));
133
134   $sqla->clause_expanders(
135     "select.from", $self->cb('_expand_select_clause_from'),
136     "update.target", $self->cb('_expand_update_clause_target'),
137     "update.update", $self->cb('_expand_update_clause_target'),
138   );
139
140   return $sqla;
141 }
142
143 sub _expand_select_clause_from {
144   my ($self, undef, $from) = @_;
145   +(from => $self->_expand_from_list(undef, $from));
146 }
147
148 sub _expand_from_list {
149   my ($self, undef, $args) = @_;
150   if (ref($args) eq 'HASH') {
151     return $args if $args->{-from_list};
152     return { -from_list => [ $self->expand_expr($args) ] };
153   }
154   my @list;
155   my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
156   while (my $entry = shift @args) {
157     if (!ref($entry) and $entry =~ /^-(.*)/) {
158       if ($1 eq 'as') {
159         $list[-1] = $self->expand_expr({ -as => [
160           $list[-1], map +(ref($_) eq 'ARRAY' ? @$_ : $_), shift(@args)
161         ]});
162         next;
163       }
164       $entry = { $entry => shift @args };
165     }
166     my $aqt = $self->expand_expr($entry, -ident);
167     if ($aqt->{-join} and not $aqt->{-join}{from}) {
168       $aqt->{-join}{from} = pop @list;
169     }
170     push @list, $aqt;
171   }
172   return { -from_list => \@list };
173 }
174
175 sub _expand_join {
176   my ($self, undef, $args) = @_;
177   my %proto = (
178     ref($args) eq 'HASH'
179       ? %$args
180       : (to => $args->[0], @{$args}[1..$#$args])
181   );
182   if (my $as = delete $proto{as}) {
183     $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
184   }
185   if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
186     $proto{using} = [
187       map [ $self->expand_expr($_, -ident) ],
188         ref($using) eq 'ARRAY' ? @$using: $using
189     ];
190   }
191   my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
192               sort keys %proto;
193   return +{ -join => \%ret };
194 }
195
196 sub _render_from_list {
197   my ($self, undef, $list) = @_;
198   return $self->join_query_parts(', ', @$list);
199 }
200
201 sub _render_join {
202   my ($self, undef, $args) = @_;
203
204   my @parts = (
205     $args->{from},
206     $self->format_keyword(join '_', ($args->{type}||()), 'join'),
207     (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
208     ($args->{on} ? (
209       $self->format_keyword('on') ,
210       $args->{on},
211     ) : ()),
212     ($args->{using} ? (
213       $self->format_keyword('using'),
214       '(', $args->{using}, ')',
215     ) : ()),
216   );
217   return $self->join_query_parts(' ', @parts);
218 }
219
220 sub _expand_op_as {
221   my ($self, undef, $vv, $k) = @_;
222   my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
223   $k ||= shift @vv;
224   my $ik = $self->expand_expr($k, -ident);
225   return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
226     if @vv == 1 and ref($vv[0]) eq 'HASH';
227
228   my @as = map $self->expand_expr($_, -ident), @vv;
229   return { -as => [ $ik, { -alias => \@as } ] };
230 }
231
232 sub _render_as {
233   my ($self, undef, $args) = @_;
234   my ($thing, $alias) = @$args;
235   return $self->join_query_parts(
236     ' ',
237     $thing,
238     $self->format_keyword('as'),
239     $alias,
240   );
241 }
242
243 sub _render_alias {
244   my ($self, undef, $args) = @_;
245   my ($as, @cols) = @$args;
246   return (@cols
247     ? $self->join_query_parts('',
248          $as,
249          '(',
250          $self->join_query_parts(
251            ', ',
252            @cols
253          ),
254          ')',
255       )
256     : $self->render_aqt($as)
257   );
258 }
259
260 sub _expand_update_clause_target {
261   my ($self, undef, $target) = @_;
262   +(target => $self->_expand_from_list(undef, $target));
263 }
264
265 sub _expand_cast {
266   my ($self, undef, $thing) = @_;
267   return { -func => [ cast => $thing ] } if ref($thing) eq 'HASH';
268   my ($cast, $to) = @{$thing};
269   +{ -func => [ cast => { -as => [
270     $self->expand_expr($cast),
271     $self->expand_expr($to, -ident),
272   ] } ] };
273 }
274
275 sub _expand_alias {
276   my ($self, undef, $args) = @_;
277   if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
278     $args = $alias;
279   }
280   +{ -alias => [
281       map $self->expand_expr($_, -ident),
282       ref($args) eq 'ARRAY' ? @{$args} : $args
283     ]
284   }
285 }
286
287 sub _expand_with {
288   my ($self, $name, $with) = @_;
289   my (undef, $type) = split '_', $name;
290   if (ref($with) eq 'HASH') {
291     return +{
292       %$with,
293       queries => [
294         map +[
295           $self->expand_expr({ -alias => $_->[0] }, -ident),
296           $self->expand_expr($_->[1]),
297         ], @{$with->{queries}}
298       ]
299     }
300   }
301   my @with = @$with;
302   my @exp;
303   while (my ($alias, $query) = splice @with, 0, 2) {
304     push @exp, [
305       $self->expand_expr({ -alias => $alias }, -ident),
306       $self->expand_expr($query)
307     ];
308   }
309   return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
310 }
311
312 sub _render_with {
313   my ($self, undef, $with) = @_;
314   my $q_part = $self->join_query_parts(', ',
315     map {
316       my ($alias, $query) = @$_;
317       $self->join_query_parts(' ',
318           $alias,
319           $self->format_keyword('as'),
320           $query,
321       )
322     } @{$with->{queries}}
323   );
324   return $self->join_query_parts(' ',
325     $self->format_keyword(join '_', 'with', ($with->{type}||'')),
326     $q_part,
327   );
328 }
329
330 sub _expand_setop {
331   my ($self, $setop, $args) = @_;
332   +{ "-${setop}" => {
333        %$args,
334        queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
335   } };
336 }
337
338 sub _render_setop {
339   my ($self, $setop, $args) = @_;
340   $self->join_query_parts(
341     ' '.$self->format_keyword(join '_', $setop, ($args->{type}||())).' ',
342     @{$args->{queries}}
343   );
344 }
345
346 1;