| 1 | package UR::Context; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Sub::Name; | ||
| 6 | use Scalar::Util; | ||
| 7 | |||
| 8 | require UR; | ||
| 9 | our $VERSION = "0.46"; # UR $VERSION; | ||
| 10 | |||
| 11 | use UR::Context::ImportIterator; | ||
| 12 | use UR::Context::ObjectFabricator; | ||
| 13 | use UR::Context::LoadingIterator; | ||
| 14 | |||
| 15 | UR::Object::Type->define( | ||
| 16 | class_name => 'UR::Context', | ||
| 17 | is_abstract => 1, | ||
| 18 | has => [ | ||
| 19 | parent => { is => 'UR::Context', id_by => 'parent_id', is_optional => 1 }, | ||
| 20 | query_underlying_context => { is => 'Boolean', | ||
| 21 | is_optional => 1, | ||
| 22 | default_value => undef, | ||
| 23 | doc => 'Flag indicating whether the context must (1), must not (0) or may (undef) query underlying contexts when handling a query' }, | ||
| 24 | ], | ||
| 25 | valid_signals => [qw(precommit sync_databases commit prerollback rollback)], | ||
| 26 | doc => <<EOS | ||
| 27 | The environment in which all data examination and change occurs in UR. The current context represents the current | ||
| 28 | state of everything, and acts as a manager/intermediary between the current application and underlying database(s). | ||
| 29 | This is responsible for mapping object requests to database requests, managing caching, transaction | ||
| 30 | consistency, locking, etc. by delegating to the correct components to handle these tasks. | ||
| 31 | EOS | ||
| 32 | ); | ||
| 33 | |||
| 34 | our @CARP_NOT = qw( UR::Object::Iterator Class::AutoloadCAN ); | ||
| 35 | |||
| 36 | # These references all point to internal structures of the current process context. | ||
| 37 | # They are created here for boostrapping purposes, because they must exist before the object itself does. | ||
| 38 | our $all_objects_loaded ||= {}; # Master index of all tracked objects by class and then id. | ||
| 39 | our $all_change_subscriptions ||= {}; # Index of other properties by class, property_name, and then value. | ||
| 40 | our $all_objects_are_loaded ||= {}; # Track when a class informs us that all objects which exist are loaded. | ||
| 41 | our $all_params_loaded ||= {}; # Track parameters used to load by template_id then by rule_id | ||
| 42 | |||
| 43 | # These items are used by prune_object_cache() to control the cache size | ||
| 44 | our $all_objects_cache_size ||= 0; # count of the unloadable objects we've loaded from data sources | ||
| 45 | our $cache_last_prune_serial ||= 0; # serial number the last time we pruned objects | ||
| 46 | our $cache_size_highwater; # high water mark for cache size. Start pruning when $all_objects_cache_size goes over | ||
| 47 | our $cache_size_lowwater; # low water mark for cache size | ||
| 48 | our $GET_COUNTER = 1; # This is where the serial number for the __get_serial key comes from | ||
| 49 | our $light_cache = 0; # whether refs in all_objects_loaded should be weak | ||
| 50 | |||
| 51 | # For bootstrapping. | ||
| 52 | $UR::Context::current = __PACKAGE__; | ||
| 53 | |||
| 54 | # called by UR.pm during bootstraping | ||
| 55 | our $initialized = 0; | ||
| 56 | sub _initialize_for_current_process { | ||
| 57 | my $class = shift; | ||
| 58 | if ($initialized) { | ||
| 59 | die "Attempt to re-initialize the current process?"; | ||
| 60 | } | ||
| 61 | |||
| 62 | my $root_id = $ENV{UR_CONTEXT_ROOT} ||= 'UR::Context::DefaultRoot'; | ||
| 63 | $UR::Context::root = UR::Context::Root->get($root_id); | ||
| 64 | unless ($UR::Context::root) { | ||
| 65 | die "Failed to find root context object '$root_id':!? Odd value in environment variable UR_CONTEXT_ROOT?"; | ||
| 66 | } | ||
| 67 | |||
| 68 | if (my $base_id = $ENV{UR_CONTEXT_BASE}) { | ||
| 69 | $UR::Context::base = UR::Context::Process->get($base_id); | ||
| 70 | unless ($UR::Context::base) { | ||
| 71 | die "Failed to find base context object '$base_id':!? Odd value in environment variable UR_CONTEXT_BASE?"; | ||
| 72 | } | ||
| 73 | } | ||
| 74 | else { | ||
| 75 | $UR::Context::base = $UR::Context::root; | ||
| 76 | } | ||
| 77 | |||
| 78 | $UR::Context::process = UR::Context::Process->_create_for_current_process(parent_id => $UR::Context::base->id); | ||
| 79 | |||
| 80 | if (exists $ENV{'UR_CONTEXT_CACHE_SIZE_LOWWATER'} || exists $ENV{'UR_CONTEXT_CACHE_SIZE_HIGHWATER'}) { | ||
| 81 | $cache_size_highwater = $ENV{'UR_CONTEXT_CACHE_SIZE_HIGHWATER'} || 0; | ||
| 82 | $cache_size_lowwater = $ENV{'UR_CONTEXT_CACHE_SIZE_LOWWATER'} || 0; | ||
| 83 | manage_objects_may_go_out_of_scope(); | ||
| 84 | } | ||
| 85 | |||
| 86 | |||
| 87 | # This changes when we initiate in-memory transactions on-top of the basic, heavier weight one for the process. | ||
| 88 | $UR::Context::current = $UR::Context::process; | ||
| 89 | |||
| 90 | if (exists $ENV{'UR_CONTEXT_MONITOR_QUERY'}) { | ||
| 91 | $UR::Context::current->monitor_query($ENV{'UR_CONTEXT_MONITOR_QUERY'}); | ||
| 92 | } | ||
| 93 | |||
| 94 | $initialized = 1; | ||
| 95 | return $UR::Context::current; | ||
| 96 | } | ||
| 97 | |||
| 98 | # whether some UR objects might go out of scope, for example if pruning is on, | ||
| 99 | # light cache is on, or an AutoUnloadPool is alive | ||
| 100 | my $objects_may_go_out_of_scope = 0; | ||
| 101 | sub objects_may_go_out_of_scope { | ||
| 102 | if (@_) { | ||
| 103 | $objects_may_go_out_of_scope = shift; | ||
| 104 | } | ||
| 105 | return $objects_may_go_out_of_scope; | ||
| 106 | } | ||
| 107 | |||
| 108 | sub manage_objects_may_go_out_of_scope { | ||
| 109 | if ((defined($cache_size_highwater) and $cache_size_highwater > 0) | ||
| 110 | or | ||
| 111 | $light_cache | ||
| 112 | or | ||
| 113 | UR::Context::AutoUnloadPool->_pool_count | ||
| 114 | ) { | ||
| 115 | objects_may_go_out_of_scope(1); | ||
| 116 | } else { | ||
| 117 | objects_may_go_out_of_scope(0); | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | |||
| 122 | # the current context is either the process context, or the current transaction on-top of it | ||
| 123 | *get_current = \¤t; | ||
| 124 | sub current { | ||
| 125 | return $UR::Context::current; | ||
| 126 | } | ||
| 127 | |||
| 128 | sub process { | ||
| 129 | return $UR::Context::process; | ||
| 130 | } | ||
| 131 | |||
| 132 | sub date_template { | ||
| 133 | return q|%Y-%m-%d %H:%M:%S|; | ||
| 134 | } | ||
| 135 | |||
| 136 | sub now { | ||
| 137 | return Date::Format::time2str(date_template(), time()); | ||
| 138 | } | ||
| 139 | |||
| 140 | my $master_monitor_query = 0; | ||
| 141 | sub monitor_query { | ||
| 142 | return if $UR::Object::Type::bootstrapping; | ||
| 143 | my $self = shift; | ||
| 144 | $self = $UR::Context::current unless (ref $self); | ||
| 145 | |||
| 146 | if (@_) { | ||
| 147 | if (ref $self) { | ||
| 148 | $self->{'monitor_query'} = shift; | ||
| 149 | } else { | ||
| 150 | $master_monitor_query = shift; | ||
| 151 | } | ||
| 152 | |||
| 153 | } | ||
| 154 | return ref($self) ? $self->{'monitor_query'} : $master_monitor_query; | ||
| 155 | } | ||
| 156 | |||
| 157 | my %_query_log_times; | ||
| 158 | my $query_logging_fh = IO::Handle->new(); | ||
| 159 | $query_logging_fh->fdopen(fileno(STDERR), 'w'); | ||
| 160 | $query_logging_fh->autoflush(1); | ||
| 161 | sub query_logging_fh { | ||
| 162 | $query_logging_fh = $_[1] if @_ > 1; | ||
| 163 | return $query_logging_fh; | ||
| 164 | } | ||
| 165 | |||
| 166 | sub _log_query_for_rule { | ||
| 167 | return if $UR::Object::Type::bootstrapping; | ||
| 168 | my $self = shift; | ||
| 169 | my($subject_class,$rule,$message) = @_; | ||
| 170 | |||
| 171 | my $monitor_level; | ||
| 172 | return unless ($monitor_level = $self->monitor_query); | ||
| 173 | return if (substr($subject_class, 0,4) eq 'UR::' and $monitor_level < 2); # Don't log queries for internal classes | ||
| 174 | |||
| 175 | my $elapsed_time = 0; | ||
| 176 | if (defined($rule)) { | ||
| 177 | my $time_now = Time::HiRes::time(); | ||
| 178 | if (! exists $_query_log_times{$rule->id}) { | ||
| 179 | $_query_log_times{$rule->id} = $time_now; | ||
| 180 | } else { | ||
| 181 | $elapsed_time = $time_now - $_query_log_times{$rule->id}; | ||
| 182 | } | ||
| 183 | } | ||
| 184 | |||
| 185 | if ($elapsed_time) { | ||
| 186 | $message .= sprintf(" Elapsed %.4f s", $elapsed_time); | ||
| 187 | } | ||
| 188 | $query_logging_fh->print($message."\n"); | ||
| 189 | } | ||
| 190 | |||
| 191 | sub _log_done_elapsed_time_for_rule { | ||
| 192 | my($self, $rule) = @_; | ||
| 193 | |||
| 194 | delete $_query_log_times{$rule->id}; | ||
| 195 | } | ||
| 196 | |||
| 197 | |||
| 198 | sub resolve_data_sources_for_class_meta_and_rule { | ||
| 199 | my $self = shift; | ||
| 200 | my $class_meta = shift; | ||
| 201 | my $boolexpr = shift; ## ignored in the default case | ||
| 202 | |||
| 203 | my $class_name = $class_meta->class_name; | ||
| 204 | |||
| 205 | # These are some hard-coded cases for splitting up class-classes | ||
| 206 | # and data dictionary entities into namespace-specific meta DBs. | ||
| 207 | # Maybe there's some more generic way to move this somewhere else | ||
| 208 | |||
| 209 | # FIXME This part is commented out for the moment. When class info is in the | ||
| 210 | # Meta DBs, then try getting this to work | ||
| 211 | #if ($class_name eq 'UR::Object::Type') { | ||
| 212 | # my %params = $boolexpr->legacy_params_hash; | ||
| 213 | # my($namespace) = ($params->{'class_name'} =~ m/^(\w+?)::/); | ||
| 214 | # $namespace ||= $params->{'class_name'}; # In case the class name is just the namespace | ||
| 215 | # | ||
| 216 | # return $namespace . '::DataSource::Meta'; | ||
| 217 | #} | ||
| 218 | |||
| 219 | my $data_source; | ||
| 220 | |||
| 221 | # For data dictionary items | ||
| 222 | # When the FileMux datasource is more generalized and works for | ||
| 223 | # any kind of underlying datasource, this code can move from here | ||
| 224 | # and into the base class for Meta datasources | ||
| 225 | if ($class_name->isa('UR::DataSource::RDBMS::Entity')) { | ||
| 226 | my $params = $boolexpr->legacy_params_hash; | ||
| 227 | my $namespace; | ||
| 228 | if ($params->{'namespace'}) { | ||
| 229 | $namespace = $params->{'namespace'}; | ||
| 230 | $data_source = $params->{'namespace'} . '::DataSource::Meta'; | ||
| 231 | |||
| 232 | } elsif ($params->{'data_source'} && | ||
| 233 | ! ref($params->{'data_source'}) && | ||
| 234 | $params->{'data_source'}->can('get_namespace')) { | ||
| 235 | |||
| 236 | $namespace = $params->{'data_source'}->get_namespace; | ||
| 237 | $data_source = $namespace . '::DataSource::Meta'; | ||
| 238 | |||
| 239 | } elsif ($params->{'data_source'} && | ||
| 240 | ref($params->{'data_source'}) eq 'ARRAY') { | ||
| 241 | my %namespaces = map { $_->get_namespace => 1 } @{$params->{'data_source'}}; | ||
| 242 | unless (scalar(keys %namespaces) == 1) { | ||
| 243 | Carp::confess("get() across multiple namespaces is not supported"); | ||
| 244 | } | ||
| 245 | $namespace = $params->{'data_source'}->[0]->get_namespace; | ||
| 246 | $data_source = $namespace . '::DataSource::Meta'; | ||
| 247 | } else { | ||
| 248 | Carp::confess("Required parameter (namespace or data_source_id) missing"); | ||
| 249 | #$data_source = 'UR::DataSource::Meta'; | ||
| 250 | } | ||
| 251 | |||
| 252 | if (my $exists = UR::Object::Type->get($data_source)) { | ||
| 253 | # switch the terminology above to stop using $data_source for the class name | ||
| 254 | # now it's the object.. | ||
| 255 | $data_source = $data_source->get(); | ||
| 256 | } | ||
| 257 | else { | ||
| 258 | $self->warning_message("no data source $data_source: generating for $namespace..."); | ||
| 259 | UR::DataSource::Meta->generate_for_namespace($namespace); | ||
| 260 | $data_source = $data_source->get(); | ||
| 261 | } | ||
| 262 | |||
| 263 | unless ($data_source) { | ||
| 264 | Carp::confess "Failed to find or generate a data source for meta data for namespace $namespace!"; | ||
| 265 | } | ||
| 266 | |||
| 267 | } else { | ||
| 268 | $data_source = $class_meta->data_source; | ||
| 269 | } | ||
| 270 | |||
| 271 | if ($data_source) { | ||
| 272 | $data_source = $data_source->resolve_data_sources_for_rule($boolexpr); | ||
| 273 | } | ||
| 274 | return $data_source; | ||
| 275 | } | ||
| 276 | |||
| 277 | |||
| 278 | # this is used to determine which data source an object should be saved-to | ||
| 279 | |||
| 280 | sub resolve_data_source_for_object { | ||
| 281 | my $self = shift; | ||
| 282 | my $object = shift; | ||
| 283 | my $class_meta = $object->__meta__; | ||
| 284 | my $class_name = $class_meta->class_name; | ||
| 285 | |||
| 286 | if ($class_name->isa('UR::DataSource::RDBMS::Entity') || $class_name->isa('UR::DataSource::RDBMS::Entity::Ghost')) { | ||
| 287 | my $data_source = $object->data_source; | ||
| 288 | my($namespace) = ($data_source =~ m/(^\w+?)::DataSource/); | ||
| 289 | unless ($namespace) { | ||
| 290 | Carp::croak("Can't resolve data source for object of type $class_name: The object's namespace could not be inferred from its data_source $data_source"); | ||
| 291 | } | ||
| 292 | my $ds_name = $namespace . '::DataSource::Meta'; | ||
| 293 | return $ds_name->get(); | ||
| 294 | } | ||
| 295 | |||
| 296 | # Default behavior | ||
| 297 | my $ds = $class_meta->data_source; | ||
| 298 | return $ds; | ||
| 299 | } | ||
| 300 | |||
| 301 | # this turns on and off light caching (weak refs) | ||
| 302 | |||
| 303 | sub _light_cache { | ||
| 304 | if (@_ > 1) { | ||
| 305 | $light_cache = $_[1]; | ||
| 306 | manage_objects_may_go_out_of_scope(); | ||
| 307 | } | ||
| 308 | return $light_cache; | ||
| 309 | } | ||
| 310 | |||
| 311 | |||
| 312 | # Given a rule, and a property name not mentioned in the rule, | ||
| 313 | # can we infer the value of that property from what actually is in the rule? | ||
| 314 | |||
| 315 | sub infer_property_value_from_rule { | ||
| 316 | my($self,$wanted_property_name,$rule) = @_; | ||
| 317 | |||
| 318 | # First, the easy case... The property is directly mentioned in the rule | ||
| 319 | if ($rule->specifies_value_for($wanted_property_name)) { | ||
| 320 | return $rule->value_for($wanted_property_name); | ||
| 321 | } | ||
| 322 | |||
| 323 | my $subject_class_name = $rule->subject_class_name; | ||
| 324 | my $subject_class_meta = UR::Object::Type->get($subject_class_name); | ||
| 325 | my $wanted_property_meta = $subject_class_meta->property_meta_for_name($wanted_property_name); | ||
| 326 | unless ($wanted_property_meta) { | ||
| 327 | $self->error_message("Class $subject_class_name has no property named $wanted_property_name"); | ||
| 328 | return; | ||
| 329 | } | ||
| 330 | |||
| 331 | if ($wanted_property_meta->is_delegated) { | ||
| 332 | $self->context_return($self->_infer_delegated_property_from_rule($wanted_property_name,$rule)); | ||
| 333 | } else { | ||
| 334 | $self->context_return($self->_infer_direct_property_from_rule($wanted_property_name,$rule)); | ||
| 335 | } | ||
| 336 | } | ||
| 337 | |||
| 338 | # These are things that are changes to the program state, but not changes to the object instance | ||
| 339 | # so they shouldn't be counted in the object's change_count | ||
| 340 | my %changes_not_counted = map { $_ => 1 } qw(load define unload query connect); | ||
| 341 | sub add_change_to_transaction_log { | ||
| 342 | my ($self,$subject, $property, @data) = @_; | ||
| 343 | |||
| 344 | my ($class,$id); | ||
| 345 | if (ref($subject)) { | ||
| 346 | $class = ref($subject); | ||
| 347 | $id = $subject->id; | ||
| 348 | unless ($changes_not_counted{$property} ) { | ||
| 349 | $subject->{_change_count}++; | ||
| 350 | #print "changing $subject $property @data\n"; | ||
| 351 | } | ||
| 352 | } | ||
| 353 | else { | ||
| 354 | $class = $subject; | ||
| 355 | $subject = undef; | ||
| 356 | $id = undef; | ||
| 357 | } | ||
| 358 | |||
| 359 | if ($UR::Context::Transaction::log_all_changes) { | ||
| 360 | # eventually all calls to __signal_change__ will go directly here | ||
| 361 | UR::Context::Transaction->log_change($subject, $class, $id, $property, @data); | ||
| 362 | } | ||
| 363 | |||
| 364 | if (my $index_list = $UR::Object::Index::all_by_class_name_and_property_name{$class}{$property}) { | ||
| 365 | unless ($property eq 'create' or $property eq 'load' or $property eq 'define') { | ||
| 366 | for my $index (@$index_list) { | ||
| 367 | $index->_remove_object( | ||
| 368 | $subject, | ||
| 369 | { $property => $data[0] } | ||
| 370 | ) | ||
| 371 | } | ||
| 372 | } | ||
| 373 | |||
| 374 | unless ($property eq 'delete' or $property eq 'unload') { | ||
| 375 | for my $index (@$index_list) { | ||
| 376 | $index->_add_object($subject) | ||
| 377 | } | ||
| 378 | } | ||
| 379 | } | ||
| 380 | } | ||
| 381 | |||
| 382 | our $sig_depth = 0; | ||
| 383 | my %subscription_classes; | ||
| 384 | sub send_notification_to_observers { | ||
| 385 | my ($self,$subject, $property, @data) = @_; | ||
| 386 | |||
| 387 | my ($class,$id); | ||
| 388 | if (ref($subject)) { | ||
| 389 | $class = ref($subject); | ||
| 390 | $id = $subject->id; | ||
| 391 | } else { | ||
| 392 | $class = $subject; | ||
| 393 | } | ||
| 394 | |||
| 395 | my $check_classes = $subscription_classes{$class}; | ||
| 396 | unless ($check_classes) { | ||
| 397 | $subscription_classes{$class} = $check_classes = [ | ||
| 398 | $class | ||
| 399 | ? ( | ||
| 400 | $class, | ||
| 401 | (grep { $_->isa("UR::Object") } $class->inheritance), | ||
| 402 | '' | ||
| 403 | ) | ||
| 404 | : ('') | ||
| 405 | ]; | ||
| 406 | } | ||
| 407 | my @check_properties = ($property ? ($property, '') : ('') ); | ||
| 408 | my @check_ids = (defined($id) ? ($id, '') : ('') ); | ||
| 409 | |||
| 410 | my @matches = | ||
| 411 | map { @$_ } | ||
| 412 | grep { defined $_ } map { defined($id) ? @$_{@check_ids} : values(%$_) } | ||
| 413 | grep { defined $_ } map { @$_{@check_properties} } | ||
| 414 | grep { defined $_ } @$UR::Context::all_change_subscriptions{@$check_classes}; | ||
| 415 | |||
| 416 | return unless @matches; | ||
| 417 | |||
| 418 | $sig_depth++; | ||
| 419 | if (@matches > 1) { | ||
| 420 | no warnings; | ||
| 421 | # sort by priority | ||
| 422 | @matches = sort { $a->[2] <=> $b->[2] } @matches; | ||
| 423 | }; | ||
| 424 | |||
| 425 | foreach my $callback_info (@matches) { | ||
| 426 | my ($callback, $note, undef, $id, $once) = @$callback_info; | ||
| 427 | UR::Observer->get($id)->delete() if $once; | ||
| 428 | $callback->($subject, $property, @data); | ||
| 429 | } | ||
| 430 | |||
| 431 | $sig_depth--; | ||
| 432 | |||
| 433 | return scalar(@matches); | ||
| 434 | } | ||
| 435 | |||
| 436 | |||
| 437 | sub query { | ||
| 438 | my $self = shift; | ||
| 439 | |||
| 440 | # Fast optimization for the default case. | ||
| 441 | if ( ( !ref($self) or ! $self->query_underlying_context) | ||
| 442 | and ! Scalar::Util::blessed($_[1]) # This happens when query() is called with a class name and boolexpr | ||
| 443 | ) { | ||
| 444 | no warnings; | ||
| 445 | if (exists $UR::Context::all_objects_loaded->{$_[0]}) { | ||
| 446 | my $is_monitor_query = $self->monitor_query; | ||
| 447 | if (defined(my $obj = $UR::Context::all_objects_loaded->{$_[0]}->{$_[1]})) { | ||
| 448 | # Matched the class and ID directly - pull it right out of the cache | ||
| 449 | if ($is_monitor_query) { | ||
| 450 | $self->_log_query_for_rule($_[0], undef, Carp::shortmess("QUERY: class $_[0] by ID $_[1]")); | ||
| 451 | $self->_log_query_for_rule($_[0], undef, "QUERY: matched 1 cached object\nQUERY: returning 1 object\n\n"); | ||
| 452 | } | ||
| 453 | |||
| 454 | $obj->{'__get_serial'} = $UR::Context::GET_COUNTER++; | ||
| 455 | return $obj; | ||
| 456 | |||
| 457 | } elsif (my $subclasses = $UR::Object::Type::_init_subclasses_loaded{$_[0]}) { | ||
| 458 | # Check subclasses of the requested class, along with the ID | ||
| 459 | # yes, it only goes one level deep. This should catch enough cases to be worth it. | ||
| 460 | # Deeper searches will be covered by get_objects_for_class_and_rule() | ||
| 461 | foreach my $subclass (@$subclasses) { | ||
| 462 | if (exists $UR::Context::all_objects_loaded->{$subclass} and | ||
| 463 | my $obj = $UR::Context::all_objects_loaded->{$subclass}->{$_[1]} | ||
| 464 | ) { | ||
| 465 | if ($is_monitor_query) { | ||
| 466 | $self->_log_query_for_rule($_[0], undef, Carp::shortmess("QUERY: class $_[0] by ID $_[1]")); | ||
| 467 | $self->_log_query_for_rule($_[0], undef, "QUERY: matched 1 cached object in subclass $subclass\nQUERY: returning 1 object\n\n"); | ||
| 468 | } | ||
| 469 | |||
| 470 | $obj->{'__get_serial'} = $UR::Context::GET_COUNTER++; | ||
| 471 | return $obj; | ||
| 472 | } | ||
| 473 | } | ||
| 474 | } | ||
| 475 | } | ||
| 476 | }; | ||
| 477 | |||
| 478 | # Normal logic for finding objects smartly is below. | ||
| 479 | |||
| 480 | my $class = shift; | ||
| 481 | |||
| 482 | # Handle the case in which this is called as an object method. | ||
| 483 | # Functionality is completely different. | ||
| 484 | |||
| 485 | if(ref($class)) { | ||
| 486 | my @rvals; | ||
| 487 | foreach my $prop (@_) { | ||
| 488 | push(@rvals, $class->$prop()); | ||
| 489 | } | ||
| 490 | |||
| 491 | if(wantarray) { | ||
| 492 | return @rvals; | ||
| 493 | } | ||
| 494 | else { | ||
| 495 | return \@rvals; | ||
| 496 | } | ||
| 497 | } | ||
| 498 | |||
| 499 | my ($rule, @extra) = UR::BoolExpr->resolve($class,@_); | ||
| 500 | |||
| 501 | if (@extra) { | ||
| 502 | # remove this and have the developer go to the datasource | ||
| 503 | if (scalar @extra == 2 and ($extra[0] eq "sql" or $extra[0] eq 'sql in')) { | ||
| 504 | return $UR::Context::current->_get_objects_for_class_and_sql($class,$extra[1]); | ||
| 505 | } | ||
| 506 | |||
| 507 | # keep this part: let the sub-class handle special params if it can | ||
| 508 | return $class->get_with_special_parameters($rule, @extra); | ||
| 509 | } | ||
| 510 | |||
| 511 | # This is here for bootstrapping reasons: we must be able to load class singletons | ||
| 512 | # in order to have metadata for regular loading.... | ||
| 513 | # UR::DataSource::QueryPlan isa UR::Value (which has custom loading logic), but we need to be able to generate | ||
| 514 | # a QueryPlan independant of the normal loading process, otherwise there'd be endless recursion (Can't generate a QueryPlan | ||
| 515 | # for a QueryPlan without generating a QueryPlan first....) | ||
| 516 | if (!$rule->has_meta_options and ($class->isa("UR::Object::Type") or $class->isa("UR::Singleton") or $class->isa("UR::DataSource::QueryPlan"))) { | ||
| 517 | my $normalized_rule = $rule->normalize; | ||
| 518 | my @objects = $class->_load($normalized_rule); | ||
| 519 | |||
| 520 | return unless defined wantarray; | ||
| 521 | return @objects if wantarray; | ||
| 522 | |||
| 523 | if ( @objects > 1 and defined(wantarray)) { | ||
| 524 | Carp::croak("Multiple matches for $class query called in scalar context. $rule matches " . scalar(@objects). " objects"); | ||
| 525 | } | ||
| 526 | |||
| 527 | return $objects[0]; | ||
| 528 | } | ||
| 529 | |||
| 530 | return $UR::Context::current->get_objects_for_class_and_rule($class, $rule); | ||
| 531 | } | ||
| 532 | |||
| 533 | sub _resolve_id_for_class_and_rule { | ||
| 534 | my ($self,$class_meta,$rule) = @_; | ||
| 535 | |||
| 536 | my $class = $class_meta->class_name; | ||
| 537 | my $id; | ||
| 538 | my @id_property_names = $class_meta->id_property_names | ||
| 539 | or Carp::confess( # Bad should be at least one | ||
| 540 | "No id property names for class ($class). This should not have happened." | ||
| 541 | ); | ||
| 542 | |||
| 543 | if ( @id_property_names == 1 ) { # only 1 - try to auto generate | ||
| 544 | $id = $class_meta->autogenerate_new_object_id($rule); | ||
| 545 | unless ( defined $id ) { | ||
| 546 | $class->error_message("Failed to auto-generate an ID for single ID property class ($class)"); | ||
| 547 | return; | ||
| 548 | } | ||
| 549 | } | ||
| 550 | else { # multiple | ||
| 551 | # Try to give a useful message by getting id prop names that are not deinfed | ||
| 552 | my @missed_names; | ||
| 553 | for my $name ( @id_property_names ) { | ||
| 554 | push @missed_names, $name unless $rule->specifies_value_for($name); | ||
| 555 | } | ||
| 556 | if ( @missed_names ) { # Ok - prob w/ class def, list the ones we missed | ||
| 557 | $class->error_message("Attempt to create $class with multiple ids without these properties: ".join(', ', @missed_names)); | ||
| 558 | return; | ||
| 559 | } | ||
| 560 | else { # Bad - something is really wrong... | ||
| 561 | Carp::confess("Attempt to create $class failed to resolve id from underlying id properties."); | ||
| 562 | } | ||
| 563 | } | ||
| 564 | |||
| 565 | return $id; | ||
| 566 | } | ||
| 567 | |||
| 568 | our $construction_method = 'create'; | ||
| 569 | |||
| 570 | # Pulled out the complicated code of create_entity() below that deals with | ||
| 571 | # abstract classes and subclassify_by | ||
| 572 | sub _create_entity_from_abstract_class { | ||
| 573 | my $self = shift; | ||
| 574 | |||
| 575 | my $class = shift; | ||
| 576 | my $class_meta = $class->__meta__; | ||
| 577 | my($rule, %extra) = UR::BoolExpr->resolve_normalized($class, @_); | ||
| 578 | |||
| 579 | # If we can easily determine the correct subclass, delegate to that subclass' create() | ||
| 580 | my $subclassify_by = $class_meta->subclassify_by(); | ||
| 581 | unless (defined $subclassify_by) { | ||
| 582 | Carp::croak("Can't call $construction_method on abstract class $class without a subclassify_by property"); | ||
| 583 | } | ||
| 584 | |||
| 585 | my $sub_class_name = $rule->value_for($subclassify_by); | ||
| 586 | unless (defined $sub_class_name) { | ||
| 587 | # The subclassification wasn't included in the rule | ||
| 588 | my $property_meta = $class_meta->property($subclassify_by); | ||
| 589 | unless ($property_meta) { | ||
| 590 | Carp::croak("Abstract class $class has subclassify_by $subclassify_by, but no property exists by that name"); | ||
| 591 | } | ||
| 592 | |||
| 593 | # There are a few different ways the property can supply a value for subclassify_by... | ||
| 594 | # The sure-fire way to get a value is to go ahead an instantiate the object into the | ||
| 595 | # base/abstract class, and then we can just call the property as a method. There's | ||
| 596 | # a lot of overhead in that, so first we'll try some of the easier, common-case ways | ||
| 597 | |||
| 598 | if ($property_meta->default_value) { | ||
| 599 | # The property has a default value | ||
| 600 | $sub_class_name = $property_meta->default_value(); | ||
| 601 | |||
| 602 | } elsif ($property_meta->is_calculated and ref($property_meta->calculate) eq 'CODE') { | ||
| 603 | # It's calculated via a coderef | ||
| 604 | |||
| 605 | my $calculate_from = $property_meta->calculate_from; | ||
| 606 | my @calculate_params; | ||
| 607 | foreach my $prop_name ( @$calculate_from ) { | ||
| 608 | # The things in calculate_from must appear in the rule | ||
| 609 | unless ($rule->specifies_value_for($prop_name)) { | ||
| 610 | Carp::croak("Class $class subclassify_by calculation property '$subclassify_by' " | ||
| 611 | . "requires '$prop_name' in the $construction_method() params\n" | ||
| 612 | . "Params were: " . UR::Util->display_string_for_params_list($rule->params_list)); | ||
| 613 | } | ||
| 614 | push @calculate_params, $rule->value_for($prop_name); | ||
| 615 | } | ||
| 616 | |||
| 617 | my $sub = $property_meta->calculate; | ||
| 618 | unless ($sub) { | ||
| 619 | Carp::croak("Can't use undefined value as subroutine reference while resolving " | ||
| 620 | . "value for class $class calculated property '$subclassify_by'"); | ||
| 621 | } | ||
| 622 | $sub_class_name = $sub->(@calculate_params); | ||
| 623 | |||
| 624 | } elsif ($property_meta->is_calculated and !ref($property_meta->calculate)) { | ||
| 625 | # It's calculated via a string that's eval-ed | ||
| 626 | Carp::croak("Can't use a non-coderef as a calculation for class $class subclassify_by"); | ||
| 627 | |||
| 628 | } elsif ($property_meta->is_delegated) { | ||
| 629 | #Carp::croak("Delegated properties are not supported for subclassifying $class with property '$subclassify_by'"); | ||
| 630 | my @values = $self->infer_property_value_from_rule($subclassify_by, $rule); | ||
| 631 | if (! @values ) { | ||
| 632 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 633 | . "Couldn't infer a value for indirect property '$subclassify_by' via rule $rule"); | ||
| 634 | } elsif (@values > 1) { | ||
| 635 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 636 | . "Infering a value for property '$subclassify_by' via rule $rule returned multiple values: " | ||
| 637 | . join(', ', @values)); | ||
| 638 | } else { | ||
| 639 | $sub_class_name = $values[0]; | ||
| 640 | } | ||
| 641 | |||
| 642 | } else { | ||
| 643 | Carp::croak("Can't use undefined value as a subclass name for $class property '$subclassify_by'"); | ||
| 644 | } | ||
| 645 | } | ||
| 646 | |||
| 647 | unless (defined $sub_class_name) { | ||
| 648 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 649 | . "Can't use undefined value as a subclass name for param '$subclassify_by'"); | ||
| 650 | } | ||
| 651 | if ($sub_class_name eq $class) { | ||
| 652 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 653 | . "Value for $subclassify_by cannot be the same as the original class"); | ||
| 654 | } | ||
| 655 | unless ($sub_class_name->isa($class)) { | ||
| 656 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 657 | . "Class $sub_class_name is not a subclass of $class"); | ||
| 658 | } | ||
| 659 | return $sub_class_name->$construction_method(@_); | ||
| 660 | } | ||
| 661 | |||
| 662 | my %memos; | ||
| 663 | my %memos2; | ||
| 664 | sub create_entity { | ||
| 665 | my $self = shift; | ||
| 666 | |||
| 667 | my $class = shift; | ||
| 668 | |||
| 669 | my $memo = $memos{$class}; | ||
| 670 | unless ($memo) { | ||
| 671 | # we only want to grab the data necessary for object construction once | ||
| 672 | # this occurs the first time a new object is created for a given class | ||
| 673 | |||
| 674 | my $class_meta = $class->__meta__; | ||
| 675 | my @inheritance = reverse ($class_meta, $class_meta->ancestry_class_metas); | ||
| 676 | |||
| 677 | # %property_objects maps property names to UR::Object::Property objects | ||
| 678 | # by going through the reversed list of UR::Object::Type objects below | ||
| 679 | # We set up this hash to have the correct property objects for each property | ||
| 680 | # name. This is important in the case of property name overlap via | ||
| 681 | # inheritance. The property object used should be the one "closest" | ||
| 682 | # to the class. In other words, a property directly on the class gets | ||
| 683 | # used instead of an inherited one. | ||
| 684 | my %property_objects; | ||
| 685 | my %direct_properties; | ||
| 686 | my %indirect_properties; | ||
| 687 | my %set_properties; | ||
| 688 | my %default_values; | ||
| 689 | my %default_value_requires_query; | ||
| 690 | my %default_value_requires_call; | ||
| 691 | my %immutable_properties; | ||
| 692 | my @deep_copy_default_values; | ||
| 693 | |||
| 694 | for my $co ( @inheritance ) { | ||
| 695 | # Reverse map the ID into property values. | ||
| 696 | # This has to occur for all subclasses which represent table rows. | ||
| 697 | |||
| 698 | # deal with %property_objects | ||
| 699 | my @property_objects = $co->direct_property_metas; | ||
| 700 | my @property_names = map { $_->property_name } @property_objects; | ||
| 701 | @property_objects{@property_names} = @property_objects; | ||
| 702 | |||
| 703 | foreach my $prop ( @property_objects ) { | ||
| 704 | my $name = $prop->property_name; | ||
| 705 | |||
| 706 | unless (defined $name) { | ||
| 707 | Carp::confess("no name on property for class " . $co->class_name . "?\n" . Data::Dumper::Dumper($prop)); | ||
| 708 | } | ||
| 709 | |||
| 710 | my $default_value = $prop->default_value; | ||
| 711 | if (defined $default_value) { | ||
| 712 | if ($prop->data_type and $prop->_data_type_as_class_name eq $prop->data_type and $prop->_data_type_as_class_name->can("get")) { | ||
| 713 | # an ID or other query params in hash/array form return an object or objects | ||
| 714 | $default_value_requires_query{$name} = $default_value; | ||
| 715 | } | ||
| 716 | elsif (ref($default_value)) { | ||
| 717 | #warn ( | ||
| 718 | # "a reference value $default_value is used as a default on " | ||
| 719 | # . $co->class_name | ||
| 720 | # . " forcing a copy during construction " | ||
| 721 | # . " of $class $name..." | ||
| 722 | #); | ||
| 723 | push @deep_copy_default_values, $name; | ||
| 724 | } | ||
| 725 | $default_values{$name} = $default_value; | ||
| 726 | } | ||
| 727 | |||
| 728 | if ($prop->calculated_default) { | ||
| 729 | $default_value_requires_call{$name} = $prop->calculated_default; | ||
| 730 | } | ||
| 731 | |||
| 732 | if ($prop->is_many) { | ||
| 733 | $set_properties{$name} = $prop; | ||
| 734 | } | ||
| 735 | elsif ($prop->is_delegated) { | ||
| 736 | $indirect_properties{$name} = $prop; | ||
| 737 | } | ||
| 738 | else { | ||
| 739 | $direct_properties{$name} = $prop; | ||
| 740 | } | ||
| 741 | |||
| 742 | unless ($prop->is_mutable) { | ||
| 743 | $immutable_properties{$name} = 1; | ||
| 744 | } | ||
| 745 | } | ||
| 746 | } | ||
| 747 | |||
| 748 | my @indirect_property_names = keys %indirect_properties; | ||
| 749 | my @direct_property_names = keys %direct_properties; | ||
| 750 | |||
| 751 | my @subclassify_by_methods; | ||
| 752 | foreach my $co ( @inheritance ) { | ||
| 753 | # If this class inherits from something with subclassify_by, make sure the param | ||
| 754 | # actually matches. If it's not supplied, then set it to the same as the class create() | ||
| 755 | # is being called on | ||
| 756 | if ( $class ne $co->class_name | ||
| 757 | and $co->is_abstract | ||
| 758 | and my $method = $co->subclassify_by | ||
| 759 | ) { | ||
| 760 | push @subclassify_by_methods, $method; | ||
| 761 | } | ||
| 762 | } | ||
| 763 | |||
| 764 | $memos{$class} = $memo = [ | ||
| 765 | $class_meta, | ||
| 766 | $class_meta->first_sub_classification_method_name, | ||
| 767 | $class_meta->is_abstract, | ||
| 768 | \@inheritance, | ||
| 769 | \%property_objects, | ||
| 770 | \%direct_properties, | ||
| 771 | \%indirect_properties, | ||
| 772 | \%set_properties, | ||
| 773 | \%immutable_properties, | ||
| 774 | \@subclassify_by_methods, | ||
| 775 | \%default_values, | ||
| 776 | (@deep_copy_default_values ? \@deep_copy_default_values : undef), | ||
| 777 | \%default_value_requires_query, | ||
| 778 | \%default_value_requires_call, | ||
| 779 | ]; | ||
| 780 | } | ||
| 781 | |||
| 782 | my ( | ||
| 783 | $class_meta, | ||
| 784 | $first_sub_classification_method_name, | ||
| 785 | $is_abstract, | ||
| 786 | $inheritance, | ||
| 787 | $property_objects, | ||
| 788 | $direct_properties, | ||
| 789 | $indirect_properties, | ||
| 790 | $set_properties, | ||
| 791 | $immutable_properties, | ||
| 792 | $subclassify_by_methods, | ||
| 793 | $initial_default_values, | ||
| 794 | $deep_copy_default_values, | ||
| 795 | $default_value_requires_query, | ||
| 796 | $initial_default_value_requires_call, | ||
| 797 | ) = @$memo; | ||
| 798 | |||
| 799 | # The old way of automagic subclassing... | ||
| 800 | # The class specifies that we should call a class method (sub_classification_method_name) | ||
| 801 | # to determine the correct subclass | ||
| 802 | if ($first_sub_classification_method_name) { | ||
| 803 | my $sub_class_name = $class->$first_sub_classification_method_name(@_); | ||
| 804 | if (defined($sub_class_name) and ($sub_class_name ne $class)) { | ||
| 805 | # delegate to the sub-class to create the object | ||
| 806 | unless ($sub_class_name->can($construction_method)) { | ||
| 807 | Carp::croak("Can't locate object method '$construction_method' via package '$sub_class_name' " | ||
| 808 | . "while resolving proper subclass for $class during $construction_method"); | ||
| 809 | |||
| 810 | } | ||
| 811 | return $sub_class_name->$construction_method(@_); | ||
| 812 | } | ||
| 813 | # fall through if the class names match | ||
| 814 | } | ||
| 815 | |||
| 816 | if ($is_abstract) { | ||
| 817 | # The new way of automagic subclassing. The class specifies a property (subclassify_by) | ||
| 818 | # that holds/returns the correct subclass name | ||
| 819 | return $self->_create_entity_from_abstract_class($class, @_); | ||
| 820 | } | ||
| 821 | |||
| 822 | # normal case: make a rule out of the passed-in params | ||
| 823 | # rather than normalizing the rule, we just do the extension part which is fast | ||
| 824 | my $rule = UR::BoolExpr->resolve($class, @_); | ||
| 825 | my $template = $rule->template; | ||
| 826 | |||
| 827 | my $params = { $rule->_params_list, $template->extend_params_list_for_values(@{$rule->{values}}) }; | ||
| 828 | if (my $a = $template->{_ambiguous_keys}) { | ||
| 829 | my $p = $template->{_ambiguous_property_names}; | ||
| 830 | @$params{@$p} = delete @$params{@$a}; | ||
| 831 | } | ||
| 832 | |||
| 833 | my $id = $params->{id}; | ||
| 834 | unless (defined $id) { | ||
| 835 | $id = $self->_resolve_id_for_class_and_rule($class_meta,$rule); | ||
| 836 | unless ($id) { | ||
| 837 | return; | ||
| 838 | } | ||
| 839 | $rule = UR::BoolExpr->resolve_normalized($class, %$params, id => $id); | ||
| 840 | $params = { $rule->params_list }; ; | ||
| 841 | } | ||
| 842 | |||
| 843 | my %default_value_requires_call = %$initial_default_value_requires_call; | ||
| 844 | delete @default_value_requires_call{ keys %$params }; | ||
| 845 | |||
| 846 | # handle postprocessing default values | ||
| 847 | |||
| 848 | my %default_values = %$initial_default_values; | ||
| 849 | |||
| 850 | for my $name (keys %$default_value_requires_query) { | ||
| 851 | my @id_by; | ||
| 852 | if (my $id_by = $property_objects->{$name}->id_by) { | ||
| 853 | @id_by = (ref($id_by) ? @$id_by : ($id_by)); | ||
| 854 | } | ||
| 855 | |||
| 856 | if ($params->{$name}) { | ||
| 857 | delete $default_values{$name}; | ||
| 858 | } | ||
| 859 | elsif (@$params{@id_by}) { | ||
| 860 | # some or all of the id is present | ||
| 861 | # don't fall back to the default | ||
| 862 | for my $id_by (@id_by) { | ||
| 863 | delete $default_values{$id_by} if exists $params->{$id_by}; | ||
| 864 | } | ||
| 865 | delete $default_values{$name}; | ||
| 866 | } | ||
| 867 | else { | ||
| 868 | my $query = $default_value_requires_query->{$name}; | ||
| 869 | my @query; | ||
| 870 | if (ref($query) eq 'HASH') { | ||
| 871 | # queries come in as a hash | ||
| 872 | @query = %$query; | ||
| 873 | } | ||
| 874 | else { | ||
| 875 | # an ID or a boolean expression | ||
| 876 | @query = ($query); | ||
| 877 | } | ||
| 878 | my $prop = $property_objects->{$name}; | ||
| 879 | my $class = $prop->_data_type_as_class_name; | ||
| 880 | eval { | ||
| 881 | if ($prop->is_many) { | ||
| 882 | $default_values{$name} = [ $class->get(@query) ]; | ||
| 883 | } | ||
| 884 | else { | ||
| 885 | $default_values{$name} = $class->get(@query); | ||
| 886 | } | ||
| 887 | }; | ||
| 888 | if ($@) { | ||
| 889 | warn "error setting " . $prop->class_name . " " . $prop->property_name . " to default_value from query $query for type $class!"; | ||
| 890 | }; | ||
| 891 | } | ||
| 892 | } | ||
| 893 | |||
| 894 | if ($deep_copy_default_values) { | ||
| 895 | for my $name (@$deep_copy_default_values) { | ||
| 896 | if ($params->{$name}) { | ||
| 897 | delete $default_values{$name}; | ||
| 898 | } | ||
| 899 | else { | ||
| 900 | $default_values{$name} = UR::Util::deep_copy($default_values{$name}); | ||
| 901 | } | ||
| 902 | } | ||
| 903 | } | ||
| 904 | |||
| 905 | # @extra is extra values gotten by inheritance | ||
| 906 | my @extra; | ||
| 907 | |||
| 908 | my $indirect_values = {}; | ||
| 909 | for my $property_name (keys %$indirect_properties) { | ||
| 910 | # pull indirect values out of the constructor hash | ||
| 911 | # so we can apply them separately after making the object | ||
| 912 | if ( exists $params->{ $property_name } ) { | ||
| 913 | $indirect_values->{ $property_name } = delete $params->{ $property_name }; | ||
| 914 | delete $default_values{$property_name}; | ||
| 915 | } | ||
| 916 | elsif (exists $default_values{$property_name}) { | ||
| 917 | $indirect_values->{ $property_name } = delete $default_values{$property_name}; | ||
| 918 | } | ||
| 919 | } | ||
| 920 | |||
| 921 | # if the indirect property is immutable, but it is via something which is | ||
| 922 | # mutable, we use those values to get or create the bridge. | ||
| 923 | my %indirect_immutable_properties_via; | ||
| 924 | for my $property_name (keys %$indirect_values) { | ||
| 925 | if ($immutable_properties->{$property_name}) { | ||
| 926 | my $meta = $indirect_properties->{$property_name}; | ||
| 927 | next unless $meta; # not indirect | ||
| 928 | my $via = $meta->via; | ||
| 929 | next unless $via; # not a via/to (id_by or reverse_id_by) | ||
| 930 | $indirect_immutable_properties_via{$via}{$property_name} = delete $indirect_values->{$property_name}; | ||
| 931 | } | ||
| 932 | } | ||
| 933 | |||
| 934 | for my $via (keys %indirect_immutable_properties_via) { | ||
| 935 | my $via_property_meta = $class_meta->property_meta_for_name($via); | ||
| 936 | my ($source_indirect_property, $source_value) = each %{$indirect_immutable_properties_via{$via}}; # There'll only ever be one key/value | ||
| 937 | |||
| 938 | unless ($via_property_meta) { | ||
| 939 | Carp::croak("No metadata for class $class property $via while resolving indirect value for property $source_indirect_property"); | ||
| 940 | } | ||
| 941 | |||
| 942 | my $indirect_property_meta = $class_meta->property_meta_for_name($source_indirect_property); | ||
| 943 | unless ($indirect_property_meta) { | ||
| 944 | Carp::croak("No metadata for class $class property $source_indirect_property while resolving indirect value for property $source_indirect_property"); | ||
| 945 | } | ||
| 946 | |||
| 947 | unless ($indirect_property_meta->to) { | ||
| 948 | # We're probably dealing with a subclassify_by property where the subclass has | ||
| 949 | # implicitly overridden the indirect property in the parent class with a constant-value | ||
| 950 | # property in the subclass. Try asking the parent class about a property of the same name | ||
| 951 | ($indirect_property_meta) = grep { $_->property_name eq $indirect_property_meta->property_name } $class_meta->ancestry_property_metas(); | ||
| 952 | unless ($indirect_property_meta and $indirect_property_meta->to) { | ||
| 953 | Carp::croak("Can't resolve indirect relationship for possibly overridden property '$source_indirect_property'" | ||
| 954 | . " in class $class. Parent classes have no property named '$source_indirect_property'"); | ||
| 955 | } | ||
| 956 | } | ||
| 957 | my $foreign_class = $via_property_meta->data_type; | ||
| 958 | my $foreign_property = $indirect_property_meta->to; | ||
| 959 | my $foreign_object = $foreign_class->get($foreign_property => $source_value); | ||
| 960 | unless ($foreign_object) { | ||
| 961 | # This will trigger recursion back here (into create_entity() ) if this property is multiply | ||
| 962 | # indirect, such as through a bridge object | ||
| 963 | $foreign_object = $foreign_class->create($foreign_property => $source_value); | ||
| 964 | unless ($foreign_object) { | ||
| 965 | Carp::croak("Can't create object of class $foreign_class with params ($foreign_property => '$source_value')" | ||
| 966 | . " while resolving indirect value for class $class property $source_indirect_property"); | ||
| 967 | } | ||
| 968 | } | ||
| 969 | |||
| 970 | my @joins = $indirect_property_meta->_resolve_join_chain(); | ||
| 971 | my %local_properties_to_set; | ||
| 972 | foreach my $join ( @joins ) { | ||
| 973 | if ($join->{foreign_class}->isa("UR::Value")) { | ||
| 974 | # this final "join" is to the set of values available to the raw primitive type | ||
| 975 | # ...not what we really mean by delegation | ||
| 976 | next; | ||
| 977 | } | ||
| 978 | for (my $i = 0; $i < @{$join->{'source_property_names'}}; $i++) { | ||
| 979 | my $source_property_name = $join->{'source_property_names'}->[$i]; | ||
| 980 | next unless (exists $direct_properties->{$source_property_name}); | ||
| 981 | my $foreign_property_name = $join->{'foreign_property_names'}->[$i]; | ||
| 982 | my $value = $foreign_object->$foreign_property_name; | ||
| 983 | |||
| 984 | if ($rule->specifies_value_for($source_property_name) | ||
| 985 | and | ||
| 986 | $rule->value_for($source_property_name) ne $value) | ||
| 987 | { | ||
| 988 | Carp::croak("Invalid parameters for $class->$construction_method(): " | ||
| 989 | . "Conflicting values for property '$source_property_name'. $construction_method rule " | ||
| 990 | . "specifies value '" . $rule->value_for($source_property_name) . "' but " | ||
| 991 | . "indirect immutable property '$source_indirect_property' with value " | ||
| 992 | . "$source_value requires it to be '$value'"); | ||
| 993 | } | ||
| 994 | |||
| 995 | $local_properties_to_set{$source_property_name} = $value; | ||
| 996 | } | ||
| 997 | } | ||
| 998 | # transfer the values we resolved back into %$params | ||
| 999 | my @param_keys = keys %local_properties_to_set; | ||
| 1000 | @$params{@param_keys} = @local_properties_to_set{@param_keys}; | ||
| 1001 | } | ||
| 1002 | |||
| 1003 | my $set_values = {}; | ||
| 1004 | for my $property_name (keys %$set_properties) { | ||
| 1005 | if (exists $params->{ $property_name }) { | ||
| 1006 | delete $default_values{ $property_name }; | ||
| 1007 | $set_values->{ $property_name } = delete $params->{ $property_name }; | ||
| 1008 | } | ||
| 1009 | } | ||
| 1010 | |||
| 1011 | my $entity = $self->_construct_object($class, %default_values, %$params, @extra); | ||
| 1012 | return unless defined $entity; | ||
| 1013 | $self->add_change_to_transaction_log($entity, $construction_method); | ||
| 1014 | $self->add_change_to_transaction_log($entity, 'load') if $construction_method eq '__define__'; | ||
| 1015 | |||
| 1016 | for my $property_name ( keys %default_value_requires_call ) { | ||
| 1017 | my $method = $default_value_requires_call{$property_name}; | ||
| 1018 | my $value = $method->($entity); | ||
| 1019 | $entity->$property_name($value); | ||
| 1020 | } | ||
| 1021 | |||
| 1022 | # If a property is calculated + immutable, and it wasn't supplied in the params, | ||
| 1023 | # that means we need to run the calculation once and store the value in the | ||
| 1024 | # object as a read-only attribute | ||
| 1025 | foreach my $property_name ( keys %$immutable_properties ) { | ||
| 1026 | my $property_meta = $property_objects->{$property_name}; | ||
| 1027 | if (!exists($params->{$property_name}) and $property_meta and $property_meta->is_calculated) { | ||
| 1028 | my $value = $entity->$property_name; | ||
| 1029 | $params->{$property_name} = $value; | ||
| 1030 | } | ||
| 1031 | } | ||
| 1032 | |||
| 1033 | for my $subclassify_by (@$subclassify_by_methods) { | ||
| 1034 | my $param_value = $rule->value_for($subclassify_by); | ||
| 1035 | $param_value = eval { $entity->$subclassify_by } unless (defined $param_value); | ||
| 1036 | $param_value = $default_values{$subclassify_by} unless (defined $param_value); | ||
| 1037 | |||
| 1038 | if (! defined $param_value) { | ||
| 1039 | |||
| 1040 | # This should have been taken care of by the time we got here... | ||
| 1041 | Carp::croak("Invalid parameters for $class->$construction_method(): " . | ||
| 1042 | "Can't use an undefined value as a subclass name for param '$subclassify_by'"); | ||
| 1043 | |||
| 1044 | } elsif ($param_value ne $class) { | ||
| 1045 | Carp::croak("Invalid parameters for $class->$construction_method(): " . | ||
| 1046 | "Value for subclassifying param '$subclassify_by' " . | ||
| 1047 | "($param_value) does not match the class it was called on ($class)"); | ||
| 1048 | } | ||
| 1049 | } | ||
| 1050 | |||
| 1051 | # add items for any multi properties | ||
| 1052 | if (%$set_values) { | ||
| 1053 | for my $property_name (keys %$set_values) { | ||
| 1054 | my $meta = $set_properties->{$property_name}; | ||
| 1055 | my $singular_name = $meta->singular_name; | ||
| 1056 | my $adder = 'add_' . $singular_name; | ||
| 1057 | my $value = $set_values->{$property_name}; | ||
| 1058 | unless (ref($value) eq 'ARRAY') { | ||
| 1059 | $value = [$value]; | ||
| 1060 | } | ||
| 1061 | for my $item (@$value) { | ||
| 1062 | if (ref($item) eq 'ARRAY') { | ||
| 1063 | $entity->$adder(@$item); | ||
| 1064 | } | ||
| 1065 | elsif (ref($item) eq 'HASH') { | ||
| 1066 | $entity->$adder(%$item); | ||
| 1067 | } | ||
| 1068 | else { | ||
| 1069 | $entity->$adder($item); | ||
| 1070 | } | ||
| 1071 | } | ||
| 1072 | } | ||
| 1073 | } | ||
| 1074 | |||
| 1075 | # set any indirect mutable properties | ||
| 1076 | if (%$indirect_values) { | ||
| 1077 | for my $property_name (keys %$indirect_values) { | ||
| 1078 | $entity->$property_name($indirect_values->{$property_name}); | ||
| 1079 | } | ||
| 1080 | } | ||
| 1081 | |||
| 1082 | if (%$immutable_properties) { | ||
| 1083 | my @problems = $entity->__errors__(); | ||
| 1084 | if (@problems) { | ||
| 1085 | my @errors_fatal_to_construction; | ||
| 1086 | |||
| 1087 | my %problems_by_property_name; | ||
| 1088 | for my $problem (@problems) { | ||
| 1089 | my @problem_properties; | ||
| 1090 | for my $name ($problem->properties) { | ||
| 1091 | if ($immutable_properties->{$name}) { | ||
| 1092 | push @problem_properties, $name; | ||
| 1093 | } | ||
| 1094 | } | ||
| 1095 | if (@problem_properties) { | ||
| 1096 | push @errors_fatal_to_construction, join(" and ", @problem_properties) . ': ' . $problem->desc; | ||
| 1097 | } | ||
| 1098 | } | ||
| 1099 | |||
| 1100 | if (@errors_fatal_to_construction) { | ||
| 1101 | my $msg = 'Failed to $construction_method ' . $class . ' with invalid immutable properties:' | ||
| 1102 | . join("\n", @errors_fatal_to_construction); | ||
| 1103 | } | ||
| 1104 | } | ||
| 1105 | } | ||
| 1106 | |||
| 1107 | $entity->__signal_observers__($construction_method); | ||
| 1108 | $entity->__signal_observers__('load') if $construction_method eq '__define__'; | ||
| 1109 | $entity->{'__get_serial'} = $UR::Context::GET_COUNTER++; | ||
| 1110 | $UR::Context::all_objects_cache_size++; | ||
| 1111 | return $entity; | ||
| 1112 | } | ||
| 1113 | |||
| 1114 | sub _construct_object { | ||
| 1115 | my $self = shift; | ||
| 1116 | my $class = shift; | ||
| 1117 | |||
| 1118 | my $params = { @_ }; | ||
| 1119 | |||
| 1120 | my $id = $params->{id}; | ||
| 1121 | unless (defined($id)) { | ||
| 1122 | Carp::confess( | ||
| 1123 | "No ID specified (or incomplete id params) for $class _construct_object. Params were:\n" | ||
| 1124 | . Data::Dumper::Dumper($params) | ||
| 1125 | ); | ||
| 1126 | } | ||
| 1127 | |||
| 1128 | if ($UR::Context::all_objects_loaded->{$class}->{$id}) { | ||
| 1129 | # The object exists. This is not an exception for some reason? | ||
| 1130 | # We just return false to indicate that the object is not creatable. | ||
| 1131 | $class->error_message("An object of class $class already exists with id value '$id'"); | ||
| 1132 | return; | ||
| 1133 | } | ||
| 1134 | |||
| 1135 | my $object; | ||
| 1136 | if ($object = $UR::DeletedRef::all_objects_deleted->{$class}->{$id}) { | ||
| 1137 | UR::DeletedRef->resurrect($object); | ||
| 1138 | %$object = %$params; | ||
| 1139 | } else { | ||
| 1140 | $object = bless $params, $class; | ||
| 1141 | } | ||
| 1142 | |||
| 1143 | if (my $ghost = $UR::Context::all_objects_loaded->{$class . "::Ghost"}->{$id}) { | ||
| 1144 | # we're making something which was previously deleted and is pending save. | ||
| 1145 | # we must capture the old db_committed data to ensure eventual saving is done correctly. | ||
| 1146 | # note this object's database state in the new object so saves occurr correctly, | ||
| 1147 | # as an update instead of an insert. | ||
| 1148 | if (my $committed_data = $ghost->{db_committed}) { | ||
| 1149 | $object->{db_committed} = { %$committed_data }; | ||
| 1150 | } | ||
| 1151 | |||
| 1152 | if (my $unsaved_data = $ghost->{'db_saved_uncommitted'}) { | ||
| 1153 | $object->{'db_saved_uncommitted'} = { %$unsaved_data }; | ||
| 1154 | } | ||
| 1155 | $ghost->__signal_change__("delete"); | ||
| 1156 | $self->_abandon_object($ghost); | ||
| 1157 | } | ||
| 1158 | |||
| 1159 | # put the object in the master repository of objects for the application. | ||
| 1160 | $UR::Context::all_objects_loaded->{$class}{$id} = $object; | ||
| 1161 | |||
| 1162 | # If we're using a light cache, weaken the reference. | ||
| 1163 | if ($light_cache) { # and substr($class,0,5) ne 'App::') { | ||
| 1164 | Scalar::Util::weaken($UR::Context::all_objects_loaded->{$class}->{$id}); | ||
| 1165 | } | ||
| 1166 | |||
| 1167 | return $object; | ||
| 1168 | } | ||
| 1169 | |||
| 1170 | sub delete_entity { | ||
| 1171 | my ($self,$entity) = @_; | ||
| 1172 | |||
| 1173 | if (ref($entity)) { | ||
| 1174 | # Delete the specified object. | ||
| 1175 | if ($entity->{db_committed} || $entity->{db_saved_uncommitted}) { | ||
| 1176 | |||
| 1177 | # gather params for the ghost object | ||
| 1178 | my $do_data_source; | ||
| 1179 | my %ghost_params; | ||
| 1180 | #my @pn; | ||
| 1181 | #{ no warnings 'syntax'; | ||
| 1182 | # @pn = grep { $_ ne 'data_source_id' || ($do_data_source=1 and 0) } # yes this really is '=' and not '==' | ||
| 1183 | # grep { exists $entity->{$_} } | ||
| 1184 | # $entity->__meta__->all_property_names; | ||
| 1185 | #} | ||
| 1186 | my(@prop_names, @many_prop_names); | ||
| 1187 | foreach my $prop_name ( $entity->__meta__->all_property_names) { | ||
| 1188 | next unless exists $entity->{$prop_name}; # skip non-directly-stored properties | ||
| 1189 | if ($prop_name eq 'data_source_id') { | ||
| 1190 | $do_data_source = 1; | ||
| 1191 | next; | ||
| 1192 | } | ||
| 1193 | if (ref($entity->{$prop_name}) eq 'ARRAY') { | ||
| 1194 | push @many_prop_names, $prop_name; | ||
| 1195 | } else { | ||
| 1196 | push @prop_names, $prop_name; | ||
| 1197 | } | ||
| 1198 | } | ||
| 1199 | |||
| 1200 | |||
| 1201 | # we're not really allowed to interrogate the data_source property directly | ||
| 1202 | @ghost_params{@prop_names} = $entity->get(@prop_names); # hrm doesn't work for is_many properties :( | ||
| 1203 | foreach my $prop_name ( @many_prop_names ) { | ||
| 1204 | my @values = $entity->get($prop_name); | ||
| 1205 | $ghost_params{$prop_name} = \@values; | ||
| 1206 | } | ||
| 1207 | if ($do_data_source) { | ||
| 1208 | $ghost_params{'data_source_id'} = $entity->{'data_source_id'}; | ||
| 1209 | } | ||
| 1210 | |||
| 1211 | # create ghost object | ||
| 1212 | my $ghost = $self->_construct_object($entity->ghost_class, id => $entity->id, %ghost_params); | ||
| 1213 | unless ($ghost) { | ||
| 1214 | Carp::confess("Failed to constructe a deletion record for an unsync'd delete."); | ||
| 1215 | } | ||
| 1216 | $ghost->__signal_change__("create"); | ||
| 1217 | |||
| 1218 | for my $com (qw(db_committed db_saved_uncommitted)) { | ||
| 1219 | $ghost->{$com} = $entity->{$com} | ||
| 1220 | if $entity->{$com}; | ||
| 1221 | } | ||
| 1222 | |||
| 1223 | } | ||
| 1224 | $entity->__signal_change__('delete'); | ||
| 1225 | $self->_abandon_object($entity); | ||
| 1226 | return $entity; | ||
| 1227 | } | ||
| 1228 | else { | ||
| 1229 | Carp::confess("Can't call delete as a class method."); | ||
| 1230 | } | ||
| 1231 | } | ||
| 1232 | |||
| 1233 | sub _abandon_object { | ||
| 1234 | my $self = shift; | ||
| 1235 | my $object = $_[0]; | ||
| 1236 | my $class = $object->class; | ||
| 1237 | my $id = $object->id; | ||
| 1238 | |||
| 1239 | if ($object->{'__get_serial'}) { | ||
| 1240 | # Keep a correct accounting of objects. This one is getting deleted by a method | ||
| 1241 | # other than UR::Context::prune_object_cache | ||
| 1242 | $UR::Context::all_objects_cache_size--; | ||
| 1243 | } | ||
| 1244 | |||
| 1245 | # Remove the object from the main hash. | ||
| 1246 | delete $UR::Context::all_objects_loaded->{$class}->{$id}; | ||
| 1247 | delete $UR::Context::all_objects_are_loaded->{$class}; | ||
| 1248 | |||
| 1249 | # Remove all of the load info it is using so it'll get re-loaded if asked for later | ||
| 1250 | if ($object->{'__load'}) { | ||
| 1251 | while (my ($template_id, $rules) = each %{ $object->{'__load'}} ) { | ||
| 1252 | foreach my $rule_id ( keys %$rules ) { | ||
| 1253 | delete $UR::Context::all_params_loaded->{$template_id}->{$rule_id}; | ||
| 1254 | |||
| 1255 | foreach my $fabricator ( UR::Context::ObjectFabricator->all_object_fabricators ) { | ||
| 1256 | $fabricator->delete_from_all_params_loaded($template_id, $rule_id); | ||
| 1257 | } | ||
| 1258 | } | ||
| 1259 | } | ||
| 1260 | } | ||
| 1261 | |||
| 1262 | # Turn our $object reference into a UR::DeletedRef. | ||
| 1263 | # Further attempts to use it will result in readable errors. | ||
| 1264 | # The object can be resurrected. | ||
| 1265 | if ($ENV{'UR_DEBUG_OBJECT_RELEASE'}) { | ||
| 1266 | print STDERR "MEM DELETE object $object class ",$object->class," id ",$object->id,"\n"; | ||
| 1267 | } | ||
| 1268 | UR::DeletedRef->bury($object); | ||
| 1269 | |||
| 1270 | return $object; | ||
| 1271 | } | ||
| 1272 | |||
| 1273 | |||
| 1274 | # This one works when the rule specifies the value of an indirect property, and we want | ||
| 1275 | # the value of a direct property of the class | ||
| 1276 | sub _infer_direct_property_from_rule { | ||
| 1277 | my($self,$wanted_property_name,$rule) = @_; | ||
| 1278 | |||
| 1279 | my $rule_template = $rule->template; | ||
| 1280 | my @properties_in_rule = $rule_template->_property_names; # FIXME - why is this method private? | ||
| 1281 | my $subject_class_name = $rule->subject_class_name; | ||
| 1282 | my $subject_class_meta = $subject_class_name->__meta__; | ||
| 1283 | |||
| 1284 | my($alternate_class,$alternate_get_property, $alternate_wanted_property); | ||
| 1285 | |||
| 1286 | my @r_values; # There may be multiple properties in the rule that will get to the wanted property | ||
| 1287 | PROPERTY_IN_RULE: | ||
| 1288 | foreach my $property_name ( @properties_in_rule) { | ||
| 1289 | my $property_meta = $subject_class_meta->property_meta_for_name($property_name); | ||
| 1290 | my $final_property_meta = $property_meta->final_property_meta || $property_meta; | ||
| 1291 | $alternate_get_property = $final_property_meta->property_name; | ||
| 1292 | $alternate_class = $final_property_meta->class_name; | ||
| 1293 | |||
| 1294 | unless ($alternate_wanted_property) { | ||
| 1295 | # Either this was also a direct property of the rule, or there's no | ||
| 1296 | # obvious link between the indirect property and the wanted property. | ||
| 1297 | # the caller probably just should have done a get() | ||
| 1298 | $alternate_wanted_property = $wanted_property_name; | ||
| 1299 | $alternate_get_property = $property_name; | ||
| 1300 | $alternate_class = $subject_class_name; | ||
| 1301 | } | ||
| 1302 | |||
| 1303 | my $value_from_rule = $rule->value_for($property_name); | ||
| 1304 | my @alternate_values; | ||
| 1305 | eval { | ||
| 1306 | # Inside an eval in case the get() throws an exception, the next | ||
| 1307 | # property in the rule may succeed | ||
| 1308 | my @alternate_objects = $self->query($alternate_class, $alternate_get_property => $value_from_rule ); | ||
| 1309 | @alternate_values = map { $_->$alternate_wanted_property } @alternate_objects; | ||
| 1310 | }; | ||
| 1311 | next unless (@alternate_values); | ||
| 1312 | |||
| 1313 | push @r_values, \@alternate_values; | ||
| 1314 | } | ||
| 1315 | |||
| 1316 | if (@r_values == 0) { | ||
| 1317 | # no solutions found | ||
| 1318 | return; | ||
| 1319 | |||
| 1320 | } elsif (@r_values == 1) { | ||
| 1321 | # there was only one solution | ||
| 1322 | return @{$r_values[0]}; | ||
| 1323 | |||
| 1324 | } else { | ||
| 1325 | # multiple solutions. Only return the intersection of them all | ||
| 1326 | # FIXME - this totally won't work for properties that return objects, listrefs or hashrefs | ||
| 1327 | # FIXME - this only works for AND rules - for now, that's all that exist | ||
| 1328 | my %intersection = map { $_ => 1 } @{ shift @r_values }; | ||
| 1329 | foreach my $list ( @r_values ) { | ||
| 1330 | %intersection = map { $_ => 1 } grep { $intersection{$_} } @$list; | ||
| 1331 | } | ||
| 1332 | return keys %intersection; | ||
| 1333 | } | ||
| 1334 | } | ||
| 1335 | |||
| 1336 | |||
| 1337 | # we want the value of a delegated property, and the rule specifies | ||
| 1338 | # a direct value | ||
| 1339 | sub _infer_delegated_property_from_rule { | ||
| 1340 | my($self, $wanted_property_name, $rule) = @_; | ||
| 1341 | |||
| 1342 | my $rule_template = $rule->template; | ||
| 1343 | my $subject_class_name = $rule->subject_class_name; | ||
| 1344 | my $subject_class_meta = $subject_class_name->__meta__; | ||
| 1345 | |||
| 1346 | my $wanted_property_meta = $subject_class_meta->property_meta_for_name($wanted_property_name); | ||
| 1347 | unless ($wanted_property_meta->via) { | ||
| 1348 | Carp::croak("There is no linking meta-property (via) on property $wanted_property_name on $subject_class_name"); | ||
| 1349 | } | ||
| 1350 | |||
| 1351 | my $linking_property_meta = $subject_class_meta->property_meta_for_name($wanted_property_meta->via); | ||
| 1352 | my $final_property_meta = $wanted_property_meta->final_property_meta; | ||
| 1353 | |||
| 1354 | if ($linking_property_meta->reverse_as) { | ||
| 1355 | eval{ $linking_property_meta->data_type->class() }; # Load the class if it isn't already loaded | ||
| 1356 | if ($linking_property_meta->data_type ne $final_property_meta->class_name) { | ||
| 1357 | Carp::croak("UR::Context::_infer_delegated_property_from_rule() doesn't handle multiple levels of indiretion yet"); | ||
| 1358 | } | ||
| 1359 | } | ||
| 1360 | |||
| 1361 | my @rule_translation = $linking_property_meta->get_property_name_pairs_for_join(); | ||
| 1362 | |||
| 1363 | my %alternate_get_params; | ||
| 1364 | foreach my $pair ( @rule_translation ) { | ||
| 1365 | my $rule_param = $pair->[0]; | ||
| 1366 | next unless ($rule_template->specifies_value_for($rule_param)); | ||
| 1367 | my $alternate_param = $pair->[1]; | ||
| 1368 | |||
| 1369 | my $value = $rule->value_for($rule_param); | ||
| 1370 | $alternate_get_params{$alternate_param} = $value; | ||
| 1371 | } | ||
| 1372 | |||
| 1373 | my $alternate_class = $final_property_meta->class_name; | ||
| 1374 | my $alternate_wanted_property = $wanted_property_meta->to; | ||
| 1375 | my @alternate_values; | ||
| 1376 | eval { | ||
| 1377 | my @alternate_objects = $self->query($alternate_class, %alternate_get_params); | ||
| 1378 | @alternate_values = map { $_->$alternate_wanted_property } @alternate_objects; | ||
| 1379 | }; | ||
| 1380 | return @alternate_values; | ||
| 1381 | } | ||
| 1382 | |||
| 1383 | |||
| 1384 | sub object_cache_size_highwater { | ||
| 1385 | my $self = shift; | ||
| 1386 | |||
| 1387 | if (@_) { | ||
| 1388 | my $value = shift; | ||
| 1389 | $cache_size_highwater = $value; | ||
| 1390 | |||
| 1391 | if (defined $value) { | ||
| 1392 | if ($cache_size_lowwater and $value <= $cache_size_lowwater) { | ||
| 1393 | Carp::confess("Can't set the highwater mark less than or equal to the lowwater mark"); | ||
| 1394 | return; | ||
| 1395 | } | ||
| 1396 | $self->prune_object_cache(); | ||
| 1397 | } | ||
| 1398 | manage_objects_may_go_out_of_scope(); | ||
| 1399 | } | ||
| 1400 | return $cache_size_highwater; | ||
| 1401 | } | ||
| 1402 | |||
| 1403 | sub object_cache_size_lowwater { | ||
| 1404 | my $self = shift; | ||
| 1405 | if (@_) { | ||
| 1406 | my $value = shift; | ||
| 1407 | $cache_size_lowwater = $value; | ||
| 1408 | |||
| 1409 | if (defined($value) and $cache_size_highwater and $value >= $cache_size_highwater) { | ||
| 1410 | Carp::confess("Can't set the lowwater mark greater than or equal to the highwater mark"); | ||
| 1411 | return; | ||
| 1412 | } | ||
| 1413 | } | ||
| 1414 | return $cache_size_lowwater; | ||
| 1415 | } | ||
| 1416 | |||
| 1417 | |||
| 1418 | sub get_data_sources_for_loaded_classes { | ||
| 1419 | my $class = shift; | ||
| 1420 | |||
| 1421 | my %data_source_for_class; | ||
| 1422 | foreach my $class ( keys %$UR::Context::all_objects_loaded ) { | ||
| 1423 | next if (substr($class,0,-6) eq '::Type'); # skip class objects | ||
| 1424 | |||
| 1425 | next unless exists $UR::Context::all_objects_loaded->{$class . '::Type'}; | ||
| 1426 | my $class_meta = $UR::Context::all_objects_loaded->{$class . '::Type'}->{$class}; | ||
| 1427 | next unless $class_meta; | ||
| 1428 | next unless ($class_meta->is_uncachable()); | ||
| 1429 | $data_source_for_class{$class} = $class_meta->data_source_id; | ||
| 1430 | } | ||
| 1431 | |||
| 1432 | return %data_source_for_class; | ||
| 1433 | } | ||
| 1434 | |||
| 1435 | |||
| 1436 | our $is_pruning = 0; | ||
| 1437 | sub prune_object_cache { | ||
| 1438 | my $self = shift; | ||
| 1439 | |||
| 1440 | return if ($is_pruning); # Don't recurse into here | ||
| 1441 | |||
| 1442 | return if (!defined($cache_size_highwater) or !defined($cache_size_lowwater)); | ||
| 1443 | return unless ($all_objects_cache_size > $cache_size_highwater); | ||
| 1444 | |||
| 1445 | $is_pruning = 1; | ||
| 1446 | my $t1; | ||
| 1447 | if ($ENV{'UR_DEBUG_OBJECT_RELEASE'} || $ENV{'UR_DEBUG_OBJECT_PRUNING'}) { | ||
| 1448 | $t1 = Time::HiRes::time(); | ||
| 1449 | print STDERR Carp::longmess("MEM PRUNE begin at $t1 ",scalar(localtime($t1)),"\n"); | ||
| 1450 | } | ||
| 1451 | |||
| 1452 | my $index_id_sep = UR::Object::Index->__meta__->composite_id_separator() || "\t"; | ||
| 1453 | |||
| 1454 | my %data_source_for_class = $self->get_data_sources_for_loaded_classes; | ||
| 1455 | |||
| 1456 | # NOTE: This pokes right into the object cache and futzes with Index IDs directly. | ||
| 1457 | # We can't get the Index objects though get() because we'd recurse right back into here | ||
| 1458 | my %indexes_by_class; | ||
| 1459 | foreach my $idx_id ( keys %{$UR::Context::all_objects_loaded->{'UR::Object::Index'}} ) { | ||
| 1460 | my $class = substr($idx_id, 0, index($idx_id, $index_id_sep)); | ||
| 1461 | next unless exists $data_source_for_class{$class}; | ||
| 1462 | push @{$indexes_by_class{$class}}, $UR::Context::all_objects_loaded->{'UR::Object::Index'}->{$idx_id}; | ||
| 1463 | } | ||
| 1464 | |||
| 1465 | my $deleted_count = 0; | ||
| 1466 | my $pass = 0; | ||
| 1467 | |||
| 1468 | $cache_size_highwater = 1 if ($cache_size_highwater < 1); | ||
| 1469 | $cache_size_lowwater = 1 if ($cache_size_lowwater < 1); | ||
| 1470 | |||
| 1471 | # Instead of sorting object cache by __get_serial, since we are trying to | ||
| 1472 | # conserve memory, we pass through the object cache reviewing chunks of older objects | ||
| 1473 | # first while working our way through the whole cache. | ||
| 1474 | my $target_serial = $cache_last_prune_serial; | ||
| 1475 | |||
| 1476 | my $serial_range = ($GET_COUNTER - $target_serial); | ||
| 1477 | my $max_passes = 10; | ||
| 1478 | my $target_serial_increment = int($serial_range / $max_passes) + 1; | ||
| 1479 | while ($all_objects_cache_size > $cache_size_lowwater && $target_serial < $GET_COUNTER) { | ||
| 1480 | $pass++; | ||
| 1481 | $target_serial += $target_serial_increment; | ||
| 1482 | |||
| 1483 | my @objects_to_prune; | ||
| 1484 | foreach my $class (keys %data_source_for_class) { | ||
| 1485 | my $objects_for_class = $UR::Context::all_objects_loaded->{$class}; | ||
| 1486 | $indexes_by_class{$class} ||= []; | ||
| 1487 | |||
| 1488 | foreach my $id ( keys ( %$objects_for_class ) ) { | ||
| 1489 | my $obj = $objects_for_class->{$id}; | ||
| 1490 | next unless defined $obj; # object with this ID does not exist | ||
| 1491 | if ( | ||
| 1492 | $obj->is_weakened | ||
| 1493 | || $obj->is_prunable && $obj->{__get_serial} && $obj->{__get_serial} <= $target_serial | ||
| 1494 | ) { | ||
| 1495 | if ($ENV{'UR_DEBUG_OBJECT_RELEASE'}) { | ||
| 1496 | print STDERR "MEM PRUNE object $obj class $class id $id\n"; | ||
| 1497 | } | ||
| 1498 | push @objects_to_prune, $obj; | ||
| 1499 | $deleted_count++; | ||
| 1500 | } | ||
| 1501 | } | ||
| 1502 | } | ||
| 1503 | $self->_weaken_references_for_objects(\@objects_to_prune); | ||
| 1504 | } | ||
| 1505 | $is_pruning = 0; | ||
| 1506 | |||
| 1507 | $cache_last_prune_serial = $target_serial; | ||
| 1508 | if ($ENV{'UR_DEBUG_OBJECT_RELEASE'} || $ENV{'UR_DEBUG_OBJECT_PRUNING'}) { | ||
| 1509 | my $t2 = Time::HiRes::time(); | ||
| 1510 | printf("MEM PRUNE complete, $deleted_count objects marked after $pass passes in %.4f sec\n\n\n",$t2-$t1); | ||
| 1511 | } | ||
| 1512 | if ($all_objects_cache_size > $cache_size_lowwater) { | ||
| 1513 | Carp::carp "After several passes of pruning the object cache, there are still $all_objects_cache_size objects"; | ||
| 1514 | if ($ENV{'UR_DEBUG_OBJECT_PRUNING'}) { | ||
| 1515 | warn "Top 10 classes by object count:\n" . $self->_object_cache_pruning_report; | ||
| 1516 | } | ||
| 1517 | } | ||
| 1518 | return 1; | ||
| 1519 | } | ||
| 1520 | |||
| 1521 | sub _weaken_references_for_objects { | ||
| 1522 | my($self, $obj_list) = @_; | ||
| 1523 | |||
| 1524 | Carp::croak('Argument to _weaken_references_to_objects must be an arrayref') | ||
| 1525 | unless ref($obj_list) eq 'ARRAY'; | ||
| 1526 | |||
| 1527 | my %indexes_by_class; | ||
| 1528 | foreach my $obj ( @$obj_list) { | ||
| 1529 | my $class = $obj->class; | ||
| 1530 | $indexes_by_class{ $class } ||= [ UR::Object::Index->get(indexed_class_name => $class) ]; | ||
| 1531 | |||
| 1532 | $_->weaken_reference_for_object($obj) foreach @{ $indexes_by_class{ $class }}; | ||
| 1533 | delete $obj->{__get_serial}; | ||
| 1534 | Scalar::Util::weaken($UR::Context::all_objects_loaded->{$class}->{$obj->id}); | ||
| 1535 | $all_objects_cache_size--; | ||
| 1536 | } | ||
| 1537 | } | ||
| 1538 | |||
| 1539 | |||
| 1540 | sub _object_cache_pruning_report { | ||
| 1541 | my $self = shift; | ||
| 1542 | my $max_show = shift; | ||
| 1543 | |||
| 1544 | $max_show = 10 unless defined ($max_show); | ||
| 1545 | |||
| 1546 | my @sorted_counts = sort { $b->[1] <=> $a->[1] } | ||
| 1547 | map { [ $_ => scalar(keys %{$UR::Context::all_objects_loaded->{$_}}) ] } | ||
| 1548 | grep { !$_->__meta__->is_meta_meta } | ||
| 1549 | keys %$UR::Context::all_objects_loaded; | ||
| 1550 | my $message = ''; | ||
| 1551 | for (my $i = 0; $i < 10 and $i < @sorted_counts; $i++) { | ||
| 1552 | my $class_name = $sorted_counts[$i]->[0]; | ||
| 1553 | my $count = $sorted_counts[$i]->[1]; | ||
| 1554 | $message .= "$class_name: $count\n"; | ||
| 1555 | |||
| 1556 | if ($ENV{'UR_DEBUG_OBJECT_PRUNING'} > 1) { | ||
| 1557 | # more detailed info | ||
| 1558 | my $no_data_source = 0; | ||
| 1559 | my $other_references = 0; | ||
| 1560 | my $strengthened = 0; | ||
| 1561 | my $has_changes = 0; | ||
| 1562 | my $prunable = 0; | ||
| 1563 | my $class_data_source = eval { $class_name->__meta__->data_source_id; }; | ||
| 1564 | foreach my $obj ( values %{$UR::Context::all_objects_loaded->{$class_name}} ) { | ||
| 1565 | next unless $obj; | ||
| 1566 | |||
| 1567 | my $is_prunable = 1; | ||
| 1568 | if (! $class_data_source ) { | ||
| 1569 | $no_data_source++; | ||
| 1570 | $is_prunable = 0; | ||
| 1571 | } | ||
| 1572 | if (! exists $obj->{'__get_serial'}) { | ||
| 1573 | $other_references++; | ||
| 1574 | $is_prunable = 0; | ||
| 1575 | } | ||
| 1576 | if (exists $obj->{'__strengthened'}) { | ||
| 1577 | $strengthened++; | ||
| 1578 | $is_prunable = 0; | ||
| 1579 | } | ||
| 1580 | if ($obj->__changes__) { | ||
| 1581 | $has_changes++; | ||
| 1582 | $is_prunable = 0; | ||
| 1583 | } | ||
| 1584 | if ($is_prunable) { | ||
| 1585 | $prunable++; | ||
| 1586 | } | ||
| 1587 | } | ||
| 1588 | $message .= sprintf("\tNo data source: %d other refs: %d strengthend: %d has changes: %d prunable: %d\n", | ||
| 1589 | $no_data_source, $other_references, $strengthened, $has_changes, $prunable); | ||
| 1590 | } | ||
| 1591 | } | ||
| 1592 | return $message; | ||
| 1593 | } | ||
| 1594 | |||
| 1595 | |||
| 1596 | sub value_for_object_property_in_underlying_context { | ||
| 1597 | my ($self, $obj, $property_name) = @_; | ||
| 1598 | |||
| 1599 | my $saved = $obj->{db_saved_uncommitted} || $obj->{db_committed}; | ||
| 1600 | unless ($saved) { | ||
| 1601 | Carp::croak(qq(No object found in underlying context)); | ||
| 1602 | } | ||
| 1603 | |||
| 1604 | return $saved->{$property_name}; | ||
| 1605 | } | ||
| 1606 | |||
| 1607 | |||
| 1608 | # True if the object was loaded from an underlying context and/or datasource, or if the | ||
| 1609 | # object has been committed to the underlying context | ||
| 1610 | sub object_exists_in_underlying_context { | ||
| 1611 | my($self, $obj) = @_; | ||
| 1612 | |||
| 1613 | return if ($obj->{'__defined'}); | ||
| 1614 | return (exists($obj->{'db_committed'}) || exists($obj->{'db_saved_uncommitted'})); | ||
| 1615 | } | ||
| 1616 | |||
| 1617 | |||
| 1618 | # Holds the logic for handling OR-type rules passed to get_objects_for_class_and_rule() | ||
| 1619 | sub _get_objects_for_class_and_or_rule { | ||
| 1620 | my ($self, $class, $rule, $load, $return_closure) = @_; | ||
| 1621 | |||
| 1622 | $rule = $rule->normalize; | ||
| 1623 | my @u = $rule->underlying_rules; | ||
| 1624 | my @results; | ||
| 1625 | for my $u (@u) { | ||
| 1626 | if (wantarray or not defined wantarray) { | ||
| 1627 | push @results, $self->get_objects_for_class_and_rule($class,$u,$load,$return_closure); | ||
| 1628 | } | ||
| 1629 | else { | ||
| 1630 | my $result = $self->get_objects_for_class_and_rule($class,$u,$load,$return_closure); | ||
| 1631 | push @results, $result; | ||
| 1632 | } | ||
| 1633 | } | ||
| 1634 | if ($return_closure) { | ||
| 1635 | my $object_sorter = $rule->template->sorter(); | ||
| 1636 | |||
| 1637 | my @next; | ||
| 1638 | return sub { | ||
| 1639 | # fill in missing slots in @next | ||
| 1640 | for(my $i = 0; $i < @results; $i++) { | ||
| 1641 | unless (defined $next[$i]) { | ||
| 1642 | # This slot got used last time through | ||
| 1643 | $next[$i] = $results[$i]->(); | ||
| 1644 | unless (defined $next[$i]) { | ||
| 1645 | # That iterator is exhausted, splice it out | ||
| 1646 | splice(@results, $i, 1); | ||
| 1647 | splice(@next, $i, 1); | ||
| 1648 | redo if $i < @results; #the next iterator is now at $i, not $i++ | ||
| 1649 | } | ||
| 1650 | } | ||
| 1651 | } | ||
| 1652 | |||
| 1653 | my $lowest_slot = 0; | ||
| 1654 | for(my $i = 1; $i < @results; $i++) { | ||
| 1655 | my $cmp = $object_sorter->($next[$lowest_slot], $next[$i]); | ||
| 1656 | if ($cmp > 0) { | ||
| 1657 | $lowest_slot = $i; | ||
| 1658 | } elsif ($cmp == 0) { | ||
| 1659 | # duplicate object, mark this slot to fill in next time around | ||
| 1660 | $next[$i] = undef; | ||
| 1661 | } | ||
| 1662 | } | ||
| 1663 | |||
| 1664 | my $retval = $next[$lowest_slot]; | ||
| 1665 | $next[$lowest_slot] = undef; | ||
| 1666 | return $retval; | ||
| 1667 | }; | ||
| 1668 | } | ||
| 1669 | |||
| 1670 | # remove duplicates | ||
| 1671 | my $last = 0; | ||
| 1672 | my $plast = 0; | ||
| 1673 | my $next = 0; | ||
| 1674 | @results = grep { $plast = $last; $last = $_; $plast == $_ ? () : ($_) } sort @results; | ||
| 1675 | |||
| 1676 | return unless defined wantarray; | ||
| 1677 | return @results if wantarray; | ||
| 1678 | if (@results > 1) { | ||
| 1679 | $self->_exception_for_multi_objects_in_scalar_context($rule,\@results); | ||
| 1680 | } | ||
| 1681 | return $results[0]; | ||
| 1682 | } | ||
| 1683 | |||
| 1684 | |||
| 1685 | # this is the underlying method for get/load/is_loaded in ::Object | ||
| 1686 | |||
| 1687 | sub get_objects_for_class_and_rule { | ||
| 1688 | my ($self, $class, $rule, $load, $return_closure) = @_; | ||
| 1689 | my $initial_load = $load; | ||
| 1690 | #my @params = $rule->params_list; | ||
| 1691 | #print "GET: $class @params\n"; | ||
| 1692 | |||
| 1693 | my $rule_template = $rule->template; | ||
| 1694 | |||
| 1695 | my $group_by = $rule_template->group_by; | ||
| 1696 | |||
| 1697 | if (ref($self) and !defined($load)) { | ||
| 1698 | $load = $self->query_underlying_context; # could still be undef... | ||
| 1699 | } | ||
| 1700 | |||
| 1701 | if ($group_by and $rule_template->order_by) { | ||
| 1702 | my %group_by = map { $_ => 1 } @{ $rule->template->group_by }; | ||
| 1703 | foreach my $order_by_property ( @{ $rule->template->order_by } ) { | ||
| 1704 | unless ($group_by{$order_by_property}) { | ||
| 1705 | Carp::croak("Property '$order_by_property' in the -order_by list must appear in the -group_by list for BoolExpr $rule"); | ||
| 1706 | } | ||
| 1707 | } | ||
| 1708 | } | ||
| 1709 | |||
| 1710 | if ( | ||
| 1711 | $cache_size_highwater | ||
| 1712 | and | ||
| 1713 | $all_objects_cache_size > $cache_size_highwater | ||
| 1714 | ) { | ||
| 1715 | $self->prune_object_cache(); | ||
| 1716 | } | ||
| 1717 | |||
| 1718 | if ($rule_template->isa("UR::BoolExpr::Template::Or")) { | ||
| 1719 | return $self->_get_objects_for_class_and_or_rule($class,$rule,$load,$return_closure); | ||
| 1720 | } | ||
| 1721 | |||
| 1722 | # an identifier for all objects gotten in this request will be set/updated on each of them for pruning later | ||
| 1723 | my $this_get_serial = $GET_COUNTER++; | ||
| 1724 | |||
| 1725 | my $meta = $class->__meta__(); | ||
| 1726 | |||
| 1727 | # A query on a subclass where the parent class is_abstract and has a subclassify_by property | ||
| 1728 | # (meaning that the parent class has a property which directly stores the proper subclass for | ||
| 1729 | # each row - subclasses inherit the property from the parent, and the subclass isn't is_abstract) | ||
| 1730 | # should have a filter added to the rule to keep only rows of the subclass we're interested in. | ||
| 1731 | # This will improve the SQL performance when it's later constructed. | ||
| 1732 | my $subclassify_by = $meta->subclassify_by; | ||
| 1733 | if ($subclassify_by | ||
| 1734 | and ! $meta->is_abstract | ||
| 1735 | and ! $rule->template->group_by | ||
| 1736 | and ! $rule->specifies_value_for($subclassify_by) | ||
| 1737 | ) { | ||
| 1738 | $rule = $rule->add_filter($subclassify_by => $class); | ||
| 1739 | } | ||
| 1740 | |||
| 1741 | # If $load is undefined, and there is no underlying context, we define it to FALSE explicitly | ||
| 1742 | # TODO: instead of checking for a data source, skip this | ||
| 1743 | # We'll always go to the underlying context, even if it has nothing. | ||
| 1744 | # This optimization only works by coincidence since we don't stack contexts currently beyond 1. | ||
| 1745 | my $ds; | ||
| 1746 | if (!defined($load) or $load) { | ||
| 1747 | ($ds) = $self->resolve_data_sources_for_class_meta_and_rule($meta,$rule); | ||
| 1748 | if (! $ds or $class =~ m/::Ghost$/) { | ||
| 1749 | # Classes without data sources and Ghosts can only ever come from the cache | ||
| 1750 | $load = 0; | ||
| 1751 | } | ||
| 1752 | } | ||
| 1753 | |||
| 1754 | # this is an arrayref of all of the cached data | ||
| 1755 | # it is set in one of two places below | ||
| 1756 | my $cached; | ||
| 1757 | |||
| 1758 | # this will turn foo=>$foo into foo.id=>$foo->id where possible | ||
| 1759 | my $no_hard_refs_rule = $rule->flatten_hard_refs; | ||
| 1760 | |||
| 1761 | # we do not currently fully "flatten" b/c the bx constant_values do not flatten/reframe | ||
| 1762 | #my $flat_rule = ( (1 or $no_hard_refs_rule->subject_class_name eq 'UR::Object::Property') ? $no_hard_refs_rule : $no_hard_refs_rule->flatten); | ||
| 1763 | |||
| 1764 | # this is a no-op if the rule is already normalized | ||
| 1765 | my $normalized_rule = $no_hard_refs_rule->normalize; | ||
| 1766 | |||
| 1767 | my $is_monitor_query = $self->monitor_query; | ||
| 1768 | $self->_log_query_for_rule($class,$normalized_rule,Carp::shortmess("QUERY: Query start for rule $normalized_rule")) if ($is_monitor_query); | ||
| 1769 | |||
| 1770 | # see if we need to load if load was not defined | ||
| 1771 | unless (defined $load) { | ||
| 1772 | # check to see if the cache is complete | ||
| 1773 | # also returns a list of the complete cached objects where that list is found as a side-effect | ||
| 1774 | my ($cache_is_complete, $cached) = $self->_cache_is_complete_for_class_and_normalized_rule($class, $normalized_rule); | ||
| 1775 | $load = ($cache_is_complete ? 0 : 1); | ||
| 1776 | } | ||
| 1777 | |||
| 1778 | if ($ds and $load and $rule_template->order_by) { | ||
| 1779 | # if any of the order_by is calculated, then we need to do an unordered query against the | ||
| 1780 | # data source, then we can do it as a non-load query and do the sorting on all the in-memory | ||
| 1781 | # objects | ||
| 1782 | my $qp = $ds->_resolve_query_plan($rule_template); | ||
| 1783 | if ($qp->order_by_non_column_data) { | ||
| 1784 | $self->_log_query_for_rule($class,$normalized_rule,"QUERY: Doing an unordered query on the datasource because one of the order_by properties of the rule is not expressable by the data source") if ($is_monitor_query); | ||
| 1785 | $self->get_objects_for_class_and_rule($class, $rule->remove_filter('-order')->remove_filter('-order_by'), 1); | ||
| 1786 | $load = 0; | ||
| 1787 | } | ||
| 1788 | } | ||
| 1789 | |||
| 1790 | my $normalized_rule_template = $normalized_rule->template; | ||
| 1791 | |||
| 1792 | # optimization for the common case | ||
| 1793 | if (!$load and !$return_closure) { | ||
| 1794 | my @c = $self->_get_objects_for_class_and_rule_from_cache($class,$normalized_rule); | ||
| 1795 | my $obj_count = scalar(@c); | ||
| 1796 | foreach ( @c ) { | ||
| 1797 | unless (exists $_->{'__get_serial'}) { | ||
| 1798 | # This is a weakened reference. Convert it back to a regular ref | ||
| 1799 | my $class = ref $_; | ||
| 1800 | my $id = $_->id; | ||
| 1801 | my $ref = $UR::Context::all_objects_loaded->{$class}->{$id}; | ||
| 1802 | $UR::Context::all_objects_loaded->{$class}->{$id} = $ref; | ||
| 1803 | } | ||
| 1804 | $_->{'__get_serial'} = $this_get_serial; | ||
| 1805 | } | ||
| 1806 | |||
| 1807 | if ($is_monitor_query) { | ||
| 1808 | $self->_log_query_for_rule($class,$normalized_rule,"QUERY: matched $obj_count cached objects (no loading)"); | ||
| 1809 | $self->_log_query_for_rule($class,$normalized_rule,"QUERY: Query complete after returning $obj_count object(s) for rule $rule"); | ||
| 1810 | $self->_log_done_elapsed_time_for_rule($normalized_rule); | ||
| 1811 | } | ||
| 1812 | |||
| 1813 | if (defined($normalized_rule_template->limit) || defined($normalized_rule_template->offset)) { | ||
| 1814 | $self->_prune_obj_list_for_limit_and_offset(\@c,$normalized_rule_template); | ||
| 1815 | } | ||
| 1816 | |||
| 1817 | return @c if wantarray; # array context | ||
| 1818 | return unless defined wantarray; # null context | ||
| 1819 | Carp::confess("multiple objects found for a call in scalar context!" . Data::Dumper::Dumper(\@c)) if @c > 1; | ||
| 1820 | return $c[0]; # scalar context | ||
| 1821 | } | ||
| 1822 | |||
| 1823 | my $object_sorter = $normalized_rule_template->sorter(); | ||
| 1824 | |||
| 1825 | # the above process might have found all of the cached data required as a side-effect in which case | ||
| 1826 | # we have a value for this early | ||
| 1827 | # either way: ensure the cached data is known and sorted | ||
| 1828 | if ($cached) { | ||
| 1829 | @$cached = sort $object_sorter @$cached; | ||
| 1830 | } | ||
| 1831 | else { | ||
| 1832 | $cached = [ sort $object_sorter $self->_get_objects_for_class_and_rule_from_cache($class,$normalized_rule) ]; | ||
| 1833 | } | ||
| 1834 | $self->_log_query_for_rule($class, $normalized_rule, "QUERY: matched ".scalar(@$cached)." cached objects") if ($is_monitor_query); | ||
| 1835 | foreach ( @$cached ) { | ||
| 1836 | unless (exists $_->{'__get_serial'}) { | ||
| 1837 | # This is a weakened reference. Convert it back to a regular ref | ||
| 1838 | my $class = ref $_; | ||
| 1839 | my $id = $_->id; | ||
| 1840 | my $ref = $UR::Context::all_objects_loaded->{$class}->{$id}; | ||
| 1841 | $UR::Context::all_objects_loaded->{$class}->{$id} = $ref; | ||
| 1842 | } | ||
| 1843 | $_->{'__get_serial'} = $this_get_serial; | ||
| 1844 | } | ||
| 1845 | |||
| 1846 | |||
| 1847 | # make a loading iterator if loading must be done for this rule | ||
| 1848 | my $loading_iterator; | ||
| 1849 | if ($load) { | ||
| 1850 | # this returns objects from the underlying context after importing them into the current context, | ||
| 1851 | # but only if they did not exist in the current context already | ||
| 1852 | $self->_log_query_for_rule($class, $normalized_rule, "QUERY: importing from underlying context with rule $normalized_rule") if ($is_monitor_query); | ||
| 1853 | |||
| 1854 | $loading_iterator = UR::Context::LoadingIterator->_create($cached, $self,$normalized_rule, $ds,$this_get_serial); | ||
| 1855 | } | ||
| 1856 | |||
| 1857 | if ($return_closure) { | ||
| 1858 | if ($load) { | ||
| 1859 | # return the iterator made above | ||
| 1860 | return $loading_iterator; | ||
| 1861 | } | ||
| 1862 | else { | ||
| 1863 | # make a quick iterator for the cached data | ||
| 1864 | if(defined($normalized_rule_template->limit) || defined($normalized_rule_template->offset)) { | ||
| 1865 | $self->_prune_obj_list_for_limit_and_offset($cached,$normalized_rule_template); | ||
| 1866 | } | ||
| 1867 | return sub { return shift @$cached }; | ||
| 1868 | } | ||
| 1869 | } | ||
| 1870 | else { | ||
| 1871 | my @results; | ||
| 1872 | if ($loading_iterator) { | ||
| 1873 | # use the iterator made above | ||
| 1874 | my $found; | ||
| 1875 | while (defined($found = $loading_iterator->(1))) { | ||
| 1876 | push @results, $found; | ||
| 1877 | } | ||
| 1878 | } | ||
| 1879 | else { | ||
| 1880 | # just get the cached data | ||
| 1881 | if(defined($normalized_rule_template->limit) || defined($normalized_rule_template->offset)) { | ||
| 1882 | $self->_prune_obj_list_for_limit_and_offset($cached,$normalized_rule_template); | ||
| 1883 | } | ||
| 1884 | @results = @$cached; | ||
| 1885 | } | ||
| 1886 | return unless defined wantarray; | ||
| 1887 | return @results if wantarray; | ||
| 1888 | if (@results > 1) { | ||
| 1889 | $self->_exception_for_multi_objects_in_scalar_context($rule,\@results); | ||
| 1890 | } | ||
| 1891 | return $results[0]; | ||
| 1892 | } | ||
| 1893 | } | ||
| 1894 | |||
| 1895 | |||
| 1896 | sub _exception_for_multi_objects_in_scalar_context { | ||
| 1897 | my($self,$rule,$resultsref) = @_; | ||
| 1898 | |||
| 1899 | my $message = sprintf("Multiple results unexpected for query.\n\tClass %s\n\trule params: %s\n\tGot %d results", | ||
| 1900 | $rule->subject_class_name, | ||
| 1901 | join(',', $rule->params_list), | ||
| 1902 | scalar(@$resultsref)); | ||
| 1903 | my $lastidx = $#$resultsref; | ||
| 1904 | if (@$resultsref > 10) { | ||
| 1905 | $message .= "; the first 10 are"; | ||
| 1906 | $lastidx = 9; | ||
| 1907 | } | ||
| 1908 | Carp::confess($message . ":\n" . Data::Dumper::Dumper([@$resultsref[0..$lastidx]])); | ||
| 1909 | } | ||
| 1910 | |||
| 1911 | sub _prune_obj_list_for_limit_and_offset { | ||
| 1912 | my($self, $obj_list, $tmpl) = @_; | ||
| 1913 | |||
| 1914 | my $limit = defined($tmpl->limit) ? $tmpl->limit : $#$obj_list; | ||
| 1915 | my $offset = $tmpl->offset || 0; | ||
| 1916 | |||
| 1917 | if ($offset > @$obj_list) { | ||
| 1918 | Carp::carp('-offset is larger than the result list'); | ||
| 1919 | @$obj_list = (); | ||
| 1920 | } else { | ||
| 1921 | @$obj_list = splice(@$obj_list, $offset, $limit); | ||
| 1922 | } | ||
| 1923 | } | ||
| 1924 | |||
| 1925 | |||
| 1926 | sub __merge_db_data_with_existing_object { | ||
| 1927 | my($self, $class_name, $existing_object, $pending_db_object_data, $property_names) = @_; | ||
| 1928 | |||
| 1929 | unless (defined $pending_db_object_data) { | ||
| 1930 | # This means a row in the database is missing for an object we loaded before | ||
| 1931 | if (defined($existing_object) | ||
| 1932 | and $self->object_exists_in_underlying_context($existing_object) | ||
| 1933 | and $existing_object->__changes__ | ||
| 1934 | ) { | ||
| 1935 | my $id = $existing_object->id; | ||
| 1936 | Carp::croak("$class_name ID '$id' previously existed in an underlying context, has since been deleted from that context, and the cached object now has unsavable changes.\nDump: ".Data::Dumper::Dumper($existing_object)."\n"); | ||
| 1937 | } else { | ||
| 1938 | #print "Removing object id ".$existing_object->id." because it has been removed from the database\n"; | ||
| 1939 | UR::Context::LoadingIterator->_remove_object_from_other_loading_iterators($existing_object); | ||
| 1940 | $existing_object->__signal_change__('delete'); | ||
| 1941 | $self->_abandon_object($existing_object); | ||
| 1942 | return $existing_object; | ||
| 1943 | } | ||
| 1944 | } | ||
| 1945 | |||
| 1946 | my $expected_db_data; | ||
| 1947 | if (exists $existing_object->{'db_saved_uncommitted'}) { | ||
| 1948 | $expected_db_data = $existing_object->{'db_saved_uncommitted'}; | ||
| 1949 | |||
| 1950 | } elsif (exists $existing_object->{'db_committed'}) { | ||
| 1951 | $expected_db_data = $existing_object->{'db_committed'}; | ||
| 1952 | |||
| 1953 | } else { | ||
| 1954 | my $id = $existing_object->id; | ||
| 1955 | Carp::croak("$class_name ID '$id' has just been loaded, but it exists in the application as a new unsaved object!\nDump: " . Data::Dumper::Dumper($existing_object) . "\n"); | ||
| 1956 | } | ||
| 1957 | |||
| 1958 | my $different = 0; | ||
| 1959 | my $conflict = undef; | ||
| 1960 | |||
| 1961 | foreach my $property ( @$property_names ) { | ||
| 1962 | no warnings 'uninitialized'; | ||
| 1963 | |||
| 1964 | # All direct properties are stored in the same-named hash key, right? | ||
| 1965 | next unless (exists $existing_object->{$property}); | ||
| 1966 | |||
| 1967 | my $object_value = $existing_object->{$property}; | ||
| 1968 | my $db_value = $pending_db_object_data->{$property}; | ||
| 1969 | my $expected_db_value = $expected_db_data->{$property}; | ||
| 1970 | |||
| 1971 | if ($object_value ne $expected_db_value) { | ||
| 1972 | $different++; | ||
| 1973 | } | ||
| 1974 | |||
| 1975 | |||
| 1976 | if ( $object_value eq $db_value # current value matches DB value | ||
| 1977 | or | ||
| 1978 | ($object_value eq $expected_db_value) # current value hasn't changed since it was loaded from the DB | ||
| 1979 | or | ||
| 1980 | ($db_value eq $expected_db_value) # DB value matches what it was when we loaded it from the DB | ||
| 1981 | ) { | ||
| 1982 | # no conflict. Check the next one | ||
| 1983 | next; | ||
| 1984 | } else { | ||
| 1985 | $conflict = $property; | ||
| 1986 | last; | ||
| 1987 | } | ||
| 1988 | } | ||
| 1989 | |||
| 1990 | if (defined $conflict) { | ||
| 1991 | # conflicting change! | ||
| 1992 | # Since the user could be catching this exception, go ahead and update the | ||
| 1993 | # object's notion of what is in the database | ||
| 1994 | my %old_dbc = %$expected_db_data; | ||
| 1995 | @$expected_db_data{@$property_names} = @$pending_db_object_data{@$property_names}; | ||
| 1996 | |||
| 1997 | my $old_value = defined($old_dbc{$conflict}) | ||
| 1998 | ? "'" . $old_dbc{$conflict} . "'" | ||
| 1999 | : '(undef)'; | ||
| 2000 | my $new_db_value = defined($pending_db_object_data->{$conflict}) | ||
| 2001 | ? "'" . $pending_db_object_data->{$conflict} . "'" | ||
| 2002 | : '(undef)'; | ||
| 2003 | my $new_obj_value = defined($existing_object->{$conflict}) | ||
| 2004 | ? "'" . $existing_object->{$conflict} . "'" | ||
| 2005 | : '(undef)'; | ||
| 2006 | |||
| 2007 | my $obj_id = $existing_object->id; | ||
| 2008 | |||
| 2009 | Carp::croak("\nA change has occurred in the database for $class_name property '$conflict' on object ID $obj_id from $old_value to $new_db_value.\n" | ||
| 2010 | . "At the same time, this application has made a change to that value to $new_obj_value.\n\n" | ||
| 2011 | . "The application should lock data which it will update and might be updated by other applications."); | ||
| 2012 | |||
| 2013 | } | ||
| 2014 | |||
| 2015 | # No conflicts. Update db_committed and db_saved_uncommitted based on the DB data | ||
| 2016 | %$expected_db_data = (%$expected_db_data, %$pending_db_object_data); | ||
| 2017 | |||
| 2018 | if (! $different) { | ||
| 2019 | # FIXME HACK! This is to handle the case when you get an object, start a software transaction, | ||
| 2020 | # change something in the database for that object, reload the object (so __merge updates the value | ||
| 2021 | # found in the DB), then rollback the transaction. The act of updating the value here in __merge makes | ||
| 2022 | # a change record that gets undone when the transaction is rolled back. After the rollback, the current | ||
| 2023 | # value goes back to the originally loaded value, db_committed has the newly clhanged DB value, but | ||
| 2024 | # _change_count is 0 turning off change tracking makes it so this internal change isn't undone by rollback | ||
| 2025 | local $UR::Context::Transaction::log_all_changes = 0; # HACK! | ||
| 2026 | # The object has no local changes. Go ahead and update the current value, too | ||
| 2027 | foreach my $property ( @$property_names ) { | ||
| 2028 | no warnings 'uninitialized'; | ||
| 2029 | next if ($existing_object->{$property} eq $pending_db_object_data->{$property}); | ||
| 2030 | |||
| 2031 | $existing_object->$property($pending_db_object_data->{$property}); | ||
| 2032 | } | ||
| 2033 | } | ||
| 2034 | |||
| 2035 | # re-figure how many changes are really there | ||
| 2036 | my @change_count = $existing_object->__changes__; | ||
| 2037 | $existing_object->{'_change_count'} = scalar(@change_count); | ||
| 2038 | |||
| 2039 | return $different; | ||
| 2040 | } | ||
| 2041 | |||
| 2042 | |||
| 2043 | |||
| 2044 | sub _get_objects_for_class_and_sql { | ||
| 2045 | # this is a depracated back-door to get objects with raw sql | ||
| 2046 | # only use it if you know what you're doing | ||
| 2047 | my ($self, $class, $sql) = @_; | ||
| 2048 | my $meta = $class->__meta__; | ||
| 2049 | #my $ds = $self->resolve_data_sources_for_class_meta_and_rule($meta,$class->define_boolexpr()); | ||
| 2050 | my $ds = $self->resolve_data_sources_for_class_meta_and_rule($meta,UR::BoolExpr->resolve($class)); | ||
| 2051 | my $id_list = $ds->_resolve_ids_from_class_name_and_sql($class,$sql); | ||
| 2052 | return unless (defined($id_list) and @$id_list); | ||
| 2053 | |||
| 2054 | my $rule = UR::BoolExpr->resolve_normalized($class, id => $id_list); | ||
| 2055 | |||
| 2056 | return $self->get_objects_for_class_and_rule($class,$rule); | ||
| 2057 | } | ||
| 2058 | |||
| 2059 | sub _cache_is_complete_for_class_and_normalized_rule { | ||
| 2060 | my ($self,$class,$normalized_rule) = @_; | ||
| 2061 | |||
| 2062 | # TODO: convert this to use the rule object instead of going back to the legacy hash format | ||
| 2063 | |||
| 2064 | my ($id,$params,@objects,$cache_is_complete); | ||
| 2065 | $params = $normalized_rule->legacy_params_hash; | ||
| 2066 | $id = $params->{id}; | ||
| 2067 | |||
| 2068 | # Determine ahead of time whether we believe the object MUST be loaded if it exists. | ||
| 2069 | # If this is true, we will shortcut out of any action which loads or prepares for loading. | ||
| 2070 | |||
| 2071 | # Try to resolve without loading in cases where we are sure | ||
| 2072 | # that doing so will return the complete results. | ||
| 2073 | |||
| 2074 | my $id_only = $params->{_id_only}; | ||
| 2075 | $id_only = undef if ref($id) and ref($id) eq 'HASH'; | ||
| 2076 | if ($id_only) { | ||
| 2077 | # _id_only means that only id parameters were passed in. | ||
| 2078 | # Either a single id or an arrayref of ids. | ||
| 2079 | # Try to pull objects from the cache in either case | ||
| 2080 | if (ref $id) { | ||
| 2081 | # arrayref id | ||
| 2082 | |||
| 2083 | # we check the immediate class and all derived | ||
| 2084 | # classes for any of the ids in the set. | ||
| 2085 | @objects = | ||
| 2086 | grep { $_ } | ||
| 2087 | map { @$_{@$id} } | ||
| 2088 | map { $all_objects_loaded->{$_} } | ||
| 2089 | ($class, $class->__meta__->subclasses_loaded); | ||
| 2090 | |||
| 2091 | # see if we found all of the requested objects | ||
| 2092 | if (@objects == @$id) { | ||
| 2093 | # we found them all | ||
| 2094 | # return them all | ||
| 2095 | $cache_is_complete = 1; | ||
| 2096 | } | ||
| 2097 | else { | ||
| 2098 | # Ideally we'd filter out the ones we found, | ||
| 2099 | # but that gets complicated. | ||
| 2100 | # For now, we do it the slow way for partial matches | ||
| 2101 | @objects = (); | ||
| 2102 | } | ||
| 2103 | } | ||
| 2104 | else { | ||
| 2105 | # scalar id | ||
| 2106 | # Check for objects already loaded. | ||
| 2107 | no warnings; | ||
| 2108 | if (exists $all_objects_loaded->{$class}->{$id}) { | ||
| 2109 | $cache_is_complete = 1; | ||
| 2110 | @objects = | ||
| 2111 | grep { $_ } | ||
| 2112 | $all_objects_loaded->{$class}->{$id}; | ||
| 2113 | } | ||
| 2114 | elsif (not $class->isa("UR::Value")) { | ||
| 2115 | # we already checked the immediate class, | ||
| 2116 | # so just check derived classes | ||
| 2117 | # this is not done for values because an identity can exist | ||
| 2118 | # with independent objects with values, unlike entities | ||
| 2119 | @objects = | ||
| 2120 | grep { $_ } | ||
| 2121 | map { $all_objects_loaded->{$_}->{$id} } | ||
| 2122 | $class->__meta__->subclasses_loaded; | ||
| 2123 | if (@objects) { | ||
| 2124 | $cache_is_complete = 1; | ||
| 2125 | } | ||
| 2126 | } | ||
| 2127 | } | ||
| 2128 | } | ||
| 2129 | elsif ($params->{_unique}) { | ||
| 2130 | # _unique means that this set of params could never | ||
| 2131 | # result in more than 1 object. | ||
| 2132 | |||
| 2133 | # See if the 1 is in the cache | ||
| 2134 | # If not we have to load | ||
| 2135 | |||
| 2136 | @objects = $self->_get_objects_for_class_and_rule_from_cache($class,$normalized_rule); | ||
| 2137 | if (@objects) { | ||
| 2138 | $cache_is_complete = 1; | ||
| 2139 | } | ||
| 2140 | } | ||
| 2141 | |||
| 2142 | if ($cache_is_complete) { | ||
| 2143 | # if the $cache_is_comlete, the $cached list DEFINITELY represents all objects we need to return | ||
| 2144 | # we know that loading is NOT necessary because what we've found cached must be the entire set | ||
| 2145 | |||
| 2146 | # Because we happen to have that set, we return it in addition to the boolean flag | ||
| 2147 | return wantarray ? (1, \@objects) : (); | ||
| 2148 | } | ||
| 2149 | |||
| 2150 | # We need to do more checking to see if loading is necessary | ||
| 2151 | # Either the parameters were non-unique, or they were unique | ||
| 2152 | # and we didn't find the object checking the cache. | ||
| 2153 | |||
| 2154 | # See if we need to do a load(): | ||
| 2155 | |||
| 2156 | my $template_id = $normalized_rule->template_id; | ||
| 2157 | my $rule_id = $normalized_rule->id; | ||
| 2158 | my $loading_is_in_progress_on_another_iterator = | ||
| 2159 | grep { $_->is_loading_in_progress_for_boolexpr($normalized_rule) } | ||
| 2160 | UR::Context::ObjectFabricator->all_object_fabricators; | ||
| 2161 | |||
| 2162 | return 0 if $loading_is_in_progress_on_another_iterator; | ||
| 2163 | |||
| 2164 | # complex (non-single-id) params | ||
| 2165 | my $loading_was_done_before_with_these_params = ( | ||
| 2166 | # exact match to previous attempt | ||
| 2167 | ( exists ($UR::Context::all_params_loaded->{$template_id}) | ||
| 2168 | and | ||
| 2169 | exists ($UR::Context::all_params_loaded->{$template_id}->{$rule_id}) | ||
| 2170 | ) | ||
| 2171 | || | ||
| 2172 | # this is a subset of a previous attempt | ||
| 2173 | ($self->_loading_was_done_before_with_a_superset_of_this_rule($normalized_rule)) | ||
| 2174 | ); | ||
| 2175 | |||
| 2176 | my $object_is_loaded_or_non_existent = | ||
| 2177 | $loading_was_done_before_with_these_params | ||
| 2178 | || $class->all_objects_are_loaded; | ||
| 2179 | |||
| 2180 | if ($object_is_loaded_or_non_existent) { | ||
| 2181 | # These same non-unique parameters were used to load previously, | ||
| 2182 | # or we loaded everything at some point. | ||
| 2183 | # No load necessary. | ||
| 2184 | return 1; | ||
| 2185 | } | ||
| 2186 | else { | ||
| 2187 | # Load according to params | ||
| 2188 | return; | ||
| 2189 | } | ||
| 2190 | } # done setting $load, and possibly filling $cached/$cache_is_complete as a side-effect | ||
| 2191 | |||
| 2192 | |||
| 2193 | sub all_objects_loaded { | ||
| 2194 | my $self = shift; | ||
| 2195 | my $class = $_[0]; | ||
| 2196 | return( | ||
| 2197 | grep {$_} | ||
| 2198 | map { values %{ $UR::Context::all_objects_loaded->{$_} } } | ||
| 2199 | $class, $class->__meta__->subclasses_loaded | ||
| 2200 | ); | ||
| 2201 | } | ||
| 2202 | |||
| 2203 | sub all_objects_loaded_unsubclassed { | ||
| 2204 | my $self = shift; | ||
| 2205 | my $class = $_[0]; | ||
| 2206 | return (grep {$_} values %{ $UR::Context::all_objects_loaded->{$class} } ); | ||
| 2207 | } | ||
| 2208 | |||
| 2209 | |||
| 2210 | sub _get_objects_for_class_and_rule_from_cache { | ||
| 2211 | # Get all objects which are loaded in the application which match | ||
| 2212 | # the specified parameters. | ||
| 2213 | my ($self, $class, $rule) = @_; | ||
| 2214 | |||
| 2215 | my ($template,@values) = $rule->template_and_values; | ||
| 2216 | |||
| 2217 | #my @param_list = $rule->params_list; | ||
| 2218 | #print "CACHE-GET: $class @param_list\n"; | ||
| 2219 | |||
| 2220 | my $strategy = $rule->{_context_query_strategy}; | ||
| 2221 | unless ($strategy) { | ||
| 2222 | if ($rule->template->group_by) { | ||
| 2223 | $strategy = $rule->{_context_query_strategy} = "set intersection"; | ||
| 2224 | } | ||
| 2225 | elsif ($rule->num_values == 0) { | ||
| 2226 | $strategy = $rule->{_context_query_strategy} = "all"; | ||
| 2227 | } | ||
| 2228 | elsif ($rule->is_id_only) { | ||
| 2229 | $strategy = $rule->{_context_query_strategy} = "id"; | ||
| 2230 | } | ||
| 2231 | else { | ||
| 2232 | $strategy = $rule->{_context_query_strategy} = "index"; | ||
| 2233 | } | ||
| 2234 | } | ||
| 2235 | |||
| 2236 | my @results = eval { | ||
| 2237 | |||
| 2238 | if ($strategy eq "all") { | ||
| 2239 | return $self->all_objects_loaded($class); | ||
| 2240 | } | ||
| 2241 | elsif ($strategy eq "id") { | ||
| 2242 | my $id = $rule->value_for_id(); | ||
| 2243 | |||
| 2244 | unless (defined $id) { | ||
| 2245 | $id = $rule->value_for_id(); | ||
| 2246 | } | ||
| 2247 | |||
| 2248 | # Try to get the object(s) from this class directly with the ID. | ||
| 2249 | # Note that the code below is longer than it needs to be, but | ||
| 2250 | # is written to run quickly by resolving the most common cases | ||
| 2251 | # first, and gathering data only if and when it must. | ||
| 2252 | |||
| 2253 | my @matches; | ||
| 2254 | if (ref($id) eq 'ARRAY') { | ||
| 2255 | # The $id is an arrayref. Get all of the set. | ||
| 2256 | @matches = grep { $_ } map { @$_{@$id} } map { $all_objects_loaded->{$_} } ($class); | ||
| 2257 | |||
| 2258 | # We're done if the number found matches the number of ID values. | ||
| 2259 | return @matches if @matches == @$id; | ||
| 2260 | } | ||
| 2261 | else { | ||
| 2262 | # The $id is a normal scalar. | ||
| 2263 | if (not defined $id) { | ||
| 2264 | #Carp::carp("Undefined id passed as params for query on $class"); | ||
| 2265 | Carp::cluck("\n\n**** Undefined id passed as params for query on $class"); | ||
| 2266 | $id ||= ''; | ||
| 2267 | } | ||
| 2268 | my $match; | ||
| 2269 | # FIXME This is a performance optimization for class metadata to avoid the search through | ||
| 2270 | # @subclasses_loaded a few lines further down. When 100s of classes are loaded it gets | ||
| 2271 | # a bit slow. Maybe UR::Object::Type should override get() instad and put it there? | ||
| 2272 | if (! $UR::Object::Type::bootstrapping and $class eq 'UR::Object::Type') { | ||
| 2273 | my $meta_class_name = $id . '::Type'; | ||
| 2274 | $match = $all_objects_loaded->{$meta_class_name}->{$id} | ||
| 2275 | || | ||
| 2276 | $all_objects_loaded->{'UR::Object::Type'}->{$id}; | ||
| 2277 | if ($match) { | ||
| 2278 | return $match; | ||
| 2279 | } else { | ||
| 2280 | return; | ||
| 2281 | } | ||
| 2282 | } | ||
| 2283 | |||
| 2284 | $match = $all_objects_loaded->{$class}->{$id}; | ||
| 2285 | |||
| 2286 | # We're done if we found anything. If not we keep checking. | ||
| 2287 | return $match if $match; | ||
| 2288 | } | ||
| 2289 | |||
| 2290 | # Try to get the object(s) from this class's subclasses. | ||
| 2291 | # We may be adding to matches made above is we used an arrayref | ||
| 2292 | # and the results are incomplete. | ||
| 2293 | |||
| 2294 | my @subclasses_loaded = $class->__meta__->subclasses_loaded; | ||
| 2295 | return @matches unless @subclasses_loaded; | ||
| 2296 | |||
| 2297 | if (ref($id) eq 'ARRAY') { | ||
| 2298 | # The $id is an arrayref. Get all of the set and add it to anything found above. | ||
| 2299 | push @matches, | ||
| 2300 | grep { $_ } | ||
| 2301 | map { @$_{@$id} } | ||
| 2302 | map { $all_objects_loaded->{$_} } | ||
| 2303 | @subclasses_loaded; | ||
| 2304 | } | ||
| 2305 | else { | ||
| 2306 | # The $id is a normal scalar, but we didn't find it above. | ||
| 2307 | # Try each subclass, exiting if we find anything. | ||
| 2308 | for (@subclasses_loaded) { | ||
| 2309 | my $match = $all_objects_loaded->{$_}->{$id}; | ||
| 2310 | return $match if $match; | ||
| 2311 | } | ||
| 2312 | } | ||
| 2313 | |||
| 2314 | # Since an ID was specified, and we've scanned the core hash every way possible, | ||
| 2315 | # we're done. Return nothing if necessary. | ||
| 2316 | return @matches; | ||
| 2317 | } | ||
| 2318 | elsif ($strategy eq "index") { | ||
| 2319 | # FIXME - optimize by using the rule (template?)'s param names directly to get the | ||
| 2320 | # index id instead of re-figuring it out each time | ||
| 2321 | |||
| 2322 | my $class_meta = $rule->subject_class_name->__meta__; | ||
| 2323 | my %params = $rule->params_list; | ||
| 2324 | my $should_evaluate_later; | ||
| 2325 | for my $key (keys %params) { | ||
| 2326 | if (substr($key,0,1) eq '-' or substr($key,0,1) eq '_') { | ||
| 2327 | delete $params{$key}; | ||
| 2328 | } | ||
| 2329 | elsif ($key =~ /^\w*\./) { | ||
| 2330 | # a chain of properties | ||
| 2331 | $should_evaluate_later = 1; | ||
| 2332 | delete $params{$key}; | ||
| 2333 | } | ||
| 2334 | else { | ||
| 2335 | my $prop_meta = $class_meta->property_meta_for_name($key); | ||
| 2336 | # NOTE: We _could_ remove the is_delegated check if we knew we were operating on | ||
| 2337 | # a read-only context. | ||
| 2338 | if ($prop_meta && ($prop_meta->is_many or $prop_meta->is_delegated)) { | ||
| 2339 | # These indexes perform poorly in the general case if we try to index | ||
| 2340 | # the is_many properties. Instead, strip them out from the basic param | ||
| 2341 | # list, and evaluate the superset of indexed objects through the rule | ||
| 2342 | $should_evaluate_later = 1; | ||
| 2343 | delete $params{$key}; | ||
| 2344 | } | ||
| 2345 | } | ||
| 2346 | } | ||
| 2347 | |||
| 2348 | my @properties = sort keys %params; | ||
| 2349 | unless (@properties) { | ||
| 2350 | # All the supplied filters were is_many properties | ||
| 2351 | return grep { $rule->evaluate($_) } $self->all_objects_loaded($class); | ||
| 2352 | } | ||
| 2353 | |||
| 2354 | my @values = map { $params{$_} } @properties; | ||
| 2355 | |||
| 2356 | unless (@properties == @values) { | ||
| 2357 | Carp::confess(); | ||
| 2358 | } | ||
| 2359 | |||
| 2360 | # find or create the index | ||
| 2361 | my $pstring = join(",",@properties); | ||
| 2362 | my $index_id = UR::Object::Index->__meta__->resolve_composite_id_from_ordered_values($class,$pstring); | ||
| 2363 | my $index = $all_objects_loaded->{'UR::Object::Index'}{$index_id}; | ||
| 2364 | $index ||= UR::Object::Index->create( | ||
| 2365 | id => $index_id, | ||
| 2366 | indexed_class_name => $class, | ||
| 2367 | indexed_property_string => $pstring | ||
| 2368 | ); | ||
| 2369 | |||
| 2370 | |||
| 2371 | # add the indexed objects to the results list | ||
| 2372 | |||
| 2373 | |||
| 2374 | if ($UR::Debug::verify_indexes) { | ||
| 2375 | my @matches = $index->get_objects_matching(@values); | ||
| 2376 | @matches = sort @matches; | ||
| 2377 | my @matches2 = sort grep { $rule->evaluate($_) } $self->all_objects_loaded($class); | ||
| 2378 | unless ("@matches" eq "@matches2") { | ||
| 2379 | print "@matches\n"; | ||
| 2380 | print "@matches2\n"; | ||
| 2381 | #Carp::cluck("Mismatch!"); | ||
| 2382 | my @matches3 = $index->get_objects_matching(@values); | ||
| 2383 | my @matches4 = $index->get_objects_matching(@values); | ||
| 2384 | return @matches2; | ||
| 2385 | } | ||
| 2386 | return @matches; | ||
| 2387 | } | ||
| 2388 | |||
| 2389 | if ($should_evaluate_later) { | ||
| 2390 | return grep { $rule->evaluate($_) } $index->get_objects_matching(@values); | ||
| 2391 | } else { | ||
| 2392 | return $index->get_objects_matching(@values); | ||
| 2393 | } | ||
| 2394 | } | ||
| 2395 | elsif ($strategy eq 'set intersection') { | ||
| 2396 | #print $rule->num_values, " ", $rule->is_id_only, "\n"; | ||
| 2397 | my $template = $rule->template; | ||
| 2398 | my $group_by = $template->group_by; | ||
| 2399 | |||
| 2400 | # get the objects in memory, and make sets for them if they do not exist | ||
| 2401 | my $rule_no_group = $rule->remove_filter('-group_by'); | ||
| 2402 | $rule_no_group = $rule_no_group->remove_filter('-order_by'); | ||
| 2403 | my @objects_in_set = $self->_get_objects_for_class_and_rule_from_cache($class, $rule_no_group); | ||
| 2404 | my @sets_from_grouped_objects = _group_objects($rule_no_group->template,\@values,$group_by,\@objects_in_set); | ||
| 2405 | |||
| 2406 | # determine the template that the grouped subsets will use | ||
| 2407 | # find templates which are subsets of that template | ||
| 2408 | # find sets with a | ||
| 2409 | my $set_class = $class . '::Set'; | ||
| 2410 | my $expected_template_id = $rule->template->_template_for_grouped_subsets->id; | ||
| 2411 | my @matches = | ||
| 2412 | grep { | ||
| 2413 | # TODO: make the template something indexable so we can pull from index | ||
| 2414 | my $bx = UR::BoolExpr->get($_->id); | ||
| 2415 | my $bxt = $bx->template; | ||
| 2416 | if ($bxt->id ne $expected_template_id) { | ||
| 2417 | #print "TEMPLATE MISMATCH $expected_template_id does not match $bxt->{id}! set: $_ with bxid $bx->{id} cannot be under rule $rule_no_group" . Data::Dumper::Dumper($_); | ||
| 2418 | (); | ||
| 2419 | } | ||
| 2420 | elsif (not $bx->is_subset_of($rule_no_group) ) { | ||
| 2421 | #print "SUBSET MISMATCH: $rule_no_group is not a superset of $_ with bxid $bx->{id}" . Data::Dumper::Dumper($_); | ||
| 2422 | (); | ||
| 2423 | } | ||
| 2424 | else { | ||
| 2425 | #print "MATCH: $rule_no_group with $expected_template_id matches $bx $bx->{id}" . Data::Dumper::Dumper($_); | ||
| 2426 | ($_); | ||
| 2427 | } | ||
| 2428 | } | ||
| 2429 | $self->all_objects_loaded($set_class); | ||
| 2430 | |||
| 2431 | # Code to check that newly fabricated set definitions are in the set we query back out: | ||
| 2432 | # my @all = $self->all_objects_loaded($set_class); | ||
| 2433 | # my %expected; | ||
| 2434 | # @expected{@sets_from_grouped_objects} = @sets_from_grouped_objects; | ||
| 2435 | # for my $match (@matches) { | ||
| 2436 | # delete $expected{$match}; | ||
| 2437 | # } | ||
| 2438 | # if (keys %expected) { | ||
| 2439 | # #$DB::single = 1; | ||
| 2440 | # print Data::Dumper::Dumper(\%expected); | ||
| 2441 | # } | ||
| 2442 | |||
| 2443 | return @matches; | ||
| 2444 | } | ||
| 2445 | else { | ||
| 2446 | die "unknown strategy $strategy"; | ||
| 2447 | } | ||
| 2448 | }; | ||
| 2449 | |||
| 2450 | # Handle passing-through any exceptions. | ||
| 2451 | die $@ if $@; | ||
| 2452 | |||
| 2453 | if (my $recurse = $template->recursion_desc) { | ||
| 2454 | my ($this,$prior) = @$recurse; | ||
| 2455 | # remove undef items. undef/NULL in the recursion linkage means it doesn't link to anything | ||
| 2456 | my @values = grep { defined } | ||
| 2457 | map { $_->$prior } | ||
| 2458 | @results; | ||
| 2459 | if (@values) { | ||
| 2460 | # We do get here, so that adjustments to intermediate foreign keys | ||
| 2461 | # in the cache will result in a new query at the correct point, | ||
| 2462 | # and not result in missing data. | ||
| 2463 | #push @results, $class->get($this => \@values, -recurse => $recurse); | ||
| 2464 | push @results, map { $class->get($this => $_, -recurse => $recurse) } @values; | ||
| 2465 | } | ||
| 2466 | } | ||
| 2467 | |||
| 2468 | my $group_by = $template->group_by; | ||
| 2469 | #if ($group_by) { | ||
| 2470 | # # return sets instead of the actual objects | ||
| 2471 | # @results = _group_objects($template,\@values,$group_by,\@results); | ||
| 2472 | #} | ||
| 2473 | |||
| 2474 | if (@results > 1) { | ||
| 2475 | my $sorter; | ||
| 2476 | if ($group_by) { | ||
| 2477 | # We need to rewrite the original rule on the member class to be a rule | ||
| 2478 | # on the Set class to do proper ordering | ||
| 2479 | my $set_class = $template->subject_class_name . '::Set'; | ||
| 2480 | my $set_template = UR::BoolExpr::Template->resolve($set_class, -group_by => $group_by); | ||
| 2481 | $sorter = $set_template->sorter; | ||
| 2482 | } else { | ||
| 2483 | $sorter = $template->sorter; | ||
| 2484 | } | ||
| 2485 | @results = sort $sorter @results; | ||
| 2486 | } | ||
| 2487 | |||
| 2488 | # Return in the standard way. | ||
| 2489 | return @results if (wantarray); | ||
| 2490 | Carp::confess("Multiple matches for $class @_!") if (@results > 1); | ||
| 2491 | return $results[0]; | ||
| 2492 | } | ||
| 2493 | |||
| 2494 | sub _group_objects { | ||
| 2495 | my ($template,$values,$group_by,$objects) = @_; | ||
| 2496 | my $sub_template = $template->remove_filter('-group_by'); | ||
| 2497 | for my $property (@$group_by) { | ||
| 2498 | $sub_template = $sub_template->add_filter($property); | ||
| 2499 | } | ||
| 2500 | my $set_class = $template->subject_class_name . '::Set'; | ||
| 2501 | my @groups; | ||
| 2502 | my %seen; | ||
| 2503 | for my $result (@$objects) { | ||
| 2504 | my %values_for_group_property; | ||
| 2505 | foreach my $group_property ( @$group_by ) { | ||
| 2506 | my @values = $result->$group_property; | ||
| 2507 | if (@values) { | ||
| 2508 | $values_for_group_property{$group_property} = \@values; | ||
| 2509 | } else { | ||
| 2510 | $values_for_group_property{$group_property} = [ undef ]; | ||
| 2511 | } | ||
| 2512 | } | ||
| 2513 | my @combinations = UR::Util::combinations_of_values(map { $values_for_group_property{$_} } @$group_by); | ||
| 2514 | foreach my $extra_values ( @combinations ) { | ||
| 2515 | my $bx = $sub_template->get_rule_for_values(@$values,@$extra_values); | ||
| 2516 | next if $seen{$bx->id}++; | ||
| 2517 | my $group = $set_class->get($bx->id); | ||
| 2518 | push @groups, $group; | ||
| 2519 | } | ||
| 2520 | } | ||
| 2521 | return @groups; | ||
| 2522 | } | ||
| 2523 | |||
| 2524 | sub _loading_was_done_before_with_a_superset_of_this_rule { | ||
| 2525 | my($self,$rule) = @_; | ||
| 2526 | |||
| 2527 | my $template = $rule->template; | ||
| 2528 | |||
| 2529 | if (exists $UR::Context::all_params_loaded->{$template->id} | ||
| 2530 | and exists $UR::Context::all_params_loaded->{$template->id}->{$rule->id} | ||
| 2531 | ) { | ||
| 2532 | return 1; | ||
| 2533 | } | ||
| 2534 | |||
| 2535 | if ($template->subject_class_name->isa("UR::Value")) { | ||
| 2536 | return; | ||
| 2537 | } | ||
| 2538 | |||
| 2539 | my @rule_values = $rule->values; | ||
| 2540 | my @rule_param_names = $template->_property_names; | ||
| 2541 | my %rule_values; | ||
| 2542 | for (my $i = 0; $i < @rule_param_names; $i++) { | ||
| 2543 | $rule_values{ $rule_param_names[$i] } = $rule_values[$i]; | ||
| 2544 | } | ||
| 2545 | |||
| 2546 | foreach my $loaded_template_id ( keys %$UR::Context::all_params_loaded ) { | ||
| 2547 | my $loaded_template = UR::BoolExpr::Template->get($loaded_template_id); | ||
| 2548 | if($template->is_subset_of($loaded_template)) { | ||
| 2549 | # Try limiting the possibilities by matching the previously-loaded rule value_id's | ||
| 2550 | # on this rule's values | ||
| 2551 | my @param_names = $loaded_template->_property_names; | ||
| 2552 | my @values = @rule_values{ @param_names }; | ||
| 2553 | my $value_id; | ||
| 2554 | { no warnings 'uninitialized'; | ||
| 2555 | $value_id = join($UR::BoolExpr::Util::record_sep, @values); | ||
| 2556 | } | ||
| 2557 | my @candidates = grep { index($_, $value_id) > 0 } keys(%{ $UR::Context::all_params_loaded->{$loaded_template_id} }); | ||
| 2558 | foreach my $loaded_rule_id ( @candidates ) { | ||
| 2559 | my $loaded_rule = UR::BoolExpr->get($loaded_rule_id); | ||
| 2560 | return 1 if ($rule->is_subset_of($loaded_rule)); | ||
| 2561 | } | ||
| 2562 | } | ||
| 2563 | } | ||
| 2564 | return; | ||
| 2565 | } | ||
| 2566 | |||
| 2567 | |||
| 2568 | |||
| 2569 | sub _forget_loading_was_done_with_template_and_rule { | ||
| 2570 | my($self,$template_id, $rule_id) = @_; | ||
| 2571 | |||
| 2572 | delete $all_params_loaded->{$template_id}->{$rule_id}; | ||
| 2573 | } | ||
| 2574 | |||
| 2575 | # Given a list of values, returns a list of lists containing all subsets of | ||
| 2576 | # the input list, including the original list and the empty list | ||
| 2577 | sub _get_all_subsets_of_params { | ||
| 2578 | my $self = shift; | ||
| 2579 | |||
| 2580 | return [] unless @_; | ||
| 2581 | my $first = shift; | ||
| 2582 | my @rest = $self->_get_all_subsets_of_params(@_); | ||
| 2583 | return @rest, map { [$first, @$_ ] } @rest; | ||
| 2584 | } | ||
| 2585 | |||
| 2586 | sub query_underlying_context { | ||
| 2587 | my $self = shift; | ||
| 2588 | unless (ref $self) { | ||
| 2589 | $self = $self->current; | ||
| 2590 | } | ||
| 2591 | if (@_) { | ||
| 2592 | $self->{'query_underlying_context'} = shift; | ||
| 2593 | } | ||
| 2594 | return $self->{'query_underlying_context'}; | ||
| 2595 | } | ||
| 2596 | |||
| 2597 | |||
| 2598 | # all of these delegate to the current context... | ||
| 2599 | |||
| 2600 | sub has_changes { | ||
| 2601 | return shift->get_current->has_changes(@_); | ||
| 2602 | } | ||
| 2603 | |||
| 2604 | sub commit { | ||
| 2605 | Carp::carp 'UR::Context::commit() called as a function, not a method. Assumming commit on current context' unless @_; | ||
| 2606 | |||
| 2607 | my $self = shift; | ||
| 2608 | $self = UR::Context->current() unless ref $self; | ||
| 2609 | |||
| 2610 | $self->__signal_change__('precommit'); | ||
| 2611 | |||
| 2612 | unless ($self->_sync_databases) { | ||
| 2613 | $self->__signal_observers__('sync_databases', 0); | ||
| 2614 | $self->__signal_change__('commit',0); | ||
| 2615 | return; | ||
| 2616 | } | ||
| 2617 | |||
| 2618 | $self->__signal_observers__('sync_databases', 1); | ||
| 2619 | |||
| 2620 | unless ($self->_commit_databases) { | ||
| 2621 | $self->__signal_change__('commit',0); | ||
| 2622 | die "Application failure during commit!"; | ||
| 2623 | } | ||
| 2624 | $self->__signal_change__('commit',1); | ||
| 2625 | |||
| 2626 | $_->delete foreach UR::Change->get(); | ||
| 2627 | |||
| 2628 | foreach ( $self->all_objects_loaded('UR::Object') ) { | ||
| 2629 | delete $_->{'_change_count'}; | ||
| 2630 | } | ||
| 2631 | |||
| 2632 | return 1; | ||
| 2633 | } | ||
| 2634 | |||
| 2635 | sub rollback { | ||
| 2636 | my $self = shift; | ||
| 2637 | unless ($self) { | ||
| 2638 | warn 'UR::Context::rollback() called as a function, not a method. Assumming rollback on current context'; | ||
| 2639 | $self = UR::Context->current(); | ||
| 2640 | } | ||
| 2641 | $self->__signal_change__('prerollback'); | ||
| 2642 | |||
| 2643 | unless ($self->_reverse_all_changes) { | ||
| 2644 | $self->__signal_change__('rollback', 0); | ||
| 2645 | die "Application failure during reverse_all_changes?!"; | ||
| 2646 | } | ||
| 2647 | unless ($self->_rollback_databases) { | ||
| 2648 | $self->__signal_change__('rollback', 0); | ||
| 2649 | die "Application failure during rollback!"; | ||
| 2650 | } | ||
| 2651 | $self->__signal_change__('rollback', 1); | ||
| 2652 | return 1; | ||
| 2653 | } | ||
| 2654 | |||
| 2655 | sub _tmp_self { | ||
| 2656 | my $self = shift; | ||
| 2657 | if (ref($self)) { | ||
| 2658 | return ($self,ref($self)); | ||
| 2659 | } | ||
| 2660 | else { | ||
| 2661 | return ($UR::Context::current, $self); | ||
| 2662 | } | ||
| 2663 | } | ||
| 2664 | |||
| 2665 | sub clear_cache { | ||
| 2666 | my ($self,$class) = _tmp_self(shift @_); | ||
| 2667 | my %args = @_; | ||
| 2668 | |||
| 2669 | # dont unload any of the infrastructional classes, or any classes | ||
| 2670 | # the user requested to be saved | ||
| 2671 | my %local_dont_unload; | ||
| 2672 | if ($args{'dont_unload'}) { | ||
| 2673 | for my $class_name (@{$args{'dont_unload'}}) { | ||
| 2674 | $local_dont_unload{$class_name} = 1; | ||
| 2675 | for my $subclass_name ($class_name->__meta__->subclasses_loaded) { | ||
| 2676 | $local_dont_unload{$subclass_name} = 1; | ||
| 2677 | } | ||
| 2678 | } | ||
| 2679 | } | ||
| 2680 | |||
| 2681 | for my $class_name (UR::Object->__meta__->subclasses_loaded) { | ||
| 2682 | |||
| 2683 | # Once transactions are fully implemented, the command params will sit | ||
| 2684 | # beneath the regular transaction, so we won't need this. For now, | ||
| 2685 | # we need a work-around. | ||
| 2686 | next if $class_name eq "UR::Command::Param"; | ||
| 2687 | next if $class_name->isa('UR::Singleton'); | ||
| 2688 | |||
| 2689 | my $class_obj = $class_name->__meta__; | ||
| 2690 | #if ($class_obj->data_source and $class_obj->is_transactional) { | ||
| 2691 | # # normal | ||
| 2692 | #} | ||
| 2693 | #elsif (!$class_obj->data_source and !$class_obj->is_transactional) { | ||
| 2694 | # # expected | ||
| 2695 | #} | ||
| 2696 | #elsif ($class_obj->data_source and !$class_obj->is_transactional) { | ||
| 2697 | # Carp::confess("!!!!!data source on non-transactional class $class_name?"); | ||
| 2698 | #} | ||
| 2699 | #elsif (!$class_obj->data_source and $class_obj->is_transactional) { | ||
| 2700 | # # okay | ||
| 2701 | #} | ||
| 2702 | |||
| 2703 | next unless $class_obj->is_uncachable; | ||
| 2704 | next if $class_obj->is_meta_meta; | ||
| 2705 | next unless $class_obj->is_transactional; | ||
| 2706 | |||
| 2707 | next if ($local_dont_unload{$class_name} || | ||
| 2708 | grep { $class_name->isa($_) } @{$args{'dont_unload'}}); | ||
| 2709 | |||
| 2710 | next if $class_obj->is_meta; | ||
| 2711 | |||
| 2712 | next if not defined $class_obj->data_source; | ||
| 2713 | |||
| 2714 | for my $obj ($self->all_objects_loaded_unsubclassed($class_name)) { | ||
| 2715 | # Check the type against %local_dont_unload again, because all_objects_loaded() | ||
| 2716 | # will return child class objects, as well as the class you asked for. For example, | ||
| 2717 | # GSC::DNA->a_o_l() will also return GSC::ReadExp objects, and the user may have wanted | ||
| 2718 | # to save those. We also check whether the $obj type isa one of the requested classes | ||
| 2719 | # because, for example, GSC::Sequence->a_o_l returns GSC::ReadExp types, and the user | ||
| 2720 | # may have wanted to save all GSC::DNAs | ||
| 2721 | my $obj_type = ref $obj; | ||
| 2722 | next if ($local_dont_unload{$obj_type} || | ||
| 2723 | grep {$obj_type->isa($_) } @{$args{'dont_unload'}}); | ||
| 2724 | $obj->unload; | ||
| 2725 | } | ||
| 2726 | my @obj = grep { defined($_) } values %{ $UR::Context::all_objects_loaded->{$class_name} }; | ||
| 2727 | if (@obj) { | ||
| 2728 | $class->warning_message("Skipped unload of $class_name objects during clear_cache: " | ||
| 2729 | . join(",",map { $_->id } @obj ) | ||
| 2730 | . "\n" | ||
| 2731 | ); | ||
| 2732 | if (my @changed = grep { $_->__changes__ } @obj) { | ||
| 2733 | require YAML; | ||
| 2734 | $class->error_message( | ||
| 2735 | "The following objects have changes:\n" | ||
| 2736 | . Data::Dumper::Dumper(\@changed) | ||
| 2737 | . "The clear_cache method cannot be called with unsaved changes on objects.\n" | ||
| 2738 | . "Use reverse_all_changes() first to really undo everything, then clear_cache()," | ||
| 2739 | . " or call sync_database() and clear_cache() if you want to just lighten memory but keep your changes.\n" | ||
| 2740 | . "Clearing the cache with active changes will be supported after we're sure all code like this is gone. :)\n" | ||
| 2741 | ); | ||
| 2742 | exit 1; | ||
| 2743 | } | ||
| 2744 | } | ||
| 2745 | delete $UR::Context::all_objects_loaded->{$class_name}; | ||
| 2746 | delete $UR::Context::all_objects_are_loaded->{$class_name}; | ||
| 2747 | delete $UR::Context::all_params_loaded->{$class_name}; | ||
| 2748 | } | ||
| 2749 | 1; | ||
| 2750 | } | ||
| 2751 | |||
| 2752 | sub _order_data_sources_for_saving { | ||
| 2753 | my @data_sources = @_; | ||
| 2754 | |||
| 2755 | my %can_savepoint = map { $_->id => $_->can_savepoint } @data_sources; | ||
| 2756 | my %classes = map { $_->id => $_->class } @data_sources; | ||
| 2757 | my %is_default = map { $_->id => $_->isa('UR::DataSource::Default') ? 1 : 0 } @data_sources; # Default data sources go last | ||
| 2758 | |||
| 2759 | return | ||
| 2760 | sort { | ||
| 2761 | $is_default{$a->id} <=> $is_default{$b->id} | ||
| 2762 | || | ||
| 2763 | $can_savepoint{$a->id} <=> $can_savepoint{$b->id} | ||
| 2764 | || | ||
| 2765 | $classes{$a->id} cmp $classes{$b->id} | ||
| 2766 | } | ||
| 2767 | @data_sources; | ||
| 2768 | } | ||
| 2769 | |||
| 2770 | |||
| 2771 | our $IS_SYNCING_DATABASE = 0; | ||
| 2772 | sub _sync_databases { | ||
| 2773 | my $self = shift; | ||
| 2774 | my %params = @_; | ||
| 2775 | |||
| 2776 | # Glue App::DB->sync_database with UR::Context->_sync_databases() | ||
| 2777 | # and avoid endless recursion. | ||
| 2778 | # FIXME Remove this when we're totally off of the old API | ||
| 2779 | # You'll also want to remove all the gotos from this function and uncomment | ||
| 2780 | # the returns | ||
| 2781 | return 1 if $IS_SYNCING_DATABASE; | ||
| 2782 | $IS_SYNCING_DATABASE = 1; | ||
| 2783 | if ($App::DB::{'sync_database'}) { | ||
| 2784 | unless (App::DB->sync_database() ) { | ||
| 2785 | $IS_SYNCING_DATABASE = 0; | ||
| 2786 | $self->error_message(App::DB->error_message()); | ||
| 2787 | return; | ||
| 2788 | } | ||
| 2789 | } | ||
| 2790 | $IS_SYNCING_DATABASE = 0; # This should be far down enough to avoid recursion, right? | ||
| 2791 | |||
| 2792 | my @o = grep { ref($_) eq 'UR::DeletedRef' } $self->all_objects_loaded('UR::Object'); | ||
| 2793 | if (@o) { | ||
| 2794 | print Data::Dumper::Dumper(\@o); | ||
| 2795 | Carp::confess(); | ||
| 2796 | } | ||
| 2797 | |||
| 2798 | # Determine what has changed. | ||
| 2799 | my @changed_objects = ( | ||
| 2800 | $self->all_objects_loaded('UR::Object::Ghost'), | ||
| 2801 | grep { $_->__changes__ } $self->all_objects_loaded('UR::Object') | ||
| 2802 | #UR::Util->mapreduce_grep(sub { $_[0]->__changes__ },$self->all_objects_loaded('UR::Object')) | ||
| 2803 | ); | ||
| 2804 | |||
| 2805 | return 1 unless (@changed_objects); | ||
| 2806 | |||
| 2807 | # Ensure validity. | ||
| 2808 | # This is primarily to catch custom validity logic in class overrides. | ||
| 2809 | my @invalid = grep { $_->__errors__ } @changed_objects; | ||
| 2810 | #my @invalid = UR::Util->mapreduce_grep(sub { $_[0]->__errors__}, @changed_objects); | ||
| 2811 | if (@invalid) { | ||
| 2812 | $self->display_invalid_data_for_save(\@invalid); | ||
| 2813 | goto PROBLEM_SAVING; | ||
| 2814 | #return; | ||
| 2815 | } | ||
| 2816 | |||
| 2817 | # group changed objects by data source | ||
| 2818 | my %ds_objects; | ||
| 2819 | for my $obj (@changed_objects) { | ||
| 2820 | my $data_source = $self->resolve_data_source_for_object($obj); | ||
| 2821 | next unless $data_source; | ||
| 2822 | my $data_source_id = $data_source->id; | ||
| 2823 | $ds_objects{$data_source_id} ||= { 'ds_obj' => $data_source, 'changed_objects' => []}; | ||
| 2824 | push @{ $ds_objects{$data_source_id}->{'changed_objects'} }, $obj; | ||
| 2825 | } | ||
| 2826 | |||
| 2827 | my @ds_in_order = | ||
| 2828 | map { $_->id } | ||
| 2829 | _order_data_sources_for_saving(map { $_->{ds_obj} } values(%ds_objects)); | ||
| 2830 | |||
| 2831 | # save on each in succession | ||
| 2832 | my @done; | ||
| 2833 | my $rollback_on_non_savepoint_handle; | ||
| 2834 | for my $data_source_id (@ds_in_order) { | ||
| 2835 | my $obj_list = $ds_objects{$data_source_id}->{'changed_objects'}; | ||
| 2836 | my $data_source = $ds_objects{$data_source_id}->{'ds_obj'}; | ||
| 2837 | my $result = $data_source->_sync_database( | ||
| 2838 | %params, | ||
| 2839 | changed_objects => $obj_list, | ||
| 2840 | ); | ||
| 2841 | if ($result) { | ||
| 2842 | push @done, $data_source; | ||
| 2843 | next; | ||
| 2844 | } | ||
| 2845 | else { | ||
| 2846 | $self->error_message( | ||
| 2847 | "Failed to sync data source: $data_source_id: " | ||
| 2848 | . $data_source->error_message | ||
| 2849 | ); | ||
| 2850 | for my $prev_data_source (@done) { | ||
| 2851 | $prev_data_source->_reverse_sync_database; | ||
| 2852 | } | ||
| 2853 | goto PROBLEM_SAVING; | ||
| 2854 | #return; | ||
| 2855 | } | ||
| 2856 | } | ||
| 2857 | |||
| 2858 | return 1; | ||
| 2859 | |||
| 2860 | PROBLEM_SAVING: | ||
| 2861 | if ($App::DB::{'rollback'}) { | ||
| 2862 | App::DB->rollback(); | ||
| 2863 | } | ||
| 2864 | return; | ||
| 2865 | } | ||
| 2866 | |||
| 2867 | |||
| 2868 | sub display_invalid_data_for_save { | ||
| 2869 | my $self = shift; | ||
| 2870 | my @objects_with_errors = @{shift @_}; | ||
| 2871 | |||
| 2872 | $self->error_message('Invalid data for save!'); | ||
| 2873 | |||
| 2874 | for my $obj (@objects_with_errors) { | ||
| 2875 | no warnings; | ||
| 2876 | my $identifier = eval { $obj->__display_name__ } || $obj->id; | ||
| 2877 | my $msg = $obj->class . " identified by " . $identifier . " has problems on\n"; | ||
| 2878 | my @problems = $obj->__errors__; | ||
| 2879 | foreach my $error ( @problems ) { | ||
| 2880 | $msg .= $error->__display_name__ . "\n"; | ||
| 2881 | } | ||
| 2882 | |||
| 2883 | $msg .= " Current state:\n"; | ||
| 2884 | my $datadumper = Data::Dumper::Dumper($obj); | ||
| 2885 | my $nr_of_lines = $datadumper =~ tr/\n//; | ||
| 2886 | if ($nr_of_lines > 40) { | ||
| 2887 | # trim it down to the first 15 and last 3 lines | ||
| 2888 | $datadumper =~ m/^((?:.*\n){15})/; | ||
| 2889 | $msg .= $1; | ||
| 2890 | $datadumper =~ m/((?:.*(?:\n|$)){3})$/; | ||
| 2891 | $msg .= "[...]\n$1\n"; | ||
| 2892 | } else { | ||
| 2893 | $msg .= $datadumper; | ||
| 2894 | } | ||
| 2895 | $self->error_message($msg); | ||
| 2896 | } | ||
| 2897 | |||
| 2898 | return 1; | ||
| 2899 | } | ||
| 2900 | |||
| 2901 | |||
| 2902 | sub _reverse_all_changes { | ||
| 2903 | my $self = shift; | ||
| 2904 | my $class; | ||
| 2905 | if (ref($self)) { | ||
| 2906 | $class = ref($self); | ||
| 2907 | } | ||
| 2908 | else { | ||
| 2909 | $class = $self; | ||
| 2910 | $self = $UR::Context::current; | ||
| 2911 | } | ||
| 2912 | |||
| 2913 | @UR::Context::Transaction::open_transaction_stack = (); | ||
| 2914 | @UR::Context::Transaction::change_log = (); | ||
| 2915 | $UR::Context::Transaction::log_all_changes = 0; | ||
| 2916 | $UR::Context::current = $UR::Context::process; | ||
| 2917 | |||
| 2918 | my @objects = | ||
| 2919 | map { $self->all_objects_loaded_unsubclassed($_) } | ||
| 2920 | grep { $_->__meta__->is_transactional } | ||
| 2921 | grep { ! $_->isa('UR::Value') } | ||
| 2922 | sort UR::Object->__meta__->subclasses_loaded(); | ||
| 2923 | |||
| 2924 | for my $object (@objects) { | ||
| 2925 | $object->__rollback__(); | ||
| 2926 | } | ||
| 2927 | |||
| 2928 | return 1; | ||
| 2929 | } | ||
| 2930 | |||
| 2931 | our $IS_COMMITTING_DATABASE = 0; | ||
| 2932 | sub _commit_databases { | ||
| 2933 | my $class = shift; | ||
| 2934 | |||
| 2935 | # Glue App::DB->commit() with UR::Context->_commit_databases() | ||
| 2936 | # and avoid endless recursion. | ||
| 2937 | # FIXME Remove this when we're totally off of the old API | ||
| 2938 | return 1 if $IS_COMMITTING_DATABASE; | ||
| 2939 | $IS_COMMITTING_DATABASE = 1; | ||
| 2940 | if ($App::DB::{'commit'}) { | ||
| 2941 | unless (App::DB->commit() ) { | ||
| 2942 | $IS_COMMITTING_DATABASE = 0; | ||
| 2943 | $class->error_message(App::DB->error_message()); | ||
| 2944 | return; | ||
| 2945 | } | ||
| 2946 | } | ||
| 2947 | $IS_COMMITTING_DATABASE = 0; | ||
| 2948 | |||
| 2949 | my @ds_in_order = _order_data_sources_for_saving($UR::Context::current->all_objects_loaded('UR::DataSource')); | ||
| 2950 | my @committed; | ||
| 2951 | foreach my $ds ( @ds_in_order ) { | ||
| 2952 | if ($ds->commit) { | ||
| 2953 | push @committed, $ds; | ||
| 2954 | } else { | ||
| 2955 | my $message = 'Data source ' . $ds->get_name . ' failed to commit: ' . join("\n\t", $ds->error_messages); | ||
| 2956 | if (@committed) { | ||
| 2957 | $message .= "\nThese data sources were successfully committed, resulting in a FRAGMENTED DISTRIBUTED TRANSACTION: " | ||
| 2958 | . join(', ', map { $_->get_name } @committed); | ||
| 2959 | } | ||
| 2960 | Carp::croak($message); | ||
| 2961 | } | ||
| 2962 | } | ||
| 2963 | |||
| 2964 | return 1; | ||
| 2965 | } | ||
| 2966 | |||
| 2967 | |||
| 2968 | our $IS_ROLLINGBACK_DATABASE = 0; | ||
| 2969 | sub _rollback_databases { | ||
| 2970 | my $class = shift; | ||
| 2971 | |||
| 2972 | # Glue App::DB->rollback() with UR::Context->_rollback_databases() | ||
| 2973 | # and avoid endless recursion. | ||
| 2974 | # FIXME Remove this when we're totally off of the old API | ||
| 2975 | return 1 if $IS_ROLLINGBACK_DATABASE; | ||
| 2976 | $IS_ROLLINGBACK_DATABASE = 1; | ||
| 2977 | if ($App::DB::{'rollback'}) { | ||
| 2978 | unless (App::DB->rollback()) { | ||
| 2979 | $IS_ROLLINGBACK_DATABASE = 0; | ||
| 2980 | $class->error_message(App::DB->error_message()); | ||
| 2981 | return; | ||
| 2982 | } | ||
| 2983 | } | ||
| 2984 | $IS_ROLLINGBACK_DATABASE = 0; | ||
| 2985 | |||
| 2986 | $class->_for_each_data_source("rollback") | ||
| 2987 | or die "FAILED TO ROLLBACK!: " . $class->error_message; | ||
| 2988 | return 1; | ||
| 2989 | } | ||
| 2990 | |||
| 2991 | sub _disconnect_databases { | ||
| 2992 | my $class = shift; | ||
| 2993 | $class->_for_each_data_source("disconnect"); | ||
| 2994 | return 1; | ||
| 2995 | } | ||
| 2996 | |||
| 2997 | sub _for_each_data_source { | ||
| 2998 | my($class,$method) = @_; | ||
| 2999 | |||
| 3000 | my @ds = $UR::Context::current->all_objects_loaded('UR::DataSource'); | ||
| 3001 | foreach my $ds ( @ds ) { | ||
| 3002 | unless ($ds->$method) { | ||
| 3003 | $class->error_message("$method failed on DataSource ",$ds->get_name); | ||
| 3004 | return; | ||
| 3005 | } | ||
| 3006 | } | ||
| 3007 | return 1; | ||
| 3008 | } | ||
| 3009 | |||
| 3010 | sub _get_committed_property_value { | ||
| 3011 | my $class = shift; | ||
| 3012 | my $object = shift; | ||
| 3013 | my $property_name = shift; | ||
| 3014 | |||
| 3015 | if ($object->{'db_committed'}) { | ||
| 3016 | return $object->{'db_committed'}->{$property_name}; | ||
| 3017 | } elsif ($object->{'db_saved_uncommitted'}) { | ||
| 3018 | return $object->{'db_saved_uncommitted'}->{$property_name}; | ||
| 3019 | } else { | ||
| 3020 | return; | ||
| 3021 | } | ||
| 3022 | } | ||
| 3023 | |||
| 3024 | sub _dump_change_snapshot { | ||
| 3025 | my $class = shift; | ||
| 3026 | my %params = @_; | ||
| 3027 | |||
| 3028 | my @c = grep { $_->__changes__ } $UR::Context::current->all_objects_loaded('UR::Object'); | ||
| 3029 | |||
| 3030 | my $fh; | ||
| 3031 | if (my $filename = $params{filename}) | ||
| 3032 | { | ||
| 3033 | $fh = IO::File->new(">$filename"); | ||
| 3034 | unless ($fh) | ||
| 3035 | { | ||
| 3036 | $class->error_message("Failed to open file $filename: $!"); | ||
| 3037 | return; | ||
| 3038 | } | ||
| 3039 | } | ||
| 3040 | else | ||
| 3041 | { | ||
| 3042 | $fh = "STDOUT"; | ||
| 3043 | } | ||
| 3044 | require YAML; | ||
| 3045 | $fh->print(YAML::Dump(\@c)); | ||
| 3046 | $fh->close; | ||
| 3047 | } | ||
| 3048 | |||
| 3049 | sub reload { | ||
| 3050 | my $self = shift; | ||
| 3051 | |||
| 3052 | # this is here for backward external compatability | ||
| 3053 | # get() now goes directly to the context | ||
| 3054 | |||
| 3055 | my $class = shift; | ||
| 3056 | if (ref $class) { | ||
| 3057 | # Trying to reload a specific object? | ||
| 3058 | if (@_) { | ||
| 3059 | Carp::confess("load() on an instance with parameters is not supported"); | ||
| 3060 | return; | ||
| 3061 | } | ||
| 3062 | @_ = ('id' ,$class->id()); | ||
| 3063 | $class = ref $class; | ||
| 3064 | } | ||
| 3065 | |||
| 3066 | my ($rule, @extra) = UR::BoolExpr->resolve_normalized($class,@_); | ||
| 3067 | |||
| 3068 | if (@extra) { | ||
| 3069 | if (scalar @extra == 2 and ($extra[0] eq "sql" or $extra[0] eq 'sql in')) { | ||
| 3070 | return $UR::Context::current->_get_objects_for_class_and_sql($class,$extra[1]); | ||
| 3071 | } | ||
| 3072 | else { | ||
| 3073 | die "Odd parameters passed directly to $class load(): @extra.\n" | ||
| 3074 | . "Processable params were: " | ||
| 3075 | . Data::Dumper::Dumper({ $rule->params_list }); | ||
| 3076 | } | ||
| 3077 | } | ||
| 3078 | return $UR::Context::current->get_objects_for_class_and_rule($class,$rule,1); | ||
| 3079 | } | ||
| 3080 | |||
| 3081 | ## This is old, untested code that we may wany to resurrect at some point | ||
| 3082 | # | ||
| 3083 | #our $CORE_DUMP_VERSION = 1; | ||
| 3084 | ## Use Data::Dumper to save a representation of the object cache to a file. Args are: | ||
| 3085 | ## filename => the name of the file to save to | ||
| 3086 | ## dumpall => boolean flagging whether to dump _everything_, or just the things | ||
| 3087 | ## that would actually be loaded later in core_restore() | ||
| 3088 | # | ||
| 3089 | #sub _core_dump { | ||
| 3090 | # my $class = shift; | ||
| 3091 | # my %args = @_; | ||
| 3092 | # | ||
| 3093 | # my $filename = $args{'filename'} || "/tmp/core." . UR::Context::Process->prog_name . ".$ENV{HOST}.$$"; | ||
| 3094 | # my $dumpall = $args{'dumpall'}; | ||
| 3095 | # | ||
| 3096 | # my $fh = IO::File->new(">$filename"); | ||
| 3097 | # if (!$fh) { | ||
| 3098 | # $class->error_message("Can't open dump file $filename for writing: $!"); | ||
| 3099 | # return undef; | ||
| 3100 | # } | ||
| 3101 | # | ||
| 3102 | # my $dumper; | ||
| 3103 | # if ($dumpall) { # Go ahead and dump everything | ||
| 3104 | # $dumper = Data::Dumper->new([$CORE_DUMP_VERSION, | ||
| 3105 | # $UR::Context::all_objects_loaded, | ||
| 3106 | # $UR::Context::all_objects_are_loaded, | ||
| 3107 | # $UR::Context::all_params_loaded, | ||
| 3108 | # $UR::Context::all_change_subscriptions], | ||
| 3109 | # ['dump_version','all_objects_loaded','all_objects_are_loaded', | ||
| 3110 | # 'all_params_loaded','all_change_subscriptions']); | ||
| 3111 | # } else { | ||
| 3112 | # my %DONT_UNLOAD = | ||
| 3113 | # map { | ||
| 3114 | # my $co = $_->__meta__; | ||
| 3115 | # if ($co and not $co->is_transactional) { | ||
| 3116 | # ($_ => 1) | ||
| 3117 | # } | ||
| 3118 | # else { | ||
| 3119 | # () | ||
| 3120 | # } | ||
| 3121 | # } | ||
| 3122 | # $UR::Context::current->all_objects_loaded('UR::Object'); | ||
| 3123 | # | ||
| 3124 | # my %aol = map { ($_ => $UR::Context::all_objects_loaded->{$_}) } | ||
| 3125 | # grep { ! $DONT_UNLOAD{$_} } keys %$UR::Context::all_objects_loaded; | ||
| 3126 | # my %aoal = map { ($_ => $UR::Context::all_objects_are_loaded->{$_}) } | ||
| 3127 | # grep { ! $DONT_UNLOAD{$_} } keys %$UR::Context::all_objects_are_loaded; | ||
| 3128 | # my %apl = map { ($_ => $UR::Context::all_params_loaded->{$_}) } | ||
| 3129 | # grep { ! $DONT_UNLOAD{$_} } keys %$UR::Context::all_params_loaded; | ||
| 3130 | # # don't dump $UR::Context::all_change_subscriptions | ||
| 3131 | # $dumper = Data::Dumper->new([$CORE_DUMP_VERSION,\%aol, \%aoal, \%apl], | ||
| 3132 | # ['dump_version','all_objects_loaded','all_objects_are_loaded', | ||
| 3133 | # 'all_params_loaded']); | ||
| 3134 | # | ||
| 3135 | # } | ||
| 3136 | # | ||
| 3137 | # $dumper->Purity(1); # For dumping self-referential data structures | ||
| 3138 | # $dumper->Sortkeys(1); # Makes quick and dirty file comparisons with sum/diff work correctly-ish | ||
| 3139 | # | ||
| 3140 | # $fh->print($dumper->Dump() . "\n"); | ||
| 3141 | # | ||
| 3142 | # $fh->close; | ||
| 3143 | # | ||
| 3144 | # return $filename; | ||
| 3145 | #} | ||
| 3146 | # | ||
| 3147 | ## Read a file previously generated with core_dump() and repopulate the object cache. Args are: | ||
| 3148 | ## filename => name of the coredump file | ||
| 3149 | ## force => boolean flag whether to go ahead and attempt to load the file even if it thinks | ||
| 3150 | ## there is a formatting problem | ||
| 3151 | #sub _core_restore { | ||
| 3152 | # my $class = shift; | ||
| 3153 | # my %args = @_; | ||
| 3154 | # my $filename = $args{'filename'}; | ||
| 3155 | # my $forcerestore = $args{'force'}; | ||
| 3156 | # | ||
| 3157 | # my $fh = IO::File->new("$filename"); | ||
| 3158 | # if (!$fh) { | ||
| 3159 | # $class->error_message("Can't open dump file $filename for restoring: $!"); | ||
| 3160 | # return undef; | ||
| 3161 | # } | ||
| 3162 | # | ||
| 3163 | # my $code; | ||
| 3164 | # while (<$fh>) { $code .= $_ } | ||
| 3165 | # | ||
| 3166 | # my($dump_version,$all_objects_loaded,$all_objects_are_loaded,$all_params_loaded,$all_change_subscriptions); | ||
| 3167 | # eval $code; | ||
| 3168 | # | ||
| 3169 | # if ($@) | ||
| 3170 | # { | ||
| 3171 | # $class->error_message("Failed to restore core file state: $@"); | ||
| 3172 | # return undef; | ||
| 3173 | # } | ||
| 3174 | # if ($dump_version != $CORE_DUMP_VERSION) { | ||
| 3175 | # $class->error_message("core file's version $dump_version differs from expected $CORE_DUMP_VERSION"); | ||
| 3176 | # return 0 unless $forcerestore; | ||
| 3177 | # } | ||
| 3178 | # | ||
| 3179 | # my %DONT_UNLOAD = | ||
| 3180 | # map { | ||
| 3181 | # my $co = $_->__meta__; | ||
| 3182 | # if ($co and not $co->is_transactional) { | ||
| 3183 | # ($_ => 1) | ||
| 3184 | # } | ||
| 3185 | # else { | ||
| 3186 | # () | ||
| 3187 | # } | ||
| 3188 | # } | ||
| 3189 | # $UR::Context::current->all_objects_loaded('UR::Object'); | ||
| 3190 | # | ||
| 3191 | # # Go through the loaded all_objects_loaded, prune out the things that | ||
| 3192 | # # are in %DONT_UNLOAD | ||
| 3193 | # my %loaded_classes; | ||
| 3194 | # foreach ( keys %$all_objects_loaded ) { | ||
| 3195 | # next if ($DONT_UNLOAD{$_}); | ||
| 3196 | # $UR::Context::all_objects_loaded->{$_} = $all_objects_loaded->{$_}; | ||
| 3197 | # $loaded_classes{$_} = 1; | ||
| 3198 | # | ||
| 3199 | # } | ||
| 3200 | # foreach ( keys %$all_objects_are_loaded ) { | ||
| 3201 | # next if ($DONT_UNLOAD{$_}); | ||
| 3202 | # $UR::Context::all_objects_are_loaded->{$_} = $all_objects_are_loaded->{$_}; | ||
| 3203 | # $loaded_classes{$_} = 1; | ||
| 3204 | # } | ||
| 3205 | # foreach ( keys %$all_params_loaded ) { | ||
| 3206 | # next if ($DONT_UNLOAD{$_}); | ||
| 3207 | # $UR::Context::all_params_loaded->{$_} = $all_params_loaded->{$_}; | ||
| 3208 | # $loaded_classes{$_} = 1; | ||
| 3209 | # } | ||
| 3210 | # # $UR::Context::all_change_subscriptions is basically a bunch of coderef | ||
| 3211 | # # callbacks that can't reliably be dumped anyway, so we skip it | ||
| 3212 | # | ||
| 3213 | # # Now, get the classes to instantiate themselves | ||
| 3214 | # foreach ( keys %loaded_classes ) { | ||
| 3215 | # $_->class() unless m/::Ghost$/; | ||
| 3216 | # } | ||
| 3217 | # | ||
| 3218 | # return 1; | ||
| 3219 | #} | ||
| 3220 | |||
| 3221 | 1; | ||
| 3222 | |||
| 3223 | =pod | ||
| 3224 | |||
| 3225 | =head1 NAME | ||
| 3226 | |||
| 3227 | UR::Context - Manage the current state of the application | ||
| 3228 | |||
| 3229 | =head1 SYNOPSIS | ||
| 3230 | |||
| 3231 | use AppNamespace; | ||
| 3232 | |||
| 3233 | my $obj = AppNamespace::SomeClass->get(id => 1234); | ||
| 3234 | $obj->some_property('I am changed'); | ||
| 3235 | |||
| 3236 | UR::Context->get_current->rollback; # some_property reverts to its original value | ||
| 3237 | |||
| 3238 | $obj->other_property('Now, I am changed'); | ||
| 3239 | |||
| 3240 | UR::Context->commit; # other_property now permanently has that value | ||
| 3241 | |||
| 3242 | |||
| 3243 | =head1 DESCRIPTION | ||
| 3244 | |||
| 3245 | The main application code will rarely interact with UR::Context objects | ||
| 3246 | directly, except for the C<commit> and C<rollback> methods. It manages | ||
| 3247 | the mappings between an application's classes, object cache, and external | ||
| 3248 | data sources. | ||
| 3249 | |||
| 3250 | =head1 SUBCLASSES | ||
| 3251 | |||
| 3252 | UR::Context is an abstract class. When an application starts up, the system | ||
| 3253 | creates a handful of Contexts that logically exist within one another: | ||
| 3254 | |||
| 3255 | =over 2 | ||
| 3256 | |||
| 3257 | =item 1. | ||
| 3258 | L<UR::Context::Root> - A context to represent all the data reachable in the | ||
| 3259 | application's namespace. It connects the application to external data | ||
| 3260 | sources. | ||
| 3261 | |||
| 3262 | =item 2. | ||
| 3263 | L<UR::Context::Process> - A context to represent the state of data within | ||
| 3264 | the currently running application. It handles the transfer of data to and | ||
| 3265 | from the Root context, through the object cache, on behalf of the application | ||
| 3266 | code. | ||
| 3267 | |||
| 3268 | =item 3. | ||
| 3269 | L<UR::Context::Transaction> - A context to represent an in-memory transaction | ||
| 3270 | as a diff of the object cache. The Transaction keeps a list of changes to | ||
| 3271 | objects and is able to revert those changes with C<rollback()>, or apply them | ||
| 3272 | to the underlying context with C<commit()>. | ||
| 3273 | |||
| 3274 | =back | ||
| 3275 | |||
| 3276 | =head1 CONSTRUCTOR | ||
| 3277 | |||
| 3278 | =over 4 | ||
| 3279 | |||
| 3280 | =item begin | ||
| 3281 | |||
| 3282 | my $trans = UR::Context::Transaction->begin(); | ||
| 3283 | |||
| 3284 | L<UR::Context::Transaction> instances are created through C<begin()>. | ||
| 3285 | |||
| 3286 | =back | ||
| 3287 | |||
| 3288 | A L<UR::Context::Root> and L<UR::Context::Process> context will be created | ||
| 3289 | for you when the application initializes. Additional instances of these | ||
| 3290 | classes are not usually instantiated. | ||
| 3291 | |||
| 3292 | =head1 METHODS | ||
| 3293 | |||
| 3294 | Most of the methods below can be called as either a class or object method | ||
| 3295 | of UR::Context. If called as a class method, they will operate on the current | ||
| 3296 | context. | ||
| 3297 | |||
| 3298 | =over 4 | ||
| 3299 | |||
| 3300 | =item get_current | ||
| 3301 | |||
| 3302 | my $context = UR::Context::get_current(); | ||
| 3303 | |||
| 3304 | Returns the UR::Context instance of whatever is the most currently created | ||
| 3305 | Context. Can be called as a class or object method. | ||
| 3306 | |||
| 3307 | =item query_underlying_context | ||
| 3308 | |||
| 3309 | my $should_load = $context->query_underlying_context(); | ||
| 3310 | $context->query_underlying_context(1); | ||
| 3311 | |||
| 3312 | A property of the Context that sets the default value of the C<$should_load> | ||
| 3313 | flag inside C<get_objects_for_class_and_rule> as described below. Initially, | ||
| 3314 | its value is undef, meaning that during a get(), the Context will query the | ||
| 3315 | underlying data sources only if this query has not been done before. Setting | ||
| 3316 | this property to 0 will make the Context never query data sources, meaning | ||
| 3317 | that the only objects retrievable are those already in memory. Setting the | ||
| 3318 | property to 1 means that every query will hit the data sources, even if the | ||
| 3319 | query has been done before. | ||
| 3320 | |||
| 3321 | =item get_objects_for_class_and_rule | ||
| 3322 | |||
| 3323 | @objs = $context->get_objects_for_class_and_rule( | ||
| 3324 | $class_name, | ||
| 3325 | $boolexpr, | ||
| 3326 | $should_load, | ||
| 3327 | $should_return_iterator | ||
| 3328 | ); | ||
| 3329 | |||
| 3330 | This is the method that serves as the main entry point to the Context behind | ||
| 3331 | the C<get()>, and C<is_loaded()> methods of L<UR::Object>, and C<reload()> method | ||
| 3332 | of UR::Context. | ||
| 3333 | |||
| 3334 | C<$class_name> and C<$boolexpr> are required arguments, and specify the | ||
| 3335 | target class by name and the rule used to filter the objects the caller | ||
| 3336 | is interested in. | ||
| 3337 | |||
| 3338 | C<$should_load> is a flag indicating whether the Context should load objects | ||
| 3339 | satisfying the rule from external data sources. A true value means it should | ||
| 3340 | always ask the relevant data sources, even if the Context believes the | ||
| 3341 | requested data is in the object cache, A false but defined value means the | ||
| 3342 | Context should not ask the data sources for new data, but only return what | ||
| 3343 | is currently in the cache matching the rule. The value C<undef> means the | ||
| 3344 | Context should use the value of its query_underlying_context property. If | ||
| 3345 | that is also undef, then it will use its own judgement about asking the | ||
| 3346 | data sources for new data, and will merge cached and external data as | ||
| 3347 | necessary to fulfill the request. | ||
| 3348 | |||
| 3349 | C<$should_return_iterator> is a flag indicating whether this method should | ||
| 3350 | return the objects directly as a list, or iterator function instead. If | ||
| 3351 | true, it returns a subref that returns one object each time it is called, | ||
| 3352 | and undef after the last matching object: | ||
| 3353 | |||
| 3354 | my $iter = $context->get_objects_for_class_and_rule( | ||
| 3355 | 'MyClass', | ||
| 3356 | $rule, | ||
| 3357 | undef, | ||
| 3358 | 1 | ||
| 3359 | ); | ||
| 3360 | my @objs; | ||
| 3361 | while (my $obj = $iter->()); | ||
| 3362 | push @objs, $obj; | ||
| 3363 | } | ||
| 3364 | |||
| 3365 | =item has_changes | ||
| 3366 | |||
| 3367 | my $bool = $context->has_changes(); | ||
| 3368 | |||
| 3369 | Returns true if any objects in the given Context's object cache (or the | ||
| 3370 | current Context if called as a class method) have any changes that haven't | ||
| 3371 | been saved to the underlying context. | ||
| 3372 | |||
| 3373 | =item commit | ||
| 3374 | |||
| 3375 | UR::Context->commit(); | ||
| 3376 | |||
| 3377 | Causes all objects with changes to save their changes back to the underlying | ||
| 3378 | context. If the current context is a L<UR::Context::Transaction>, then the | ||
| 3379 | changes will be applied to whatever Context the transaction is a part of. | ||
| 3380 | if the current context is a L<UR::Context::Process> context, then C<commit()> | ||
| 3381 | pushes the changes to the underlying L<UR::Context::Root> context, meaning | ||
| 3382 | that those changes will be applied to the relevant data sources. | ||
| 3383 | |||
| 3384 | In the usual case, where no transactions are in play and all data sources | ||
| 3385 | are RDBMS databases, calling C<commit()> will cause the program to begin | ||
| 3386 | issuing SQL against the databases to update changed objects, insert rows | ||
| 3387 | for newly created objects, and delete rows from deleted objects as part of | ||
| 3388 | an SQL transaction. If all the changes apply cleanly, it will do and SQL | ||
| 3389 | C<commit>, or C<rollback> if not. | ||
| 3390 | |||
| 3391 | commit() returns true if all the changes have been safely transferred to the | ||
| 3392 | underlying context, false if there were problems. | ||
| 3393 | |||
| 3394 | =item rollback | ||
| 3395 | |||
| 3396 | UR::Context->rollback(); | ||
| 3397 | |||
| 3398 | Causes all objects' changes for the current transaction to be reversed. | ||
| 3399 | If the current context is a L<UR::Context::Transaction>, then the | ||
| 3400 | transactional properties of those objects will be reverted to the values | ||
| 3401 | they had when the transaction started. Outside of a transaction, object | ||
| 3402 | properties will be reverted to their values when they were loaded from the | ||
| 3403 | underlying data source. rollback() will also ask all the underlying | ||
| 3404 | databases to rollback. | ||
| 3405 | |||
| 3406 | =item clear_cache | ||
| 3407 | |||
| 3408 | UR::Context->clear_cache(); | ||
| 3409 | |||
| 3410 | Asks the current context to remove all non-infrastructional data from its | ||
| 3411 | object cache. This method will fail and return false if any object has | ||
| 3412 | changes. | ||
| 3413 | |||
| 3414 | =item resolve_data_source_for_object | ||
| 3415 | |||
| 3416 | my $ds = $obj->resolve_data_source_for_object(); | ||
| 3417 | |||
| 3418 | For the given C<$obj> object, return the L<UR::DataSource> instance that | ||
| 3419 | object was loaded from or would be saved to. If objects of that class do | ||
| 3420 | not have a data source, then it will return C<undef>. | ||
| 3421 | |||
| 3422 | =item resolve_data_sources_for_class_meta_and_rule | ||
| 3423 | |||
| 3424 | my @ds = $context->resolve_data_sources_for_class_meta_and_rule($class_obj, $boolexpr); | ||
| 3425 | |||
| 3426 | For the given class metaobject and boolean expression (rule), return the list of | ||
| 3427 | data sources that will need to be queried in order to return the objects | ||
| 3428 | matching the rule. In most cases, only one data source will be returned. | ||
| 3429 | |||
| 3430 | =item infer_property_value_from_rule | ||
| 3431 | |||
| 3432 | my $value = $context->infer_property_value_from_rule($property_name, $boolexpr); | ||
| 3433 | |||
| 3434 | For the given boolean expression (rule), and a property name not mentioned in | ||
| 3435 | the rule, but is a property of the class the rule is against, return the value | ||
| 3436 | that property must logically have. | ||
| 3437 | |||
| 3438 | For example, if this object is the only TestClass object where C<foo> is | ||
| 3439 | the value 'bar', it can infer that the TestClass property C<baz> must | ||
| 3440 | have the value 'blah' in the current context. | ||
| 3441 | |||
| 3442 | my $obj = TestClass->create(id => 1, foo => 'bar', baz=> 'blah'); | ||
| 3443 | my $rule = UR::BoolExpr->resolve('TestClass', foo => 'bar); | ||
| 3444 | my $val = $context->infer_property_value_from_rule('baz', $rule); | ||
| 3445 | # val now is 'blah' | ||
| 3446 | |||
| 3447 | =item object_cache_size_highwater | ||
| 3448 | |||
| 3449 | UR::Context->object_cache_size_highwater(5000); | ||
| 3450 | my $highwater = UR::Context->object_cache_size_highwater(); | ||
| 3451 | |||
| 3452 | Set or get the value for the Context's object cache pruning high water | ||
| 3453 | mark. The object cache pruner will be run during the next C<get()> if the | ||
| 3454 | cache contains more than this number of prunable objects. See the | ||
| 3455 | L</Object Cache Pruner> section below for more information. | ||
| 3456 | |||
| 3457 | =item object_cache_size_lowwater | ||
| 3458 | |||
| 3459 | UR::Context->object_cache_size_lowwater(5000); | ||
| 3460 | my $lowwater = UR::Context->object_cache_size_lowwater(); | ||
| 3461 | |||
| 3462 | Set or get the value for the Context's object cache pruning high water | ||
| 3463 | mark. The object cache pruner will stop when the number of prunable objects | ||
| 3464 | falls below this number. | ||
| 3465 | |||
| 3466 | =item prune_object_cache | ||
| 3467 | |||
| 3468 | UR::Context->prune_object_cache(); | ||
| 3469 | |||
| 3470 | Manually run the object cache pruner. | ||
| 3471 | |||
| 3472 | =item reload | ||
| 3473 | |||
| 3474 | UR::Context->reload($object); | ||
| 3475 | UR::Context->reload('Some::Class', 'property_name', value); | ||
| 3476 | |||
| 3477 | Ask the context to load an object's data from an underlying Context, even if | ||
| 3478 | the object is already cached. With a single parameter, it will use that | ||
| 3479 | object's ID parameters as the basis for querying the data source. C<reload> | ||
| 3480 | will also accept a class name and list of key/value parameters the same as | ||
| 3481 | C<get>. | ||
| 3482 | |||
| 3483 | =item _light_cache | ||
| 3484 | |||
| 3485 | UR::Context->_light_cache(1); | ||
| 3486 | |||
| 3487 | Turn on or off the light caching flag. Light caching alters the behavior | ||
| 3488 | of the object cache in that all object references in the cache are made weak | ||
| 3489 | by Scalar::Util::weaken(). This means that the application code must keep | ||
| 3490 | hold of any object references it wants to keep alive. Light caching defaults | ||
| 3491 | to being off, and must be explicitly turned on with this method. | ||
| 3492 | |||
| 3493 | =back | ||
| 3494 | |||
| 3495 | =head1 Custom observer aspects | ||
| 3496 | |||
| 3497 | UR::Context sends signals for observers watching for some non-standard aspects. | ||
| 3498 | |||
| 3499 | =over 2 | ||
| 3500 | |||
| 3501 | =item precommit | ||
| 3502 | |||
| 3503 | After C<commit()> has been called, but before any changes are saved to the | ||
| 3504 | data sources. The only parameters to the Observer's callback are the Context | ||
| 3505 | object and the aspect ("precommit"). | ||
| 3506 | |||
| 3507 | =item commit | ||
| 3508 | |||
| 3509 | After C<commit()> has been called, and after an attempt has been made to save | ||
| 3510 | the changes to the data sources. The parameters to the callback are the | ||
| 3511 | Context object, the aspect ("commit"), and a boolean value indicating whether | ||
| 3512 | the commit succeeded or not. | ||
| 3513 | |||
| 3514 | =item prerollback | ||
| 3515 | |||
| 3516 | After C<rollback()> has been called, but before and object state is reverted. | ||
| 3517 | |||
| 3518 | =item rollback | ||
| 3519 | |||
| 3520 | After C<rollback()> has been called, and after an attempt has been made to | ||
| 3521 | revert the state of all the loaded objects. The parameters to the callback | ||
| 3522 | are the Context object, the aspect ("rollback"), and a boolean value | ||
| 3523 | indicating whether the rollback succeeded or not. | ||
| 3524 | |||
| 3525 | =back | ||
| 3526 | |||
| 3527 | =head1 Data Concurrency | ||
| 3528 | |||
| 3529 | Currently, the Context is optimistic about data concurrency, meaning that | ||
| 3530 | it does very little to prevent clobbering data in underlying Contexts during | ||
| 3531 | a commit() if other processes have changed an object's data after the Context | ||
| 3532 | has cached and object. For example, a database has an object with ID 1 and | ||
| 3533 | a property with value 'bob'. A program loads this object and changes the | ||
| 3534 | property to 'fred', but does not yet commit(). Meanwhile, another program | ||
| 3535 | loads the same object, changes the value to 'joe' and does commit(). Finally | ||
| 3536 | the first program calls commit(). The final value in the database will be | ||
| 3537 | 'fred', and no exceptions will be raised. | ||
| 3538 | |||
| 3539 | As part of the caching behavior, the Context keeps a record of what the | ||
| 3540 | object's state is as it's loaded from the underlying Context. This is how | ||
| 3541 | the Context knows what object have been changed during C<commit()>. | ||
| 3542 | |||
| 3543 | If an already cached object's data is reloaded as part of some other query, | ||
| 3544 | data consistency of each property will be checked. If there are no | ||
| 3545 | conflicting changes, then any differences between the object's initial state | ||
| 3546 | and the current state in the underlying Context will be applied to the | ||
| 3547 | object's notion of what it thinks its initial state is. | ||
| 3548 | |||
| 3549 | In some future release, UR may support additional data concurrency methods | ||
| 3550 | such as pessimistic concurrency: check that the current state of all | ||
| 3551 | changed (or even all cached) objects in the underlying Context matches the | ||
| 3552 | initial state before committing changes downstream. Or allowing the object | ||
| 3553 | cache to operate in write-through mode for some or all classes. | ||
| 3554 | |||
| 3555 | =head1 Internal Methods | ||
| 3556 | |||
| 3557 | There are many methods in UR::Context meant to be used internally, but are | ||
| 3558 | worth documenting for anyone interested in the inner workings of the Context | ||
| 3559 | code. | ||
| 3560 | |||
| 3561 | =over 4 | ||
| 3562 | |||
| 3563 | =item _create_import_iterator_for_underlying_context | ||
| 3564 | |||
| 3565 | $subref = $context->_create_import_iterator_for_underlying_context( | ||
| 3566 | $boolexpr, $data_source, $serial_number | ||
| 3567 | ); | ||
| 3568 | $next_obj = $subref->(); | ||
| 3569 | |||
| 3570 | This method is part of the object loading process, and is called by | ||
| 3571 | L</get_objects_for_class_and_rule> when it is determined that the requested | ||
| 3572 | data does not exist in the object cache, and data should be brought in from | ||
| 3573 | another, underlying Context. Usually this means the data will be loaded | ||
| 3574 | from an external data source. | ||
| 3575 | |||
| 3576 | C<$boolexpr> is the L<UR::BoolExpr> rule, usually from the application code. | ||
| 3577 | |||
| 3578 | C<$data_source> is the L<UR::DataSource> that will be used to load data from. | ||
| 3579 | |||
| 3580 | C<$serial_number> is used by the object cache pruner. Each object loaded | ||
| 3581 | through this iterator will have $serial_number in its C<__get_serial> hashref | ||
| 3582 | key. | ||
| 3583 | |||
| 3584 | It works by first getting an iterator for the data source (the | ||
| 3585 | C<$db_iterator>). It calls L</_resolve_query_plan_for_ds_and_bxt> to find out | ||
| 3586 | how data is to be loaded and whether this request spans multiple data | ||
| 3587 | sources. It calls L</__create_object_fabricator_for_loading_template> to get | ||
| 3588 | a list of closures to transform the primary data source's data into UR | ||
| 3589 | objects, and L</_create_secondary_loading_closures> (if necessary) to get | ||
| 3590 | more closures that can load and join data from the primary to the secondary | ||
| 3591 | data source(s). | ||
| 3592 | |||
| 3593 | It returns a subref that works as an iterator, loading and returning objects | ||
| 3594 | one at a time from the underlying context into the current context. It | ||
| 3595 | returns undef when there are no more objects to return. | ||
| 3596 | |||
| 3597 | The returned iterator works by first asking the C<$db_iterator> for the next | ||
| 3598 | row of data as a listref. Asks the secondary data source joiners whether | ||
| 3599 | there is any matching data. Calls the object fabricator closures to convert | ||
| 3600 | the data source data into UR objects. If any of the object requires | ||
| 3601 | subclassing, then additional importing iterators are created to handle that. | ||
| 3602 | Finally, the objects matching the rule are returned to the caller one at a | ||
| 3603 | time. | ||
| 3604 | |||
| 3605 | =item _resolve_query_plan_for_ds_and_bxt | ||
| 3606 | |||
| 3607 | my $query_plan = $context->_resolve_query_plan_for_ds_and_bxt( | ||
| 3608 | $data_source, | ||
| 3609 | $boolexpr_tmpl | ||
| 3610 | ); | ||
| 3611 | my($query_plan, @addl_info) = $context->_resolve_query_plan_for_ds_and_bxt( | ||
| 3612 | $data_source, | ||
| 3613 | $boolexpr_tmpl | ||
| 3614 | ); | ||
| 3615 | |||
| 3616 | When a request is made that will hit one or more data sources, | ||
| 3617 | C<_resolve_query_plan_for_ds_and_bxt> is used to call a method of the same name | ||
| 3618 | on the data source. It returns a hashref used by many other parts of the | ||
| 3619 | object loading system, and describes what data source to use, how to query | ||
| 3620 | that data source to get the objects, how to use the raw data returned by | ||
| 3621 | the data source to construct objects and how to resolve any delegated | ||
| 3622 | properties that are a part of the rule. | ||
| 3623 | |||
| 3624 | C<$data_source> is a L<UR::DataSource> object ID. C<$coolexpr_tmpl> is a | ||
| 3625 | L<UR::BoolExpr::Template> object. | ||
| 3626 | |||
| 3627 | In the common case, the query will only use one data source, and this method | ||
| 3628 | returns that data directly. But if the primary data source sets the | ||
| 3629 | C<joins_across_data_sources> key on the data structure as may be the case | ||
| 3630 | when a rule involves a delegated property to a class that uses a different | ||
| 3631 | data source, then this methods returns an additional list of data. For | ||
| 3632 | each additional data source needed to resolve the query, this list will have | ||
| 3633 | three items: | ||
| 3634 | |||
| 3635 | =over 2 | ||
| 3636 | |||
| 3637 | =item 1. | ||
| 3638 | |||
| 3639 | The secondary data source ID | ||
| 3640 | |||
| 3641 | =item 2. | ||
| 3642 | |||
| 3643 | A listref of delegated L<UR::Object::Property> objects joining the primary | ||
| 3644 | data source to this secondary data source. | ||
| 3645 | |||
| 3646 | =item 3. | ||
| 3647 | |||
| 3648 | A L<UR::BoolExpr::Template> rule template applicable against the secondary | ||
| 3649 | data source | ||
| 3650 | |||
| 3651 | =back | ||
| 3652 | |||
| 3653 | =item _create_secondary_rule_from_primary | ||
| 3654 | |||
| 3655 | my $new_rule = $context->_create_secondary_rule_from_primary( | ||
| 3656 | $primary_rule, | ||
| 3657 | $delegated_properties, | ||
| 3658 | $secondary_rule_tmpl | ||
| 3659 | ); | ||
| 3660 | |||
| 3661 | When resolving a request that requires multiple data sources, | ||
| 3662 | this method is used to construct a rule against applicable against the | ||
| 3663 | secondary data source. C<$primary_rule> is the L<UR::BoolExpr> rule used | ||
| 3664 | in the original query. C<$delegated_properties> is a listref of | ||
| 3665 | L<UR::Object::Property> objects as returned by | ||
| 3666 | L</_resolve_query_plan_for_ds_and_bxt()> linking the primary to the secondary data | ||
| 3667 | source. C<$secondary_rule_tmpl> is the rule template, also as returned by | ||
| 3668 | L</_resolve_query_plan_for_ds_and_bxt()>. | ||
| 3669 | |||
| 3670 | =item _create_secondary_loading_closures | ||
| 3671 | |||
| 3672 | my($obj_importers, $joiners) = $context->_create_secondary_loading_closures( | ||
| 3673 | $primary_rule_tmpl, | ||
| 3674 | @addl_info); | ||
| 3675 | |||
| 3676 | When reolving a request that spans multiple data sources, | ||
| 3677 | this method is used to construct two lists of subrefs to aid in the request. | ||
| 3678 | C<$primary_rule_tmpl> is the L<UR::BoolExpr::Template> rule template made | ||
| 3679 | from the original rule. C<@addl_info> is the same list returned by | ||
| 3680 | L</_resolve_query_plan_for_ds_and_bxt>. For each secondary data source, there | ||
| 3681 | will be one item in the two listrefs that are returned, and in the same | ||
| 3682 | order. | ||
| 3683 | |||
| 3684 | C<$obj_importers> is a listref of subrefs used as object importers. They | ||
| 3685 | transform the raw data returned by the data sources into UR objects. | ||
| 3686 | |||
| 3687 | C<$joiners> is also a listref of subrefs. These closures know how the | ||
| 3688 | properties link the primary data source data to the secondary data source. | ||
| 3689 | They take the raw data from the primary data source, load the next row of | ||
| 3690 | data from the secondary data source, and returns the secondary data that | ||
| 3691 | successfully joins to the primary data. You can think of these closures as | ||
| 3692 | performing the same work as an SQL C<join> between data in different data | ||
| 3693 | sources. | ||
| 3694 | |||
| 3695 | =item _cache_is_complete_for_class_and_normalized_rule | ||
| 3696 | |||
| 3697 | ($is_cache_complete, $objects_listref) = | ||
| 3698 | $context->_cache_is_complete_for_class_and_normalized_rule( | ||
| 3699 | $class_name, $boolexpr | ||
| 3700 | ); | ||
| 3701 | |||
| 3702 | This method is part of the object loading process, and is called by | ||
| 3703 | L</get_objects_for_class_and_rule> to determine if the objects requested | ||
| 3704 | by the L<UR::BoolExpr> C<$boolexpr> will be found entirely in the object | ||
| 3705 | cache. If the answer is yes then C<$is_cache_complete> will be true. | ||
| 3706 | C<$objects_listef> may or may not contain objects matching the rule from | ||
| 3707 | the cache. If that list is not returned, then | ||
| 3708 | L</get_objects_for_class_and_rule> does additional work to locate the | ||
| 3709 | matching objects itself via L</_get_objects_for_class_and_rule_from_cache> | ||
| 3710 | |||
| 3711 | It does its magic by looking at the C<$boolexpr> and loosely matching it | ||
| 3712 | against the query cache C<$UR::Context::all_params_loaded> | ||
| 3713 | |||
| 3714 | =item _get_objects_for_class_and_rule_from_cache | ||
| 3715 | |||
| 3716 | @objects = $context->_get_objects_for_class_and_rule_from_cache( | ||
| 3717 | $class_name, $boolexpr | ||
| 3718 | ); | ||
| 3719 | |||
| 3720 | This method is called by L</get_objects_for_class_and_rule> when | ||
| 3721 | L<_cache_is_complete_for_class_and_normalized_rule> says the requested | ||
| 3722 | objects do exist in the cache, but did not return those items directly. | ||
| 3723 | |||
| 3724 | The L<UR::BoolExpr> C<$boolexpr> contains hints about how the matching data | ||
| 3725 | is likely to be found. Its C<_context_query_strategy> key will contain | ||
| 3726 | one of three values | ||
| 3727 | |||
| 3728 | =over 2 | ||
| 3729 | |||
| 3730 | =item 1. all | ||
| 3731 | |||
| 3732 | This rule is against a class with no filters, meaning it should return every | ||
| 3733 | member of that class. It calls C<$class-E<gt>all_objects_loaded> to extract | ||
| 3734 | all objects of that class in the object cache. | ||
| 3735 | |||
| 3736 | =item 2. id | ||
| 3737 | |||
| 3738 | This rule is against a class and filters by only a single ID, or a list of | ||
| 3739 | IDs. The request is fulfilled by plucking the matching objects right out | ||
| 3740 | of the object cache. | ||
| 3741 | |||
| 3742 | =item 3. index | ||
| 3743 | |||
| 3744 | This rule is against one more more non-id properties. An index is built | ||
| 3745 | mapping the filtered properties and their values, and the cached objects | ||
| 3746 | which have those values. The request is fulfilled by using the index to | ||
| 3747 | find objects matching the filter. | ||
| 3748 | |||
| 3749 | =item 4. set intersection | ||
| 3750 | |||
| 3751 | This is a group-by rule and will return a ::Set object. | ||
| 3752 | |||
| 3753 | =back | ||
| 3754 | |||
| 3755 | =item _loading_was_done_before_with_a_superset_of_this_params_hashref | ||
| 3756 | |||
| 3757 | $bool = $context->_loading_was_done_before_with_a_superset_of_this_params_hashref( | ||
| 3758 | $class_name, | ||
| 3759 | $params_hashref | ||
| 3760 | ); | ||
| 3761 | |||
| 3762 | This method is used by L</_cache_is_complete_for_class_and_normalized_rule> | ||
| 3763 | to determine if the requested data was asked for previously, either from a | ||
| 3764 | get() asking for a superset of the current request, or from a request on | ||
| 3765 | a parent class of the current request. | ||
| 3766 | |||
| 3767 | For example, if a get() is done on a class with one param: | ||
| 3768 | |||
| 3769 | @objs = ParentClass->get(param_1 => 'foo'); | ||
| 3770 | |||
| 3771 | And then later, another request is done with an additional param: | ||
| 3772 | |||
| 3773 | @objs2 = ParentClass->get(param_1 => 'foo', param_2 => 'bar'); | ||
| 3774 | |||
| 3775 | Then the first request must have returned all the data that could have | ||
| 3776 | possibly satisfied the second request, and so the system will not issue | ||
| 3777 | a query against the data source. | ||
| 3778 | |||
| 3779 | As another example, given those two previously done queries, if another | ||
| 3780 | get() is done on a class that inherits from ParentClass | ||
| 3781 | |||
| 3782 | @objs3 = ChildClass->get(param_1 => 'foo'); | ||
| 3783 | |||
| 3784 | again, the first request has already loaded all the relevant data, and | ||
| 3785 | therefore won't query the data source. | ||
| 3786 | |||
| 3787 | =item _sync_databases | ||
| 3788 | |||
| 3789 | $bool = $context->_sync_databases(); | ||
| 3790 | |||
| 3791 | Starts the process of committing all the Context's changes to the external | ||
| 3792 | data sources. _sync_databases() is the workhorse behind L</commit>. | ||
| 3793 | |||
| 3794 | First, it finds all objects with changes. Checks those changed objects | ||
| 3795 | for validity with C<$obj-E<gt>invalid>. If any objects are found invalid, | ||
| 3796 | then _sync_databases() will fail. Finally, it bins all the changed objects | ||
| 3797 | by data source, and asks each data source to save those objects' changes. | ||
| 3798 | It returns true if all the data sources were able to save the changes, | ||
| 3799 | false otherwise. | ||
| 3800 | |||
| 3801 | =item _reverse_all_changes | ||
| 3802 | |||
| 3803 | $bool = $context->_reverse_all_changes(); | ||
| 3804 | |||
| 3805 | _reverse_all_changes() is the workhorse behind L</rollback>. | ||
| 3806 | |||
| 3807 | For each class, it goes through each object of that class. If the object | ||
| 3808 | is a L<UR::Object::Ghost>, representing a deleted object, it converts the | ||
| 3809 | ghost back to the live version of the object. For other classes, it makes | ||
| 3810 | a list of properties that have changed since they were loaded (represented | ||
| 3811 | by the C<db_committed> hash key in the object), and reverts those changes | ||
| 3812 | by using each property's accessor method. | ||
| 3813 | |||
| 3814 | =back | ||
| 3815 | |||
| 3816 | =head1 The Object Cache | ||
| 3817 | |||
| 3818 | The object cache is integral to the way the Context works, and also the main | ||
| 3819 | difference between UR and other ORMs. Other systems do no caching and | ||
| 3820 | require the calling application to hold references to any objects it | ||
| 3821 | is interested in. Say one part of the app loads data from the database and | ||
| 3822 | gives up its references, then if another part of the app does the same or | ||
| 3823 | similar query, it will have to ask the database again. | ||
| 3824 | |||
| 3825 | UR handles caching of classes, objects and queries to avoid asking the data | ||
| 3826 | sources for data it has loaded previously. The object cache is essentially | ||
| 3827 | a software transaction that sits above whatever database transaction is | ||
| 3828 | active. After objects are loaded, any changes, creations or deletions exist | ||
| 3829 | only in the object cache, and are not saved to the underlying data sources | ||
| 3830 | until the application explicitly requests a commit or rollback. | ||
| 3831 | |||
| 3832 | Objects are returned to the application only after they are inserted into | ||
| 3833 | the object cache. This means that if disconnected parts of the application | ||
| 3834 | are returned objects with the same class and ID, they will have references | ||
| 3835 | to the same exact object reference, and changes made in one part will be | ||
| 3836 | visible to all other parts of the app. An unchanged object can be removed | ||
| 3837 | from the object cache by calling its C<unload()> method. | ||
| 3838 | |||
| 3839 | Since changes to the underlying data sources are effectively delayed, it is | ||
| 3840 | possible that the application's notion of the object's current state does | ||
| 3841 | not match the data stored in the data source. You can mitigate this by using | ||
| 3842 | the C<load()> class or object method to fetch the latest data if it's a | ||
| 3843 | problem. Another issue to be aware of is if multiple programs are likely | ||
| 3844 | to commit conflicting changes to the same data, then whichever applies its | ||
| 3845 | changes last will win; some kind of external locking needs to be applied. | ||
| 3846 | Finally, if two programs attempt to insert data with the same ID columns | ||
| 3847 | into an RDBMS table, the second application's commit will fail, since that | ||
| 3848 | will likely violate a constraint. | ||
| 3849 | |||
| 3850 | =head2 Object Change Tracking | ||
| 3851 | |||
| 3852 | As objects are loaded from their data sources, their properties are | ||
| 3853 | initialized with the data from the query, and a copy of the same data is | ||
| 3854 | stored in the object in its C<db_committed> hash key. Anyone can ask the | ||
| 3855 | object for a list of its changes by calling C<$obj-E<gt>changed>. | ||
| 3856 | Internally, changed() goes through all the object's properties, comparing | ||
| 3857 | the current values in the object's hash with the same keys under | ||
| 3858 | 'db_committed'. | ||
| 3859 | |||
| 3860 | Objects created through the C<create()> class method have no 'db_committed', | ||
| 3861 | and so the object knows it it a newly created object in this context. | ||
| 3862 | |||
| 3863 | Every time an object is retrieved with get() or through an iterator, it is | ||
| 3864 | assigned a serial number in its C<__get_serial> hash key from the | ||
| 3865 | C<$UR::Context::GET_SERIAL> counter. This number is unique and increases | ||
| 3866 | with each get(), and is used by the L</Object Cache Pruner> to expire the | ||
| 3867 | least recently requested data. | ||
| 3868 | |||
| 3869 | Objects also track what parameters have been used to get() them in the hash | ||
| 3870 | C<$obj-E<gt>{__load}>. This is a copy of the data in | ||
| 3871 | C<$UR::Context::all_params_loaded-E<gt>{$template_id}>. For each rule | ||
| 3872 | ID, it will have a count of the number of times that rule was used in a get(). | ||
| 3873 | |||
| 3874 | =head2 Deleted Objects and Ghosts | ||
| 3875 | |||
| 3876 | Calling delete() on an object is tracked in a different way. First, a new | ||
| 3877 | object is created, called a ghost. Ghost classes exist for every | ||
| 3878 | class in the application and are subclasses of L<UR::Object::Ghost>. For | ||
| 3879 | example, the ghost class for MyClass is MyClass::Ghost. This ghost object | ||
| 3880 | is initialized with the data from the original object. The original object | ||
| 3881 | is removed from the object cache, and is reblessed into the UR::DeletedRef | ||
| 3882 | class. Any attempt to interact with the object further will raise an | ||
| 3883 | exception. | ||
| 3884 | |||
| 3885 | Ghost objects are not included in a get() request on the regular class, | ||
| 3886 | though the app can ask for them specifically using | ||
| 3887 | C<MyClass::Ghost-E<gt>get(%params)>. | ||
| 3888 | |||
| 3889 | Ghost classes do not have ghost classes themselves. Calling create() or | ||
| 3890 | delete() on a Ghost class or object will raise an exception. Calling other | ||
| 3891 | methods on the Ghost object that exist on the original, live class will | ||
| 3892 | delegate over to the live class's method. | ||
| 3893 | |||
| 3894 | =head2 all_objects_are_loaded | ||
| 3895 | |||
| 3896 | C<$UR::Context::all_objects_are_loaded> is a hashref keyed by class names. | ||
| 3897 | If the value is true, then L</_cache_is_complete_for_class_and_normalized_rule> | ||
| 3898 | knows that all the instances of that class exist in the object cache, and | ||
| 3899 | it can avoid asking the underlying context/datasource for that class' data. | ||
| 3900 | |||
| 3901 | =head2 all_params_loaded | ||
| 3902 | |||
| 3903 | C<$UR::Context::all_params_loaded> is a two-level hashref. The first level | ||
| 3904 | is template (L<UR::BoolExpr::Template>) IDs. The second level is rule | ||
| 3905 | (L<UR::BoolExpr>) IDs. The values are how many times that class and rule | ||
| 3906 | have been involved in a get(). This data is used by | ||
| 3907 | L</_loading_was_done_before_with_a_superset_of_this_params_hashref> | ||
| 3908 | to determine if the requested data will be found in the object cache for | ||
| 3909 | non-id queries. | ||
| 3910 | |||
| 3911 | =head2 all_objects_loaded | ||
| 3912 | |||
| 3913 | C<$UR::Context::all_objects_loaded> is a two-level hashref. The first level | ||
| 3914 | is class names. The second level is object IDs. Every time an object is | ||
| 3915 | created, defined or loaded from an underlying context, it is inserted into | ||
| 3916 | the C<all_objects_loaded> hash. For queries involving only ID properties, | ||
| 3917 | the Context can retrieve them directly out of the cache if they appear there. | ||
| 3918 | |||
| 3919 | The entire cache can be purged of non-infrastructional objects by calling | ||
| 3920 | L</clear_cache>. | ||
| 3921 | |||
| 3922 | =head2 Object Cache Pruner | ||
| 3923 | |||
| 3924 | The default Context behavior is to cache all objects it knows about for the | ||
| 3925 | entire life of the process. For programs that churn through large amounts | ||
| 3926 | of data, or live for a long time, this is probably not what you want. | ||
| 3927 | |||
| 3928 | The Context has two settings to loosely control the size of the object | ||
| 3929 | cache. L</object_cache_size_highwater> and L</object_cache_size_lowwater>. | ||
| 3930 | As objects are created and loaded, a count of uncachable objects is kept | ||
| 3931 | in C<$UR::Context::all_objects_cache_size>. The first part of | ||
| 3932 | L</get_objects_for_class_and_rule> checks to see of the current size is | ||
| 3933 | greater than the highwater setting, and call L</prune_object_cache> if so. | ||
| 3934 | |||
| 3935 | prune_object_cache() works by looking at what C<$UR::Context::GET_SERIAL> | ||
| 3936 | was the last time it ran, and what it is now, and making a guess about | ||
| 3937 | what object serial number to use as a guide for removing objects by starting | ||
| 3938 | at 10% of the difference between the last serial and the current value, | ||
| 3939 | called the target serial. | ||
| 3940 | |||
| 3941 | |||
| 3942 | It then starts executing a loop as long as C<$UR::Context::all_objects_cache_size> | ||
| 3943 | is greater than the lowwater setting. For each uncachable object, if its | ||
| 3944 | C<__get_serial> is less than the target serial, it is weakened from any | ||
| 3945 | L<UR::Object::Index>es it may be a member of, and then weakened from the | ||
| 3946 | main object cache, C<$UR::Context::all_objects_loaded>. | ||
| 3947 | |||
| 3948 | The application may lock an object in the cache by calling C<__strengthen__> on | ||
| 3949 | it, Likewise, the app may hint to the pruner to throw away an object as | ||
| 3950 | soon as possible by calling C<__weaken__>. | ||
| 3951 | |||
| 3952 | =head1 SEE ALSO | ||
| 3953 | |||
| 3954 | L<UR::Context::Root>, L<UR::Context::Process>, L<UR::Object>, | ||
| 3955 | L<UR::DataSource>, L<UR::Object::Ghost>, L<UR::Observer> | ||
| 3956 | |||
| 3957 | =cut | ||
| 3958 |