Carbon.pm untested

filter: Statementstmt 0.0% 0 / 1248 Branchbran 0.0% 0 / 544 Conditioncond 0.0% 0 / 441 MC/DCmcdc 0.0% 0 / 261 Subroutinesub 0.0% 0 / 96 Podpod 0.0% 0 / 68 totaltotal 0.0% 0 / 2658 CC 273 SCAR 56.4
CC
273
Cov
0%
format_conditions
930.0
new
870.0
modify
812.0
CRAP 282.6
1 # BingoX::Carbon
2 # -----------------
3 # $Revision: 2.36 $
4 # $Date: 2001/12/20 19:22:38 $
5 # ---------------------------------------------------------
6  
7 =head1 NAME
8  
9 BingoX::Carbon - An object oriented database abstraction superclass
10  
11 =head1 SYNOPSIS
12  
13 use BingoX::Carbon ( [ ':cache_all', ] [ ':no_dynmeth' ] );
14  
15 # $BR - Blessed Reference
16 # $SV - Scalar Value
17 # @AV - Array Value
18 # $HR - Hash Ref
19 # $AR - Array Ref
20 # $SR - Stream Ref
21  
22 # $proto - BingoX::Carbon object OR sub-class
23 # $object - BingoX::Carbon object
24  
25 CONSTRUCTORS
26  
27 $BR = $proto->new( $dbh, \%data );
28 $BR = $proto->get( $dbh, $ID );
29 $BR = $object->duplicate;
30  
31 STREAM CONSTRUCTOR METHODS
32  
33 $SR = $proto->stream_obj( $dbh, \%params, [\@fields,] [\@sort] );
34 $SR = $proto->stream_hash( $dbh, \%params, [\@fields,] [\@sort] );
35 $SR = $proto->stream_array( $dbh, \%params, [\@fields,] [\@sort] );
36  
37 LIST CONSTRUCTOR METHODS
38  
39 $AR = $proto->list_obj( $dbh, \%params, [\@fields,] [\@sort] );
40 $AR = $proto->list_hash( $dbh, \%params, [\@fields,] [\@sort] );
41 $AR = $proto->list_array( $dbh, \%params, [\@fields,] [\@sort] );
42  
43 RELATION METHODS
44  
45 $SV = $object->relate( $fobject | \@fobjects | (\@fids, $fclass, $fcolumn) );
46 $SV = $object->unrelate( $fobject | \@fobjects | (\@fids, $fclass, $fcolumn) );
47 $SV = $object->isrelated( $fobject );
48 $AR = $object->list_related( $fclass [, \@fields] [, \@sort] );
49 $SR = $object->stream_related( $fclass [, \@fields] [, \@sort] );
50 $SV = $proto->unrelate_all( $fclass )
51  
52 DATABASE MANIUPLATION METHODS
53  
54 $BR = $object->modify( \%new_data );
55 $SV = $proto->modify( $dbh, \%params, \%new_data );
56 $SV = $object->rm;
57 $SV = $proto->rm( $dbh, \%params );
58  
59 CLASS DATA ACCESSOR METHODS
60  
61 $SV = $proto->table( $dbh );
62 $SV = $proto->identity( $dbh );
63 $AR = $proto->primary_keys( $dbh );
64 $HR = $proto->def_fields( $dbh );
65 $AR = $proto->field_order( $dbh );
66 $SV = $proto->identity( $dbh );
67 $SV = $proto->sequence( $dbh );
68 $SV = $proto->seqcol( $dbh );
69  
70 DATABASE/SQL METHODS
71  
72 $SR = $proto->sql_select( $dbh );
73 @AV = $proto->format_select( $dbh, \%params, \@fields, \@sort [,$alias] );
74 @AV = $proto->format_conditions( $dbh, \%params [,$alias] );
75  
76 =head1 REQUIRES
77  
78 DBI, Carp, strict, Date::Parse, BingoX::Time
79  
80 =head1 EXPORTS
81  
82 Nothing
83  
84 =head1 DESCRIPTION
85  
86 BingoX::Carbon provides a database abstraction in which each row of data is represented
87 by an object blessed into a class representing the table. Each Carbon Class represents
88 a table or view in the database. The database and classes are described by variables
89 in said classes. After Carbon classes have been set up to represent tables in a
90 database, creating, retrieving and modifying data is simply a matter of method calls
91 against Carbon objects and classes. For a tutorial on setting up a Carbon project,
92 see L<carbontut> packaged with BingoX.
93  
94 =head1 DATABASE SUPPORT
95  
96 Currently, Carbon has been tested and is known to work with B<Sybase>, B<Oracle>, and
97 B<PostgreSQL>. Carbon should with minimal change be able to support many other databases.
98  
99 Due to Carbon's extensive use of transactions, it will not currently work with database engines that
100 do not support transactions - most notably MySQL.
101  
102 We tried to keep Carbon/BingoX as database agnostic as possible, but had to put some database specific
103 code to support such things as Sybase's Indentity columns, Oracles Sequences, the different date formats,
104 and Oracles use of all caps.
105  
106 If you would like to help Carbon support MySQL or other database engines, feel free to send patches
107 or contact us for help.
108  
109 =head1 CLASS VARIABLES
110  
111 =head2 REQUIRED
112  
113 Classes that inherit from BingoX::Carbon must have the following class variables:
114  
115 =over 4
116  
117 =item * $table
118  
119 A scalar that contains the table name the class represents.
120  
121 =item * @primary_keys
122  
123 An array containing the primary key colulmn names.
124  
125 =item * @field_order
126  
127 An array containing all the table's column names in perferred order of use.
128 Was formerly used for order of display, but has since been replaced by the
129 BingoX Display namespace modules.
130  
131 =back
132  
133 =head2 OPTIONAL
134  
135 =over 4
136  
137 =item * $identity
138  
139 A scalar that contains the name of the column which is a Sybase IDENTITY column.
140 There can be only one identity column per table.
141  
142 =item * $seqcol
143  
144 A scalar that contains the name of the column which should be populated by a sequence.
145  
146 =item * $sequence
147  
148 A scalar that contains the name of the sequence object in the database which new()
149 will poll to determine what to populate $seqcol with.
150  
151 =item * %relations
152  
153 A hash containing relational data. The keys to the hash are class names of
154 foreign objects. The values are class names that represents the referential class
155 for any object blessed in the class of the key.
156  
157 e.g. :
158  
159 %relations = ( ClassOne => 'ClassOne_ClassTwo' );
160  
161 =item * %foreign_keys
162  
163 A hash containing relational data present in referential classes. The keys to the hash
164 are class names representing the classes referred to. The values are the names of the
165 columns which contain the foreign key to the referred table.
166  
167 e.g. :
168  
169 %foreign_keys = ( ClassOne => 'one', ClassTwo => 'two' );
170  
171 =item * $title_field
172  
173 The column which should be used to display the object in a list.
174  
175 =item * %content_fields
176  
177 This hash lets Carbon classes have virtual columns to hold large amounts of
178 content data. The keys of this hash are virtual colum names whose values
179 are Carbon classnames that handle those content columns.
180  
181 e.g. :
182  
183 %content_fields = ( content => 'Class::Data::Content' );
184  
185 =item * %date_fields
186  
187 The keys of this hash are column names from the fieldorder array that have a
188 database type of date. Putting those columns in here make sure that you will
189 get Unix time when asking for those columns.
190  
191 e.g. :
192  
193 %date_fields = ( showdate => 1 );
194  
195 =back
196  
197 =head1 METHODS
198  
199 =head2 CONSTRUCTORS AND STATIC METHODS
200  
201 =over 4
202  
203 =cut
204  
205 package BingoX::Carbon;
206  
207 use DBI;
208 use Carp qw(:DEFAULT cluck);
209 use strict;
210 use Date::Parse;
211 use BingoX::Time;
212 use vars qw($AUTOLOAD $debug);
213  
214 BEGIN {
215 $BingoX::Carbon::REVISION = (qw$Revision: 2.36 $)[-1];
216 $BingoX::Carbon::VERSION = '1.92';
217  
218 $debug = undef;
219  
220 if ($debug) {
221 require Data::Dumper;
222 }
223 }
224  
225 =item C<import> ( )
226  
227 Called from 'use BingoX::Carbon;'
228  
229 Possible arguments are as follows:
230  
231 =back
232  
233 =over 4
234  
235 =item * :cache_all
236  
237 flag will put all data into the object at time of construction.
238 The default action is to store only primary_keys in the object
239 until data is needed, but this approach proved very inefficient
240 in certain situations.
241  
242 =item * :no_dynmeth
243  
244 flag will stop the creation of methods in calling class for all
245 the elements of the class' fieldorder.
246  
247 =item * :full_dynmeth
248  
249 flag will avoid using 'forwarder' methods and instead use full
250 dynamic methods - each with it's own code resembling AUTOLOAD.
251 By default, forwarder methods are used and all call
252 _old_school_autoload
253  
254 Any other element, not starting with the ':' character will be interpreted
255 as a method name with which to create an access method in the calling class.
256  
257 =back
258  
259 =cut
260 sub import {
261 my $self = shift;
262 my $myclass = ref($self) || $self;
263 my $class = (caller)[0];
264 my @args = @_;
265 warn "BingoX::Carbon: import: class=$class: @args myclass=$myclass" if ($debug);
266  
267 ## Initialize special content and date field methods
268 no strict 'refs';
269 @{"${class}::ISA"} = ( __PACKAGE__ ) unless ($class->isa( __PACKAGE__ ));
270 BingoX::Carbon::_content_meth_init( $class );
271 BingoX::Carbon::_date_meth_init( $class );
272  
273 my $no_dynmeth = 0;
274 my $full_dynmeth = 0;
275 ## BingoX::Carbon methods are called as functions, passing $class (caller[0]). ##
276 ## This is needed because import is called before the $class @ISA is set. ##
277 ## Therefore, calling $class->method wouldn't work because $class doesn't inherit ##
278 ## from anything yet! ##
279 my @fields = ( );
280 foreach (@args) {
281 if (substr($_, 0, 1) eq ':') {
282 if ($_ eq ':cache_all') {
283 $BingoX::Carbon::cache_all{ $class }++;
284 } elsif ($_ eq ':full_dynmeth') {
285 $full_dynmeth = 1;
286 } elsif ($_ eq ':no_dynmeth') {
287 $no_dynmeth = 1;
288 &BingoX::Carbon::_create_access_method( $class, 'AUTOLOAD' );
289 }
290 } else {
291 warn "explicitly creating method $_ in class $class" if ($debug);
292 # &BingoX::Carbon::_create_access_method( $class, $_ );
293 # &BingoX::Carbon::_create_forwarder_method( $class, $_ );
294 push(@fields, $_);
295  
296 }
297 } # END foreach block
298  
299 push(@fields, @{ &BingoX::Carbon::fieldorder( $class ) || [] }) unless ($no_dynmeth);
300 foreach my $name (@fields) {
301 if ($full_dynmeth) {
302 &BingoX::Carbon::_create_access_method( $class, $name );
303 } else {
304 &BingoX::Carbon::_create_forwarder_method( $class, $name );
305 }
306 }
307 } # END sub import
308  
309  
310 =over 4
311  
312 =item C<new> ( [ $dbh, ] \%data )
313  
314 Constructs a new object with the data in the hashref passed to it.
315 You must supply a value for all primary key columns, unless the database
316 provides a method for autogenerating this value. If an ID isn't specified
317 the ID will be the next number in the database sequence :
318  
319 Sybase
320  
321 Class data $identity contains name of column which is a Sybase IDENTITY.
322 The IDENTITY field will be omitted from the insert statement so Sybase can autogenerate it.
323 New will then select @@identity to retreive the result of triggering IDENTITY.
324 Because it does this within a single statement, it will get the correct value.
325  
326 Oracle, Postgres
327  
328 Class data $sequence contains name of Sequence object in database, and
329 class data $seqcol contains name of column where BingoX::Carbon will insert the value
330 returned by triggering $sequence.
331  
332 =cut
333 sub new {
334 my $self = shift;
335 my $class = ref($self) || $self;
336 my $dbh = ref($self) ? $self->dbh : shift;
337 ref($dbh) || return $self->error_handler("In ${class}::new() called without dbh object");
338 my $data = shift;
339 ref($data) || return $self->error_handler("In ${class}::new() called without data hash");
340 my ($sth, @insert_fields, @insert_values); # used to hold data for INSERT
341 $self = { }; # initialize self
342  
343 ## Get data out of data hash which should go in a content table. ##
344 my %content;
345 if (my $contentfields = $class->contentfields) {
346 foreach (keys %$contentfields) {
347 $content{$_} = delete $data->{$_};
348 }
349 }
350  
351 ## Get data out of data hash which are date fields. ##
352 if (my $datefields = $class->datefields) {
353 foreach (keys %$datefields) {
354 $data->{$_} = $data->{$_}->time2str( $class->date_format ) if (ref $data->{$_});
355 warn "datefield $_ ==> " . $data->{$_} . "\n" if ($debug > 1);
356 }
357 }
358  
359 ## Get data out of data hash which is for a related class. ##
360 my %selected;
361 if ($class->relations) {
362 warn "In class->relations == \n" . Data::Dumper::Dumper( $data ) if ($debug > 1);
363 foreach (keys %{ $class->relations }) {
364 warn "relations $_ ==> [$_]\n" if ($debug > 1);
365 $selected{$_} = { map{ $_ => 1 } @{ delete $data->{$_} } } if ($data->{$_});
366 }
367 }
368  
369 ## prepare data to be inserted and build object ##
370 foreach (keys %$data) {
371 ## make sure field exists in class deffields ##
372 next if (/^_/);
373 exists($class->deffields->{$_}) || return $class->error_handler("In ${class}::new : $_ doesn't exist in deffields [$class]\n");
374 my $value = $self->{$_} = $data->{$_};
375 push(@insert_fields, (defined $value ? $_ : ( )));
376 push(@insert_values, (defined $value ? $value : ( )));
377 }
378  
379 local $dbh->{'AutoCommit'} = 0 if (%selected || %content); # BEGIN TRANSACTION (if needed)
380 eval {
381 local $dbh->{'RaiseError'} = 1;
382 ## If ID not specified, get next ID from sequence ##
383 foreach (@{ $class->primary_keys || [ ] }) {
384 warn "Primary Key: $_... " if ($debug);
385 next if ((defined $self->{$_}) || ($class->identity eq $_));
386 my $sql;
387 if (($class->seqcol eq $_) && defined(my $sequence = $class->sequence)) {
388 ## get the ID from the database sequence ##
389 if ($dbh->{'Driver'}->{'Name'} eq 'Oracle') {
390 $sql = 'SELECT ' . $sequence . '.nextval FROM DUAL';
391 } elsif ($dbh->{'Driver'}->{'Name'} eq 'Pg') {
392 $sql = "SELECT nextval('" . $sequence . "')";
393 } else {
394 die "don't know how to read sequences for database driver $dbh->{'Driver'}->{'Name'}\n";
395 }
396 } else {
397 die "no data supplied for primary key $_\n";
398 }
399 $sth = $dbh->prepare( $sql ) || croak "prepare\n$sql;\n" . $dbh->errstr . "\n\n";
400 $sth->execute || croak "execute\n$sql;\n" . $sth->errstr . "\n\n";
401 $self->{$_} = $sth->fetch->[0] || croak "fetch\n$sql;\n" . $sth->errstr . "\n\n";
402 $sth->finish();
403 push(@insert_fields, $_);
404 push(@insert_values, $self->{$_});
405 }
406  
407 ## make INSERT statement ##
408 my $INSERT = "INSERT INTO " . $class->table;
409 $INSERT .= ' (' . join(',', @insert_fields). ')' if (@insert_fields);
410 $INSERT .= ' VALUES (' . join(',', ('?') x scalar(@insert_values)) . ')';
411 $INSERT .= ' SELECT @@identity' if (($dbh->{'Driver'}->{'Name'} eq 'Sybase') && $class->identity && !defined($self->{$class->identity})); # SYBASE IDENTITY support
412 warn "$class->new:\t\t\t\"$INSERT\" [ @insert_values ]\n" if ($debug);
413  
414 ## INSERT data or freak out! ##
415 $sth = $dbh->prepare( $INSERT ) || croak "prepare\n$INSERT;\n" . $dbh->errstr . "\n\n";
416 $sth->execute( @insert_values ) || croak "execute\n$INSERT\nwith VALUES: " . join(',', @insert_values) . "\n" . $sth->errstr . "\n\n";
417  
418 ## GET SYBASE IDENTITY COLUMN VALUE ##
419 if (($dbh->{'Driver'}->{'Name'} eq 'Sybase') && $class->identity && !defined($self->{$class->identity})) {
420 $self->{ $class->identity } = $sth->fetch->[0];
421 die "Sybase Identity failed\n" unless (defined($self->{$class->identity}));
422 }
423 $sth->finish;
424  
425 ## bless object ##
426 $self->{'_dbh'} = $dbh;
427 bless $self, $class;
428  
429 ## Start Relation Code ##
430 if (%selected) {
431 foreach my $relclass (keys %selected) { # Itterates through classnames in $selected
432 my %local_selected = %{ $selected{ $relclass } }; # puts cpkeys of $_ classname
433  
434 ## Here we relate all newly related items (we also might ##
435 ## be related objects which are already related, but it won't mind) ##
436 foreach my $cpk (keys %local_selected) { # goes through all newly related cpkeys
437 my %params;
438 @params{ @{ $relclass->primary_keys } } = split($self->pkd,$cpk);
439 $self->relate( $relclass->get( $dbh, \%params ) );
440 }
441 }
442 }
443  
444 ## Save content data. ##
445 foreach (keys %content) {
446 $self->$_( $content{$_} ) || die "Could not add content field $_";
447 }
448 }; # END of eval
449  
450 ## Caught exception, ROLLBACK TRANSACTION ##
451 if ($@) {
452 $class->errors( $@ );
453 $dbh->rollback if (%selected || %content);
454 return $class->error_handler("In ${class}::new - $@")
455 }
456 warn 'in new self ==> ' . Data::Dumper::Dumper( $self ) if ($debug);
457 $dbh->commit if (%selected || %content); ## No errors ## COMMIT TRANSACTION ##
458  
459 return $self;
460 } # END sub new
461  
462 =item C<get> ( [ $dbh, ] \%params )
463  
464 Constructs an object from the database using the parameters passed.
465 NOTE: Passing one scalar variable as an ID to get has been deprecated!
466 get will assume the parameters { $self->primary_keys->[0] => shift() }
467 if a scalar is passed in place of \%params. Future version of BingoX::Carbon
468 will not support this!
469  
470 For instructions on the format of \%params, see L<"item_format_conditions">.
471  
472 =cut
473 sub get {
474 my $self = shift;
475 my $class = ref($self) || $self;
476 my $dbh = ref($self) ? $self->dbh : shift;
477 my $params = shift || return undef;
478 unless (ref($params) eq 'HASH') {
479 $params = { $self->primary_keys->[0] => $params };
480 }
481  
482 my $code = $class->stream_obj( $dbh, $params, @_ ) || return undef;
483 my $obj = $code->();
484 $code->(1); # finish
485 undef $code;
486 return $obj;
487 } # END sub get
488  
489  
490 =item C<modify> ( \%new_data )
491  
492 Object method:
493  
494 Modify instance data with \%new_data and sync with database.
495 Returns $self if success, undef if failure.
496  
497 =item C<modify> ( $dbh, \%params, \%new_data )
498  
499 Static method:
500  
501 Modify all rows satisfied by conditions in \%params with \%new_data
502 Returns true if success, undef if failure.
503  
504 N.B. - You CAN NOT modify non-columnar information (i.e., relationships or extra-tabular "content" fields)
505 for multiple rows simultaneously.
506  
507 For instructions on the format of \%params, see L<"item_format_conditions">.
508  
509 =cut
510 sub modify {
511 my $self = shift;
512 my $class = ref($self) || $self;
513 my $dbh = ref($self) ? $self->dbh : shift;
514 ref($dbh) || return $class->error_handler("In ${class}::modify() called without dbh object");
515 my ($data, $params);
516  
517 return undef unless ref($dbh);
518 #### Object method section
519 if (ref $self) {
520 $data = shift || return undef;
521 return undef unless (ref($data) eq 'HASH');
522 ## Use values of primary keys as conditional parameters (to effect this row only) ##
523 $params = { map { $_ => $self->$_() } @{ $self->primary_keys } };
524  
525 ## Static method section ##
526 } else {
527 $params = shift;
528 $data = shift;
529 ref($data) || return $class->error_handler("In ${class}::modify() called without data hash");
530 ## Must have all three of these, and $data must contain something ##
531 return undef unless (((ref($params) eq 'HASH') || (ref($params) eq 'ARRAY')) && (ref($data) eq 'HASH') && %$data);
532 }
533  
534 ## Start Content Fields Code ##
535 my %content;
536 if (my $contentfields = $class->contentfields) {
537 foreach (keys %$contentfields) {
538 $content{$_} = delete $data->{$_};
539 warn "contentfield $_ ==> " . $content{$_} . "\n" if ($debug > 1);
540 }
541 (%content && !ref($self)) && return $class->error_handler("In ${class}::modify() - static (group) modify called specifying special content fields");
542 }
543 ## End Content Fields Code ##
544  
545 ## Start Date Fields Code ##
546 if (my $datefields = $class->datefields) {
547 foreach (keys %$datefields) {
548 $data->{$_} = $data->{$_}->time2str( $self->date_format ) if (ref $data->{$_});
549 warn "datefield $_ ==> " . $data->{$_} . "\n" if ($debug > 1);
550 }
551 }
552 ## End Date Fields Code ##
553  
554 ## Start Relation Code ##
555 my %selected;
556 if (ref $class->relations) {
557 foreach (keys %{ $class->relations }) {
558 $selected{$_} = { map{ $_ => 1 } @{ delete $data->{$_} } } if ($data->{$_});
559 }
560 (%selected && !ref($self)) && return $class->error_handler("In ${class}::modify() - static (group) modify called specifying relationships");
561 }
562 ## End Relation Code ##
563  
564 local $dbh->{'AutoCommit'} = 0 if (%selected || %content); # BEGIN TRANSACTION (if needed)
565 eval {
566 local $dbh->{'RaiseError'} = 1;
567 if (keys %$data) {
568 my (@update_fields, @update_values);
569 foreach (keys %{ $data }) {
570 next if ({map { $_ => 1 } @{ $self->primary_keys || []}}->{$_});
571 exists($class->deffields->{$_}) || croak "method $_ doesn't exist in \%${class}::deffields\n";
572  
573 my $value = $data->{$_};
574 $self->{$_} = $value if (ref $self);
575  
576 if (index($value, '##') != -1) {
577 while ($value =~ s/##(.+?)##/?/o) {
578 push(@update_values, $1);
579 }
580 push(@update_fields, $_ . ' = ' . $value);
581 $self->{$_} = '' if (ref $self);
582 } else {
583 push(@update_fields, $_ . ' = ' . (defined $value ? '?' : 'NULL'));
584 push(@update_values, (defined $value ? $value : ( )));
585 }
586 }
587  
588 ## make UPDATE statement ##
589 my ($where, @wherevals) = $class->format_conditions( $dbh, $params );
590 my $UPDATE = "UPDATE " . $class->table . " SET " . join(',', @update_fields) . " $where";
591 warn "$class->modify :\t\t\t\"$UPDATE\" [@update_values] [@wherevals]\n" if ($debug);
592  
593 ## UPDATE data ##
594 my $sth = $dbh->prepare( $UPDATE ) || croak "$UPDATE;\n" . $dbh->errstr . "\n";
595 $sth->execute( @update_values, @wherevals ) || croak "execute\n$UPDATE;\n" . $sth->errstr . "\n";
596 $sth->finish;
597 }
598  
599 ######################### BEGIN Relations Code ########################
600 ### This next block itterates through the class names in $selected ###
601 ### hashref and does the following: ###
602 ### 1. Gets previously related objects of said class. ###
603 ### 2. Compares previously related objects to new list of ###
604 ### related objects. ###
605 ### - In order to do this it gets the cpkey() of each ###
606 ### previously related object and puts ###
607 ### them all in a hash. ###
608 ### 3. Unrelates no longer related objects. ###
609 ### 4. Relates all newly related objects. ###
610 #######################################################################
611 if (%selected) {
612 ## Iterates through classnames in $selected ##
613 foreach my $relclass (keys %selected) {
614 ## puts cpkeys of $_ classname ##
615 my %local_selected = %{ $selected{$relclass} };
616  
617 ## get already related objects ##
618 my $current_objs = $self->list_related( $relclass );
619  
620 ## creates a hash of cpkeys => objects. ##
621 my %cpkeys = map { $_->cpkey => $_ } @$current_objs;
622  
623 ## remove keys from cpkeys that are also in local selected. ##
624 %cpkeys = map { $_ => $cpkeys{$_} } grep {!$local_selected{$_}} keys %cpkeys;
625 foreach my $cpk (keys %cpkeys) { # go through previously related cpkeys
626 $self->unrelate( $cpkeys{$cpk} ); # unrelate
627 }
628  
629 ## Here we relate all newly related items (we also might be related objects ##
630 ## which are already related, but it won't mind) ##
631 foreach my $cpk (keys %local_selected) { # goes through all newly related cpkeys
632 my %params;
633 @params{ @{ $relclass->primary_keys } } = split($self->pkd,$cpk);
634 $self->relate( $relclass->get( $dbh, \%params ) );
635 }
636 }
637 }
638 ################################### END RELATIONS CODE ################################################
639  
640 ## Save content data. ##
641 foreach (keys %content) {
642 warn "Saving content: $_ ==> $content{$_}" if ($debug > 1);
643 $self->$_( $content{$_} );
644 }
645 }; # END of eval
646  
647 ## Caught exception, ROLLBACK TRANSACTION ##
648 if ($@) {
649 $self->errors( $@ );
650 $dbh->rollback if (%selected || %content);
651 return $class->error_handler("In ${class}::modify() - $@");
652 }
653 $dbh->commit if (%selected || %content);
654  
655 return ref($self) ? $self : 1;
656 } # END sub modify
657  
658 =item C<duplicate> ( [ $dbh, ] [ $object ] )
659  
660 Returns a duplicate object, differing only by the primary key.
661  
662 =cut
663 sub duplicate {
664 my $self = shift;
665 my $class = ref($self) || $self;
666 my $dbh = ref($self) ? $self->dbh : shift;
667  
668 $self = ref($self) ? $self : $class->get( shift() );
669 my $data = { %$self };
670 foreach (@{ $self->primary_keys }) {
671 delete $data->{$_};
672 }
673  
674 $class->new( $dbh, $data );
675 } # END sub duplicate
676  
677 =item C<rm> ( )
678  
679 Object method:
680  
681 Deletes the object and all database records associated with it.
682  
683 =item C<rm> ( $dbh, \%params )
684  
685 Static method:
686  
687 Deletes all database rows satisfied by the conditions in \%params.
688  
689 For instructions on the format of \%params, see L<"item_format_conditions">.
690  
691 =cut
692 sub rm {
693 my $self = shift;
694 my $class = ref($self) || $self;
695 my $dbh = ref($self) ? $self->dbh : shift;
696 ref($dbh) || return $class->error_handler("In ${class}::rm() called without dbh object");
697 my $params;
698  
699 local $dbh->{'AutoCommit'} = 0; # BEGIN TRANSACTION
700 eval {
701 local $dbh->{'RaiseError'} = 1;
702  
703 ## Object method section ##
704 if (ref $self) {
705 ## Use values of primary keys as conditional parameters ##
706 ## (to effect this row only) ##
707 $params = { map { $_ => $self->$_() } @{ $self->primary_keys } };
708  
709 ## Start Content Fields Code ##
710 my @contentfields = keys %{ $class->contentfields };
711 map { $self->$_('') } @contentfields; # this deletes the content fields
712 ## End Content Fields Code ##
713  
714 ## Start Unrelate related objects Code ##
715 if ($class->relations) {
716 foreach (keys %{ $class->relations }) {
717 $self->unrelate( $self->list_related( $_ ) );
718 }
719 }
720 ## End Unrelate related objects Code ##
721  
722 ## Static method section ##
723 } else {
724 $params = shift;
725 return undef unless (ref($params) eq 'HASH' || ref($params) eq 'ARRAY');
726 }
727  
728 my ($where, @wherevals) = $class->format_conditions( $dbh, $params );
729 die "invalid conditions\n" unless ($where);
730  
731 my $DELETE = 'DELETE FROM ' . $class->table . ' ' . $where;
732 warn "$class->rm :\t\t\t\"$DELETE\" [@wherevals]\n" if ($debug);
733  
734 ## execute statement or error out ##
735 my $sth = $dbh->prepare( $DELETE ) || croak "$DELETE;\n" . $dbh->errstr . "\n";
736 $sth->execute( @wherevals ) || croak "$DELETE;\n" . $sth->errstr . "\n";
737 $sth->finish;
738 }; # END of eval
739  
740 ## Caught exception, ROLLBACK TRANSACTION ##
741 if ($@) {
742 $self->errors( $@ );
743 $dbh->rollback;
744 return $class->error_handler("In ${class}::rm() - $@");
745 }
746 $dbh->commit;
747  
748 ## delete sucessful ##
749 ref($self) && undef( %{ $self } ); # Scoop out creamy filling
750 return 1;
751 } # END sub rm
752  
753 =back
754  
755 =cut
756  
757 ################################################################################
758 ############################## Data List Methods: ##############################
759 ################################################################################
760  
761  
762 =head2 DATA LIST CONSTRUCTOR METHODS
763  
764 =over 4
765  
766 =item C<list_obj> ( [ $dbh, ] \%params, \@fields, \@sort )
767  
768 Returns an arrayref of objects meeting all specifications in \%params.
769  
770 For instructions on the format of \%params, see L<"item_format_conditions">.
771  
772 =cut
773 sub list_obj {
774 my $self = shift;
775 my $class = ref($self) || $self;
776 my $dbh = ref($self) ? $self->dbh : shift;
777 ref($dbh) || return $self->error_handler('BingoX::Carbon::list_obj called without dbh object');
778 my $params = shift || { };
779 my $fields = shift;
780 if (!$BingoX::Carbon::cache_all{ $class } && ref($fields) eq 'ARRAY') {
781 ## Make sure primary keys are included in $fields (map construct removes duplicates) ##
782 $fields = [
783 keys %{
784 {
785 map { $_ => 1 } (@$fields, @{ $class->primary_keys })
786 }
787 }
788 ];
789 } else {
790 ## No fields passed, use the default ##
791 $fields = $BingoX::Carbon::cache_all{$class} ? $class->fieldorder : $class->primary_keys;
792 }
793 my $sort = shift || $class->primary_keys;
794 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
795 unless ($SELECT) {
796 warn "no select statement" if ($debug);
797 return undef;
798 }
799 warn "list_obj: $SELECT" if ($debug);
800 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
801 return undef unless (ref $code);
802 my (@data, $data);
803 while ($data = $code->()) {
804 $data->{'_dbh'} = $dbh;
805 push @data, bless($data, $class);
806 }
807 return \@data;
808 } # END sub list_obj
809  
810 =item C<list_hash> ( [ $dbh, ] \%params, \@fields, \@sort )
811  
812 Returns an arrayref of hashrefs meeting all specifications in \%params
813  
814 For instructions on the format of \%params, see L<"item_format_conditions">.
815  
816 =cut
817 sub list_hash {
818 my $self = shift;
819 my $class = ref($self) || $self;
820 my $dbh = ref($self) ? $self->dbh : shift;
821 ref($dbh) || return $self->error_handler('BingoX::Carbon::list_hash called without dbh object');
822 my $params = shift || { };
823 my $fields = shift || $class->fieldorder;
824 my $sort = shift || $class->primary_keys;
825 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
826 unless ($SELECT) {
827 warn "no select statement" if ($debug);
828 return undef;
829 }
830 warn "list_hash: $SELECT" if ($debug);
831 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
832 return undef unless (ref $code);
833 my @data;
834 while (my $data = $code->()) {
835 push(@data, $data);
836 }
837 return \@data;
838 } # END sub list_hash
839  
840 =item C<list_array> ( [ $dbh, ] \%params, \@fields, \@sort )
841  
842 Returns an arrayref of arrayrefs meeting all specifications in \%params. Data is sorted
843 in the order of $class->deffields.
844  
845 For instructions on the format of \%params, see L<"item_format_conditions">.
846  
847 =cut
848 sub list_array {
849 my $self = shift;
850 my $class = ref($self) || $self;
851 my $dbh = ref($self) ? $self->dbh : shift;
852 ref($dbh) || return $self->error_handler('BingoX::Carbon::list_array called without dbh object');
853 my $params = shift || { };
854 my $fields = shift || $class->fieldorder;
855 my $sort = shift || $class->primary_keys;
856 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
857 unless ($SELECT) {
858 warn "no select statement" if ($debug);
859 return undef;
860 }
861 warn "list_array: $SELECT" if ($debug);
862 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
863 return undef unless (ref $code);
864 my @data;
865 while (my $data = $code->()) {
866 my @row = map { $data->{$_} } @{ $fields };
867 push(@data, \@row);
868 }
869 return \@data;
870 } # END sub list_array
871  
872 =back
873  
874 =cut
875  
876 ################################################################################
877 ############################# Data Stream Methods: #############################
878 ################################################################################
879  
880  
881 =head2 DATA STREAM CONSTRUCTOR METHODS
882  
883 =over 4
884  
885 =item C<stream_obj> ( [ $dbh, ] \%params, \@fields, \@sort )
886  
887 Returns an code reference which, when dereferenced, will continue to return objects
888 meeting all specifications in \%params until all matching rows have been returned, then
889 it will return undef. Will optionally limit itself to the fields specified in \@fields,
890 and optionally sorted in the order of \@sort.
891  
892 For instructions on the format of \%params, see L<"item_format_conditions">.
893  
894 =cut
895 sub stream_obj {
896 my $self = shift;
897 my $class = ref($self) || $self;
898 my $dbh = ref($self) ? $self->dbh : shift;
899 ref($dbh) || return $self->error_handler('BingoX::Carbon::stream_obj called without dbh object');
900 my $params = shift || { };
901 my $fields = shift;
902 if (!$BingoX::Carbon::cache_all{ $class } && ref($fields) eq 'ARRAY') {
903 ## Make sure primary keys are included in $fields (map construct removes duplicates) ##
904 $fields = [
905 keys %{
906 {
907 map { $_ => 1 } (@$fields, @{ $class->primary_keys })
908 }
909 }
910 ];
911 } else {
912 ## No fields passed, use the default ##
913 $fields = $BingoX::Carbon::cache_all{ $class } ? $class->fieldorder : $class->primary_keys;
914 }
915 my $sort = shift || $class->primary_keys;
916 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
917 unless ($SELECT) {
918 warn "no select statement" if ($debug);
919 return undef;
920 }
921 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
922 return undef unless (ref $code);
923 return bless(sub {
924 my $data = $code->(@_) || return undef;
925 $data->{'_dbh'} = $dbh;
926 return bless( $data, $class );
927 }, 'BingoX::Carbon::Stream');
928 } # END sub stream_obj
929  
930 =item C<stream_hash> ( [ $dbh, ] \%params, \@fields, \@sort )
931  
932 Returns an code reference which, when dereferenced, will continue to return a hashref
933 meeting all specifications in \%params until all matching rows have been returned, then
934 it will return undef. Will optionally limit itself to the fields specified in \@fields,
935 and optionally sorted in the order of \@sort.
936  
937 For instructions on the format of \%params, see L<"item_format_conditions">.
938  
939 =cut
940 sub stream_hash {
941 my $self = shift;
942 my $class = ref($self) || $self;
943 my $dbh = ref($self) ? $self->dbh : shift;
944 ref($dbh) || return $self->error_handler('BingoX::Carbon::stream_hash called without dbh object');
945 my $params = shift || { };
946 my $fields = shift || $class->fieldorder;
947 my $sort = shift || $class->primary_keys;
948 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
949 unless ($SELECT) {
950 warn "no select statement" if ($debug);
951 return undef;
952 }
953 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
954 return undef unless (ref $code);
955 return bless(sub {
956 my $data = $code->(@_) || return undef;
957 return $data;
958 }, 'BingoX::Carbon::Stream');
959 } # END sub stream_hash
960  
961 =item C<stream_array> ( [ $dbh, ] \%params, \@fields, \@sort )
962  
963 Returns an code reference which, when dereferenced, will continue to return an arrayref
964 meeting all specifications in \%params until all matching rows have been returned, then
965 it will return undef. Will optionally limit itself to the fields specified in \@fields,
966 and optionally sorted in the order of \@sort.
967  
968 For instructions on the format of \%params, see L<"item_format_conditions">.
969  
970 =cut
971 sub stream_array {
972 my $self = shift;
973 my $class = ref($self) || $self;
974 my $dbh = ref($self) ? $self->dbh : shift;
975 ref($dbh) || return $self->error_handler('BingoX::Carbon::stream_array called without dbh object');
976 my $params = shift || { };
977 my $fields = shift || $class->fieldorder;
978 my $sort = shift || $class->primary_keys;
979 my ($SELECT, @bindings) = $class->format_select( $dbh, $params, $fields, $sort );
980 unless ($SELECT) {
981 warn "no select statement" if ($debug);
982 return undef;
983 }
984 my $code = $class->sql_select( $dbh, $SELECT, \@bindings );
985 return undef unless (ref $code);
986 return bless(sub {
987 my $data = $code->(@_) || return undef;
988 my @row = map { $data->{$_} } @{ $fields };
989 return \@row;
990 }, 'BingoX::Carbon::Stream');
991 } # END sub stream_array
992  
993 =back
994  
995 =cut
996  
997 ################################################################################
998 ############################# Relational Methods: ##############################
999 ################################################################################
1000  
1001  
1002 =head2 RELATIONAL METHODS
1003  
1004 =over 4
1005  
1006 =item C<relate> ( $OBJ )
1007  
1008 =item C<relate> ( \@OBJECTS )
1009  
1010 =item C<relate> ( \@IDS, $ID_CLASS, $ID_COLUMN )
1011  
1012 Relates object to $OBJ, all objects in \@OBJECTS, or objects represented by
1013 \@IDS from the $ID_CLASS class in the $ID_COLUMN column of the database. Returns
1014 the number of objects passed that have been related to the object.
1015  
1016 =cut
1017 sub relate {
1018 my $self = shift;
1019 my $class = ref($self) || return $self->error_handler('relate must be called as an object method');
1020 my $dbh = $self->dbh;
1021 my $data = shift;
1022 my (@OBJECTS, $fclass, $rclass);
1023 ############################################################################
1024 ## code duped from get_relation_info so that grep can be used to single ##
1025 ## out relations that don't exist already ##
1026 ############################################################################
1027 if (ref($data) eq 'ARRAY') {
1028 if ($#{ $data } >= 0) {
1029 if ($fclass = ref($data->[0])) { # Array of objects
1030 @OBJECTS = @{ $data };
1031 } else { # Array of IDs
1032 $fclass = shift;
1033 my $column = shift;
1034 @OBJECTS = @{ $fclass->list_obj( $dbh,
1035 {
1036 $column => [ 'IN', @$data ]
1037 }
1038 )
1039 };
1040 }
1041 } else {
1042 return $self->error_handler('empty array reference passed to relate');
1043 }
1044 } elsif ($fclass = ref($data)) { # Single object
1045 @OBJECTS = ( $data );
1046 } else {
1047 return $self->error_handler('relate called with invalid parameters - check documentation');
1048 }
1049 ############################################################################
1050  
1051 ## OBJECTS to be related are in the ARRAY @OBJECTS ##
1052 my $related = 0;
1053 my $toberelated = $#OBJECTS;
1054 @OBJECTS = grep { 1 ^ $self->isrelated( $_ ) } @OBJECTS;
1055 $related = ($toberelated - $#OBJECTS); # Add already related objects
1056  
1057 ($rclass, $data) = $self->get_relation_info( 'I', \@OBJECTS );
1058 return $related unless (ref($data) eq 'ARRAY');
1059 foreach (@{ $data }) {
1060 $rclass->new( $dbh, $_ ) || next;
1061 $related++;
1062 }
1063 return $related;
1064 } # END sub relate
1065  
1066  
1067 =item C<unrelate> ( $OBJ )
1068  
1069 =item C<unrelate> ( \@OBJECTS )
1070  
1071 =item C<unrelate> ( \@IDS, $ID_CLASS, $ID_COLUMN )
1072  
1073 Unrelates object from $OBJ, all objects in \@OBJECTS, or objects represented by
1074 \@IDS from the $ID_CLASS class in the $ID_COLUMN column of the database. Returns
1075 the number of objects that no longer are related to the object.
1076  
1077 =cut
1078 sub unrelate {
1079 my $self = shift;
1080 my $class = ref($self) || return $self->error_handler('unrelate must be called as an object method');
1081 my $dbh = $self->dbh;
1082 my $data = shift;
1083 my (@OBJECTS, $fclass, $rclass);
1084 ############################################################################
1085 ## code duped from get_relation_info so that grep can be used to single ##
1086 ## out relations that don't exist already ##
1087 ############################################################################
1088 if (ref($data) eq 'ARRAY') {
1089 if ($#{ $data } >= 0) {
1090 if ($fclass = ref($data->[0])) { # Array of objects
1091 @OBJECTS = @{ $data };
1092 } else { # Array of IDs
1093 $fclass = shift;
1094 my $column = shift;
1095 @OBJECTS = @{ $fclass->list_obj( $dbh,
1096 {
1097 $column => [ 'IN', @$data ]
1098 }
1099 )
1100 };
1101 }
1102 } else {
1103 return $self->error_handler('empty array reference passed to unrelate');
1104 }
1105 } elsif ($fclass = ref($data)) { # Single object
1106 @OBJECTS = ( $data );
1107 } else {
1108 return $self->error_handler('unrelate called with invalid parameters - check documentation');
1109 }
1110 ############################################################################
1111  
1112 ## OBJECTS to be unrelated are in the ARRAY @OBJECTS ##
1113 my $removed = scalar(@OBJECTS);
1114 @OBJECTS = grep { $self->isrelated( $_ ) } @OBJECTS;
1115  
1116 ($rclass, $data) = $self->get_relation_info( 'S', \@OBJECTS );
1117 return $removed unless (ref($data) eq 'HASH');
1118 my $list = $rclass->list_obj( $dbh, $data );
1119 return undef unless (ref $list);
1120 foreach my $OBJ (@$list) {
1121 $removed-- unless ($OBJ->rm);
1122 }
1123 return $removed;
1124 } # END sub unrelate
1125  
1126  
1127 =item C<unrelate_all> ( $fclass [ , $unary_rev ] )
1128  
1129 Unrelates all related objects in class $fclass from current object.
1130 Optional $unary_rev does reverse operation for unary relationships
1131  
1132 i.e.:
1133  
1134 unrelates "parent" objects from current
1135  
1136 =cut
1137 sub unrelate_all {
1138 my $self = shift;
1139 my $class = ref($self) || return $self->error_handler('unrelate_all must be called as an object method');
1140 my $dbh = $self->dbh;
1141 my $fclass = shift;
1142 my $unary_rev = shift; # UNARY REVERSE FLAG (use second column)
1143 my $rclass = $self->relations->{ $fclass } || return $self->error_handler("class $class is not related to class $fclass");
1144 my $params = $self->_related_subquery_conditions( $fclass, $unary_rev );
1145 $rclass->rm( $dbh, $params );
1146 } # END sub unrelate_all
1147  
1148  
1149 =item C<isrelated> ( $OBJ )
1150  
1151 Returns a true value if $OBJ is related to the object, false otherwise.
1152  
1153 =cut
1154 sub isrelated {
1155 my $self = shift;
1156 my $class = ref($self) || return $self->error_handler('isrelated must be called as an object method');
1157 my $dbh = $self->dbh;
1158 my $OBJECT = shift || return undef;
1159 my ($rclass, $data) = $self->get_relation_info( 'S', $OBJECT );
1160 return undef unless (ref($data) eq 'HASH');
1161 return ref($rclass->get( $dbh, $data )) ? 1 : 0;
1162 } # END sub isrelated
1163  
1164  
1165 =item C<list_related> ( $class [, \@fields] [, \@sort] [, $unary_rev_flag ] )
1166  
1167 Returns an arrayref of objects of $class related to the object.
1168  
1169 =cut
1170 sub list_related {
1171 my $self = shift;
1172 my $class = ref($self) || return $self->error_handler('method list_related must be called as an object method');
1173 my $dbh = $self->dbh;
1174 my $fclass = shift || return undef;
1175 my $fields = shift || $fclass->primary_keys;
1176 my $sort = shift || $fclass->primary_keys;
1177 my $unary_rev = shift; # UNARY REVERSE FLAG (use second column)
1178 my $code = $self->stream_related( $fclass, $fields, $sort, $unary_rev );
1179 return undef unless (ref $code);
1180 my @array;
1181 while (my $data = $code->()) {
1182 push(@array, $data);
1183 }
1184 return \@array;
1185 } # END sub list_related
1186  
1187  
1188 =item C<stream_related> ( $class [, \@fields] [, \@sort] [, $unary_rev_flag ] )
1189  
1190 Returns an code reference which, when dereferenced, will continue to return objects
1191 of $class related to the object until all matching rows have been returned, then
1192 it will return undef.
1193  
1194 =back
1195  
1196 =cut
1197 sub stream_related {
1198 my $self = shift;
1199 my $class = ref($self) || return $self->error_handler('method list_related must be called as an object method');
1200 my $dbh = ref($self) ? $self->dbh : return undef;
1201 my $fclass = shift || return undef;
1202 my $fields = shift || $fclass->primary_keys;
1203 my $sort = shift || $fclass->primary_keys;
1204 my $unary_rev = shift; # UNARY REVERSE FLAG (use second column)
1205 my $params = $self->_related_conditions( $fclass, $unary_rev );
1206 return $fclass->stream_obj( $dbh, $params, $fields, $sort );
1207 } # END sub stream_related
1208  
1209  
1210 =begin private_method
1211  
1212 _related_subquery_conditions ( $fclass [, $unary_rev ] )
1213 - $fclass is the "foreign" class (related class)
1214 - in scalar context, returns \%fparams (see unrelate_all())
1215 - in array context, returns (\%fparams, \@fcolumns, \@columns) (see _related_conditions())
1216 %fparams : parameters of query (can be passed to format_conditions())
1217 @fcolumns : relevant columns in foreign class
1218 @columns : relevant columns in this class
1219  
1220 =end private_method
1221  
1222 =cut
1223 sub _related_subquery_conditions {
1224 my $self = shift;
1225 my $class = ref($self) || return $self->error_handler('method _related_subquery_conditions must be called as an object method');
1226 my $fclass = shift || return undef;
1227 my $unary_rev = shift; # UNARY REVERSE FLAG (use second column)
1228 my $relations = $class->relations;
1229 my $rclass = $relations->{ $fclass } || return undef;
1230 my $rfkeys = $rclass->foreign_keys;
1231 my @columns = ( $class ); # Doesn't belong in the array, but it'll get shifted
1232 my @fcolumns = ( $fclass ); # off at the beginning of the block below.
1233 my %fparams;
1234  
1235 if ($class eq $fclass) { # UNARY RELATIONSHIP
1236 my $data = $rfkeys->{ $class };
1237 @columns = @fcolumns = ( );
1238 foreach my $key (keys %{ $data }) {
1239 next unless (ref($data->{ $key }) eq 'ARRAY');
1240 push @columns, $key;
1241 push @fcolumns, $data->{ $key };
1242 }
1243 %fparams = map {
1244 $fcolumns[$_]->[($unary_rev ? 1 : 0)] => $self->${\$columns[$_]}()
1245 } (0 .. $#columns);
1246 } else { # BINARY RELATIONSHIP
1247 foreach my $arrayref (\@fcolumns, \@columns) {
1248 my $data = $rfkeys->{ shift(@$arrayref) };
1249 if (ref($data) eq 'HASH') {
1250 foreach my $key (keys %{ $data }) {
1251 if (ref($data->{ $key }) eq 'ARRAY') {
1252 next; # Aieee, unary syntax in binary relationship
1253 } else {
1254 push(@$arrayref, $data->{ $key });
1255 }
1256 }
1257 } elsif (ref($data) eq 'ARRAY') {
1258 @$arrayref = @{ $data };
1259 } elsif (!(ref $data)) {
1260 @$arrayref = ( $data );
1261 } else {
1262 return undef;
1263 }
1264 }
1265 %fparams = map { $_ => $self->$_() } @columns;
1266 }
1267 return wantarray ? (\%fparams, \@fcolumns, \@columns) : \%fparams;
1268 } # END sub _related_subquery_conditions
1269  
1270  
1271 =begin private_method
1272  
1273 _related_conditions ( $fclass [, $unary_rev ] )
1274 - $fclass is the "foreign" class (related class)
1275 - generates conditions suitable for using with stream_obj()
1276 - used only by stream_related() and list_related()
1277  
1278 =end private_method
1279  
1280 =cut
1281 sub _related_conditions {
1282 my $self = shift;
1283 my $class = ref($self) || return $self->error_handler('method _related_conditions must be called as an object method');
1284 my $dbh = ref($self) ? $self->dbh : return undef;
1285 my $fclass = shift || return undef;
1286 my $unary_rev = shift; # UNARY REVERSE FLAG (use second column)
1287 my $relations = $class->relations;
1288 my $rclass = $relations->{ $fclass } || return undef;
1289 my $rfkeys = $rclass->foreign_keys;
1290  
1291 my($fparams, $fcolumns, $columns) = $self->_related_subquery_conditions( $fclass, $unary_rev );
1292 my %params;
1293 if ($class eq $fclass) {
1294 foreach my $i (0 .. $#{ $fcolumns }) {
1295 $params{ $columns->[$i] } = [
1296 'IN',
1297 $rclass->format_select(
1298 $dbh,
1299 $fparams,
1300 [
1301 $fcolumns->[$i]->[($unary_rev ? 0 : 1)]
1302 ],
1303 undef,
1304 'rel'
1305 )
1306 ];
1307 }
1308 } else {
1309 foreach my $i (0 .. $#{ $fcolumns }) {
1310 $params{ $fcolumns->[$i] } = [
1311 'IN',
1312 $rclass->format_select(
1313 $dbh,
1314 $fparams,
1315 [
1316 $fcolumns->[$i]
1317 ],
1318 undef,
1319 'rel'
1320 )
1321 ];
1322 }
1323 }
1324 return \%params;
1325 } # END sub _related_conditions
1326  
1327  
1328 =over 4
1329  
1330 =item C<get_relation_info> ( ('I' | 'S'), $OBJ )
1331  
1332 =item C<get_relation_info> ( ('I' | 'S'), \@OBJECTS )
1333  
1334 =item C<get_relation_info> ( ('I' | 'S'), \@IDS, $ID_CLASS, $ID_COLUMN )
1335  
1336 Returns as the first element the relational class on which the second data element
1337 is associated. If the first argument is an 'I' (INSERT), the second element is a
1338 hashref suitable to pass to new or modify. If the first argument is an 'S' (SELECT),
1339 returns a hashref suitable to pass to get, list_*, stream_*, etc. This method is
1340 primarily used by methods relate, unrelate, isrelated, and related.
1341  
1342 =cut
1343 sub get_relation_info {
1344 my $self = shift;
1345 my $class = ref($self) || return $self->error_handler('relate must be called as an object method');
1346 my $dbh = $self->dbh;
1347 my $type = shift || return undef;
1348 my $data = shift;
1349  
1350 my ($OBJECTS, $fclass);
1351 if (ref($data) eq 'ARRAY') {
1352 if ($#{ $data } >= 0) {
1353 if ($fclass = ref($data->[0])) { # Array of objects
1354 $OBJECTS = $data;
1355 } else { # Array of IDs
1356 $fclass = shift;
1357 my $column = shift;
1358 $OBJECTS = $fclass->list_obj( $dbh, { $column => [ 'IN', @$data ] } );
1359 }
1360 } else {
1361 return undef;
1362 }
1363 } elsif ($fclass = ref($data)) { # Single object
1364 $OBJECTS = [ $data ];
1365 } else {
1366 return undef;
1367 }
1368  
1369 ## OBJECTS to be related are in the ARRAYREF $OBJECTS ##
1370 my $relations = $self->relations || return $self->error_handler("No relations found for the $class class");
1371 my $rclass = $relations->{$fclass} || return undef;
1372 my $rfkeys = $rclass->foreign_keys || return $self->error_handler("No foreign keys found for the $rclass class");
1373 my (%objects, %relational_columns);
1374 $relational_columns{'local'} = $rfkeys->{ $class };
1375 $relational_columns{'foreign'} = $rfkeys->{ $fclass };
1376 @objects{ 'local', 'foreign' } = ( [ $self ], $OBJECTS );
1377 if ($type eq 'S') {
1378 my %params;
1379 foreach (qw(local foreign)) {
1380 my $data = $relational_columns{$_};
1381 my (%column_info, $columns);
1382 if (ref($data) eq 'HASH') { # Multiple columns represent the same primary key (to relate two of the same type of item)
1383 %column_info = %{ $data };
1384 $columns = [ keys %column_info ];
1385 } elsif (ref($data) eq 'ARRAY') {
1386 $columns = $data;
1387 } elsif (!(ref $data)) {
1388 $columns = [ $data ];
1389 } else {
1390 return $self->error_handler("Relation misconfiguration in $class or $fclass");
1391 }
1392 foreach my $column (@{ $columns }) {
1393 my $method = $column;
1394 if (ref($column_info{ $column })) {
1395 my $i = 0;
1396 do {
1397 last unless (defined($column = $column_info{ $method }->[$i++]));
1398 } while (exists $params{ $column });
1399 return undef if (exists $params{ $column });
1400 }
1401 next unless (ref $objects{$_}->[0]);
1402 if ($#{ $objects{ $_ } } == 0) {
1403 $params{ $column } = $objects{$_}->[0]->$method();
1404 } else {
1405 $params{ $column } = [
1406 'IN',
1407 map { $_->$method() } @{ $objects{$_} }
1408 ];
1409 }
1410 }
1411 }
1412 warn "get_relation_info returning SELECT to " . (caller 1)[3] . " data: " . Data::Dumper::Dumper(\%params) if ($debug);
1413 return ($rclass, \%params);
1414 } elsif ($type eq 'I') {
1415 my $data = $relational_columns{'local'};
1416 my (%gparams, %column_info, $columns);
1417 if (ref($data) eq 'HASH') { # Multiple columns represent the same primary key (to relate two of the same type of item)
1418 %column_info = %{ $data };
1419 $columns = [ keys %column_info ];
1420 } elsif (ref($data) eq 'ARRAY') {
1421 $columns = $data;
1422 } elsif (!(ref $data)) {
1423 $columns = [ $data ];
1424 } else {
1425 return $self->error_handler("Relation misconfiguration in $class");
1426 }
1427 foreach my $column (@{ $columns }) {
1428 my $method = $column;
1429 $column = $column_info{ $column }->[0] if (ref($column_info{ $column }) eq 'ARRAY');
1430 $gparams{ $column } = $self->$method();
1431 }
1432  
1433 my @params;
1434 $data = $relational_columns{'foreign'};
1435 foreach my $OBJECT (@{ $OBJECTS }) {
1436 my %params = ( %gparams );
1437 my (%column_info, $columns);
1438 if (ref($data) eq 'HASH') { # Multiple columns represent the same primary key (to relate two of the same type of item)
1439 %column_info = %{ $data };
1440 $columns = [ keys %column_info ];
1441 } elsif (ref($data) eq 'ARRAY') {
1442 $columns = $data;
1443 } elsif (!(ref $data)) {
1444 $columns = [ $data ];
1445 } else {
1446 return $self->error_handler("Relation misconfiguration in $fclass");
1447 }
1448 foreach my $column (@{ $columns }) {
1449 my $method = $column;
1450 $column = $column_info{ $column }->[1] if (ref($column_info{ $column }) eq 'ARRAY');
1451 $params{ $column } = $OBJECT->$method();
1452 }
1453 push(@params, \%params);
1454 }
1455 warn "get_relation_info returning INSERT to " . (caller 1)[3] . " data: " . Data::Dumper::Dumper(\@params) if ($debug);
1456 return ($rclass, \@params);
1457 } else {
1458 return undef;
1459 }
1460 } # END sub get_relation_info
1461  
1462 =back
1463  
1464 =cut
1465  
1466 ################################################################################
1467 ######################## Class Variable Access Methods: ########################
1468 ################################################################################
1469  
1470  
1471 =head2 CLASS DATA ACCESSOR METHODS
1472  
1473 =over 4
1474  
1475 =item C<table> ( [ $dbh ] )
1476  
1477 Returns class defined table name
1478  
1479 =cut
1480 sub table {
1481 no strict 'refs';
1482 my $self = shift;
1483 my $class = ref($self) || $self;
1484 return ${"${class}::table"} || $self->error_handler("Package variable ${class}::table not defined");
1485 } # END sub table
1486  
1487  
1488 =item C<identity> ( [ $dbh ] )
1489  
1490 Returns class defined identity column as a string.
1491  
1492 =cut
1493 sub identity {
1494 no strict 'refs';
1495 my $self = shift;
1496 my $class = ref($self) || $self;
1497 return ${"${class}::identity"};
1498 } # END sub identity
1499  
1500  
1501 =item C<sequence> ( [ $dbh ] )
1502  
1503 Returns class defined sequence used by this table as a string.
1504  
1505 =cut
1506 sub sequence {
1507 no strict 'refs';
1508 my $self = shift;
1509 my $class = ref($self) || $self;
1510 return ${"${class}::sequence"};
1511 } # END sub sequence
1512  
1513  
1514 =item C<seqcol> ( [ $dbh ] )
1515  
1516 Returns class defined seqcol used by this table as a string.
1517  
1518 =cut
1519 sub seqcol {
1520 no strict 'refs';
1521 my $self = shift;
1522 my $class = ref($self) || $self;
1523 return ${"${class}::seqcol"};
1524 } # END sub seqcol
1525  
1526  
1527 =item C<def_fields> ( )
1528  
1529 Returns class defined fields as a hash reference
1530  
1531 =cut
1532 sub deffields { $_[0]->def_fields }
1533 sub def_fields {
1534 my $self = shift;
1535 my $class = ref($self) || $self;
1536 no strict 'refs';
1537 return \%{"${class}::deffields"} if (defined %{"${class}::deffields"});
1538 return \%{"${class}::def_fields"} if (defined %{"${class}::def_fields"});
1539 return { %{"${class}::def_fields"} = map { $_ => 1 } @{ $class->field_order || [ ] } };
1540 } # END sub def_fields
1541  
1542  
1543 =item C<field_order> ( )
1544  
1545 Returns class defined field order as an anonymous array
1546  
1547 =cut
1548 sub fieldorder { $_[0]->field_order }
1549 sub field_order {
1550 my $self = shift;
1551 my $class = ref($self) || $self;
1552 no strict 'refs';
1553 return [ @{"${class}::fieldorder"} ] if (@{"${class}::fieldorder"});
1554 return [ @{"${class}::field_order"} ] || $self->error_handler("Package variable ${class}::field_order not defined");
1555 } # END sub field_order
1556  
1557  
1558 =item C<relations> ( )
1559  
1560 Returns class defined relations as a hash reference
1561  
1562 =cut
1563 sub relations {
1564 my $self = shift;
1565 my $class = ref($self) || $self;
1566 no strict 'refs';
1567 return { %{"${class}::relations"} };
1568 } # END sub relations
1569  
1570  
1571 =item C<foreign_keys> ( )
1572  
1573 Returns class defined foreign_keys as a hash reference
1574  
1575 =cut
1576 sub foreign_keys {
1577 my $self = shift;
1578 my $class = ref($self) || $self;
1579 no strict 'refs';
1580 return { %{"${class}::foreign_keys"} };
1581 } # END sub foreign_keys
1582  
1583  
1584 =item C<cpkey> ( )
1585  
1586 Returns a string representing a single composite primary key joined by $self->pkd.
1587  
1588 B<OPTIMIZE>
1589  
1590 =cut
1591 sub cpkey {
1592 my $self = shift;
1593 return undef unless (ref $self);
1594 return $self->{'_cpkey'} if ($self->{'_cpkey'});
1595 $self->{'_cpkey'} = join($self->pkd, map { $self->$_() } @{ $self->primary_keys } );
1596 return $self->{'_cpkey'};
1597 } # END sub cpkey
1598  
1599 =item C<cpkey_params> ($cpkey)
1600  
1601 Returns a params hash from the cpkey string passed.
1602  
1603 =cut
1604 sub cpkey_params {
1605 my $self = shift;
1606 my $cpkey = shift;
1607 my $pkeys = $self->primary_keys;
1608
1609 my $hash = {
1610 map {
1611 shift(@{ $pkeys }) => $_
1612 } split($self->pkd, $cpkey)
1613 };
1614 return $hash;
1615 } # END sub cpeky
1616  
1617 =item C<title_field> ( )
1618  
1619 Returns class defined title_field as a string.
1620  
1621 =cut
1622 sub title_field {
1623 no strict 'refs';
1624 my $self = shift;
1625 my $class = ref($self) || $self;
1626 return ${"${class}::title_field"};
1627 } # END sub title_field
1628  
1629  
1630 =item C<title_size> ( )
1631  
1632 Returns class defined title_size as a string.
1633  
1634 =cut
1635 sub title_size {
1636 no strict 'refs';
1637 my $self = shift;
1638 my $class = ref($self) || $self;
1639 return ${"${class}::title_size"};
1640 } # END sub title_size
1641  
1642  
1643 =item C<content_fields> ( )
1644  
1645 Returns class defined content fields order as an hashref
1646  
1647 =cut
1648 sub contentfields { $_[0]->content_fields }
1649 sub content_fields {
1650 no strict 'refs';
1651 my $self = shift;
1652 my $class = ref($self) || $self;
1653 return { %{"${class}::contentfields"} } if (keys %{"${class}::contentfields"});
1654 return { %{"${class}::content_fields"} };
1655 } # END sub content_fields
1656  
1657  
1658 =item C<date_fields> ( )
1659  
1660 Returns class defined date fields order as an hashref
1661  
1662 =cut
1663 sub datefields { $_[0]->date_fields }
1664 sub date_fields {
1665 no strict 'refs';
1666 my $self = shift;
1667 my $class = ref($self) || $self;
1668 return { %{"${class}::datefields"} } if (keys %{"${class}::datefields"});
1669 return { %{"${class}::date_fields"} };
1670 } # END sub date_fields
1671  
1672  
1673 =item C<primary_keys> ( [ $dbh ] )
1674  
1675 Returns class defined primary keys as an array ref.
1676 NOTE: The use of the class variable $primary_key has been deprecated!
1677 primary_keys will construct an array ref with $primary_key if it is used.
1678 Future verson of BingoX::Carbon will not support this!
1679  
1680 =cut
1681 sub primary_keys {
1682 my $self = shift;
1683 my $class = ref($self) || $self;
1684 my $dbh = ref($self) ? $self->dbh : shift;
1685 no strict 'refs';
1686 my @pkeys = @{"${class}::primary_keys"};
1687 unless (@pkeys) {
1688 @pkeys = ( ${"${class}::primary_key"} );
1689 $self->error_handler("Package variable ${class}::primary_keys not defined") unless (@pkeys);
1690 }
1691 return \@pkeys;
1692 } # END sub primary_keys
1693  
1694 =item C<dbh> ( )
1695  
1696 Returns class database handler object.
1697 Keeps a global which gets removed with a $r->register_cleanup.
1698  
1699 =cut
1700 sub dbh {
1701 my $self = shift;
1702 my $class = ref($self) || $self;
1703 return $self->{'_dbh'} if (ref($self) && ref($self->{'_dbh'}));
1704 if (ref(my $dbh = $self->cached_dbh)) {
1705 return $dbh;
1706 } else {
1707 $dbh = $self->connectdb;
1708 $self->{'_dbh'} = $dbh if (ref $self);
1709 $self->cached_dbh( $dbh );
1710 return $dbh;
1711 }
1712 } # END sub dbh
1713  
1714  
1715 =item C<cached_dbh> ( [ $dbh ] )
1716  
1717 Returns the cached database handle if it has been set.
1718 Optionally sets the cached database handle to $dbh.
1719  
1720 =cut
1721 sub cached_dbh {
1722 my $self = shift;
1723 my $class = ref($self) || $self;
1724 my $dclass = $self->dataclass( $class );
1725 no strict 'refs';
1726 if ($#_ >= 0) {
1727 my $new = shift;
1728 if (ref $new) {
1729 warn "setting new dbh [${dclass}::dbh]" if ($debug > 2);
1730 ${ "${dclass}::dbh" } = $new;
1731 Apache->register_cleanup(sub { ${ "${dclass}::dbh" } = undef; })
1732 if (exists $ENV{MOD_PERL});
1733 } else {
1734 warn "clearing cached dbh [${dclass}::dbh]" if ($debug > 2);
1735 ${ "${dclass}::dbh" } = undef;
1736 }
1737 warn "\tnew value: " . ${ "${dclass}::dbh" } if ($debug > 2);
1738 }
1739 return ${ "${dclass}::dbh" };
1740 } # END sub cached_dbh
1741  
1742  
1743 =item C<purge_dbh> ( )
1744  
1745 Clears the database handle cache variable.
1746  
1747 =cut
1748 sub purge_dbh {
1749 my $self = shift;
1750 my $class = ref($self) || $self;
1751 my $dclass = $self->dataclass( $class );
1752 $self->cached_dbh( undef );
1753 return 1;
1754 } # END method purge_dbh
1755  
1756  
1757 =item C<error_handler> ( )
1758  
1759 Carps @_ if debugging is activated
1760 prints stack backtrace if $debug > 2
1761 always returns undef (if you choose to overload this method, please make sure you return undef)
1762  
1763 =cut
1764 sub error_handler {
1765 my $class = ref($_[0]) ? ref(shift) : shift;
1766 $debug && (($debug > 2) ? cluck("$class: ", @_) : carp("$class: ", @_));
1767 return undef;
1768 } # END sub error_handler
1769  
1770  
1771 =item C<errors> ( )
1772  
1773 Returns $self->{'_errors'} if called as an object method.
1774 Returns $errstr of the called class otherwise.
1775  
1776 =cut
1777 sub errors {
1778 my $self = shift;
1779 my $data = shift;
1780 if (ref $self) {
1781 if ($data) {
1782 $self->{'_errors'} = $data;
1783 return $self->{'_errors'};
1784 } else {
1785 return delete $self->{'_errors'};
1786 }
1787 } else {
1788 no strict 'refs';
1789 if ($data) {
1790 ${"${self}::errstr"} = $data;
1791 return ${"${self}::errstr"};
1792 } else {
1793 my $error = ${"${self}::errstr"};
1794 ${"${self}::errstr"} = undef;
1795 return $error;
1796 }
1797 }
1798 } # END sub errors
1799  
1800  
1801 =item C<data_class> ( )
1802  
1803 Returns the data class
1804  
1805 =cut
1806 sub dataclass { $_[0]->data_class($_[1]) }
1807 sub data_class {
1808 my $self = shift;
1809 my $class = shift;
1810 my $lclass = $class;
1811 no strict 'refs';
1812 my @isa = @{ "${class}::ISA" };
1813 while ($isa[0] ne __PACKAGE__) {
1814 $lclass = shift(@isa);
1815 unshift( @isa, @{ "${lclass}::ISA" } );
1816 return undef unless (@isa);
1817 }
1818 return $lclass;
1819 } # END sub dataclass
1820  
1821  
1822 =item C<data_class_name> ( )
1823  
1824 Returns the rightmost part of the data_class_name name (thats the text right of the ::)
1825  
1826 =cut
1827 sub data_class_name {
1828 my $self = shift;
1829 return $self->{'_data_class_name'} if (ref $self);
1830 $self->db_class =~ /^.*:(.*)/;
1831 $self->{'_data_class_name'} = $1 if (ref $self);
1832 return $1;
1833 } # END sub data_class_name
1834  
1835  
1836 =item C<connectdb> ( )
1837  
1838 *** NEEDS ERROR HANDLER ****
1839  
1840 Called as a static method, it just returns the DBH Object.
1841  
1842 =cut
1843 sub connectdb {
1844 my $self = shift;
1845 my $class = ref($self) || $self;
1846 no strict 'refs';
1847 my $dclass = $self->dataclass( $class );
1848 my @connect = @{ "${dclass}::connectarray" };
1849 @connect = @DATABASE::connectarray unless @connect;
1850 my $dbh = DBI->connect( @connect ) || return $self->error_handler("Could not connect to the database @connect " . DBI->errstr . "\n");
1851 $dbh->do("alter session set NLS_DATE_FORMAT = 'Mon DD YYYY HH12:MI:SSAM'") if ($dbh->{'Driver'}->{'Name'} eq 'Oracle');
1852 return $dbh;
1853 } # END sub connectdb
1854  
1855  
1856 =item C<pkd> ( )
1857  
1858 Returns a constant for the primary key delimiter.
1859  
1860 =cut
1861 sub pkd { return '~' }
1862  
1863  
1864 =item C<date_format> ( )
1865  
1866 Returns a constant, the strftime template for what date strings are to be
1867 displayed as.
1868  
1869 =cut
1870 sub date_format { return '%d %b %Y %T' }
1871  
1872  
1873 =item C<str2time> ( $string )
1874  
1875 This is method is used to parse your default date format into a format
1876 that str2time understands, such as:
1877  
1878 Date: 961221 (yymmdd)
1879 Date: 12-21-96 (mm-dd-yy) ( '-', '.' or '/' )
1880 Date: 12-June-96 (dd-month-yy) ( '-', '.' or '/' )
1881 Date: June 12 96 00:00PM (month dd yy hh:mmPM)
1882 Date: June 12 96 00::00:00 (month dd yy hh:mm::ss)
1883  
1884 If time is not passed then time defaults to 00:00:00.
1885  
1886 =cut
1887 sub str2time {
1888 my $self = shift;
1889 my $string = shift;
1890  
1891 Date::Parse::str2time( $string );
1892 } # END sub str2time
1893  
1894  
1895 =back
1896  
1897 =cut
1898  
1899 ################################################################################
1900 ################################# SQL Methods: #################################
1901 ################################################################################
1902  
1903  
1904 =head2 SQL GENERATION METHODS
1905  
1906 =over 4
1907  
1908 =item C<sql_select> ( [ $dbh, ] $SELECT [, \@bindings] )
1909  
1910 Excutes the prepared select statement and returns an arrayref of objects. The @bindings
1911 array contains values of SQL placeholders if used. Returns a code reference that will
1912 return a hashref when dereferenced.
1913  
1914 =cut
1915 sub sql_select {
1916 my $self = shift;
1917 my $class = ref($self) || $self;
1918 my $dbh = ref($self) ? $self->dbh : shift;
1919 ref($dbh) || return $self->error_handler('BingoX::Carbon::sql_select called without dbh object');
1920 my $SELECT = shift || return $self->error_handler("In ${class}::sql_select(), called without SELECT statement");
1921 my $bindings = shift;
1922 my @bindings = ref($bindings) ? @$bindings : ( );
1923 warn "$class->sql_select:\t\t\"$SELECT\" [@bindings]\n" if ($debug);
1924 my $sth;
1925 $sth = $dbh->prepare( $SELECT ) || return $self->error_handler("In ${class}::sql_select(), prepare\n$SELECT;\n" . $dbh->errstr . "\n\n");
1926 $sth->execute( @bindings ) || return $self->error_handler("In ${class}::sql_select(), execute\n$SELECT;\n" . $sth->errstr . "\n\n");
1927 return ($dbh->{'Driver'}->{'Name'} eq 'Oracle')
1928 ? (bless(sub { # Oracle version (slower!)
1929 if ($_[0]) {
1930 $sth->finish if (defined $sth);
1931 undef $sth;
1932 return undef;
1933 }
1934 return undef unless ($sth->{'Active'});
1935 my $resultdata = $sth->fetchrow_hashref;
1936 unless (ref($resultdata) eq 'HASH') {
1937 $sth->finish;
1938 return undef;
1939 }
1940 my $data = {
1941 map {
1942 (((join ' ',@{ $class->fieldorder }) =~ /\b($_)\b/i)[0] || $_) => $resultdata->{$_}
1943 } keys %$resultdata
1944 };
1945 return $data;
1946 }, 'BingoX::Carbon::Stream'))
1947 : (bless(
1948 sub { # Normal version
1949 if ($_[0]) {
1950 $sth->finish if (defined $sth);
1951 undef $sth;
1952 return undef;
1953 }
1954 return undef unless ($sth->{'Active'});
1955 my $data = $sth->fetchrow_hashref;
1956 unless (ref($data) eq 'HASH') {
1957 $sth->finish;
1958 return undef;
1959 }
1960 return $data;
1961 }, 'BingoX::Carbon::Stream'
1962 ));
1963 } # END sub sql_select
1964  
1965  
1966 =item C<format_select> ( [ $dbh, ] \%params, \@fields, \@sort [, $alias ] )
1967  
1968 Returns formatted SQL 'SELECT' statement, selecting @fields that meet all specifications
1969 in %params, sorted by @sort. Also returns bindings of all dynamic placeholders in SQL statement.
1970 Optionally, $alias may specify the table alias to be used in the statment
1971 (" WHERE alias.name = 'myname'"). Sub-values should be surrounded by ##,
1972 ie "name LIKE ##me##", for conditions involving: ( LIKE, NOT, <, >, SELECT )
1973 Finally, and sort terms may be reversed (made descending) by prepending them with a '-'. (e.g.,
1974 to sort by 'col1' ascending and 'col2' descending, pass 'qw(col1 -col2)'.)
1975  
1976 For instructions on the format of \%params, see L<"item_format_conditions">.
1977  
1978 =cut
1979 sub format_select {
1980 my $self = shift;
1981 my $class = ref($self) || $self;
1982 my $dbh = ref($self) ? $self->dbh : shift;
1983 my $params = shift;
1984 my $fields = shift || $class->primary_keys;
1985 my $sort = shift;
1986 my $alias = shift;
1987 ## make sure we have params ##
1988 return undef unless ((ref $params eq 'HASH') || (ref $params eq 'ARRAY'));
1989 $fields = $class->primary_keys unless ($#{ $fields } >= 0);
1990 $fields = join(', ', grep { $_ } @{ $fields });
1991 my $table = $class->table;
1992 $table .= " $alias" if ($alias);
1993 my ($WHERE, @bindings);
1994 if ((defined $params) && (((ref($params) eq 'HASH') && %{ $params }) || (ref($params) eq 'ARRAY' && @{ $params }))) {
1995 ($WHERE, @bindings) = $class->format_conditions( $params, $alias );
1996 return $self->error_handler('select conditions failed') unless (defined $WHERE);
1997 }
1998  
1999 # Don't complain to me about the lowercase SQL
2000 # -- for some reason the caps screw up on views in Oracle 8i (doesn't make
2001 # much sense to me)
2002 my @order = (
2003 'select',
2004 $fields,
2005 'from',
2006 $table
2007 );
2008  
2009 push(@order, $WHERE) if ($WHERE);
2010 if (ref($sort) && (grep { $_ } @{ $sort })) {
2011 ## ORDER ##
2012 push(@order, 'ORDER BY ' . join(', ', map { substr($_,0,1) eq '-' ? substr($_,1) . ' DESC' : $_ } @{ $sort }));
2013 }
2014 my $SELECT = join(' ', @order);
2015 warn "$class->format_select:\t\t\"$SELECT\" [@bindings]\n" if ($debug);
2016 return($SELECT, @bindings);
2017 } # END sub format_select
2018  
2019  
2020 =item C<format_conditions> ( [ $dbh, ] \%params [, $alias ] )
2021  
2022 Returns formatted sql 'WHERE' block, and an array of values to be bound (passed to
2023 DBI->execute().) Optionally, $alias may specify the table alias to be used in the statment
2024 (" WHERE alias.name = 'myname'"). The keys of %params are the fields you are trying to match;
2025 the values of %params are specified as follows :
2026  
2027 =back
2028  
2029 =over 4
2030  
2031 =item * equality condition
2032  
2033 To test one equality, simply pass the value you wish to match as the value.
2034  
2035 e.g. :
2036  
2037 { $field => 12 }
2038 { $field => 'twelve' }
2039  
2040 =item * inequalities or multiple equalities (LIKE, NOT, <, >, IN, BETWEEN)
2041  
2042 Sub-values should be surrounded by ##, ie "name LIKE ##me##", for conditions involving:
2043 ( LIKE, NOT, <, > ).
2044  
2045 To use IN or BETWEEN (with or without NOT), params should contain something similar
2046 to ( $field => [ $type, @LIST ] ) where $type is '[NOT ]IN' or '[NOT ]BETWEEN' and
2047 @LIST is the set of values for the statement.
2048  
2049 =item * NULL/NOT NULL conditions
2050  
2051 To test for a NULL condition or NOT NULL condition, pass 'IS NULL' or 'IS NOT NULL'
2052 (respectively) as the value.
2053  
2054 e.g. :
2055  
2056 { $field => 'IS NOT NULL' }
2057  
2058 =item * subqueries
2059  
2060 When using a SELECT statement in an IN block, the argument immediately following the select
2061 statement should be the arrayref containing any bindings for that statement.
2062 This means that you may use the output of format_conditions as the input for a subquery :
2063  
2064 $conditions = $obj_class1->format_conditions(
2065 $dbh,
2066 {
2067 $field => [
2068 'IN',
2069 $obj_class2->format_conditions( $dbh, $field => $value )
2070 ]
2071 }
2072 );
2073  
2074 =item * multiple values
2075  
2076 To match multiple conditions, pass an arrayref (that does not begin with 'IN' or 'BETWEEN'!)
2077 containing a list of conditions (any of the conditions above.) You MUST delimit each condition
2078 with either '&&' (for AND) or '||' (for OR), and you may also use '(' or ')' to separate logical
2079 conditions.
2080  
2081 e.g. :
2082  
2083 { $field => [ 1, '||', '(', 2, '&&', 3, ')' ] }
2084  
2085 =back
2086  
2087 =cut
2088 sub format_conditions {
2089 my $self = shift;
2090 my $class = ref($self) || $self;
2091 my $dbh = ref($self) ? $self->dbh : shift;
2092 my $params = ((ref $dbh eq 'HASH') || (ref $dbh eq 'ARRAY')) ? $dbh : (shift || { });
2093 my $alias = shift;
2094 my $order;
2095 ## Allow caller to specify order (and logical operation) of parameters ##
2096 if (ref $params eq 'ARRAY') {
2097 ($order, $params) = @$params;
2098 if (@$order) { # add parameters not specified in list
2099 my %tmpparams = %$params;
2100 map { delete $tmpparams{$_} } @$order;
2101 if (%tmpparams) { # %tmpparams remaining are parameters not in $order list
2102 unshift @$order, '(';
2103 push @$order, (')', 'AND', split (' ', join(' AND ', keys %tmpparams)));
2104 }
2105 } else { # order list empty!
2106 $order = [ split (' ', join(' AND ', keys %$params)) ];
2107 }
2108 } elsif (ref $params eq 'HASH') {
2109 $order = [ split (' ', join(' AND ', keys %$params)) ];
2110 } else { # make sure we have params
2111 return undef;
2112 }
2113  
2114 ## parse each field and add to SQL statement ##
2115 my ($WHERE, @query, @bindings);
2116 foreach my $field (@$order) {
2117 if (($field eq 'AND') || ($field eq 'OR') || ($field eq '(') || $field eq ')') {
2118 next if (($field =~ /^(?:AND|OR)$/o) && (!@query || ($query[$#query] =~ /^(?:AND|OR)$/o)));
2119 next if (($field =~ /^(?:\(|\))$/o) && ($query[$#query] =~ /^(?:\(|\))$/o));
2120 push @query, $field;
2121 next;
2122 }
2123 ## make sure field is in params ##
2124 unless (defined $class->deffields->{$field}) {
2125 pop @query;
2126 next;
2127 }
2128 ## enforce precedence ##
2129 my $sql = '('; # ) loathe BBEdit
2130  
2131 my @valuelist = $params->{$field};
2132 next unless (defined $valuelist[0]);
2133  
2134 ## add relation prefix if $r_flag ##
2135 $field = "${alias}.${field}" if $alias;
2136 for (my $x = 0; $x <= $#valuelist; $x++) {
2137 my $value = $valuelist[$x];
2138 if (ref($value) eq 'ARRAY') { # IN, BETWEEN, or multiple comparisons
2139 my ( $type, @values ) = @{ $value };
2140 if (substr(lc($type), -2) eq 'in') { # 'IN' or 'NOT IN'
2141 return $self->error_handler("no bindings passed to format_conditions for type ($type)")
2142 unless (@values);
2143 my (@IN_bindings, @IN_sql);
2144 while (my $value = shift(@values)) {
2145 if (lc(substr($value, 0, 6)) eq 'select') {
2146 push (@IN_sql, $value);
2147 push (@IN_bindings, splice(@values, 0, $#values + 1)); # $/
2148 } else {
2149 push (@IN_sql, '?');
2150 push (@IN_bindings, $value);
2151 }
2152 }
2153 $sql .= "$field " . uc($type) . ' (' . join(', ', @IN_sql) . ')';
2154 push(@bindings, @IN_bindings);
2155 } elsif (substr(lc($type), -7) eq 'between') { # 'BETWEEN' or 'NOT BETWEEN'
2156 return $self->error_handler("no bindings passed to format_conditions for type ($type)")
2157 unless (@values);
2158 $sql .= "$field " . uc($type) . ' ? AND ?';
2159 push(@bindings, @values[0,1]);
2160 } else { # LIST of conditions
2161 splice (@valuelist, $x+1, 0, @$value); # appending will push to next iterations
2162 }
2163 } elsif ($value =~ /^\/(.+?)\/$/) { # regex
2164 $sql .= "$field ~ ?";
2165 push(@bindings, $1);
2166 } elsif ($value =~ /^(\d+?)-(\d+?)$/) { # date or numeric range
2167 $sql .= "($field > ? AND $field < ?)";
2168 push(@bindings, $1, $2);
2169 } elsif ($value eq '&&') { # AND
2170 $sql .= ' AND ';
2171 } elsif ($value eq '||') { # OR
2172 $sql .= ' OR ';
2173 # BEGIN BBEdit loathing
2174 } elsif ($value eq '(') # Open paren ) loathe BBedit
2175 { # loathe BBedit here, too!
2176 $sql .= '('; # ) loathe BBedit
2177 } # loathe BBedit here, too! # ( loathe BBedit
2178 elsif ($value eq ')') { # Close paren ( loathe BBedit
2179 $sql .= ')'; # END BBEdit loathing
2180 } elsif (lc($value) =~ /^(?:like|not|is)\s|<|>/) { # Allow LIKE,NOT,IS,<,>,<=,>= blindly
2181 if ($value =~ /##/) {
2182 while ($value =~ s/##(.+?)##/?/o) {
2183 push(@bindings, $1);
2184 }
2185 }
2186 $sql .= "$field $value"; # can use with embeded SELECT
2187 ### Why do we need this code? Uncomment if you change the else!
2188 # } elsif ($value =~ /^-?(?:\d+?)\.?(?:\d*?)$/) { # exact match number
2189 # $sql .= "$field = ?";
2190 # push(@bindings, $value);
2191 ###
2192 } else { # exact match lexical
2193 $sql .= "$field = ?";
2194 push(@bindings, $value);
2195 }
2196 } # END for (multiple values loop)
2197 ## enforce precedence ( ##
2198 $sql .= ')';
2199  
2200 ## add to array to be joined later ##
2201 push(@query, $sql) if ($sql ne '()');
2202 } # END foreach (fields loop)
2203  
2204 $WHERE = 'WHERE ' . join(' ', @query) if (@query);
2205 warn "$class->format_conditions:\t\"$WHERE\" [@bindings]\n" if ($debug);
2206 return ($WHERE, @bindings);
2207 } # END sub format_conditions
2208  
2209  
2210 =head2 AUTOLOAD
2211  
2212 =over 4
2213  
2214 =item AUTOLOAD
2215  
2216 AUTOLOAD method - returns requested field data from object.
2217 If that requested data has not been cached, it is retrieved from the
2218 database, cached, and returned. If data is passed then field value is
2219 modified in the database and instance data, and value is returned.
2220  
2221  
2222 =cut
2223 sub AUTOLOAD {
2224 my $self = shift;
2225 ref($self) || return $self->error_handler("In ${self}::AUTOLOAD($AUTOLOAD)\n$self is not an object\n\n");
2226 my $class = ref($self);
2227  
2228 return if ($AUTOLOAD =~ /::DESTROY$/);
2229 my $name = substr($AUTOLOAD, rindex($AUTOLOAD, ':') + 1); # strip fully-qualified portion
2230
2231 return undef unless ($name);
2232 if ($self->can( $name )) { # Accessor method already exists!
2233 local($AUTOLOAD) = $AUTOLOAD; # This means I was called as SUPER::$name
2234 $self->_old_school_autoload( @_ ); # Act like an AUTOLOAD should!
2235 } else { # No accessor method
2236 $class->_create_access_method( $name ); # Make a fresh one
2237 $self->$name( @_ ); # Now call it
2238 }
2239 } # END sub AUTOLOAD
2240  
2241  
2242 =begin private_method
2243  
2244 _create_access_method($name)
2245 - dynamically creates accessor method for method $name
2246 - called by AUTOLOAD() or import()
2247  
2248 =end private_method
2249  
2250 =cut
2251 sub _create_access_method {
2252 my $self = shift;
2253 my $class = ref($self) || $self;
2254 my $name = shift;
2255 my $return = 0;
2256 return undef unless ($name);
2257 if ($name eq 'AUTOLOAD') { # No method constuction, just
2258 no strict 'refs'; # make the plain old AUTOLOAD
2259 if ($class->can('AUTOLOAD')) {
2260 $return = $class->can('AUTOLOAD');
2261 undef *{"${class}::AUTOLOAD"};
2262 }
2263 *{"${class}::AUTOLOAD"} = \&BingoX::Carbon::_old_school_autoload;
2264  
2265 } elsif ($class->can($name)) { # Already there!
2266 warn "access method '${class}::$name' already exists" if ($debug);
2267 } else { # Let's make a method today! (Excited yet?)
2268 warn "creating access method '${class}::$name'..." if ($debug);
2269 eval qq`
2270 no strict 'refs';
2271 *{"${class}::$name"} = sub {
2272 my \$self = shift;
2273 my \$class = ref(\$self) || return undef;
2274 if (defined(my \$data = shift)) {
2275 \$self->modify({$name => \$data})
2276 || return \$self->error_handler("In dynamic method $name()\n\tmodify({$name => \$data}) failed\n\n\t");
2277 \$self->{'$name'} = \$data;
2278 } elsif (!exists \$self->{'$name'}) {
2279 map { ('$name' eq \$_) && return \$self->error_handler("In dynamic method $name()\n\tBingoX::Carbon ABUSE! Object in class $class has no value for primary key $name in instance data!\n\n\t") }
2280 \@{ \$self->primary_keys };
2281 my \%params = map { \$_ => \$self->\$_() } (\@{ \$self->primary_keys });
2282 my \$aref = \$self->list_array( \\\%params, ['$name'] );
2283 \$self->{'$name'} = \$aref->[0]->[0];
2284 }
2285 return \$self->{'$name'};
2286 };
2287 `;
2288 }
2289 return $return;
2290 } # END sub _create_access_method
2291  
2292  
2293 =begin private_method
2294  
2295 _create_forwarder_method($name)
2296 - dynamically creates accessor method for method $name
2297 - called by AUTOLOAD() or import()
2298  
2299 =end private_method
2300  
2301 =cut
2302 sub _create_forwarder_method {
2303 my $self = shift;
2304 my $class = ref($self) || $self;
2305 my $name = shift;
2306 my $return = 0;
2307 return undef unless ($name);
2308 if ($name eq 'AUTOLOAD') { # No method constuction, just
2309 no strict 'refs'; # make the plain old AUTOLOAD
2310 if ($class->can('AUTOLOAD')) {
2311 $return = $class->can('AUTOLOAD');
2312 undef *{"${class}::AUTOLOAD"};
2313 }
2314 *{"${class}::AUTOLOAD"} = \&BingoX::Carbon::_old_school_autoload;
2315  
2316 } elsif ($class->can($name)) { # Already there!
2317 warn "forwarder method '${class}::$name' already exists" if ($debug);
2318 } else { # Let's make a method today! (Excited yet?)
2319 warn "creating forwarder method '${class}::$name'..." if ($debug);
2320 eval qq`
2321 no strict 'refs';
2322 *{"${class}::$name"} = sub {
2323 local(\$AUTOLOAD) = '$name';
2324 my \$self = shift;
2325 return \$self->_old_school_autoload( \@_ );
2326 };
2327 `;
2328 }
2329 return $return;
2330 } # END sub _create_forwarder_method
2331  
2332  
2333 =begin private_method
2334  
2335 _old_school_autoload
2336 - this is what AUTOLOAD() used to be (this is your father's AUTOLOAD)
2337 - loading BingoX::Carbon with the ':no_dynmeth' tag will assign
2338 $class::AUTOLOAD to this method
2339  
2340 =end private_method
2341  
2342 =cut
2343 sub _old_school_autoload {
2344 my $self = shift;
2345 ref($self) || return $self->error_handler("In " . $self . "::AUTOLOAD()\n$self is not an object\n\n");
2346 my $class = ref($self);
2347  
2348 return if ($AUTOLOAD =~ /::DESTROY$/o);
2349 my $name = substr($AUTOLOAD, rindex($AUTOLOAD, ':') + 1); # strip fully-qualified portion
2350  
2351 ## Check to see if valid field name ##
2352 exists $self->deffields->{ $name }
2353 || return $self->error_handler("In AUTOLOAD()\n\tMethod $name not defined in class $class\n\n\t");
2354  
2355 if (defined(my $data = shift)) { # Data passed -- call modify()
2356 $self->modify({ $name => $data })
2357 || return $self->error_handler("In AUTOLOAD()\n\tmodify({$name => $data}) failed\n\n\t");
2358 } elsif (!exists $self->{ $name }) { # No data passed or cached, retrieve from database
2359 ## Check for nasty BingoX::Carbon abuse ##
2360 map { ($name eq $_) && return $class->error_handler("In AUTOLOAD()\n\tBingoX::Carbon ABUSE! Object in class $class has no value for primary key $name in instance data!\n\n\t") }
2361 @{ $self->primary_keys };
2362 my %params = map { $_ => $self->$_() } (@{ $self->primary_keys });
2363 my $aref = $self->list_array( \%params, [$name] );
2364 $self->{$name} = $aref->[0]->[0];
2365 }
2366 return $self->{$name};
2367 } # END sub _old_school_autoload
2368  
2369 =begin private_method
2370  
2371 _content> ( $content_class, $column, $content )
2372  
2373 Object Method:
2374 If $content (optional) is passed, the content will either be reomoved
2375 or modified in the db. If no content is passed, then the content will
2376 be selected from the db.
2377  
2378 =end private_method
2379  
2380 =cut
2381 sub _content {
2382 my $self = shift;
2383 return undef unless (ref $self);
2384 my $content_class = shift;
2385 my $content = shift;
2386 my $params;
2387 if (ref($content) eq 'HASH') {
2388 $params = $content;
2389 $content = undef;
2390 } else {
2391 $params = shift || {};
2392 }
2393 my $content_column = delete $params->{'_column'} || 'content'; # standard content column name
2394 my $pos_column = delete $params->{'_pos'} || 'pos'; # standard position column name
2395 map { $params->{$_} = $self->$_() } @{ $self->primary_keys };
2396 if (defined $content) {
2397 my @split_content;
2398 ## splits the content string into 255 char elements into array ##
2399 unless ($content eq '') {
2400 my $pos = 0;
2401 for ($pos = 0; $pos <= length($content); $pos += 255) {
2402 push(@split_content, substr($content, $pos, 255));
2403 }
2404 }
2405 my $dbh = $self->dbh();
2406 local $dbh->{'AutoCommit'} = 0; # BEGIN TRANSACTION
2407 eval {
2408 local $dbh->{'RaiseError'} = 1;
2409 $content_class->rm( $self->dbh, $params ) || die "Could not remove existing content field value " . $dbh->errstr();
2410  
2411 unless ($content eq '') {
2412 for (0 .. $#split_content) {
2413 warn "ADDING CONTENT: $content_class => " . $split_content[$_] if ($debug > 2);
2414 $content_class->new(
2415 $self->dbh,
2416 {
2417 %$params,
2418 $pos_column => $_ + 1,
2419 $content_column => $split_content[$_]
2420 }
2421 ) || die "Could not add content field value " . $dbh->errstr();
2422 }
2423 }
2424 $self->{ $content_class } = $content;
2425 }; # END of EVAL
2426  
2427 if ($@) { # if failure
2428 $dbh->rollback();
2429 return $self->error_handler("Failed to add content - $@"); # give error
2430 }
2431 return 1;
2432 } else {
2433 return join('', map { $_->[0] }
2434 @{ $content_class->list_array(
2435 $self->dbh,
2436 $params,
2437 [ $content_column ],
2438 [ $pos_column ]
2439 ) || [ ]
2440 }
2441 );
2442 }
2443 1;
2444 } # END sub _content
2445  
2446  
2447 =item C<int_to_bitmap> ( $int )
2448  
2449 Returns a 32-bit bit-string which corresponds to the integer $int.
2450  
2451 =cut
2452 sub int_to_bitmap {
2453 unpack ('B32', pack('N', ($_[1] || $_[0])));
2454 } # END sub int_to_bitmap
2455  
2456  
2457 =item C<bitmap_to_int> ( $bitmap )
2458  
2459 Returns an integer that corresponds to the (at most) 32-bit bit-string $bitmap.
2460  
2461 =cut
2462 sub bitmap_to_int {
2463 unpack ('N', pack('B32', substr("0" x 32 . ($_[1] || $_[0]), -32)));
2464 } # END sub bitmap_to_int
2465  
2466 =item C<get_list_hash> ( )
2467  
2468 =item C<get_list_hash> ( [ $dbh ] [, \%params ] )
2469  
2470 If used as a static method then you must pass $dbh.
2471  
2472 Returns a hash ref of all the objects in the class it was called against.
2473 The hash is built from the C<cpkey>, and the C<title_field>, substr()'d to
2474 the C<title_size> or by default 80 chars.
2475  
2476  
2477 B<OPTIMIZE>
2478  
2479 =cut
2480 sub get_list_hash {
2481 my $self = shift;
2482 my $class = ref($self) || $self;
2483 my $dbh = ref($self) ? $self->dbh : shift;
2484 ref($dbh) || return $self->error_handler('BingoX::Carbon::stream_obj called without dbh object');
2485 my $params = shift || { };
2486  
2487  
2488 my $title_size = $class->title_size || 80;
2489 my $title_field = $class->title_field;
2490 my $fields = $class->primary_keys;
2491 my $sort = [ ];
2492 unless ($class->content_fields->{ $title_field }) {
2493 push(@$fields, $title_field);
2494 $sort = [ $title_field ];
2495 }
2496  
2497 my $stream = $class->stream_obj(
2498 $dbh,
2499 $params,
2500 $fields,
2501 $sort
2502 );
2503  
2504 my $hash = { };
2505 while (my $obj = $stream->()) {
2506 $hash->{ $obj->cpkey }
2507 = length($obj->$title_field()) > $title_size
2508 ? substr($obj->$title_field(), 0, ($title_size - 3)) . '...'
2509 : $obj->$title_field();
2510 }
2511  
2512 warn Data::Dumper::Dumper( $hash ) if ($debug > 2);
2513 return $hash;
2514 } # END sub get_list_hash
2515  
2516  
2517 =begin private_method
2518  
2519 initializes content methods
2520  
2521 =end private_method
2522  
2523 =cut
2524 sub _content_meth_init {
2525 my $class = shift;
2526 my $contentfields = shift || $class->contentfields;
2527 foreach my $field (keys %$contentfields) {
2528 next if $class->can($field);
2529 ## CREATE DYNAMIC ACCESS METHOD ##
2530 no strict 'refs';
2531 *{"${class}::$field"} =
2532 sub {
2533 my $self = shift;
2534 return undef unless (ref $self);
2535 warn "CONTENT: $field => '" . $_[0] . "'" if ($debug);
2536 $self->_content( $contentfields->{ $field }, @_ );
2537 };
2538 }
2539 } # END sub _content_meth_init
2540  
2541  
2542 =begin private_method
2543  
2544 initializes date methods. Makes a lot of assumptions. The main date
2545 format is in Sybase. If not it assumes that the date format is in a
2546 string format as that of strftime.
2547  
2548 =end private_method
2549  
2550 =cut
2551 sub _date_meth_init {
2552 my $class = shift;
2553 if (my $datefields = $class->datefields) {
2554 foreach my $field (keys %$datefields) {
2555 next if $class->can($field);
2556 ## CREATE DYNAMIC ACCESS METHOD ##
2557 eval qq`
2558 package $class;
2559 \*{ $field } =
2560 sub {
2561 my \$self = shift;
2562 return undef unless ref(\$self);
2563 my \$data = shift;
2564 my \$date;
2565 if (ref \$data) {
2566 \$date = \$data;
2567 } else {
2568 \$date = BingoX::Time->new( \$data );
2569 }
2570  
2571 if (defined \$data) {
2572 \$self->modify({ $field => \$date->time2str( \$self->date_format ) });
2573 } else {
2574 my \$meth = "SUPER::$field";
2575 my \$value = \$self->\$meth();
2576 my \$time_local = \$self->str2time( \$value );
2577 \$date = (\$value ? BingoX::Time->new( \$time_local ) : undef);
2578 }
2579  
2580 return \$date;
2581 }; # END sub
2582 `;
2583 }
2584 }
2585 } # END sub _date_meth_init
2586  
2587  
2588 package BingoX::Carbon::Stream;
2589  
2590 # Objects are constructed in the BingoX::Carbon::stream_obj method above.
2591 sub next {
2592 my $self = shift;
2593 return $self->();
2594 } # END sub next
2595  
2596 sub close {
2597 my $self = shift;
2598 return $self->(1);
2599 } # END sub close
2600  
2601  
2602 1;
2603  
2604 __END__