extract more extraclauses stuff to methods
[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(
b99e393b 8 expand_expr expand_maybe_list_expr render_aqt
df5d0507 9 format_keyword join_query_parts
10 ) ],
11);
1ff9018c 12
13BEGIN { *puke = \&SQL::Abstract::puke }
14
df5d0507 15sub cb {
16 my ($self, $method) = @_;
17 return sub { local $self->{sqla} = shift; $self->$method(@_) };
18}
19
20sub apply_to {
21 my ($self, $sqla) = @_;
22 $self = $self->new unless ref($self);
ad078c71 23 my @clauses = $sqla->clauses_of('select');
2b0b3d43 24 my @before_setop;
25 CLAUSE: foreach my $idx (0..$#clauses) {
26 if ($clauses[$idx] eq 'order_by') {
27 @before_setop = @clauses[0..$idx-1];
28 splice(@clauses, $idx, 0, qw(setop group_by having));
29 last CLAUSE;
30 }
31 }
32 die "Huh?" unless @before_setop;
ad078c71 33 $sqla->clauses_of(select => 'with', @clauses);
34 $sqla->clause_expanders(
df5d0507 35 'select.group_by', $self->cb(sub {
b99e393b 36 $_[0]->expand_maybe_list_expr($_[2], -ident)
df5d0507 37 }),
38 'select.having', $self->cb(sub { $_[0]->expand_expr($_[2]) }),
58ebc7fa 39 );
a6227174 40 foreach my $thing (qw(join from_list)) {
ad078c71 41 $sqla->expander($thing => $self->cb("_expand_${thing}"))
df5d0507 42 ->renderer($thing => $self->cb("_render_${thing}"))
a6227174 43 }
ad078c71 44 $sqla->op_expander(as => $self->cb('_expand_op_as'));
45 $sqla->expander(as => $self->cb('_expand_op_as'));
46 $sqla->renderer(as => $self->cb('_render_as'));
2f4717ad 47 $sqla->expander(alias => $self->cb('_expand_alias'));
ad078c71 48 $sqla->renderer(alias => $self->cb('_render_alias'));
58ebc7fa 49
ad078c71 50 $sqla->clauses_of(update => sub {
ee706e89 51 my ($self, @clauses) = @_;
52 splice(@clauses, 2, 0, 'from');
53 @clauses;
54 });
55
ad078c71 56 $sqla->clauses_of(delete => sub {
ee706e89 57 my ($self, @clauses) = @_;
58 splice(@clauses, 1, 0, 'using');
59 @clauses;
60 });
61
ad078c71 62 $sqla->clause_expanders(
df5d0507 63 'update.from' => $self->cb('_expand_select_clause_from'),
64 'delete.using' => $self->cb(sub {
fe8b493f 65 +(using => $_[0]->_expand_from_list(undef, $_[2]));
df5d0507 66 }),
67 'insert.rowvalues' => $self->cb(sub {
fe8b493f 68 +(from => $_[0]->expand_expr({ -values => $_[2] }));
df5d0507 69 }),
70 'insert.select' => $self->cb(sub {
fe8b493f 71 +(from => $_[0]->expand_expr({ -select => $_[2] }));
df5d0507 72 }),
58ebc7fa 73 );
26994fdd 74
2b0b3d43 75 # set ops
ad078c71 76 $sqla->wrap_expander(select => sub {
3f9899e5 77 my $orig = shift;
df5d0507 78 $self->cb(sub {
2b0b3d43 79 my $self = shift;
df5d0507 80 my $exp = $self->sqla->$orig(@_);
2b0b3d43 81 return $exp unless my $setop = (my $sel = $exp->{-select})->{setop};
82 if (my @keys = grep $sel->{$_}, @before_setop) {
83 my %inner; @inner{@keys} = delete @{$sel}{@keys};
84 unshift @{(values(%$setop))[0]{queries}},
85 { -select => \%inner };
86 }
87 return $exp;
df5d0507 88 });
3f9899e5 89 });
df5d0507 90 my $expand_setop = $self->cb(sub {
d175037f 91 my ($self, $setop, $args) = @_;
92 +{ "-${setop}" => {
2b0b3d43 93 %$args,
94 queries => [ map $self->expand_expr($_), @{$args->{queries}} ],
95 } };
df5d0507 96 });
ad078c71 97 $sqla->expanders(map +($_ => $expand_setop), qw(union intersect except));
2b0b3d43 98
ad078c71 99 $sqla->clause_renderer('select.setop' => $self->cb(sub {
fe8b493f 100 my ($self, undef, $setop) = @_;
3f312d2e 101 $self->render_aqt($setop);
df5d0507 102 }));
2b0b3d43 103
ad078c71 104 $sqla->renderer($_ => $self->cb(sub {
260e0f29 105 my ($self, $setop, $args) = @_;
0236f122 106 $self->join_query_parts(
260e0f29 107 ' '.$self->format_keyword(join '_', $setop, ($args->{type}||())).' ',
a1f8b6ef 108 @{$args->{queries}}
260e0f29 109 );
df5d0507 110 })) for qw(union intersect except);
260e0f29 111
df5d0507 112 my $setop_expander = $self->cb(sub {
f61bfd7b 113 my ($self, $setop, $args) = @_;
114 my ($op, $type) = split '_', $setop;
115 +(setop => $self->expand_expr({
116 "-${op}" => {
117 ($type ? (type => $type) : ()),
118 queries => (ref($args) eq 'ARRAY' ? $args : [ $args ])
119 }
120 }));
df5d0507 121 });
f61bfd7b 122
ad078c71 123 $sqla->clause_expanders(
f61bfd7b 124 map +($_ => $setop_expander),
125 map "select.${_}",
126 map +($_, "${_}_all", "${_}_distinct"),
127 qw(union intersect except)
128 );
d175037f 129
2f4717ad 130 my $w_exp = $self->cb('_expand_with');
131 my $w_rdr = $self->cb('_render_with');
132 $sqla->clause_expander('select.with' => $w_exp);
133 $sqla->clause_expander('select.with_recursive' => $w_exp);
134 $sqla->clause_renderer('select.with' => $w_rdr);
135
a97ecd95 136 foreach my $stmt (qw(insert update delete)) {
ad078c71 137 $sqla->clauses_of($stmt => 'with', $sqla->clauses_of($stmt));
2f4717ad 138 $sqla->clause_expander("${stmt}.$_" => $w_exp)
a97ecd95 139 for qw(with with_recursive);
2f4717ad 140 $sqla->clause_renderer("${stmt}.with" => $w_rdr);
a97ecd95 141 }
2f4717ad 142
143 $sqla->expander(cast => $self->cb('_expand_cast'));
df5d0507 144
ad078c71 145 $sqla->clause_expanders(
df5d0507 146 "select.from", $self->cb('_expand_select_clause_from'),
147 "update.target", $self->cb('_expand_update_clause_target'),
148 "update.update", $self->cb('_expand_update_clause_target'),
149 );
2b0b3d43 150
ad078c71 151 return $sqla;
1ff9018c 152}
153
7741b7ad 154sub _expand_select_clause_from {
fe8b493f 155 my ($self, undef, $from) = @_;
7741b7ad 156 +(from => $self->_expand_from_list(undef, $from));
157}
158
159sub _expand_from_list {
160 my ($self, undef, $args) = @_;
161 if (ref($args) eq 'HASH') {
38e67490 162 return $args if $args->{-from_list};
7741b7ad 163 return { -from_list => [ $self->expand_expr($args) ] };
164 }
165 my @list;
86a6ebf4 166 my @args = ref($args) eq 'ARRAY' ? @$args : ($args);
7741b7ad 167 while (my $entry = shift @args) {
b99e9a14 168 if (!ref($entry) and $entry =~ /^-(.*)/) {
169 if ($1 eq 'as') {
170 $list[-1] = $self->expand_expr({ -as => [
171 $list[-1], map +(ref($_) eq 'ARRAY' ? @$_ : $_), shift(@args)
172 ]});
173 next;
174 }
7741b7ad 175 $entry = { $entry => shift @args };
176 }
177 my $aqt = $self->expand_expr($entry, -ident);
178 if ($aqt->{-join} and not $aqt->{-join}{from}) {
179 $aqt->{-join}{from} = pop @list;
180 }
181 push @list, $aqt;
182 }
183 return { -from_list => \@list };
184}
185
186sub _expand_join {
187 my ($self, undef, $args) = @_;
188 my %proto = (
189 ref($args) eq 'HASH'
190 ? %$args
191 : (to => $args->[0], @{$args}[1..$#$args])
192 );
b99e9a14 193 if (my $as = delete $proto{as}) {
984db0d7 194 $proto{to} = $self->expand_expr({ -as => [ $proto{to}, $as ] });
b99e9a14 195 }
e0eb8d26 196 if (defined($proto{using}) and ref(my $using = $proto{using}) ne 'HASH') {
13c99dad 197 $proto{using} = [
e0eb8d26 198 map [ $self->expand_expr($_, -ident) ],
199 ref($using) eq 'ARRAY' ? @$using: $using
13c99dad 200 ];
e0eb8d26 201 }
7741b7ad 202 my %ret = map +($_ => $self->expand_expr($proto{$_}, -ident)),
203 sort keys %proto;
204 return +{ -join => \%ret };
205}
206
207sub _render_from_list {
a01911a2 208 my ($self, undef, $list) = @_;
a1f8b6ef 209 return $self->join_query_parts(', ', @$list);
7741b7ad 210}
211
212sub _render_join {
a01911a2 213 my ($self, undef, $args) = @_;
7741b7ad 214
215 my @parts = (
412f9efe 216 $args->{from},
217 $self->format_keyword(join '_', ($args->{type}||()), 'join'),
51ccda04 218 (map +($_->{-ident} || $_->{-as} ? $_ : ('(', $_, ')')), $args->{to}),
7741b7ad 219 ($args->{on} ? (
412f9efe 220 $self->format_keyword('on') ,
221 $args->{on},
7741b7ad 222 ) : ()),
223 ($args->{using} ? (
412f9efe 224 $self->format_keyword('using'),
13c99dad 225 '(', $args->{using}, ')',
7741b7ad 226 ) : ()),
227 );
0236f122 228 return $self->join_query_parts(' ', @parts);
7741b7ad 229}
230
b99e9a14 231sub _expand_op_as {
232 my ($self, undef, $vv, $k) = @_;
984db0d7 233 my @vv = (ref($vv) eq 'ARRAY' ? @$vv : $vv);
234 $k ||= shift @vv;
235 my $ik = $self->expand_expr($k, -ident);
236 return +{ -as => [ $ik, $self->expand_expr($vv[0], -alias) ] }
237 if @vv == 1 and ref($vv[0]) eq 'HASH';
238
239 my @as = map $self->expand_expr($_, -ident), @vv;
240 return { -as => [ $ik, { -alias => \@as } ] };
b99e9a14 241}
242
243sub _render_as {
a01911a2 244 my ($self, undef, $args) = @_;
984db0d7 245 my ($thing, $alias) = @$args;
0236f122 246 return $self->join_query_parts(
ac7992be 247 ' ',
984db0d7 248 $thing,
ac7992be 249 $self->format_keyword('as'),
984db0d7 250 $alias,
1ba47f38 251 );
252}
253
254sub _render_alias {
984db0d7 255 my ($self, undef, $args) = @_;
1ba47f38 256 my ($as, @cols) = @$args;
257 return (@cols
0236f122 258 ? $self->join_query_parts('',
a1f8b6ef 259 $as,
3f312d2e 260 '(',
261 $self->join_query_parts(
262 ', ',
263 @cols
264 ),
265 ')',
1ba47f38 266 )
267 : $self->render_aqt($as)
b99e9a14 268 );
269}
270
f9f1fdcd 271sub _expand_update_clause_target {
fe8b493f 272 my ($self, undef, $target) = @_;
f9f1fdcd 273 +(target => $self->_expand_from_list(undef, $target));
274}
275
2f4717ad 276sub _expand_cast {
277 my ($self, undef, $thing) = @_;
278 return { -func => [ cast => $thing ] } if ref($thing) eq 'HASH';
279 my ($cast, $to) = @{$thing};
280 +{ -func => [ cast => { -as => [
281 $self->expand_expr($cast),
282 $self->expand_expr($to, -ident),
283 ] } ] };
284}
285
286sub _expand_alias {
287 my ($self, undef, $args) = @_;
288 if (ref($args) eq 'HASH' and my $alias = $args->{-alias}) {
289 $args = $alias;
290 }
291 +{ -alias => [
292 map $self->expand_expr($_, -ident),
293 ref($args) eq 'ARRAY' ? @{$args} : $args
294 ]
295 }
296}
297
298sub _expand_with {
299 my ($self, $name, $with) = @_;
300 my (undef, $type) = split '_', $name;
301 if (ref($with) eq 'HASH') {
302 return +{
303 %$with,
304 queries => [
305 map +[
306 $self->expand_expr({ -alias => $_->[0] }, -ident),
307 $self->expand_expr($_->[1]),
308 ], @{$with->{queries}}
309 ]
310 }
311 }
312 my @with = @$with;
313 my @exp;
314 while (my ($alias, $query) = splice @with, 0, 2) {
315 push @exp, [
316 $self->expand_expr({ -alias => $alias }, -ident),
317 $self->expand_expr($query)
318 ];
319 }
320 return +(with => { ($type ? (type => $type) : ()), queries => \@exp });
321}
322
323sub _render_with {
324 my ($self, undef, $with) = @_;
325 my $q_part = $self->join_query_parts(', ',
326 map {
327 my ($alias, $query) = @$_;
328 $self->join_query_parts(' ',
329 $alias,
330 $self->format_keyword('as'),
331 $query,
332 )
333 } @{$with->{queries}}
334 );
335 return $self->join_query_parts(' ',
336 $self->format_keyword(join '_', 'with', ($with->{type}||'')),
337 $q_part,
338 );
339}
340
1ff9018c 3411;