more cleanup using register()
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / ExtraClauses.pm
CommitLineData
1ff9018c 1package SQL::Abstract::ExtraClauses;
2
df5d0507 3use Moo;
4
5has sqla => (
6 is => 'ro', init_arg => undef,
7 handles => [ qw(
1601bb47 8 expand_expr expand_maybe_list_expr render_aqt join_query_parts
df5d0507 9 ) ],
10);
1ff9018c 11
df5d0507 12sub cb {
c671eba6 13 my ($self, $method, @args) = @_;
14 return sub {
15 local $self->{sqla} = shift;
16 $self->$method(@args, @_)
17 };
df5d0507 18}
19
ec49a2e1 20sub register {
d37f2f17 21 my ($self, @pairs) = @_;
ec49a2e1 22 my $sqla = $self->sqla;
d37f2f17 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 }
ec49a2e1 28 }
29 return $self;
30}
31
df5d0507 32sub apply_to {
33 my ($self, $sqla) = @_;
34 $self = $self->new unless ref($self);
ec49a2e1 35 local $self->{sqla} = $sqla;
36 $self->register_extensions($sqla);
37}
38
39sub register_extensions {
40 my ($self, $sqla) = @_;
ad078c71 41 my @clauses = $sqla->clauses_of('select');
2b0b3d43 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;
4be5ded3 51 $sqla->clauses_of(select => @clauses);
ec49a2e1 52 $self->register(
d37f2f17 53 clause_expanders => [
ec49a2e1 54 'select.group_by'
55 => sub { $_[0]->expand_maybe_list_expr($_[2], -ident) },
56 'select.having'
57 => sub { $_[0]->expand_expr($_[2]) },
d37f2f17 58 ],
e67751dd 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' ],
47662caa 70 );
58ebc7fa 71
ad078c71 72 $sqla->clauses_of(update => sub {
ee706e89 73 my ($self, @clauses) = @_;
74 splice(@clauses, 2, 0, 'from');
75 @clauses;
76 });
77
ad078c71 78 $sqla->clauses_of(delete => sub {
ee706e89 79 my ($self, @clauses) = @_;
80 splice(@clauses, 1, 0, 'using');
81 @clauses;
82 });
83
4be5ded3 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 ],
58ebc7fa 95 );
26994fdd 96
2b0b3d43 97 # set ops
ad078c71 98 $sqla->wrap_expander(select => sub {
c671eba6 99 $self->cb('_expand_select', $_[0], \@before_setop);
3f9899e5 100 });
2b0b3d43 101
4be5ded3 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) ],
e2db8228 108 );
2b0b3d43 109
41086177 110 my $setop_expander = $self->cb('_expand_clause_setop');
f61bfd7b 111
ad078c71 112 $sqla->clause_expanders(
f61bfd7b 113 map +($_ => $setop_expander),
114 map "select.${_}",
115 map +($_, "${_}_all", "${_}_distinct"),
116 qw(union intersect except)
117 );
d175037f 118
4be5ded3 119 foreach my $stmt (qw(select insert update delete)) {
ad078c71 120 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
4be5ded3 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 );
a97ecd95 128 }
2f4717ad 129
4be5ded3 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 ]
df5d0507 136 );
2b0b3d43 137
ad078c71 138 return $sqla;
1ff9018c 139}
140
c671eba6 141sub _expand_select {
093442c8 142 my ($self, $orig, $before_setop, @args) = @_;
143 my $exp = $self->sqla->$orig(@args);
c671eba6 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
7741b7ad 153sub _expand_from_list {
154 my ($self, undef, $args) = @_;
155 if (ref($args) eq 'HASH') {
38e67490 156 return $args if $args->{-from_list};
7741b7ad 157 return { -from_list => [ $self->expand_expr($args) ] };
158 }
159 my @list;
86a6ebf4 160 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
7741b7ad 161 while (my $entry = shift @args) {
b99e9a14 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 }
7741b7ad 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 );
b99e9a14 187 if (my $as = delete $proto{as}) {
984db0d7 188 $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
b99e9a14 189 }
e0eb8d26 190 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
13c99dad 191 $proto{using} = [
e0eb8d26 192 map [ $self->expand_expr($_, -ident) ],
193 ref($using) eq 'ARRAY' ? @$using: $using
13c99dad 194 ];
e0eb8d26 195 }
7741b7ad 196 my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
197 sort keys %proto;
198 return +{ -join => \%ret };
199}
200
201sub _render_from_list {
a01911a2 202 my ($self, undef, $list) = @_;
a1f8b6ef 203 return $self->join_query_parts(', ', @$list);
7741b7ad 204}
205
206sub _render_join {
a01911a2 207 my ($self, undef, $args) = @_;
7741b7ad 208
209 my @parts = (
412f9efe 210 $args->{from},
1601bb47 211 { -keyword => join '_', ($args->{type}||()), 'join' },
51ccda04 212 (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
7741b7ad 213 ($args->{on} ? (
1601bb47 214 { -keyword => 'on' },
412f9efe 215 $args->{on},
7741b7ad 216 ) : ()),
217 ($args->{using} ? (
1601bb47 218 { -keyword => 'using' },
13c99dad 219 '(', $args->{using}, ')',
7741b7ad 220 ) : ()),
221 );
0236f122 222 return $self->join_query_parts(' ', @parts);
7741b7ad 223}
224
b99e9a14 225sub _expand_op_as {
226 my ($self, undef, $vv, $k) = @_;
984db0d7 227 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
984db0d7 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 } ] };
b99e9a14 234}
235
236sub _render_as {
a01911a2 237 my ($self, undef, $args) = @_;
984db0d7 238 my ($thing, $alias) = @$args;
0236f122 239 return $self->join_query_parts(
ac7992be 240 ' ',
984db0d7 241 $thing,
1601bb47 242 { -keyword => 'as' },
984db0d7 243 $alias,
1ba47f38 244 );
245}
246
247sub _render_alias {
984db0d7 248 my ($self, undef, $args) = @_;
1ba47f38 249 my ($as, @cols) = @$args;
250 return (@cols
0236f122 251 ? $self->join_query_parts('',
a1f8b6ef 252 $as,
3f312d2e 253 '(',
254 $self->join_query_parts(
255 ', ',
256 @cols
257 ),
258 ')',
1ba47f38 259 )
260 : $self->render_aqt($as)
b99e9a14 261 );
262}
263
f9f1fdcd 264sub _expand_update_clause_target {
fe8b493f 265 my ($self, undef, $target) = @_;
f9f1fdcd 266 +(target => $self->_expand_from_list(undef, $target));
267}
268
2f4717ad 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,
1601bb47 323 { -keyword => 'as' },
2f4717ad 324 $query,
325 )
326 } @{$with->{queries}}
327 );
328 return $self->join_query_parts(' ',
1601bb47 329 { -keyword => join '_', 'with', ($with->{type}||'') },
2f4717ad 330 $q_part,
331 );
332}
333
51046d0e 334sub _expand_setop {
335 my ($self, $setop, $args) = @_;
336 +{ "-${setop}" => {
337 %$args,
338 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
339 } };
340}
341
b5f4a869 342sub _render_setop {
343 my ($self, $setop, $args) = @_;
344 $self->join_query_parts(
1601bb47 345 { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
b5f4a869 346 @{$args->{queries}}
347 );
348}
349
41086177 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
1ff9018c 3611;
3001f097 362
583c7957 363__END__
364
3001f097 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
583c7957 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
3001f097 459=cut