1package Class::DBI::__::Base; 2 3require 5.00502; 4 5use Class::Trigger 0.07; 6use base qw(Class::Accessor Class::Data::Inheritable Ima::DBI); 7 8package Class::DBI; 9 10use strict; 11 12use base "Class::DBI::__::Base"; 13 14use vars qw($VERSION); 15$VERSION = '0.96'; 16 17use Class::DBI::ColumnGrouper; 18use Class::DBI::Query; 19use Carp (); 20use List::Util; 21use UNIVERSAL::moniker; 22 23use vars qw($Weaken_Is_Available); 24 25BEGIN { 26 $Weaken_Is_Available = 1; 27 eval { 28 require Scalar::Util; 29 import Scalar::Util qw(weaken); 30 }; 31 if ($@) { 32 $Weaken_Is_Available = 0; 33 } 34} 35 36use overload 37 '""' => sub { shift->stringify_self }, 38 bool => sub { not shift->_undefined_primary }, 39 fallback => 1; 40 41sub stringify_self { 42 my $self = shift; 43 return (ref $self || $self) unless $self; # empty PK 44 my @cols = $self->columns('Stringify'); 45 @cols = $self->primary_columns unless @cols; 46 return join "/", $self->get(@cols); 47} 48 49sub _undefined_primary { 50 my $self = shift; 51 return grep !defined, $self->_attrs($self->primary_columns); 52} 53 54{ 55 my %deprecated = ( 56 croak => "_croak", # 0.89 57 carp => "_carp", # 0.89 58 min => "minimum_value_of", # 0.89 59 max => "maximum_value_of", # 0.89 60 normalize_one => "_normalize_one", # 0.89 61 _primary => "primary_column", # 0.90 62 primary => "primary_column", # 0.89 63 primary_key => "primary_column", # 0.90 64 essential => "_essential", # 0.89 65 column_type => "has_a", # 0.90 66 associated_class => "has_a", # 0.90 67 is_column => "find_column", # 0.90 68 has_column => "find_column", # 0.94 69 add_hook => "add_trigger", # 0.90 70 run_sql => "retrieve_from_sql", # 0.90 71 rollback => "discard_changes", # 0.91 72 commit => "update", # 0.91 73 autocommit => "autoupdate", # 0.91 74 new => 'create', # 0.93 75 _commit_vals => '_update_vals', # 0.91 76 _commit_line => '_update_line', # 0.91 77 make_filter => 'add_constructor', # 0.93 78 ); 79 80 no strict 'refs'; 81 while (my ($old, $new) = each %deprecated) { 82 *$old = sub { 83 my @caller = caller; 84 warn 85 "Use of '$old' is deprecated at $caller[1] line $caller[2]. Use '$new' instead\n"; 86 goto &$new; 87 }; 88 } 89} 90 91sub normalize { shift->_carp("normalize is deprecated") } # 0.94 92sub normalize_hash { shift->_carp("normalize_hash is deprecated") } # 0.94 93 94#---------------------------------------------------------------------- 95# Our Class Data 96#---------------------------------------------------------------------- 97__PACKAGE__->mk_classdata('__AutoCommit'); 98__PACKAGE__->mk_classdata('__hasa_list'); 99__PACKAGE__->mk_classdata('_table'); 100__PACKAGE__->mk_classdata('_table_alias'); 101__PACKAGE__->mk_classdata('sequence'); 102__PACKAGE__->mk_classdata('__grouper'); 103__PACKAGE__->mk_classdata('__data_type'); 104__PACKAGE__->mk_classdata('__driver'); 105__PACKAGE__->__data_type({}); 106 107__PACKAGE__->mk_classdata('iterator_class'); 108__PACKAGE__->iterator_class('Class::DBI::Iterator'); 109__PACKAGE__->__grouper(Class::DBI::ColumnGrouper->new()); 110 111__PACKAGE__->mk_classdata('purge_object_index_every'); 112__PACKAGE__->purge_object_index_every(1000); 113 114__PACKAGE__->add_relationship_type( 115 has_a => "Class::DBI::Relationship::HasA", 116 has_many => "Class::DBI::Relationship::HasMany", 117 might_have => "Class::DBI::Relationship::MightHave", 118); 119__PACKAGE__->mk_classdata('__meta_info'); 120__PACKAGE__->__meta_info({}); 121 122#---------------------------------------------------------------------- 123# SQL we'll need 124#---------------------------------------------------------------------- 125__PACKAGE__->set_sql(MakeNewObj => <<''); 126INSERT INTO __TABLE__ (%s) 127VALUES (%s) 128 129__PACKAGE__->set_sql(update => <<""); 130UPDATE __TABLE__ 131SET %s 132WHERE __IDENTIFIER__ 133 134__PACKAGE__->set_sql(Nextval => <<''); 135SELECT NEXTVAL ('%s') 136 137__PACKAGE__->set_sql(SearchSQL => <<''); 138SELECT %s 139FROM %s 140WHERE %s 141 142__PACKAGE__->set_sql(RetrieveAll => <<''); 143SELECT __ESSENTIAL__ 144FROM __TABLE__ 145 146__PACKAGE__->set_sql(Retrieve => <<''); 147SELECT __ESSENTIAL__ 148FROM __TABLE__ 149WHERE %s 150 151__PACKAGE__->set_sql(Flesh => <<''); 152SELECT %s 153FROM __TABLE__ 154WHERE __IDENTIFIER__ 155 156__PACKAGE__->set_sql(single => <<''); 157SELECT %s 158FROM __TABLE__ 159 160__PACKAGE__->set_sql(DeleteMe => <<""); 161DELETE 162FROM __TABLE__ 163WHERE __IDENTIFIER__ 164 165 166# Override transform_sql from Ima::DBI to provide some extra 167# transformations 168sub transform_sql { 169 my ($self, $sql, @args) = @_; 170 171 my %cmap; 172 my $expand_table = sub { 173 my ($class, $alias) = split /=/, shift, 2; 174 my $table = $class ? $class->table : $self->table; 175 $cmap{ $alias || $table } = $class || ref $self || $self; 176 ($alias ||= "") &&= " AS $alias"; 177 return $table . $alias; 178 }; 179 180 my $expand_join = sub { 181 my $joins = shift; 182 my @table = split /\s+/, $joins; 183 my %tojoin = map { $table[$_] => $table[ $_ + 1 ] } 0 .. $#table - 1; 184 my @sql; 185 while (my ($t1, $t2) = each %tojoin) { 186 my ($c1, $c2) = map $cmap{$_} 187 || $self->_croak("Don't understand table '$_' in JOIN"), ($t1, $t2); 188 189 my $join_col = sub { 190 my ($c1, $c2) = @_; 191 my $meta = $c1->meta_info('has_a'); 192 my ($col) = grep $meta->{$_}->foreign_class eq $c2, keys %$meta; 193 $col; 194 }; 195 196 my $col = $join_col->($c1 => $c2) || do { 197 ($c1, $c2) = ($c2, $c1); 198 ($t1, $t2) = ($t2, $t1); 199 $join_col->($c1 => $c2); 200 }; 201 202 $self->_croak("Don't know how to join $c1 to $c2") unless $col; 203 push @sql, sprintf " %s.%s = %s.%s ", $t1, $col, $t2, 204 $c2->primary_column; 205 } 206 return join " AND ", @sql; 207 }; 208 209 $sql =~ s/__TABLE\(?(.*?)\)?__/$expand_table->($1)/eg; 210 $sql =~ s/__JOIN\((.*?)\)__/$expand_join->($1)/eg; 211 $sql =~ s/__ESSENTIAL__/join ", ", $self->_essential/eg; 212 $sql =~ 213 s/__ESSENTIAL\((.*?)\)__/join ", ", map "$1.$_", $self->_essential/eg; 214 if ($sql =~ /__IDENTIFIER__/) { 215 my $key_sql = join " AND ", map "$_=?", $self->primary_columns; 216 $sql =~ s/__IDENTIFIER__/$key_sql/g; 217 } 218 return $self->SUPER::transform_sql($sql => @args); 219} 220 221#---------------------------------------------------------------------- 222# EXCEPTIONS 223#---------------------------------------------------------------------- 224 225sub _carp { 226 my ($self, $msg) = @_; 227 Carp::carp($msg || $self); 228 return; 229} 230 231sub _croak { 232 my ($self, $msg) = @_; 233 Carp::croak($msg || $self); 234} 235 236#---------------------------------------------------------------------- 237# SET UP 238#---------------------------------------------------------------------- 239 240sub connection { 241 my $class = shift; 242 $class->set_db(Main => @_); 243} 244 245{ 246 my %Per_DB_Attr_Defaults = ( 247 pg => { AutoCommit => 0 }, 248 oracle => { AutoCommit => 0 }, 249 ); 250 251 sub _default_attributes { 252 my $class = shift; 253 return ( 254 $class->SUPER::_default_attributes, 255 FetchHashKeyName => 'NAME_lc', 256 ShowErrorStatement => 1, 257 AutoCommit => 1, 258 ChopBlanks => 1, 259 %{ $Per_DB_Attr_Defaults{ lc $class->__driver } || {} }, 260 ); 261 } 262} 263 264sub set_db { 265 my ($class, $db_name, $data_source, $user, $password, $attr) = @_; 266 267 # 'dbi:Pg:dbname=foo' we want 'Pg'. I think this is enough. 268 my ($driver) = $data_source =~ /^dbi:(\w+)/i; 269 $class->__driver($driver); 270 $class->SUPER::set_db('Main', $data_source, $user, $password, $attr); 271} 272 273sub table { 274 my ($proto, $table, $alias) = @_; 275 my $class = ref $proto || $proto; 276 $class->_table($table) if $table; 277 $class->table_alias($alias) if $alias; 278 return $class->_table || $class->_table($class->table_alias); 279} 280 281sub table_alias { 282 my ($proto, $alias) = @_; 283 my $class = ref $proto || $proto; 284 $class->_table_alias($alias) if $alias; 285 return $class->_table_alias || $class->_table_alias($class->moniker); 286} 287 288sub columns { 289 my $proto = shift; 290 my $class = ref $proto || $proto; 291 my $group = shift || "All"; 292 return $class->_set_columns($group => @_) if @_; 293 return $class->all_columns if $group eq "All"; 294 return $class->primary_column if $group eq "Primary"; 295 return $class->_essential if $group eq "Essential"; 296 return $class->__grouper->group_cols($group); 297} 298 299sub _set_columns { 300 my ($class, $group, @columns) = @_; 301 302 # Careful to take copy 303 $class->__grouper(Class::DBI::ColumnGrouper->clone($class->__grouper) 304 ->add_group($group => @columns)); 305 $class->_mk_column_accessors(@columns); 306 return @columns; 307} 308 309sub all_columns { shift->__grouper->all_columns } 310 311sub id { 312 my $self = shift; 313 my $class = ref($self) 314 or return $self->_croak("Can't call id() as a class method"); 315 316 # we don't use get() here because all objects should have 317 # exisitng values for PK columns, or else loop endlessly 318 my @pk_values = $self->_attrs($self->primary_columns); 319 return @pk_values if wantarray; 320 $self->_croak( 321 "id called in scalar context for class with multiple primary key columns") 322 if @pk_values > 1; 323 return $pk_values[0]; 324} 325 326sub primary_column { 327 my $self = shift; 328 my @primary_columns = $self->__grouper->primary; 329 return @primary_columns if wantarray; 330 $self->_carp( 331 ref($self) 332 . " has multiple primary columns, but fetching in scalar context") 333 if @primary_columns > 1; 334 return $primary_columns[0]; 335} 336*primary_columns = \&primary_column; 337 338sub _essential { shift->__grouper->essential } 339 340sub find_column { 341 my ($class, $want) = @_; 342 return $class->__grouper->find_column($want); 343} 344 345sub _find_columns { 346 my $class = shift; 347 my $cg = $class->__grouper; 348 return map $cg->find_column($_), @_; 349} 350 351sub has_real_column { # is really in the database 352 my ($class, $want) = @_; 353 return ($class->find_column($want) || return)->in_database; 354} 355 356sub data_type { 357 my $class = shift; 358 my %datatype = @_; 359 while (my ($col, $type) = each %datatype) { 360 $class->_add_data_type($col, $type); 361 } 362} 363 364sub _add_data_type { 365 my ($class, $col, $type) = @_; 366 my $datatype = $class->__data_type; 367 $datatype->{$col} = $type; 368 $class->__data_type($datatype); 369} 370 371# Make a set of accessors for each of a list of columns. We construct 372# the method name by calling accessor_name() and mutator_name() with the 373# normalized column name. 374 375# mutator_name will be the same as accessor_name unless you override it. 376 377# If both the accessor and mutator are to have the same method name, 378# (which will always be true unless you override mutator_name), a read-write 379# method is constructed for it. If they differ we create both a read-only 380# accessor and a write-only mutator. 381 382sub _mk_column_accessors { 383 my $class = shift; 384 foreach my $obj ($class->_find_columns(@_)) { 385 my %method = ( 386 ro => $obj->accessor($class->accessor_name($obj->name)), 387 wo => $obj->mutator($class->mutator_name($obj->name)), 388 ); 389 my $both = ($method{ro} eq $method{wo}); 390 foreach my $type (keys %method) { 391 my $name = $method{$type}; 392 my $acc_type = $both ? "make_accessor" : "make_${type}_accessor"; 393 my $accessor = $class->$acc_type($obj->name_lc); 394 $class->_make_method($_, $accessor) for ($name, "_${name}_accessor"); 395 } 396 } 397} 398 399sub _make_method { 400 my ($class, $name, $method) = @_; 401 return if defined &{"$class\::$name"}; 402 $class->_carp("Column '$name' in $class clashes with built-in method") 403 if Class::DBI->can($name) 404 and not($name eq "id" and join(" ", $class->primary_columns) eq "id"); 405 no strict 'refs'; 406 *{"$class\::$name"} = $method; 407 $class->_make_method(lc $name => $method); 408} 409 410sub accessor_name { 411 my ($class, $column) = @_; 412 return $column; 413} 414 415sub mutator_name { 416 my ($class, $column) = @_; 417 return $class->accessor_name($column); 418} 419 420sub autoupdate { 421 my $proto = shift; 422 ref $proto ? $proto->_obj_autoupdate(@_) : $proto->_class_autoupdate(@_); 423} 424 425sub _obj_autoupdate { 426 my ($self, $set) = @_; 427 my $class = ref $self; 428 $self->{__AutoCommit} = $set if defined $set; 429 defined $self->{__AutoCommit} 430 ? $self->{__AutoCommit} 431 : $class->_class_autoupdate; 432} 433 434sub _class_autoupdate { 435 my ($class, $set) = @_; 436 $class->__AutoCommit($set) if defined $set; 437 return $class->__AutoCommit; 438} 439 440sub make_read_only { 441 my $proto = shift; 442 $proto->add_trigger("before_$_" => sub { _croak "$proto is read only" }) 443 foreach qw/create delete update/; 444 return $proto; 445} 446 447sub find_or_create { 448 my $class = shift; 449 my $hash = ref $_[0] eq "HASH" ? shift: {@_}; 450 my ($exists) = $class->search($hash); 451 return defined($exists) ? $exists : $class->create($hash); 452} 453 454sub create { 455 my $class = shift; 456 return $class->_croak("create needs a hashref") unless ref $_[0] eq 'HASH'; 457 my $info = { %{ +shift } }; # make sure we take a copy 458 459 my $data; 460 while (my ($k, $v) = each %$info) { 461 my $col = $class->find_column($k) 462 || (List::Util::first { $_->mutator eq $k } $class->columns) 463 || (List::Util::first { $_->accessor eq $k } $class->columns) 464 || $class->_croak("$k is not a column of $class"); 465 $data->{$col} = $v; 466 } 467 468 $class->normalize_column_values($data); 469 $class->validate_column_values($data); 470 return $class->_create($data); 471} 472 473sub _attrs { 474 my ($self, @atts) = @_; 475 return @{$self}{@atts}; 476} 477*_attr = \&_attrs; 478 479sub _attribute_store { 480 my $self = shift; 481 my $vals = @_ == 1 ? shift: {@_}; 482 my (@cols) = keys %$vals; 483 @{$self}{@cols} = @{$vals}{@cols}; 484} 485 486# If you override this method, you must use the same mechanism to log changes 487# for future updates, as other parts of Class::DBI depend on it. 488sub _attribute_set { 489 my $self = shift; 490 my $vals = @_ == 1 ? shift: {@_}; 491 492 # We increment instead of setting to 1 because it might be useful to 493 # someone to know how many times a value has changed between updates. 494 for my $col (keys %$vals) { $self->{__Changed}{$col}++; } 495 $self->_attribute_store($vals); 496} 497 498sub _attribute_delete { 499 my ($self, @attributes) = @_; 500 delete @{$self}{@attributes}; 501} 502 503sub _attribute_exists { 504 my ($self, $attribute) = @_; 505 exists $self->{$attribute}; 506} 507 508# keep an index of live objects using weak refs 509my %Live_Objects; 510my $Init_Count = 0; 511 512sub _init { 513 my $class = shift; 514 my $data = shift || {}; 515 my $obj; 516 my $obj_key = ""; 517 518 my @primary_columns = $class->primary_columns; 519 if (@primary_columns == grep defined, @{$data}{@primary_columns}) { 520 521 # create single unique key for this object 522 $obj_key = join "|", $class, map { $_ . '=' . $data->{$_} } 523 sort @primary_columns; 524 } 525 526 unless (defined($obj = $Live_Objects{$obj_key})) { 527 528 # not in the object_index, or we don't have all keys yet 529 $obj = bless {}, $class; 530 $obj->_attribute_store(%$data); 531 532 # don't store it unless all keys are present 533 if ($obj_key && $Weaken_Is_Available) { 534 weaken($Live_Objects{$obj_key} = $obj); 535 536 # time to clean up your room? 537 $class->purge_dead_from_object_index 538 if ++$Init_Count % $class->purge_object_index_every == 0; 539 } 540 } 541 542 return $obj; 543} 544 545sub purge_dead_from_object_index { 546 delete @Live_Objects{ grep !defined $Live_Objects{$_}, keys %Live_Objects }; 547} 548 549sub remove_from_object_index { 550 my $self = shift; 551 my @primary_columns = $self->primary_columns; 552 my %data; 553 @data{@primary_columns} = $self->get(@primary_columns); 554 my $obj_key = join "|", ref $self, map $_ . '=' . $data{$_}, 555 sort @primary_columns; 556 delete $Live_Objects{$obj_key}; 557} 558 559sub clear_object_index { 560 %Live_Objects = (); 561} 562 563sub _prepopulate_id { 564 my $self = shift; 565 my @primary_columns = $self->primary_columns; 566 return $self->_croak( 567 sprintf "Can't create %s object with null primary key columns (%s)", 568 ref $self, $self->_undefined_primary) 569 if @primary_columns > 1; 570 $self->_attribute_store($primary_columns[0] => $self->_next_in_sequence) 571 if $self->sequence; 572} 573 574sub _create { 575 my ($proto, $data) = @_; 576 my $class = ref $proto || $proto; 577 578 my $self = $class->_init($data); 579 $self->call_trigger('before_create'); 580 $self->call_trigger('deflate_for_create'); 581 582 $self->_prepopulate_id if $self->_undefined_primary; 583 584 # Reinstate data 585 my ($real, $temp) = ({}, {}); 586 foreach my $col (grep $self->_attribute_exists($_), $self->all_columns) { 587 ($class->has_real_column($col) ? $real : $temp)->{$col} = 588 $self->_attrs($col); 589 } 590 $self->_insert_row($real); 591 592 my @primary_columns = $class->primary_columns; 593 $self->_attribute_store( 594 $primary_columns[0] => $real->{ $primary_columns[0] }) 595 if @primary_columns == 1; 596 597 delete $self->{__Changed}; 598 599 my %primary_columns; 600 @primary_columns{@primary_columns} = (); 601 my @discard_columns = grep !exists $primary_columns{$_}, keys %$real; 602 $self->call_trigger('create', discard_columns => \@discard_columns); # XXX 603 604 # Empty everything back out again! 605 $self->_attribute_delete(@discard_columns); 606 $self->call_trigger('after_create'); 607 return $self; 608} 609 610sub _next_in_sequence { 611 my $self = shift; 612 return $self->sql_Nextval($self->sequence)->select_val; 613} 614 615sub _auto_increment_value { 616 my $self = shift; 617 my $dbh = $self->db_Main; 618 619 # the DBI will provide a standard attribute soon, meanwhile... 620 my $id = $dbh->{mysql_insertid} # mysql 621 || eval { $dbh->func('last_insert_rowid') }; # SQLite 622 $self->_croak("Can't get last insert id") unless defined $id; 623 return $id; 624} 625 626sub _insert_row { 627 my $self = shift; 628 my $data = shift; 629 eval { 630 my @columns = keys %$data; 631 my $sth = $self->sql_MakeNewObj( 632 join(', ', @columns), 633 join(', ', map $self->_column_placeholder($_), @columns), 634 ); 635 $self->_bind_param($sth, \@columns); 636 $sth->execute(values %$data); 637 my @primary_columns = $self->primary_columns; 638 $data->{ $primary_columns[0] } = $self->_auto_increment_value 639 if @primary_columns == 1 640 && !defined $data->{ $primary_columns[0] }; 641 }; 642 if ($@) { 643 my $class = ref $self; 644 return $self->_croak( 645 "Can't insert new $class: $@", 646 err => $@, 647 method => 'create' 648 ); 649 } 650 return 1; 651} 652 653sub _bind_param { 654 my ($class, $sth, $keys) = @_; 655 my $datatype = $class->__data_type or return; 656 for my $i (0 .. $#$keys) { 657 if (my $type = $datatype->{ $keys->[$i] }) { 658 $sth->bind_param($i + 1, undef, $type); 659 } 660 } 661} 662 663sub retrieve { 664 my $class = shift; 665 my @primary_columns = $class->primary_columns 666 or return $class->_croak( 667 "Can't retrieve unless primary columns are defined"); 668 my %key_value; 669 if (@_ == 1 && @primary_columns == 1) { 670 my $id = shift; 671 return unless defined $id; 672 return $class->_croak("Can't retrieve a reference") if ref($id); 673 $key_value{ $primary_columns[0] } = $id; 674 } else { 675 %key_value = @_; 676 $class->_croak( 677 "$class->retrieve(@_) parameters don't include values for all primary key columns (@primary_columns)" 678 ) 679 if keys %key_value < @primary_columns; 680 } 681 my @rows = $class->search(%key_value); 682 $class->_carp("$class->retrieve(@_) selected " . @rows . " rows") 683 if @rows > 1; 684 return $rows[0]; 685} 686 687# Get the data, as a hash, but setting certain values to whatever 688# we pass. Used by copy() and move(). 689# This can take either a primary key, or a hashref of all the columns 690# to change. 691sub _data_hash { 692 my $self = shift; 693 my @columns = $self->all_columns; 694 my %data; 695 @data{@columns} = $self->get(@columns); 696 my @primary_columns = $self->primary_columns; 697 delete @data{@primary_columns}; 698 if (@_) { 699 my $arg = shift; 700 unless (ref $arg) { 701 $self->_croak("Need hash-ref to edit copied column values") 702 unless @primary_columns == 1; 703 $arg = { $primary_columns[0] => $arg }; 704 } 705 @data{ keys %$arg } = values %$arg; 706 } 707 return \%data; 708} 709 710sub copy { 711 my $self = shift; 712 return $self->create($self->_data_hash(@_)); 713} 714 715#---------------------------------------------------------------------- 716# CONSTRUCT 717#---------------------------------------------------------------------- 718 719sub construct { 720 my ($proto, $data) = @_; 721 my $class = ref $proto || $proto; 722 my $self = $class->_init($data); 723 $self->call_trigger('select'); 724 return $self; 725} 726 727sub move { 728 my ($class, $old_obj, @data) = @_; 729 $class->_carp("move() is deprecated. If you really need it, " 730 . "you should tell me quickly so I can abandon my plan to remove it."); 731 return $old_obj->_croak("Can't move to an unrelated class") 732 unless $class->isa(ref $old_obj) 733 or $old_obj->isa($class); 734 return $class->create($old_obj->_data_hash(@data)); 735} 736 737sub delete { 738 my $self = shift; 739 return $self->_search_delete(@_) if not ref $self; 740 $self->call_trigger('before_delete'); 741 742 eval { $self->sql_DeleteMe->execute($self->id) }; 743 if ($@) { 744 return $self->_croak("Can't delete $self: $@", err => $@); 745 } 746 $self->call_trigger('after_delete'); 747 undef %$self; 748 bless $self, 'Class::DBI::Object::Has::Been::Deleted'; 749 return 1; 750} 751 752sub _search_delete { 753 my ($class, @args) = @_; 754 $class->_carp( 755 "Delete as class method is deprecated. Use search and delete_all instead." 756 ); 757 my $it = $class->search_like(@args); 758 while (my $obj = $it->next) { $obj->delete } 759 return 1; 760} 761 762# Return the placeholder to be used in UPDATE and INSERT queries. 763# Overriding this is deprecated in favour of 764# __PACKAGE__->find_column('entered')->placeholder('IF(1, CURDATE(), ?)); 765 766sub _column_placeholder { 767 my ($self, $column) = @_; 768 return $self->find_column($column)->placeholder; 769} 770 771sub update { 772 my $self = shift; 773 my $class = ref($self) 774 or return $self->_croak("Can't call update as a class method"); 775 776 $self->call_trigger('before_update'); 777 return 1 unless my @changed_cols = $self->is_changed; 778 $self->call_trigger('deflate_for_update'); 779 my @primary_columns = $self->primary_columns; 780 my $sth = $self->sql_update($self->_update_line); 781 $class->_bind_param($sth, \@changed_cols); 782 my $rows = eval { $sth->execute($self->_update_vals, $self->id); }; 783 return $self->_croak("Can't update $self: $@", err => $@) if $@; 784 785 # enable this once new fixed DBD::SQLite is released: 786 if (0 and $rows != 1) { # should always only update one row 787 $self->_croak("Can't update $self: row not found") if $rows == 0; 788 $self->_croak("Can't update $self: updated more than one row"); 789 } 790 791 $self->call_trigger('after_update', discard_columns => \@changed_cols); 792 793 # delete columns that changed (in case adding to DB modifies them again) 794 $self->_attribute_delete(@changed_cols); 795 delete $self->{__Changed}; 796 return 1; 797} 798 799sub _update_line { 800 my $self = shift; 801 join(', ', map "$_ = " . $self->_column_placeholder($_), $self->is_changed); 802} 803 804sub _update_vals { 805 my $self = shift; 806 $self->_attrs($self->is_changed); 807} 808 809sub DESTROY { 810 my ($self) = shift; 811 if (my @changed = $self->is_changed) { 812 my $class = ref $self; 813 $self->_carp("$class $self destroyed without saving changes to " 814 . join(', ', @changed)); 815 } 816} 817 818sub discard_changes { 819 my $self = shift; 820 return $self->_croak("Can't discard_changes while autoupdate is on") 821 if $self->autoupdate; 822 $self->_attribute_delete($self->is_changed); 823 delete $self->{__Changed}; 824 return 1; 825} 826 827# We override the get() method from Class::Accessor to fetch the data for 828# the column (and associated) columns from the database, using the _flesh() 829# method. We also allow get to be called with a list of keys, instead of 830# just one. 831 832sub get { 833 my $self = shift; 834 return $self->_croak("Can't fetch data as class method") unless ref $self; 835 836 my @cols = $self->_find_columns(@_); 837 return $self->_croak("Can't get() nothing!") unless @cols; 838 839 if (my @fetch_cols = grep !$self->_attribute_exists($_), @cols) { 840 $self->_flesh($self->__grouper->groups_for(@fetch_cols)); 841 } 842 843 return $self->_attrs(@cols); 844} 845 846sub _flesh { 847 my ($self, @groups) = @_; 848 my @real = grep $_ ne "TEMP", @groups; 849 if (my @want = grep !$self->_attribute_exists($_), 850 $self->__grouper->columns_in(@real)) { 851 my %row; 852 @row{@want} = $self->sql_Flesh(join ", ", @want)->select_row($self->id); 853 $self->_attribute_store(\%row); 854 $self->call_trigger('select'); 855 } 856 return 1; 857} 858 859# We also override set() from Class::Accessor so we can keep track of 860# changes, and either write to the database now (if autoupdate is on), 861# or when update() is called. 862sub set { 863 my $self = shift; 864 my $column_values = {@_}; 865 866 $self->normalize_column_values($column_values); 867 $self->validate_column_values($column_values); 868 869 while (my ($column, $value) = each %$column_values) { 870 my $col = $self->find_column($column) or die "No such column: $column\n"; 871 $self->_attribute_set($col => $value); 872 873 # $self->SUPER::set($column, $value); 874 875 eval { $self->call_trigger("after_set_$column") }; # eg inflate 876 if ($@) { 877 $self->_attribute_delete($column); 878 return $self->_croak("after_set_$column trigger error: $@", err => $@); 879 } 880 } 881 882 $self->update if $self->autoupdate; 883 return 1; 884} 885 886sub is_changed { 887 my $self = shift; 888 grep $self->has_real_column($_), keys %{ $self->{__Changed} }; 889} 890 891sub any_changed { keys %{ shift->{__Changed} } } 892 893# By default do nothing. Subclasses should override if required. 894# 895# Given a hash ref of column names and proposed new values, 896# edit the values in the hash if required. 897# For create $self is the class name (not an object ref). 898sub normalize_column_values { 899 my ($self, $column_values) = @_; 900} 901 902# Given a hash ref of column names and proposed new values 903# validate that the whole set of new values in the hash 904# is valid for the object in relation to its current values 905# For create $self is the class name (not an object ref). 906sub validate_column_values { 907 my ($self, $column_values) = @_; 908 my @errors; 909 foreach my $column (keys %$column_values) { 910 eval { 911 $self->call_trigger("before_set_$column", $column_values->{$column}, 912 $column_values); 913 }; 914 push @errors, $column => $@ if $@; 915 } 916 return unless @errors; 917 $self->_croak( 918 "validate_column_values error: " . join(" ", @errors), 919 method => 'validate_column_values', 920 data => {@errors} 921 ); 922} 923 924# We override set_sql() from Ima::DBI so it has a default database connection. 925sub set_sql { 926 my ($class, $name, $sql, $db, @others) = @_; 927 $db ||= 'Main'; 928 $class->SUPER::set_sql($name, $sql, $db, @others); 929 $class->_generate_search_sql($name) if $sql =~ /select/i; 930 return 1; 931} 932 933sub _generate_search_sql { 934 my ($class, $name) = @_; 935 my $method = "search_$name"; 936 defined &{"$class\::$method"} 937 and return $class->_carp("$method() already exists"); 938 my $sql_method = "sql_$name"; 939 no strict 'refs'; 940 *{"$class\::$method"} = sub { 941 my ($class, @args) = @_; 942 return $class->sth_to_objects($name, \@args); 943 }; 944} 945 946sub dbi_commit { my $proto = shift; $proto->SUPER::commit(@_); } 947sub dbi_rollback { my $proto = shift; $proto->SUPER::rollback(@_); } 948 949#---------------------------------------------------------------------- 950# Constraints / Triggers 951#---------------------------------------------------------------------- 952 953sub constrain_column { 954 my $class = shift; 955 my $col = $class->find_column(+shift) 956 or return $class->_croak("constraint_column needs a valid column"); 957 my $how = shift 958 or return $class->_croak("constrain_column needs a constraint"); 959 if (ref $how eq "ARRAY") { 960 my %hash = map { $_ => 1 } @$how; 961 $class->add_constraint(list => $col => sub { exists $hash{ +shift } }); 962 } elsif (ref $how eq "Regexp") { 963 $class->add_constraint(regexp => $col => sub { shift =~ $how }); 964 } else { 965 my $try_method = sprintf '_constrain_by_%s', $how->moniker; 966 if (my $dispatch = $class->can($try_method)) { 967 $class->$dispatch($col => ($how, @_)); 968 } else { 969 $class->_croak("Don't know how to constrain $col with $how"); 970 } 971 } 972} 973 974sub add_constraint { 975 my $class = shift; 976 $class->_invalid_object_method('add_constraint()') if ref $class; 977 my $name = shift or return $class->_croak("Constraint needs a name"); 978 my $column = $class->find_column(+shift) 979 or return $class->_croak("Constraint $name needs a valid column"); 980 my $code = shift 981 or return $class->_croak("Constraint $name needs a code reference"); 982 return $class->_croak("Constraint $name '$code' is not a code reference") 983 unless ref($code) eq "CODE"; 984 985 $column->is_constrained(1); 986 $class->add_trigger( 987 "before_set_$column" => sub { 988 my ($self, $value, $column_values) = @_; 989 $code->($value, $self, $column, $column_values) 990 or return $self->_croak( 991 "$class $column fails '$name' constraint with '$value'"); 992 } 993 ); 994} 995 996sub add_trigger { 997 my ($self, $name, @args) = @_; 998 return $self->_croak("on_setting trigger no longer exists") 999 if $name eq "on_setting"; 1000 $self->_carp( 1001 "$name trigger deprecated: use before_$name or after_$name instead") 1002 if ($name eq "create" or $name eq "delete"); 1003 $self->SUPER::add_trigger($name => @args); 1004} 1005 1006#---------------------------------------------------------------------- 1007# Inflation 1008#---------------------------------------------------------------------- 1009 1010sub add_relationship_type { 1011 my ($self, %rels) = @_; 1012 while (my ($name, $class) = each %rels) { 1013 $self->_require_class($class); 1014 no strict 'refs'; 1015 *{"$self\::$name"} = sub { 1016 my $proto = shift; 1017 $class->set_up($name => $proto => @_); 1018 }; 1019 } 1020} 1021 1022sub _extend_meta { 1023 my ($class, $type, $subtype, $val) = @_; 1024 my %hash = %{ $class->__meta_info || {} }; 1025 $hash{$type}->{$subtype} = $val; 1026 $class->__meta_info(\%hash); 1027} 1028 1029sub meta_info { 1030 my ($class, $type, $subtype) = @_; 1031 my $meta = $class->__meta_info; 1032 return $meta unless $type; 1033 return $meta->{$type} unless $subtype; 1034 return $meta->{$type}->{$subtype}; 1035} 1036 1037sub _simple_bless { 1038 my ($class, $pri) = @_; 1039 return $class->_init({ $class->primary_column => $pri }); 1040} 1041 1042sub _deflated_column { 1043 my ($self, $col, $val) = @_; 1044 $val ||= $self->_attrs($col) if ref $self; 1045 return $val unless ref $val; 1046 my $meta = $self->meta_info(has_a => $col) or return $val; 1047 my ($a_class, %meths) = ($meta->foreign_class, %{ $meta->args }); 1048 if (my $deflate = $meths{'deflate'}) { 1049 $val = $val->$deflate(ref $deflate eq 'CODE' ? $self : ()); 1050 return $val unless ref $val; 1051 } 1052 return $self->_croak("Can't deflate $col: $val is not a $a_class") 1053 unless UNIVERSAL::isa($val, $a_class); 1054 return $val->id if UNIVERSAL::isa($val => 'Class::DBI'); 1055 return "$val"; 1056} 1057 1058#---------------------------------------------------------------------- 1059# SEARCH 1060#---------------------------------------------------------------------- 1061 1062sub retrieve_all { shift->sth_to_objects('RetrieveAll') } 1063 1064sub retrieve_from_sql { 1065 my ($class, $sql, @vals) = @_; 1066 $sql =~ s/^\s*(WHERE)\s*//i; 1067 return $class->sth_to_objects($class->sql_Retrieve($sql), \@vals); 1068} 1069 1070sub search_like { shift->_do_search(LIKE => @_) } 1071sub search { shift->_do_search("=" => @_) } 1072 1073sub _do_search { 1074 my ($proto, $search_type, @args) = @_; 1075 my $class = ref $proto || $proto; 1076 1077 @args = %{ $args[0] } if ref $args[0] eq "HASH"; 1078 my (@cols, @vals); 1079 my $search_opts = @args % 2 ? pop @args : {}; 1080 while (my ($col, $val) = splice @args, 0, 2) { 1081 my $column = $class->find_column($col) 1082 || (List::Util::first { $_->accessor eq $col } $class->columns) 1083 || $class->_croak("$col is not a column of $class"); 1084 push @cols, $column; 1085 push @vals, $class->_deflated_column($column, $val); 1086 } 1087 1088 my $frag = join " AND ", 1089 map defined($vals[$_]) ? "$cols[$_] $search_type ?" : "$cols[$_] IS NULL", 1090 0 .. $#cols; 1091 $frag .= " ORDER BY $search_opts->{order_by}" 1092 if $search_opts->{order_by}; 1093 return $class->sth_to_objects($class->sql_Retrieve($frag), 1094 [ grep defined, @vals ]); 1095 1096} 1097 1098#---------------------------------------------------------------------- 1099# CONSTRUCTORS 1100#---------------------------------------------------------------------- 1101 1102sub add_constructor { 1103 my ($class, $method, $fragment) = @_; 1104 return $class->_croak("constructors needs a name") unless $method; 1105 no strict 'refs'; 1106 my $meth = "$class\::$method"; 1107 return $class->_carp("$method already exists in $class") 1108 if *$meth{CODE}; 1109 *$meth = sub { 1110 my $self = shift; 1111 $self->sth_to_objects($self->sql_Retrieve($fragment), \@_); 1112 }; 1113} 1114 1115sub sth_to_objects { 1116 my ($class, $sth, $args) = @_; 1117 $class->_croak("sth_to_objects needs a statement handle") unless $sth; 1118 unless (UNIVERSAL::isa($sth => "DBI::st")) { 1119 my $meth = "sql_$sth"; 1120 $sth = $class->$meth(); 1121 } 1122 my (%data, @rows); 1123 eval { 1124 $sth->execute(@$args) unless $sth->{Active}; 1125 $sth->bind_columns(\(@data{ @{ $sth->{NAME_lc} } })); 1126 push @rows, {%data} while $sth->fetch; 1127 }; 1128 return $class->_croak("$class can't $sth->{Statement}: $@", err => $@) 1129 if $@; 1130 return $class->_ids_to_objects(\@rows); 1131} 1132*_sth_to_objects = \&sth_to_objects; 1133 1134sub _my_iterator { 1135 my $self = shift; 1136 my $class = $self->iterator_class; 1137 $self->_require_class($class); 1138 return $class; 1139} 1140 1141sub _ids_to_objects { 1142 my ($class, $data) = @_; 1143 return $#$data + 1 unless defined wantarray; 1144 return map $class->construct($_), @$data if wantarray; 1145 return $class->_my_iterator->new($class => $data); 1146} 1147 1148#---------------------------------------------------------------------- 1149# SINGLE VALUE SELECTS 1150#---------------------------------------------------------------------- 1151 1152sub _single_row_select { 1153 my ($self, $sth, @args) = @_; 1154 Carp::confess("_single_row_select is deprecated in favour of select_row"); 1155 return $sth->select_row(@args); 1156} 1157 1158sub _single_value_select { 1159 my ($self, $sth, @args) = @_; 1160 $self->_carp("_single_value_select is deprecated in favour of select_val"); 1161 return $sth->select_val(@args); 1162} 1163 1164sub count_all { shift->sql_single("COUNT(*)")->select_val } 1165 1166sub maximum_value_of { 1167 my ($class, $col) = @_; 1168 $class->sql_single("MAX($col)")->select_val; 1169} 1170 1171sub minimum_value_of { 1172 my ($class, $col) = @_; 1173 $class->sql_single("MIN($col)")->select_val; 1174} 1175 1176sub _unique_entries { 1177 my ($class, %tmp) = shift; 1178 return grep !$tmp{$_}++, @_; 1179} 1180 1181sub _invalid_object_method { 1182 my ($self, $method) = @_; 1183 $self->_carp( 1184 "$method should be called as a class method not an object method"); 1185} 1186 1187#---------------------------------------------------------------------- 1188# misc stuff 1189#---------------------------------------------------------------------- 1190 1191sub _extend_class_data { 1192 my ($class, $struct, $key, $value) = @_; 1193 my %hash = %{ $class->$struct() || {} }; 1194 $hash{$key} = $value; 1195 $class->$struct(\%hash); 1196} 1197 1198my %required_classes; # { required_class => class_that_last_required_it, ... } 1199 1200sub _require_class { 1201 my ($self, $load_class) = @_; 1202 $required_classes{$load_class} ||= my $for_class = ref($self) || $self; 1203 1204 # return quickly if class already exists 1205 no strict 'refs'; 1206 return if exists ${"$load_class\::"}{ISA}; 1207 (my $load_module = $load_class) =~ s!::!/!g; 1208 return if eval { require "$load_module.pm" }; 1209 1210 # Only ignore "Can't locate" errors for the specific module we're loading 1211 return if $@ =~ /^Can't locate \Q$load_module\E\.pm /; 1212 1213 # Other fatal errors (syntax etc) must be reported (as per base.pm). 1214 chomp $@; 1215 1216 # This error message prefix is especially handy when dealing with 1217 # classes that are being loaded by other classes recursively. 1218 # The final message shows the path, e.g.: 1219 # Foo can't load Bar: Bar can't load Baz: syntax error at line ... 1220 $self->_croak("$for_class can't load $load_class: $@"); 1221} 1222 1223sub _check_classes { # may automatically call from CHECK block in future 1224 while (my ($load_class, $by_class) = each %required_classes) { 1225 next if $load_class->isa("Class::DBI"); 1226 $by_class->_croak( 1227 "Class $load_class used by $by_class has not been loaded"); 1228 } 1229} 1230 1231#---------------------------------------------------------------------- 1232# Deprecations 1233#---------------------------------------------------------------------- 1234 1235__PACKAGE__->mk_classdata('__hasa_rels'); 1236__PACKAGE__->__hasa_rels({}); 1237 1238sub ordered_search { 1239 shift->_croak( 1240 "Ordered search no longer exists. Pass order_by to search instead."); 1241} 1242 1243sub hasa { 1244 my ($class, $f_class, $f_col) = @_; 1245 $class->_carp( 1246 "hasa() is deprecated in favour of has_a(). Using it instead."); 1247 $class->has_a($f_col => $f_class); 1248} 1249 1250sub hasa_list { 1251 my $class = shift; 1252 $class->_carp("hasa_list() is deprecated in favour of has_many()"); 1253 $class->has_many(@_[ 2, 0, 1 ], { nohasa => 1 }); 1254} 1255 12561; 1257 1258__END__ 1259 1260=head1 NAME 1261 1262 Class::DBI - Simple Database Abstraction 1263 1264=head1 SYNOPSIS 1265 1266 package Music::DBI; 1267 use base 'Class::DBI'; 1268 Music::DBI->connection('dbi:mysql:dbname', 'username', 'password'); 1269 1270 package Music::Artist; 1271 use base 'Music::DBI'; 1272 Music::Artist->table('artist'); 1273 Music::Artist->columns(All => qw/artistid name/); 1274 Music::Artist->has_many(cds => 'Music::CD'); 1275 1276 package Music::CD; 1277 use base 'Music::DBI'; 1278 Music::CD->table('cd'); 1279 Music::CD->columns(All => qw/cdid artist title year/); 1280 Music::CD->has_many(tracks => 'Music::Track'); 1281 Music::CD->has_a(artist => 'Music::Artist'); 1282 Music::CD->has_a(reldate => 'Time::Piece', 1283 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d") }, 1284 deflate => 'ymd', 1285 ); 1286 1287 Music::CD->might_have(liner_notes => LinerNotes => qw/notes/); 1288 1289 package Music::Track; 1290 use base 'Music::DBI'; 1291 Music::Track->table('track'); 1292 Music::Track->columns(All => qw/trackid cd position title/); 1293 1294 #-- Meanwhile, in a nearby piece of code! --# 1295 1296 my $artist = Music::Artist->create({ artistid => 1, name => 'U2' }); 1297 1298 my $cd = $artist->add_to_cds({ 1299 cdid => 1, 1300 title => 'October', 1301 year => 1980, 1302 }); 1303 1304 # Oops, got it wrong. 1305 $cd->year(1981); 1306 $cd->update; 1307 1308 # etc. 1309 1310 foreach my $track ($cd->tracks) { 1311 print $track->position, $track->title 1312 } 1313 1314 $cd->delete; # also deletes the tracks 1315 1316 my $cd = Music::CD->retrieve(1); 1317 my @cds = Music::CD->retrieve_all; 1318 my @cds = Music::CD->search(year => 1980); 1319 my @cds = Music::CD->search_like(title => 'October%'); 1320 1321=head1 INTRODUCTION 1322 1323Class::DBI provides a convenient abstraction layer to a database. 1324 1325It not only provides a simple database to object mapping layer, but can 1326be used to implement several higher order database functions (triggers, 1327referential integrity, cascading delete etc.), at the application level, 1328rather than at the database. 1329 1330This is particularly useful when using a database which doesn't support 1331these (such as MySQL), or when you would like your code to be portable 1332across multiple databases which might implement these things in different 1333ways. 1334 1335In short, Class::DBI aims to make it simple to introduce 'best 1336practice' when dealing with data stored in a relational database. 1337 1338=head2 How to set it up 1339 1340=over 4 1341 1342=item I<Set up a database.> 1343 1344You must have an existing database set up, have DBI.pm installed and 1345the necessary DBD:: driver module for that database. See L<DBI> and 1346the documentation of your particular database and driver for details. 1347 1348=item I<Set up a table for your objects to be stored in.> 1349 1350Class::DBI works on a simple one class/one table model. It is your 1351responsibility to have your database tables already set up. Automating that 1352process is outside the scope of Class::DBI. 1353 1354Using our CD example, you might declare a table something like this: 1355 1356 CREATE TABLE cd ( 1357 cdid INTEGER PRIMARY KEY, 1358 artist INTEGER, # references 'artist' 1359 title VARCHAR(255), 1360 year CHAR(4), 1361 ); 1362 1363=item I<Set up an application base class> 1364 1365It's usually wise to set up a "top level" class for your entire 1366application to inherit from, rather than have each class inherit 1367directly from Class::DBI. This gives you a convenient point to 1368place system-wide overrides and enhancements to Class::DBI's behavior. 1369 1370 package Music::DBI; 1371 use base 'Class::DBI'; 1372 1373=item I<Give it a database connection> 1374 1375Class::DBI needs to know how to access the database. It does this 1376through a DBI connection which you set up by calling the connection() 1377method. 1378 1379 Music::DBI->connection('dbi:mysql:dbname', 'user', 'password'); 1380 1381By setting the connection up in your application base class all the 1382table classes that inherit from it will share the same connection. 1383 1384=item I<Set up each Class> 1385 1386 package Music::CD; 1387 use base 'Music::DBI'; 1388 1389Each class will inherit from your application base class, so you don't 1390need to repeat the information on how to connect to the database. 1391 1392=item I<Declare the name of your table> 1393 1394Inform Class::DBI what table you are using for this class: 1395 1396 Music::CD->table('cd'); 1397 1398=item I<Declare your columns.> 1399 1400This is done using the columns() method. In the simplest form, you tell 1401it the name of all your columns (with the single primary key first): 1402 1403 Music::CD->columns(All => qw/cdid artist title year/); 1404 1405If the primary key of your table spans multiple columns then 1406declare them using a separate call to columns() like this: 1407 1408 Music::CD->columns(Primary => qw/pk1 pk2/); 1409 Music::CD->columns(Others => qw/foo bar baz/); 1410 1411For more information about how you can more efficiently use subsets of 1412your columns, see L</"LAZY POPULATION"> 1413 1414=item I<Done.> 1415 1416That's it! You now have a class with methods to L<\create>(), 1417L<\retrieve>(), L<\search>() for, L<\update>() and L<\delete>() objects 1418from your table, as well as accessors and mutators for each of the 1419columns in that object (row). 1420 1421=back 1422 1423Let's look at all that in more detail: 1424 1425=head1 CLASS METHODS 1426 1427=head2 connection 1428 1429 __PACKAGE__->connection($data_source, $user, $password, \%attr); 1430 1431This sets up a database connection with the given information. 1432 1433This uses Ima::DBI to set up an inheritable connection (named Main). It is 1434therefore usual to only set up a connection() in your application base class 1435and let the 'table' classes inherit from it. 1436 1437 package Music::DBI; 1438 use base 'Class::DBI'; 1439 1440 Music::DBI->connection('dbi:foo:dbname', 'user', 'password'); 1441 1442 package My::Other::Table; 1443 use base 'Music::DBI'; 1444 1445Class::DBI helps you along a bit to set up the database connection. 1446connection() provides its own default attributes depending on the driver 1447name in the data_source parameter. The connection() method provides defaults 1448for these attributes: 1449 1450 FetchHashKeyName => 'NAME_lc', 1451 ShowErrorStatement => 1, 1452 ChopBlanks => 1, 1453 AutoCommit => 1, 1454 1455(Except for Oracle and Pg, where AutoCommit defaults 0, placing the 1456database in transactional mode). 1457 1458The defaults can always be extended (or overridden if you know what 1459you're doing) by supplying your own \%attr parameter. For example: 1460 1461 Music::DBI->connection(dbi:foo:dbname','user','pass',{ChopBlanks=>0}); 1462 1463We use the inherited RootClass of DBIx::ContextualFetch from Ima::DBI, 1464and you should be very careful not to change this unless you know what 1465you're doing! 1466 1467=head3 Dynamic Database Connections / db_Main 1468 1469It is sometimes desirable to generate your database connection information 1470dynamically, for example, to allow multiple databases with the same 1471schema to not have to duplicate an entire class hierarchy. 1472 1473The preferred method for doing this is to supply your own db_Main() 1474method rather than calling L<connection>(). This method should return a 1475valid database handle, and should ensure it sets the standard attributes 1476described above, preferably by combining $class->_default_attributes() 1477with your own. 1478 1479Note that connection information is class data, and that changing it 1480at run time may have unexpected behaviour for instances of the class 1481already in existence. 1482 1483=head2 table 1484 1485 __PACKAGE__->table($table); 1486 1487 $table = Class->table; 1488 $table = $obj->table; 1489 1490An accessor to get/set the name of the database table in which this 1491class is stored. It -must- be set. 1492 1493Table information is inherited by subclasses, but can be overridden. 1494 1495=head2 table_alias 1496 1497 package Shop::Order; 1498 __PACKAGE__->table('orders'); 1499 __PACKAGE__->table_alias('orders'); 1500 1501When Class::DBI constructs SQL, it aliases your table name to a name 1502representing your class. However, if your class's name is an SQL reserved 1503word (such as 'Order') this will cause SQL errors. In such cases you 1504should supply your own alias for your table name (which can, of course, 1505be the same as the actual table name). 1506 1507This can also be passed as a second argument to 'table': 1508 1509 __PACKAGE__-->table('orders', 'orders'); 1510 1511As with table, this is inherited but can be overriden. 1512 1513=head2 sequence / auto_increment 1514 1515 __PACKAGE__->sequence($sequence_name); 1516 1517 $sequence_name = Class->sequence; 1518 $sequence_name = $obj->sequence; 1519 1520If you are using a database which supports sequences and you want to use 1521a sequence to automatically supply values for the primary key of a table, 1522then you should declare this using the sequence() method: 1523 1524 __PACKAGE__->columns(Primary => 'id'); 1525 __PACKAGE__->sequence('class_id_seq'); 1526 1527Class::DBI will use the sequence to generate a primary key value when 1528objects are created without one. 1529 1530*NOTE* This method does not work for Oracle. However, Class::DBI::Oracle 1531(which can be downloaded separately from CPAN) provides a suitable 1532replacement sequence() method. 1533 1534If you are using a database with AUTO_INCREMENT (e.g. MySQL) then you do 1535not need this, and any call to create() without a primary key specified 1536will fill this in automagically. 1537 1538Sequence and auto-increment mechanisms only apply to tables that have 1539a single column primary key. For tables with multi-column primary keys 1540you need to supply the key values manually. 1541 1542=head1 CONSTRUCTORS and DESTRUCTORS 1543 1544The following are methods provided for convenience to create, retrieve 1545and delete stored objects. It's not entirely one-size fits all and you 1546might find it necessary to override them. 1547 1548=head2 create 1549 1550 my $obj = Class->create(\%data); 1551 1552This is a constructor to create a new object and store it in the database. 1553 1554%data consists of the initial information to place in your object and 1555the database. The keys of %data match up with the columns of your 1556objects and the values are the initial settings of those fields. 1557 1558 my $cd = Music::CD->create({ 1559 cdid => 1, 1560 artist => $artist, 1561 title => 'October', 1562 year => 1980, 1563 }); 1564 1565If the table has a single primary key column and that column value 1566is not defined in %data, create() will assume it is to be generated. 1567If a sequence() has been specified for this Class, it will use that. 1568Otherwise, it will assume the primary key can be generated by 1569AUTO_INCREMENT and attempt to use that. 1570 1571The C<before_create> trigger is invoked directly after storing the 1572supplied values into the new object and before inserting the record 1573into the database. The object stored in $self may not have all the 1574functionality of the final object after_creation, particularly if the 1575database is going to be providing the primary key value. 1576 1577For tables with multi-column primary keys you need to supply all 1578the key values, either in the arguments to the create() method, or 1579by setting the values in a C<before_create> trigger. 1580 1581If the class has declared relationships with foreign classes via 1582has_a(), you can pass an object to create() for the value of that key. 1583Class::DBI will Do The Right Thing. 1584 1585After the new record has been inserted into the database the data 1586for non-primary key columns is discarded from the object. If those 1587columns are accessed again they'll simply be fetched as needed. 1588This ensures that the data in the application is consistent with 1589what the database I<actually> stored. 1590 1591The C<after_create> trigger is invoked after the database insert 1592has executed. 1593 1594=head2 find_or_create 1595 1596 my $cd = Music::CD->find_or_create({ artist => 'U2', title => 'Boy' }); 1597 1598This checks if a CD can be found to match the information passed, and 1599if not creates it. 1600 1601=head2 delete 1602 1603 $obj->delete; 1604 Music::CD->search(year => 1980, title => 'Greatest %')->delete_all; 1605 1606Deletes this object from the database and from memory. If you have set up 1607any relationships using has_many, this will delete the foreign elements 1608also, recursively (cascading delete). $obj is no longer usable after 1609this call. 1610 1611Multiple objects can be deleted by calling delete_all on the Iterator 1612returned from a search. Each object found will be deleted in turn, 1613so cascading delete and other triggers will be honoured. 1614 1615The C<before_delete> trigger is when an object instance is about to be 1616deleted. It is invoked before any cascaded deletes. The C<after_delete> 1617trigger is invoked after the record has been deleted from the database 1618and just before the contents in memory are discarded. 1619 1620=head1 RETRIEVING OBJECTS 1621 1622We provide a few simple search methods, more to show the potential of 1623the class than to be serious search methods. 1624 1625=head2 retrieve 1626 1627 $obj = Class->retrieve( $id ); 1628 $obj = Class->retrieve( %key_values ); 1629 1630Given key values it will retrieve the object with that key from the 1631database. For tables with a single column primary key a single 1632parameter can be used, otherwise a hash of key-name key-value pairs 1633must be given. 1634 1635 my $cd = Music::CD->retrieve(1) or die "No such cd"; 1636 1637=head2 retrieve_all 1638 1639 my @objs = Class->retrieve_all; 1640 my $iterator = Class->retrieve_all; 1641 1642Retrieves objects for all rows in the database. This is probably a 1643bad idea if your table is big, unless you use the iterator version. 1644 1645=head2 search 1646 1647 @objs = Class->search(column1 => $value, column2 => $value ...); 1648 1649This is a simple search for all objects where the columns specified are 1650equal to the values specified e.g.: 1651 1652 @cds = Music::CD->search(year => 1990); 1653 @cds = Music::CD->search(title => "Greatest Hits", year => 1990); 1654 1655You may also specify the sort order of the results by adding a final 1656hash of arguments with the key 'order_by': 1657 1658 @cds = Music::CD->search(year => 1990, { order_by=>'artist' }); 1659 1660=head2 search_like 1661 1662 @objs = Class->search_like(column1 => $like_pattern, ....); 1663 1664This is a simple search for all objects where the columns specified are 1665like the values specified. $like_pattern is a pattern given in SQL LIKE 1666predicate syntax. '%' means "any one or more characters", '_' means 1667"any single character". 1668 1669 @cds = Music::CD->search_like(title => 'October%'); 1670 @cds = Music::CD->search_like(title => 'Hits%', artist => 'Various%'); 1671 1672You can also use 'order_by' with these, as with search(). 1673 1674=head1 ITERATORS 1675 1676 my $it = Music::CD->search_like(title => 'October%'); 1677 while (my $cd = $it->next) { 1678 print $cd->title; 1679 } 1680 1681Any of the above searches (as well as those defined by has_many) can also 1682be used as an iterator. Rather than creating a list of objects matching 1683your criteria, this will return a Class::DBI::Iterator instance, which 1684can return the objects required one at a time. 1685 1686Currently the iterator initially fetches all the matching row data into 1687memory, and defers only the creation of the objects from that data until 1688the iterator is asked for the next object. So using an iterator will 1689only save significant memory if your objects will inflate substantially 1690when used. 1691 1692In the case of has_many relationships with a mapping method, the mapping 1693method is not called until each time you call 'next'. This means that 1694if your mapping is not a one-to-one, the results will probably not be 1695what you expect. 1696 1697=head2 Subclassing the Iterator 1698 1699 Music::CD->iterator_class('Music::CD::Iterator'); 1700 1701You can also subclass the default iterator class to override its 1702functionality. This is done via class data, and so is inherited into 1703your subclasses. 1704 1705=head2 QUICK RETRIEVAL 1706 1707 my $obj = Class->construct(\%data); 1708 1709This is used to turn data from the database into objects, and should 1710thus only be used when writing constructors. It is very handy for 1711cheaply setting up lots of objects from data for without going back to 1712the database. 1713 1714For example, instead of doing one SELECT to get a bunch of IDs and then 1715feeding those individually to retrieve() (and thus doing more SELECT 1716calls), you can do one SELECT to get the essential data of many objects 1717and feed that data to construct(): 1718 1719 return map $class->construct($_), $sth->fetchall_hash; 1720 1721The construct() method creates a new empty object, loads in the column 1722values, and then invokes the C<select> trigger. 1723 1724=head1 COPY AND MOVE 1725 1726=head2 copy 1727 1728 $new_obj = $obj->copy; 1729 $new_obj = $obj->copy($new_id); 1730 $new_obj = $obj->copy({ title => 'new_title', rating => 18 }); 1731 1732This creates a copy of the given $obj, removes the primary key, 1733sets any supplied column values and calls create() to insert a new 1734record in the database. 1735 1736For tables with a single column primary key, copy() can be called 1737with no parameters and the new object will be assigned a key 1738automatically. Or a single parameter can be supplied and will be 1739used as the new key. 1740 1741For tables with a multi-olumn primary key, copy() must be called with 1742parameters which supply new values for all primary key columns, unless 1743a C<before_create> trigger will supply them. The create() method will 1744fail if any primary key columns are not defined. 1745 1746 my $blrunner_dc = $blrunner->copy("Bladerunner: Director's Cut"); 1747 my $blrunner_unrated = $blrunner->copy({ 1748 Title => "Bladerunner: Director's Cut", 1749 Rating => 'Unrated', 1750 }); 1751 1752=head2 move 1753 1754 my $new_obj = Sub::Class->move($old_obj); 1755 my $new_obj = Sub::Class->move($old_obj, $new_id); 1756 my $new_obj = Sub::Class->move($old_obj, \%changes); 1757 1758For transferring objects from one class to another. Similar to copy(), an 1759instance of Sub::Class is created using the data in $old_obj (Sub::Class 1760is a subclass of $old_obj's subclass). Like copy(), you can supply 1761$new_id as the primary key of $new_obj (otherwise the usual sequence or 1762autoincrement is used), or a hashref of multiple new values. 1763 1764=head1 TRIGGERS 1765 1766 __PACKAGE__->add_trigger(trigger_point_name => \&code_to_execute); 1767 1768 # e.g. 1769 1770 __PACKAGE__->add_trigger(after_create => \&call_after_create); 1771 1772It is possible to set up triggers that will be called at various 1773points in the life of an object. Valid trigger points are: 1774 1775 before_create (also used for deflation) 1776 after_create 1777 before_set_$column (also used by add_constraint) 1778 after_set_$column (also used for inflation and by has_a) 1779 before_update (also used for deflation and by might_have) 1780 after_update 1781 before_delete 1782 after_delete 1783 select (also used for inflation and by construct and _flesh) 1784 1785You can create any number of triggers for each point, but you cannot 1786specify the order in which they will be run. Each will be passed the 1787object being dealt with (whose values you may change if required), 1788and return values will be ignored. 1789 1790All triggers are passed the object they are being fired for. 1791Some triggers are also passed extra parameters as name-value pairs. 1792The individual triggers are documented with the methods that trigger them. 1793 1794=head1 CONSTRAINTS 1795 1796 __PACKAGE__->add_constraint('name', column => \&check_sub); 1797 1798 # e.g. 1799 1800 __PACKAGE__->add_constraint('over18', age => \&check_age); 1801 1802 # Simple version 1803 sub check_age { 1804 my ($value) = @_; 1805 return $value >= 18; 1806 } 1807 1808 # Cross-field checking - must have SSN if age < 18 1809 sub check_age { 1810 my ($value, $self, $column_name, $changing) = @_; 1811 return 1 if $value >= 18; # We're old enough. 1812 return 1 if $changing->{SSN}; # We're also being given an SSN 1813 return 0 if !ref($self); # This is a create, so we can't have an SSN 1814 return 1 if $self->ssn; # We already have one in the database 1815 return 0; # We can't find an SSN anywhere 1816 } 1817 1818It is also possible to set up constraints on the values that can be set 1819on a column. The constraint on a column is triggered whenever an object 1820is created and whenever the value in that column is being changed. 1821 1822The constraint code is called with four parameters: 1823 1824 - The new value to be assigned 1825 - The object it will be assigned to 1826 (or class name when initially creating an object) 1827 - The name of the column 1828 (useful if many constraints share the same code) 1829 - A hash ref of all new column values being assigned 1830 (useful for cross-field validation) 1831 1832The constraints are applied to all the columns being set before the 1833object data is changed. Attempting to create or modify an object 1834where one or more constraint fail results in an exception and the object 1835remains unchanged. 1836 1837Note 1: Constraints are implemented using before_set_$column triggers. 1838This will only prevent you from setting these values through a 1839the provided create() or set() methods. It will always be possible to 1840bypass this if you try hard enough. 1841 1842Note 2: When an object is created constraints are currently only 1843checked for column names included in the parameters to create(). 1844This is probably a bug and is likely to change in future. 1845 1846=head2 constrain_column 1847 1848 Film->constrain_column(year => qr/\d{4}/); 1849 Film->constrain_column(rating => [qw/U Uc PG 12 15 18/]); 1850 1851Simple anonymous constraints can also be added to a column using the 1852constrain_column() method. By default this takes either a regex which 1853must match, or a reference to a list of possible values. 1854 1855However, this behaviour can be extended (or replaced) by providing a 1856constraint handler for the type of argument passed to constrain_column. 1857This behavior should be provided in a method named "_constrain_by_$type", 1858where $type is the moniker of the argument. For example, the 1859two shown above would be provided by _constrain_by_array() and 1860_constrain_by_regexp(). 1861 1862=head1 DATA NORMALIZATION 1863 1864Before an object is assigned data from the application (via create or 1865a set accessor) the normalize_column_values() method is called with 1866a reference to a hash containing the column names and the new values 1867which are to be assigned (after any validation and constraint checking, 1868as described below). 1869 1870Currently Class::DBI does not offer any per-column mechanism here. 1871The default method is empty. You can override it in your own classes 1872to normalize (edit) the data in any way you need. For example the values 1873in the hash for certain columns could be made lowercase. 1874 1875The method is called as an instance method when the values of an existing 1876object are being changed, and as a class method when a new object is 1877being created. 1878 1879=head1 DATA VALIDATION 1880 1881Before an object is assigned data from the application (via create or 1882a set accessor) the validate_column_values() method is called with a 1883reference to a hash containing the column names and the new values which 1884are to be assigned. 1885 1886The method is called as an instance method when the values of an existing 1887object are being changed, and as a class method when a new object is 1888being created. 1889 1890The default method calls the before_set_$column trigger for each column 1891name in the hash. Each trigger is called inside an eval. Any failures 1892result in an exception after all have been checked. The exception data 1893is a reference to a hash which holds the column name and error text for 1894each trigger error. 1895 1896When using this mechanism for form data validation, for example, 1897this exception data can be stored in an exception object, via a 1898custom _croak() method, and then caught and used to redisplay the 1899form with error messages next to each field which failed validation. 1900 1901=head1 EXCEPTIONS 1902 1903All errors that are generated, or caught and propagated, by Class::DBI 1904are handled by calling the _croak() method (as an instance method 1905if possible, or else as a class method). 1906 1907The _croak() method is passed an error message and in some cases 1908some extra information as described below. The default behaviour 1909is simply to call Carp::croak($message). 1910 1911Applications that require custom behaviour should override the 1912_croak() method in their application base class (or table classes 1913for table-specific behaviour). For example: 1914 1915 use Error; 1916 1917 sub _croak { 1918 my ($self, $message, %info) = @_; 1919 # convert errors into exception objects 1920 # except for duplicate insert errors which we'll ignore 1921 Error->throw(-text => $message, %info) 1922 unless $message =~ /^Can't insert .* duplicate/; 1923 return; 1924 } 1925 1926The _croak() method is expected to trigger an exception and not 1927return. If it does return then it should use C<return;> so that an 1928undef or empty list is returned as required depending on the calling 1929context. You should only return other values if you are prepared to 1930deal with the (unsupported) consequences. 1931 1932For exceptions that are caught and propagated by Class::DBI, $message 1933includes the text of $@ and the original $@ value is available in $info{err}. 1934That allows you to correctly propagate exception objects that may have 1935been thrown 'below' Class::DBI (using Exception::Class::DBI for example). 1936 1937Exceptions generated by some methods may provide additional data in 1938$info{data} and, if so, also store the method name in $info{method}. 1939For example, the validate_column_values() method stores details of 1940failed validations in $info{data}. See individual method documentation 1941for what additional data they may store, if any. 1942 1943=head1 WARNINGS 1944 1945All warnings are handled by calling the _carp() method (as 1946an instance method if possible, or else as a class method). 1947The default behaviour is simply to call Carp::carp(). 1948 1949=head1 INSTANCE METHODS 1950 1951=head2 accessors 1952 1953Class::DBI inherits from Class::Accessor and thus provides individual 1954accessor methods for every column in your subclass. It also overrides 1955the get() and set() methods provided by Accessor to automagically handle 1956database reading and writing. (Note that as it doesn't make sense to 1957store a list of values in a column, set() takes a hash of column => 1958value pairs, rather than the single key => values of Class::Accessor). 1959 1960=head2 the fundamental set() and get() methods 1961 1962 $value = $obj->get($column_name); 1963 @values = $obj->get(@column_names); 1964 1965 $obj->set($column_name => $value); 1966 $obj->set($col1 => $value1, $col2 => $value2 ... ); 1967 1968These methods are the fundamental entry points for getting and setting 1969column values. The extra accessor methods automatically generated for 1970each column of your table are simple wrappers that call these get() 1971and set() methods. 1972 1973The set() method calls normalize_column_values() then 1974validate_column_values() before storing the values. The 1975C<before_set_$column> trigger is invoked by validate_column_values(), 1976checking any constraints that may have been set up. The 1977C<after_set_$column> trigger is invoked after the new value has been 1978stored. 1979 1980It is possible for an object to not have all its column data in memory 1981(due to lazy inflation). If the get() method is called for such a column 1982then it will select the corresponding group of columns and then invoke 1983the C<select> trigger. 1984 1985=head2 Changing Your Column Accessor Method Names 1986 1987=head2 accessor_name / mutator_name 1988 1989If you want to change the name of your accessors, you need to provide an 1990accessor_name() method, which will convert a column name to a method name. 1991 1992e.g: if your local naming convention was to prepend the word 'customer' 1993to each column in the 'customer' table, so that you had the columns 1994'customerid', 'customername' and 'customerage', you would end up with 1995code filled with calls to $customer->customerid, $customer->customername, 1996$customer->customerage etc. By creating an accessor_name method like: 1997 1998 sub accessor_name { 1999 my ($class, $column) = @_; 2000 $column =~ s/^customer//; 2001 return $column; 2002 } 2003 2004Your methods would now be the simpler $customer->id, $customer->name and 2005$customer->age etc. 2006 2007Similarly, if you want to have distinct accessor and mutator methods, 2008you would provide a mutator_name() method which would return the name 2009of the method to change the value: 2010 2011 sub mutator_name { 2012 my ($class, $column) = @_; 2013 return "set_$column"; 2014 } 2015 2016If you override the mutator_name, then the accessor method will be 2017enforced as read-only, and the mutator as write-only. 2018 2019=head2 update vs auto update 2020 2021There are two modes for the accessors to work in: manual update and 2022autoupdate. When in autoupdate mode, every time one calls an accessor 2023to make a change an UPDATE will immediately be sent to the database. 2024Otherwise, if autoupdate is off, no changes will be written until update() 2025is explicitly called. 2026 2027This is an example of manual updating: 2028 2029 # The calls to NumExplodingSheep() and Rating() will only make the 2030 # changes in memory, not in the database. Once update() is called 2031 # it writes to the database in one swell foop. 2032 $gone->NumExplodingSheep(5); 2033 $gone->Rating('NC-17'); 2034 $gone->update; 2035 2036And of autoupdating: 2037 2038 # Turn autoupdating on for this object. 2039 $gone->autoupdate(1); 2040 2041 # Each accessor call causes the new value to immediately be written. 2042 $gone->NumExplodingSheep(5); 2043 $gone->Rating('NC-17'); 2044 2045Manual updating is probably more efficient than autoupdating and 2046it provides the extra safety of a discard_changes() option to clear out all 2047unsaved changes. Autoupdating can be more convenient for the programmer. 2048Autoupdating is I<off> by default. 2049 2050If changes are left un-updated or not rolledback when the object is 2051destroyed (falls out of scope or the program ends) then Class::DBI's 2052DESTROY method will print a warning about unsaved changes. 2053 2054=head2 autoupdate 2055 2056 __PACKAGE__->autoupdate($on_or_off); 2057 $update_style = Class->autoupdate; 2058 2059 $obj->autoupdate($on_or_off); 2060 $update_style = $obj->autoupdate; 2061 2062This is an accessor to the current style of auto-updating. When called 2063with no arguments it returns the current auto-updating state, true for on, 2064false for off. When given an argument it turns auto-updating on and off: 2065a true value turns it on, a false one off. 2066 2067When called as a class method it will control the updating style for 2068every instance of the class. When called on an individual object it 2069will control updating for just that object, overriding the choice for 2070the class. 2071 2072 __PACKAGE__->autoupdate(1); # Autoupdate is now on for the class. 2073 2074 $obj = Class->retrieve('Aliens Cut My Hair'); 2075 $obj->autoupdate(0); # Shut off autoupdating for this object. 2076 2077The update setting for an object is not stored in the database. 2078 2079=head2 update 2080 2081 $obj->update; 2082 2083If L</autoupdate> is not enabled then changes you make to your object are 2084not reflected in the database until you call update(). It is harmless 2085to call update() if there are no changes to be saved. (If autoupdate 2086is on there'll never be anything to save.) 2087 2088Note: If you have transactions turned on for your database (but see 2089L<"TRANSACTIONS"> below) you will also need to call dbi_commit(), as 2090update() merely issues the UPDATE to the database). 2091 2092After the database update has been executed, the data for columns 2093that have been updated are deleted from the object. If those columns 2094are accessed again they'll simply be fetched as needed. This ensures 2095that the data in the application is consistent with what the database 2096I<actually> stored. 2097 2098When update() is called the C<before_update>($self) trigger is 2099always invoked immediately. 2100 2101If any columns have been updated then the C<after_update> trigger 2102is invoked after the database update has executed and is passed: 2103 ($self, discard_columns => \@discard_columns, rows => $rows) 2104 2105(where rows is the return value from the DBI execute() method). 2106 2107The trigger code can modify the discard_columns array to affect 2108which columns are discarded. 2109 2110For example: 2111 2112 Class->add_trigger(after_update => sub { 2113 my ($self, %args) = @_; 2114 my $discard_columns = $args{discard_columns}; 2115 # discard the md5_hash column if any field starting with 'foo' 2116 # has been updated - because the md5_hash will have been changed 2117 # by a trigger. 2118 push @$discard_columns, 'md5_hash' if grep { /^foo/ } @$discard_columns; 2119 }); 2120 2121Take care to not delete a primary key column unless you know what 2122you're doing. 2123 2124The update() method returns the number of rows updated, which should 2125always be 1, or else -1 if no update was needed. If the record in the 2126database has been deleted, or its primary key value changed, then the 2127update will not affect any records and so the update() method will 2128return 0. 2129 2130=head2 discard_changes 2131 2132 $obj->discard_changes; 2133 2134Removes any changes you've made to this object since the last update. 2135Currently this simply discards the column values from the object. 2136 2137If you're using autoupdate this method will throw an exception. 2138 2139=head2 is_changed 2140 2141 my $changed = $obj->is_changed; 2142 my @changed_keys = $obj->is_changed; 2143 2144Indicates if the given $obj has changes since the last update. Returns 2145a list of keys which have changed. (If autoupdate is on, this method 2146will return an empty list, unless called inside a before_update or 2147after_set_$column trigger) 2148 2149=head2 id 2150 2151 $id = $obj->id; 2152 2153Returns a unique identifier for this object. It's the equivalent of 2154$obj->get($self->columns('Primary')); A warning will be generated 2155if this method is used on a table with a multi-column primary key. 2156 2157=head2 LOW-LEVEL DATA ACCESS 2158 2159On some occasions, such as when you're writing triggers or constraint 2160routines, you'll want to manipulate data in a Class::DBI object without 2161using the usual get() and set() accessors, which may themselves call 2162triggers, fetch information from the database, and the like. Rather than 2163intereacting directly with the hash that makes up a Class::DBI object 2164(the exact implementation of which may change in a future release) you 2165should use Class::DBI's low-level accessors. These appear 'private' to 2166make you think carefully about using them - they should not be a common 2167means of dealing with the object. 2168 2169The object is modelled as a set of key-value pairs, where the keys are 2170normalized column names (returned by find_column()), and the values are 2171the data from the database row represented by the object. Access is 2172via these functions: 2173 2174=over 4 2175 2176=item _attrs 2177 2178 @values = $object->_attrs(@cols); 2179 2180Returns the values for one or more keys. 2181 2182=item _attribute_store 2183 2184 $object->_attribute_store( { $col0 => $val0, $col1 => $val1 } ); 2185 $object->_attribute_store($col0, $val0, $col1, $val1); 2186 2187Stores values in the object. They key-value pairs may be passed in 2188either as a simple list or as a hash reference. This only updates 2189values in the object itself; changes will not be propagated to the 2190database. 2191 2192=item _attribute_set 2193 2194 $object->_attribute_set( { $col0 => $val0, $col1 => $val1 } ); 2195 $object->_attribute_set($col0, $val0, $col1, $val1); 2196 2197Updates values in the object via _attribute_store(), but also logs 2198the changes so that they are propagated to the database with the next 2199update. (Unlike set(), however, _attribute_set() will not trigger an 2200update if autoupdate is turned on.) 2201 2202=item _attribute_delete 2203 2204 @values = $object->_attribute_delete(@cols); 2205 2206Deletes values from the object, and returns the deleted values. 2207 2208=item _attribute_exists 2209 2210 $bool = $object->_attribute_exists($col); 2211 2212Returns a true value if the object contains a value for the specified 2213column, and a false value otherwise. 2214 2215=back 2216 2217By default, Class::DBI uses simple hash references to store object 2218data, but all access is via these routines, so if you want to 2219implement a different data model, just override these functions. 2220 2221=head2 OVERLOADED OPERATORS 2222 2223Class::DBI and its subclasses overload the perl builtin I<stringify> 2224and I<bool> operators. This is a significant convenience. 2225 2226The perl builtin I<bool> operator is overloaded so that a Class::DBI 2227object reference is true so long as all its key columns have defined 2228values. (This means an object with an id() of zero is not considered 2229false.) 2230 2231When a Class::DBI object reference is used in a string context it will, 2232by default, return the value of the primary key. (Composite primary key 2233values will be separated by a slash). 2234 2235You can also specify the column(s) to be used for stringification via 2236the special 'Stringify' column group. So, for example, if you're using 2237an auto-incremented primary key, you could use this to provide a more 2238meaningful display string: 2239 2240 Widget->columns(Stringify => qw/name/); 2241 2242If you need to do anything more complex, you can provide an stringify_self() 2243method which stringification will call: 2244 2245 sub stringify_self { 2246 my $self = shift; 2247 return join ":", $self->id, $self->name; 2248 } 2249 2250This overloading behaviour can be useful for columns that have has_a() 2251relationships. For example, consider a table that has price and currency 2252fields: 2253 2254 package Widget; 2255 use base 'My::Class::DBI'; 2256 Widget->table('widget'); 2257 Widget->columns(All => qw/widgetid name price currency_code/); 2258 2259 $obj = Widget->retrieve($id); 2260 print $obj->price . " " . $obj->currency_code; 2261 2262The would print something like "C<42.07 USD>". If the currency_code 2263field is later changed to be a foreign key to a new currency table then 2264$obj->currency_code will return an object reference instead of a plain 2265string. Without overloading the stringify operator the example would now 2266print something like "C<42.07 Widget=HASH(0x1275}>" and the fix would 2267be to change the code to add a call to id(): 2268 2269 print $obj->price . " " . $obj->currency_code->id; 2270 2271However, with overloaded stringification, the original code continues 2272to work as before, with no code changes needed. 2273 2274This makes it much simpler and safer to add relationships to exisiting 2275applications, or remove them later. 2276 2277=head1 TABLE RELATIONSHIPS 2278 2279Databases are all about relationships. And thus Class::DBI provides a 2280way for you to set up descriptions of your relationhips. 2281 2282Currently we provide three such methods: 'has_a', 'has_many', and 2283'might_have'. 2284 2285=head2 has_a 2286 2287 Music::CD->has_a(artist => 'Music::Artist'); 2288 print $cd->artist->name; 2289 2290We generally use 'has_a' to supply lookup information for a foreign 2291key, i.e. we declare that the value we have stored in the column is 2292the primary key of another table. Thus, when we access the 'artist' 2293method we don't just want that ID returned, but instead we inflate it 2294to this other object. 2295 2296However, we can also use has_a to inflate the data value to any 2297other object. A common usage would be to inflate a date field to a 2298Time::Piece object: 2299 2300 Music::CD->has_a(reldate => 'Date::Simple'); 2301 print $cd->reldate->format("%d %b, %Y"); 2302 2303 Music::CD->has_a(reldate => 'Time::Piece', 2304 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d") }, 2305 deflate => 'ymd', 2306 ); 2307 print $cd->reldate->strftime("%d %b, %Y"); 2308 2309If the foreign class is another Class::DBI representation we will 2310call retrieve() on that class with our value. Any other object will be 2311instantiated either by calling new($value) or using the given 'inflate' 2312method. If the inflate method name is a subref, it will be executed, 2313and will be passed the value and the Class::DBI object as arguments. 2314 2315When the object is being written to the database the object will be 2316deflated either by calling the 'deflate' method (if given), or by 2317attempting to stringify the object. If the deflate method is a subref, 2318it will be passed the Class::DBI object as an argument. 2319 2320*NOTE* You should not attempt to make your primary key column inflate 2321using has_a() as bad things will happen. If you have two tables which 2322share a primary key, consider using might_have() instead. 2323 2324=head2 has_many 2325 2326 Class->has_many(method_to_create => "Foreign::Class"); 2327 2328 Music::CD->has_many(tracks => 'Music::Track'); 2329 2330 my @tracks = $cd->tracks; 2331 2332 my $track6 = $cd->add_to_tracks({ 2333 position => 6, 2334 title => 'Tomorrow', 2335 }); 2336 2337This method declares that another table is referencing us (i.e. storing 2338our primary key in its table). 2339 2340It creates a named accessor method in our class which returns a list of 2341all the matching Foreign::Class objects. 2342 2343In addition it creates another method which allows a new associated object 2344to be constructed, taking care of the linking automatically. This method 2345is the same as the accessor method with "add_to_" prepended. 2346 2347The add_to_tracks example above is exactly equivalent to: 2348 2349 my $track6 = Music::Track->create({ 2350 cd => $cd, 2351 position => 6, 2352 title => 'Tomorrow', 2353 }); 2354 2355When setting up the relationship we examine the foreign class's has_a() 2356declarations to discover which of its columns reference our class. (Note 2357that because this happens at compile time, if the foreign class is defined 2358in the same file, the class with the has_a() must be defined earlier than 2359the class with the has_many(). If the classes are in different files, 2360Class::DBI should be able to do the right thing). If no such has_a() 2361declarations can be found, or none link to us, we assume that it is linking 2362to us via a column named after the moniker() of our class. If this is 2363not true you can pass an additional third argument to the has_many() 2364declaration stating which column of the foreign class references us. 2365 2366=head3 Limiting 2367 2368 Music::Artist->has_many(cds => 'Music::CD'); 2369 my @cds = $artist->cds(year => 1980); 2370 2371When calling the method created by has_many, you can also supply any 2372additional key/value pairs for restricting the search. The above example 2373will only return the CDs with a year of 1980. 2374 2375=head3 Ordering 2376 2377 Music::CD->has_many(tracks => 'Music::Track', { order_by => 'playorder' }); 2378 2379Often you wish to order the values returned from has_many. This can be 2380done by passing a hash ref containing a 'order_by' value of the column by 2381which you want to order. 2382 2383=head3 Mapping 2384 2385 Music::CD->has_many(styles => [ 'Music::StyleRef' => 'style' ]); 2386 2387Sometimes we don't want to return an instance of the Foreign::Class, 2388but instead the result of calling a method on that object. We can do 2389this by changing the Foreign::Class declaration to a listref of the 2390Foreign::Class and the method to call on that class. 2391 2392The above is exactly equivalent to: 2393 2394 Music::CD->has_many(_style_refs => 'Music::StyleRef'); 2395 2396 sub styles { 2397 my $self = shift; 2398 return map $_->style, $self->_style_refs; 2399 } 2400 2401For an example of where this is useful see L</"MANY TO MANY RELATIONSHIPS"> 2402below. 2403 2404=head2 might_have 2405 2406 Music::CD->might_have(method_name => Class => (@fields_to_import)); 2407 2408 Music::CD->might_have(liner_notes => LinerNotes => qw/notes/); 2409 2410 my $liner_notes_object = $cd->liner_notes; 2411 my $notes = $cd->notes; # equivalent to $cd->liner_notes->notes; 2412 2413might_have() is similar to has_many() for relationships that can have 2414at most one associated objects. For example, if you have a CD database 2415to which you want to add liner notes information, you might not want 2416to add a 'liner_notes' column to your main CD table even though there 2417is no multiplicity of relationship involved (each CD has at most one 2418'liner notes' field). So, we create another table with the same primary 2419key as this one, with which we can cross-reference. 2420 2421But you don't want to have to keep writing methods to turn the the 2422'list' of liner_notes objects you'd get back from has_many into the 2423single object you'd need. So, might_have() does this work for you. It 2424creates you an accessor to fetch the single object back if it exists, 2425and it also allows you import any of its methods into your namespace. So, 2426in the example above, the LinerNotes class can be mostly invisible - 2427you can just call $cd->notes and it will call the notes method on the 2428correct LinerNotes object transparently for you. 2429 2430Making sure you don't have namespace clashes is up to you, as is correctly 2431creating the objects, but I may make these simpler in later versions. 2432(Particularly if someone asks for them!) 2433 2434=head2 Notes 2435 2436has_a(), might_have() and has_many() check that the relevant class has 2437already been loaded. If it hasn't then they try to load the module of 2438the same name using require. If the require fails because it can't 2439find the module then it will assume it's not a simple require (i.e., 2440Foreign::Class isn't in Foreign/Class.pm) and that you will take care 2441of it and ignore the warning. Any other error, such as a syntax error, 2442triggers an exception. 2443 2444NOTE: The two classes in a relationship do not have to be in the same 2445database, on the same machine, or even in the same type of database! It 2446is quite acceptable for a table in a MySQL database to be connected to 2447a different table in an Oracle database, and for cascading delete etc 2448to work across these. This should assist greatly if you need to migrate 2449a database gradually. 2450 2451=head1 MANY TO MANY RELATIONSHIPS 2452 2453Class::DBI does not currently support Many to Many relationships, per se. 2454However, by combining the relationships that already exist it is possible 2455to set these up. 2456 2457Consider the case of Films and Actors, with a linking Role table. First 2458of all we'll set up our Role class: 2459 2460 Role->table('role'); 2461 Role->columns(Primary => qw/film actor/); 2462 Role->has_a(film => 'Film'); 2463 Role->has_a(actor => 'Actor'); 2464 2465We have a multi-column primary key, with each column pointing to another class. 2466 2467Then, we need to set up our Film and Actor class to use this linking table: 2468 2469 Film->table('film'); 2470 Film->columns(All => qw/id title rating/); 2471 Film->has_many(stars => [ Role => 'actor' ]); 2472 2473 Actor->table('actor'); 2474 Actor->columns(All => qw/id name/); 2475 Actor->has_many(films => [ Role => 'film' ]); 2476 2477In each case we use the 'mapping method' variation of has_many() to say 2478that we don't want an instance of the Role class, but rather the result 2479of calling a method on that instance. As we have set up those methods 2480in Role to inflate to the actual Actor and Film objects, this gives us a 2481cheap many-to-many relationship. In the case of Film, this is equivalent 2482to the more long-winded: 2483 2484 Film->has_many(roles => "Role"); 2485 2486 sub actors { 2487 my $self = shift; 2488 return map $_->actor, $self->roles 2489 } 2490 2491As this is almost exactly what is created internally, add_to_stars and 2492add_to_films will generally do the right thing as they are actually 2493doing the equivalent of add_to_roles: 2494 2495 $film->add_to_actors({ actor => $actor }); 2496 2497Similarly a cascading delete will also do the right thing as it will 2498only delete the relationship from the linking table. 2499 2500If the Role table were to contain extra information, such as the name 2501of the character played, then you would usually need to skip these 2502short-cuts and set up each of the relationships, and associated helper 2503methods, manually. 2504 2505=head1 ADDING NEW RELATIONSHIP TYPES 2506 2507=head2 add_relationship_type 2508 2509The relationships described above are implemented through 2510Class::DBI::Relationship subclasses. These are then plugged into 2511Class::DBI through an add_relationship_type() call: 2512 2513 __PACKAGE__->add_relationship_type( 2514 has_a => "Class::DBI::Relationship::HasA", 2515 has_many => "Class::DBI::Relationship::HasMany", 2516 might_have => "Class::DBI::Relationship::MightHave", 2517 ); 2518 2519If is thus possible to add new relationship types, or modify the behaviour 2520of the existing types. See L<Class::DBI::Relationship> for more information 2521on what is required. 2522 2523=head1 DEFINING SQL STATEMENTS 2524 2525There are several main approaches to setting up your own SQL queries: 2526 2527For queries which could be used to create a list of matching objects 2528you can create a constructor method associated with this SQL and let 2529Class::DBI do the work for you, or just inline the entire query. 2530 2531For more complex queries you need to fall back on the underlying Ima::DBI 2532query mechanism. (Caveat: since Ima::DBI uses sprintf-style interpolation, 2533you need to be careful to double any "wildcard" % signs in your queries). 2534 2535=head2 add_constructor 2536 2537 __PACKAGE__->add_constructor(method_name => 'SQL_where_clause'); 2538 2539The SQL can be of arbitrary complexity and will be turned into: 2540 SELECT (essential columns) 2541 FROM (table name) 2542 WHERE <your SQL> 2543 2544This will then create a method of the name you specify, which returns 2545a list of objects as with any built in query. 2546 2547For example: 2548 2549 Music::CD->add_constructor(new_music => 'year > 2000'); 2550 my @recent = Music::CD->new_music; 2551 2552You can also supply placeholders in your SQL, which must then be 2553specified at query time: 2554 2555 Music::CD->add_constructor(new_music => 'year > ?'); 2556 my @recent = Music::CD->new_music(2000); 2557 2558=head2 retrieve_from_sql 2559 2560On occasions where you want to execute arbitrary SQL, but don't want 2561to go to the trouble of setting up a constructor method, you can inline 2562the entire WHERE clause, and just get the objects back directly: 2563 2564 my @cds = Music::CD->retrieve_from_sql(qq{ 2565 artist = 'Ozzy Osbourne' AND 2566 title like "%Crazy" AND 2567 year <= 1986 2568 ORDER BY year 2569 LIMIT 2,3 2570 }); 2571 2572=head2 Ima::DBI queries 2573 2574When you can't use 'add_constructor', e.g. when using aggregate functions, 2575you can fall back on the fact that Class::DBI inherits from Ima::DBI 2576and prefers to use its style of dealing with statements, via set_sql(). 2577 2578The Class::DBI set_sql() method defaults to using prepare_cached() 2579unless the $cache parameter is defined and false (see Ima::DBI docs for 2580more information). 2581 2582To assist with writing SQL that is inheritable into subclasses, several 2583additional substitutions are available here: __TABLE__, __ESSENTIAL__ 2584and __IDENTIFIER__. These represent the table name associated with the 2585class, its essential columns, and the primary key of the current object, 2586in the case of an instance method on it. 2587 2588For example, the SQL for the internal 'update' method is implemented as: 2589 2590 __PACKAGE__->set_sql('update', <<""); 2591 UPDATE __TABLE__ 2592 SET %s 2593 WHERE __IDENTIFIER__ 2594 2595The 'longhand' version of the new_music constructor shown above would 2596similarly be: 2597 2598 Music::CD->set_sql(new_music => qq{ 2599 SELECT __ESSENTIAL__ 2600 FROM __TABLE__ 2601 WHERE year > ? 2602 }; 2603 2604We also extend the Ima::DBI set_sql() to create a helper shortcut method, 2605named by prefixing the name of your SQL fragment with search_. Thus, 2606the above call to set_sql() will automatically set up the method 2607Music::CD->search_new_music(), which will execute this search and 2608return the relevant objects or Iterator. (If you have placeholders 2609in your query, you must pass the relevant arguments when calling your 2610search method.) 2611 2612This does the equivalent of: 2613 2614 sub search_new_music { 2615 my ($class, @args) = @_; 2616 my $sth = $class->sql_new_music; 2617 $sth->execute(@args); 2618 return $class->sth_to_objects($sth); 2619 } 2620 2621The $sth which we use to return the objects here is a normal DBI-style 2622statement handle, so if your results can't even be turned into objects 2623easily, you can still call $sth->fetchrow_array etc and return whatever 2624data you choose. 2625 2626Of course, any query can be added via set_sql, including joins. So, 2627to add a query that returns the 10 Artists with the most CDs, you could 2628write (with MySQL): 2629 2630 Music::Artist->set_sql(most_cds => qq{ 2631 SELECT artist.id, COUNT(cd.id) AS cds 2632 FROM artist, cd 2633 WHERE artist.id = cd.artist 2634 GROUP BY artist.id 2635 ORDER BY cds DESC 2636 LIMIT 10 2637 }); 2638 2639 my @artists = Music::Artist->search_most_cds(); 2640 2641If you also need to access the 'cds' value returned from this query, 2642the best approach is to declare 'cds' to be a TEMP column. (See 2643L</"Non-Persistent Fields"> below). 2644 2645=head2 Class::DBI::AbstractSearch 2646 2647 my @music = Music::CD->search_where( 2648 artist => [ 'Ozzy', 'Kelly' ], 2649 status => { '!=', 'outdated' }, 2650 ); 2651 2652The L<Class::DBI::AbstractSearch> module, available from CPAN, is a 2653plugin for Class::DBI that allows you to write arbitrarily complex 2654searches using perl data structures, rather than SQL. 2655 2656=head2 Single Value SELECTs 2657 2658Selects which only return a single value can take advantage of Ima::DBI's 2659$sth->select_val() call, coupled with Class::DBI's sql_single SQL. 2660 2661head3 select_val 2662 2663Selects which only return a single value can take advantage of Ima::DBI's 2664$sth->select_val() call. For example, 2665 2666 __PACKAGE__->set_sql(count_all => "SELECT COUNT(*) FROM __TABLE__"); 2667 # .. then .. 2668 my $count = $class->sql_count_all->select_val; 2669 2670=head3 sql_single 2671 2672Internally we define a very simple SQL fragment: "SELECT %s FROM __TABLE__". 2673Using this we implement the above Class->count_all(), as 2674 2675 $class->sql_single("COUNT(*)")->select_val; 2676 2677This interpolates the COUNT(*) into the %s of the SQL, and then executes 2678the query, returning a single value. 2679 2680Any SQL set up via set_sql() can of course be supplied here, and 2681select_val can take arguments for any placeholders there. 2682 2683Internally we define several helper methods using this approach: 2684 2685=over 4 2686 2687=item - count_all 2688 2689=item - maximum_value_of($column) 2690 2691=item - minimum_value_of($column) 2692 2693=back 2694 2695=head1 LAZY POPULATION 2696 2697In the tradition of Perl, Class::DBI is lazy about how it loads your 2698objects. Often, you find yourself using only a small number of the 2699available columns and it would be a waste of memory to load all of them 2700just to get at two, especially if you're dealing with large numbers of 2701objects simultaneously. 2702 2703You should therefore group together your columns by typical usage, as 2704fetching one value from a group can also pre-fetch all the others in 2705that group for you, for more efficient access. 2706 2707So for example, if we usually fetch the artist and title, but don't use 2708the 'year' so much, then we could say the following: 2709 2710 Music::CD->columns(Primary => qw/cdid/); 2711 Music::CD->columns(Essential => qw/artist title/); 2712 Music::CD->columns(Others => qw/year runlength/); 2713 2714Now when you fetch back a CD it will come pre-loaded with the 'cdid', 2715'artist' and 'title' fields. Fetching the 'year' will mean another visit 2716to the database, but will bring back the 'runlength' whilst it's there. 2717 2718This can potentially increase performance. 2719 2720If you don't like this behavior, then just add all your non-primary key 2721columns to the one group, and Class::DBI will load everything at once. 2722 2723=head2 columns 2724 2725 my @all_columns = $class->columns; 2726 my @columns = $class->columns($group); 2727 2728 my @primary = $class->primary_columns; 2729 my $primary = $class->primary_column; 2730 my @essential = $class->_essential; 2731 2732There are four 'reserved' groups: 'All', 'Essential', 'Primary' and 2733'TEMP'. 2734 2735B<'All'> are all columns used by the class. If not set it will be 2736created from all the other groups. 2737 2738B<'Primary'> is the primary key columns for this class. It I<must> 2739be set before objects can be used. 2740 2741If 'All' is given but not 'Primary' it will assume the first column in 2742'All' is the primary key. 2743 2744B<'Essential'> are the minimal set of columns needed to load and use 2745the object. Only the columns in this group will be loaded when an object 2746is retrieve()'d. It is typically used to save memory on a class that has 2747a lot of columns but where we mostly only use a few of them. It will 2748automatically be set to B<'All'> if you don't set it yourself. 2749The 'Primary' column is always part of your 'Essential' group and 2750Class::DBI will put it there if you don't. 2751 2752For simplicity we provide primary_columns(), primary_column(), and 2753_essential() methods which return these. The primary_column() method 2754should only be used for tables that have a single primary key column. 2755 2756=head2 Non-Persistent Fields 2757 2758 Music::CD->columns(TEMP => qw/nonpersistent/); 2759 2760If you wish to have fields that act like columns in every other way, but 2761that don't actually exist in the database (and thus will not persist), 2762you can declare them as part of a column group of 'TEMP'. 2763 2764=head2 find_column 2765 2766 Class->find_column($column); 2767 $obj->find_column($column); 2768 2769The columns of a class are stored as Class::DBI::Column objects. This 2770method will return you the object for the given column, if it exists. 2771This is most useful either in a boolean context to discover if the column 2772exists, or to 'normalize' a user-entered column name to an actual Column. 2773 2774The interface of the Column object itself is still under development, 2775so you shouldn't really rely on anything internal to it. 2776 2777=head1 TRANSACTIONS 2778 2779Class::DBI suffers from the usual problems when dealing with transactions. 2780In particular, you should be very wary when committing your changes that 2781you may actually be in a wider scope than expected and that your caller 2782may not be expecting you to commit. 2783 2784However, as long as you are aware of this, and try to keep the scope 2785of your transactions small, ideally always within the scope of a single 2786method, you should be able to work with transactions with few problems. 2787 2788=head2 dbi_commit / dbi_rollback 2789 2790 $obj->dbi_commit(); 2791 $obj->dbi_rollback(); 2792 2793We provide these thin aliases through to the DBI's commit() and rollback() 2794commands to commit or rollback all changes to this object. 2795 2796=head2 Localised Transactions 2797 2798A nice idiom for turning on a transaction locally (with AutoCommit turned 2799on globally) (courtesy of Dominic Mitchell) is: 2800 2801 sub do_transaction { 2802 my $class = shift; 2803 my ( $code ) = @_; 2804 # Turn off AutoCommit for this scope. 2805 # A commit will occur at the exit of this block automatically, 2806 # when the local AutoCommit goes out of scope. 2807 local $class->db_Main->{ AutoCommit }; 2808 2809 # Execute the required code inside the transaction. 2810 eval { $code->() }; 2811 if ( $@ ) { 2812 my $commit_error = $@; 2813 eval { $class->dbi_rollback }; # might also die! 2814 die $commit_error; 2815 } 2816 } 2817 2818 And then you just call: 2819 2820 Music::DBI->do_transaction( sub { 2821 my $artist = Music::Artist->create({ name => 'Pink Floyd' }); 2822 my $cd = $artist->add_to_cds({ 2823 title => 'Dark Side Of The Moon', 2824 year => 1974, 2825 }); 2826 }); 2827 2828Now either both will get added, or the entire transaction will be 2829rolled back. 2830 2831=head1 UNIQUENESS OF OBJECTS IN MEMORY 2832 2833Class::DBI supports uniqueness of objects in memory. In a given perl 2834interpreter there will only be one instance of any given object at 2835one time. Many variables may reference that object, but there can be 2836only one. 2837 2838Here's an example to illustrate: 2839 2840 my $artist1 = Music::Artist->create({ artistid => 7, name => 'Polysics' }); 2841 my $artist2 = Music::Artist->retrieve(7); 2842 my $artist3 = Music::Artist->search( name => 'Polysics' )->first; 2843 2844Now $artist1, $artist2, and $artist3 all point to the same object. If you 2845update a property on one of them, all of them will reflect the update. 2846 2847This is implemented using a simple object lookup index for all live 2848objects in memory. It is not a traditional cache - when your objects 2849go out of scope, they will be destroyed normally, and a future retrieve 2850will instantiate an entirely new object. 2851 2852The ability to perform this magic for you replies on your perl having 2853access to the Scalar::Util::weaken function. Although this is part of 2854the core perl distribution, some vendors do not compile support for it. 2855To find out if your perl has support for it, you can run this on the 2856command line: 2857 2858 perl -e 'use Scalar::Util qw(weaken)' 2859 2860If you get an error message about weak references not being implemented, 2861Class::DBI will not maintain this lookup index, but give you a separate 2862instances for each retrieve. 2863 2864A few new tools are offered for adjusting the behavior of the object 2865index. These are still somewhat experimental and may change in a 2866future release. 2867 2868=head2 remove_from_object_index 2869 2870 $artist->remove_from_object_index(); 2871 2872This is an object method for removing a single object from the live 2873objects index. You can use this if you want to have multiple distinct 2874copies of the same object in memory. 2875 2876=head2 clear_object_index 2877 2878 Music::DBI->clear_object_index(); 2879 2880You can call this method on any class or instance of Class::DBI, but 2881the effect is universal: it removes all objects from the index. 2882 2883=head2 purge_object_index_every 2884 2885 Music::Artist->purge_object_index_every(2000); 2886 2887Weak references are not removed from the index when an object goes 2888out of scope. This means that over time the index will grow in memory. 2889This is really only an issue for long-running environments like mod_perl, 2890but every so often we go through and clean out dead references to prevent 2891it. By default, this happens evey 1000 object loads, but you can change 2892that default for your class by calling the purge_object_index_every 2893method with a number. 2894 2895Eventually this may handled in the DESTROY method instead. 2896 2897As a final note, keep in mind that you can still have multiple distinct 2898copies of an object in memory if you have multiple perl interpreters 2899running. CGI, mod_perl, and many other common usage situations run 2900multiple interpreters, meaning that each one of them may have an instance 2901of an object representing the same data. However, this is no worse 2902than it was before, and is entirely normal for database applications in 2903multi-process environments. 2904 2905=head1 SUBCLASSING 2906 2907The preferred method of interacting with Class::DBI is for you to write 2908a subclass for your database connection, with each table-class inheriting 2909in turn from it. 2910 2911As well as encapsulating the connection information in one place, 2912this also allows you to override default behaviour or add additional 2913functionality across all of your classes. 2914 2915As the innards of Class::DBI are still in flux, you must exercise extreme 2916caution in overriding private methods of Class::DBI (those starting with 2917an underscore), unless they are explicitly mentioned in this documentation 2918as being safe to override. If you find yourself needing to do this, 2919then I would suggest that you ask on the mailing list about it, and 2920we'll see if we can either come up with a better approach, or provide 2921a new means to do whatever you need to do. 2922 2923=head1 CAVEATS 2924 2925=head2 Multi-Column Foreign Keys are not supported 2926 2927=head2 Don't change or inflate the value of your primary columns 2928 2929Altering your primary key column currently causes Bad Things to happen. 2930I should really protect against this. 2931 2932=head1 SUPPORTED DATABASES 2933 2934Theoretically Class::DBI should work with almost any standard RDBMS. Of 2935course, in the real world, we know that that's not true. We know that 2936it works with MySQL, PostgrSQL, Oracle and SQLite, each of which have 2937their own additional subclass on CPAN that you should explore if you're 2938using them. 2939 2940 L<Class::DBI::mysql>, L<Class::DBI::Pg>, L<Class::DBI::Oracle>, 2941 L<Class::DBI::SQLite> 2942 2943For the most part it's been reported to work with Sybase, although there 2944are some issues with multi-case column/table names. Beyond that lies 2945The Great Unknown(tm). If you have access to other databases, please 2946give this a test run, and let me know the results. 2947 2948This is known not to work with DBD::RAM. As a minimum it requires a 2949database that supports table aliasing, and a DBI driver that supports 2950placeholders. 2951 2952=head1 CURRENT AUTHOR 2953 2954Tony Bowden <classdbi@tmtm.com> 2955 2956=head1 AUTHOR EMERITUS 2957 2958Michael G Schwern <schwern@pobox.com> 2959 2960=head1 THANKS TO 2961 2962Tim Bunce, Tatsuhiko Miyagawa, Perrin Hawkins, Alexander Karelas, Barry 2963Hoggard, Bart Lateur, Boris Mouzykantskii, Brad Bowman, Brian Parker, 2964Casey West, Charles Bailey, Christopher L. Everett Damian Conway, Dan 2965Thill, Dave Cash, David Jack Olrik, Dominic Mitchell, Drew Taylor, 2966Drew Wilson, Jay Strauss, Jesse Sheidlower, Jonathan Swartz, Marty 2967Pauley, Michael Styer, Mike Lambert, Paul Makepeace, Phil Crow, Richard 2968Piacentini, Simon Cozens, Simon Wilcox, Thomas Klausner, Tom Renfro, 2969Uri Gutman, William McKee, the Class::DBI mailing list, the POOP group, 2970and all the others who've helped, but that I've forgetten to mention. 2971 2972=head1 SUPPORT 2973 2974Support for Class::DBI is via the mailing list. The list is used for 2975general queries on the use of Class::DBI, bug reports, patches, and 2976suggestions for improvements or new features. 2977 2978To join the list visit http://groups.kasei.com/mail/info/cdbi-talk 2979 2980You can also report bugs through the CPAN RT interface, but I'll 2981proabably also forward those to the mailing list for discussion (and 2982often bounce mailing list bug reports to the RT interface so I don't 2983forget about them!) 2984 2985When submitting patches I quite like the 'diff -Bub' format. Bug fixes 2986also get applied much quicker if you supply a failing test case (even 2987in preference to a fix!) 2988 2989The interface to Class::DBI is fairly stable, but there are still 2990occasions when we need to break backwards compatability. Such issues 2991will be raised on the list before release, so if you use Class::DBI in 2992a production environment, it's probably a good idea to keep a watch on 2993the list (and definitely on the CHANGES file of a new release). 2994 2995=head1 LICENSE 2996 2997This library is free software; you can redistribute it and/or modify 2998it under the same terms as Perl itself. 2999 3000=head1 SEE ALSO 3001 3002There is a Class::DBI wiki at: 3003 http://www.class-dbi.com/cgi-bin/wiki/index.cgi?HomePage 3004 3005Amongst other things it provides the beginnings of a Cookbook of typical 3006tricks and tips. Please contribute! 3007 3008There are lots of 3rd party subclasses and plugins available. 3009For a full list see: 3010 http://search.cpan.org/search?query=Class%3A%3ADBI&mode=module 3011 3012An article on Class::DBI was published on Perl.com a while ago. It's 3013slightly out of date already, but it's a good introduction: 3014 http://www.perl.com/pub/a/2002/11/27/classdbi.html 3015 3016http://poop.sourceforge.net/ provides a document comparing a variety 3017of different approaches to database persistence, such as Class::DBI, 3018Alazabo, Tangram, SPOPS etc. 3019 3020Class::DBI is built on top of L<Ima::DBI>, L<Class::Accessor> and 3021L<Class::Data::Inheritable>. 3022 3023=cut 3024 3025