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