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