document group by and having clauses
[dbsrgits/SQL-Abstract.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(
8480fb63 8 expand_expr render_aqt join_query_parts
df5d0507 9 ) ],
10);
1ff9018c 11
df5d0507 12sub cb {
c671eba6 13 my ($self, $method, @args) = @_;
14 return sub {
15 local $self->{sqla} = shift;
16 $self->$method(@args, @_)
17 };
df5d0507 18}
19
ec49a2e1 20sub register {
d37f2f17 21 my ($self, @pairs) = @_;
ec49a2e1 22 my $sqla = $self->sqla;
d37f2f17 23 while (my ($method, $cases) = splice(@pairs, 0, 2)) {
24 my @cases = @$cases;
25 while (my ($name, $case) = splice(@cases, 0, 2)) {
26 $sqla->$method($name, $self->cb($case));
27 }
ec49a2e1 28 }
29 return $self;
30}
31
df5d0507 32sub apply_to {
33 my ($self, $sqla) = @_;
34 $self = $self->new unless ref($self);
ec49a2e1 35 local $self->{sqla} = $sqla;
36 $self->register_extensions($sqla);
37}
38
39sub register_extensions {
40 my ($self, $sqla) = @_;
f1c52c0c 41
ad078c71 42 my @clauses = $sqla->clauses_of('select');
2b0b3d43 43 my @before_setop;
44 CLAUSE: foreach my $idx (0..$#clauses) {
45 if ($clauses[$idx] eq 'order_by') {
46 @before_setop = @clauses[0..$idx-1];
47 splice(@clauses, $idx, 0, qw(setop group_by having));
48 last CLAUSE;
49 }
50 }
f1c52c0c 51
2b0b3d43 52 die "Huh?" unless @before_setop;
4be5ded3 53 $sqla->clauses_of(select => @clauses);
58ebc7fa 54
ad078c71 55 $sqla->clauses_of(update => sub {
ee706e89 56 my ($self, @clauses) = @_;
57 splice(@clauses, 2, 0, 'from');
58 @clauses;
59 });
60
ad078c71 61 $sqla->clauses_of(delete => sub {
ee706e89 62 my ($self, @clauses) = @_;
63 splice(@clauses, 1, 0, 'using');
64 @clauses;
65 });
66
4be5ded3 67 $self->register(
f1c52c0c 68 (map +(
69 "${_}er" => [
70 do {
71 my $x = $_;
72 (map +($_ => "_${x}_${_}"), qw(join from_list alias))
73 }
74 ]
75 ), qw(expand render)),
76 binop_expander => [ as => '_expand_op_as' ],
77 renderer => [ as => '_render_as' ],
78 expander => [ cast => '_expand_cast' ],
4be5ded3 79 clause_expanders => [
f1c52c0c 80 "select.from", '_expand_from_list',
81 'select.group_by'
8480fb63 82 => sub { $_[0]->expand_expr({ -list => $_[2] }, -ident) },
f1c52c0c 83 'select.having'
84 => sub { $_[0]->expand_expr($_[2]) },
4be5ded3 85 'update.from' => '_expand_from_list',
f1c52c0c 86 "update.target", '_expand_update_clause_target',
87 "update.update", '_expand_update_clause_target',
4be5ded3 88 'delete.using' => '_expand_from_list',
89 'insert.rowvalues' => sub {
90 +(from => $_[0]->expand_expr({ -values => $_[2] }));
91 },
92 'insert.select' => sub {
93 +(from => $_[0]->expand_expr({ -select => $_[2] }));
94 },
95 ],
58ebc7fa 96 );
26994fdd 97
2b0b3d43 98 # set ops
ad078c71 99 $sqla->wrap_expander(select => sub {
c671eba6 100 $self->cb('_expand_select', $_[0], \@before_setop);
3f9899e5 101 });
2b0b3d43 102
4be5ded3 103 $self->register(
104 clause_renderer => [
105 'select.setop' => sub { $_[0]->render_aqt($_[2]) }
106 ],
107 expander => [ map +($_ => '_expand_setop'), qw(union intersect except) ],
108 renderer => [ map +($_ => '_render_setop'), qw(union intersect except) ],
e2db8228 109 );
2b0b3d43 110
41086177 111 my $setop_expander = $self->cb('_expand_clause_setop');
f61bfd7b 112
ad078c71 113 $sqla->clause_expanders(
f61bfd7b 114 map +($_ => $setop_expander),
115 map "select.${_}",
116 map +($_, "${_}_all", "${_}_distinct"),
117 qw(union intersect except)
118 );
d175037f 119
4be5ded3 120 foreach my $stmt (qw(select insert update delete)) {
ad078c71 121 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
4be5ded3 122 $self->register(
123 clause_expanders => [
124 "${stmt}.with" => '_expand_with',
125 "${stmt}.with_recursive" => '_expand_with',
126 ],
127 clause_renderer => [ "${stmt}.with" => '_render_with' ],
128 );
a97ecd95 129 }
2f4717ad 130
ad078c71 131 return $sqla;
1ff9018c 132}
133
c671eba6 134sub _expand_select {
093442c8 135 my ($self, $orig, $before_setop, @args) = @_;
136 my $exp = $self->sqla->$orig(@args);
c671eba6 137 return $exp unless my $setop = (my $sel = $exp->{-select})->{setop};
138 if (my @keys = grep $sel->{$_}, @$before_setop) {
139 my %inner; @inner{@keys} = delete @{$sel}{@keys};
140 unshift @{(values(%$setop))[0]{queries}},
141 { -select => \%inner };
142 }
143 return $exp;
144}
145
7741b7ad 146sub _expand_from_list {
147 my ($self, undef, $args) = @_;
148 if (ref($args) eq 'HASH') {
38e67490 149 return $args if $args->{-from_list};
7741b7ad 150 return { -from_list => [ $self->expand_expr($args) ] };
151 }
152 my @list;
86a6ebf4 153 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
7741b7ad 154 while (my $entry = shift @args) {
b99e9a14 155 if (!ref($entry) and $entry =~ /^-(.*)/) {
156 if ($1 eq 'as') {
157 $list[-1] = $self->expand_expr({ -as => [
158 $list[-1], map +(ref($_) eq 'ARRAY' ? @$_ : $_), shift(@args)
159 ]});
160 next;
161 }
7741b7ad 162 $entry = { $entry => shift @args };
163 }
164 my $aqt = $self->expand_expr($entry, -ident);
165 if ($aqt->{-join} and not $aqt->{-join}{from}) {
166 $aqt->{-join}{from} = pop @list;
167 }
168 push @list, $aqt;
169 }
09742461 170 return $list[0] if @list == 1;
7741b7ad 171 return { -from_list => \@list };
172}
173
174sub _expand_join {
175 my ($self, undef, $args) = @_;
176 my %proto = (
177 ref($args) eq 'HASH'
178 ? %$args
d36cb439 179 : (to => @$args)
7741b7ad 180 );
b99e9a14 181 if (my $as = delete $proto{as}) {
ca97398a 182 $proto{to} = $self->expand_expr(
183 { -as => [ { -from_list => $proto{to} }, $as ] }
184 );
b99e9a14 185 }
e0eb8d26 186 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
13c99dad 187 $proto{using} = [
e0eb8d26 188 map [ $self->expand_expr($_, -ident) ],
189 ref($using) eq 'ARRAY' ? @$using: $using
13c99dad 190 ];
e0eb8d26 191 }
ca97398a 192 my %ret = (
193 type => delete $proto{type},
194 to => $self->expand_expr({ -from_list => delete $proto{to} }, -ident)
ca97398a 195 );
196 %ret = (%ret,
197 map +($_ => $self->expand_expr($proto{$_}, -ident)),
198 sort keys %proto
199 );
7741b7ad 200 return +{ -join => \%ret };
201}
202
203sub _render_from_list {
a01911a2 204 my ($self, undef, $list) = @_;
a1f8b6ef 205 return $self->join_query_parts(', ', @$list);
7741b7ad 206}
207
208sub _render_join {
a01911a2 209 my ($self, undef, $args) = @_;
7741b7ad 210
211 my @parts = (
412f9efe 212 $args->{from},
1601bb47 213 { -keyword => join '_', ($args->{type}||()), 'join' },
ca97398a 214 (map +($_->{-ident} || $_->{-as}
215 ? $_
216 : ('(', $self->render_aqt($_, 1), ')')),
09742461 217 map +(@{$_->{-from_list}||[]} == 1 ? $_->{-from_list}[0] : $_),
218 $args->{to}
ca97398a 219 ),
7741b7ad 220 ($args->{on} ? (
1601bb47 221 { -keyword => 'on' },
412f9efe 222 $args->{on},
7741b7ad 223 ) : ()),
224 ($args->{using} ? (
1601bb47 225 { -keyword => 'using' },
13c99dad 226 '(', $args->{using}, ')',
7741b7ad 227 ) : ()),
228 );
0236f122 229 return $self->join_query_parts(' ', @parts);
7741b7ad 230}
231
b99e9a14 232sub _expand_op_as {
233 my ($self, undef, $vv, $k) = @_;
984db0d7 234 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
984db0d7 235 my $ik = $self->expand_expr($k, -ident);
4979c509 236 return +{ -as => [ $ik, $self->expand_expr($vv[0], -ident) ] }
984db0d7 237 if @vv == 1 and ref($vv[0]) eq 'HASH';
238
239 my @as = map $self->expand_expr($_, -ident), @vv;
4979c509 240 return { -as => [ $ik, $self->expand_expr({ -alias => \@as }) ] };
b99e9a14 241}
242
243sub _render_as {
a01911a2 244 my ($self, undef, $args) = @_;
984db0d7 245 my ($thing, $alias) = @$args;
0236f122 246 return $self->join_query_parts(
ac7992be 247 ' ',
984db0d7 248 $thing,
1601bb47 249 { -keyword => 'as' },
984db0d7 250 $alias,
1ba47f38 251 );
252}
253
254sub _render_alias {
984db0d7 255 my ($self, undef, $args) = @_;
1ba47f38 256 my ($as, @cols) = @$args;
257 return (@cols
0236f122 258 ? $self->join_query_parts('',
a1f8b6ef 259 $as,
3f312d2e 260 '(',
261 $self->join_query_parts(
262 ', ',
263 @cols
264 ),
265 ')',
1ba47f38 266 )
267 : $self->render_aqt($as)
b99e9a14 268 );
269}
270
f9f1fdcd 271sub _expand_update_clause_target {
fe8b493f 272 my ($self, undef, $target) = @_;
f9f1fdcd 273 +(target => $self->_expand_from_list(undef, $target));
274}
275
2f4717ad 276sub _expand_cast {
277 my ($self, undef, $thing) = @_;
278 return { -func => [ cast => $thing ] } if ref($thing) eq 'HASH';
279 my ($cast, $to) = @{$thing};
280 +{ -func => [ cast => { -as => [
281 $self->expand_expr($cast),
282 $self->expand_expr($to, -ident),
283 ] } ] };
284}
285
286sub _expand_alias {
287 my ($self, undef, $args) = @_;
288 if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
289 $args = $alias;
290 }
4979c509 291 my @parts = map $self->expand_expr($_, -ident),
292 ref($args) eq 'ARRAY' ? @{$args} : $args;
293 return $parts[0] if @parts == 1;
294 return { -alias => \@parts };
2f4717ad 295}
296
297sub _expand_with {
298 my ($self, $name, $with) = @_;
299 my (undef, $type) = split '_', $name;
300 if (ref($with) eq 'HASH') {
301 return +{
302 %$with,
303 queries => [
304 map +[
305 $self->expand_expr({ -alias => $_->[0] }, -ident),
306 $self->expand_expr($_->[1]),
307 ], @{$with->{queries}}
308 ]
309 }
310 }
311 my @with = @$with;
312 my @exp;
313 while (my ($alias, $query) = splice @with, 0, 2) {
314 push @exp, [
315 $self->expand_expr({ -alias => $alias }, -ident),
316 $self->expand_expr($query)
317 ];
318 }
319 return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
320}
321
322sub _render_with {
323 my ($self, undef, $with) = @_;
324 my $q_part = $self->join_query_parts(', ',
325 map {
326 my ($alias, $query) = @$_;
327 $self->join_query_parts(' ',
328 $alias,
1601bb47 329 { -keyword => 'as' },
2f4717ad 330 $query,
331 )
332 } @{$with->{queries}}
333 );
334 return $self->join_query_parts(' ',
1601bb47 335 { -keyword => join '_', 'with', ($with->{type}||'') },
2f4717ad 336 $q_part,
337 );
338}
339
51046d0e 340sub _expand_setop {
341 my ($self, $setop, $args) = @_;
342 +{ "-${setop}" => {
343 %$args,
344 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
345 } };
346}
347
b5f4a869 348sub _render_setop {
349 my ($self, $setop, $args) = @_;
350 $self->join_query_parts(
1601bb47 351 { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
b5f4a869 352 @{$args->{queries}}
353 );
354}
355
41086177 356sub _expand_clause_setop {
357 my ($self, $setop, $args) = @_;
358 my ($op, $type) = split '_', $setop;
359 +(setop => $self->expand_expr({
360 "-${op}" => {
361 ($type ? (type => $type) : ()),
362 queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
363 }
364 }));
365}
366
1ff9018c 3671;
3001f097 368
583c7957 369__END__
370
3001f097 371=head1 NAME
372
373SQL::Abstract::ExtraClauses - new/experimental additions to L<SQL::Abstract>
374
375=head1 SYNOPSIS
376
377 my $sqla = SQL::Abstract->new;
378 SQL::Abstract::ExtraClauses->apply_to($sqla);
379
6aac9987 380=head1 WARNING
381
382This module is basically a nursery for things that seem like a good idea
383to live in until we figure out if we were right about that.
384
3001f097 385=head1 METHODS
386
387=head2 apply_to
388
389Applies the plugin to an L<SQL::Abstract> object.
390
f1c52c0c 391=head2 register_extensions
392
393Registers the extensions described below
394
3001f097 395=head2 cb
396
397For plugin authors, creates a callback to call a method on the plugin.
398
f1c52c0c 399=head2 register
400
401For plugin authors, registers callbacks more easily.
402
3001f097 403=head2 sqla
404
405Available only during plugin callback executions, contains the currently
406active L<SQL::Abstract> object.
407
583c7957 408=head1 NODE TYPES
409
410=head2 alias
411
412Represents a table alias. Expands name and column names with ident as default.
413
414 # expr
415 { -alias => [ 't', 'x', 'y', 'z' ] }
416
417 # aqt
418 { -alias => [
419 { -ident => [ 't' ] }, { -ident => [ 'x' ] },
420 { -ident => [ 'y' ] }, { -ident => [ 'z' ] },
421 ] }
422
423 # query
424 t(x, y, z)
425 []
426
427=head2 as
428
429Represents an sql AS. LHS is expanded with ident as default, RHS is treated
430as a list of arguments for the alias node.
431
432 # expr
433 { foo => { -as => 'bar' } }
434
435 # aqt
4979c509 436 { -as => [ { -ident => [ 'foo' ] }, { -ident => [ 'bar' ] } ] }
583c7957 437
438 # query
439 foo AS bar
440 []
441
442 # expr
443 { -as => [ { -select => { _ => 'blah' } }, 't', 'blah' ] }
444
445 # aqt
446 { -as => [
447 { -select =>
448 { select => { -op => [ ',', { -ident => [ 'blah' ] } ] } }
449 },
450 { -alias => [ { -ident => [ 't' ] }, { -ident => [ 'blah' ] } ] },
451 ] }
452
453 # query
454 (SELECT blah) AS t(blah)
455 []
456
457=head2 cast
458
459 # expr
460 { -cast => [ { -ident => 'birthday' }, 'date' ] }
461
462 # aqt
463 { -func => [
464 'cast', {
465 -as => [ { -ident => [ 'birthday' ] }, { -ident => [ 'date' ] } ]
466 },
467 ] }
468
469 # query
470 CAST(birthday AS date)
471 []
472
d36cb439 473=head2 join
474
475If given an arrayref, pretends it was given a hashref with the first
476element of the arrayref as the value for 'to' and the remaining pairs copied.
477
478Given a hashref, the 'as' key is if presented expanded to wrap the 'to'.
479
480If present the 'using' key is expanded as a list of idents.
481
482Known keys are: 'from' (the left hand side), 'type' ('left', 'right', or
483nothing), 'to' (the right hand side), 'on' and 'using'.
484
485 # expr
486 { -join => {
487 from => 'lft',
488 on => { 'lft.bloo' => { '>' => 'rgt.blee' } },
489 to => 'rgt',
490 type => 'left',
491 } }
492
493 # aqt
494 { -join => {
495 from => { -ident => [ 'lft' ] },
496 on => { -op => [
497 '>', { -ident => [ 'lft', 'bloo' ] },
498 { -ident => [ 'rgt', 'blee' ] },
499 ] },
500 to => { -ident => [ 'rgt' ] },
501 type => 'left',
502 } }
503
504 # query
505 lft LEFT JOIN rgt ON lft.bloo > rgt.blee
506 []
507
508=head2 from_list
509
510List of components of the FROM clause; -foo type elements indicate a pair
511with the next element; this is easiest if I show you:
512
513 # expr
514 { -from_list => [
515 't1', -as => 'table_one', -join =>
516 [ 't2', 'on', { 'table_one.x' => 't2.x' } ],
517 ] }
518
519 # aqt
09742461 520 { -join => {
4979c509 521 from =>
522 {
523 -as => [ { -ident => [ 't1' ] }, { -ident => [ 'table_one' ] } ]
524 },
09742461 525 on => { -op => [
526 '=', { -ident => [ 'table_one', 'x' ] },
527 { -ident => [ 't2', 'x' ] },
528 ] },
529 to => { -ident => [ 't2' ] },
530 type => undef,
531 } }
d36cb439 532
533 # query
534 t1 AS table_one JOIN t2 ON table_one.x = t2.x
535 []
536
537Or with using:
538
539 # expr
540 { -from_list =>
541 [ 't1', -as => 'table_one', -join => [ 't2', 'using', [ 'x' ] ] ]
542 }
543
544 # aqt
09742461 545 { -join => {
4979c509 546 from =>
547 {
548 -as => [ { -ident => [ 't1' ] }, { -ident => [ 'table_one' ] } ]
549 },
09742461 550 to => { -ident => [ 't2' ] },
551 type => undef,
552 using =>
553 { -op => [ 'or', { -op => [ 'or', { -ident => [ 'x' ] } ] } ] },
554 } }
d36cb439 555
556 # query
557 t1 AS table_one JOIN t2 USING ( x )
558 []
559
560With oddities:
561
562 # expr
563 { -from_list => [
ca97398a 564 'x', -join =>
565 [ [ 'y', -join => [ 'z', 'type', 'left' ] ], 'type', 'left' ],
d36cb439 566 ] }
567
568 # aqt
09742461 569 { -join => {
570 from => { -ident => [ 'x' ] },
571 to => { -join => {
572 from => { -ident => [ 'y' ] },
573 to => { -ident => [ 'z' ] },
d36cb439 574 type => 'left',
09742461 575 } },
576 type => 'left',
577 } }
d36cb439 578
579 # query
580 x LEFT JOIN ( y LEFT JOIN z )
581 []
582
6aac9987 583=head1 STATEMENT EXTENSIONS
584
585=head2 group by clause for select
586
587Expanded as a list with an ident default:
588
589 # expr
590 { -select => { group_by => [ 'foo', 'bar' ] } }
591
592 # aqt
593 { -select => { group_by =>
594 {
595 -op => [ ',', { -ident => [ 'foo' ] }, { -ident => [ 'bar' ] } ]
596 }
597 } }
598
599 # query
600 GROUP BY foo, bar
601 []
602
603=head2 having clause for select
604
605Basic expr, just like where, given having is pretty much post-group-by
606where clause:
607
608 # expr
609 { -select =>
610 { having => { '>' => [ { -count => { -ident => 'foo' } }, 3 ] } }
611 }
612
613 # aqt
614 { -select => { having => { -op => [
615 '>', { -func => [ 'count', { -ident => [ 'foo' ] } ] },
616 { -bind => [ undef, 3 ] },
617 ] } } }
618
619 # query
620 HAVING COUNT(foo) > ?
621 [ 3 ]
622
3001f097 623=cut