ObjectDriver/BaseObject.pm untested

filter: Statementstmt 0.0% 0 / 408 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 60 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 71 Podpod 0.0% 0 / 58 totaltotal 0.0% 0 / 750 CC 60 SCAR 33.0
CC
60
Cov
0%
has_a
182.0
search
42.0
primary_key_to_terms
30.0
CRAP 27.1
1 # $Id$
2  
3 package Data::ObjectDriver::BaseObject;
4 use strict;
5 use warnings;
6  
7 our $HasWeaken;
8 eval q{ use Scalar::Util qw(weaken) }; ## no critic
9 $HasWeaken = !$@;
10  
11 use Carp ();
12  
13 use Class::Trigger qw( pre_save post_save post_load pre_search
14 pre_insert post_insert pre_update post_update
15 pre_remove post_remove post_inflate );
16  
17 use Data::ObjectDriver::ResultSet;
18  
19 ## Global Transaction variables
20 our @WorkingDrivers;
21 our $TransactionLevel = 0;
22  
23 sub install_properties {
24 my $class = shift;
25 my($props) = @_;
26 my $columns = delete $props->{columns};
27 $props->{columns} = [];
28 {
29 no strict 'refs'; ## no critic
30 *{"${class}::__properties"} = sub { $props };
31 }
32  
33 foreach my $col (@$columns) {
34 $class->install_column($col);
35 }
36 return $props;
37 }
38  
39 sub install_column {
40 my($class, $col, $type) = @_;
41 my $props = $class->properties;
42  
43 push @{ $props->{columns} }, $col;
44 $props->{column_names}{$col} = ();
45 # predefine getter/setter methods here
46 # Skip adding this method if the class overloads it.
47 # this lets the SUPER::columnname magic do it's thing
48 if (! $class->can($col)) {
49 no strict 'refs'; ## no critic
50 *{"${class}::$col"} = $class->column_func($col);
51 }
52 if ($type) {
53 $props->{column_defs}{$col} = $type;
54 }
55 }
56  
57 sub properties {
58 my $this = shift;
59 my $class = ref($this) || $this;
60 $class->__properties;
61 }
62  
63 # see docs below
64  
65 sub has_a {
66 my $class = shift;
67 my @args = @_;
68  
69 # Iterate over each remote object
70 foreach my $config (@args) {
71 my $parentclass = $config->{class};
72  
73 # Parameters
74 my $column = $config->{column};
75 my $method = $config->{method};
76 my $cached = $config->{cached} || 0;
77 my $parent_method = $config->{parent_method};
78  
79 # column is required
80 if (!defined($column)) {
81 die "Please specify a valid column for $parentclass"
82 }
83  
84 # create a method name based on the column
85 if (! defined $method) {
86 if (!ref($column)) {
87 $method = $column;
88 $method =~ s/_id$//;
89 $method .= "_obj";
90 } elsif (ref($column) eq 'ARRAY') {
91 foreach my $col (@{$column}) {
92 my $part = $col;
93 $part =~ s/_id$//;
94 $method .= $part . '_';
95 }
96 $method .= "obj";
97 }
98 }
99  
100 # die if we have clashing methods method
101 if (! defined $method || defined(*{"${class}::$method"})) {
102 die "Please define a valid method for $class->$column";
103 }
104  
105 if ($cached) {
106 # Store cached item inside this object's namespace
107 my $cachekey = "__cache_$method";
108  
109 no strict 'refs'; ## no critic
110 *{"${class}::$method"} = sub {
111 my $obj = shift;
112  
113 return $obj->{$cachekey}
114 if defined $obj->{$cachekey};
115  
116 my $id = (ref($column) eq 'ARRAY')
117 ? [ map { $obj->{column_values}->{$_} } @{$column}]
118 : $obj->{column_values}->{$column}
119 ;
120 ## Hold in a variable here too, so we don't lose it immediately
121 ## by having only the weak reference.
122 my $ret = $parentclass->lookup($id);
123 if ($HasWeaken) {
124 $obj->{$cachekey} = $ret;
125 weaken($obj->{$cachekey});
126 }
127 return $ret;
128 };
129 } else {
130 if (ref($column)) {
131 no strict 'refs'; ## no critic
132 *{"${class}::$method"} = sub {
133 my $obj = shift;
134 return $parentclass->lookup([ map{ $obj->{column_values}->{$_} } @{$column}]);
135 };
136 } else {
137 no strict 'refs'; ## no critic
138 *{"${class}::$method"} = sub {
139 return $parentclass->lookup(shift()->{column_values}->{$column});
140 };
141 }
142 }
143  
144 # now add to the parent
145 if (!defined $parent_method) {
146 $parent_method = lc($class);
147 $parent_method =~ s/^.*:://;
148  
149 $parent_method .= '_objs';
150 }
151 if (ref($column)) {
152 no strict 'refs'; ## no critic
153 *{"${parentclass}::$parent_method"} = sub {
154 my $obj = shift;
155 my $terms = shift || {};
156 my $args = shift;
157  
158 my $primary_key = $obj->primary_key;
159  
160 # inject pk search into given terms.
161 # composite key, ugh
162 foreach my $key (@$column) {
163 $terms->{$key} = shift(@{$primary_key});
164 }
165  
166 return $class->search($terms, $args);
167 };
168 } else {
169 no strict 'refs'; ## no critic
170 *{"${parentclass}::$parent_method"} = sub {
171 my $obj = shift;
172 my $terms = shift || {};
173 my $args = shift;
174 # TBD - use primary_key_to_terms
175 $terms->{$column} = $obj->primary_key;
176 return $class->search($terms, $args);
177 };
178 };
179 } # end of loop over class names
180 return;
181 }
182  
183 sub driver {
184 my $class = shift;
185 $class->properties->{driver} ||= $class->properties->{get_driver}->();
186 }
187  
188 sub get_driver {
189 my $class = shift;
190 $class->properties->{get_driver} = shift if @_;
191 }
192  
193 sub new {
194 my $obj = bless {}, shift;
195  
196 return $obj->init(@_);
197 }
198  
199 sub init {
200 my $self = shift;
201  
202 while (@_) {
203 my $field = shift;
204 my $val = shift;
205 $self->$field($val);
206 }
207 return $self;
208 }
209  
210 sub is_pkless {
211 my $obj = shift;
212 my $prop_pk = $obj->properties->{primary_key};
213 return 1 if ! $prop_pk;
214 return 1 if ref $prop_pk eq 'ARRAY' && ! @$prop_pk;
215 }
216  
217 sub is_primary_key {
218 my $obj = shift;
219 my($col) = @_;
220  
221 my $prop_pk = $obj->properties->{primary_key};
222 if (ref($prop_pk)) {
223 for my $pk (@$prop_pk) {
224 return 1 if $pk eq $col;
225 }
226 } else {
227 return 1 if $prop_pk eq $col;
228 }
229  
230 return;
231 }
232  
233 sub primary_key_tuple {
234 my $obj = shift;
235 my $pk = $obj->properties->{primary_key} || return;
236 $pk = [ $pk ] unless ref($pk) eq 'ARRAY';
237 $pk;
238 }
239  
240 sub primary_key {
241 my $obj = shift;
242 my $pk = $obj->primary_key_tuple;
243 my @val = map { $obj->$_() } @$pk;
244 @val == 1 ? $val[0] : \@val;
245 }
246  
247 sub is_same_array {
248 my($a1, $a2) = @_;
249 return if ($#$a1 != $#$a2);
250 for (my $i = 0; $i <= $#$a1; $i++) {
251 return if $a1->[$i] ne $a2->[$i];
252 }
253 return 1;
254 }
255  
256 sub primary_key_to_terms {
257 my($obj, $id) = @_;
258 my $pk = $obj->primary_key_tuple;
259 if (! defined $id) {
260 $id = $obj->primary_key;
261 } else {
262 if (ref($id) eq 'HASH') {
263 my @keys = sort keys %$id;
264 unless (is_same_array(\@keys, [ sort @$pk ])) {
265 Carp::confess("keys don't match with primary keys: @keys|@$pk");
266 }
267 return $id;
268 }
269 }
270 $id = [ $id ] unless ref($id) eq 'ARRAY';
271 my %terms;
272 @terms{@$pk} = @$id;
273 \%terms;
274 }
275  
276 sub is_same {
277 my($obj, $other) = @_;
278  
279 my @a;
280 for my $o ($obj, $other) {
281 push @a, [ map { $o->$_() } @{ $o->primary_key_tuple }];
282 }
283 return is_same_array( @a );
284 }
285  
286 sub object_is_stored {
287 my $obj = shift;
288 return $obj->{__is_stored} ? 1 : 0;
289 }
290 sub pk_str {
291 my ($obj) = @_;
292 my $pk = $obj->primary_key;
293 return $pk unless ref ($pk) eq 'ARRAY';
294 return join (":", @$pk);
295 }
296  
297 sub has_primary_key {
298 my $obj = shift;
299 return unless @{$obj->primary_key_tuple};
300 my $val = $obj->primary_key;
301 $val = [ $val ] unless ref($val) eq 'ARRAY';
302 for my $v (@$val) {
303 return unless defined $v;
304 }
305 1;
306 }
307  
308 sub datasource { $_[0]->properties->{datasource} }
309  
310 sub columns_of_type {
311 my $obj = shift;
312 my($type) = @_;
313 my $props = $obj->properties;
314 my $cols = $props->{columns};
315 my $col_defs = $props->{column_defs};
316 my @cols;
317 for my $col (@$cols) {
318 push @cols, $col if $col_defs->{$col} && $col_defs->{$col} eq $type;
319 }
320 \@cols;
321 }
322  
323 sub set_values {
324 my $obj = shift;
325 my $values = shift;
326 for my $col (keys %$values) {
327 unless ( $obj->has_column($col) ) {
328 Carp::croak("You tried to set non-existent column $col to value $values->{$col} on " . ref($obj));
329 }
330 $obj->$col($values->{$col});
331 }
332 }
333  
334 sub set_values_internal {
335 my $obj = shift;
336 my $values = shift;
337 for my $col (keys %$values) {
338 # Not needed for the internal version of this method
339 #unless ( $obj->has_column($col) ) {
340 # Carp::croak("You tried to set inexistent column $col to value $values->{$col} on " . ref($obj));
341 #}
342  
343 $obj->column_values->{$col} = $values->{$col};
344 }
345 }
346  
347 sub clone {
348 my $obj = shift;
349 my $clone = $obj->clone_all;
350 for my $pk (@{ $obj->primary_key_tuple }) {
351 $clone->$pk(undef);
352 }
353 $clone;
354 }
355  
356 sub clone_all {
357 my $obj = shift;
358 my $clone = ref($obj)->new();
359 $clone->set_values_internal($obj->column_values);
360 $clone->{changed_cols} = defined $obj->{changed_cols} ? { %{$obj->{changed_cols}} } : undef;
361 $clone;
362 }
363  
364 sub has_column {
365 return exists $_[0]->properties->{column_names}{$_[1]};
366 }
367  
368 sub column_names {
369 ## Reference to a copy.
370 [ @{ shift->properties->{columns} } ]
371 }
372  
373 sub column_values { $_[0]->{'column_values'} ||= {} }
374  
375 ## In 0.1 version we didn't die on inexistent column
376 ## which might lead to silent bugs
377 ## You should override column if you want to find the old
378 ## behaviour
379 sub column {
380 my $obj = shift;
381 my $col = shift or return;
382 unless ($obj->has_column($col)) {
383 Carp::croak("Cannot find column '$col' for class '" . ref($obj) . "'");
384 }
385  
386 # set some values
387 if (@_) {
388 $obj->{column_values}->{$col} = shift;
389 unless ($_[0] && ref($_[0]) eq 'HASH' && $_[0]->{no_changed_flag}) {
390 $obj->{changed_cols}->{$col}++;
391 }
392 }
393  
394 $obj->{column_values}->{$col};
395 }
396  
397 sub column_func {
398 my $obj = shift;
399 my $col = shift or die "Must specify column";
400  
401 return sub {
402 my $obj = shift;
403 # getter
404 return $obj->{column_values}->{$col} unless (@_);
405  
406 # setter
407 my ($val, $flags) = @_;
408 $obj->{column_values}->{$col} = $val;
409 unless ($flags && ref($flags) eq 'HASH' && $flags->{no_changed_flag}) {
410 $obj->{changed_cols}->{$col}++;
411 }
412  
413 return $obj->{column_values}->{$col};
414 };
415 }
416  
417  
418 sub changed_cols_and_pk {
419 my $obj = shift;
420 keys %{$obj->{changed_cols}};
421 }
422  
423 sub changed_cols {
424 my $obj = shift;
425 my $pk = $obj->primary_key_tuple;
426 my %pk = map { $_ => 1 } @$pk;
427 grep !$pk{$_}, $obj->changed_cols_and_pk;
428 }
429  
430 sub is_changed {
431 my $obj = shift;
432 if (@_) {
433 return exists $obj->{changed_cols}->{$_[0]};
434 } else {
435 return $obj->changed_cols > 0;
436 }
437 }
438  
439 sub exists {
440 my $obj = shift;
441 return 0 unless $obj->has_primary_key;
442 $obj->_proxy('exists', @_);
443 }
444  
445 sub save {
446 my $obj = shift;
447 if ($obj->exists(@_)) {
448 return $obj->update(@_);
449 } else {
450 return $obj->insert(@_);
451 }
452 }
453  
454 sub bulk_insert {
455 my $class = shift;
456 my $driver = $class->driver;
457  
458 return $driver->bulk_insert($class, @_);
459 }
460  
461 sub lookup {
462 my $class = shift;
463 my $driver = $class->driver;
464 my $obj = $driver->lookup($class, @_) or return;
465 $driver->cache_object($obj);
466 $obj;
467 }
468  
469 sub lookup_multi {
470 my $class = shift;
471 my $driver = $class->driver;
472 my $objs = $driver->lookup_multi($class, @_) or return;
473 for my $obj (@$objs) {
474 $driver->cache_object($obj) if $obj;
475 }
476 $objs;
477 }
478  
479 sub result {
480 my $class = shift;
481 my ($terms, $args) = @_;
482  
483 return Data::ObjectDriver::ResultSet->new({
484 class => (ref $class || $class),
485 page_size => delete $args->{page_size},
486 paging => delete $args->{no_paging},
487 terms => $terms,
488 args => $args,
489 });
490 }
491  
492 sub search {
493 my $class = shift;
494 my($terms, $args) = @_;
495 my $driver = $class->driver;
496 if (wantarray) {
497 my @objs = $driver->search($class, $terms, $args);
498  
499 ## Don't attempt to cache objects where the caller specified fetchonly,
500 ## because they won't be complete.
501 ## Also skip this step if we don't get any objects back from the search
502 if (!$args->{fetchonly} || !@objs) {
503 for my $obj (@objs) {
504 $driver->cache_object($obj) if $obj;
505 }
506 }
507 return @objs;
508 } else {
509 my $iter = $driver->search($class, $terms, $args);
510 return $iter if $args->{fetchonly};
511  
512 my $caching_iter = sub {
513 my $d = $driver;
514  
515 my $o = $iter->();
516 unless ($o) {
517 $iter->end;
518 return;
519 }
520 $driver->cache_object($o);
521 return $o;
522 };
523 return Data::ObjectDriver::Iterator->new($caching_iter, sub { $iter->end });
524 }
525 }
526  
527 sub remove { shift->_proxy( 'remove', @_ ) }
528 sub update { shift->_proxy( 'update', @_ ) }
529 sub insert { shift->_proxy( 'insert', @_ ) }
530 sub replace { shift->_proxy( 'replace', @_ ) }
531 sub fetch_data { shift->_proxy( 'fetch_data', @_ ) }
532 sub uncache_object { shift->_proxy( 'uncache_object', @_ ) }
533  
534 sub refresh {
535 my $obj = shift;
536 return unless $obj->has_primary_key;
537 my $fields = $obj->fetch_data;
538 $obj->set_values_internal($fields);
539 $obj->call_trigger('post_load');
540 $obj->driver->cache_object($obj);
541 return 1;
542 }
543  
544 ## NOTE: I wonder if it could be useful to BaseObject superclass
545 ## to override the global transaction flag. If so, I'd add methods
546 ## to manipulate this flag and the working drivers. -- Yann
547 sub _proxy {
548 my $obj = shift;
549 my($meth, @args) = @_;
550 my $driver = $obj->driver;
551 ## faster than $obj->txn_active && ! $driver->txn_active but see note.
552 if ($TransactionLevel && ! $driver->txn_active) {
553 $driver->begin_work;
554 push @WorkingDrivers, $driver;
555 }
556 $driver->$meth($obj, @args);
557 }
558  
559 sub txn_active { $TransactionLevel }
560  
561 sub begin_work {
562 my $class = shift;
563 if ( $TransactionLevel > 0 ) {
564 Carp::carp(
565 $TransactionLevel > 1
566 ? "$TransactionLevel transactions already active"
567 : "Transaction already active"
568 );
569 }
570 $TransactionLevel++;
571 }
572  
573 sub commit {
574 my $class = shift;
575 $class->_end_txn('commit');
576 }
577  
578 sub rollback {
579 my $class = shift;
580 $class->_end_txn('rollback');
581 }
582  
583 sub _end_txn {
584 my $class = shift;
585 my $meth = shift;
586
587 ## Ignore nested transactions
588 if ($TransactionLevel > 1) {
589 $TransactionLevel--;
590 return;
591 }
592
593 if (! $TransactionLevel) {
594 Carp::carp("No active transaction to end; ignoring $meth");
595 return;
596 }
597 my @wd = @WorkingDrivers;
598 $TransactionLevel--;
599 @WorkingDrivers = ();
600
601 for my $driver (@wd) {
602 $driver->$meth;
603 }
604 }
605  
606 sub txn_debug {
607 my $class = shift;
608 return {
609 txn => $TransactionLevel,
610 drivers => \@WorkingDrivers,
611 };
612 }
613  
614 sub deflate { { columns => shift->column_values } }
615  
616 sub inflate {
617 my $class = shift;
618 my($deflated) = @_;
619 my $obj = $class->new;
620 $obj->set_values_internal($deflated->{columns});
621 $obj->call_trigger('post_inflate');
622 return $obj;
623 }
624  
625 sub DESTROY { }
626  
627 sub AUTOLOAD {
628 my $obj = $_[0];
629 (my $col = our $AUTOLOAD) =~ s!.+::!!;
630 Carp::croak("Cannot find method '$col' for class '$obj'") unless ref $obj;
631 unless ($obj->has_column($col)) {
632 Carp::croak("Cannot find column '$col' for class '" . ref($obj) . "'");
633 }
634  
635 {
636 no strict 'refs'; ## no critic
637 *$AUTOLOAD = $obj->column_func($col);
638 }
639  
640 goto &$AUTOLOAD;
641 }
642  
643 sub has_partitions {
644 my $class = shift;
645 my(%param) = @_;
646 my $how_many = delete $param{number}
647 or Carp::croak("number (of partitions) is required");
648  
649 ## save the number of partitions in the class
650 $class->properties->{number_of_partitions} = $how_many;
651  
652 ## Save the get_driver subref that we were passed, so that the
653 ## SimplePartition driver can access it.
654 $class->properties->{partition_get_driver} = delete $param{get_driver}
655 or Carp::croak("get_driver is required");
656  
657 ## When creating a new $class object, we should automatically fill in
658 ## the partition ID by selecting one at random, unless a partition_id
659 ## is already defined. This allows us to keep it simple but for the
660 ## caller to do something more complex, if it wants to.
661 $class->add_trigger(pre_insert => sub {
662 my($obj, $orig_obj) = @_;
663 unless (defined $obj->partition_id) {
664 my $partition_id = int(rand $how_many) + 1;
665 $obj->partition_id($partition_id);
666 $orig_obj->partition_id($partition_id);
667 }
668 });
669 }
670  
671 1;
672  
673 __END__