cleanup join rendering some
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract / ExtraClauses.pm
CommitLineData
f8392f56 1package SQL::Abstract::ExtraClauses;
2
b40d30dc 3use Moo;
4
5has sqla => (
6 is => 'ro', init_arg => undef,
7 handles => [ qw(
312abf42 8 expand_expr expand_maybe_list_expr render_aqt join_query_parts
b40d30dc 9 ) ],
10);
f8392f56 11
b40d30dc 12sub cb {
22f5ed9a 13 my ($self, $method, @args) = @_;
14 return sub {
15 local $self->{sqla} = shift;
16 $self->$method(@args, @_)
17 };
b40d30dc 18}
19
8346c47f 20sub register {
942c16b1 21 my ($self, @pairs) = @_;
8346c47f 22 my $sqla = $self->sqla;
942c16b1 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 }
8346c47f 28 }
29 return $self;
30}
31
b40d30dc 32sub apply_to {
33 my ($self, $sqla) = @_;
34 $self = $self->new unless ref($self);
8346c47f 35 local $self->{sqla} = $sqla;
36 $self->register_extensions($sqla);
37}
38
39sub register_extensions {
40 my ($self, $sqla) = @_;
ad993fa3 41
ac3616e8 42 my @clauses = $sqla->clauses_of('select');
f7a20100 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 }
ad993fa3 51
f7a20100 52 die "Huh?" unless @before_setop;
d689c054 53 $sqla->clauses_of(select => @clauses);
71c1b4d5 54
ac3616e8 55 $sqla->clauses_of(update => sub {
e6b86bee 56 my ($self, @clauses) = @_;
57 splice(@clauses, 2, 0, 'from');
58 @clauses;
59 });
60
ac3616e8 61 $sqla->clauses_of(delete => sub {
e6b86bee 62 my ($self, @clauses) = @_;
63 splice(@clauses, 1, 0, 'using');
64 @clauses;
65 });
66
d689c054 67 $self->register(
ad993fa3 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' ],
d689c054 79 clause_expanders => [
ad993fa3 80 "select.from", '_expand_from_list',
81 'select.group_by'
82 => sub { $_[0]->expand_maybe_list_expr($_[2], -ident) },
83 'select.having'
84 => sub { $_[0]->expand_expr($_[2]) },
d689c054 85 'update.from' => '_expand_from_list',
ad993fa3 86 "update.target", '_expand_update_clause_target',
87 "update.update", '_expand_update_clause_target',
d689c054 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 ],
71c1b4d5 96 );
37b399a8 97
f7a20100 98 # set ops
ac3616e8 99 $sqla->wrap_expander(select => sub {
22f5ed9a 100 $self->cb('_expand_select', $_[0], \@before_setop);
95ab9342 101 });
f7a20100 102
d689c054 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) ],
5824607d 109 );
f7a20100 110
0f4de029 111 my $setop_expander = $self->cb('_expand_clause_setop');
bb36c26d 112
ac3616e8 113 $sqla->clause_expanders(
bb36c26d 114 map +($_ => $setop_expander),
115 map "select.${_}",
116 map +($_, "${_}_all", "${_}_distinct"),
117 qw(union intersect except)
118 );
f7fd09f7 119
d689c054 120 foreach my $stmt (qw(select insert update delete)) {
ac3616e8 121 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
d689c054 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 );
44a6affb 129 }
6d42f0b9 130
ac3616e8 131 return $sqla;
f8392f56 132}
133
22f5ed9a 134sub _expand_select {
b5c13e0a 135 my ($self, $orig, $before_setop, @args) = @_;
136 my $exp = $self->sqla->$orig(@args);
22f5ed9a 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
f79455dc 146sub _expand_from_list {
147 my ($self, undef, $args) = @_;
148 if (ref($args) eq 'HASH') {
09ceda11 149 return $args if $args->{-from_list};
f79455dc 150 return { -from_list => [ $self->expand_expr($args) ] };
151 }
152 my @list;
b9e35873 153 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
f79455dc 154 while (my $entry = shift @args) {
6990b2aa 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 }
f79455dc 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 }
170 return { -from_list => \@list };
171}
172
173sub _expand_join {
174 my ($self, undef, $args) = @_;
175 my %proto = (
176 ref($args) eq 'HASH'
177 ? %$args
ad133cfd 178 : (to => @$args)
f79455dc 179 );
6990b2aa 180 if (my $as = delete $proto{as}) {
5823ddfe 181 $proto{to} = $self->expand_expr(
182 { -as => [ { -from_list => $proto{to} }, $as ] }
183 );
6990b2aa 184 }
0891ae97 185 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
60757815 186 $proto{using} = [
0891ae97 187 map [ $self->expand_expr($_, -ident) ],
188 ref($using) eq 'ARRAY' ? @$using: $using
60757815 189 ];
0891ae97 190 }
5823ddfe 191 my %ret = (
192 type => delete $proto{type},
193 to => $self->expand_expr({ -from_list => delete $proto{to} }, -ident)
194 ->{-from_list}[0]
195 );
196 %ret = (%ret,
197 map +($_ => $self->expand_expr($proto{$_}, -ident)),
198 sort keys %proto
199 );
f79455dc 200 return +{ -join => \%ret };
201}
202
203sub _render_from_list {
6c39a2f7 204 my ($self, undef, $list) = @_;
3e230b71 205 return $self->join_query_parts(', ', @$list);
f79455dc 206}
207
208sub _render_join {
6c39a2f7 209 my ($self, undef, $args) = @_;
f79455dc 210
211 my @parts = (
e48c4b9a 212 $args->{from},
312abf42 213 { -keyword => join '_', ($args->{type}||()), 'join' },
5823ddfe 214 (map +($_->{-ident} || $_->{-as}
215 ? $_
216 : ('(', $self->render_aqt($_, 1), ')')),
217 $args->{to}
218 ),
f79455dc 219 ($args->{on} ? (
312abf42 220 { -keyword => 'on' },
e48c4b9a 221 $args->{on},
f79455dc 222 ) : ()),
223 ($args->{using} ? (
312abf42 224 { -keyword => 'using' },
60757815 225 '(', $args->{using}, ')',
f79455dc 226 ) : ()),
227 );
59c7f80e 228 return $self->join_query_parts(' ', @parts);
f79455dc 229}
230
6990b2aa 231sub _expand_op_as {
232 my ($self, undef, $vv, $k) = @_;
01e9b916 233 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
01e9b916 234 my $ik = $self->expand_expr($k, -ident);
235 return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
236 if @vv == 1 and ref($vv[0]) eq 'HASH';
237
238 my @as = map $self->expand_expr($_, -ident), @vv;
239 return { -as => [ $ik, { -alias => \@as } ] };
6990b2aa 240}
241
242sub _render_as {
6c39a2f7 243 my ($self, undef, $args) = @_;
01e9b916 244 my ($thing, $alias) = @$args;
59c7f80e 245 return $self->join_query_parts(
8d1295c3 246 ' ',
01e9b916 247 $thing,
312abf42 248 { -keyword => 'as' },
01e9b916 249 $alias,
369e7844 250 );
251}
252
253sub _render_alias {
01e9b916 254 my ($self, undef, $args) = @_;
369e7844 255 my ($as, @cols) = @$args;
256 return (@cols
59c7f80e 257 ? $self->join_query_parts('',
3e230b71 258 $as,
68a92d22 259 '(',
260 $self->join_query_parts(
261 ', ',
262 @cols
263 ),
264 ')',
369e7844 265 )
266 : $self->render_aqt($as)
6990b2aa 267 );
268}
269
af407e9a 270sub _expand_update_clause_target {
1107714b 271 my ($self, undef, $target) = @_;
af407e9a 272 +(target => $self->_expand_from_list(undef, $target));
273}
274
6d42f0b9 275sub _expand_cast {
276 my ($self, undef, $thing) = @_;
277 return { -func => [ cast => $thing ] } if ref($thing) eq 'HASH';
278 my ($cast, $to) = @{$thing};
279 +{ -func => [ cast => { -as => [
280 $self->expand_expr($cast),
281 $self->expand_expr($to, -ident),
282 ] } ] };
283}
284
285sub _expand_alias {
286 my ($self, undef, $args) = @_;
287 if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
288 $args = $alias;
289 }
290 +{ -alias => [
291 map $self->expand_expr($_, -ident),
292 ref($args) eq 'ARRAY' ? @{$args} : $args
293 ]
294 }
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,
312abf42 329 { -keyword => 'as' },
6d42f0b9 330 $query,
331 )
332 } @{$with->{queries}}
333 );
334 return $self->join_query_parts(' ',
312abf42 335 { -keyword => join '_', 'with', ($with->{type}||'') },
6d42f0b9 336 $q_part,
337 );
338}
339
4b5f7259 340sub _expand_setop {
341 my ($self, $setop, $args) = @_;
342 +{ "-${setop}" => {
343 %$args,
344 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
345 } };
346}
347
acfbc601 348sub _render_setop {
349 my ($self, $setop, $args) = @_;
350 $self->join_query_parts(
312abf42 351 { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
acfbc601 352 @{$args->{queries}}
353 );
354}
355
0f4de029 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
f8392f56 3671;
99fe0bf3 368
eba4f083 369__END__
370
99fe0bf3 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
380=head1 METHODS
381
382=head2 apply_to
383
384Applies the plugin to an L<SQL::Abstract> object.
385
ad993fa3 386=head2 register_extensions
387
388Registers the extensions described below
389
99fe0bf3 390=head2 cb
391
392For plugin authors, creates a callback to call a method on the plugin.
393
ad993fa3 394=head2 register
395
396For plugin authors, registers callbacks more easily.
397
99fe0bf3 398=head2 sqla
399
400Available only during plugin callback executions, contains the currently
401active L<SQL::Abstract> object.
402
eba4f083 403=head1 NODE TYPES
404
405=head2 alias
406
407Represents a table alias. Expands name and column names with ident as default.
408
409 # expr
410 { -alias => [ 't', 'x', 'y', 'z' ] }
411
412 # aqt
413 { -alias => [
414 { -ident => [ 't' ] }, { -ident => [ 'x' ] },
415 { -ident => [ 'y' ] }, { -ident => [ 'z' ] },
416 ] }
417
418 # query
419 t(x, y, z)
420 []
421
422=head2 as
423
424Represents an sql AS. LHS is expanded with ident as default, RHS is treated
425as a list of arguments for the alias node.
426
427 # expr
428 { foo => { -as => 'bar' } }
429
430 # aqt
431 { -as =>
432 [
433 { -ident => [ 'foo' ] },
434 { -alias => [ { -ident => [ 'bar' ] } ] },
435 ]
436 }
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
ad133cfd 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
520 { -from_list => [ { -join => {
521 from => { -as => [
522 { -ident => [ 't1' ] },
523 { -alias => [ { -ident => [ 'table_one' ] } ] },
524 ] },
525 on => { -op => [
526 '=', { -ident => [ 'table_one', 'x' ] },
527 { -ident => [ 't2', 'x' ] },
528 ] },
529 to => { -ident => [ 't2' ] },
530 type => undef,
531 } } ] }
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
545 { -from_list => [ { -join => {
546 from => { -as => [
547 { -ident => [ 't1' ] },
548 { -alias => [ { -ident => [ 'table_one' ] } ] },
549 ] },
550 to => { -ident => [ 't2' ] },
551 type => undef,
552 using =>
553 {
554 -op => [ 'or', { -op => [ 'or', { -ident => [ 'x' ] } ] } ]
555 },
556 } } ] }
557
558 # query
559 t1 AS table_one JOIN t2 USING ( x )
560 []
561
562With oddities:
563
564 # expr
565 { -from_list => [
5823ddfe 566 'x', -join =>
567 [ [ 'y', -join => [ 'z', 'type', 'left' ] ], 'type', 'left' ],
ad133cfd 568 ] }
569
570 # aqt
571 { -from_list => [ { -join => {
572 from => { -ident => [ 'x' ] },
573 to => { -join => {
574 from => { -ident => [ 'y' ] },
575 to => { -ident => [ 'z' ] },
576 type => 'left',
577 } },
578 type => 'left',
579 } } ] }
580
581 # query
582 x LEFT JOIN ( y LEFT JOIN z )
583 []
584
99fe0bf3 585=cut