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