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