initial register code for EC plugin
[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 {
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
df5d0507 30sub apply_to {
31 my ($self, $sqla) = @_;
32 $self = $self->new unless ref($self);
ec49a2e1 33 local $self->{sqla} = $sqla;
34 $self->register_extensions($sqla);
35}
36
37sub register_extensions {
38 my ($self, $sqla) = @_;
ad078c71 39 my @clauses = $sqla->clauses_of('select');
2b0b3d43 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;
ad078c71 49 $sqla->clauses_of(select => 'with', @clauses);
ec49a2e1 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]) },
58ebc7fa 56 );
a6227174 57 foreach my $thing (qw(join from_list)) {
ad078c71 58 $sqla->expander($thing => $self->cb("_expand_${thing}"))
df5d0507 59 ->renderer($thing => $self->cb("_render_${thing}"))
a6227174 60 }
e90782e3 61 $sqla->binop_expander(as => $self->cb('_expand_op_as'));
ad078c71 62 $sqla->renderer(as => $self->cb('_render_as'));
2f4717ad 63 $sqla->expander(alias => $self->cb('_expand_alias'));
ad078c71 64 $sqla->renderer(alias => $self->cb('_render_alias'));
58ebc7fa 65
ad078c71 66 $sqla->clauses_of(update => sub {
ee706e89 67 my ($self, @clauses) = @_;
68 splice(@clauses, 2, 0, 'from');
69 @clauses;
70 });
71
ad078c71 72 $sqla->clauses_of(delete => sub {
ee706e89 73 my ($self, @clauses) = @_;
74 splice(@clauses, 1, 0, 'using');
75 @clauses;
76 });
77
ad078c71 78 $sqla->clause_expanders(
805c64f1 79 'update.from' => $self->cb('_expand_from_list'),
9a20a32d 80 'delete.using' => $self->cb('_expand_from_list'),
df5d0507 81 'insert.rowvalues' => $self->cb(sub {
fe8b493f 82 +(from => $_[0]->expand_expr({ -values => $_[2] }));
df5d0507 83 }),
84 'insert.select' => $self->cb(sub {
fe8b493f 85 +(from => $_[0]->expand_expr({ -select => $_[2] }));
df5d0507 86 }),
58ebc7fa 87 );
26994fdd 88
2b0b3d43 89 # set ops
ad078c71 90 $sqla->wrap_expander(select => sub {
c671eba6 91 $self->cb('_expand_select', $_[0], \@before_setop);
3f9899e5 92 });
2b0b3d43 93
e2db8228 94 $sqla->clause_renderer(
95 'select.setop' => $self->cb(sub { $_[0]->render_aqt($_[2]); })
96 );
2b0b3d43 97
51046d0e 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 }
260e0f29 102
41086177 103 my $setop_expander = $self->cb('_expand_clause_setop');
f61bfd7b 104
ad078c71 105 $sqla->clause_expanders(
f61bfd7b 106 map +($_ => $setop_expander),
107 map "select.${_}",
108 map +($_, "${_}_all", "${_}_distinct"),
109 qw(union intersect except)
110 );
d175037f 111
2f4717ad 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
a97ecd95 118 foreach my $stmt (qw(insert update delete)) {
ad078c71 119 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
2f4717ad 120 $sqla->clause_expander("${stmt}.$_" => $w_exp)
a97ecd95 121 for qw(with with_recursive);
2f4717ad 122 $sqla->clause_renderer("${stmt}.with" => $w_rdr);
a97ecd95 123 }
2f4717ad 124
125 $sqla->expander(cast => $self->cb('_expand_cast'));
df5d0507 126
ad078c71 127 $sqla->clause_expanders(
805c64f1 128 "select.from", $self->cb('_expand_from_list'),
df5d0507 129 "update.target", $self->cb('_expand_update_clause_target'),
130 "update.update", $self->cb('_expand_update_clause_target'),
131 );
2b0b3d43 132
ad078c71 133 return $sqla;
1ff9018c 134}
135
c671eba6 136sub _expand_select {
093442c8 137 my ($self, $orig, $before_setop, @args) = @_;
138 my $exp = $self->sqla->$orig(@args);
c671eba6 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
7741b7ad 148sub _expand_from_list {
149 my ($self, undef, $args) = @_;
150 if (ref($args) eq 'HASH') {
38e67490 151 return $args if $args->{-from_list};
7741b7ad 152 return { -from_list => [ $self->expand_expr($args) ] };
153 }
154 my @list;
86a6ebf4 155 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
7741b7ad 156 while (my $entry = shift @args) {
b99e9a14 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 }
7741b7ad 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
175sub _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 );
b99e9a14 182 if (my $as = delete $proto{as}) {
984db0d7 183 $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
b99e9a14 184 }
e0eb8d26 185 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
13c99dad 186 $proto{using} = [
e0eb8d26 187 map [ $self->expand_expr($_, -ident) ],
188 ref($using) eq 'ARRAY' ? @$using: $using
13c99dad 189 ];
e0eb8d26 190 }
7741b7ad 191 my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
192 sort keys %proto;
193 return +{ -join => \%ret };
194}
195
196sub _render_from_list {
a01911a2 197 my ($self, undef, $list) = @_;
a1f8b6ef 198 return $self->join_query_parts(', ', @$list);
7741b7ad 199}
200
201sub _render_join {
a01911a2 202 my ($self, undef, $args) = @_;
7741b7ad 203
204 my @parts = (
412f9efe 205 $args->{from},
1601bb47 206 { -keyword => join '_', ($args->{type}||()), 'join' },
51ccda04 207 (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
7741b7ad 208 ($args->{on} ? (
1601bb47 209 { -keyword => 'on' },
412f9efe 210 $args->{on},
7741b7ad 211 ) : ()),
212 ($args->{using} ? (
1601bb47 213 { -keyword => 'using' },
13c99dad 214 '(', $args->{using}, ')',
7741b7ad 215 ) : ()),
216 );
0236f122 217 return $self->join_query_parts(' ', @parts);
7741b7ad 218}
219
b99e9a14 220sub _expand_op_as {
221 my ($self, undef, $vv, $k) = @_;
984db0d7 222 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
984db0d7 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 } ] };
b99e9a14 229}
230
231sub _render_as {
a01911a2 232 my ($self, undef, $args) = @_;
984db0d7 233 my ($thing, $alias) = @$args;
0236f122 234 return $self->join_query_parts(
ac7992be 235 ' ',
984db0d7 236 $thing,
1601bb47 237 { -keyword => 'as' },
984db0d7 238 $alias,
1ba47f38 239 );
240}
241
242sub _render_alias {
984db0d7 243 my ($self, undef, $args) = @_;
1ba47f38 244 my ($as, @cols) = @$args;
245 return (@cols
0236f122 246 ? $self->join_query_parts('',
a1f8b6ef 247 $as,
3f312d2e 248 '(',
249 $self->join_query_parts(
250 ', ',
251 @cols
252 ),
253 ')',
1ba47f38 254 )
255 : $self->render_aqt($as)
b99e9a14 256 );
257}
258
f9f1fdcd 259sub _expand_update_clause_target {
fe8b493f 260 my ($self, undef, $target) = @_;
f9f1fdcd 261 +(target => $self->_expand_from_list(undef, $target));
262}
263
2f4717ad 264sub _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
274sub _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
286sub _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
311sub _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,
1601bb47 318 { -keyword => 'as' },
2f4717ad 319 $query,
320 )
321 } @{$with->{queries}}
322 );
323 return $self->join_query_parts(' ',
1601bb47 324 { -keyword => join '_', 'with', ($with->{type}||'') },
2f4717ad 325 $q_part,
326 );
327}
328
51046d0e 329sub _expand_setop {
330 my ($self, $setop, $args) = @_;
331 +{ "-${setop}" => {
332 %$args,
333 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
334 } };
335}
336
b5f4a869 337sub _render_setop {
338 my ($self, $setop, $args) = @_;
339 $self->join_query_parts(
1601bb47 340 { -keyword => ' '.join('_', $setop, ($args->{type}||())).' ' },
b5f4a869 341 @{$args->{queries}}
342 );
343}
344
41086177 345sub _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
1ff9018c 3561;
3001f097 357
583c7957 358__END__
359
3001f097 360=head1 NAME
361
362SQL::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
373Applies the plugin to an L<SQL::Abstract> object.
374
375=head2 cb
376
377For plugin authors, creates a callback to call a method on the plugin.
378
379=head2 sqla
380
381Available only during plugin callback executions, contains the currently
382active L<SQL::Abstract> object.
383
583c7957 384=head1 NODE TYPES
385
386=head2 alias
387
388Represents 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
405Represents an sql AS. LHS is expanded with ident as default, RHS is treated
406as 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
3001f097 454=cut