consolidate other things
[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;
ac3616e8 51 $sqla->clauses_of(select => 'with', @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
ac3616e8 84 $sqla->clause_expanders(
c319683e 85 'update.from' => $self->cb('_expand_from_list'),
adda3bd8 86 'delete.using' => $self->cb('_expand_from_list'),
b40d30dc 87 'insert.rowvalues' => $self->cb(sub {
1107714b 88 +(from => $_[0]->expand_expr({ -values => $_[2] }));
b40d30dc 89 }),
90 'insert.select' => $self->cb(sub {
1107714b 91 +(from => $_[0]->expand_expr({ -select => $_[2] }));
b40d30dc 92 }),
71c1b4d5 93 );
37b399a8 94
f7a20100 95 # set ops
ac3616e8 96 $sqla->wrap_expander(select => sub {
22f5ed9a 97 $self->cb('_expand_select', $_[0], \@before_setop);
95ab9342 98 });
f7a20100 99
5824607d 100 $sqla->clause_renderer(
101 'select.setop' => $self->cb(sub { $_[0]->render_aqt($_[2]); })
102 );
f7a20100 103
4b5f7259 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 }
b42692a6 108
0f4de029 109 my $setop_expander = $self->cb('_expand_clause_setop');
bb36c26d 110
ac3616e8 111 $sqla->clause_expanders(
bb36c26d 112 map +($_ => $setop_expander),
113 map "select.${_}",
114 map +($_, "${_}_all", "${_}_distinct"),
115 qw(union intersect except)
116 );
f7fd09f7 117
6d42f0b9 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
44a6affb 124 foreach my $stmt (qw(insert update delete)) {
ac3616e8 125 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
6d42f0b9 126 $sqla->clause_expander("${stmt}.$_" => $w_exp)
44a6affb 127 for qw(with with_recursive);
6d42f0b9 128 $sqla->clause_renderer("${stmt}.with" => $w_rdr);
44a6affb 129 }
6d42f0b9 130
ac3616e8 131 $sqla->clause_expanders(
c319683e 132 "select.from", $self->cb('_expand_from_list'),
b40d30dc 133 "update.target", $self->cb('_expand_update_clause_target'),
134 "update.update", $self->cb('_expand_update_clause_target'),
135 );
f7a20100 136
ac3616e8 137 return $sqla;
f8392f56 138}
139
22f5ed9a 140sub _expand_select {
b5c13e0a 141 my ($self, $orig, $before_setop, @args) = @_;
142 my $exp = $self->sqla->$orig(@args);
22f5ed9a 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
f79455dc 152sub _expand_from_list {
153 my ($self, undef, $args) = @_;
154 if (ref($args) eq 'HASH') {
09ceda11 155 return $args if $args->{-from_list};
f79455dc 156 return { -from_list => [ $self->expand_expr($args) ] };
157 }
158 my @list;
b9e35873 159 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
f79455dc 160 while (my $entry = shift @args) {
6990b2aa 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 }
f79455dc 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
179sub _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 );
6990b2aa 186 if (my $as = delete $proto{as}) {
01e9b916 187 $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
6990b2aa 188 }
0891ae97 189 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
60757815 190 $proto{using} = [
0891ae97 191 map [ $self->expand_expr($_, -ident) ],
192 ref($using) eq 'ARRAY' ? @$using: $using
60757815 193 ];
0891ae97 194 }
f79455dc 195 my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
196 sort keys %proto;
197 return +{ -join => \%ret };
198}
199
200sub _render_from_list {
6c39a2f7 201 my ($self, undef, $list) = @_;
3e230b71 202 return $self->join_query_parts(', ', @$list);
f79455dc 203}
204
205sub _render_join {
6c39a2f7 206 my ($self, undef, $args) = @_;
f79455dc 207
208 my @parts = (
e48c4b9a 209 $args->{from},
312abf42 210 { -keyword => join '_', ($args->{type}||()), 'join' },
cbe3b5a9 211 (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
f79455dc 212 ($args->{on} ? (
312abf42 213 { -keyword => 'on' },
e48c4b9a 214 $args->{on},
f79455dc 215 ) : ()),
216 ($args->{using} ? (
312abf42 217 { -keyword => 'using' },
60757815 218 '(', $args->{using}, ')',
f79455dc 219 ) : ()),
220 );
59c7f80e 221 return $self->join_query_parts(' ', @parts);
f79455dc 222}
223
6990b2aa 224sub _expand_op_as {
225 my ($self, undef, $vv, $k) = @_;
01e9b916 226 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
01e9b916 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 } ] };
6990b2aa 233}
234
235sub _render_as {
6c39a2f7 236 my ($self, undef, $args) = @_;
01e9b916 237 my ($thing, $alias) = @$args;
59c7f80e 238 return $self->join_query_parts(
8d1295c3 239 ' ',
01e9b916 240 $thing,
312abf42 241 { -keyword => 'as' },
01e9b916 242 $alias,
369e7844 243 );
244}
245
246sub _render_alias {
01e9b916 247 my ($self, undef, $args) = @_;
369e7844 248 my ($as, @cols) = @$args;
249 return (@cols
59c7f80e 250 ? $self->join_query_parts('',
3e230b71 251 $as,
68a92d22 252 '(',
253 $self->join_query_parts(
254 ', ',
255 @cols
256 ),
257 ')',
369e7844 258 )
259 : $self->render_aqt($as)
6990b2aa 260 );
261}
262
af407e9a 263sub _expand_update_clause_target {
1107714b 264 my ($self, undef, $target) = @_;
af407e9a 265 +(target => $self->_expand_from_list(undef, $target));
266}
267
6d42f0b9 268sub _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
278sub _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
290sub _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
315sub _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,
312abf42 322 { -keyword => 'as' },
6d42f0b9 323 $query,
324 )
325 } @{$with->{queries}}
326 );
327 return $self->join_query_parts(' ',
312abf42 328 { -keyword => join '_', 'with', ($with->{type}||'') },
6d42f0b9 329 $q_part,
330 );
331}
332
4b5f7259 333sub _expand_setop {
334 my ($self, $setop, $args) = @_;
335 +{ "-${setop}" => {
336 %$args,
337 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
338 } };
339}
340
acfbc601 341sub _render_setop {
342 my ($self, $setop, $args) = @_;
343 $self->join_query_parts(
312abf42 344 { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
acfbc601 345 @{$args->{queries}}
346 );
347}
348
0f4de029 349sub _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
f8392f56 3601;
99fe0bf3 361
eba4f083 362__END__
363
99fe0bf3 364=head1 NAME
365
366SQL::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
377Applies the plugin to an L<SQL::Abstract> object.
378
379=head2 cb
380
381For plugin authors, creates a callback to call a method on the plugin.
382
383=head2 sqla
384
385Available only during plugin callback executions, contains the currently
386active L<SQL::Abstract> object.
387
eba4f083 388=head1 NODE TYPES
389
390=head2 alias
391
392Represents 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
409Represents an sql AS. LHS is expanded with ident as default, RHS is treated
410as 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
99fe0bf3 458=cut