simply from list handling
[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 join_query_parts
9   ) ],
10 );
11
12 sub cb {
13   my ($self, $method, @args) = @_;
14   return sub {
15     local $self->{sqla} = shift;
16     $self->$method(@args, @_)
17   };
18 }
19
20 sub register {
21   my ($self, @pairs) = @_;
22   my $sqla = $self->sqla;
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     }
28   }
29   return $self;
30 }
31
32 sub apply_to {
33   my ($self, $sqla) = @_;
34   $self = $self->new unless ref($self);
35   local $self->{sqla} = $sqla;
36   $self->register_extensions($sqla);
37 }
38
39 sub register_extensions {
40   my ($self, $sqla) = @_;
41
42   my @clauses = $sqla->clauses_of('select');
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   }
51
52   die "Huh?" unless @before_setop;
53   $sqla->clauses_of(select => @clauses);
54
55   $sqla->clauses_of(update => sub {
56     my ($self, @clauses) = @_;
57     splice(@clauses, 2, 0, 'from');
58     @clauses;
59   });
60
61   $sqla->clauses_of(delete => sub {
62     my ($self, @clauses) = @_;
63     splice(@clauses, 1, 0, 'using');
64     @clauses;
65   });
66
67   $self->register(
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' ],
79     clause_expanders => [
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]) },
85       'update.from' => '_expand_from_list',
86       "update.target", '_expand_update_clause_target',
87       "update.update", '_expand_update_clause_target',
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     ],
96   );
97
98   # set ops
99   $sqla->wrap_expander(select => sub {
100     $self->cb('_expand_select', $_[0], \@before_setop);
101   });
102
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) ],
109   );
110
111   my $setop_expander = $self->cb('_expand_clause_setop');
112
113   $sqla->clause_expanders(
114     map +($_ => $setop_expander),
115       map "select.${_}",
116         map +($_, "${_}_all", "${_}_distinct"),
117           qw(union intersect except)
118   );
119
120   foreach my $stmt (qw(select insert update delete)) {
121     $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
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     );
129   }
130
131   return $sqla;
132 }
133
134 sub _expand_select {
135   my ($self, $orig, $before_setop, @args) = @_;
136   my $exp = $self->sqla->$orig(@args);
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
146 sub _expand_from_list {
147   my ($self, undef, $args) = @_;
148   if (ref($args) eq 'HASH') {
149     return $args if $args->{-from_list};
150     return { -from_list => [ $self->expand_expr($args) ] };
151   }
152   my @list;
153   my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
154   while (my $entry = shift @args) {
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       }
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 $list[0] if @list == 1;
171   return { -from_list => \@list };
172 }
173
174 sub _expand_join {
175   my ($self, undef, $args) = @_;
176   my %proto = (
177     ref($args) eq 'HASH'
178       ? %$args
179       : (to => @$args)
180   );
181   if (my $as = delete $proto{as}) {
182     $proto{to} = $self->expand_expr(
183                    { -as => [ { -from_list => $proto{to} }, $as ] }
184                  );
185   }
186   if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
187     $proto{using} = [
188       map [ $self->expand_expr($_, -ident) ],
189         ref($using) eq 'ARRAY' ? @$using: $using
190     ];
191   }
192   my %ret = (
193     type => delete $proto{type},
194     to => $self->expand_expr({ -from_list => delete $proto{to} }, -ident)
195   );
196   %ret = (%ret,
197     map +($_ => $self->expand_expr($proto{$_}, -ident)),
198       sort keys %proto
199   );
200   return +{ -join => \%ret };
201 }
202
203 sub _render_from_list {
204   my ($self, undef, $list) = @_;
205   return $self->join_query_parts(', ', @$list);
206 }
207
208 sub _render_join {
209   my ($self, undef, $args) = @_;
210
211   my @parts = (
212     $args->{from},
213     { -keyword => join '_', ($args->{type}||()), 'join' },
214     (map +($_->{-ident} || $_->{-as}
215       ? $_
216       : ('(', $self->render_aqt($_, 1), ')')),
217         map +(@{$_->{-from_list}||[]} == 1 ? $_->{-from_list}[0] : $_),
218           $args->{to}
219     ),
220     ($args->{on} ? (
221       { -keyword => 'on' },
222       $args->{on},
223     ) : ()),
224     ($args->{using} ? (
225       { -keyword => 'using' },
226       '(', $args->{using}, ')',
227     ) : ()),
228   );
229   return $self->join_query_parts(' ', @parts);
230 }
231
232 sub _expand_op_as {
233   my ($self, undef, $vv, $k) = @_;
234   my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
235   my $ik = $self->expand_expr($k, -ident);
236   return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
237     if @vv == 1 and ref($vv[0]) eq 'HASH';
238
239   my @as = map $self->expand_expr($_, -ident), @vv;
240   return { -as => [ $ik, { -alias => \@as } ] };
241 }
242
243 sub _render_as {
244   my ($self, undef, $args) = @_;
245   my ($thing, $alias) = @$args;
246   return $self->join_query_parts(
247     ' ',
248     $thing,
249     { -keyword => 'as' },
250     $alias,
251   );
252 }
253
254 sub _render_alias {
255   my ($self, undef, $args) = @_;
256   my ($as, @cols) = @$args;
257   return (@cols
258     ? $self->join_query_parts('',
259          $as,
260          '(',
261          $self->join_query_parts(
262            ', ',
263            @cols
264          ),
265          ')',
266       )
267     : $self->render_aqt($as)
268   );
269 }
270
271 sub _expand_update_clause_target {
272   my ($self, undef, $target) = @_;
273   +(target => $self->_expand_from_list(undef, $target));
274 }
275
276 sub _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
286 sub _expand_alias {
287   my ($self, undef, $args) = @_;
288   if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
289     $args = $alias;
290   }
291   +{ -alias => [
292       map $self->expand_expr($_, -ident),
293       ref($args) eq 'ARRAY' ? @{$args} : $args
294     ]
295   }
296 }
297
298 sub _expand_with {
299   my ($self, $name, $with) = @_;
300   my (undef, $type) = split '_', $name;
301   if (ref($with) eq 'HASH') {
302     return +{
303       %$with,
304       queries => [
305         map +[
306           $self->expand_expr({ -alias => $_->[0] }, -ident),
307           $self->expand_expr($_->[1]),
308         ], @{$with->{queries}}
309       ]
310     }
311   }
312   my @with = @$with;
313   my @exp;
314   while (my ($alias, $query) = splice @with, 0, 2) {
315     push @exp, [
316       $self->expand_expr({ -alias => $alias }, -ident),
317       $self->expand_expr($query)
318     ];
319   }
320   return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
321 }
322
323 sub _render_with {
324   my ($self, undef, $with) = @_;
325   my $q_part = $self->join_query_parts(', ',
326     map {
327       my ($alias, $query) = @$_;
328       $self->join_query_parts(' ',
329           $alias,
330           { -keyword => 'as' },
331           $query,
332       )
333     } @{$with->{queries}}
334   );
335   return $self->join_query_parts(' ',
336     { -keyword => join '_', 'with', ($with->{type}||'') },
337     $q_part,
338   );
339 }
340
341 sub _expand_setop {
342   my ($self, $setop, $args) = @_;
343   +{ "-${setop}" => {
344        %$args,
345        queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
346   } };
347 }
348
349 sub _render_setop {
350   my ($self, $setop, $args) = @_;
351   $self->join_query_parts(
352     { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
353     @{$args->{queries}}
354   );
355 }
356
357 sub _expand_clause_setop {
358   my ($self, $setop, $args) = @_;
359   my ($op, $type) = split '_', $setop;
360   +(setop => $self->expand_expr({
361     "-${op}" => {
362       ($type ? (type => $type) : ()),
363       queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
364     }
365   }));
366 }
367
368 1;
369
370 __END__
371
372 =head1 NAME
373
374 SQL::Abstract::ExtraClauses - new/experimental additions to L<SQL::Abstract>
375
376 =head1 SYNOPSIS
377
378   my $sqla = SQL::Abstract->new;
379   SQL::Abstract::ExtraClauses->apply_to($sqla);
380
381 =head1 METHODS
382
383 =head2 apply_to
384
385 Applies the plugin to an L<SQL::Abstract> object.
386
387 =head2 register_extensions
388
389 Registers the extensions described below
390
391 =head2 cb
392
393 For plugin authors, creates a callback to call a method on the plugin.
394
395 =head2 register
396
397 For plugin authors, registers callbacks more easily.
398
399 =head2 sqla
400
401 Available only during plugin callback executions, contains the currently
402 active L<SQL::Abstract> object.
403
404 =head1 NODE TYPES
405
406 =head2 alias
407
408 Represents a table alias. Expands name and column names with ident as default.
409
410   # expr
411   { -alias => [ 't', 'x', 'y', 'z' ] }
412
413   # aqt
414   { -alias => [
415       { -ident => [ 't' ] }, { -ident => [ 'x' ] },
416       { -ident => [ 'y' ] }, { -ident => [ 'z' ] },
417   ] }
418
419   # query
420   t(x, y, z)
421   []
422
423 =head2 as
424
425 Represents an sql AS. LHS is expanded with ident as default, RHS is treated
426 as a list of arguments for the alias node.
427
428   # expr
429   { foo => { -as => 'bar' } }
430
431   # aqt
432   { -as =>
433       [
434         { -ident => [ 'foo' ] },
435         { -alias => [ { -ident => [ 'bar' ] } ] },
436       ]
437   }
438
439   # query
440   foo AS bar
441   []
442
443   # expr
444   { -as => [ { -select => { _ => 'blah' } }, 't', 'blah' ] }
445
446   # aqt
447   { -as => [
448       { -select =>
449           { select => { -op => [ ',', { -ident => [ 'blah' ] } ] } }
450       },
451       { -alias => [ { -ident => [ 't' ] }, { -ident => [ 'blah' ] } ] },
452   ] }
453
454   # query
455   (SELECT blah) AS t(blah)
456   []
457
458 =head2 cast
459
460   # expr
461   { -cast => [ { -ident => 'birthday' }, 'date' ] }
462
463   # aqt
464   { -func => [
465       'cast', {
466         -as => [ { -ident => [ 'birthday' ] }, { -ident => [ 'date' ] } ]
467       },
468   ] }
469
470   # query
471   CAST(birthday AS date)
472   []
473
474 =head2 join
475
476 If given an arrayref, pretends it was given a hashref with the first
477 element of the arrayref as the value for 'to' and the remaining pairs copied.
478
479 Given a hashref, the 'as' key is if presented expanded to wrap the 'to'.
480
481 If present the 'using' key is expanded as a list of idents.
482
483 Known keys are: 'from' (the left hand side), 'type' ('left', 'right', or
484 nothing), 'to' (the right hand side), 'on' and 'using'.
485
486   # expr
487   { -join => {
488       from => 'lft',
489       on => { 'lft.bloo' => { '>' => 'rgt.blee' } },
490       to => 'rgt',
491       type => 'left',
492   } }
493
494   # aqt
495   { -join => {
496       from => { -ident => [ 'lft' ] },
497       on => { -op => [
498           '>', { -ident => [ 'lft', 'bloo' ] },
499           { -ident => [ 'rgt', 'blee' ] },
500       ] },
501       to => { -ident => [ 'rgt' ] },
502       type => 'left',
503   } }
504
505   # query
506   lft LEFT JOIN rgt ON lft.bloo > rgt.blee
507   []
508
509 =head2 from_list
510
511 List of components of the FROM clause; -foo type elements indicate a pair
512 with the next element; this is easiest if I show you:
513
514   # expr
515   { -from_list => [
516       't1', -as => 'table_one', -join =>
517       [ 't2', 'on', { 'table_one.x' => 't2.x' } ],
518   ] }
519
520   # aqt
521   { -join => {
522       from => { -as => [
523           { -ident => [ 't1' ] },
524           { -alias => [ { -ident => [ 'table_one' ] } ] },
525       ] },
526       on => { -op => [
527           '=', { -ident => [ 'table_one', 'x' ] },
528           { -ident => [ 't2', 'x' ] },
529       ] },
530       to => { -ident => [ 't2' ] },
531       type => undef,
532   } }
533
534   # query
535   t1 AS table_one JOIN t2 ON table_one.x = t2.x
536   []
537
538 Or with using:
539
540   # expr
541   { -from_list =>
542       [ 't1', -as => 'table_one', -join => [ 't2', 'using', [ 'x' ] ] ]
543   }
544
545   # aqt
546   { -join => {
547       from => { -as => [
548           { -ident => [ 't1' ] },
549           { -alias => [ { -ident => [ 'table_one' ] } ] },
550       ] },
551       to => { -ident => [ 't2' ] },
552       type => undef,
553       using =>
554         { -op => [ 'or', { -op => [ 'or', { -ident => [ 'x' ] } ] } ] },
555   } }
556
557   # query
558   t1 AS table_one JOIN t2 USING ( x )
559   []
560
561 With oddities:
562
563   # expr
564   { -from_list => [
565       'x', -join =>
566       [ [ 'y', -join => [ 'z', 'type', 'left' ] ], 'type', 'left' ],
567   ] }
568
569   # aqt
570   { -join => {
571       from => { -ident => [ 'x' ] },
572       to => { -join => {
573           from => { -ident => [ 'y' ] },
574           to => { -ident => [ 'z' ] },
575           type => 'left',
576       } },
577       type => 'left',
578   } }
579
580   # query
581   x LEFT JOIN ( y LEFT JOIN z )
582   []
583
584 =cut