The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Rose::DB::Object - Object representation of a single row in a database table.

SYNOPSIS

  ## Step 0: Set up your Rose::DB data sources, otherwise you
  ## won't be able to connect to the database at all!

  ##
  ## Create classes - two possible approaches:
  ##

  #
  # 1. Automatic configuration
  #

  package Category;

  use Rose::DB::Object;
  our @ISA = qw(Rose::DB::Object);

  __PACKAGE__->meta->table('categories');

  __PACKAGE__->meta->auto_initialize;

  ...

  package Product;

  use Rose::DB::Object;
  our @ISA = qw(Rose::DB::Object);

  __PACKAGE__->meta->table('products');

  __PACKAGE__->meta->auto_initialize;

  #
  # 2. Manual configuration
  #

  package Category;

  use Rose::DB::Object;
  our @ISA = qw(Rose::DB::Object);

  __PACKAGE__->meta->table('categories');

  __PACKAGE__->meta->columns
  (
    id          => { type => 'int', primary_key => 1 },
    name        => { type => 'varchar', length => 255 },
    description => { type => 'text' },
  );

  __PACKAGE__->meta->add_unique_key('name');

  __PACKAGE__->meta->initialize;

  ...

  package Product;

  use Rose::DB::Object;
  our @ISA = qw(Rose::DB::Object);

  __PACKAGE__->meta->table('products');

  __PACKAGE__->meta->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' },
  );

  __PACKAGE__->meta->add_unique_key('name');

  __PACKAGE__->meta->foreign_keys
  (
    category =>
    {
      class       => 'Category',
      key_columns =>
      {
        category_id => 'id',
      }
    },
  );

  __PACKAGE__->meta->initialize;

  ...

  #
  # 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;

  print $product->category->name;

  $product->end_date->add(days => 45);

  $product->save;

  ...

DESCRIPTION

Rose::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.

Restrictions

Rose::DB::Object objects can represent rows in almost any database table, subject to the following constraints.

  • The database server must be supported by Rose::DB.

  • The database table must have a primary key.

  • The primary key must not allow null values in any of its columns.

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 work-arounds: 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.

Features

Rose::DB::Object provides the following functions:

  • Create a row in the database by saving a newly constructed object.

  • Initialize an object by loading a row from the database.

  • Update a row by saving a modified object back to the database.

  • Delete a row from the database.

  • Fetch an object referred to by a foreign key in the current object. (The "has a" relationship.)

  • Fetch multiple a objects that refer to the current object. (The "has many" relationship.)

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:

  • Fetch multiple objects from the database using arbitrary query conditions, limits, and offsets.

  • Iterate over a list of objects, fetching from the database in response to each step of the iterator.

  • Fetch objects along with "foreign objects" (referred to by foreign keys) in a single query by automatically generating the appropriate SQL join(s).

  • Count the number of objects that match a given query.

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.

Configuration

Before 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 init_db 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-dervied 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.

Error Handling

Error 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 then encounter an error.

PLEASE NOTE: The return values described in the method documentation below are only relevant when the error mode is set to something "non-fatal." In other words, 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

new PARAMS

Returns a new Rose::DB::Object constructed according to PARAMS, where PARAMS are name/value pairs. Any object method is a valid parameter name.

CLASS METHODS

meta

Returns the Rose::DB::Object::Metadata-derived object associated with this class. This object describes the database table whose rows are fronted by this class: the name of the table, its columns, unique keys, foreign keys, etc.

See the Rose::DB::Object::Metadata documentation for more information.

meta_class

Return the name of the Rose::DB::Object::Metadata-derived class used to store this object's metadata. Subclasses should override this method if they want to use a custom Rose::DB::Object::Metadata subclass. (See the source code for Rose::DB::Object::Std for an example of this.)

OBJECT METHODS

db [DB]

Get or set the Rose::DB object used to access the database that contains the table whose rows are fronted by the Rose::DB::Object-derived class.

If it does not already exist, this object is created with a simple, argument-less call to Rose::DB->new(). To override this default in a subclass, override the init_db method and return the Rose::DB to be used as the new default.

init_db

Returns the Rose::DB-derived object used to access the database in the absence of an explicit db value. The default implementation simply calls Rose::DB->new() with no arguments.

Override this method in your subclass in order to use a different default data source.

dbh

Returns the DBI database handle contained in db.

delete

Delete the row represented by the current object. The object must have been previously loaded from the database (or must otherwise have a defined primary key value) in order to be deleted. Returns true if the row was deleted or did not exist, false otherwise.

error

Returns the text message associated with the last error that occurred.

load [PARAMS]

Load a row from the database table, initializing the object with the values from that row. An object can be loaded based on either a primary key or a unique key.

Returns true if the row was loaded successfully, undef if the row could not be loaded due to an error, or zero (0) if the row does not exist.

PARAMS are optional name/value pairs. If the parameter speculative is passed with a true value, and if the load failed because the row was not found, then the error_mode setting is ignored and zero (0) is returned.

not_found

Returns true if the previous call to load failed because a row in the database table with the specified primary or unique key did not exist, false otherwise.

meta

Returns the Rose::DB::Object::Metadata object associated with this class. This object describes the database table whose rows are fronted by this class: the name of the table, its columns, unique keys, foreign keys, etc.

See the Rose::DB::Object::Metadata documentation for more information.

save [PARAMS]

Save the current object to the database table. In the absence of PARAMS, if the object was previously loaded from the database, the row will be updated. Otherwise, a new row will be created.

PARAMS are name/value pairs. Valid parameters are:

  • insert

    If set to a true value, then an insert is attempted, regardless of whether or not the object was previously loaded from the database.

  • update

    If set to a true value, then an update is attempted, regardless of whether or not the object was previously loaded from the database.

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.

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.

Here are examples of primary key column definitions that provide auto-generated values, one for each of the databases supported by Rose::DB.

  • PostgreSQL

        CREATE TABLE mytable
        (
          id   SERIAL PRIMARY KEY,
          ...
        );
  • MySQL

        CREATE TABLE mytable
        (
          id   INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
          ...
        );
  • Informix

        CREATE TABLE mytable
        (
          id   SERIAL NOT NULL PRIMARY KEY,
          ...
        );

Other data definitions are possible, of course, but the three definitions above are used in the Rose::DB::Object test suite and are therefore guaranteed to work. If you have success with alternative approaches, patches and/or new tests are welcome.

If your 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 Rose::DB::Object;
    our @ISA = qw(Rose::DB::Object);

    __PACKAGE__->meta->table('mytable');

    __PACKAGE__->meta->columns
    (
      k1   => { type => 'int', not_null => 1 },
      k2   => { type => 'int', not_null => 1 },
      name => { type => 'varchar', length => 255 },
      ...
    );

    __PACKAGE__->meta->primary_key_columns('k1', 'k2');

    __PACKAGE__->meta->initialize;

    __PACKAGE__->meta->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.

RESERVED METHODS

As 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 suddently 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")

AUTHOR

John C. Siracusa (siracusa@mindspring.com)

COPYRIGHT

Copyright (c) 2005 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.