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