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