-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDBICParams.pm
More file actions
342 lines (268 loc) · 9.99 KB
/
DBICParams.pm
File metadata and controls
342 lines (268 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package WebAPI::DBIC::Resource::Role::DBICParams;
=head1 NAME
WebAPI::DBIC::Resource::Role::DBICParams - methods for handling url parameters
=cut
use Moo::Role;
use Carp;
use Scalar::Util qw(blessed);
use Try::Tiny;
use Devel::Dwarn;
requires 'set';
requires 'throwable';
requires 'prefetch';
# TODO the params supported by a resource should be determined by the roles
# consumed by that resource, plus any extra params it wants to declare support for.
# So this should be reworked to enable that.
# we use malformed_request() call from Web::Machine to trigger parameter processing
sub malformed_request {
my $self = shift;
$self->handle_request_params;
return 0;
}
# used to a) define order that params are handled,
# and b) to force calling of a handler even if param is missing
sub get_param_order {
return qw(page rows sort);
}
# call _handle_${basename}_param methods for each parameter
# where basename is the name with any .suffix removed ('me.id' => 'me')
sub handle_request_params {
my $self = shift;
my %queue;
for my $param ($self->param) {
next if $param eq ""; # ignore empty parameters
my @v = $self->param($param);
# XXX we don't handle multiple params which appear more than once
die "Multiple $param parameters are not supported\n" if @v > 1;
# parameters with names containing a '.' are assumed to be search criteria
# this covers both 'me.field=foo' and 'relname.field=bar'
if ($param =~ /^\w+\.\w+/) {
$param =~ s/^me\.(\w+\.\w+)/$1/; # handle deprecated 'me.relname.fieldname' form
$queue{search_criteria}->{$param} = $v[0];
next;
}
die "Explicit search_criteria param not allowed"
if $param eq 'search_criteria';
# for parameters with names like foo[x]=3&foo[y]=4
# we accumulate the value as a hash { x => 3, y => 4 }
if ($param =~ /^(\w+)\[(\w+)\]$/) {
die "$param=$v[0] can't follow $param=$queue{$param} parameter\n"
if $queue{$1} and not ref $queue{$1};
$queue{$1}{$2} = $v[0];
}
else {
die "$param=$v[0] can't follow $param=$queue{$param} parameter\n"
if $queue{$param} and ref $queue{$param};
$param = 'sort' if $param eq 'order'; # XXX back-compat
$queue{$param} = $v[0];
}
}
# call handlers in desired order, then any remaining ones
my %done;
for my $param ($self->get_param_order, keys %queue) {
next if $done{$param}++;
my $value = delete $queue{$param};
my $method = "_handle_${param}_param";
unless ($self->can($method)) {
die "The $param parameter is not supported by the $self resource\n";
}
$self->$method($value, $param);
}
return 0;
}
## no critic (ProhibitUnusedPrivateSubroutines)
sub _handle_rows_param {
my ($self, $value) = @_;
$value = 30 unless defined $value;
$self->set( $self->set->search_rs(undef, { rows => $value }) );
return;
}
sub _handle_page_param {
my ($self, $value) = @_;
$value = 1 unless defined $value;
$self->set( $self->set->search_rs(undef, { page => $value }) );
return;
}
sub _handle_with_param { }
sub _handle_rollback_param { }
sub _handle_search_criteria_param {
my ($self, $value) = @_;
$self->set( $self->set->search_rs($value) );
return;
}
sub _handle_join_param {
my ($self) = shift;
$self->_handle_prefetch_param(@_);
}
sub _handle_prefetch_param {
my ($self, $value) = @_;
# Prefetchs/join in DBIC accepts either:
# prefetch => relname OR
# prefetch => [relname1, relname2] OR
# prefetch => {relname1 => relname_on_relname1} OR
# prefetch => [{relname1 => [{relname_on_relname1 => relname_on_relname_on_relname1}, other_relname_on_relaname1]},relname2] ETC
# Noramalise all prefetches to most complicated form.
# eg &prefetch=foo,bar or &prefetch.json={...}
my $prefetch = $self->_resolve_prefetch($value, $self->set->result_source);
return unless scalar @$prefetch;
# XXX hack?: perhaps use {embedded}{$key} = sub { ... };
# see lib/WebAPI/DBIC/Resource/Role/DBIC.pm
$self->prefetch( $prefetch ); # include self, even if deleted below
$prefetch = [grep { !defined $_->{self}} @$prefetch];
my $join_args;
if ($self->param('fields') || $self->param('join')){
$join_args = {
join => $prefetch,
collapse => 1,
};
} else {
$join_args = {
prefetch => $prefetch,
};
}
Dwarn $join_args if $ENV{WEBAPI_DBIC_DEBUG};
$self->set( $self->set->search_rs(undef, $join_args)) if scalar @$prefetch;
return;
}
sub _resolve_prefetch {
my ($self, $prefetch, $result_class) = @_;
my @errors;
# Here we recursively resolve each of the prefetches to normalise them all to the most complicated
# form that can exist. The results will be a ArrayRef of HashRefs that can be passed to DBIC
# directly.
# This code is largely taken from the _resolve_join subroutine in DBIx::Class
return [] unless defined $prefetch and length $prefetch;
my @return;
if (ref $prefetch eq 'ARRAY') {
push @return, map {
@{$self->_resolve_prefetch($_, $result_class)}
} @$prefetch;
} elsif (ref $prefetch eq 'HASH') {
for my $rel (keys %$prefetch) {
next if $rel eq 'self';
if (my @validate_errors = $self->_validate_relationship($result_class, $rel)) {
push @errors, @validate_errors;
} else {
push @return, {
$rel => $self->_resolve_prefetch($prefetch->{$rel}, $result_class->related_source($rel))
};
}
}
} elsif (ref $prefetch) {
push @errors,
"No idea how to resolve prefetch reftype ".ref $prefetch;
} else {
for my $rel (split ',', $prefetch) {
my @validate_errors = $self->_validate_relationship($result_class, $rel);
if ($rel ne 'self' && scalar @validate_errors) {
push @errors, @validate_errors;
} else {
push @return, {
$rel => [{}],
};
}
}
}
$self->throwable->throw_bad_request(400, errors => \@errors)
if @errors;
return \@return;
}
sub _validate_relationship {
my ($self, $result_class, $rel) = @_;
my @errors;
my $rel_info;
try {
$rel_info = $result_class->relationship_info($rel);
local $SIG{__DIE__}; # avoid strack trace from these dies:
die "no relationship with that name\n"
if not $rel_info;
die "relationship is $rel_info->{attrs}{accessor} but only single, filter and multi are supported\n"
if not $rel_info->{attrs}{accessor} =~ m/^(?:single|filter|multi)$/; # sanity
}
catch {
push @errors, {
$rel => $_,
_meta => {
relationship => $rel_info,
relationships => [ sort $result_class->relationships ]
}, # XXX
};
};
return @errors;
}
sub _handle_fields_param {
my ($self, $value) = @_;
my @columns;
if (ref $value eq 'ARRAY') {
@columns = @$value;
}
else {
@columns = split /\s*,\s*/, $value;
}
for my $clause (@columns) {
# we take care to avoid injection risks
my ($field) = ($clause =~ /^ ([a-z0-9_\.]*) $/x);
$self->throwable->throw_bad_request(400, errors => [{
parameter => "invalid fields clause",
_meta => { fields => $field, }, # XXX
}]) if not defined $field;
}
$self->set( $self->set->search_rs(undef, { columns => \@columns }) )
if @columns;
return;
}
sub _handle_sort_param {
my ($self, $value) = @_;
my @order_spec;
# to support sort[typename]=... we need to be able to make type names
# to relationship names that map to the type and are included in the query
# (there might be more than one relationship on 'me' that leads to
# the same resource type so there's a potential ambiguity)
if (ref $value) {
$self->throwable->throw_bad_request(400, errors => [{
parameter => "per-type sort specifiers are not supported yet",
_meta => { sort => $value, }, # XXX
}]);
}
if (not defined $value) {
$value = (join ",", map { "me.$_" } $self->set->result_source->primary_columns);
}
for my $clause (split /,/, $value) {
# we take care to avoid injection risks
my ($field, $dir);
if ($clause =~ /^ ([a-z0-9_\.]*)\b (?:\s+(asc|desc))? $/xi) {
($field, $dir) = ($1, $2 || 'asc');
}
elsif ($clause =~ /^ (-?) ([a-z0-9_\.]*)$/xi) {
($field, $dir) = ($2, ($1) ? 'desc' : 'asc');
}
unless (defined $field) {
$self->throwable->throw_bad_request(400, errors => [{
parameter => "invalid order clause",
_meta => { order => $clause, }, # XXX
}]);
}
# https://metacpan.org/pod/SQL::Abstract#ORDER-BY-CLAUSES
push @order_spec, { "-$dir" => $field };
}
$self->set( $self->set->search_rs(undef, { order_by => \@order_spec }) )
if @order_spec;
return;
}
sub _handle_distinct_param {
my ($self, $value) = @_;
my @errors;
# these restrictions avoid edge cases we don't want to deal with yet
my $sort = $self->param('sort') || $self->param('order'); # XXX insufficient
push @errors, "distinct param requires sort (or order) param"
unless $sort;
push @errors, "distinct param requires fields param"
unless $self->param('fields');
push @errors, "distinct param requires fields and orders parameters to have same value"
unless $self->param('fields') eq $sort;
my $errors = join(", ", @errors);
die "$errors\n" if $errors; # TODO throw?
$self->set( $self->set->search_rs(undef, { distinct => $value }) );
return;
}
1;