blib/lib/UR/Object/Index.pm untested

filter: Statementstmt 0.0% 0 / 318 Branchbran 0.0% 0 / 144 Conditioncond 0.0% 0 / 104 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 602 SCAR 85.9
CC
73
Cov
0%
get_objects_matching
2862.0
_build_data_tree
42.0
_setup_change_subscription
30.0
CRAP 5402.0
1 # Index for cached objects.
2  
3 package UR::Object::Index;
4 our $VERSION = "0.46"; # UR $VERSION;;
5 use base qw(UR::Object);
6  
7 use strict;
8 use warnings;
9 require UR;
10  
11 use List::MoreUtils;
12  
13 # wrapper for one of the ID properties to make it less ugly
14  
15 sub indexed_property_names
16 {
17 my $self = shift;
18 unless (exists $self->{indexed_property_names}) {
19 no warnings;
20 $self->{indexed_property_names} = [ split(/,/,$self->{indexed_property_string}) ];
21 }
22 return @{$self->{indexed_property_names}};
23 }
24  
25 sub indexed_property_numericness {
26 my $self = shift;
27 unless (exists $self->{indexed_property_numericness}) {
28 my $class_meta = $self->indexed_class_name->__meta__;
29 my @is_numeric = map {
30 my @props = $class_meta->_concrete_property_meta_for_class_and_name($_);
31 @props == 1
32 ? $props[0]->is_numeric
33 : 0 # multiple ID properties are treated as a string
34 }
35 $self->indexed_property_names;
36  
37 $self->{indexed_property_numericness} = \@is_numeric;
38 }
39 return @{ $self->{indexed_property_numericness} };
40 }
41  
42  
43 # the only non-id property has an accessor...
44  
45 sub data_tree
46 {
47 if (@_ > 1)
48 {
49 my $old = $_[0]->{data_tree};
50 my $new = $_[1];
51 if ($old ne $new)
52 {
53 $_[0]->{data_tree} = $new;
54 $_[0]->__signal_change__('data_tree', $old, $new);
55 }
56 return $new;
57 }
58 return $_[0]->{data_tree};
59 }
60  
61 # override create to initilize the index
62  
63 sub create {
64 my $class = shift;
65
66 # NOTE: This is called from one location in UR::Context and relies
67 # on all properties including the ID being specifically defined.
68
69 my $self = $UR::Context::current->_construct_object($class, @_);
70 return unless $self;
71 $self->{data_tree} ||= {};
72
73 $self->_build_data_tree;
74 $self->_setup_change_subscription;
75
76 $self->__signal_change__("create");
77 return $self;
78 }
79  
80 # this does a lookup as efficiently as possible
81  
82 sub get_objects_matching
83 {
84 my $self = shift;
85 my @values = @_;
86  
87 # The hash access below generates warnings
88 # where undef is a value. Ignore these.
89 no warnings 'uninitialized';
90  
91 my @hr = ($self->{data_tree});
92 my @is_numeric = $self->indexed_property_numericness;
93  
94 my $iter = List::MoreUtils::each_array(@values, @is_numeric);
95 while(my($value, $is_numeric) = $iter->())
96 {
97 my $value_ref = ref($value);
98 if($value_ref eq "HASH")
99 {
100 # property => { operator => "not like", value => "H~_WGS%", escape "~" }
101 if (my $op = $value->{operator})
102 {
103 $op = lc($op);
104 my $not = 0;
105 if ($op =~ m/^(!|not\s*)(.*)/) {
106 $not = 1;
107 $op = $2;
108 }
109  
110 my $result;
111  
112 if ($op eq '=' and !$not) {
113 @hr = grep { $_ } map { $_->{$value->{'value'}} } @hr;
114 }
115 elsif ($op eq 'like')
116 {
117 my $comparison_value = $value->{value};
118 my $escape = $value->{escape};
119
120 my $regex =
121 UR::BoolExpr::Template::PropertyComparison::Like->
122 comparison_value_and_escape_character_to_regex(
123 $comparison_value,
124 $escape
125 );
126
127 my @thr;
128 if ($not)
129 {
130 # Get the values using the regular or negative match op.
131 foreach my $h (@hr) {
132 foreach my $k (sort keys %$h) {
133 next if $k eq ''; # an earlier undef value got saved as an empty string here
134 if($k !~ /$regex/) {
135 push @thr, $h->{$k};
136 }
137 }
138 }
139 }
140 else
141 {
142 # Standard positive match
143 for my $h (@hr) {
144 for my $k (sort keys %$h) {
145 next if $k eq ''; # an earlier undef value got saved as an empty string here
146 if ($k =~ /$regex/) {
147 push @thr, $h->{$k};
148 }
149 }
150 }
151 }
152 @hr = grep { $_ } @thr;
153 }
154 elsif ($op eq 'in' and !$not)
155 {
156 $value = $value->{value};
157 my $has_null = ( (grep { length($_) == 0 } @$value) ? 1 : 0);
158 if ($has_null) {
159 @hr = grep { $_ } map { @$_{@$value} } @hr;
160 } else {
161 my @value = grep { length($_) > 0 } @$value;
162 @hr = grep { $_ } map { @$_{@value} } @hr;
163 }
164 }
165 elsif ($op eq 'in' and $not)
166 {
167 $value = $value->{value};
168
169 # make a hash if we got an array as a value
170 #die ">@$value<" if ref($value) eq "ARRAY";
171 $value = { map { $_ => 1 } @$value } if ref($value) eq "ARRAY";
172
173 # if there is a single null, the not in clause will be false
174 if ($value->{""}) {
175 @hr = ();
176 }
177 else {
178 # return everything NOT in the hash
179 my @thr;
180 for my $h (@hr) {
181 for my $k (sort keys %$h) {
182 next unless length($k);
183 unless ($value->{$k}) {
184 push @thr, $h->{$k};
185 }
186 }
187 }
188 @hr = grep { $_ } @thr;
189 }
190  
191 } elsif ($op eq 'isa') {
192 my @thr;
193 foreach my $h ( @hr ) {
194 foreach my $k ( keys %$h) {
195 if ($k->isa($value->{value}) xor $not) {
196 push @thr, $h->{$k};
197 }
198 }
199 }
200 @hr = grep { $_ } @thr;
201  
202 } elsif ($op eq 'true' or $op eq 'false') {
203 $not = (( $op eq 'true' && $not) or ($op eq 'false' && !$not));
204 my @thr;
205 foreach my $h ( @hr ) {
206 foreach my $k ( keys %$h ) {
207 if ($k xor $not) {
208 push @thr, $h->{$k};
209 }
210 }
211 }
212 @hr = grep { $_ } @thr;
213  
214 } elsif ($not and ($op eq '=' or !$op)) {
215 my @thr;
216 foreach my $h (@hr) {
217 foreach my $k (sort keys %$h) {
218 # An empty string for $k means the object's value was loaded as NULL
219 # and we want things like 0 != NULL to be true to match the SQL that
220 # gets generated for the same rule
221 my $t = ($k eq '')
222 ||
223 ($is_numeric
224 ? $k != $value->{value}
225 : $k ne $value->{value});
226 if ($t) {
227 push @thr, $h->{$k};
228 }
229 }
230 }
231 @hr = grep { $_ } @thr;
232 } elsif($op eq '>') {
233 my @thr;
234 foreach my $h (@hr) {
235 foreach my $k (keys %$h) {
236 next if $k eq ''; # an earlier undef value got saved as an empty string here
237 my $t = $is_numeric
238 ? $k > $value->{value}
239 : $k gt $value->{value};
240 if ($t xor $not) {
241 push @thr, $h->{$k};
242 }
243 }
244 }
245 @hr = grep { $_ } @thr;
246 } elsif($op eq '<') {
247 my @thr;
248 foreach my $h (@hr) {
249 foreach my $k (keys %$h) {
250 next if $k eq ''; # an earlier undef value got saved as an empty string here
251 my $t = $is_numeric
252 ? $k < $value->{value}
253 : $k lt $value->{value};
254 if ($t xor $not) {
255 push @thr, $h->{$k};
256 }
257 }
258 }
259 @hr = grep { $_ } @thr;
260 } elsif($op eq '>=') {
261 my @thr;
262 foreach my $h (@hr) {
263 foreach my $k (keys %$h) {
264 next if $k eq ''; # an earlier undef value got saved as an empty string here
265 my $t = $is_numeric
266 ? $k >= $value->{value}
267 : $k ge $value->{value};
268 if ($t xor $not) {
269 push @thr, $h->{$k};
270 }
271 }
272 }
273 @hr = grep { $_ } @thr;
274 } elsif($op eq '<=') {
275 my @thr;
276 foreach my $h (@hr) {
277 foreach my $k (keys %$h) {
278 next if $k eq ''; # an earlier undef value got saved as an empty string here
279 my $t = $is_numeric
280 ? $k <= $value->{value}
281 : $k le $value->{value};
282 if ($t xor $not) {
283 push @thr, $h->{$k};
284 }
285 }
286 }
287 @hr = grep { $_ } @thr;
288 } elsif($op eq 'ne') {
289 my @thr;
290 foreach my $h (@hr) {
291 foreach my $k (sort keys %$h) {
292 next if $k eq ''; # an earlier undef value got saved as an empty string here
293 if($k ne $value->{value} xor $not) {
294 push @thr, $h->{$k};
295 }
296 }
297 }
298 @hr = grep { $_ } @thr;
299 } elsif($op eq '<>') {
300 my @thr;
301 foreach my $h (@hr) {
302 foreach my $k (sort keys %$h) {
303 if((length($k) and length($value->{value}) and $k ne $value->{value}) xor $not) {
304 push @thr, $h->{$k};
305 }
306 }
307 }
308 @hr = grep { $_ } @thr;
309 } elsif($op eq 'between') {
310 my @thr;
311 my ($min,$max) = @{ $value->{value} };
312 foreach my $h (@hr) {
313 foreach my $k (sort keys %$h) {
314 next if $k eq '';
315 my $t = $is_numeric
316 ? ( $k >= $min and $k <= $max )
317 : ( $k ge $min and $k le $max );
318 if ($t xor $not) {
319 push @thr, $h->{$k};
320 }
321 }
322 }
323 @hr = grep { $_ } @thr;
324 } else {
325 use Data::Dumper;
326 Carp::confess("Unknown operator in key-value pair used in index lookup for index " . Dumper($value));
327 }
328 }
329 else
330 {
331 Carp::confess("No operator specified in hashref value!" . Dumper($value));
332 }
333 }
334 elsif (not $value_ref)
335 {
336 # property => value
337 @hr = grep { $_ } map { $_->{$value} } @hr;
338 }
339 elsif ($value_ref eq "ARRAY")
340 {
341 # property => [ v1, v2, v3]
342 @hr = grep { $_ } map { @$_{@$value} } @hr;
343 }
344 }
345 return (map { values(%$_) } @hr);
346 }
347  
348  
349 # private methods
350  
351 sub _build_data_tree
352 {
353 my $self = $_[0];
354
355 my @indexed_property_names = $self->indexed_property_names;
356 my $hr_base = $self->{data_tree};
357
358 # _remove_object in bulk.
359 %$hr_base = ();
360 my $indexed_class_name = $self->indexed_class_name;
361
362 if (my @bad_properties =
363 grep { not $indexed_class_name->can($_) }
364 @indexed_property_names
365 ) {
366 Carp::confess(
367 "Attempt to index $indexed_class_name by properties which "
368 . "do not function: @bad_properties"
369 );
370 }
371
372 # _add_object in bulk.
373 for my $object ($UR::Context::current->all_objects_loaded($indexed_class_name)) {
374 my(@values, $hr);
375 if (@indexed_property_names) {
376 @values = map { my $val = $object->$_; defined $val ? $val : undef } @indexed_property_names;
377 @values = (undef) unless(@values);
378 }
379 $hr = $hr_base;
380 for my $value (@values)
381 {
382 no warnings 'uninitialized'; # in case $value is undef
383 $hr->{$value} ||= {};
384 $hr = $hr->{$value};
385 }
386 my $obj_id = $object->id;
387 $hr->{$obj_id} = $object;
388 if (Scalar::Util::isweak($UR::Context::all_objects_loaded->{$indexed_class_name}->{$obj_id})) {
389 Scalar::Util::weaken($hr->{$obj_id});
390 }
391 }
392 }
393  
394 # FIXME maybe objects in an index should always be weakend?
395 sub weaken_reference_for_object {
396 my $self = shift;
397 my $object = shift;
398 my $overrides = shift; # FIXME copied from _remove_object - what's this for?
399  
400 no warnings;
401 my @indexed_property_names = $self->indexed_property_names;
402 my @values =
403 map
404 {
405 ($overrides && exists($overrides->{$_}))
406 ?
407 $overrides->{$_}
408 :
409 $object->$_
410 }
411 @indexed_property_names;
412  
413 my $hr = $self->{data_tree};
414 my $value;
415 for $value (@values)
416 {
417 $hr = $hr->{$value};
418 return unless $hr;
419 }
420 Scalar::Util::weaken($hr->{$object->id});
421 }
422
423
424 sub _setup_change_subscription
425 {
426
427 my $self = shift;
428
429
430 my $indexed_class_name = $self->indexed_class_name;
431 my @indexed_property_names = $self->indexed_property_names;
432
433 if (1) {
434 # This is a new indexing strategy which pays at index creation time instead of use.
435
436 my @properties_to_watch = (@indexed_property_names, qw/create delete load unload/);
437 #print "making index $self->{id}\n";
438 for my $class ($indexed_class_name, @{ $UR::Object::Type::_init_subclasses_loaded{$indexed_class_name} }) {
439 for my $property (@properties_to_watch) {
440 my $index_list = $UR::Object::Index::all_by_class_name_and_property_name{$class}{$property} ||= [];
441 #print " adding to $class\n";
442 push @$index_list, $self;
443 }
444 }
445
446 return 1;
447 }
448
449 # This will be ignored for now.
450 # If the __signal_change__/subscription system is improved, it may be better to go back?
451
452 my %properties_to_watch = map { $_ => 1 } (@indexed_property_names, qw/create delete load unload/);
453
454 $self->{_get_change_subscription} = $indexed_class_name->create_subscription(
455 callback =>
456 sub
457 {
458 my ($changed_object, $changed_property, $old_value, $new_value) = @_;
459
460 #print "got change $changed_property for $indexed_class_name: $changed_object->{id}: @_\n";
461
462 # ensure we don't track changes for subclasses
463 #return() unless ref($changed_object) eq $indexed_class_name;
464
465 # ensure we only add/remove for selected method calls
466 return() unless $properties_to_watch{$_[1]};
467
468 #print "changing @_\n";
469
470 $self->_remove_object(
471 $changed_object,
472 { $changed_property => $old_value }
473 ) if ($changed_property ne 'create'
474 and $changed_property ne 'load'
475 and $changed_property ne '__define__');
476
477 $self->_add_object($changed_object) if ($changed_property ne 'delete' and $changed_property ne 'unload');
478 },
479 note => "index monitor " . $self->id,
480 priority => 0,
481 );
482 }
483  
484 sub _get_change_subscription
485 {
486 # accessor for the change subscription
487 $_[0]->{_get_change_subscription} = $_[1] if (@_ > 1);
488 return $_[0]->{_get_change_subscription};
489 }
490  
491 sub _remove_object($$)
492 {
493 no warnings;
494
495 my ($self, $object, $overrides) = @_;
496 my @indexed_property_names = $self->indexed_property_names;
497 my @values =
498 map
499 {
500 ($overrides && exists($overrides->{$_}))
501 ?
502 $overrides->{$_}
503 :
504 $object->$_
505 }
506 @indexed_property_names;
507
508 my $hr = $self->{data_tree};
509 my $value;
510 for $value (@values)
511 {
512 $hr = $hr->{$value};
513 }
514 delete $hr->{$object->id};
515 }
516  
517 sub _add_object($$)
518 {
519 # We get warnings when undef converts into an empty string.
520 # For efficiency, we turn warnings off in this method.
521 no warnings;
522
523 my ($self, $object) = @_;
524 my @indexed_property_names = $self->indexed_property_names;
525 my @values = map { $object->$_ } @indexed_property_names;
526 my $hr = $self->{data_tree};
527 my $value;
528 for $value (@values)
529 {
530 $hr->{$value} ||= {};
531 $hr = $hr->{$value};
532 }
533 $hr->{$object->id} = $object;
534
535 # This is the exact formula used elsewhere. TODO: refactor, base on class meta
536 if ($UR::Context::light_cache and substr($self->indexed_class_name,0,5) ne 'App::') {
537 Scalar::Util::weaken($hr->{$object->id});
538 }
539 }
540  
541 sub _all_objects_indexed {
542 my $self = shift;
543  
544 my @object_hashes = ( $self->{data_tree} );
545  
546 # Recurse one level deep for each indexed property name
547 # and collect the hashes at that level
548 foreach ( $self->indexed_property_names ) {
549 my @new_object_hashes;
550 while (my $hr = shift @object_hashes) {
551 push @new_object_hashes, values(%$hr);
552 }
553 @object_hashes = @new_object_hashes;
554 }
555  
556 # The final level's values are all the objects
557 return map { values %$_ } @object_hashes;
558 }
559  
560 1;
561  
562 =pod
563  
564 =head1 NAME
565  
566 UR::Object::Index - Indexing system for retrieving objects by non-id properties
567  
568 =head1 DESCRIPTION
569  
570 This class implements an indexing system for objects to retrieve them quickly
571 by properties other than their ID properties. Their existence and use is
572 managed by the Context as needed, and end-users should never need to interact
573 with UR::Object::Index instances.
574  
575 Internally, they are a container for objects of the same class and a set of
576 properties used to look them up. Each time a get() is performed on a new set
577 of non-id properties, a new Index is created to handle the request for
578 objects which may already exist in the object cache,
579  
580 The data_tree inside the Index is a multi-level hash. The levels are in the
581 same order as the properties in the get request. At each level, the hash
582 keys are the values that target property has. For that level and key, all the
583 objects inside have the same value for that property. A get() by three non-id
584 properties will have a 3-level hash.
585  
586 =cut