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