consolidate other things
[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   my @clauses = $sqla->clauses_of('select');
42   my @before_setop;
43   CLAUSE: foreach my $idx (0..$#clauses) {
44     if ($clauses[$idx] eq 'order_by') {
45       @before_setop = @clauses[0..$idx-1];
46       splice(@clauses, $idx, 0, qw(setop group_by having));
47       last CLAUSE;
48     }
49   }
50   die "Huh?" unless @before_setop;
51   $sqla->clauses_of(select => 'with', @clauses);
52   $self->register(
53     clause_expanders => [
54       'select.group_by'
55         => sub { $_[0]->expand_maybe_list_expr($_[2], -ident) },
56       'select.having'
57         => sub { $_[0]->expand_expr($_[2]) },
58     ],
59     (map +(
60       "${_}er" => [
61         do {
62           my $x = $_;
63           (map +($_ => "_${x}_${_}"), qw(join from_list alias))
64         }
65        ]
66     ), qw(expand render)),
67     binop_expander => [ as => '_expand_op_as' ],
68     renderer => [ as => '_render_as' ],
69     expander => [ cast => '_expand_cast' ],
70   );
71
72   $sqla->clauses_of(update => sub {
73     my ($self, @clauses) = @_;
74     splice(@clauses, 2, 0, 'from');
75     @clauses;
76   });
77
78   $sqla->clauses_of(delete => sub {
79     my ($self, @clauses) = @_;
80     splice(@clauses, 1, 0, 'using');
81     @clauses;
82   });
83
84   $sqla->clause_expanders(
85     'update.from' => $self->cb('_expand_from_list'),
86     'delete.using' => $self->cb('_expand_from_list'),
87     'insert.rowvalues' => $self->cb(sub {
88       +(from => $_[0]->expand_expr({ -values => $_[2] }));
89     }),
90     'insert.select' => $self->cb(sub {
91       +(from => $_[0]->expand_expr({ -select => $_[2] }));
92     }),
93   );
94
95   # set ops
96   $sqla->wrap_expander(select => sub {
97     $self->cb('_expand_select', $_[0], \@before_setop);
98   });
99
100   $sqla->clause_renderer(
101     'select.setop' => $self->cb(sub { $_[0]->render_aqt($_[2]); })
102   );
103
104   foreach my $setop (qw(union intersect except)) {
105     $sqla->expander($setop => $self->cb('_expand_setop'));
106     $sqla->renderer($setop => $self->cb('_render_setop'));
107   }
108
109   my $setop_expander = $self->cb('_expand_clause_setop');
110
111   $sqla->clause_expanders(
112     map +($_ => $setop_expander),
113       map "select.${_}",
114         map +($_, "${_}_all", "${_}_distinct"),
115           qw(union intersect except)
116   );
117
118   my $w_exp = $self->cb('_expand_with');
119   my $w_rdr = $self->cb('_render_with');
120   $sqla->clause_expander('select.with' => $w_exp);
121   $sqla->clause_expander('select.with_recursive' => $w_exp);
122   $sqla->clause_renderer('select.with' => $w_rdr);
123
124   foreach my $stmt (qw(insert update delete)) {
125     $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
126     $sqla->clause_expander("${stmt}.$_" => $w_exp)
127       for qw(with with_recursive);
128     $sqla->clause_renderer("${stmt}.with" => $w_rdr);
129   }
130
131   $sqla->clause_expanders(
132     "select.from", $self->cb('_expand_from_list'),
133     "update.target", $self->cb('_expand_update_clause_target'),
134     "update.update", $self->cb('_expand_update_clause_target'),
135   );
136
137   return $sqla;
138 }
139
140 sub _expand_select {
141   my ($self, $orig, $before_setop, @args) = @_;
142   my $exp = $self->sqla->$orig(@args);
143   return $exp unless my $setop = (my $sel = $exp->{-select})->{setop};
144   if (my @keys = grep $sel->{$_}, @$before_setop) {
145     my %inner; @inner{@keys} = delete @{$sel}{@keys};
146     unshift @{(values(%$setop))[0]{queries}},
147       { -select => \%inner };
148   }
149   return $exp;
150 }
151
152 sub _expand_from_list {
153   my ($self, undef, $args) = @_;
154   if (ref($args) eq 'HASH') {
155     return $args if $args->{-from_list};
156     return { -from_list => [ $self->expand_expr($args) ] };
157   }
158   my @list;
159   my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
160   while (my $entry = shift @args) {
161     if (!ref($entry) and $entry =~ /^-(.*)/) {
162       if ($1 eq 'as') {
163         $list[-1] = $self->expand_expr({ -as => [
164           $list[-1], map +(ref($_) eq 'ARRAY' ? @$_ : $_), shift(@args)
165         ]});
166         next;
167       }
168       $entry = { $entry => shift @args };
169     }
170     my $aqt = $self->expand_expr($entry, -ident);
171     if ($aqt->{-join} and not $aqt->{-join}{from}) {
172       $aqt->{-join}{from} = pop @list;
173     }
174     push @list, $aqt;
175   }
176   return { -from_list => \@list };
177 }
178
179 sub _expand_join {
180   my ($self, undef, $args) = @_;
181   my %proto = (
182     ref($args) eq 'HASH'
183       ? %$args
184       : (to => $args->[0], @{$args}[1..$#$args])
185   );
186   if (my $as = delete $proto{as}) {
187     $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
188   }
189   if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
190     $proto{using} = [
191       map [ $self->expand_expr($_, -ident) ],
192         ref($using) eq 'ARRAY' ? @$using: $using
193     ];
194   }
195   my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
196               sort keys %proto;
197   return +{ -join => \%ret };
198 }
199
200 sub _render_from_list {
201   my ($self, undef, $list) = @_;
202   return $self->join_query_parts(', ', @$list);
203 }
204
205 sub _render_join {
206   my ($self, undef, $args) = @_;
207
208   my @parts = (
209     $args->{from},
210     { -keyword => join '_', ($args->{type}||()), 'join' },
211     (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
212     ($args->{on} ? (
213       { -keyword => 'on' },
214       $args->{on},
215     ) : ()),
216     ($args->{using} ? (
217       { -keyword => 'using' },
218       '(', $args->{using}, ')',
219     ) : ()),
220   );
221   return $self->join_query_parts(' ', @parts);
222 }
223
224 sub _expand_op_as {
225   my ($self, undef, $vv, $k) = @_;
226   my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
227   my $ik = $self->expand_expr($k, -ident);
228   return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
229     if @vv == 1 and ref($vv[0]) eq 'HASH';
230
231   my @as = map $self->expand_expr($_, -ident), @vv;
232   return { -as => [ $ik, { -alias => \@as } ] };
233 }
234
235 sub _render_as {
236   my ($self, undef, $args) = @_;
237   my ($thing, $alias) = @$args;
238   return $self->join_query_parts(
239     ' ',
240     $thing,
241     { -keyword => 'as' },
242     $alias,
243   );
244 }
245
246 sub _render_alias {
247   my ($self, undef, $args) = @_;
248   my ($as, @cols) = @$args;
249   return (@cols
250     ? $self->join_query_parts('',
251          $as,
252          '(',
253          $self->join_query_parts(
254            ', ',
255            @cols
256          ),
257          ')',
258       )
259     : $self->render_aqt($as)
260   );
261 }
262
263 sub _expand_update_clause_target {
264   my ($self, undef, $target) = @_;
265   +(target => $self->_expand_from_list(undef, $target));
266 }
267
268 sub _expand_cast {
269   my ($self, undef, $thing) = @_;
270   return { -func => [ cast => $thing ] } if ref($thing) eq 'HASH';
271   my ($cast, $to) = @{$thing};
272   +{ -func => [ cast => { -as => [
273     $self->expand_expr($cast),
274     $self->expand_expr($to, -ident),
275   ] } ] };
276 }
277
278 sub _expand_alias {
279   my ($self, undef, $args) = @_;
280   if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
281     $args = $alias;
282   }
283   +{ -alias => [
284       map $self->expand_expr($_, -ident),
285       ref($args) eq 'ARRAY' ? @{$args} : $args
286     ]
287   }
288 }
289
290 sub _expand_with {
291   my ($self, $name, $with) = @_;
292   my (undef, $type) = split '_', $name;
293   if (ref($with) eq 'HASH') {
294     return +{
295       %$with,
296       queries => [
297         map +[
298           $self->expand_expr({ -alias => $_->[0] }, -ident),
299           $self->expand_expr($_->[1]),
300         ], @{$with->{queries}}
301       ]
302     }
303   }
304   my @with = @$with;
305   my @exp;
306   while (my ($alias, $query) = splice @with, 0, 2) {
307     push @exp, [
308       $self->expand_expr({ -alias => $alias }, -ident),
309       $self->expand_expr($query)
310     ];
311   }
312   return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
313 }
314
315 sub _render_with {
316   my ($self, undef, $with) = @_;
317   my $q_part = $self->join_query_parts(', ',
318     map {
319       my ($alias, $query) = @$_;
320       $self->join_query_parts(' ',
321           $alias,
322           { -keyword => 'as' },
323           $query,
324       )
325     } @{$with->{queries}}
326   );
327   return $self->join_query_parts(' ',
328     { -keyword => join '_', 'with', ($with->{type}||'') },
329     $q_part,
330   );
331 }
332
333 sub _expand_setop {
334   my ($self, $setop, $args) = @_;
335   +{ "-${setop}" => {
336        %$args,
337        queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
338   } };
339 }
340
341 sub _render_setop {
342   my ($self, $setop, $args) = @_;
343   $self->join_query_parts(
344     { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
345     @{$args->{queries}}
346   );
347 }
348
349 sub _expand_clause_setop {
350   my ($self, $setop, $args) = @_;
351   my ($op, $type) = split '_', $setop;
352   +(setop => $self->expand_expr({
353     "-${op}" => {
354       ($type ? (type => $type) : ()),
355       queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
356     }
357   }));
358 }
359
360 1;
361
362 __END__
363
364 =head1 NAME
365
366 SQL::Abstract::ExtraClauses - new/experimental additions to L<SQL::Abstract>
367
368 =head1 SYNOPSIS
369
370   my $sqla = SQL::Abstract->new;
371   SQL::Abstract::ExtraClauses->apply_to($sqla);
372
373 =head1 METHODS
374
375 =head2 apply_to
376
377 Applies the plugin to an L<SQL::Abstract> object.
378
379 =head2 cb
380
381 For plugin authors, creates a callback to call a method on the plugin.
382
383 =head2 sqla
384
385 Available only during plugin callback executions, contains the currently
386 active L<SQL::Abstract> object.
387
388 =head1 NODE TYPES
389
390 =head2 alias
391
392 Represents a table alias. Expands name and column names with ident as default.
393
394   # expr
395   { -alias => [ 't', 'x', 'y', 'z' ] }
396
397   # aqt
398   { -alias => [
399       { -ident => [ 't' ] }, { -ident => [ 'x' ] },
400       { -ident => [ 'y' ] }, { -ident => [ 'z' ] },
401   ] }
402
403   # query
404   t(x, y, z)
405   []
406
407 =head2 as
408
409 Represents an sql AS. LHS is expanded with ident as default, RHS is treated
410 as a list of arguments for the alias node.
411
412   # expr
413   { foo => { -as => 'bar' } }
414
415   # aqt
416   { -as =>
417       [
418         { -ident => [ 'foo' ] },
419         { -alias => [ { -ident => [ 'bar' ] } ] },
420       ]
421   }
422
423   # query
424   foo AS bar
425   []
426
427   # expr
428   { -as => [ { -select => { _ => 'blah' } }, 't', 'blah' ] }
429
430   # aqt
431   { -as => [
432       { -select =>
433           { select => { -op => [ ',', { -ident => [ 'blah' ] } ] } }
434       },
435       { -alias => [ { -ident => [ 't' ] }, { -ident => [ 'blah' ] } ] },
436   ] }
437
438   # query
439   (SELECT blah) AS t(blah)
440   []
441
442 =head2 cast
443
444   # expr
445   { -cast => [ { -ident => 'birthday' }, 'date' ] }
446
447   # aqt
448   { -func => [
449       'cast', {
450         -as => [ { -ident => [ 'birthday' ] }, { -ident => [ 'date' ] } ]
451       },
452   ] }
453
454   # query
455   CAST(birthday AS date)
456   []
457
458 =cut