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

filter: Statementstmt 0.0% 0 / 960 Branchbran 0.0% 0 / 440 Conditioncond 0.0% 0 / 257 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 1728 SCAR 108.0
CC
221
Cov
0%
_normalize_class_description_impl
1722.0
_complete_class_meta_object_definitions
1482.0
_process_class_definition_property_keys
756.0
CRAP 49062.0
1 # This line forces correct deployment by some tools.
2 package UR::Object::Type::Initializer;
3  
4 package UR::Object::Type;
5  
6 use strict;
7 use warnings;
8 require UR;
9  
10 use UR::Util;
11  
12 BEGIN {
13 # Perl 5.10 did not require mro in order to call get_mro but it looks
14 # like that was "fixed" in newer version.
15 if ($^V ge v5.9.5) {
16 eval "require mro";
17 }
18 };
19  
20 our $VERSION = "0.46"; # UR $VERSION;
21  
22 use Carp ();
23 use Sub::Name ();
24 use Sub::Install ();
25  
26 # keys are class property names (like er_role, is_final, etc) and values are
27 # the default value to use if it's not specified in the class definition
28 #
29 # For most classes, this kind of thing is handled by the default_value attribute on
30 # a class' property. For bootstrapping reasons, the default values for the
31 # properties of UR::Object::Type' class need to be listed here as well. If
32 # any of these change, or new default valued items are added, be sure to also
33 # update the class definition for UR::Object::Type (which really lives in UR.pm
34 # for the moment)
35 %UR::Object::Type::defaults = (
36 er_role => 'entity',
37 is_final => 0,
38 is_singleton => 0,
39 is_transactional => 1,
40 is_mutable => 1,
41 is_many => 0,
42 is_abstract => 0,
43 subclassify_by_version => 0,
44 );
45  
46 # All those same comments also apply to UR::Object::Property's properties
47 %UR::Object::Property::defaults = (
48 is_optional => 0,
49 is_transient => 0,
50 is_constant => 0,
51 is_volatile => 0,
52 is_classwide => 0,
53 is_delegated => 0,
54 is_calculated => 0,
55 is_mutable => undef,
56 is_transactional => 1,
57 is_many => 0,
58 is_numeric => 0,
59 is_specified_in_module_header => 0,
60 is_deprecated => 0,
61 position_in_module_header => -1,
62 doc_position => -1,
63 is_undocumented => 0,
64 );
65  
66 @UR::Object::Type::meta_id_ref_shared_properties = (
67 qw/
68 is_optional
69 is_transient
70 is_constant
71 is_volatile
72 is_classwide
73 is_transactional
74 is_abstract
75 is_concrete
76 is_final
77 is_many
78 is_deprecated
79 is_undocumented
80 /
81 );
82  
83 %UR::Object::Type::converse = (
84 required => 'optional',
85 abstract => 'concrete',
86 one => 'many',
87 );
88  
89 # These classes are used to define an object class.
90 # As such, they get special handling to bootstrap the system.
91  
92 our %meta_classes = map { $_ => 1 }
93 qw/
94 UR::Object
95 UR::Object::Type
96 UR::Object::Property
97 /;
98  
99 our $bootstrapping = 1;
100 our @partially_defined_classes;
101  
102 # When copying the object hash to create its db_committed, these keys should be removed because
103 # they contain things like coderefs
104 our @keys_to_delete_from_db_committed = qw( id db_committed _id_property_sorter get_composite_id_resolver get_composite_id_decomposer );
105  
106 # Stages of Class Initialization
107 #
108 # define() is called to indicate the class structure (create() may also be called by the db sync command to make new classes)
109 #
110 # the parameters to define()/create() are normalized by _normalize_class_description()
111 #
112 # a basic functional class meta object is created by _define_minimal_class_from_normalized_class_description()
113 #
114 # accessors are created
115 #
116 # if we're still bootstrapping:
117 #
118 # the class is stashed in an array so the post-bootstrapping stages can be done in bulk
119 #
120 # we exit define()
121 #
122 # if we're done bootstrapping:
123 #
124 # _inform_all_parent_classes_of_newly_loaded_subclass() sets up an internal map of known subclasses of each base class
125 #
126 # _complete_class_meta_object_definitions() decomposes the definition into normalized objects
127 #
128  
129 sub __define__ {
130 my $class = shift;
131 my $desc = $class->_normalize_class_description(@_);
132  
133 my $class_name = $desc->{class_name} ||= (caller(0))[0];
134 $desc->{class_name} = $class_name;
135  
136 my $self;
137  
138 my %params = $class->_construction_params_for_desc($desc);
139 my $meta_class_name;
140 if (%params) {
141 $self = __PACKAGE__->__define__(%params);
142 return unless $self;
143 $meta_class_name = $params{class_name};
144 }
145 else {
146 $meta_class_name = __PACKAGE__;
147 }
148  
149 $self = $UR::Context::all_objects_loaded->{$meta_class_name}{$class_name};
150 if ($self) {
151 #$DB::single = 1;
152 #Carp::cluck("Re-defining class $class_name? Found $meta_class_name with id '$class_name'");
153 return $self;
154 }
155  
156 $self = $class->_make_minimal_class_from_normalized_class_description($desc);
157 Carp::confess("Failed to define class $class_name!") unless $self;
158  
159 # we do this for define() but not create()
160 my %db_committed = %$self;
161 delete @db_committed{@keys_to_delete_from_db_committed};
162 $self->{'db_committed'} = \%db_committed;
163  
164 $self->_initialize_accessors_and_inheritance
165 or Carp::confess("Error initializing accessors for $class_name!");
166  
167 if ($bootstrapping) {
168 push @partially_defined_classes, $self;
169 }
170 else {
171 unless ($self->_inform_all_parent_classes_of_newly_loaded_subclass()) {
172 Carp::confess(
173 "Failed to link to parent classes to complete definition of class $class_name!"
174 . $class->error_message
175 );
176 }
177 unless ($self->_complete_class_meta_object_definitions()) {
178 #$DB::single = 1;
179 $self->_complete_class_meta_object_definitions();
180 Carp::confess(
181 "Failed to complete definition of class $class_name!"
182 . $class->error_message
183 );
184 }
185 }
186  
187 $self->_inform_roles_of_new_class();
188  
189 return $self;
190 }
191  
192  
193 sub create {
194 # this is typically only used by code which intendes to autogenerate source code
195 # it will lead to the writing of a Perl module upon commit.
196 my $class = shift;
197 my $desc = $class->_normalize_class_description(@_);
198  
199 my $class_name = $desc->{class_name} ||= (caller(0))[0];
200 my $meta_class_name = $desc->{meta_class_name};
201  
202 no strict 'refs';
203 unless (
204 $meta_class_name eq __PACKAGE__
205 or
206 # in newer Perl interpreters the ->isa() call can return true
207 # even if @ISA has been emptied (OS X) ???
208 (scalar(@{$meta_class_name . '::ISA'}) and $meta_class_name->isa(__PACKAGE__))
209 ) {
210 if (__PACKAGE__->get(class_name => $meta_class_name)) {
211 warn "class $meta_class_name already exists when creating class meta for $class_name?!";
212 }
213 else {
214 __PACKAGE__->create(
215 __PACKAGE__->_construction_params_for_desc($desc)
216 );
217 }
218 }
219  
220 my $self = $class->_make_minimal_class_from_normalized_class_description($desc);
221 Carp::confess("Failed to define class $class_name!") unless $self;
222  
223 $self->_initialize_accessors_and_inheritance
224 or Carp::confess("Failed to define class $class_name!");
225  
226 $self->_inform_all_parent_classes_of_newly_loaded_subclass()
227 or Carp::confess(
228 "Failed to link to parent classes to complete definition of class $class_name!"
229 . $class->error_message
230 );
231  
232 $self->generated(0);
233  
234 $self->__signal_change__("create");
235  
236 return $self;
237 }
238  
239 sub _preprocess_subclass_description {
240 # allow a class to modify the description of any subclass before it instantiates
241 # this filtering allows a base class to specify policy, add meta properties, etc.
242 my ($self,$prev_desc) = @_;
243  
244 my $current_desc = $prev_desc;
245  
246 if (my $preprocessor = $self->subclass_description_preprocessor) {
247 # the preprocessor must me a method name in the class being adjusted
248 no strict 'refs';
249 unless ($self->class_name->can($preprocessor)) {
250 die "Class " . $self->class_name
251 . " specifies a pre-processor for subclass descriptions "
252 . $preprocessor . " which is not defined in the "
253 . $self->class_name . " package!";
254 }
255 $current_desc = $self->class_name->$preprocessor($current_desc);
256 $current_desc = $self->_normalize_class_description_impl(%$current_desc);
257 }
258  
259 # only call it on the direct parent classes, let recursion walk the tree
260 my @parent_class_names =
261 grep { $_->can('__meta__') }
262 $self->parent_class_names();
263  
264 for my $parent_class_name (@parent_class_names) {
265 my $parent_class = $parent_class_name->__meta__;
266 $current_desc = $parent_class->_preprocess_subclass_description($current_desc);
267 }
268  
269 return $current_desc;
270 }
271  
272 sub _construction_params_for_desc {
273 my $class = shift;
274 my $desc = shift;
275  
276 my $class_name = $desc->{class_name};
277 my $meta_class_name = $desc->{meta_class_name};
278 my @extended_metadata;
279 if ($desc->{type_has}) {
280 @extended_metadata = ( has => [ @{ $desc->{type_has} } ] );
281 }
282  
283 if (
284 $meta_class_name eq __PACKAGE__
285 ) {
286 if (@extended_metadata) {
287 die "Cannot extend class metadata of $class_name because it is a class involved in UR bootstrapping.";
288 }
289 return();
290 }
291 else {
292 if ($bootstrapping) {
293 return (
294 class_name => $meta_class_name,
295 is => __PACKAGE__,
296 @extended_metadata,
297 );
298 }
299 else {
300 my $parent_classes = $desc->{is};
301 my @meta_parent_classes = map { $_ . '::Type' } @$parent_classes;
302 for (@$parent_classes) {
303 __PACKAGE__->use_module_with_namespace_constraints($_);
304 eval {$_->class};
305 if ($@) {
306 die "Error with parent class $_ when defining $class_name! $@";
307 }
308 }
309 return (
310 class_name => $meta_class_name,
311 is => \@meta_parent_classes,
312 @extended_metadata,
313 );
314 }
315 }
316  
317 }
318  
319  
320  
321 sub initialize_bootstrap_classes
322 {
323 # This is called once at the end of compiling the UR module set to handle
324 # classes which did incomplete initialization while bootstrapping.
325 # Until bootstrapping occurs is done,
326 my $class = shift;
327  
328 for my $class_meta (@partially_defined_classes) {
329 unless ($class_meta->_inform_all_parent_classes_of_newly_loaded_subclass) {
330 my $class_name = $class_meta->{class_name};
331 Carp::confess (
332 "Failed to complete inheritance linkage definition of class $class_name!"
333 . $class_meta->error_message
334 );
335 }
336  
337 }
338 while (my $class_meta = shift @partially_defined_classes) {
339 unless ($class_meta->_complete_class_meta_object_definitions()) {
340 my $class_name = $class_meta->{class_name};
341 Carp::confess(
342 "Failed to complete definition of class $class_name!"
343 . $class_meta->error_message
344 );
345 }
346 }
347 $bootstrapping = 0;
348  
349 # It should be safe to set up callbacks now. register_callback() instead
350 # of create() so a subsequent rollback won't remove the observer.
351 UR::Observer->register_callback(
352 subject_class_name => 'UR::Object::Property',
353 subject_id => '',
354 aspect => '',
355 priority => 1,
356 note => '',
357 once => 0,
358 callback => \&UR::Object::Type::_property_change_callback,
359 );
360 }
361  
362 sub _normalize_class_description {
363 my $class = shift;
364 my $desc = $class->_normalize_class_description_impl(@_);
365  
366 $class->compose_roles($desc) unless $bootstrapping;
367  
368 unless ($bootstrapping) {
369 for my $parent_class_name (@{ $desc->{is} }) {
370 my $parent_class = $parent_class_name->__meta__;
371 $desc = $parent_class->_preprocess_subclass_description($desc);
372 }
373 }
374  
375 # we previously handled property meta extensions when normalizing the property
376 # now we merely save unrecognized things
377 # this is now done afterward so that parent classes can preprocess their subclasses descriptions before extending
378 # normalize the data behind the property descriptions
379 my @property_names = keys %{$desc->{has}};
380 for my $property_name (@property_names) {
381 Carp::croak("Invalid property name in class ".$desc->{class_name}.": '$property_name'")
382 unless UR::Util::is_valid_property_name($property_name);
383  
384 my $pdesc = $desc->{has}->{$property_name};
385 my $unknown_ma = delete $pdesc->{unrecognized_meta_attributes};
386 next unless $unknown_ma;
387 for my $name (keys %$unknown_ma) {
388 if (exists $desc->{attributes_have}->{$name}) {
389 $pdesc->{$name} = delete $unknown_ma->{$name};
390 }
391 }
392 if (%$unknown_ma) {
393 my $class_name = $desc->{class_name};
394 my @unknown_ma = sort keys %$unknown_ma;
395 Carp::confess("unknown meta-attributes present for $class_name $property_name: @unknown_ma\n");
396 }
397 }
398  
399 return $desc;
400 }
401  
402 sub _canonicalize_class_params {
403 my($params, $mappings) = @_;
404  
405 my %canon_params;
406  
407 for my $mapping ( @$mappings ) {
408 my ($primary_field_name, @alternate_field_names) = @$mapping;
409 my @all_fields = ($primary_field_name, @alternate_field_names);
410 my @values = grep { defined($_) } delete @$params{@all_fields};
411 if (@values > 1) {
412 Carp::confess(
413 "Multiple values in for field "
414 . join("/", @all_fields)
415 );
416 }
417 elsif (@values == 1) {
418 $canon_params{$primary_field_name} = $values[0];
419 }
420 }
421  
422 return %canon_params;
423 }
424  
425 our @CLASS_DESCRIPTION_KEY_MAPPINGS_COMMON_TO_CLASSES_AND_ROLES = (
426 [ roles => qw//],
427 [ is_abstract => qw/abstract/],
428 [ is_final => qw/final/],
429 [ is_singleton => qw//],
430 [ is_transactional => qw//],
431 [ id_by => qw/id_properties/],
432 [ has => qw/properties/],
433 [ type_has => qw//],
434 [ attributes_have => qw//],
435 [ er_role => qw/er_type/],
436 [ doc => qw/description/],
437 [ relationships => qw//],
438 [ constraints => qw/unique_constraints/],
439 [ namespace => qw//],
440 [ schema_name => qw//],
441 [ data_source_id => qw/data_source instance/],
442 [ select_hint => qw/query_hint/],
443 [ join_hint => qw//],
444 [ subclassify_by => qw/sub_classification_property_name/],
445 [ sub_classification_meta_class_name => qw//],
446 [ sub_classification_method_name => qw//],
447 [ first_sub_classification_method_name => qw//],
448 [ composite_id_separator => qw//],
449 [ generate => qw//],
450 [ generated => qw//],
451 [ subclass_description_preprocessor => qw//],
452 [ id_generator => qw/id_sequence_generator_name/],
453 [ subclassify_by_version => qw//],
454 [ meta_class_name => qw//],
455 [ valid_signals => qw//],
456 );
457  
458 my @CLASS_DESCRIPTION_KEY_MAPPINGS = (
459 @CLASS_DESCRIPTION_KEY_MAPPINGS_COMMON_TO_CLASSES_AND_ROLES,
460 [ class_name => qw//],
461 [ type_name => qw/english_name/],
462 [ is => qw/inheritance extends isa is_a/],
463 [ table_name => qw/sql dsmap/],
464 );
465  
466 sub _normalize_class_description_impl {
467 my $class = shift;
468 my %old_class = @_;
469  
470 if (exists $old_class{extra}) {
471 %old_class = (%{delete $old_class{extra}}, %old_class);
472 }
473  
474 my $class_name = delete $old_class{class_name};
475  
476 my %new_class = (
477 class_name => $class_name,
478 is_singleton => $UR::Object::Type::defaults{'is_singleton'},
479 is_final => $UR::Object::Type::defaults{'is_final'},
480 is_abstract => $UR::Object::Type::defaults{'is_abstract'},
481 _canonicalize_class_params(\%old_class, \@CLASS_DESCRIPTION_KEY_MAPPINGS),
482 );
483  
484 if (my $pp = $new_class{subclass_description_preprocessor}) {
485 if (!ref($pp)) {
486 unless ($pp =~ /::/) {
487 # a method name, not fully qualified
488 $new_class{subclass_description_preprocessor} =
489 $new_class{class_name}
490 . '::'
491 . $new_class{subclass_description_preprocessor};
492 } else {
493 $new_class{subclass_description_preprocessor} = $pp;
494 }
495 }
496 elsif (ref($pp) ne 'CODE') {
497 die "unexpected " . ref($pp) . " reference for subclass_description_preprocessor for $class_name!";
498 }
499 }
500  
501 unless ($new_class{er_role}) {
502 $new_class{er_role} = $UR::Object::Type::defaults{'er_role'};
503 }
504  
505 my @crap = qw/source/;
506 delete @old_class{@crap};
507  
508 if ($class_name =~ /^(.*?)::/) {
509 $new_class{namespace} = $1;
510 }
511 else {
512 $new_class{namespace} = $new_class{class_name};
513 }
514  
515 if (not exists $new_class{is_transactional}
516 and not $meta_classes{$class_name}
517 ) {
518 $new_class{is_transactional} = $UR::Object::Type::defaults{'is_transactional'};
519 }
520  
521 unless ($new_class{is}) {
522 no warnings;
523 no strict 'refs';
524 if (my @isa = @{ $class_name . "::ISA" }) {
525 $new_class{is} = \@isa;
526 }
527 }
528  
529 unless ($new_class{is}) {
530 if ($new_class{table_name}) {
531 $new_class{is} = ['UR::Entity']
532 }
533 else {
534 $new_class{is} = ['UR::Object']
535 }
536 }
537  
538 unless ($new_class{'doc'}) {
539 $new_class{'doc'} = undef;
540 }
541  
542 foreach my $key ( qw(valid_signals roles) ) {
543 unless (UR::Util::ensure_arrayref(\%new_class, $key)) {
544 Carp::croak("The '$key' metadata for class $class_name must be an arrayref");
545 }
546 }
547  
548 # Later code expects these to be listrefs
549 for my $field (qw/is id_by has relationships constraints/) {
550 _massage_field_into_arrayref(\%new_class, $field);
551 }
552  
553  
554 # These may have been found and moved over. Restore.
555 $old_class{has} = delete $new_class{has};
556 $old_class{attributes_have} = delete $new_class{attributes_have};
557  
558 # Install structures to track fully formatted property data.
559 my $instance_properties = $new_class{has} = {};
560 my $meta_properties = $new_class{attributes_have} = {};
561  
562 # The id might be a single value, or not specified at all.
563 my $id_properties;
564 if (not exists $new_class{id_by}) {
565 if ($new_class{is}) {
566 $id_properties = $new_class{id_by} = [];
567 }
568 else {
569 $id_properties = $new_class{id_by} = [ id => { is_optional => 0 } ];
570 }
571 }
572 elsif ( (not ref($new_class{id_by})) or (ref($new_class{id_by}) ne 'ARRAY') ) {
573 $id_properties = $new_class{id_by} = [ $new_class{id_by} ];
574 }
575 else {
576 $id_properties = $new_class{id_by};
577 }
578  
579 _normalize_id_property_data(\%old_class, \%new_class);
580  
581 if (@$id_properties > 1
582 and grep {$_ eq 'id'} @$id_properties)
583 {
584 Carp::croak("Cannot initialize class $class_name: "
585 . "Cannot have an ID property named 'id' when the class has multiple ID properties ("
586 . join(', ', map { "'$_'" } @$id_properties)
587 . ")");
588 }
589  
590 _process_class_definition_property_keys(\%old_class, \%new_class);
591  
592 # NOT ENABLED YET
593 if (0) {
594 # done processing direct properties of this process
595 # extend %$instance_properties with properties of the parent classes
596 my @parent_class_names = @{ $new_class{is} };
597 for my $parent_class_name (@parent_class_names) {
598 my $parent_class_meta = $parent_class_name->__meta__;
599 die "no meta for $parent_class_name while initializing $class_name?" unless $parent_class_meta;
600 my $parent_normalized_properties = $parent_class_meta->{has};
601 for my $parent_property_name (keys %$parent_normalized_properties) {
602 my $parent_property_data = $parent_normalized_properties->{$parent_property_name};
603 my $inherited_copy = $instance_properties->{$parent_property_name};
604 unless ($inherited_copy) {
605 $inherited_copy = UR::Util::deep_copy($parent_property_data);
606 }
607 $inherited_copy->{class_name} = $class_name;
608 my $override = $inherited_copy->{overrides_class_names} ||= [];
609 push @$override, $parent_property_data->{class_name};
610 }
611 }
612 }
613  
614 if (($new_class{data_source_id} and not ref($new_class{data_source_id})) and not $new_class{schema_name}) {
615 my $s = $new_class{data_source_id};
616 $s =~ s/^.*::DataSource:://;
617 $new_class{schema_name} = $s;
618 }
619  
620 if (%old_class) {
621 # this should have all been deleted above
622 # we actually process it later, since these may be related to parent classes extending
623 # the class definition
624 $new_class{extra} = \%old_class;
625 };
626  
627 # ensure parent classes are loaded
628 unless ($bootstrapping) {
629 my @base_classes = map { ref($_) ? @$_ : $_ } $new_class{is};
630 for my $parent_class_name (@base_classes) {
631 # ensure the parent classes are fully processed
632 no warnings;
633 unless ($parent_class_name->can("__meta__")) {
634 __PACKAGE__->use_module_with_namespace_constraints($parent_class_name);
635 Carp::croak("Class $class_name cannot initialize because of errors using parent class $parent_class_name: $@") if $@;
636 }
637 unless ($parent_class_name->can("__meta__")) {
638 if ($ENV{'HARNESS_ACTIVE'}) {
639 Carp::confess("Class $class_name cannot initialize because of errors using parent class $parent_class_name. Failed to find static method '__meta__' on $parent_class_name. Does class $parent_class_name exist, and is it loaded?\n The entire list of base classes was ".join(', ', @base_classes));
640 }
641 Carp::croak("Class $class_name cannot initialize because of errors using parent class $parent_class_name. Failed to find static method '__meta__' on $parent_class_name. Does class $parent_class_name exist, and is it loaded?");
642 }
643 my $parent_class = $parent_class_name->__meta__;
644 unless ($parent_class) {
645 Carp::carp("No class metadata object for $parent_class_name");
646 next;
647 }
648  
649 # the the parent classes indicate version, if needed
650 if ($parent_class->{'subclassify_by_version'} and not $parent_class_name =~ /::Ghost/) {
651 unless ($class_name =~ /^${parent_class_name}::V\d+/) {
652 my $ns = $parent_class_name;
653 $ns =~ s/::.*//;
654 my $version;
655 if ($ns and $ns->can("component_version")) {
656 $version = $ns->component_version($class);
657 }
658 unless ($version) {
659 $version = '1';
660 }
661 $parent_class_name = $parent_class_name . '::V' . $version;
662 eval "use $parent_class_name";
663 Carp::confess("Error using versioned module $parent_class_name!:\n$@") if $@;
664 redo;
665 }
666 }
667 }
668 $new_class{is} = \@base_classes;
669 }
670  
671 # allow parent classes to adjust the description in systematic ways
672 my @additional_property_meta_attributes;
673 unless ($bootstrapping) {
674 for my $parent_class_name (@{ $new_class{is} }) {
675 my $parent_class = $parent_class_name->__meta__;
676 if (my $parent_meta_properties = $parent_class->{attributes_have}) {
677 push @additional_property_meta_attributes, %$parent_meta_properties;
678 }
679 }
680 }
681  
682 __PACKAGE__->_normalize_property_descriptions_during_normalize_class_description(\%new_class);
683  
684 unless ($bootstrapping) {
685 %$meta_properties = (%$meta_properties, @additional_property_meta_attributes);
686  
687 # Inheriting from an abstract class that subclasses with a subclassify_by means that
688 # this class' property named by that subclassify_by is actually a constant equal to this
689 # class' class name
690 PARENT_CLASS:
691 foreach my $parent_class_name ( @{ $new_class{'is'} }) {
692 my $parent_class_meta = $parent_class_name->__meta__();
693 foreach my $ancestor_class_meta ( $parent_class_meta->all_class_metas ) {
694 if (my $subclassify_by = $ancestor_class_meta->subclassify_by) {
695 if (not $instance_properties->{$subclassify_by}) {
696 my %old_property = (
697 property_name => $subclassify_by,
698 default_value => $class_name,
699 is_constant => 1,
700 is_classwide => 1,
701 is_specified_in_module_header => 0,
702 column_name => '',
703 implied_by => $parent_class_meta->class_name . '::subclassify_by',
704 );
705 my %new_property = $class->_normalize_property_description1($subclassify_by, \%old_property, \%new_class);
706 my %new_property2 = $class->_normalize_property_description2(\%new_property, \%new_class);
707 $instance_properties->{$subclassify_by} = \%new_property2;
708 last PARENT_CLASS;
709 }
710 }
711 }
712 }
713 }
714  
715 my $meta_class_name = __PACKAGE__->_resolve_meta_class_name_for_class_name($class_name);
716 $new_class{meta_class_name} ||= $meta_class_name;
717 return \%new_class;
718 }
719  
720 # Transform the id properties into a list of raw ids,
721 # and move the property definitions into "id_implied"
722 # where present so they can be processed below.
723 sub _normalize_id_property_data {
724 my($old_class_desc, $new_class_desc) = @_;
725  
726 my $id_properties = $new_class_desc->{id_by};
727 my $property_rank = 0;
728 my @replacement;
729 my $pos = 0;
730  
731 for(my $n = 0; $n < @$id_properties; $n++) {
732 my $name = $id_properties->[$n];
733  
734 my $data = $id_properties->[$n+1];
735 if (ref($data)) {
736 $old_class_desc->{id_implied}->{$name} ||= $data;
737 if (my $obj_ids = $data->{id_by}) {
738 push @replacement, (ref($obj_ids) ? @$obj_ids : ($obj_ids));
739 }
740 else {
741 push @replacement, $name;
742 }
743 $n++;
744 }
745 else {
746 $old_class_desc->{id_implied}->{$name} ||= {};
747 push @replacement, $name;
748 }
749 $old_class_desc->{id_implied}->{$name}->{'position_in_module_header'} = $pos++;
750 }
751 @$id_properties = @replacement;
752 }
753  
754 # Given several different kinds of input, convert it into an arrayref
755 sub _massage_field_into_arrayref {
756 my($class_desc, $field_name) = @_;
757  
758 my $value = $class_desc->{$field_name};
759 my $reftype = ref $value;
760 if (! exists $class_desc->{$field_name}) {
761 $class_desc->{$field_name} = [];
762  
763 } elsif (! $reftype) {
764 # It's a plain string, wrap it in an arrayref
765 $class_desc->{$field_name} = [ $value ];
766  
767 } elsif ($reftype eq 'HASH') {
768 # Later code expects it to be a listref - convert it
769 $class_desc->{$field_name} = [ %$value ];
770  
771 } elsif ($reftype ne 'ARRAY') {
772 my $class_name = $class_desc->{class_name};
773 Carp::croak "$class_name cannot initialize because its $field_name section is not a string, arrayref or hashref";
774  
775 }
776 }
777  
778 sub _normalize_property_descriptions_during_normalize_class_description {
779 my($class, $new_class) = @_;
780  
781 my $instance_properties = $new_class->{has};
782  
783 # normalize the data behind the property descriptions
784 my @property_names = keys %$instance_properties;
785 for my $property_name (@property_names) {
786 my %old_property = %{ $instance_properties->{$property_name} };
787 my %new_property = $class->_normalize_property_description1($property_name, \%old_property, $new_class);
788 %new_property = $class->_normalize_property_description2(\%new_property, $new_class);
789 $instance_properties->{$property_name} = \%new_property;
790 }
791  
792 # Find 'via' properties where the to is '-filter' and rewrite them to
793 # copy some attributes from the source property
794 # This feels like a hack, but it makes other parts of the system easier by
795 # not having to deal with -filter
796 foreach my $property_name ( @property_names ) {
797 my $property_data = $instance_properties->{$property_name};
798 if ($property_data->{'to'} && $property_data->{'to'} eq '-filter') {
799 my $via = $property_data->{'via'};
800 my $via_property_data = $instance_properties->{$via};
801 unless ($via_property_data) {
802 my $class_name = $new_class->{class_name};
803 Carp::croak "Cannot initialize class $class_name: Property '$property_name' filters '$via', but there is no property '$via'.";
804 }
805  
806 $property_data->{'data_type'} = $via_property_data->{'data_type'};
807 $property_data->{'reverse_as'} = $via_property_data->{'reverse_as'};
808 if ($via_property_data->{'where'}) {
809 unshift @{$property_data->{'where'}}, @{$via_property_data->{'where'}};
810 }
811 }
812 }
813  
814 # Catch a mistake in the class definition where a property is 'via'
815 # something, and its 'to' is the same as the via's reverse_as. This
816 # ends up being a circular definition and generates junk SQL
817 foreach my $property_name ( @property_names ) {
818 my $property_data = $instance_properties->{$property_name};
819 my $via = $property_data->{'via'};
820 my $to = $property_data->{'to'};
821 if (defined($via) and defined($to)) {
822 my $via_property_data = $instance_properties->{$via};
823 next unless ($via_property_data and $via_property_data->{'reverse_as'});
824 if ($via_property_data->{'reverse_as'} eq $to) {
825 my $class_name = $new_class->{class_name};
826 Carp::croak("Cannot initialize class $class_name: Property '$property_name' defines "
827 . "an incompatible relationship. Its 'to' is the same as reverse_as for property '$via'");
828 }
829 }
830 }
831 }
832  
833 sub _process_class_definition_property_keys {
834 my($old_class, $new_class) = @_;
835  
836 my($class_name, $instance_properties, $meta_properties) = @$new_class{'class_name', 'has','attributes_have'};
837 $class_name ||= $new_class->{role_name}; # This is used by role construction, too
838  
839 # Flatten and format the property list(s) in the class description.
840 # NOTE: we normalize the details at the end of normalizing the class description.
841 my @keys = _class_definition_property_keys_in_processing_order($old_class);
842 foreach my $key ( @keys ) {
843 # parse the key to see if we're looking at instance or meta attributes,
844 # and take the extra words as additional attribute meta-data.
845 my @added_property_meta;
846 my $properties;
847 if ($key =~ /has/) {
848 @added_property_meta =
849 grep { $_ ne 'has' } split(/[_-]/,$key);
850 $properties = $instance_properties;
851 }
852 elsif ($key =~ /attributes_have/) {
853 @added_property_meta =
854 grep { $_ ne 'attributes' and $_ ne 'have' } split(/[_-]/,$key);
855 $properties = $meta_properties;
856 }
857 elsif ($key eq 'id_implied') {
858 # these are additions to the regular "has" list from complex identity properties
859 $properties = $instance_properties;
860 }
861 else {
862 die "Odd key $key?";
863 }
864 @added_property_meta = map { 'is_' . $_ => 1 } @added_property_meta;
865  
866 # the property data can be a string, array, or hash as they come in
867 # convert string, hash and () into an array
868 my $property_data = delete $old_class->{$key};
869  
870 my @tmp;
871 if (!ref($property_data)) {
872 if (defined($property_data)) {
873 @tmp = split(/\s+/, $property_data);
874 }
875 else {
876 @tmp = ();
877 }
878 }
879 elsif (ref($property_data) eq 'HASH') {
880 @tmp = map {
881 ($_ => $property_data->{$_})
882 } sort keys %$property_data;
883 }
884 elsif (ref($property_data) eq 'ARRAY') {
885 @tmp = @$property_data;
886 }
887 else {
888 die "Unrecognized data $property_data appearing as property list!";
889 }
890  
891 # process the array of property specs
892 my $pos = 0;
893 while (my $name = shift @tmp) {
894 my $params;
895 if (ref($tmp[0])) {
896 $params = shift @tmp;
897 unless (ref($params) eq 'HASH') {
898 my $seen_type = ref($params);
899 Carp::confess("class $class_name property $name has a $seen_type reference instead of a hashref describing its meta-attributes!");
900 }
901 %$params = (@added_property_meta, %$params) if @added_property_meta;
902 }
903 else {
904 $params = { @added_property_meta };
905 }
906  
907 unless (exists $params->{'position_in_module_header'}) {
908 $params->{'position_in_module_header'} = $pos++;
909 }
910 unless (exists $params->{is_specified_in_module_header}) {
911 $params->{is_specified_in_module_header} = $class_name . '::' . $key;
912 }
913  
914 # Indirect properties can mention the same property name more than once. To
915 # avoid stomping over existing property data with this other property data,
916 # merge the new info into the existing hash. Otherwise, the new property name
917 # gets an empty hash of info
918 if ($properties->{$name}) {
919 # this property already exists, but is also implied by some other property which added it to the end of the listed
920 # extend the existing definition
921 foreach my $key ( keys %$params ) {
922 next if ($key eq 'is_specified_in_module_header' || $key eq 'position_in_module_header');
923 # once a property gets set to is_optional => 0, it stays there, even if it's later set to 1
924 next if ($key eq 'is_optional'
925 and
926 exists($properties->{$name}->{'is_optional'})
927 and
928 defined($properties->{$name}->{'is_optional'})
929 and
930 $properties->{$name}->{'is_optional'} == 0);
931 $properties->{$name}->{$key} = $params->{$key};
932 }
933 $params = $properties->{$name};
934 } else {
935 $properties->{$name} = $params;
936 }
937  
938 # a single calculate_from can be a simple string, convert to a listref
939 if (my $calculate_from = $params->{'calculate_from'}) {
940 $params->{'calculate_from'} = [ $calculate_from ] unless (ref($calculate_from) eq 'ARRAY');
941 }
942  
943 if (my $id_by = $params->{id_by}) {
944 $id_by = [ $id_by ] unless ref($id_by) eq 'ARRAY';
945 my @id_by_names;
946 while (@$id_by) {
947 my $id_name = shift @$id_by;
948 my $params2;
949 if (ref($id_by->[0])) {
950 $params2 = shift @$id_by;
951 }
952 else {
953 $params2 = {};
954 }
955 for my $p (@UR::Object::Type::meta_id_ref_shared_properties) {
956 if (exists $params->{$p}) {
957 $params2->{$p} = $params->{$p};
958 }
959 }
960 $params2->{implied_by} = $name;
961 $params2->{is_specified_in_module_header} = 0;
962  
963 push @id_by_names, $id_name;
964 push @tmp, $id_name, $params2;
965 }
966 $params->{id_by} = \@id_by_names;
967 }
968  
969 if (my $id_class_by = $params->{'id_class_by'}) {
970 if (ref $id_class_by) {
971 Carp::croak("Cannot initialize class $class_name: "
972 . "Property $name has an 'id_class_by' that is not a plain string");
973 }
974 push @tmp, $id_class_by, { implied_by => $name, is_specified_in_module_header => 0 };
975 }
976  
977 } # next property in group
978  
979 # id-by properties' metadata can influence the id-ed-by property metadata
980 for my $pdata (values %$properties) {
981 next unless $pdata->{id_by};
982 for my $id_property (@{ $pdata->{id_by} }) {
983 my $id_pdata = $properties->{$id_property};
984 for my $p (@UR::Object::Type::meta_id_ref_shared_properties) {
985 if (exists $id_pdata->{$p} xor exists $pdata->{$p}) {
986 # if one or the other specifies a value, copy it to the one that's missing
987 $id_pdata->{$p} = $pdata->{$p} = $id_pdata->{$p} || $pdata->{$p};
988 } elsif (!exists $id_pdata->{$p} and !exists $pdata->{$p} and exists $UR::Object::Property::defaults{$p}) {
989 # if neither has a value, use the default for both
990 $id_pdata->{$p} = $pdata->{$p} = $UR::Object::Property::defaults{$p};
991 }
992 }
993 }
994 }
995  
996 }
997 }
998  
999 sub compose_roles {
1000 my($class, $desc) = @_;
1001  
1002 UR::Role::Prototype->_apply_roles_to_class_desc($desc);
1003 $class->_normalize_property_descriptions_during_normalize_class_description($desc);
1004 }
1005  
1006 # Return the order to process the has, has_optional, has_constant, etc keys
1007 sub _class_definition_property_keys_in_processing_order {
1008 my $class_hashref = shift;
1009  
1010 my @order;
1011  
1012 # we want to hit 'id_implied' first to preserve position_ and is_specified_ keys
1013 push(@order, 'id_implied') if exists $class_hashref->{id_implied};
1014  
1015 # 'has' next so is_optional can get set to 0 in case the same property also appears in has_optional
1016 push(@order, 'has') if exists $class_hashref->{has};
1017  
1018 # everything else
1019 push @order, grep { /has_|attributes_have/ } keys %$class_hashref;
1020  
1021 return @order;
1022 }
1023  
1024  
1025  
1026 sub _normalize_property_description1 {
1027 my $class = shift;
1028 my $property_name = shift;
1029 my $property_data = shift;
1030 my $class_data = shift || $class;
1031 my $class_name = $class_data->{class_name};
1032 my %old_property = %$property_data;
1033 my %new_class = %$class_data;
1034  
1035 if (exists $old_property{unrecognized_meta_attributes}) {
1036 %old_property = (%{delete $old_property{unrecognized_meta_attributes}}, %old_property);
1037 }
1038  
1039 delete $old_property{source};
1040  
1041 if ($old_property{implied_by} and $old_property{implied_by} eq $property_name) {
1042 $class->warning_message("Cleaning up odd self-referential 'implied_by' on $class_name $property_name");
1043 delete $old_property{implied_by};
1044 }
1045  
1046 # Only 1 of is_abstract, is_concrete or is_final may be set
1047 {
1048 no warnings 'uninitialized';
1049 my $modifier_sum = $old_property{is_abstract}
1050 + $old_property{is_concrete}
1051 + $old_property{is_final};
1052  
1053 if ($modifier_sum > 1) {
1054 Carp::confess("abstract/concrete/final are mutually exclusive. Error in class definition for $class_name property $property_name!");
1055 } elsif ($modifier_sum == 0) {
1056 $old_property{is_concrete} = 1;
1057 }
1058 }
1059  
1060 my %new_property = (
1061 class_name => $class_name,
1062 property_name => $property_name,
1063 );
1064  
1065 for my $mapping (
1066 [ property_type => qw/resolution/],
1067 [ class_name => qw//],
1068 [ property_name => qw//],
1069 [ column_name => qw/sql/],
1070 [ constraint_name => qw//],
1071 [ data_length => qw/len/],
1072 [ data_type => qw/type is isa is_a/],
1073 [ calculated_default => qw//],
1074 [ default_value => qw/default value/],
1075 [ valid_values => qw//],
1076 [ example_values => qw//],
1077 [ doc => qw/description/],
1078 [ is_optional => qw/is_nullable nullable optional/],
1079 [ is_transient => qw//],
1080 [ is_volatile => qw//],
1081 [ is_constant => qw//],
1082 [ is_classwide => qw/is_class_wide/],
1083 [ is_delegated => qw//],
1084 [ is_calculated => qw//],
1085 [ is_mutable => qw//],
1086 [ is_transactional => qw//],
1087 [ is_abstract => qw//],
1088 [ is_concrete => qw//],
1089 [ is_final => qw//],
1090 [ is_many => qw//],
1091 [ is_deprecated => qw//],
1092 [ is_undocumented => qw//],
1093 [ is_numeric => qw//],
1094 [ is_id => qw//],
1095 [ id_by => qw//],
1096 [ id_class_by => qw//],
1097 [ specify_by => qw//],
1098 [ order_by => qw//],
1099 [ access_as => qw//],
1100 [ via => qw//],
1101 [ to => qw//],
1102 [ where => qw/restrict filter/],
1103 [ implied_by => qw//],
1104 [ calculate => qw//],
1105 [ calculate_from => qw//],
1106 [ calculate_perl => qw/calc_perl/],
1107 [ calculate_sql => qw/calc_sql/],
1108 [ calculate_js => qw//],
1109 [ reverse_as => qw/reverse_id_by im_its/],
1110 [ is_legacy_eav => qw//],
1111 [ is_dimension => qw//],
1112 [ is_specified_in_module_header => qw//],
1113 [ position_in_module_header => qw//],
1114 [ singular_name => qw//],
1115 [ plural_name => qw//],
1116 ) {
1117 my $primary_field_name = $mapping->[0];
1118  
1119 my $found_key;
1120 foreach my $key ( @$mapping ) {
1121 if (exists $old_property{$key}) {
1122 if ($found_key) {
1123 my @keys = grep { exists $old_property{$_} } @$mapping;
1124 Carp::croak("Invalid class definition for $class_name in property '$property_name'. The keys "
1125 . join(', ',$found_key,@keys) . " are all synonyms for $primary_field_name");
1126 }
1127 $found_key = $key;
1128 }
1129 }
1130  
1131 if ($found_key) {
1132 $new_property{$primary_field_name} = delete $old_property{$found_key};
1133 } elsif (exists $UR::Object::Property::defaults{$primary_field_name}) {
1134 $new_property{$primary_field_name} = $UR::Object::Property::defaults{$primary_field_name};
1135 }
1136 }
1137  
1138 if (my $data = delete $old_property{delegate}) {
1139 if ($data->{via} =~ /^eav_/ and $data->{to} eq 'value') {
1140 $new_property{is_legacy_eav} = 1;
1141 }
1142 else {
1143 die "Odd delegation for $property_name: "
1144 . Data::Dumper::Dumper($data);
1145 }
1146 }
1147  
1148 if ($new_property{default_value} && $new_property{calculated_default}) {
1149 die qq(Can't initialize class $class_name: Property '$new_property{property_name}' has both default_value and calculated_default specified.);
1150 }
1151  
1152 if ($new_property{calculated_default}) {
1153 if ($new_property{calculated_default} eq 1) {
1154 $new_property{calculated_default} = '__default_' . $new_property{property_name} . '__';
1155 }
1156  
1157 my $ref = ref $new_property{calculated_default};
1158 if ($ref and $ref ne 'CODE') {
1159 die qq(Can't initialize class $class_name: Property '$new_property{property_name}' has calculated_default specified as a $ref ref but it must be a method name or coderef.);
1160 }
1161  
1162 unless ($ref) {
1163 my $method = $class_name->can($new_property{calculated_default});
1164 unless ($method) {
1165 die qq(Can't initialize class $class_name: Property '$new_property{property_name}' has calculated_default specified as '$new_property{calculated_default}' but method does not exist.);
1166 }
1167 $new_property{calculated_default} = $method;
1168 }
1169 }
1170  
1171 if ($new_property{id_by} && $new_property{reverse_as}) {
1172 die qq(Can't initialize class $class_name: Property '$new_property{property_name}' has both id_by and reverse_as specified.);
1173 }
1174  
1175 if ($new_property{data_type}) {
1176 if (my (undef, $length) = $new_property{data_type} =~ m/(\s*)\((\d+)\)$/) {
1177 $new_property{data_length} = $length;
1178 }
1179 if ($new_property{data_type} =~ m/[^\w:]/
1180 and
1181 (!ref($new_property{data_type}) or !$new_property{data_type}->isa('UR::Role::Param'))
1182 ) {
1183 Carp::croak("Can't initialize class $class_name: Property '" . $new_property{property_name}
1184 . "' has metadata for is/data_type that does not look like a class name ($new_property{data_type})");
1185 }
1186 }
1187  
1188 if (%old_property) {
1189 $new_property{unrecognized_meta_attributes} = \%old_property;
1190 %new_property = (%old_property, %new_property);
1191 }
1192  
1193 return %new_property;
1194 }
1195  
1196 sub _normalize_property_description2 {
1197 my $class = shift;
1198 my $property_data = shift;
1199 my $class_data = shift || $class;
1200  
1201 my $property_name = $property_data->{property_name};
1202 my $class_name = $property_data->{class_name};
1203  
1204 my %new_property = %$property_data;
1205 my %new_class = %$class_data;
1206  
1207 if (grep { $_ ne 'is_calculated' && $_ ne 'calculated_default' && /calc/ } keys %new_property) {
1208 $new_property{is_calculated} = 1;
1209 }
1210  
1211 if ($new_property{via}
1212 || $new_property{to}
1213 || $new_property{id_by}
1214 || $new_property{reverse_as}
1215 ) {
1216 $new_property{is_delegated} = 1;
1217 if (defined $new_property{via} and not defined $new_property{to}) {
1218 $new_property{to} = $property_name;
1219 }
1220 }
1221  
1222 if (!defined($new_property{is_mutable})) {
1223 if ($new_property{is_delegated}
1224 or
1225 (defined $class_data->{'subclassify_by'} and $class_data->{'subclassify_by'} eq $property_name)
1226 ) {
1227 $new_property{is_mutable} = 0;
1228 }
1229 else {
1230 $new_property{is_mutable} = 1;
1231 }
1232 }
1233  
1234 # For classes that have (or pretend to have) tables, the Property objects
1235 # should get their column_name property automatically filled in
1236 my $the_data_source;
1237 if (ref($new_class{'data_source_id'}) eq 'HASH') {
1238 # This is an inline-defined data source
1239 $the_data_source = $new_class{'data_source_id'}->{'is'};
1240 } elsif ($new_class{'data_source_id'}) {
1241 $the_data_source = $new_class{'data_source_id'};
1242 # using local() here to save $@ doesn't work. You end up with the
1243 # error "Unknown error" if one of the parent classes of the data source has
1244 # some kind of problem
1245 my $dollarat = $@;
1246 $@ = '';
1247 $the_data_source = UR::DataSource->get($the_data_source) || eval { $the_data_source->get() };
1248 unless ($the_data_source) {
1249 my $error = "Can't resolve data source from value '"
1250 . $new_class{'data_source_id'}
1251 . "' in class definition for $class_name";
1252 if ($@) {
1253 $error .= "\n$@";
1254 }
1255 Carp::croak($error);
1256 }
1257 $@ = $dollarat;
1258 }
1259 # UR::DataSource::File-backed classes don't have table_names, but for querying/saving to
1260 # work property, their properties still have to have column_name filled in
1261 if (($new_class{table_name} or ($the_data_source and ($the_data_source->initializer_should_create_column_name_for_class_properties())))
1262 and not exists($new_property{column_name}) # They didn't supply a column_name
1263 and not $new_property{is_transient}
1264 and not $new_property{is_delegated}
1265 and not $new_property{is_calculated}
1266 and not $new_property{is_legacy_eav}
1267 ) {
1268 $new_property{column_name} = $new_property{property_name};
1269 if ($the_data_source and $the_data_source->table_and_column_names_are_upper_case) {
1270 $new_property{column_name} = uc($new_property{column_name});
1271 }
1272 }
1273  
1274 if ($new_property{order_by} and not $new_property{is_many}) {
1275 die "Cannot use order_by except on is_many properties!";
1276 }
1277  
1278 if ($new_property{specify_by} and not $new_property{is_many}) {
1279 die "Cannot use specify_by except on is_many properties!";
1280 }
1281  
1282 if ($new_property{implied_by} and $new_property{implied_by} eq $property_name) {
1283 $class->warnings_message("New data has odd self-referential 'implied_by' on $class_name $property_name!");
1284 delete $new_property{implied_by};
1285 }
1286  
1287 return %new_property;
1288 }
1289  
1290  
1291 sub _make_minimal_class_from_normalized_class_description {
1292 my $class = shift;
1293 my $desc = shift;
1294  
1295 my $class_name = $desc->{class_name};
1296 unless ($class_name) {
1297 Carp::confess("No class name specified?");
1298 }
1299  
1300 my $meta_class_name = $desc->{meta_class_name};
1301 die unless $meta_class_name;
1302 if ($meta_class_name ne __PACKAGE__) {
1303 unless (
1304 $meta_class_name->isa(__PACKAGE__)
1305 ) {
1306 warn "Bogus meta class $meta_class_name doesn't inherit from UR::Object::Type?"
1307 }
1308 }
1309  
1310 # only do this when the classes match
1311 # when they do not match, the super-class has already called this by delegating to the correct subclass
1312 $class_name::VERSION = 2.0; # No BumpVersion
1313  
1314 my $self = bless { id => $class_name, %$desc }, $meta_class_name;
1315  
1316 $UR::Context::all_objects_loaded->{$meta_class_name}{$class_name} = $self;
1317 my $full_name = join( '::', $class_name, '__meta__' );
1318 Sub::Install::reinstall_sub({
1319 into => $class_name,
1320 as => '__meta__',
1321 code => Sub::Name::subname $full_name => sub {$self},
1322 });
1323  
1324 return $self;
1325 }
1326  
1327 sub _initialize_accessors_and_inheritance {
1328 my $self = shift;
1329  
1330 $self->initialize_direct_accessors;
1331  
1332 my $class_name = $self->{class_name};
1333  
1334 my @is = @{ $self->{is} };
1335 unless (@is) {
1336 @is = ('UR::ModuleBase')
1337 }
1338 eval "\@${class_name}::ISA = (" . join(',', map { "'$_'" } @is) . ")\n";
1339 Carp::croak("Can't initialize \@ISA for class_name '$class_name': $@\nMaybe the class_name or one of the parent classes are not valid class names") if $@;
1340  
1341 my $namespace_mro;
1342 my $namespace_name = $self->{namespace};
1343 if (
1344 !$bootstrapping
1345 && !$class_name->isa('UR::Namespace')
1346 && $namespace_name
1347 && $namespace_name->isa('UR::Namespace')
1348 && $namespace_name->can('get')
1349 && (my $namespace = $namespace_name->get())
1350 ) {
1351 $namespace_mro = $namespace->method_resolution_order;
1352 }
1353  
1354 if ($^V lt v5.9.5 && $namespace_mro && $namespace_mro eq 'c3') {
1355 warn "C3 method resolution order is not supported on Perl < 5.9.5. Reverting $namespace_name namespace to DFS.";
1356 my $namespace = $namespace_name->get();
1357 $namespace_mro = $namespace->method_resolution_order('dfs');
1358 }
1359  
1360 if ($^V ge v5.9.5 && $namespace_mro && mro::get_mro($class_name) ne $namespace_mro) {
1361 mro::set_mro($class_name, $namespace_mro);
1362 }
1363  
1364 return $self;
1365 }
1366  
1367 our %_init_subclasses_loaded;
1368 sub subclasses_loaded {
1369 return @{ $_init_subclasses_loaded{shift->class_name}};
1370 }
1371  
1372 our %_inform_all_parent_classes_of_newly_loaded_subclass;
1373 sub _inform_all_parent_classes_of_newly_loaded_subclass {
1374 my $self = shift;
1375 my $class_name = $self->class_name;
1376  
1377 Carp::confess("re-initializing class $class_name") if $_inform_all_parent_classes_of_newly_loaded_subclass{$class_name};
1378 $_inform_all_parent_classes_of_newly_loaded_subclass{$class_name} = 1;
1379  
1380 no strict 'refs';
1381 no warnings;
1382 my @parent_classes = @{ $class_name . "::ISA" };
1383 for my $parent_class (@parent_classes) {
1384 unless ($parent_class->can("id")) {
1385 __PACKAGE__->use_module_with_namespace_constraints($parent_class);
1386 if ($@) {
1387 die "Failed to find parent_class $parent_class for $class_name!";
1388 }
1389 }
1390 }
1391  
1392 my @i = sort $class_name->inheritance;
1393 $_init_subclasses_loaded{$class_name} ||= [];
1394 my $last_parent_class = "";
1395 for my $parent_class (@i) {
1396 next if $parent_class eq $last_parent_class;
1397  
1398 $last_parent_class = $parent_class;
1399 $_init_subclasses_loaded{$parent_class} ||= [];
1400 push @{ $_init_subclasses_loaded{$parent_class} }, $class_name;
1401 push @{ $parent_class . "::_init_subclasses_loaded" }, $class_name;
1402  
1403 # any index on a parent class must move to the child class
1404 # if the child class were loaded before the index is made, it is pushed down at index creation time
1405 if (my $parent_index_hashrefs = $UR::Object::Index::all_by_class_name_and_property_name{$parent_class}) {
1406 #print "PUSHING INDEXES FOR $parent_class to $class_name\n";
1407 for my $parent_property (keys %$parent_index_hashrefs) {
1408 my $parent_indexes = $parent_index_hashrefs->{$parent_property};
1409 my $indexes = $UR::Object::Index::all_by_class_name_and_property_name{$class_name}{$parent_property} ||= [];
1410 push @$indexes, @$parent_indexes;
1411 }
1412 }
1413 }
1414  
1415 return 1;
1416 }
1417  
1418 sub _inform_roles_of_new_class {
1419 my $self = shift;
1420  
1421 foreach my $role_obj ( @{ $self->{roles} } ) {
1422 my $package = $role_obj->role_name;
1423 next unless my $import = $package->can('__import__');
1424 $import->($package, $self);
1425 }
1426 }
1427  
1428 sub _complete_class_meta_object_definitions {
1429 my $self = shift;
1430  
1431 # track related objects
1432 my @subordinate_objects;
1433  
1434 # grab some data from the object
1435 my $class_name = $self->{class_name};
1436 my $table_name = $self->{table_name};
1437  
1438 # decompose the embedded complex data structures into normalized objects
1439 my $inheritance = $self->{is};
1440 my $properties = $self->{has};
1441 my $relationships = $self->{relationships} || [];
1442 my $constraints = $self->{constraints};
1443 my $data_source = $self->{'data_source_id'};
1444  
1445 my $id_properties = $self->{id_by};
1446 my %id_property_rank;
1447 for (my $i = '0 but true'; $i < @$id_properties; $i++) {
1448 $id_property_rank{$id_properties->[$i]} = $i;
1449 }
1450  
1451 # mark id/non-id properites
1452 foreach my $pinfo ( values %$properties ) {
1453 $pinfo->{'is_id'} = $id_property_rank{$pinfo->{'property_name'}};
1454 }
1455  
1456 # handle inheritance
1457 unless ($class_name eq "UR::Object") {
1458 no strict 'refs';
1459  
1460 # sanity check
1461 my @expected = @$inheritance;
1462 my @actual = @{ $class_name . "::ISA" };
1463  
1464 if (@actual and "@actual" ne "@expected") {
1465 Carp::confess("for $class_name: expected '@expected' actual '@actual'\n");
1466 }
1467  
1468 # set
1469 @{ $class_name . "::ISA" } = @$inheritance;
1470 }
1471  
1472 if (not $data_source and $class_name->can("__load__")) {
1473 # $data_source = UR::DataSource::Default->__define__;
1474 $data_source = $self->{data_source_id} = $self->{db_committed}->{data_source_id} = 'UR::DataSource::Default';
1475 }
1476  
1477 # Create inline data source
1478 if ($data_source and ref($data_source) eq 'HASH') {
1479 $self->{'__inline_data_source_data'} = $data_source;
1480 my $ds_class = $data_source->{'is'};
1481 my $inline_ds = $ds_class->create_from_inline_class_data($self, $data_source);
1482 $self->{'data_source_id'} = $self->{'db_committed'}->{'data_source_id'} = $inline_ds->id;
1483 }
1484  
1485
1486 if ($self->{'data_source_id'} and !defined($self->{table_name})) {
1487 my $data_source_obj = UR::DataSource->get($self->{'data_source_id'}) || eval { $self->{'data_source_id'}->get() };
1488 if ($data_source_obj and $data_source_obj->initializer_should_create_column_name_for_class_properties() ) {
1489 $self->{table_name} = '__default__';
1490 }
1491 }
1492  
1493 for my $parent_class_name (@$inheritance) {
1494 my $parent_class = $parent_class_name->__meta__;
1495 unless ($parent_class) {
1496 #$DB::single = 1;
1497 $parent_class = $parent_class_name->__meta__;
1498 $self->error_message("Failed to find parent class $parent_class_name\n");
1499 return;
1500 }
1501  
1502 # These class meta values get propogated from parent to child
1503 foreach my $inh_property ( qw(schema_name data_source_id) ) {
1504 if (not defined ($self->$inh_property)) {
1505 if (my $inh_value = $parent_class->$inh_property) {
1506 $self->{$inh_property} = $self->{'db_committed'}->{$inh_property} = $inh_value;
1507 }
1508 }
1509 }
1510  
1511 # For classes with no data source, the default for id_generator is -urinternal
1512 # For classes with a data source, autogenerate_new_object_id_for_class_name_and_rule gets called
1513 # on that data source which can use id_generator as it sees fit
1514 if (! defined $self->{id_generator}) {
1515 my $id_generator;
1516 if ($self->{data_source_id}) {
1517 if ($parent_class->data_source_id
1518 and
1519 $parent_class->data_source_id eq $self->data_source_id
1520 ) {
1521 $id_generator = $parent_class->id_generator;
1522 }
1523 } else {
1524 $id_generator = $parent_class->id_generator;
1525 }
1526 $self->{id_generator} = $self->{'db_committed'}->{id_generator} = $id_generator;
1527 }
1528  
1529  
1530 # If a parent is declared as a singleton, we are too.
1531 # This only works for abstract singletons.
1532 if ($parent_class->is_singleton and not $self->is_singleton) {
1533 $self->is_singleton($parent_class->is_singleton);
1534 }
1535 }
1536  
1537 # when we "have" an object reference, add it to the list of old-style references
1538 # also ensure the old-style property definition is complete
1539 for my $pinfo (grep { $_->{id_by} } values %$properties) {
1540 push @$relationships, $pinfo->{property_name}, $pinfo;
1541  
1542 my $id_properties = $pinfo->{id_by};
1543 my $r_class_name = $pinfo->{data_type};
1544 unless($r_class_name) {
1545 die sprintf("Object accessor property definition for %s::%s has an 'id_by' but no 'data_type'",
1546 $pinfo->{'class_name'}, $pinfo->{'property_name'});
1547 }
1548 my $r_class;
1549 my @r_id_properties;
1550  
1551 for (my $n=0; $n<@$id_properties; $n++) {
1552 my $id_property_name = $id_properties->[$n];
1553 my $id_property_detail = $properties->{$id_property_name};
1554 unless ($id_property_detail) {
1555 #$DB::single = 1;
1556 1;
1557 }
1558  
1559 # No data_type specified, first try parent classes for the same property name
1560 # and use their type
1561 if (!$bootstrapping and !exists($id_property_detail->{data_type})) {
1562 if (my $inh_prop = ($self->ancestry_property_metas(property_name => $id_property_name))[0]) {
1563 $id_property_detail->{data_type} = $inh_prop->data_type;
1564 }
1565 }
1566  
1567 # Didn't find one - use the data type of the ID property(s) in the class we point to
1568 unless ($id_property_detail->{data_type}) {
1569 unless ($r_class) {
1570 # FIXME - it'd be nice if we didn't have to load the remote class here, and
1571 # instead put off loading until it's necessary
1572 $r_class ||= UR::Object::Type->get($r_class_name);
1573 unless ($r_class) {
1574 Carp::confess("Unable to load $r_class_name while defining relationship ".$pinfo->{'property_name'}. " in class $class_name");
1575 }
1576 @r_id_properties = $r_class->id_property_names;
1577 }
1578 my ($r_property) =
1579 map {
1580 my $r_class_ancestor = UR::Object::Type->get($_);
1581 my $data = $r_class_ancestor->{has}{$r_id_properties[$n]};
1582 ($data ? ($data) : ());
1583 }
1584 ($r_class_name, $r_class_name->__meta__->ancestry_class_names);
1585 unless ($r_property) {
1586 #$DB::single = 1;
1587 my $property_name = $pinfo->{'property_name'};
1588 if (@$id_properties != @r_id_properties) {
1589 Carp::croak("Can't resolve relationship for class $class_name property '$property_name': "
1590 . "id_by metadata has " . scalar(@$id_properties) . " items, but remote class "
1591 . "$r_class_name only has " . scalar(@r_id_properties) . " ID properties\n");
1592 } else {
1593 my $r_id_property = $r_id_properties[$n] ? "'$r_id_properties[$n]'" : '(undef)';
1594 Carp::croak("Can't resolve relationship for class $class_name property '$property_name': "
1595 . "Class $r_class_name does not have an ID property named $r_id_property, "
1596 . "which would be linked to the local property '".$id_properties->[$n]."'\n");
1597 }
1598 }
1599 $id_property_detail->{data_type} = $r_property->{data_type};
1600 }
1601 }
1602 next;
1603 }
1604  
1605 # make old-style (bc4nf) property objects in the default way
1606 my %property_objects;
1607  
1608 for my $pinfo (values %$properties) {
1609 my $property_name = $pinfo->{property_name};
1610 my $property_subclass = $pinfo->{property_subclass};
1611  
1612 # Acme::Employee::Attribute::Name is a bc6nf attribute
1613 # extends Acme::Employee::Attribute
1614 # extends UR::Object::Attribute
1615 # extends UR::Object
1616 my @words = map { ucfirst($_) } split(/_/,$property_name);
1617 #@words = $self->namespace->get_vocabulary->convert_to_title_case(@words);
1618 my $bridge_class_name =
1619 $class_name
1620 . "::Attribute::"
1621 . join('', @words);
1622  
1623 # Acme::Employee::Attribute::Name::Type is both the class definition for the bridge,
1624 # and also the attribute/property metadata for
1625 my $property_meta_class_name = $bridge_class_name . "::Type";
1626  
1627 # define a new class for the above, inheriting from UR::Object::Property
1628 # all of the "attributes_have" get put into the class definition
1629 # call the constructor below on that new class
1630 #UR::Object::Type->__define__(
1631 ## class_name => $property_meta_class_name,
1632 # is => 'UR::Object::Property', # TODO: go through the inheritance
1633 # has => [
1634 # @{ $class_name->__meta__->{attributes_have} }
1635 # ]
1636 #)
1637  
1638 my ($singular_name,$plural_name);
1639 unless ($pinfo->{plural_name} and $pinfo->{singular_name}) {
1640 require Lingua::EN::Inflect;
1641 if ($pinfo->{is_many}) {
1642 $plural_name = $pinfo->{plural_name} ||= $pinfo->{property_name};
1643 $pinfo->{singular_name} = Lingua::EN::Inflect::PL_V($plural_name);
1644 }
1645 else {
1646 $singular_name = $pinfo->{singular_name} ||= $pinfo->{property_name};
1647 $pinfo->{plural_name} = Lingua::EN::Inflect::PL($singular_name);
1648 }
1649 }
1650  
1651 my $property_object = UR::Object::Property->__define__(%$pinfo, id => $class_name . "\t" . $property_name);
1652  
1653 unless ($property_object) {
1654 $self->error_message("Error creating property $property_name for class " . $self->class_name . ": " . $class_name->error_message);
1655 for $property_object (@subordinate_objects) { $property_object->unload }
1656 $self->unload;
1657 return;
1658 }
1659  
1660 $property_objects{$property_name} = $property_object;
1661 push @subordinate_objects, $property_object;
1662 }
1663  
1664 if ($constraints) {
1665 my $property_rule_template = UR::BoolExpr::Template->resolve('UR::Object::Property','class_name','property_name');
1666  
1667 my $n = 1;
1668 for my $unique_set (sort { $a->{sql} cmp $b->{sql} } @$constraints) {
1669 my ($name,$properties,$group,$sql);
1670 if (ref($unique_set) eq "HASH") {
1671 $name = $unique_set->{name};
1672 $properties = $unique_set->{properties};
1673 $sql = $unique_set->{sql};
1674 $name ||= $sql;
1675 }
1676 else {
1677 $properties = @$unique_set;
1678 $name = '(unnamed)';
1679 $n++;
1680 }
1681 for my $property_name (sort @$properties) {
1682 my $prop_rule = $property_rule_template->get_rule_for_values($class_name,$property_name);
1683 my $property = $UR::Context::current->get_objects_for_class_and_rule('UR::Object::Property', $prop_rule);
1684 unless ($property) {
1685 Carp::croak("Constraint '$name' on class $class_name requires unknown property '$property_name'");
1686 }
1687 }
1688 }
1689 }
1690  
1691 for my $obj ($self,@subordinate_objects) {
1692 #use Data::Dumper;
1693 no strict;
1694 my %db_committed = %$obj;
1695 delete @db_committed{@keys_to_delete_from_db_committed};
1696 $obj->{'db_committed'} = \%db_committed;
1697  
1698 };
1699  
1700 unless ($self->generate) {
1701 $self->error_message("Error generating class " . $self->class_name . " as part of creation : " . $self->error_message);
1702 for my $property_object (@subordinate_objects) { $property_object->unload }
1703 $self->unload;
1704 return;
1705 }
1706  
1707 if (my $extra = $self->{extra}) {
1708 $self->_apply_extra_attrs_to_class_or_role($extra);
1709 }
1710  
1711 $self->__signal_change__("load");
1712  
1713  
1714 my @i = $class_name->inheritance;
1715  
1716 for my $parent_class_name (@i) {
1717 if ($parent_class_name->can('__signal_observers__')) {
1718 $parent_class_name->__signal_observers__('subclass_loaded', $class_name);
1719 }
1720 }
1721  
1722 # The inheritance method is high overhead because of the number of times it is called.
1723 # Cache on a per-class basis.
1724 if (grep { $_ eq '' } @i) {
1725 print "$class_name! @{ $self->{is} }";
1726 $class_name->inheritance;
1727 }
1728 Carp::confess("Odd inheritance @i for $class_name") unless $class_name->isa('UR::Object');
1729 my $src1 = " return shift->SUPER::inheritance(\@_) if ( (ref(\$_[0])||\$_[0]) ne '$class_name'); return (" . join(", ", map { "'$_'" } (@i)) . ")";
1730 my $src2 = qq|sub ${class_name}::inheritance { $src1 }|;
1731 eval $src2 unless $class_name eq 'UR::Object';
1732 die $@ if $@;
1733  
1734 $self->{'_property_meta_for_name'} = \%property_objects;
1735  
1736 # return the new class object
1737 return $self;
1738 }
1739  
1740 sub _apply_extra_attrs_to_class_or_role {
1741 my($self, $extra) = @_;
1742  
1743 if ($extra) {
1744 # some class characteristics may be only present in subclasses of UR::Object
1745 # we handle these at this point, since the above is needed for bootstrapping
1746 my %still_not_found;
1747 for my $key (sort keys %$extra) {
1748 if ($self->can($key)) {
1749 $self->$key($extra->{$key});
1750 }
1751 else {
1752 $still_not_found{$key} = $extra->{$key};
1753 }
1754 }
1755 if (%still_not_found) {
1756 my $kind = $self->isa('UR::Object::Type')
1757 ? 'Class'
1758 : 'Role';
1759 my $name = $self->id;
1760  
1761 $DB::single = 1;
1762 Carp::croak("Bad $kind defninition for $name. Unrecognized properties:\n\t"
1763 . join("\n\t", join(' => ', map { ($_, $still_not_found{$_}) } keys %still_not_found)));
1764 }
1765 }
1766  
1767  
1768 }
1769  
1770 # write the module from the existing data in the class object
1771 sub generate {
1772 my $self = shift;
1773 return 1 if $self->{'generated'};
1774  
1775 #my %params = @_; # Doesn't seem to be used below...
1776  
1777  
1778 # The follwing code will override a lot intentionally.
1779 # Supress the warning messages.
1780 no warnings;
1781  
1782 # the class that this object represents
1783 # the class that we're going to generate
1784 # the "new class"
1785 my $class_name = $self->class_name;
1786  
1787 # this is done earlier in the class definition process in _make_minimal_class_from_normalized_class_description()
1788 my $full_name = join( '::', $class_name, '__meta__' );
1789 Sub::Install::reinstall_sub({
1790 into => $class_name,
1791 as => '__meta__',
1792 code => Sub::Name::subname $full_name => sub {$self},
1793 });
1794  
1795 my @parent_class_names = $self->parent_class_names;
1796  
1797 do {
1798 no strict 'refs';
1799 if (@{ $class_name . '::ISA' }) {
1800 #print "already have isa for class_name $class_name: " . join(",",@{ $class_name . '::ISA' }) . "\n";
1801 }
1802 else {
1803 no strict 'refs';
1804 @{ $class_name . '::ISA' } = @parent_class_names;
1805 #print "setting isa for class_name $class_name: " . join(",",@{ $class_name . '::ISA' }) . "\n";
1806 };
1807 };
1808  
1809  
1810 my ($props, $cols) = ([], []); # for _all_properties_columns()
1811 $self->{_all_properties_columns} = [$props, $cols];
1812  
1813 my $id_props = []; # for _all_id_properties()
1814 $self->{_all_id_properties} = $id_props;
1815  
1816 # build the supplemental classes
1817 for my $parent_class_name (@parent_class_names) {
1818 next if $parent_class_name eq "UR::Object";
1819  
1820 if ($parent_class_name eq $class_name) {
1821 Carp::confess("$class_name has parent class list which includes itself?: @parent_class_names\n");
1822 }
1823  
1824 my $parent_class_meta = UR::Object::Type->get(class_name => $parent_class_name);
1825  
1826 unless ($parent_class_meta) {
1827 #$DB::single = 1;
1828 $parent_class_meta = UR::Object::Type->get(class_name => $parent_class_name);
1829 Carp::confess("Cannot generate $class_name: Failed to find class meta-data for base class $parent_class_name.");
1830 }
1831  
1832 unless ($parent_class_meta->generated()) {
1833 $parent_class_meta->generate();
1834 }
1835  
1836 unless ($parent_class_meta->{_all_properties_columns}) {
1837 Carp::confess("No _all_properties_columns for $parent_class_name?");
1838 }
1839  
1840 # inherit properties and columns
1841 my ($p, $c) = @{ $parent_class_meta->{_all_properties_columns} };
1842 push @$props, @$p if $p;
1843 push @$cols, @$c if $c;
1844 my $id_p = $parent_class_meta->{_all_id_properties};
1845 push @$id_props, @$id_p if $id_p;
1846 }
1847  
1848  
1849 # set up accessors/mutators for properties
1850 my @property_objects =
1851 UR::Object::Property->get(class_name => $self->class_name);
1852  
1853 my @id_property_objects = $self->direct_id_property_metas;
1854 my %id_property;
1855 for my $ipo (@id_property_objects) {
1856 $id_property{$ipo->property_name} = 1;
1857 }
1858  
1859 if (@id_property_objects) {
1860 $id_props = [];
1861 for my $ipo (@id_property_objects) {
1862 push @$id_props, $ipo->property_name;
1863 }
1864 }
1865  
1866 my $has_table;
1867 my @parent_classes = map { UR::Object::Type->get(class_name => $_) } @parent_class_names;
1868 for my $co ($self, @parent_classes) {
1869 if ($co->table_name) {
1870 $has_table = 1;
1871 last;
1872 }
1873 }
1874  
1875 my $data_source_obj = $self->data_source;
1876 my $columns_are_upper_case;
1877 if ($data_source_obj) {
1878 $columns_are_upper_case = $data_source_obj->table_and_column_names_are_upper_case;
1879 }
1880  
1881 my @sort_list = map { [$_->property_name, $_] } @property_objects;
1882 for my $sorted_item ( sort { $a->[0] cmp $b->[0] } @sort_list ) {
1883 my $property_object = $sorted_item->[1];
1884 if ($property_object->column_name) {
1885 push @$props, $property_object->property_name;
1886 push @$cols, $columns_are_upper_case ? uc($property_object->column_name) : $property_object->column_name;
1887 }
1888 }
1889  
1890 # set the flag to prevent this from occurring multiple times.
1891 $self->generated(1);
1892  
1893 # read in filesystem package if there is one
1894 #$self->use_filesystem_package($class_name);
1895  
1896 # Let each class in the inheritance hierarchy do any initialization
1897 # required for this class. Note that the _init_subclass method does
1898 # not call SUPER::, but relies on this code to find its parents. This
1899 # is the only way around a sparsely-filled multiple inheritance tree.
1900  
1901 # TODO: Replace with $class_name->EVERY::LAST::_init_subclass()
1902  
1903 #unless (
1904 # $bootstrapping
1905 # and
1906 # $UR::Object::_init_subclass->{$class_name}
1907 #)
1908 {
1909 my @inheritance = $class_name->inheritance;
1910 my %done;
1911 for my $parent (reverse @inheritance) {
1912 my $initializer = $parent->can("_init_subclass");
1913 next unless $initializer;
1914 next if $done{$initializer};
1915 $initializer->($class_name,$class_name)
1916 or die "Parent class $parent failed to initialize subclass "
1917 . "$class_name :" . $parent->error_message;
1918 $done{$initializer} = 1;
1919 }
1920 }
1921  
1922 unless ($class_name->isa("UR::Object")) {
1923 print Data::Dumper::Dumper('@C::ISA',\@C::ISA,'@B::ISA',\@B::ISA);
1924 }
1925  
1926 # ensure the class is generated
1927 die "Error in module for $class_name. Resulting class does not appear to be generated!" unless $self->generated;
1928  
1929 # ensure the class inherits from UR::Object
1930 die "$class_name does not inherit from UR::Object!" unless $class_name->isa("UR::Object");
1931  
1932 return 1;
1933 }
1934  
1935  
1936 1;
1937  
1938