|
NAMERose::DB::Object - Extensible, high performance object-relational mapper (ORM).SYNOPSIS## For an informal overview of Rose::DB::Object, please ## see the Rose::DB::Object::Tutorial documentation. The ## reference documentation follows. ## First, set up your Rose::DB data sources, otherwise you ## won't be able to connect to the database at all. See ## the Rose::DB documentation for more information. For ## a quick start, see the Rose::DB::Tutorial documentation. ## ## Create classes - two possible approaches: ## # # 1. Automatic configuration # package Category; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'categories', auto => 1, ); ... package Price; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'prices', auto => 1, ); ... package Product; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'products', auto => 1, ); # # 2. Manual configuration # package Category; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'categories', columns => [ id => { type => 'int', primary_key => 1 }, name => { type => 'varchar', length => 255 }, description => { type => 'text' }, ], unique_key => 'name', ); ... package Price; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'prices', columns => [ id => { type => 'int', primary_key => 1 }, price => { type => 'decimal' }, region => { type => 'char', length => 3 }, product_id => { type => 'int' } ], unique_key => [ 'product_id', 'region' ], ); ... package Product; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'products', columns => [ id => { type => 'int', primary_key => 1 }, name => { type => 'varchar', length => 255 }, description => { type => 'text' }, category_id => { type => 'int' }, status => { type => 'varchar', check_in => [ 'active', 'inactive' ], default => 'inactive', }, start_date => { type => 'datetime' }, end_date => { type => 'datetime' }, date_created => { type => 'timestamp', default => 'now' }, last_modified => { type => 'timestamp', default => 'now' }, ], unique_key => 'name', foreign_keys => [ category => { class => 'Category', key_columns => { category_id => 'id' }, }, ], relationships => [ prices => { type => 'one to many', class => 'Price', column_map => { id => 'product_id' }, }, ], ); ... # # Example usage # $product = Product->new(id => 123, name => 'GameCube', status => 'active', start_date => '11/5/2001', end_date => '12/1/2007', category_id => 5); $product->save; ... $product = Product->new(id => 123); $product->load; # Load foreign object via "one to one" relationship print $product->category->name; $product->end_date->add(days => 45); $product->save; ... $product = Product->new(id => 456); $product->load; # Load foreign objects via "one to many" relationship print join ' ', $product->prices; ... DESCRIPTIONRose::DB::Object is a base class for objects that encapsulate a single row in a database table. Rose::DB::Object-derived objects are sometimes simply called "Rose::DB::Object objects" in this documentation for the sake of brevity, but be assured that derivation is the only reasonable way to use this class.Rose::DB::Object inherits from, and follows the conventions of, Rose::Object. See the Rose::Object documentation for more information. For an informal overview of this module distribution, consult the Rose::DB::Object::Tutorial. RestrictionsRose::DB::Object objects can represent rows in almost any database table, subject to the following constraints.
Although the list above contains the only hard and fast rules, there may be other realities that you'll need to work around. The most common example is the existence of a column name in the database table that conflicts with the name of a method in the Rose::DB::Object API. There are two possible workarounds: either explicitly alias the column, or define a mapping function. See the alias_column and column_name_to_method_name_mapper methods in the Rose::DB::Object::Metadata documentation for more details. There are also varying degrees of support for data types in each database server supported by Rose::DB. If you have a table that uses a data type not supported by an existing Rose::DB::Object::Metadata::Column-derived class, you will have to write your own column class and then map it to a type name using Rose::DB::Object::Metadata's column_type_class method, yada yada. (Or, of course, you can map the new type to an existing column class.) The entire framework is extensible. This module distribution contains straight-forward implementations of the most common column types, but there's certainly more that can be done. Submissions are welcome. FeaturesRose::DB::Object provides the following functions:
Objects can be loaded based on either a primary key or a unique key. Since all tables fronted by Rose::DB::Objects must have non-null primary keys, insert, update, and delete operations are done based on the primary key. In addition, its sibling class, Rose::DB::Object::Manager, can do the following:
Rose::DB::Object::Manager can be subclassed and used separately (the recommended approach), or it can create object manager methods within a Rose::DB::Object subclass. See the Rose::DB::Object::Manager documentation for more information. Rose::DB::Object can parse, coerce, inflate, and deflate column values on your behalf, providing the most convenient possible data representations on the Perl side of the fence, while allowing the programmer to completely forget about the ugly details of the data formats required by the database. Default implementations are included for most common column types, and the framework is completely extensible. Finally, the Rose::DB::Object::Loader can be used to automatically create a suite of Rose::DB::Object and Rose::DB::Object::Manager subclasses based on the contents of the database. ConfigurationBefore Rose::DB::Object can do any useful work, you must register at least one Rose::DB data source. By default, Rose::DB::Object instantiates a Rose::DB object by passing no arguments to its constructor. (See the db method.) If you register a Rose::DB data source using the default type and domain, this will work fine. Otherwise, you must override the meta method in your Rose::DB::Object subclass and have it return the appropriate Rose::DB-derived object.To define your own Rose::DB::Object-derived class, you must describe the table that your class will act as a front-end for. This is done through the Rose::DB::Object::Metadata object associated with each Rose::DB::Object-derived class. The metadata object is accessible via Rose::DB::Object's meta method. Metadata objects can be populated manually or automatically. Both techniques are shown in the synopsis above. The automatic mode works by asking the database itself for the information. There are some caveats to this approach. See the auto-initialization section of the Rose::DB::Object::Metadata documentation for more information. Serial and Auto-Incremented ColumnsMost databases provide a way to use a series of arbitrary integers as primary key column values. Some support a native "SERIAL" column data type. Others use a special auto-increment column attribute.Rose::DB::Object supports at least one such serial or auto-incremented column type in each supported database. In all cases, the Rose::DB::Object-derived class setup is the same: package My::DB::Object; ... __PACKAGE__->meta->setup ( columns => [ id => { type => 'serial', primary_key => 1, not_null => 1 }, ... ], ... ); (Note that the column doesn't have to be named "id"; it can be named anything.) If the database column uses big integers, use "bigserial" column "type" instead. Given the column metadata definition above, Rose::DB::Object will automatically generate and/or retrieve the primary key column value when an object is save()d. Example: $o = My::DB::Object->new(name => 'bud'); # no id specified $o->save; # new id value generated here print "Generated new id value: ", $o->id; This will only work, however, if the corresponding column definition in the database is set up correctly. The exact technique varies from vendor to vendor. Below are examples of primary key column definitions that provide auto-generated values. There's one example for each of the databases supported by Rose::DB.
If the table has a multi-column primary key or does not use a column type that supports auto-generated values, you can define a custom primary key generator function using the primary_key_generator method of the Rose::DB::Object::Metadata-derived object that contains the metadata for this class. Example: package MyDBObject; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup ( table => 'mytable', columns => [ k1 => { type => 'int', not_null => 1 }, k2 => { type => 'int', not_null => 1 }, name => { type => 'varchar', length => 255 }, ... ], primary_key_columns => [ 'k1', 'k2' ], primary_key_generator => sub { my($meta, $db) = @_; # Generate primary key values somehow my $k1 = ...; my $k2 = ...; return $k1, $k2; }, ); See the Rose::DB::Object::Metadata documentation for more information on custom primary key generators. InheritanceSimple, single inheritance between Rose::DB::Object-derived classes is supported. (Multiple inheritance is not currently supported.) The first time the metadata object for a given class is accessed, it is created by making a one-time "deep copy" of the base class's metadata object (as long that the base class has one or more columns set). This includes all columns, relationships, foreign keys, and other metadata from the base class. From that point on, the subclass may add to or modify its metadata without affecting any other class.Tip: When using perl 5.8.0 or later, the Scalar::Util::Clone module is highly recommended. If it's installed, it will be used to more efficiently clone base-class metadata objects. If the base class has already been initialized, the subclass must explicitly specify whether it wants to create a new set of column and relationship methods, or merely inherit the methods from the base class. If the subclass contains any metadata modifications that affect method creation, then it must create a new set of methods to reflect those changes. Finally, note that column types cannot be changed "in-place." To change a column type, delete the old column and add a new one with the same name. This can be done in one step with the replace_column method. Example: package BaseClass; use base 'Rose::DB::Object'; __PACKAGE__->meta->setup ( table => 'objects', columns => [ id => { type => 'int', primary_key => 1 }, start => { type => 'scalar' }, ], ); ... package SubClass; use base 'BaseClass'; # Set a default value for this column. __PACKAGE__->meta->column('id')->default(123); # Change the "start" column into a datetime column. __PACKAGE__->meta->replace_column(start => { type => 'datetime' }); # Initialize, replacing any inherited methods with newly created ones __PACKAGE__->meta->initialize(replace_existing => 1); ... $b = BaseClass->new; $id = $b->id; # undef $b->start('1/2/2003'); print $b->start; # '1/2/2003' (plain string) $s = SubClass->new; $id = $s->id; # 123 $b->start('1/2/2003'); # Value is converted to a DateTime object print $b->start->strftime('%B'); # 'January' To preserve all inherited methods in a subclass, do this instead: package SubClass; use base 'BaseClass'; __PACKAGE__->meta->initialize(preserve_existing => 1); Error HandlingError handling for Rose::DB::Object-derived objects is controlled by the error_mode method of the Rose::DB::Object::Metadata object associated with the class (accessible via the meta method). The default setting is "fatal", which means that Rose::DB::Object methods will croak if they encounter an error.PLEASE NOTE: The error return values described in the object method documentation are only relevant when the error mode is set to something "non-fatal." In other words, if an error occurs, you'll never see any of those return values if the selected error mode dies or croaks or otherwise throws an exception when an error occurs. CONSTRUCTOR
CLASS METHODS
OBJECT METHODS
The cascaded delete feature described above plays it safe by only deleting rows that are not referenced by any other rows (according to the metadata provided by each Rose::DB::Object-derived class). I strongly recommend that you implement "cascaded delete" in the database itself, rather than using this feature. It will undoubtedly be faster and more robust than doing it "client-side." You may also want to cascade only to certain tables, or otherwise deviate from the "safe" plan. If your database supports automatic cascaded delete and/or triggers, please consider using these features.
Returns true if the row was inserted successfully, false otherwise. The true value returned on success will be the object itself. If the object overloads its boolean value such that it is not true, then a true value will be returned instead of the object itself.
SUBCLASS NOTE: If you are going to override the load method in your subclass, you must pass an alias to the actual object as the first argument to the method, rather than passing a copy of the object reference. Example: # This is the CORRECT way to override load() while still # calling the base class version of the method. sub load { my $self = $_[0]; # Copy, not shift ... # Do your stuff shift->SUPER::load(@_); # Call superclass } Now here's the wrong way: # This is the WRONG way to override load() while still # calling the base class version of the method. sub load { my $self = shift; # WRONG! The alias to the object is now lost! ... # Do your stuff $self->SUPER::load(@_); # This won't work right! } This requirement exists in order to preserve some sneaky object-replacement optimizations in the base class implementation of load. At some point, those optimizations may change or go away. But if you follow these guidelines, your code will continue to work no matter what.
It is an error to pass both the "insert" and "update" parameters in a single call. Returns true if the row was inserted or updated successfully, false otherwise. The true value returned on success will be the object itself. If the object overloads its boolean value such that it is not true, then a true value will be returned instead of the object itself. If an insert was performed and the primary key is a single column that supports auto-generated values, then the object accessor for the primary key column will contain the auto-generated value. See the Serial and Auto-Incremented Columns section for more information.
Returns true if the row was updated successfully, false otherwise. The true value returned on success will be the object itself. If the object overloads its boolean value such that it is not true, then a true value will be returned instead of the object itself. RESERVED METHODSAs described in the Rose::DB::Object::Metadata documentation, each column in the database table has an associated get/set accessor method in the Rose::DB::Object. Since the Rose::DB::Object API already defines many methods (load, save, meta, etc.), accessor methods for columns that share the name of an existing method pose a problem. The solution is to alias such columns using Rose::DB::Object::Metadata's alias_column method.Here is a list of method names reserved by the Rose::DB::Object API. If you have a column with one of these names, you must alias it. db dbh delete DESTROY error init_db _init_db insert load meta meta_class not_found save update Note that not all of these methods are public. These methods do not suddenly become public just because you now know their names! Remember the stated policy of the Rose web application framework: if a method is not documented, it does not exist. (And no, the list of method names above does not constitute "documentation.") DEVELOPMENT POLICYThe Rose development policy applies to this, and all "Rose::*" modules. Please install Rose from CPAN and then run ""perldoc Rose"" for more information.SUPPORTFor an informal overview of Rose::DB::Object, consult the Rose::DB::Object::Tutorial.perldoc Rose::DB::Object::Tutorial Any Rose::DB::Object questions or problems can be posted to the Rose::DB::Object mailing list. To subscribe to the list or view the archives, go here: <http://groups.google.com/group/rose-db-object> Although the mailing list is the preferred support mechanism, you can also email the author (see below) or file bugs using the CPAN bug tracking system: <http://rt.cpan.org/NoAuth/Bugs.html?Dist=Rose-DB-Object> There's also a wiki and other resources linked from the Rose project home page: <http://rose.googlecode.com> CONTRIBUTORSBradley C Bailey, Graham Barr, Kostas Chatzikokolakis, David Christensen, Lucian Dragus, Justin Ellison, Perrin Harkins, Cees Hek, Benjamin Hitz, Dave Howorth, Peter Karman, Ed Loehr, Adam Mackler, Michael Reece, Thomas Whaples, Douglas Wilson, Teodor ZlatanovAUTHORJohn C. Siracusa (siracusa@gmail.com)LICENSECopyright (c) 2010 by John C. Siracusa. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Visit the GSP FreeBSD Man Page Interface. |