SPOPS/DBI.pm untested

filter: Statementstmt 0.0% 0 / 555 Branchbran 0.0% 0 / 182 Conditioncond 0.0% 0 / 211 MC/DCmcdc 0.0% 0 / 133 Subroutinesub 0.0% 0 / 53 Podpod 0.0% 0 / 42 totaltotal 0.0% 0 / 1176 CC 92 SCAR 43.0
CC
92
Cov
0%
save
306.0
field_update
132.0
_save_insert
110.0
CRAP 73.5
1 package SPOPS::DBI;
2  
3 # $Id: DBI.pm,v 3.23 2004/06/02 00:48:21 lachoy Exp $
4  
5 use strict;
6 use base qw( SPOPS SPOPS::SQLInterface );
7 use Data::Dumper qw( Dumper );
8 use DBI;
9 use Log::Log4perl qw( get_logger );
10 use SPOPS::Exception qw( spops_error );
11 use SPOPS::Exception::DBI;
12 use SPOPS::Iterator::DBI;
13 use SPOPS::Secure qw( :level );
14 use SPOPS::Tie qw( $PREFIX_INTERNAL );
15  
16 my $log = get_logger();
17  
18 $SPOPS::DBI::VERSION = sprintf("%d.%02d", q$Revision: 3.23 $ =~ /(\d+)\.(\d+)/);
19  
20 $SPOPS::DBI::GUESS_ID_FIELD_TYPE = DBI::SQL_INTEGER();
21  
22  
23 ########################################
24 # CONFIGURATION
25 ########################################
26  
27 # Point by default to configuration values; children
28 # can override with hardcoded values if desired
29  
30 sub no_insert_id { return 0; } # used anymore??
31 sub field_alter { return $_[0]->CONFIG->{field_alter} }
32 sub insert_alter { return $_[0]->CONFIG->{insert_alter} }
33 sub base_table { return $_[0]->CONFIG->{base_table} }
34 sub key_table { return $_[0]->CONFIG->{key_table} || $_[0]->CONFIG->{base_table} }
35 sub table_name { return $_[0]->CONFIG->{table_name} || $_[0]->CONFIG->{base_table} }
36 sub no_insert { return $_[0]->CONFIG->{no_insert} || {} }
37 sub no_update { return $_[0]->CONFIG->{no_update} || {} }
38 sub skip_undef { return $_[0]->CONFIG->{skip_undef} || {} }
39 sub no_save_sync { return $_[0]->CONFIG->{no_save_sync} }
40  
41  
42 ########################################
43 # CLASS CONFIGURATION
44 ########################################
45  
46 sub behavior_factory {
47 my ( $class ) = @_;
48 require SPOPS::ClassFactory::DBI;
49 $log->is_info &&
50 $log->info( "Installing SPOPS::DBI behaviors for ($class)" );
51 return { links_to => \&SPOPS::ClassFactory::DBI::conf_relate_links_to,
52 id_method => \&SPOPS::ClassFactory::DBI::conf_multi_field_key_id,
53 read_code => \&SPOPS::ClassFactory::DBI::conf_multi_field_key_other };
54 }
55  
56  
57 ########################################
58 # CONNECTION RETRIEVAL
59 ########################################
60  
61 # Override this to get the db handle from somewhere
62  
63 sub global_datasource_handle { return undef }
64  
65 # Backward compatible
66  
67 sub global_db_handle { my $o = shift; return $o->global_datasource_handle( @_ ) }
68  
69  
70 ########################################
71 # SQL DEFAULTS
72 ########################################
73  
74 # This is (I think) an ANSI SQL default for returning
75 # the current date/datetime; db-specific modules should
76 # override as needed, although you can also simply call
77 #
78 # my $formatted_date = $obj->now; (or SPOPS::Utility->now)
79 #
80 # And format as needed (See SPOPS::Utility->now) for direct insert.
81  
82 sub sql_current_date { return 'CURRENT_TIMESTAMP()' }
83 sub sql_fetch_types { return "SELECT * FROM $_[1] WHERE 1 = 0" }
84 sub sql_case_insensitive { return 'LIKE' }
85  
86 ########################################
87 # CLASS INITIALIZATION
88 ########################################
89  
90 # Make this the default for everyone -- they can override it
91 # themselves...
92  
93 sub class_initialize {
94 my ( $class, $CONFIG ) = @_;
95 $CONFIG ||= {};
96 my $C = $class->CONFIG;
97 $C->{table_owner} = $CONFIG->{db_info}{db_owner};
98 $C->{table_name} = ( $C->{table_owner} )
99 ? "$C->{table_owner}.$C->{base_table}" : $C->{base_table};
100  
101 # allow subclasses to do their own thing
102 $class->_class_initialize( $CONFIG );
103 return 1;
104 }
105  
106  
107 sub _class_initialize { return 1 }
108  
109  
110 ########################################
111 # OBJECT IDENTIFICATION
112 ########################################
113  
114 # Generic method to return a SQL clause to identify a particular
115 # record -- a suitable for a where clause:
116 # page_id = 5
117 # comment_id = '818172723'
118  
119 sub id_clause {
120 my ( $item, $id, $opt, $p ) = @_;
121  
122 $opt ||= '';
123 $p ||= {};
124  
125 # If we weren't passed an ID and $item isn't an
126 # object, there's a problem
127  
128 unless ( $id or ref( $item ) ) {
129 $log->warn( "No ID passed in and called as a class method rather than",
130 "an object method." );
131 return undef;
132 }
133 $id ||= $item->id;
134  
135 my $db = $p->{db} || $item->global_datasource_handle( $p->{connect_key} );
136 unless ( $db ) {
137 spops_error 'Cannot create ID clause because no database ',
138 'handle accessible.';
139 }
140  
141 my $id_field = $item->id_field;
142 my $type_info = eval { $item->db_discover_types(
143 $item->base_table,
144 { dbi_type_info => $p->{dbi_type_info},
145 db => $db } ) };
146  
147 # If we cannot get the type via our own system, just guess that the
148 # ID field is a number
149  
150 if ( $@ ) {
151 $type_info = SPOPS::DBI::TypeInfo->new({ table => $item->base_table });
152 $type_info->add_type( $id_field, $SPOPS::DBI::GUESS_ID_FIELD_TYPE );
153 $log->warn( "Trying to build ID clause but cannot discover type information about ",
154 "table ", $item->base_table, ". Making a best guess using field ",
155 "type '$SPOPS::DBI::GUESS_ID_FIELD_TYPE'" );
156 }
157 my $use_id_field = ( $opt eq 'noqualify' )
158 ? $id_field
159 : join( '.', $item->table_name, $id_field );
160 my $quoted_value = $item->sql_quote( $id, $type_info->get_type( $id_field ), $db );
161 return join(' = ', $use_id_field, $quoted_value );
162 }
163  
164  
165 # Should return: ( 'myid' ) if 'noqualify' param is true
166 # ( 'mytable.myid' ) if not true
167  
168 sub id_field_select {
169 my ( $class, $p ) = @_;
170 return ( $p->{noqualify} )
171 ? $class->id_field
172 : join( '.', $class->table_name, $class->id_field );
173 }
174  
175  
176 ########################################
177 # UTILITY
178 ########################################
179  
180 # Class method
181 # - If \%fields -- return a hashref with no private fields and keys
182 # translated to mapped fields
183 # - If \@fields -- return an arrayref with no private fields and
184 # fields translated to mapped fields
185  
186 sub filter_fields {
187 my ( $class, $fields ) = @_;
188 my $typeof = ref $fields;
189 my $mapped = $class->CONFIG->{field_map};
190 if ( $typeof eq 'HASH' ) {
191 my %new = ();
192 for ( keys %{ $fields } ) {
193 next if ( /^_/ );
194 if ( $mapped->{ $_ } ) {
195 $new{ $mapped->{ $_ } } = $fields->{ $_ };
196 }
197 else {
198 $new{ $_ } = $fields->{ $_ };
199 }
200 }
201 return \%new;
202 }
203 elsif ( $typeof eq 'ARRAY' ) {
204 return [ map { $mapped->{ $_ } || $_ } grep ! /^_/, @{ $fields } ];
205 }
206 spops_error "Argument must be arrayref or hashref.";
207 }
208  
209  
210 ########################################
211 # FETCHING
212 ########################################
213  
214 # Allows the user to define how fields will be formatted
215 # in a SELECT (date formatting, substrings, etc)
216  
217 sub format_select {
218 my ( $class, $fields, $conf ) = @_;
219 $conf ||= {};
220 my $typeof = ref $fields;
221 unless ( $typeof eq 'ARRAY' ) {
222 spops_error "Fields passed in for referring to format must be ",
223 "an arrayref (Type: $typeof)";
224 }
225 my @return_fields;
226 my $altered = $class->field_alter() || {};
227 foreach my $field ( @{ $fields } ) {
228 push @return_fields, $conf->{ $field } || $altered->{ $field } || $field;
229 }
230 return \@return_fields;
231 }
232  
233  
234 sub fetch {
235 my ( $class, $id, $p ) = @_;
236 $p ||= {};
237  
238 $log->is_debug &&
239 $log->debug( "Trying to fetch an item of $class with ID $id and params ",
240 join( " // ", map { sprintf( "%s -> %s", $_, defined $p->{$_} ? $p->{$_} : '' ) }
241 grep { defined $_ } keys %{ $p } ) );
242  
243 # No ID, no object
244  
245 return undef unless ( defined( $id ) and $id ne '' and $id !~ /^tmp/ );
246  
247 # Security violations bubble up to caller
248  
249 my $level = $p->{security_level};
250 unless ( $p->{skip_security} ) {
251 $level ||= $class->check_action_security({ id => $id,
252 required => SEC_LEVEL_READ });
253 }
254  
255 # Do any actions the class wants before fetching -- note that if
256 # any of the actions returns undef (false), we bail.
257  
258 return undef unless ( $class->pre_fetch_action( { %{ $p }, id => $id } ) );
259  
260 my $obj = undef;
261  
262 # If we were passed the data for an object, go ahead and create
263 # it; if not, check to see if we can whip up a cached object
264  
265 if ( ref $p->{data} eq 'HASH' ) {
266 $obj = $class->new({ %{ $p->{data} }, skip_default_values => 1 });
267 }
268 else {
269 $obj = $class->get_cached_object({ %{ $p }, id => $id });
270 $p->{skip_cache}++; # Set so we don't re-cache it later
271 }
272  
273 unless ( ref $obj eq $class ) {
274 my ( $raw_fields, $select_fields ) = $class->_fetch_select_fields( $p );
275 $log->is_info &&
276 $log->info( "SELECTing: ", join( "//", @{ $select_fields } ) );
277  
278 # Put all the arguments into a hash (so we can reuse them simply
279 # later) and grab the record
280  
281 my %args = (
282 from => [ $class->table_name ],
283 select => $select_fields,
284 where => $class->id_clause( $id, undef, $p ),
285 db => $p->{db},
286 return => 'single',
287 );
288 my $row = eval { $class->db_select( \%args ) };
289 if ( $@ ) {
290 $class->fail_fetch( \%args );
291 die $@;
292 }
293  
294 # If the row isn't found, return nothing; just as if an incorrect
295 # (or nonexistent) ID were passed in
296  
297 return undef unless ( $row );
298  
299 # Note that we pass $p along to the ->new() method, in case
300 # other information was passed in needed by it -- however, we
301 # need to be careful that certain parameters used by this
302 # method (e.g., the optional 'field_alter') is not the same as
303 # a parameter of an object -- THAT would be fun to debug...
304  
305 $obj = $class->new({ id => $id, skip_default_values => 1, %{ $p } });
306 $obj->_fetch_assign_row( $raw_fields, $row, $p );
307 }
308 return $obj->_fetch_post_process( $p, $level );
309 }
310  
311  
312  
313 sub fetch_iterator {
314 my ( $class, $p ) = @_;
315 $log->is_info &&
316 $log->info( "Trying to create an Iterator with: ", Dumper( $p ) );
317 ( $p->{fields}, $p->{select} ) = $class->_construct_group_select( $p );
318 $p->{class} = $class;
319 ( $p->{offset}, $p->{max} ) = SPOPS::Utility->determine_limit( $p->{limit} );
320 unless ( ref $p->{id_list} ) {
321 $p->{sth} = $class->_execute_multiple_record_query( $p );
322 }
323 return SPOPS::Iterator::DBI->new( $p );
324 }
325  
326  
327 # TODO: Put the pre_fetch_action in here
328  
329 sub fetch_group {
330 my ( $class, $p ) = @_;
331 ( $p->{raw_fields}, $p->{select} ) = $class->_construct_group_select( $p );
332 my $sth = $class->_execute_multiple_record_query( $p );
333 my ( $offset, $max ) = SPOPS::Utility->determine_limit( $p->{limit} );
334 my @obj_list = ();
335  
336 my $row_count = 0;
337 ROW:
338 while ( my $row = $sth->fetchrow_arrayref ) {
339 my $obj = $class->new({ skip_default_values => 1 });
340 $obj->_fetch_assign_row( $p->{raw_fields}, $row, $p );
341  
342 next ROW unless ( $obj ); # How could this ever be true?
343  
344 # Check security on the row unless overridden by
345 # 'skip_security'. If the security check fails that's ok, just
346 # skip the row and move on
347  
348 my $sec_level = SEC_LEVEL_WRITE;
349 unless ( $p->{skip_security} ) {
350 $log->is_debug &&
351 $log->debug( "Checking security for [", ref( $obj ), ": ", $obj->id, "]" );
352 $sec_level = eval {
353 $obj->check_action_security({ required => SEC_LEVEL_READ })
354 };
355 if ( $@ ) {
356 $log->is_info &&
357 $log->info( "Security check for object in ",
358 "fetch_group() failed, skipping." );
359 next ROW;
360 }
361 }
362  
363 # Not to the offset yet, so go to the next row but still increment
364 # the counter so we calculate limits properly
365  
366 if ( $offset and ( $row_count < $offset ) ) {
367 $row_count++;
368 next ROW;
369 }
370 last ROW if ( $max and ( $row_count >= $max ) );
371 $row_count++;
372  
373 # If we've made it down to here, we're home free; just call the
374 # post_fetch callback
375  
376 next ROW unless ( $obj->_fetch_post_process( $p, $sec_level ) );
377 push @obj_list, $obj;
378 }
379 $sth->finish;
380 return \@obj_list;
381 }
382  
383  
384 # Take the fields that are just columns and prepend them with the
385 # table name; other columns are assumed to be taken care of
386  
387 sub _construct_group_select {
388 my ( $class, $p ) = @_;
389 my $table_name = $class->table_name;
390 my ( $raw_fields, $select_fields ) = $class->_fetch_select_fields( $p );
391 my @select = ();
392 for ( my $i = 0; $i < scalar @{ $raw_fields }; $i++ ) {
393 if ( $raw_fields->[ $i ] ne $select_fields->[ $i ] ) {
394 push @select, $select_fields->[ $i ];
395 }
396 elsif ( $raw_fields->[ $i ] =~ /^$table_name\./ ) {
397 push @select, $select_fields->[ $i ];
398 }
399 else {
400 push @select, join( '.', $table_name, $raw_fields->[ $i ] );
401 }
402 }
403 return ( $raw_fields, \@select );
404 }
405  
406  
407 # Find the number of objects that would have been returned from a
408 # query, including security. Note that we only fetch the ID field
409 # here...
410  
411 sub fetch_count {
412 my ( $class, $p ) = @_;
413 my $row_count = 0;
414 if ( $p->{skip_security} ) {
415 $p->{select} = [ 'COUNT(*)' ];
416 my $db = $p->{db}
417 || $class->global_datasource_handle( $p->{connect_key} );
418 my $row_count_rec = eval {
419 $class->db_select({ select => [ 'COUNT(*)' ],
420 where => $p->{where},
421 value => $p->{value},
422 from => $class->table_name,
423 return => 'single',
424 db => $db })
425 };
426 $row_count = $row_count_rec->[0];
427 if ( $@ ) {
428 $log->warn( "Caught error running SELECT COUNT(*): $@" );
429 }
430 }
431 else {
432 $p->{select} = [ $class->id_field_select( $p ) ];
433 my $sth = $class->_execute_multiple_record_query( $p );
434 while ( my $row = $sth->fetch ) {
435 eval {
436 $class->check_action_security({ id => $row->[0],
437 required => SEC_LEVEL_READ })
438 };
439 next if ( $@ );
440 $row_count++;
441 }
442 }
443 return $row_count;
444 }
445  
446  
447 sub _execute_multiple_record_query {
448 my ( $class, $p ) = @_;
449 $p->{from} ||= [ $class->table_name ];
450 my %from = map { $_ => 1 } @{ $p->{from} };
451 unless ( $from{ $class->table_name } ) {
452 $from{ $class->table_name }++;
453 }
454 $p->{from} = [ keys %from ];
455 $p->{select} ||= $class->_fetch_select_fields( $p );
456 $p->{return} = 'sth';
457 $p->{db} ||= $class->global_datasource_handle( $p->{connect_key} );
458  
459 # We return a DBI statement handle here so we can scroll through the
460 # rows without assigning them all.
461  
462 return $class->db_select( $p );
463 }
464  
465  
466 # field_list has precedence, then column_group, then 'all'
467  
468 sub _fetch_select_fields {
469 my ( $class, $p ) = @_;
470 my $field_list = $p->{field_list};
471  
472 # If we were given a column group then grab its fields, ensuring
473 # that the ID field is in there as well. If the column group
474 # specified doesn't exist, then the $field_list is empty and will be
475 # filled with all the fields below.
476  
477 if ( ! $field_list and $p->{column_group} ) {
478 $log->is_info &&
479 $log->info( "Trying to retrieve fields for column group ($p->{column_group})" );
480 if ( $p->{column_group} eq '_id_field' ) {
481 $field_list = [ scalar $class->id_field ];
482 }
483 else {
484 my $column_defs = $class->CONFIG->{column_group} || {};
485 $field_list = $column_defs->{ $p->{column_group} };
486 if ( ref $field_list eq 'ARRAY' and scalar @{ $field_list } ) {
487 my %field_hash = map { $_ => 1 } @{ $field_list }, $class->id_field;
488 $field_list = [ keys %field_hash ];
489 }
490 }
491 $log->is_debug &&
492 $log->debug( "Found field list from column group: ", Dumper( $field_list ) );
493 }
494  
495 # If the fields weren't passed in and we're not using a column
496 # group, then use all the fields
497  
498 $field_list ||= $class->field_list;
499 my @alter_field_list = @{ $field_list };
500  
501 # If the user passed in extra fields for the SELECT (for
502 # instances, if 'having' criteria is used) then they always go on
503 # the end of the SELECT
504  
505 if ( $p->{field_extra} ) {
506 push @alter_field_list, ( ref $p->{field_extra} eq 'ARRAY' )
507 ? @{ $p->{field_extra} } : $p->{field_extra};
508 }
509 return ( $field_list,
510 $class->format_select( \@alter_field_list,
511 $p->{field_alter} ) );
512 }
513  
514  
515 # Assign the fetched values to an object. Note that we clear all the
516 # 'loaded' flags first.
517  
518 sub _fetch_assign_row {
519 my ( $self, $fields, $row, $p ) = @_;
520 $log->is_info &&
521 $log->info( "Setting data from row into ", ref( $self ) );
522 $self->clear_all_loaded();
523 foreach my $i ( 0 .. ( scalar @{ $row } - 1 ) ) {
524 $log->is_debug &&
525 $log->debug( sprintf( " %-20s --> %s",
526 $fields->[ $i ],
527 ( defined $row->[ $i ] ) ? substr( $row->[ $i ], 0, 10 ) : '' ) );
528 $self->{ $fields->[ $i ] } = $row->[ $i ];
529 $self->set_loaded( $fields->[ $i ] );
530 }
531 $log->is_info &&
532 $log->info( "Finished setting data into ", ref( $self ), ": ", $self->id );
533 }
534  
535  
536 sub _fetch_post_process {
537 my ( $self, $p, $level ) = @_;
538  
539 # Create an entry for this object in the cache unless either the
540 # class or this call to fetch() doesn't want us to.
541  
542 $self->set_cached_object( $p );
543  
544 # Execute any actions the class (or any parent) wants after
545 # creating the object (see SPOPS.pm)
546  
547 return undef unless ( $self->post_fetch_action( $p ) );
548  
549 # Clear the 'changed' flag
550  
551 $self->clear_change;
552  
553 # Mark this as being a saved object
554  
555 $self->has_save;
556  
557 # Set the security fetched from above into this object
558 # as a temporary property (see SPOPS::Tie for more info
559 # on temporary properties); note that this is set whether
560 # we retrieve a cached copy or not
561  
562 $self->{tmp_security_level} = $level;
563 $log->is_info &&
564 $log->info(
565 ref $self, "(", $self->id, ") : cache set (if available),",
566 "post_fetch_action() done, change flag cleared and save ",
567 "flag set. Security: $level" );
568 return $self;
569 }
570  
571  
572 ########################################
573 # LAZY LOADING
574 ########################################
575  
576 # This is to be passed to SPOPS::Tie as a coderef so it can do a
577 # lazy-load a field that hasn't yet been loaded (fetched) so instead
578 # of having an inner (unnamed) sub doing the work, we just create a
579 # wrapper.
580  
581 sub get_lazy_load_sub {
582 return \&perform_lazy_load;
583 }
584  
585 sub perform_lazy_load {
586 my ( $class, $data, $field ) = @_;
587 unless ( ref $data eq 'HASH' ) {
588 spops_error 'No object data given -- cannot lazy load!';
589 }
590 unless ( $field ) {
591 spops_error 'No field given -- cannot lazy load!';
592 }
593 my $use_field = $class->filter_fields( [ $field ] );
594 if ( scalar @{ $use_field } == 0 || ! $use_field->[0] ) {
595 $log->warn( "Cannot lazy load field [$field] -- it begins ",
596 "with a '_' character and is therefore private" );
597 return undef;
598 }
599 $log->is_debug &&
600 $log->debug( "Performing lazy load for $class -> $use_field->[0]" );
601  
602 my $id_field = $class->id_field;
603 my $id = $data->{ $id_field } || $data->{ lc $id_field };
604  
605 # Use this if we ever need the other data passed in to be normalized
606 # to our fieldnames...
607 # my %proper_field_data = ();
608 # foreach my $field ( @{ $class->field_list } ) {
609 # if ( exists $data->{ $field } ) {
610 # $proper_field_data{ $field } = $data->{ $field };
611 # }
612 # elsif ( exists $data->{ lc $field } ) {
613 # $proper_field_data{ $field } = $data->{ lc $field };
614 # }
615 # }
616 my %args = ( from => [ $class->table_name ],
617 select => [ $use_field->[0] ],
618 where => $class->id_clause( $id ),
619 return => 'single' );
620 my $row = $class->db_select( \%args );
621 return $row->[0];
622 }
623  
624 sub refetch {
625 my ( $self, $fields, $p ) = @_;
626  
627 # Calling with no fields results in refetching all fields
628 $fields = $self->field_list unless ( $fields );
629  
630 # if it's a scalar, make it an arrayref
631 $fields = [ $fields ] unless ( ref $fields );
632 my $actual_fields = $self->filter_fields( $fields );
633  
634 $p->{from} = [ $self->table_name ];
635 $p->{select} = $actual_fields;
636 $p->{where} = $self->id_clause( undef, undef, $p );
637 $p->{return} = 'single';
638 $p->{db} ||= $self->global_datasource_handle( $p->{connect_key} );
639  
640 my $row = $self->db_select( $p );
641  
642 for ( 0 .. ( scalar @{ $row } - 1 ) ) {
643 $self->{ $fields->[ $_ ] } = $row->[ $_ ];
644 }
645 return ( scalar @{ $row } == 1 ) ? $row->[0] : @{ $row };
646 }
647  
648 ########################################
649 # SAVING
650 ########################################
651  
652  
653 sub save {
654 my ( $self, $p ) = @_;
655 $log->is_info &&
656 $log->info( "Trying to save a (", ref $self, ")" );
657  
658 # We can force save() to be an INSERT by passing in a true value
659 # for the is_add parameter; otherwise, we rely on the flag within
660 # SPOPS::Tie to reflect whether an object has been saved or not.
661  
662 my $is_add = ( $p->{is_add} or ! $self->saved );
663  
664 # If this is an update and it hasn't changed, we don't need to do
665 # anything.
666  
667 unless ( $is_add or $self->changed ) {
668 $log->is_info &&
669 $log->info( "This object exists and has not changed. Exiting." );
670 return $self;
671 }
672  
673 # Check security for create/update
674  
675 my $action = ( $is_add ) ? 'create' : 'update';
676 my ( $level );
677 unless ( $p->{skip_security} ) {
678 $level = $self->check_action_security({ required => SEC_LEVEL_WRITE,
679 is_add => $is_add });
680 }
681 $log->is_info &&
682 $log->info( "Security check passed ok. Continuing." );
683  
684 # Callback for objects to do something before they're saved
685  
686 return undef unless ( $self->pre_save_action({ %{ $p },
687 is_add => $is_add }) );
688  
689 # Do not include these fields in the insert/update at all. Allow
690 # user to override even with an empty arrayref.
691  
692 my ( %not_included );
693 if ( $is_add ) {
694 my ( @no_insert_items );
695 if ( $p->{no_insert} ) {
696 @no_insert_items = ( ref $p->{no_insert} eq 'ARRAY' )
697 ? @{ $p->{no_insert} } : ( $p->{no_insert} );
698 }
699 elsif ( my $no_insert_config = $self->no_insert ) {
700 @no_insert_items = keys %{ $no_insert_config };
701 }
702 %not_included = map { $_ => 1 } @no_insert_items;
703 }
704 else {
705 my ( @no_update_items );
706 if ( $p->{no_update} ) {
707 @no_update_items = ( ref $p->{no_update} eq 'ARRAY' )
708 ? @{ $p->{no_update} } : ( $p->{no_update} );
709 }
710 elsif ( my $no_update_config = $self->no_update ) {
711 @no_update_items = keys %{ $no_update_config };
712 }
713 %not_included = map { $_ => 1 } @no_update_items;
714 }
715  
716 # Do not include these fields in the insert/update if they're not defined
717 # (note that this includes blank/empty)
718  
719 $p->{skip_undef} ||= [];
720 my $skip_undef = $self->skip_undef || {};
721 $skip_undef->{ $_ }++ for ( @{ $p->{skip_undef} } );
722  
723 $p->{field} = [];
724 $p->{value} = [];
725  
726 FIELD:
727 foreach my $field ( keys %{ $self->field } ) {
728 next FIELD if ( $not_included{ $field } );
729 my $value = $self->{ $field };
730 next FIELD if ( ! defined $value and $skip_undef->{ $field } );
731 push @{ $p->{field} }, $field;
732 push @{ $p->{value} }, $value;
733 }
734  
735 # Do the insert/update based on whether the object is new; don't
736 # catch the die() that might be thrown -- let that percolate
737  
738 if ( $is_add ) { $self->_save_insert( $p, \%not_included ) }
739 else { $self->_save_update( $p, \%not_included ) }
740  
741 # Set the 'has_save' flag so that any saved changes to the object
742 # in the post_save will be an update rather than another insert;
743 # clear the changed fields for the same reason
744  
745 $self->has_save;
746 $self->clear_change;
747  
748 # Do any actions that need to happen after you save the object
749  
750 return undef unless ( $self->post_save_action({ %{ $p },
751 is_add => $is_add }) );
752  
753 # Save the newly-created/updated object to the cache
754  
755 $self->set_cached_object( $p );
756  
757 # Note the action that we've just taken (opportunity for subclasses)
758  
759 unless ( $p->{skip_log} ) {
760 $self->log_action( $action, scalar $self->id );
761 }
762  
763 return $self;
764 }
765  
766 # Called by _save_insert()
767  
768 sub pre_fetch_id { return undef }
769 sub post_fetch_id { return undef }
770  
771 sub _save_insert {
772 my ( $self, $p, $not_inserted ) = @_;
773 $p ||= {};
774 $log->is_info &&
775 $log->info( "Treating the save as an INSERT ",
776 "with fields [", join( ', ', @{ $p->{field} } ), "]" );
777  
778 my $db = $p->{db} || $self->global_datasource_handle( $p->{connect_key} );
779  
780 # Ability to get the ID you want before the insert statement is
781 # executed. If something is returned, push the value plus the ID
782 # field onto the appropriate stack; if ID is already defined in
783 # the object use that in preference to the fetched value
784  
785 my ( $pre_id, $do_quote ) = $self->pre_fetch_id( { %{ $p }, db => $db } );
786 if ( $pre_id ) {
787 my $use_id = $self->id || $pre_id;
788 $self->id( $use_id );
789 push @{ $p->{field} }, $self->id_field;
790 push @{ $p->{value} }, $self->id;
791 $p->{no_quote}{ $self->id_field } = 1 unless ( $do_quote );
792 $log->is_info &&
793 $log->info( "Retrieved ID before insert: $pre_id, using object ID $use_id" );
794 }
795  
796 $self->apply_insert_alter( $p );
797  
798 # Do the insert; ask DB to return the statement handle
799 # if we need it for getting the just-inserted ID; note that
800 # both 'field' and 'value' are in $p, so we do not need to
801 # specify them in the %args
802 #
803 # Note also that we pass \%p in just in case we want to tell
804 # db_insert not to quote anything from the original call.
805  
806 my %args = ( table => $self->table_name,
807 return_sth => 1,
808 db => $db,
809 %{ $p } );
810 my $sth = $self->db_insert( \%args );
811 if ( $@ ) {
812 $log->warn( "Insert failed! Args: ", Dumper( \%args ), $@ );
813 $self->fail_save( \%args );
814 die $@;
815 }
816  
817 # Ability to get the ID from the statement just inserted
818 # via an overridden subclass method; if something is
819 # returned, set the ID in the object.
820  
821 my $post_id = $self->post_fetch_id( { %{ $p },
822 db => $db,
823 statement => $sth } );
824 if ( $post_id ) {
825 $self->id( $post_id );
826 $log->is_info &&
827 $log->info( "ID fetched after insert: $post_id" );
828 }
829  
830 # Here we actually re-fetch any new information from the database
831 # since on an insert any DEFAULT values might have kicked in. The config
832 # of the object should include a list called 'sql_defaults' that have
833 # all the fields defined something like this:
834 # expired char(3) default 'no'
835 # so that we can match up what's in the db with the object. We
836 # also use any values specified in the class or object 'no_insert'
837  
838 unless ( $p->{no_sync} or $self->no_save_sync ) {
839 my %fill_in_uniq = map { $_ => 1 } ( @{ $self->CONFIG->{sql_defaults} },
840 keys %{ $not_inserted } );
841  
842 # Get rid of the ID field, since it's a) defined in the
843 # object, b) pre-fetched or c) post-fetched; if it's none of
844 # the three then that makes it difficult to get the default
845 # values :-)
846  
847 delete $fill_in_uniq{ $self->id_field };
848  
849 my @fill_in_fields = grep { $_ } sort keys %fill_in_uniq;
850 if ( scalar @fill_in_fields ) {
851 $log->is_info &&
852 $log->info( "Fetching defaults for fields ",
853 join( ' // ', @fill_in_fields ), " after insert." );
854 my $row = eval { $self->db_select({
855 from => [ $self->table_name ],
856 select => \@fill_in_fields,
857 where => $self->id_clause( undef, undef, $p ),
858 db => $p->{db},
859 return => 'single' }) };
860 # Even though there was an error, we probably want to continue
861 # processing... I'm ambivalent about this.
862  
863 if ( $@ ) {
864 $log->warn( "Cannot refetch row: $@" );
865 }
866 else {
867 for ( my $i = 0; $i < scalar @fill_in_fields; $i++ ) {
868 $log->is_debug &&
869 $log->debug( "Setting $fill_in_fields[$i] to ",
870 ( defined $row->[$i] ) ? $row->[$i] : '' );
871 $self->{ $fill_in_fields[ $i ] } = $row->[ $i ];
872 }
873 }
874 }
875 }
876  
877 # Now create the initial security for this object unless
878 # we have requested to skip it
879  
880 # TODO: Check this -- should skip_security only mean that we don't
881 # want to check security for saving? Should it mean we skip it
882 # ENTIRELY, as if it's not there? (I suspect not...)
883 #
884 # NOTE: We say in the docs that we don't check security for
885 # inserts (it's application-specific), so 'skip_security' means we
886 # don't want to set security
887  
888 unless ( $p->{skip_security} ) {
889 $self->create_initial_security({ object_id => scalar $self->id });
890 }
891 return 1;
892 }
893  
894  
895 # See if we're supposed to modify any of the given values with the
896 # 'insert_alter' configuration
897  
898 sub apply_insert_alter {
899 my ( $self, $p ) = @_;
900  
901 my $insert_alter = $self->insert_alter || $p->{insert_alter};
902 return unless ( ref $insert_alter eq 'HASH' and keys %{ $insert_alter } );
903  
904 my $num_fields = scalar @{ $p->{value} };
905 for ( my $i = 0; $i < $num_fields; $i++ ) {
906 my $field_name = $p->{field}[ $i ];
907 next unless ( $insert_alter->{ lc $field_name } );
908 $log->is_info &&
909 $log->info(
910 "Setting 'insert_alter' for [$field_name]",
911 "defined as [", $insert_alter->{ lc $field_name }, "]",
912 "with value [$p->{value}[ $i ]]" );
913 $p->{value}[ $i ] = sprintf( $insert_alter->{ lc $field_name },
914 $p->{value}[ $i ] );
915 $p->{no_quote}{ $field_name } = 1;
916 }
917 }
918  
919  
920 sub _save_update {
921 my ( $self, $p ) = @_;
922  
923 # If the ID of the object is changing, we still need to be able to
924 # refer to the row with its old ID; allow the user to pass in the old
925 # ID in this case so we can create the ID clause with it
926  
927 my $id_clause = ( $p->{use_id} )
928 ? $self->id_clause( $p->{use_id}, undef, $p )
929 : $self->id_clause( undef, undef, $p );
930 $log->is_info &&
931 $log->info( "Processing save as UPDATE with ",
932 "clause [$id_clause] and fields [",
933 join( ', ', @{ $p->{field} } ), "]" );
934  
935 # Note that the 'field' and 'value' parameters are in $p and
936 # exist when the hashref is expanded into %args
937  
938 my %args = ( where => $id_clause,
939 table => $self->table_name,
940 %{ $p } );
941 my $rv = eval { $self->db_update( \%args ); };
942 if ( $@ ) {
943 $log->warn( "Update failed! Args: ", Dumper( \%args ), $@ );
944 $self->fail_save( \%args );
945 die $@;
946 }
947 return 1;
948 }
949  
950  
951 sub field_update {
952 my ( $item, $fields, $p ) = @_;
953 unless ( $fields ) {
954 spops_error "You must pass some sort of field to update!";
955 }
956  
957 # This can be called as a class method or as an object method...
958  
959 my $is_object = ref $item;
960  
961 if ( ! $is_object and ! $p->{where} ) {
962 spops_error "If called as a class method, you must specify filtering ",
963 "criteria in the 'where' clause";
964 }
965 if ( ! $is_object and ! ref $fields eq 'HASH' ) {
966 spops_error "If called as a class method, you must specify fields and ",
967 "values as a hashref for the first argument.";
968 }
969  
970 my ( %holding, %old_values );
971  
972 # convert to hashref ...
973 if ( ref $fields ) {
974 if (ref $fields eq 'ARRAY') { ## ... from arrayref
975 for ( @{ $fields } ) {
976 $holding{ $_ } = $item->{ $_ };
977 }
978 }
979 else { ## ... no conversion
980 %holding = %{ $fields };
981 }
982 }
983 else { # ... from scalar
984 $holding{ $fields } = $item->{ $fields };
985 }
986  
987 # translate field mapping if available, and ensure that no private
988 # fields are used in the update
989  
990 my $new = $item->filter_fields( \%holding );
991  
992 # set up WHERE clause for 'if_match' option
993  
994 if ( $p->{if_match} && ! $p->{where} ) {
995  
996 # take match values from $p->{if_match} href
997 if ( ref $p->{if_match} eq 'HASH' ) {
998 for ( keys %{ $p->{if_match} } ) {
999 $old_values{ $_ } = $p->{if_match}{ $_ };
1000 }
1001 }
1002  
1003 # take match values from $item
1004 else {
1005 for ( keys %{ $new } ) {
1006 $old_values{ $_ } = $item->{ $_ };
1007 }
1008 }
1009  
1010 my @where = ();
1011 my $type_info = $item->db_discover_types( $item->table_name, $p );
1012 while ( my ( $k, $v ) = each %old_values ) {
1013 $v = $item->sql_quote( $v, $type_info->get_type( $k ), $p->{db} );
1014 push @where, " $k = $v ";
1015 }
1016 $p->{where} = join( ' AND ', @where );
1017 }
1018  
1019 if ( $is_object ) {
1020 $p->{where} = ( $p->{where} )
1021 ? join( ' AND ', $item->id_clause( undef, undef, $p ), $p->{where} )
1022 : $item->id_clause( undef, undef, $p );
1023 }
1024 for ( keys %{ $new } ) {
1025 push @{ $p->{field} }, $_;
1026 push @{ $p->{value} }, $new->{ $_ };
1027 }
1028 $p->{table} = $item->table_name;
1029 $p->{db} ||= $item->global_datasource_handle( $p->{connect_key} );
1030  
1031 my $rv = ( $item->db_update( $p ) != 0 );
1032  
1033 # update values in object if db_update was successful and we
1034 # passed in new values (vs. from object).
1035  
1036 if ( $rv and $is_object and ref $fields eq 'HASH' ) {
1037 for ( keys %{ $new } ) {
1038 $item->{ $_ } = $new->{ $_ };
1039 }
1040 }
1041 return $rv;
1042 }
1043  
1044  
1045 ########################################
1046 # REMOVING
1047 ########################################
1048  
1049 sub remove {
1050 my ( $self, $p ) = @_;
1051  
1052 # Don't remove it unless it's been saved already
1053  
1054 return undef unless ( $self->is_saved );
1055  
1056 my $level = SEC_LEVEL_WRITE;
1057 unless ( $p->{skip_security} ) {
1058 $level = $self->check_action_security({ required => SEC_LEVEL_WRITE });
1059 }
1060  
1061 $log->is_info &&
1062 $log->info( "Security check passed ok. Continuing." );
1063  
1064 # Allow members to perform an action before getting removed
1065  
1066 return undef unless ( $self->pre_remove_action( $p ) );
1067  
1068 # Do the removal, building the where clause if necessary
1069  
1070 my $where = $p->{where} || $self->id_clause( undef, undef, $p );
1071 my $id = $self->id;
1072 my $rv = eval { $self->db_delete({
1073 table => $self->table_name,
1074 where => $where,
1075 value => $p->{value},
1076 db => $p->{db} }) };
1077  
1078 if ( $@ ) {
1079 $self->fail_remove;
1080 die $@
1081 }
1082  
1083 # Otherwise...
1084 # ... remove this item from the cache
1085  
1086 if ( $self->use_cache( $p ) ) {
1087 $self->global_cache->clear({ data => $self });
1088 }
1089  
1090 # ... execute any actions after a successful removal
1091  
1092 return undef unless ( $self->post_remove_action( $p ) );
1093  
1094 # ... and log the deletion
1095  
1096 $self->log_action( 'delete', $id ) unless ( $p->{skip_log} );
1097  
1098 # Clear out the 'changed' and 'saved' flags
1099  
1100 $self->clear_change;
1101 $self->clear_save;
1102 return 1;
1103 }
1104  
1105 1;
1106  
1107 __END__