blib/lib/UR/Object/Type/InternalAPI.pm untested

filter: Statementstmt 0.0% 0 / 983 Branchbran 0.0% 0 / 386 Conditioncond 0.0% 0 / 141 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 90 Podpod 0.0% 0 / 68 totaltotal 0.0% 0 / 1668 SCAR 105.4
CC
194
Cov
0%
_load
342.0
_property_change_callback
182.0
property_for_column
156.0
CRAP 37830.0
1 package UR::Object::Type;
2 use warnings;
3 use strict;
4  
5 require UR;
6 our $VERSION = "0.46"; # UR $VERSION;
7  
8 use Sys::Hostname;
9 use Cwd;
10 use Scalar::Util qw(blessed);
11 use Sub::Name;
12  
13 our %meta_classes;
14 our $bootstrapping = 1;
15 our @partially_defined_classes;
16 our $pwd_at_compile_time = cwd();
17  
18 # each method which caches data on the class for properties stores its hash key here
19 # when properties mutate this is cleared
20 our @cache_keys;
21  
22 sub property_metas {
23 my $self = $_[0];
24 my @a = map { $self->property_meta_for_name($_) } $self->all_property_names();
25 return @a;
26 }
27  
28 # Some accessor methods drawn from properties need to be overridden.
29 # Some times because they need to operate during bootstrapping. Sometimes
30 # because the method needs some special behavior like sorting or filtering.
31 # Sometimes to optimize performance or cache data
32  
33 # This needs to remain overridden to enforce the restriction on callers
34 sub data_source {
35 my $self = shift;
36 my $ds = $self->data_source_id(@_);
37
38 return undef unless $ds;
39 local $@;
40 my $obj = eval { UR::DataSource->get($ds) || $ds->get() };
41  
42 return $obj;
43 }
44  
45 sub ancestry_class_metas {
46 #my $rule_template = UR::BoolExpr::Template->resolve(__PACKAGE__,'id');
47  
48 # Can't use the speed optimization of getting a template here. Using the Context to get
49 # objects here causes endless recursion during bootstrapping
50 map { __PACKAGE__->get($_) } shift->ancestry_class_names;
51 #return map { $UR::Context::current->get_objects_for_class_and_rule(__PACKAGE__, $_) }
52 # map { $rule_template->get_rule_for_values($_) }
53 # shift->ancestry_class_names;
54  
55 }
56  
57 our $PROPERTY_META_FOR_NAME_TEMPLATE;
58 push @cache_keys, '_property_meta_for_name';
59 sub property_meta_for_name {
60 my ($self, $property_name) = @_;
61  
62 return unless $property_name;
63  
64 if (index($property_name,'.') != -1) {
65 my @chain = split(/\./,$property_name);
66 my $last_class_meta = $self;
67 my $last_class_name = $self->id;
68 my @pmeta;
69 for my $full_link (@chain) {
70 my ($link) = ($full_link =~ /^([^\-\?]+)/);
71 my $property_meta = $last_class_meta->property_meta_for_name($link);
72 push @pmeta, $property_meta;
73 last if $link eq $chain[-1];
74 my @joins = UR::Object::Join->resolve_chain($last_class_name, $link);
75 return unless @joins;
76  
77 $last_class_name = $joins[-1]{foreign_class};
78 $last_class_meta = $last_class_name->__meta__;
79 }
80 return unless (@pmeta and $pmeta[-1]);
81 return @pmeta if wantarray;
82 return $pmeta[-1];
83 }
84  
85 my $pos = index($property_name,'-');
86 if ($pos != -1) {
87 $property_name = substr($property_name,0,$pos);
88 }
89  
90 if (exists($self->{'_property_meta_for_name'}) and $self->{'_property_meta_for_name'}->{$property_name}) {
91 return $self->{'_property_meta_for_name'}->{$property_name};
92 }
93 $PROPERTY_META_FOR_NAME_TEMPLATE ||= UR::BoolExpr::Template->resolve('UR::Object::Property', 'class_name', 'property_name');
94  
95 my $property;
96 for my $class ($self->class_name, $self->ancestry_class_names) {
97 my $rule = $PROPERTY_META_FOR_NAME_TEMPLATE->get_rule_for_values($class, $property_name);
98 $property = $UR::Context::current->get_objects_for_class_and_rule('UR::Object::Property', $rule);
99 if ($property) {
100 return $self->{'_property_meta_for_name'}->{$property_name} = $property;
101 }
102 }
103 return;
104 }
105  
106 # A front-end for property_meta_for_name, but
107 # will translate the generic 'id' property into the class' real ID property,
108 # if it's not called 'id'
109 sub _concrete_property_meta_for_class_and_name {
110 my($self,$property_name) = @_;
111  
112 my @property_metas = $self->property_meta_for_name($property_name);
113  
114 for (my $i = 0; $i < @property_metas; $i++) {
115 if ($property_metas[$i]->id eq "UR::Object\tid"
116 and $property_name !~ /\./) #If we're looking at a foreign object's id, can't replace with our own
117 {
118 # This is the generic id property. Remap it to the class' real ID property name
119 my @id_properties = $self->id_property_names;
120 if (@id_properties == 1 and $id_properties[0] eq 'id') {
121 next; # this class doesn't have any other ID properties
122 }
123 #return map { $self->_concrete_property_meta_for_class_and_name($_) } @id_properties;
124 my @remapped = map { $self->_concrete_property_meta_for_class_and_name($_) } @id_properties;
125 splice(@property_metas, $i, 1, @remapped);
126 }
127 }
128 return @property_metas;
129 }
130  
131  
132  
133 sub _flatten_property_name {
134 my ($self, $name) = @_;
135
136 my $flattened_name = '';
137 my @add_keys;
138 my @add_values;
139  
140 my @meta = $self->property_meta_for_name($name);
141 for my $meta (@meta) {
142 my @joins = $meta->_resolve_join_chain();
143 for my $join (@joins) {
144 if ($flattened_name) {
145 $flattened_name .= '.';
146 }
147 $flattened_name .= $join->{source_name_for_foreign};
148 if (my $where = $join->{where}) {
149 $flattened_name .= '-' . $join->sub_group_label;
150 my $join_class = $join->{foreign_class};
151 my $bx2 = UR::BoolExpr->resolve($join_class,@$where);
152 my $bx2_flat = $bx2->flatten(); # recurses through this
153 my ($bx2_flat_template, @values) = $bx2_flat->template_and_values();
154 my @keys = @{ $bx2_flat_template->{_keys} };
155 for my $key (@keys) {
156 next if substr($key,0,1) eq '-';
157 my $full_key = $flattened_name . '?.' . $key;
158 push @add_keys, $full_key;
159 push @add_values, shift @values;
160 }
161 if (@values) {
162 Carp:confess("Unexpected mismatch in count of keys and values!");
163 }
164 }
165 }
166 }
167 return ($flattened_name, \@add_keys, \@add_values);
168 };
169  
170 our $DIRECT_ID_PROPERTY_METAS_TEMPLATE;
171 sub direct_id_property_metas {
172 my $self = _object(shift);
173 $DIRECT_ID_PROPERTY_METAS_TEMPLATE ||= UR::BoolExpr::Template->resolve('UR::Object::Property', 'class_name', 'property_name', 'is_id >=');
174 my $class_name = $self->class_name;
175 my @id_property_objects =
176 map { $UR::Context::current->get_objects_for_class_and_rule('UR::Object::Property', $_) }
177 map { $DIRECT_ID_PROPERTY_METAS_TEMPLATE->get_rule_for_values($class_name, $_, 0) }
178 @{$self->{'id_by'}};
179  
180 my $sort_sub = sub ($$) { return $_[0]->is_id cmp $_[1]->is_id };
181 @id_property_objects = sort $sort_sub @id_property_objects;
182 if (@id_property_objects == 0) {
183 @id_property_objects = $self->property_meta_for_name("id");
184 }
185 return @id_property_objects;
186 }
187  
188 sub parent_class_names {
189 my $self = shift;
190 return @{ $self->{is} };
191 }
192  
193  
194 # If $property_name represents an alias-type property (via => '__self__'),
195 # then return a string with all the aliases removed
196 push @cache_keys, '_resolve_property_aliases';
197 sub resolve_property_aliases {
198 my($self,$property_name) = @_;
199  
200 return unless $property_name;
201 unless ($self->{'_resolve_property_aliases'} && $self->{'_resolve_property_aliases'}->{$property_name}) {
202 $self->{'_resolve_property_aliases'} ||= {};
203  
204 my @property_metas = $self->property_meta_for_name($property_name);
205 my @property_names;
206 if (@property_metas) {
207 @property_names = map { $_->alias_for } @property_metas;
208 } else {
209 # there was a problem resolving the chain of properties
210 # This happens in the case of an object accessor (is => 'Some::Class') without an id_by
211 my @split_names = split(/\./,$property_name);
212 my $name_count = @split_names;
213 my $prop_meta = $self->property_meta_for_name(shift @split_names);
214 return unless $prop_meta;
215 my $foreign_class = $prop_meta->data_type && eval { $prop_meta->data_type->__meta__};
216 return unless $foreign_class;
217 @property_names = ( $prop_meta->alias_for, $foreign_class->resolve_property_aliases(join('.', @split_names)));
218 unless (@property_names >= $name_count) {
219 Carp::croak("Some parts from property '$property_name' of class ".$self->class_name
220 . " didn't resolve");
221 }
222 }
223 $self->{'_resolve_property_aliases'}->{$property_name} = join('.', @property_names);
224 }
225 return $self->{'_resolve_property_aliases'}->{$property_name};
226 }
227  
228  
229 push @cache_keys, '_id_property_names';
230 sub id_property_names {
231 # FIXME Take a look at id_property_names and all_id_property_names.
232 # They look extremely similar, but tests start dying if you replace one
233 # with the other, or remove both and rely on the property's accessor method
234  
235 my $self = _object(shift);
236  
237 unless ($self->{'_id_property_names'}) {
238 my @id_by;
239 unless ($self->{id_by} and @id_by = @{ $self->{id_by} }) {
240 foreach my $parent ( @{ $self->{'is'} } ) {
241 my $parent_class = $parent->class->__meta__;
242 next unless $parent_class;
243 @id_by = $parent_class->id_property_names;
244 last if @id_by;
245 }
246 }
247 $self->{'_id_property_names'} = \@id_by;
248 }
249 return @{$self->{'_id_property_names'}};
250 }
251  
252 push @cache_keys, '_all_id_property_names';
253 sub all_id_property_names {
254 # return shift->id_property_names(@_); This makes URT/t/99_transaction.t fail
255 my $self = shift;
256 unless ($self->{_all_id_property_names}) {
257 my ($tmp,$last) = ('','');
258 $self->{_all_id_property_names} = [
259 grep { $tmp = $last; $last = $_; $tmp ne $_ }
260 sort
261 map { @{ $_->{id_by} } }
262 map { __PACKAGE__->get($_) }
263 ($self->class_name, $self->ancestry_class_names)
264 ];
265 }
266 return @{ $self->{_all_id_property_names} };
267 }
268  
269 sub direct_id_column_names {
270 my $self = _object(shift);
271 my @id_column_names =
272 map { $_->column_name }
273 $self->direct_id_property_metas;
274 return @id_column_names;
275 }
276  
277  
278 sub ancestry_table_names {
279 my $self = _object(shift);
280 my @inherited_table_names =
281 grep { defined($_) }
282 map { $_->table_name }
283 $self->ancestry_class_metas;
284 return @inherited_table_names;
285 }
286  
287 sub all_table_names {
288 my $self = _object(shift);
289 my @table_names =
290 grep { defined($_) }
291 ( $self->table_name, $self->ancestry_table_names );
292 return @table_names;
293 }
294  
295 sub first_table_name {
296 my $self = _object(shift);
297 if ($self->{_first_table_name}) {
298 return $self->{first_table_name};
299 }
300  
301 my @classes = ($self);
302 while(@classes) {
303 my $co = shift @classes;
304 if (my $table_name = $co->table_name) {
305 $self->{first_table_name} = $table_name;
306 return $table_name;
307 }
308 my @parents = map { $_->__meta__ } @{$co->{'is'}};
309 push @classes, @parents;
310 }
311 return;
312 }
313
314  
315 sub ancestry_class_names {
316 my $self = shift;
317
318 if ($self->{_ordered_inherited_class_names}) {
319 return @{ $self->{_ordered_inherited_class_names} };
320 }
321
322 my $ordered_inherited_class_names = $self->{_ordered_inherited_class_names} = [ @{ $self->{is} } ];
323 my @unchecked = @$ordered_inherited_class_names;
324 my %seen = ( $self->{class_name} => 1 );
325 while (my $ancestor_class_name = shift @unchecked) {
326 next if $seen{$ancestor_class_name};
327 $seen{$ancestor_class_name} = 1;
328 my $class_meta = $ancestor_class_name->__meta__;
329 Carp::confess("Can't find meta for $ancestor_class_name!") unless $class_meta;
330 next unless $class_meta->{is};
331 push @$ordered_inherited_class_names, @{ $class_meta->{is} };
332 unshift @unchecked, $_ for reverse @{ $class_meta->{is} };
333 }
334 return @$ordered_inherited_class_names;
335 }
336  
337 push @cache_keys, '_all_property_names';
338 sub all_property_names {
339 my $self = shift;
340
341 if ($self->{_all_property_names}) {
342 return @{ $self->{_all_property_names} };
343 }
344
345 my %seen = ();
346 my $all_property_names = $self->{_all_property_names} = [];
347 for my $class_name ($self->class_name, $self->ancestry_class_names) {
348 next if $class_name eq 'UR::Object';
349 my $class_meta = UR::Object::Type->get($class_name);
350 if (my $has = $class_meta->{has}) {
351 push @$all_property_names,
352 grep {
353 not exists $has->{$_}{id_by}
354 }
355 grep { !exists $seen{$_} }
356 sort keys %$has;
357 foreach (@$all_property_names) {
358 $seen{$_} = 1;
359 }
360 }
361 }
362 return @$all_property_names;
363 }
364  
365  
366 ########################################################################
367 # End of overridden property methods
368 ########################################################################
369  
370 sub _resolve_meta_class_name_for_class_name {
371 my $class = shift;
372 my $class_name = shift;
373 #if ($class_name->isa("UR::Object::Type") or $meta_classes{$class_name} or $class_name =~ '::Type') {
374 if ($meta_classes{$class_name} or $class_name =~ '::Type') {
375 return "UR::Object::Type"
376 }
377 else {
378 return $class_name . "::Type";
379 }
380 }
381  
382 sub _resolve_meta_class_name {
383 my $class = shift;
384 my ($rule,%extra) = UR::BoolExpr->resolve_normalized($class, @_);
385 my %params = $rule->params_list;
386 my $class_name = $params{class_name};
387 return unless $class_name;
388 return $class->_resolve_meta_class_name_for_class_name($class_name);
389 }
390  
391  
392 # This method can go away when we have the is_cached meta-property
393 sub first_sub_classification_method_name {
394 my $self = shift;
395
396 # This may be one of many things which class meta-data should "inherit" from classes which
397 # its instances inherit from. This value is set to the value found on the most concrete class
398 # in the inheritance tree.
399  
400 return $self->{___first_sub_classification_method_name} if exists $self->{___first_sub_classification_method_name};
401
402 $self->{___first_sub_classification_method_name} = $self->sub_classification_method_name;
403 unless ($self->{___first_sub_classification_method_name}) {
404 for my $parent_class ($self->ancestry_class_metas) {
405 last if ($self->{___first_sub_classification_method_name} = $parent_class->sub_classification_method_name);
406 }
407 }
408
409 return $self->{___first_sub_classification_method_name};
410 }
411  
412  
413 # Another thing that is "inherited" from parent class metas
414 sub subclassify_by {
415 my $self = shift;
416  
417 return $self->{'__subclassify_by'} if exists $self->{'__subclassify_by'};
418  
419 $self->{'__subclassify_by'} = $self->__subclassify_by;
420 unless ($self->{'__subclassify_by'}) {
421 for my $parent_class ($self->ancestry_class_metas) {
422 last if ($self->{'__subclassify_by'} = $parent_class->__subclassify_by);
423 }
424 }
425  
426 return $self->{'__subclassify_by'};
427 }
428  
429 sub resolve_composite_id_from_ordered_values {
430 my $self = shift;
431 my $resolver = $self->get_composite_id_resolver;
432 return $resolver->(@_);
433 }
434  
435 sub resolve_ordered_values_from_composite_id {
436 my $self = shift;
437 my $decomposer = $self->get_composite_id_decomposer;
438 return $decomposer->(@_);
439 }
440  
441 sub get_composite_id_decomposer {
442 my $self = shift;
443 my $decomposer;
444 unless ($decomposer = $self->{get_composite_id_decomposer}) {
445 my @id_property_names = $self->id_property_names;
446 if (@id_property_names == 1) {
447 $decomposer = sub { $_[0] };
448 }
449 else {
450 my $separator = $self->_resolve_composite_id_separator;
451 $decomposer = sub {
452 if (ref($_[0])) {
453 # ID is an arrayref, or we'll throw an exception.
454 my $id = $_[0];
455 my $underlying_id_count = scalar(@$id);
456
457 # Handle each underlying ID, turning each into an arrayref divided by property value.
458 my @decomposed_ids;
459 for my $underlying_id (@$id) {
460 push @decomposed_ids, [map { $_ eq '' ? undef : $_ } split($separator,$underlying_id)];
461 }
462
463 # Count the property values.
464 my $underlying_property_count = scalar(@{$decomposed_ids[0]}) if @decomposed_ids;
465 $underlying_property_count ||= 0;
466
467 # Make a list of property values, but each value will be an
468 # arrayref of a set of values instead of a single value.
469 my @property_values;
470 for (my $n = 0; $n < $underlying_property_count; $n++) {
471 $property_values[$n] = [ map { $_->[$n] } @decomposed_ids ];
472 }
473 return @property_values;
474 }
475 else {
476 # Regular scalar ID.
477 no warnings 'uninitialized'; # $_[0] can be undef in some cases...
478 return split($separator,$_[0])
479 }
480 };
481 }
482 Sub::Name::subname('UR::Object::Type::InternalAPI::composite_id_decomposer(closure)',$decomposer);
483 $self->{get_composite_id_decomposer} = $decomposer;
484 }
485 return $decomposer;
486 }
487  
488 sub _resolve_composite_id_separator {
489 # TODO: make the class pull this from its parent at creation time
490 # and only have it dump it if it differs from its parent
491 my $self = shift;
492 my $separator = "\t";
493 for my $class_meta ($self, $self->ancestry_class_metas) {
494 if ($class_meta->composite_id_separator) {
495 $separator = $class_meta->composite_id_separator;
496 last;
497 }
498 }
499 return $separator;
500 }
501  
502 sub get_composite_id_resolver {
503 my $self = shift;
504 my $resolver;
505 unless($resolver = $self->{get_composite_id_resolver}) {
506 my @id_property_names = $self->id_property_names;
507 if (@id_property_names == 1) {
508 $resolver = sub { $_[0] };
509 }
510 else {
511 my $separator = $self->_resolve_composite_id_separator;
512 $resolver = sub {
513 if (ref($_[0]) eq 'ARRAY') {
514 # Determine how big the arrayrefs are.
515 my $underlying_id_count = scalar(@{$_[0]});
516
517 # We presume that, if one value is an arrayref, the others are also,
518 # and are of equal length.
519 my @id;
520 for (my $id_num = 0; $id_num < $underlying_id_count; $id_num++) {
521 # One value per id_property on the class.
522 # Each value is an arrayref in this case.
523 for my $value (@_) {
524 no warnings 'uninitialized'; # Some values in the list might be undef
525 $id[$id_num] .= $separator if $id[$id_num];
526 $id[$id_num] .= $value->[$id_num];
527 }
528 }
529 return \@id;
530 }
531 else {
532 no warnings 'uninitialized'; # Some values in the list might be undef
533 return join($separator,@_)
534 }
535 };
536 }
537 Sub::Name::subname('UR::Object::Type::InternalAPI::composite_id_resolver(closure)',$resolver);
538 $self->{get_composite_id_resolver} = $resolver;
539 }
540 return $resolver;
541 }
542  
543 # UNUSED, BUT BETTER FOR MULTI-COLUMN FK
544 sub composite_id_list_scalar_mix {
545 # This is like the above, but handles the case of arrayrefs
546 # mixing with scalar values in a multi-property id.
547  
548 my ($self, @values) = @_;
549  
550 my @id_sets;
551 for my $value (@values) {
552 if (@id_sets == 0) {
553 if (not ref $value) {
554 @id_sets = ($value);
555 }
556 else {
557 @id_sets = @$value;
558 }
559 }
560 else {
561 if (not ref $value) {
562 for my $id_set (@id_sets) {
563 $id_set .= "\t" . $value;
564 }
565 }
566 else {
567 for my $new_id (@$value) {
568 for my $id_set (@id_sets) {
569 $id_set .= "\t" . $value;
570 }
571 }
572 }
573 }
574 }
575  
576 if (@id_sets == 1) {
577 return $id_sets[0];
578 }
579 else {
580 return \@id_sets;
581 }
582 }
583  
584  
585 sub id_property_sorter {
586 # Return a closure that sort can use to sort objects by all their ID properties
587 # This should be the same order that an SQL query with 'order by ...' would return them
588 my $self = shift;
589 return $self->{'_id_property_sorter'} ||= $self->sorter();
590 }
591  
592 sub sorter {
593 my ($self,@properties) = @_;
594 push @properties, $self->id_property_names;
595 my $key = join("__",@properties);
596 my $sorter = $self->{_sorter}{$key};
597 unless ($sorter) {
598 my @is_numeric;
599 my @is_descending;
600 for my $property (@properties) {
601 if ($property =~ m/^(-|\+)(.*)$/) {
602 push @is_descending, $1 eq '-';
603 $property = $2; # yes, we're manipulating the original list element
604 } else {
605 push @is_descending, 0;
606 }
607  
608 my ($pmeta,@extra) = $self->_concrete_property_meta_for_class_and_name($property);
609 if(@extra) {
610 # maybe a composite property (typically ID), or a chained property (prop.other_prop)
611 $pmeta = $self->property_meta_for_name($property);
612 }
613  
614 if ($pmeta) {
615 my $is_numeric = $pmeta->is_numeric;
616 push @is_numeric, $is_numeric;
617 }
618 elsif ($UR::initialized) {
619 Carp::cluck("Failed to find property meta for $property on $self? Cannot produce a sorter for @properties");
620 push @is_numeric, 0;
621 }
622 else {
623 push @is_numeric, 0;
624 }
625 }
626  
627 no warnings 'uninitialized';
628 $sorter = $self->{_sorter}{$key} ||= sub($$) {
629  
630 for (my $n = 0; $n < @properties; $n++) {
631 my $property = $properties[$n];
632 my @property_string = split('\.',$property);
633  
634 my($first,$second) = $is_descending[$n] ? ($_[1], $_[0]) : ($_[0], $_[1]);
635 for my $current (@property_string) {
636 $first = $first->$current;
637 $second = $second->$current;
638 if (!defined($second)) {
639 return -1;
640 } elsif (!defined($first)) {
641 return 1;
642 }
643 }
644  
645 my $cmp = $is_numeric[$n] ? $first <=> $second : $first cmp $second;
646 return $cmp if $cmp;
647 }
648 return 0;
649 };
650 }
651 Sub::Name::subname("UR::Object::Type::sorter__" . $self->class_name . '__' . $key, $sorter);
652 return $sorter;
653 }
654  
655 sub is_meta {
656 my $self = shift;
657 my $class_name = $self->class_name;
658 return grep { $_ ne 'UR::Object' and $class_name->isa($_) } keys %meta_classes;
659 }
660  
661 sub is_meta_meta {
662 my $self = shift;
663 my $class_name = $self->class_name;
664 return 1 if $meta_classes{$class_name};
665 return;
666 }
667  
668 # Things that can't safely be removed from the object cache.
669 our %uncachable_types = ( ( map { $_ => 0 } keys %UR::Object::Type::meta_classes), # meta-classes are locked in the cache...
670 'UR::Object' => 1, # .. except for UR::Object
671 'UR::Object::Ghost' => 0,
672 'UR::DataSource' => 0,
673 'UR::Context' => 0,
674 'UR::Object::Index' => 0,
675 );
676 sub is_uncachable {
677 my $self = shift;
678  
679 my $class_name = $self->class_name;
680  
681 if (@_) {
682 # setting the is_uncachable value
683 return $uncachable_types{$class_name} = shift;
684 }
685  
686 unless (exists $uncachable_types{$class_name}) {
687 my $is_uncachable = 1;
688 foreach my $type ( keys %uncachable_types ) {
689 if ($class_name->isa($type) and ! $uncachable_types{$type}) {
690 $is_uncachable = 0;
691 last;
692 }
693 }
694 $uncachable_types{$class_name} = $is_uncachable;
695 unless (exists $uncachable_types{$class_name}) {
696 die "Couldn't determine is_uncachable() for $class_name";
697 }
698 }
699 return $uncachable_types{$class_name};
700 }
701  
702  
703 # Mechanisms for generating object IDs when none were specified at
704 # creation time
705  
706 sub autogenerate_new_object_id_uuid {
707 require Data::UUID;
708 my $uuid = Data::UUID->new->create_hex();
709 $uuid =~ s/^0x//;
710 return $uuid;
711 }
712  
713 our $autogenerate_id_base_format = join(" ",Sys::Hostname::hostname(), "%s", time); # the %s gets $$ when needed
714 our $autogenerate_id_iter = 10000;
715 sub autogenerate_new_object_id_urinternal {
716 my($self, $rule) = @_;
717  
718 my @id_property_names = $self->id_property_names;
719 if (@id_property_names > 1) {
720 # we really could, but it seems like if you
721 # asked to do it, it _has_ to be a mistake. If there's a legitimate
722 # reason, this check should be removed
723 $self->error_message("Can't autogenerate ID property values for multiple ID property class " . $self->class_name);
724 return;
725 }
726 return sprintf($autogenerate_id_base_format, $$) . " " . (++$autogenerate_id_iter);
727 }
728  
729 sub autogenerate_new_object_id_datasource {
730 my($self,$rule) = @_;
731  
732 my ($data_source) = $UR::Context::current->resolve_data_sources_for_class_meta_and_rule($self);
733 if ($data_source) {
734 return $data_source->autogenerate_new_object_id_for_class_name_and_rule(
735 $self->class_name,
736 $rule
737 );
738 } else {
739 Carp::croak("Class ".$self->class." has id_generator '-datasource', but the class has no data source to delegate to");
740 }
741 }
742  
743  
744 # Support the autogeneration of unique IDs for objects which require them.
745 sub autogenerate_new_object_id {
746 my $self = _object($_[0]);
747 #my $rule = shift;
748  
749 unless ($self->{'_resolved_id_generator'}) {
750 my $id_generator = $self->id_generator;
751  
752 if (ref($id_generator) eq 'CODE') {
753 $self->{'_resolved_id_generator'} = $id_generator;
754  
755 } elsif ($id_generator and $id_generator =~ m/^\-(\S+)/) {
756 my $id_method = 'autogenerate_new_object_id_' . $1;
757 my $subref = $self->can($id_method);
758 unless ($subref) {
759 Carp::croak("'$id_generator' is an invalid id_generator for class "
760 . $self->class_name
761 . ": Can't locate object method '$id_method' via package ".ref($self));
762 }
763 $self->{'_resolved_id_generator'} = $subref;
764  
765 } else {
766 # delegate to the data source
767 my ($data_source) = $UR::Context::current->resolve_data_sources_for_class_meta_and_rule($self);
768 if ($data_source) {
769 $self->{'_resolved_id_generator'} = sub {
770 $data_source->autogenerate_new_object_id_for_class_name_and_rule(
771 shift->class_name,
772 shift
773 )
774 };
775 }
776 }
777 }
778 goto $self->{'_resolved_id_generator'};
779 }
780  
781 # from ::Object->generate_support_class
782 our %support_class_suffixes = map { $_ => 1 } qw/Set View Viewer Ghost Iterator Value/;
783 sub generate_support_class_for_extension {
784 my $self = shift;
785 my $extension_for_support_class = shift;
786 my $subject_class_name = $self->class_name;
787  
788 unless ($subject_class_name) {
789 Carp::confess("No subject class name for $self?");
790 }
791  
792 return unless defined $extension_for_support_class;
793  
794 if ($subject_class_name eq "UR::Object") {
795 # Carp::cluck("can't generate $extension_for_support_class for UR::Object!\n");
796 # NOTE: we hit this a bunch of times when "getting" meta-data objects during boostrap.
797 return;
798 }
799  
800 unless ($support_class_suffixes{$extension_for_support_class})
801 {
802 #$self->debug_message("Cannot generate a class with extension $extension_for_support_class.");
803 return;
804 }
805  
806 my $subject_class_obj = UR::Object::Type->get(class_name => $subject_class_name);
807 unless ($subject_class_obj) {
808 $self->debug_message("Cannot autogenerate $extension_for_support_class because $subject_class_name does not exist.");
809 return;
810 }
811  
812 my $new_class_name = $subject_class_name . "::" . $extension_for_support_class;
813 my $class_obj;
814 if ($class_obj = UR::Object::Type->is_loaded($new_class_name)) {
815 # getting the subject class autogenerated the support class automatically
816 # shortcut out
817 return $class_obj;
818 }
819  
820 no strict 'refs';
821 my @subject_parent_class_names = @{ $subject_class_name . "::ISA" };
822 my @parent_class_names =
823 grep { UR::Object::Type->get(class_name => $_) }
824 map { $_ . "::" . $extension_for_support_class }
825 grep { $_->isa("UR::Object") }
826 grep { $_ !~ /^UR::/ or $extension_for_support_class eq "Ghost" }
827 @subject_parent_class_names;
828 use strict 'refs';
829  
830 unless (@parent_class_names) {
831 if (UR::Object::Type->get(class_name => ("UR::Object::" . $extension_for_support_class))) {
832 @parent_class_names = "UR::Object::" . $extension_for_support_class;
833 }
834 }
835  
836 unless (@parent_class_names) {
837 #print Carp::longmess();
838 #$self->error_message("Cannot autogenerate $extension_for_support_class for $subject_class_name because parent classes (@subject_parent_class_names) do not have classes with that extension.");
839 return;
840 }
841
842 my @id_property_names = $subject_class_obj->id_property_names;
843 my %id_property_names = map { $_ => 1 } @id_property_names;
844
845 if ($extension_for_support_class eq 'Ghost') {
846 my $subject_class_metaobj = UR::Object::Type->get($self->meta_class_name); # Class object for the subject_class
847 my %class_params = map { $_ => $subject_class_obj->$_ }
848 grep { my $p = $subject_class_metaobj->property_meta_for_name($_)
849 || Carp::croak("Can't no metadata for property '$_' of class ".$self->meta_class_name);
850 ! $p->is_delegated and ! $p->is_calculated }
851 $subject_class_obj->__meta__->all_property_names;
852 delete $class_params{generated};
853 delete $class_params{meta_class_name};
854 delete $class_params{subclassify_by};
855 delete $class_params{sub_classification_meta_class_name};
856 delete $class_params{id_generator};
857 delete $class_params{id};
858 delete $class_params{is};
859 delete $class_params{roles};
860  
861 my $attributes_have = UR::Util::deep_copy($subject_class_obj->{attributes_have});
862 my $class_props = UR::Util::deep_copy($subject_class_obj->{has});
863 for (values %$class_props) {
864 delete $_->{class_name};
865 delete $_->{property_name};
866 }
867
868 %class_params = (
869 %class_params,
870 class_name => $new_class_name,
871 is => \@parent_class_names,
872 is_abstract => 0,
873 has => [%$class_props],
874 attributes_have => $attributes_have,
875 id_properties => \@id_property_names,
876 );
877 $class_obj = UR::Object::Type->define(%class_params);
878 }
879 else {
880 $class_obj = UR::Object::Type->define(
881 class_name => $subject_class_name . "::" . $extension_for_support_class,
882 is => \@parent_class_names,
883 );
884 }
885 return $class_obj;
886 }
887  
888 sub has_table {
889 my $self = shift;
890 if ($bootstrapping) {
891 return 0;
892 }
893 return 1 if $self->table_name;
894 # FIXME - shouldn't this call inheritance() instead of parent_classes()?
895 my @parent_classes = $self->parent_classes;
896 for my $class_name (@parent_classes) {
897 next if $class_name eq "UR::Object";
898 my $class_obj = UR::Object::Type->get(class_name => $class_name);
899 if ($class_obj->has_direct_table) {
900 return 1;
901 }
902 }
903 return;
904 }
905  
906 sub has_direct_table {
907 my $self = shift;
908 return 1 if $self->table_name;
909  
910 if ($self->data_source_id and $self->data_source_id->isa('UR::DataSource::Default')) {
911 my $load_function_name = join('::', $self->class_name, '__load__');
912 return 1 if exists &$load_function_name;
913 }
914 return;
915 }
916  
917 sub most_specific_subclass_with_table {
918 my $self = shift;
919  
920 return $self->class_name if $self->table_name;
921  
922 foreach my $class_name ( $self->class_name->inheritance ) {
923 my $class_obj = UR::Object::Type->get(class_name => $class_name);
924 return $class_name if ($class_obj and $class_obj->has_direct_table);
925 }
926 return;
927 }
928  
929 sub most_general_subclass_with_table {
930 my $self = shift;
931  
932 my @subclass_list = reverse ( $self->class_name, $self->class_name->inheritance );
933 foreach my $class_name ( $self->inheritance ) {
934 my $class_obj = UR::Object::Type->get(class_name => $class_name);
935 return $class_name if ($class_obj && $class_obj->has_direct_table);
936 }
937 return;
938 }
939  
940
941  
942 sub _load {
943 my $class = shift;
944 my $rule = shift;
945  
946 $rule = $rule->normalize;
947 my $params = $rule->legacy_params_hash;
948  
949 # While core entity classes are actually loaded,
950 # support classes dynamically generate for them as needed.
951 # Examples are Acme::Employee::View::emp_id, and Acme::Equipment::Ghost
952  
953 # Try to parse the class name.
954 my $class_name = $params->{class_name};
955  
956 # See if the class autogenerates from another class.
957 # i.e.: Acme::Foo::Bar might be generated by Acme::Foo
958 unless ($class_name) {
959 my $namespace = $params->{namespace};
960 if (my $data_source = $params->{data_source_id}) {
961 $namespace = $data_source->get_namespace;
962 }
963 if ($namespace) {
964 # FIXME This chunk seems to be getting called each time there's a new table/class
965 #Carp::cluck("Getting all classes for namespace $namespace from the filesystem...");
966 my @classes = $namespace->get_material_classes;
967 return $class->is_loaded($params);
968 }
969 Carp::confess("Non-class_name used to find a class object: "
970 . join(', ', map { "$_ => " . (defined $params->{$_} ? "'" . $params->{$_} . "'" : 'undef') } keys %$params));
971 }
972  
973 # Besides the common case of asking for a class by its name, the next most
974 # common thing is asking for multiple classes by their names. Rather than doing the
975 # hard work of doing it "right" right here, just recursively call myself with each
976 # item in that list
977 if (ref $class_name eq 'ARRAY') {
978 # FIXME is there a more efficient way to add/remove class_name from the rule?
979 my $rule_without_class_name = $rule->remove_filter('class_name');
980 $rule_without_class_name = $rule_without_class_name->remove_filter('id'); # id is a synonym for class_name
981 my @objs = map { $class->_load($rule_without_class_name->add_filter(class_name => $_)) } @$class_name;
982 return $class->context_return(@objs);
983 }
984
985 # If the class is loaded, we're done.
986 # This is an un-documented unique constraint right now.
987 my $class_obj = $class->is_loaded(class_name => $class_name);
988 return $class_obj if $class_obj;
989  
990 # Handle deleted classes.
991 # This is written in non-oo notation for bootstrapping.
992 no warnings;
993 if (
994 $class_name ne "UR::Object::Type::Ghost"
995 and
996 UR::Object::Type::Ghost->can("class")
997 and
998 $UR::Context::current->get_objects_for_class_and_rule("UR::Object::Type::Ghost",$rule,0)
999 ) {
1000 return;
1001 }
1002  
1003 # Check the filesystem. The file may create its metadata object.
1004 my $exception = do {
1005 local $@;
1006 eval "use $class_name";
1007 $@;
1008 };
1009 unless ($exception) {
1010 # If the above module was loaded, and is an UR::Object,
1011 # this will find the object. If not, it will return nothing.
1012 $class_obj = $UR::Context::current->get_objects_for_class_and_rule($class,$rule,0);
1013 return $class_obj if $class_obj;
1014 }
1015 if ($exception) {
1016 # We need to handle $@ here otherwise we'll see
1017 # "Can't locate UR/Object/Type/Ghost.pm in @INC" error.
1018 # We want to fall through "in the right circumstances".
1019 (my $module_path = $class_name . '.pm') =~ s/::/\//g;
1020 unless ($exception =~ /Can't locate $module_path in \@INC/) {
1021 die "Error while autoloading with 'use $class_name': $exception";
1022 }
1023 }
1024  
1025 # Parse the specified class name to check for a suffix.
1026 my ($prefix, $base, $suffix) = ($class_name =~ /^([^\:]+)::(.*)::([^:]+)/);
1027  
1028 my @parts;
1029 ($prefix, @parts) = split(/::/,$class_name);
1030  
1031 for (my $suffix_pos = $#parts; $suffix_pos >= 0; $suffix_pos--)
1032 {
1033 $class_obj = $UR::Context::current->get_objects_for_class_and_rule($class,$rule,0);
1034 if ($class_obj) {
1035 # the class was somehow generated while we were checking other classes for it and failing.
1036 # this can happen b/c some class with a name which is a subset of the one we're looking
1037 # for might "use" the one we want.
1038 return $class_obj if $class_obj;
1039 }
1040  
1041 my $base = join("::", @parts[0 .. $suffix_pos-1]);
1042 my $suffix = join("::", @parts[$suffix_pos..$#parts]);
1043  
1044 # See if a class exists for the same name w/o the suffix.
1045 # This may cause this function to be called recursively for
1046 # classes like Acme::Equipment::Set::View::upc_code,
1047 # which would fire recursively for three extensions of
1048 # Acme::Equipment.
1049 my $full_base_class_name = $prefix . ($base ? "::" . $base : "");
1050 my $base_class_obj;
1051 my $exception = do {
1052 local $@;
1053 $base_class_obj = eval { $full_base_class_name->__meta__ };
1054 $@;
1055 };
1056 if ($exception && $exception =~ m/^Error while autoloading/) {
1057 die $exception;
1058 }
1059  
1060 if ($base_class_obj)
1061 {
1062 # If so, that class may be able to generate a support
1063 # class.
1064 $class_obj = $full_base_class_name->__extend_namespace__($suffix);
1065 if ($class_obj)
1066 {
1067 # Autogeneration worked.
1068 # We still defer to is_loaded, since other parameters
1069 # may prevent the newly "loaded" class from being
1070 # returned.
1071 return $UR::Context::current->get_objects_for_class_and_rule($class,$rule,0)
1072 }
1073 }
1074 }
1075  
1076 # If we fall-through to this point, no class was found and no module.
1077 return;
1078 }
1079  
1080  
1081 sub use_module_with_namespace_constraints {
1082 use strict;
1083 use warnings;
1084  
1085 my $self = shift;
1086 my $target_class = shift;
1087  
1088 # If you do "use Acme; $o = Acme::Rocket->new();", and Perl finds Acme.pm
1089 # at "/foo/bar/Acme.pm", Acme::Rocket must be under /foo/bar/Acme/
1090 # in order to be dynamically loaded.
1091  
1092 my @words = split("::",$target_class);
1093 my $path;
1094 while (@words > 1) {
1095 my $namespace_name = join("::",@words[0..$#words-1]);
1096 my $namespace_expected_module = join("/",@words[0..$#words-1]) . ".pm";
1097  
1098  
1099 if ($path = $INC{$namespace_expected_module}) {
1100 #print "got mod $namespace_expected_module at $path for $target_class\n";
1101 $path =~ s/\/*$namespace_expected_module//g;
1102 }
1103 else {
1104 my $namespace_obj = UR::Object::Type->is_loaded(class_name => $namespace_name);
1105 if ($namespace_obj) {
1106 eval { $path = $namespace_obj->module_directory };
1107 if ($@) {
1108 # non-module class
1109 # don't auto-use, but don't make a lot of noise about it either
1110 }
1111 }
1112 }
1113 last if $path;
1114 pop @words;
1115 }
1116  
1117 unless ($path) {
1118 #Carp::cluck("No module_directory found for namespace $namespace_name."
1119 # . " Cannot dynamically load $target_class.");
1120 return;
1121 }
1122  
1123  
1124 $self->_use_safe($target_class,$path);
1125 my $meta = UR::Object::Type->is_loaded(class_name => $target_class);
1126 if ($meta) {
1127 return $meta;
1128 }
1129 else {
1130 return;
1131 }
1132 }
1133  
1134 sub _use_safe {
1135 use strict;
1136 use warnings;
1137  
1138 my ($self, $target_class, $expected_directory) = @_;
1139  
1140 # TODO: use some smart module to determine whether the path is
1141 # relative on the current system.
1142 if (defined($expected_directory) and $expected_directory !~ /^[\/\\]/) {
1143 $expected_directory = $pwd_at_compile_time . "/" . $expected_directory;
1144 }
1145  
1146 my $class_path = $target_class . ".pm";
1147 $class_path =~ s/\:\:/\//g;
1148  
1149 my @INC_COPY = @INC;
1150 if ($expected_directory) {
1151 unshift @INC, $expected_directory;
1152 }
1153 my $found = "";
1154 for my $dir (@INC) {
1155 if ($dir and (-e $dir . "/" . $class_path)) {
1156 $found = $dir;
1157 last;
1158 }
1159 }
1160  
1161 if (!$found) {
1162 # not found
1163 @INC = @INC_COPY;
1164 return;
1165 }
1166  
1167 if ($expected_directory and $expected_directory ne $found) {
1168 # not found in the specified location
1169 @INC = @INC_COPY;
1170 return;
1171 }
1172  
1173 do {
1174 local $SIG{__DIE__};
1175 local $SIG{__WARN__};
1176 eval "use $target_class";
1177 };
1178  
1179 # FIXME - if the use above failed because of a compilation error in the module we're trying to
1180 # load, then the error message below just tells the user that "Compilation failed in require"
1181 # and isn't propogating the error message about what caused the compile to fail
1182 if ($@) {
1183 #local $SIG{__DIE__};
1184  
1185 @INC = @INC_COPY;
1186 die ("ERROR DYNAMICALLY LOADING CLASS $target_class\n$@");
1187 }
1188  
1189 for (0..$#INC) {
1190 if ($INC[$_] eq $expected_directory) {
1191 splice @INC, $_, 1;
1192 last;
1193 }
1194 }
1195  
1196 return 1;
1197 }
1198  
1199  
1200 # sub _object
1201 # This is used to make sure that methods are called
1202 # as object methods and not class methods.
1203 # The typical case that's important is when something
1204 # like UR::Object::Type->method(...) is called.
1205 # If an object is expected in a method and it gets
1206 # a class instead, well, unpredictable things can
1207 # happen.
1208 #
1209 # For many methods on UR::Objects, the implementation
1210 # is in UR::Object. However, some of those methods
1211 # have the same name as methods in here (purposefully),
1212 # and those UR::Object methods often get the
1213 # UR::Object::Type object and call the same method,
1214 # which ends up in this file. The problem is when
1215 # those methods are called on UR::Object::Type
1216 # itself it come directly here, without getting
1217 # the UR::Object::Type object for UR::Object::Type
1218 # (confused yet?). So to fix this, we use _object to
1219 # make sure we have an object and not a class.
1220 #
1221 # Basically, we make sure we're working with a class
1222 # object and not a class name.
1223 #
1224  
1225 sub _object {
1226 return ref($_[0]) ? $_[0] : $_[0]->__meta__;
1227 }
1228  
1229 # new version gets everything, including "id" itself and object ref properties
1230 push @cache_keys, '_all_property_type_names';
1231 sub all_property_type_names {
1232 my $self = shift;
1233
1234 if ($self->{_all_property_type_names}) {
1235 return @{ $self->{_all_property_type_names} };
1236 }
1237
1238 #my $rule_template = UR::BoolExpr::Template->resolve('UR::Object::Type', 'id');
1239  
1240 my $all_property_type_names = $self->{_all_property_type_names} = [];
1241 for my $class_name ($self->class_name, $self->ancestry_class_names) {
1242 my $class_meta = UR::Object::Type->get($class_name);
1243 #my $rule = $rule_template->get_rule_for_values($class_name);
1244 #my $class_meta = $UR::Context::current->get_objects_for_class_and_rule('UR::Object::Type',$rule);
1245 if (my $has = $class_meta->{has}) {
1246 push @$all_property_type_names, sort keys %$has;
1247 }
1248 }
1249 return @$all_property_type_names;
1250 }
1251  
1252 sub table_for_property {
1253 my $self = _object(shift);
1254 Carp::croak('must pass a property_name to table_for_property') unless @_;
1255 my $property_name = shift;
1256 for my $class_object ( $self, $self->ancestry_class_metas )
1257 {
1258 my $property_object = UR::Object::Property->get( class_name => $class_object->class_name, property_name => $property_name );
1259 if ( $property_object )
1260 {
1261 next unless $property_object->column_name;
1262 return $class_object->table_name;
1263 }
1264 }
1265  
1266 return;
1267 }
1268  
1269 sub column_for_property {
1270 my $self = _object(shift);
1271 Carp::croak('must pass a property_name to column_for_property') unless @_;
1272 my $property_name = shift;
1273  
1274 my($properties,$columns) = @{$self->{'_all_properties_columns'}};
1275 for (my $i = 0; $i < @$properties; $i++) {
1276 if ($properties->[$i] eq $property_name) {
1277 return $columns->[$i];
1278 }
1279 }
1280  
1281 for my $class_object ( $self->ancestry_class_metas ) {
1282 my $column_name = $class_object->column_for_property($property_name);
1283 return $column_name if $column_name;
1284 }
1285 return;
1286 }
1287  
1288 sub property_for_column {
1289 my $self = _object(shift);
1290 Carp::croak('must pass a column_name to property_for_column') unless @_;
1291 my $column_name = lc(shift);
1292  
1293 my $data_source = $self->data_source || 'UR::DataSource';
1294 my($table_name,$self_table_name);
1295 ($table_name, $column_name) = $data_source->_resolve_table_and_column_from_column_name($column_name);
1296 (undef, $self_table_name) = $data_source->_resolve_owner_and_table_from_table_name($self->table_name);
1297  
1298 if (! $table_name) {
1299 my($properties,$columns) = @{$self->{'_all_properties_columns'}};
1300 for (my $i = 0; $i < @$columns; $i++) {
1301 if (lc($columns->[$i]) eq $column_name) {
1302 return $properties->[$i];
1303 }
1304 }
1305 } elsif ($table_name
1306 and
1307 $self_table_name
1308 and lc($self_table_name) eq lc($table_name)
1309 ) {
1310 # @$properties and @$columns contain items inherited from parent classes
1311 # make sure the property we find with that name goes to this class
1312 my $property_name = $self->property_for_column($column_name);
1313 return undef unless $property_name;
1314 my $prop_meta = $self->property_meta_for_name($property_name);
1315 if ($prop_meta->class_name eq $self->class_name
1316 and
1317 lc($prop_meta->column_name) eq $column_name
1318 ) {
1319 return $property_name;
1320 }
1321  
1322 } elsif ($table_name) {
1323  
1324 for my $class_object ( $self, $self->ancestry_class_metas ) {
1325 next unless $class_object->data_source;
1326 my $class_object_table_name;
1327 (undef, $class_object_table_name)
1328 = $class_object->data_source->_resolve_owner_and_table_from_table_name($class_object->table_name);
1329  
1330 if (! $class_object_table_name
1331 or
1332 $table_name ne lc($class_object_table_name)
1333 ) {
1334 (undef, $class_object_table_name) = $class_object->data_source->parse_view_and_alias_from_inline_view($class_object->table_name);
1335 }
1336 next if (! $class_object_table_name
1337 or
1338 $table_name ne lc($class_object_table_name));
1339  
1340 my $property_name = $class_object->property_for_column($column_name);
1341 return $property_name if $property_name;
1342 }
1343 }
1344  
1345 return;
1346 }
1347  
1348 # Methods for maintaining unique constraints
1349 # This is primarily used by the class re-writer (ur update classes-from-db), but
1350 # BoolExprs use them,too
1351  
1352 # Adds a constraint by name and property list to the class metadata. The class initializer
1353 # fills this data in via the 'constraints' key, so it shouldn't call add_unique_constraint()
1354 # directly
1355 sub add_unique_constraint {
1356 my $self = shift;
1357  
1358 unless (@_) {
1359 Carp::croak('method add_unique_constraint requires a constraint name as a parameter');
1360 }
1361 my $constraint_name = shift;
1362  
1363 my $constraints = $self->unique_property_set_hashref();
1364 if (exists $constraints->{$constraint_name}) {
1365 Carp::croak("A constraint named '$constraint_name' already exists for class ".$self->class_name);
1366 }
1367  
1368 unless (@_) {
1369 Carp::croak('method add_unique_constraint requires one or more property names as parameters');
1370 }
1371 my @property_names = @_;
1372  
1373 # Add a new constraint record
1374 push @{ $self->{'constraints'} } , { sql => $constraint_name, properties => \@property_names };
1375 # invalidate the other cached data
1376 $self->_invalidate_cached_data_for_subclasses('_unique_property_sets', '_unique_property_set_hashref');
1377 }
1378  
1379 sub remove_unique_constraint {
1380 my $self = shift;
1381  
1382 unless (@_) {
1383 Carp::croak("method remove_unique_constraint requires a constraint name as a parameter");
1384 }
1385  
1386 my $constraint_name = shift;
1387 my $constraints = $self->unique_property_set_hashref();
1388 unless (exists $constraints->{$constraint_name}) {
1389 Carp::croak("There is no constraint named '$constraint_name' for class ".$self->class_name);
1390 }
1391  
1392 # Remove the constraint record
1393 for (my $i = 0; $i < @{$self->{'constraints'}}; $i++) {
1394 if ($self->{'constraints'}->[$i]->{'sql'} = $constraint_name) {
1395 splice(@{$self->{'constraints'}}, $i, 1);
1396 }
1397 }
1398 $self->_invalidate_cached_data_for_subclasses('_unique_property_sets', '_unique_property_set_hashref');
1399 }
1400  
1401  
1402 # This returns a list of lists. Each inner list is the properties/columns
1403 # involved in the constraint
1404 sub unique_property_sets {
1405 my $self = shift;
1406 if ($self->{_unique_property_sets}) {
1407 return @{ $self->{_unique_property_sets} };
1408 }
1409  
1410 my $unique_property_sets = $self->{_unique_property_sets} = [];
1411  
1412 for my $class_name ($self->class_name, $self->ancestry_class_names) {
1413 my $class_meta = UR::Object::Type->get($class_name);
1414 if ($class_meta->{constraints}) {
1415 for my $spec (@{ $class_meta->{constraints} }) {
1416 push @$unique_property_sets, [ @{ $spec->{properties} } ]
1417 }
1418 }
1419 }
1420 return @$unique_property_sets;
1421 }
1422  
1423 # Return the constraint information as a hashref
1424 # keys are the SQL constraint name, values are a listref of property/column names involved
1425 sub unique_property_set_hashref {
1426 my $self = shift;
1427  
1428 if ($self->{_unique_property_set_hashref}) {
1429 return $self->{_unique_property_set_hashref};
1430 }
1431  
1432 my $unique_property_set_hashref = $self->{_unique_property_set_hashref} = {};
1433
1434 for my $class_name ($self->class_name, $self->ancestry_class_names) {
1435 my $class_meta = UR::Object::Type->get($class_name);
1436 if ($class_meta->{'constraints'}) {
1437 for my $spec (@{ $class_meta->{'constraints'} }) {
1438 my $unique_group = $spec->{'sql'};
1439 next if ($unique_property_set_hashref->{$unique_group}); # child classes override parents
1440 $unique_property_set_hashref->{$unique_group} = [ @{$spec->{properties}} ];
1441 }
1442 }
1443 }
1444  
1445 return $unique_property_set_hashref;
1446 }
1447  
1448  
1449 # Used by the class meta meta data constructors to make changes in the
1450 # raw data stored in the class object's hash. These should really
1451 # only matter while running ur update
1452  
1453 # Args are:
1454 # 1) An UR::Object::Property object with attribute_name, class_name, id, property_name, type_name
1455 # 2) The method called: _construct_object, load,
1456 # 3) An id?
1457 sub _property_change_callback {
1458 my($property_obj,$method, $old_val, $new_val) = @_;
1459  
1460 return if ($method eq 'load' || $method eq 'unload');
1461 return unless ref($property_obj); # happens when, say, error_message is called on the UR::Object::Property class
1462  
1463 my $class_obj = UR::Object::Type->get(class_name => $property_obj->class_name);
1464 my $property_name = $property_obj->property_name;
1465  
1466 $old_val = '' unless(defined $old_val);
1467 $new_val = '' unless(defined $new_val);
1468  
1469 if ($method eq 'create') {
1470 unless ($class_obj->{'has'}->{$property_name}) {
1471 my @attr = qw( class_name data_length data_type is_delegated is_optional property_name );
1472  
1473 my %new_property;
1474 foreach my $attr_name (@attr ) {
1475 $new_property{$attr_name} = $property_obj->$attr_name();
1476 }
1477 $class_obj->{'has'}->{$property_name} = \%new_property;
1478 }
1479 if (defined $property_obj->is_id) {
1480 &_id_property_change_callback($property_obj, 'create');
1481 }
1482  
1483 } elsif ($method eq 'delete') {
1484 if (defined $property_obj->is_id) {
1485 &_id_property_change_callback($property_obj, 'delete');
1486 }
1487 delete $class_obj->{'has'}->{$property_name};
1488  
1489 } elsif ($method eq 'is_id' and $new_val ne $old_val) {
1490 my $change = $new_val ? 'create' : 'delete';
1491 &_id_property_change_callback($property_obj, $change);
1492 }
1493  
1494 if (exists $class_obj->{'has'}->{$property_name}
1495 && exists $class_obj->{'has'}->{$property_name}->{$method}) {
1496 $class_obj->{'has'}->{$property_name}->{$method} = $new_val;
1497  
1498 }
1499  
1500 # Invalidate the cache used by all_property_names()
1501 for my $key (@cache_keys) {
1502 $class_obj->_invalidate_cached_data_for_subclasses($key);
1503 }
1504 }
1505  
1506  
1507 # Some expensive-to-calculate data gets stored in the class meta hashref
1508 # and needs to be removed for all the existing subclasses
1509 sub _invalidate_cached_data_for_subclasses {
1510 my($class_meta, @cache_keys) = @_;
1511  
1512 delete @$class_meta{@cache_keys};
1513  
1514 my @subclasses = @{$UR::Object::Type::_init_subclasses_loaded{$class_meta->class_name}};
1515 my %seen;
1516 while (my $subclass = shift @subclasses) {
1517 next if ($seen{$subclass}++);
1518 my $sub_meta = UR::Object::Type->get(class_name => $subclass);
1519 delete @$sub_meta{@cache_keys};
1520 push @subclasses, @{$UR::Object::Type::_init_subclasses_loaded{$sub_meta->class_name}};
1521 }
1522 }
1523  
1524  
1525 # A streamlined version of the method just below that dosen't check that the
1526 # data in both places is the same before a delete operation. What was happening
1527 # was that an ID property got deleted and the position checks out ok, but then
1528 # a second ID property gets deleted and now the position dosen't match because we
1529 # aren't able to update the object's position property 'cause it's an ID property
1530 # and can't be changed.
1531 #
1532 # The short story is that we've lowered the bar for making sure it's safe to delete info
1533 sub _id_property_change_callback {
1534 my $property_obj = shift;
1535 my $method = shift;
1536  
1537 return if ($method eq 'load' || $method eq 'unload');
1538  
1539 my $class = UR::Object::Type->get(class_name => $property_obj->class_name);
1540
1541 if ($method eq 'create') {
1542 my $pos = $property_obj->id_by;
1543 $pos += 0; # make sure it's a number
1544 if ($pos <= @{$class->{'id_by'}}) {
1545 splice(@{$class->{'id_by'}}, $pos, 0, $property_obj->property_name);
1546 } else {
1547 # $pos is past the end... probably an id property was deleted and another added
1548 push @{$class->{'id_by'}}, $property_obj->property_name;
1549 }
1550 } elsif ($method eq 'delete') {
1551 my $property_name = $property_obj->property_name;
1552 for (my $i = 0; $i < @{$class->{'id_by'}}; $i++) {
1553 if ($class->{'id_by'}->[$i] eq $property_name) {
1554 splice(@{$class->{'id_by'}}, $i, 1);
1555 return;
1556 }
1557 }
1558 #$DB::single = 1;
1559 Carp::confess("Internal data consistancy problem: could not find property named $property_name in id_by list for class meta " . $class->class_name);
1560  
1561 } else {
1562 # Shouldn't get here since ID properties can't be changed, right?
1563 #$DB::single = 1;
1564 Carp::confess("Shouldn't be here as ID properties can't change");
1565 1;
1566 }
1567  
1568 $class->{'_all_id_property_names'} = undef; # Invalidate the cache used by all_id_property_names
1569 }
1570  
1571  
1572 #
1573 # BOOTSTRAP CODE
1574 #
1575  
1576 sub get_with_special_parameters {
1577 my $class = shift;
1578 my $rule = shift;
1579 my %extra = @_;
1580 if (my $namespace = delete $extra{'namespace'}) {
1581 unless (keys %extra) {
1582 my @c = $namespace->get_material_classes();
1583 @c = grep { $_->namespace eq $namespace } $class->is_loaded($rule->params_list);
1584 return $class->context_return(@c);
1585 }
1586 }
1587 return $class->SUPER::get_with_special_parameters($rule,@_);
1588 }
1589  
1590 sub __signal_change__ {
1591 my $self = shift;
1592 my @rv = $self->SUPER::__signal_change__(@_);
1593 if ($_[0] eq "delete") {
1594 my $class_name = $self->{class_name};
1595 $self->ungenerate();
1596 }
1597 return @rv;
1598 }
1599  
1600 my @default_valid_signals = qw(create delete commit rollback load unload load_external subclass_loaded);
1601 our %STANDARD_VALID_SIGNALS;
1602 @STANDARD_VALID_SIGNALS{@default_valid_signals} = (1) x @default_valid_signals;
1603 sub _is_valid_signal {
1604 my $self = shift;
1605 my $aspect = shift;
1606  
1607 # An aspect of empty string (or undef) means all aspects are being observed.
1608 return 1 unless (defined($aspect) and length($aspect));
1609  
1610 # All standard creation and destruction methods emit a signal.
1611 return 1 if ($STANDARD_VALID_SIGNALS{$aspect});
1612  
1613 for my $property ($self->all_property_names)
1614 {
1615 return 1 if $property eq $aspect;
1616 }
1617  
1618 if (!exists $self->{'_is_valid_signal'}) {
1619 $self->{'_is_valid_signal'} = { map { $_ => 1 } @{$self->{'valid_signals'}} };
1620 }
1621  
1622 return 1 if ($self->{'_is_valid_signal'}->{$aspect});
1623  
1624 foreach my $parent_meta ( $self->parent_class_metas ) {
1625 if ($parent_meta->_is_valid_signal($aspect)) {
1626 $self->{'_is_valid_signal'}->{$aspect} = 1;
1627 return 1;
1628 }
1629 }
1630  
1631 return 0;
1632 }
1633  
1634  
1635 sub generated {
1636 my $self = shift;
1637 if (@_) {
1638 $self->{'generated'} = shift;
1639 }
1640 return $self->{'generated'};
1641 }
1642  
1643 sub ungenerate {
1644 my $self = shift;
1645 my $class_name = $self->class_name;
1646 delete $UR::Object::_init_subclass->{$class_name};
1647 delete $UR::Object::Type::_inform_all_parent_classes_of_newly_loaded_subclass{$class_name};
1648 do {
1649 no strict;
1650 no warnings;
1651 my @symbols_which_are_not_subordinate_namespaces =
1652 grep { substr($_,-2) ne '::' }
1653 keys %{ $class_name . "::" };
1654 my $hr = \%{ $class_name . "::" };
1655 delete @$hr{@symbols_which_are_not_subordinate_namespaces};
1656 };
1657 my $module_name = $class_name;
1658 $module_name =~ s/::/\//g;
1659 $module_name .= ".pm";
1660 delete $INC{$module_name};
1661 $self->{'generated'} = 0;
1662 }
1663  
1664 sub singular_accessor_name_for_is_many_accessor {
1665 my($self, $property_name) = @_;
1666 unless (exists $self->{_accessor_singular_names}->{$property_name}) {
1667 my $property_meta = $self->property_meta_for_name($property_name) if ($self->generated);
1668 if ($bootstrapping # trust the caller when bootstrapping
1669 or
1670 ! $self->generated # when called from UR::Object::Type::AccessorWriter and the property isn't created yet
1671 or
1672 ($property_meta && $property_meta->is_many)
1673 ) {
1674 require Lingua::EN::Inflect;
1675 $self->{_accessor_singular_names}->{$property_name} = Lingua::EN::Inflect::PL_V($property_name);
1676 } else {
1677 $self->{_accessor_singular_names}->{$property_name} = undef;
1678 }
1679 }
1680 return $self->{_accessor_singular_names}->{$property_name};
1681 }
1682  
1683 sub iterator_accessor_name_for_is_many_accessor {
1684 my($self, $property_name) = @_;
1685  
1686 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1687 return $singular && "${singular}_iterator";
1688 }
1689  
1690 sub set_accessor_name_for_is_many_accessor {
1691 my($self, $property_name) = @_;
1692  
1693 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1694 return $singular && "${singular}_set";
1695 }
1696  
1697 sub rule_accessor_name_for_is_many_accessor {
1698 my($self, $property_name) = @_;
1699  
1700 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1701 return $singular && "__${singular}_rule";
1702 }
1703  
1704 sub arrayref_accessor_name_for_is_many_accessor {
1705 my($self, $property_name) = @_;
1706  
1707 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1708 return $singular && "${singular}_arrayref";
1709 }
1710  
1711 sub adder_name_for_is_many_accessor {
1712 my($self, $property_name) = @_;
1713  
1714 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1715 return $singular && "add_${singular}";
1716 }
1717  
1718 sub remover_name_for_is_many_accessor {
1719 my($self, $property_name) = @_;
1720  
1721 my $singular = $self->singular_accessor_name_for_is_many_accessor($property_name);
1722 return $singular && "remove_${singular}";
1723 }
1724  
1725 1;
1726