NAME
Data::ObjectDriver::BaseObject - base class for modeled objects
SYNOPSIS
package Ingredient;
use base qw( Data::ObjectDriver::BaseObject );
__PACKAGE__->install_properties({
columns => [ 'ingredient_id', 'recipe_id', 'name', 'quantity' ],
datasource => 'ingredient',
primary_key => [ 'recipe_id', 'ingredient_id' ],
driver => FoodDriver->driver,
});
__PACKAGE__->has_a(
{ class => 'Recipe', column => 'recipe_id', }
);
package main;
my ($ingredient) = Ingredient->search({ recipe_id => 4, name => 'rutabaga' });
$ingredient->quantity(7);
$ingredient->save();
DESCRIPTION
Data::ObjectDriver::BaseObject provides services to data objects modeled with the Data::ObjectDriver object relational mapper.
CLASS DEFINITION
Class->install_properties(\%params)
Defines all the properties of the specified object class. Generally you should call install_properties()
in the body of your class definition, so the properties can be set when the class is use
d or require
d.
Required members of %params
are:
columns
All the columns in the object class. This property is an arrayref.
datasource
The identifier of the table in which the object class's data are stored. Usually the datasource is simply the table name, but the datasource can be decorated into the table name by the
Data::ObjectDriver::DBD
module if the database requires special formatting of table names.driver
orget_driver
The driver used to perform database operations (lookup, update, etc) for the object class.
driver
is the instance ofData::ObjectDriver
to use. If your driver requires configuration options not available when the properties are initially set, specify a coderef asget_driver
instead. It will be called the first time the driver is needed, storing the driver in the class'sdriver
property for subsequent calls.
The optional members of %params
are:
primary_key
The column or columns used to uniquely identify an instance of the object class. If one column (such as a simple numeric ID) identifies the class,
primary_key
should be a scalar. Otherwise,primary_key
is an arrayref.column_defs
Specifies types for specially typed columns, if any, as a hashref. For example, if a column holds a timestamp, name it in
column_defs
as adate
for proper handling with someData::ObjectDriver::Driver::DBD
database drivers. Columns for which types aren't specified are handled aschar
columns.Known
column_defs
types are:blob
A blob of binary data.
Data::ObjectDriver::Driver::DBD::Pg
maps this toDBI::Pg::PG_BYTEA
,DBD::SQLite
toDBI::SQL_BLOB
andDBD::Oracle
toORA_BLOB
.bin_char
A non-blob string of binary data.
Data::ObjectDriver::Driver::DBD::SQLite
maps this toDBI::SQL_BINARY
.
Other types may be defined by custom database drivers as needed, so consult their documentation.
db
The name of the database. When used with
Data::ObjectDriver::Driver::DBI
type object drivers, this name is passed to theinit_db
method when the actual database handle is being created.
Custom object drivers may define other properties for your object classes. Consult the documentation of those object drivers for more information.
Class->install_column($col, $def)
Modify the Class definition to declare a new column $col
of definition <$def> (see column_defs).
Class->has_a(@definitions)
NOTE: has_a
is an experimental system, likely to both be buggy and change in future versions.
Defines a foreign key reference between two classes, creating accessor methods to retrieve objects both ways across the reference. For each defined reference, two methods are created: one for objects of class Class
to load the objects they reference, and one for objects of the referenced class to load the set of Class
objects that reference them.
For example, this definition:
package Ingredient;
__PACKAGE__->has_a(
{ class => 'Recipe', column => 'recipe_id' },
);
would create Ingredient->recipe_obj
and Recipe->ingredient_objs
instance methods.
Each member of @definitions
is a hashref containing the parameters for creating one accessor method. The required members of these hashes are:
class
The class to associate.
column
The column or columns in this class that identify the primary key of the associated object. As with primary keys, use a single scalar string for a single column or an arrayref for a composite key.
The optional members of has_a()
definitions are:
method
The name of the accessor method to create.
By default, the method name is the concatenated set of column names with each
_id
suffix removed, and the suffix_obj
appended at the end of the method name. For example, ifcolumn
were['recipe_id', 'ingredient_id']
, the resulting method would be calledrecipe_ingredient_obj
by default.cached
Whether to keep a reference to the foreign object once it's loaded. Subsequent calls to the accessor method would return that reference immediately.
parent_method
The name of the reciprocal method created in the referenced class named in
class
.By default, that method is named with the lowercased name of the current class with the suffix
_objs
. For example, if in yourIngredient
class you defined a relationship withRecipe
on the columnrecipe_id
, this would create a$recipe->ingredient_objs
method.Note that if you reference one class with multiple sets of fields, you can omit only one parent_method; otherwise the methods would be named the same thing. For instance, if you had a
Friend
class with two references toUser
objects in itsuser_id
andfriend_id
columns, one of them would need aparent_method
.
Class->has_partitions(%param)
Defines that the given class is partitioned, configuring it for use with the Data::ObjectDriver::Driver::SimplePartition
object driver. Required members of %param
are:
number
The number of partitions in which objects of this class may be stored.
get_driver
A function that returns an object driver, given a partition ID and any extra parameters specified when the class's
Data::ObjectDriver::Driver::SimplePartition
was instantiated.
Note that only the parent object for use with the SimplePartition
driver should use has_partitions()
. See Data::ObjectDriver::Driver::SimplePartition
for more about partitioning.
BASIC USAGE
Class->lookup($id)
Returns the instance of Class
with the given value for its primary key. If Class
has a complex primary key (more than one column), $id
should be an arrayref specifying the column values in the same order as specified in the primary_key
property.
Class->search(\%terms, [\%args])
Returns all instances of Class
that match the values specified in \%terms
, keyed on column names. In list context, search
returns the objects containing those values. In scalar context, search
returns an iterator function containing the same set of objects.
Your search can be customized with parameters specified in \%args
. Commonly recognized parameters (those implemented by the standard Data::ObjectDriver
object drivers) are:
sort
A column by which to order the object results.
direction
If set to
descend
, the results (ordered by thesort
column) are returned in descending order. Otherwise, results will be in ascending order.limit
The number of results to return, at most. You can use this with
offset
to paginate yoursearch()
results.offset
The number of results to skip before the first returned result. Use this with
limit
to paginate yoursearch()
results.fetchonly
A list (arrayref) of columns that should be requested. If specified, only the specified columns of the resulting objects are guaranteed to be set to the correct values.
Note that any caching object drivers you use may opt to ignore
fetchonly
instructions, or decline to cache objects queried withfetchonly
.for_update
If true, instructs the object driver to indicate the query is a search, but the application may want to update the data after. That is, the generated SQL
SELECT
query will include aFOR UPDATE
clause.
All options are passed to the object driver, so your driver may support additional options.
Class->result(\%terms, [\%args])
Takes the same %terms and %args arguments that search takes, but instead of executing the query immediately, returns a Data::ObjectDriver::ResultSet object representing the set of results.
$obj->exists()
Returns true if $obj
already exists in the database.
$obj->save()
Saves $obj
to the database, whether it is already there or not. That is, save()
is functionally:
$obj->exists() ? $obj->update() : $obj->insert()
$obj->update()
Saves changes to $obj
, an object that already exists in its database.
$obj->insert()
Adds $obj
to the database in which it should exist, according to its object driver and configuration.
$obj->remove()
Deletes $obj
from its database.
$obj->replace()
Replaces $obj
in the database. Does the right thing if the driver knows how to REPLACE object, ala MySQL.
USAGE
Class->new(%columns)
Returns a new object of the given class, initializing its columns with the values in %columns
.
$obj->init(%columns)
Initializes $obj
i by initializing its columns with the values in %columns
.
Override this method if you must do initial configuration to new instances of $obj
's class that are not more appropriate as a post_load
callback.
Class->properties()
Returns the named object class's properties as a hashref. Note that some of the standard object class properties, such as primary_key
, have more convenient accessors than reading the properties directly.
Class->driver()
Returns the object driver for this class, invoking the class's get_driver function (and caching the result for future calls) if necessary.
Class->get_driver($get_driver_fn)
Sets the function used to find the object driver for Class objects (that is, the get_driver
property).
Note that once driver()
has been called, the get_driver
function is not used. Usually you would specify your function as the get_driver
parameter to install_properties()
.
Class->is_pkless()
Returns whether the given object class has a primary key defined.
Class->is_primary_key($column)
Returns whether the given column is or is part of the primary key for Class
objects.
$obj->primary_key()
Returns the values of the primary key fields of $obj
.
Class->primary_key_tuple()
Returns the names of the primary key fields of Class
objects.
$obj->is_same($other_obj)
Do a primary key check on $obj
and $<other_obj> and returns true only if they are identical.
$obj->object_is_stored()
Returns true if the object hasn't been stored in the database yet. This is particularly useful in triggers where you can then determine if the object is being INSERTED or just UPDATED.
$obj->pk_str()
returns the primary key has a printable string.
$obj->has_primary_key()
Returns whether the given object has values for all of its primary key fields.
$obj->uncache_object()
If you use a Cache driver, returned object will be automatically cached as a result of common retrieve operations. In some rare cases you may want the cache to be cleared explicitly, and this method provides you with a way to do it.
$obj->primary_key_to_terms([$id])
Returns $obj
's primary key as a hashref of values keyed on column names, suitable for passing as search()
terms. If $id
is specified, convert that primary key instead of $obj
's.
Class->datasource()
Returns the datasource for objects of class Class
. That is, returns the datasource
property of Class
.
Class->columns_of_type($type)
Returns the list of columns in Class
objects that hold data of type $type
, as an arrayref. Columns are of a certain type when they are set that way in Class
's column_defs
property.
$obj->set_values(\%values)
Sets all the columns of $obj
that are members of \%values
to the values specified there.
$obj->set_values_internal(\%values)
Sets new specified values of $obj
, without using any overridden mutator methods of $obj
and without marking the changed columns changed.
$obj->clone()
Returns a new object of the same class as $obj containing the same data, except for primary keys, which are set to undef
.
$obj->clone_all()
Returns a new object of the same class as $obj containing the same data, including all key fields.
Class->has_column($column)
Returns whether a column named $column
exists in objects of class <Class>.
Class->column_names()
Returns the list of columns in Class
objects as an arrayref.
$obj->column_values()
Returns the columns and values in the given object as a hashref.
$obj->column($column, [$value])
Returns the value of $obj
's column $column
. If $value
is specified, column()
sets the first.
Note the usual way of accessing and mutating column values is through the named accessors:
$obj->column('fred', 'barney'); # possible
$obj->fred('barney'); # preferred
$obj->is_changed([$column])
Returns whether any values in $obj
have changed. If $column
is given, returns specifically whether that column has changed.
$obj->changed_cols_and_pk()
Returns the list of all columns that have changed in $obj
since it was last loaded from or saved to the database, as a list.
$obj->changed_cols()
Returns the list of changed columns in $obj
as a list, except for any columns in $obj
's primary key (even if they have changed).
Class->lookup_multi(\@ids)
Returns a list (arrayref) of objects as specified by their primary keys.
Class->bulk_insert(\@columns, \@data)
Adds the given data, an arrayref of arrayrefs containing column values in the order of column names given in \@columns
, as directly to the database as Class
records.
Note that only some database drivers (for example, Data::ObjectDriver::Driver::DBD::Pg
) implement the bulk insert operation.
$obj->fetch_data()
Returns the current values from $obj
as saved in the database, as a hashref.
$obj->refresh()
Resets the values of $obj
from the database. Any unsaved modifications to $obj
will be lost, and any made meanwhile will be reflected in $obj
afterward.
$obj->column_func($column)
Creates an accessor/mutator method for column $column
, returning it as a coderef.
Override this if you need special behavior in all accessor/mutator methods.
$obj->deflate()
Returns a minimal representation of the object, for use in caches where you might want to preserve space (like memcached). Can also be overridden by subclasses to store the optimal representation of an object in the cache. For example, if you have metadata attached to an object, you might want to store that in the cache, as well.
Class->inflate($deflated)
Inflates the deflated representation of the object $deflated into a proper object in the class Class. That is, undoes the operation $deflated = $obj->deflate()
by returning a new object equivalent to $obj
.
TRANSACTION SUPPORT AND METHODS
Introduction
When dealing with the methods on this class, the transactions are global, i.e: applied to all drivers. You can still enable transactions per driver if you directly use the driver API.
Class->begin_work
This enable transactions globally for all drivers until the next rollback or commit call on the class.
If begin_work is called while a transaction is still active (nested transaction) then the two transactions are merged. So inner transactions are ignored and a warning will be emitted.
Class->rollback
This rollbacks all the transactions since the last begin work, and exits from the active transaction state.
Class->commit
Commits the transactions, and exits from the active transaction state.
Class->txn_debug
Just return the value of the global flag and the current working drivers in a hashref.
Class->txn_active
Returns true if a transaction is already active.
DIAGNOSTICS
Please specify a valid column for class
One of the class relationships you defined with
has_a()
was missing acolumn
member.Please define a valid method for column
One of the class relationships you defined with
has_a()
was missing itsmethod
member and a method name could not be generated, or the class for which you specified the relationship already has a method by that name. Perhaps you specified an additional accessor by the same name for that class.keys don't match with primary keys: list
The hashref of values you passed as the ID to
primary_key_to_terms()
was missing or had extra members. Perhaps you used a fullcolumn_values()
hash instead of only including that class's key fields.You tried to set inexistent column column name to value data on class name
The hashref you specified to
set_values()
contained keys that are not defined columns for that class of object. Perhaps you invoked it on the wrong class, or did not fully filter members of the hash out before using it.Cannot find column 'column' for class 'class'
The column you specified to
column()
does not exist for that class, you attempted to use an automatically generated accessor/mutator for a column that doesn't exist, or attempted to use a column accessor as a class method instead of an instance method. Perhaps you performed your call on the wrong class or variable, or misspelled a method or column name.Must specify column
You invoked the
column_func()
method without specifying a column name. Column names are required to create the accessor/mutator function, so it knows what data member of the object to use.number (of partitions) is required
You attempted to define partitioning for a class without specifying the number of partitions for that class in the
number
member. Perhaps your logic for determining the number of partitions resulted inundef
or 0.get_driver is required
You attempted to define partitioning for a class without specifying the function to find the object driver for a partition ID as the
get_driver
member.
BUGS AND LIMITATIONS
There are no known bugs in this module.
SEE ALSO
Data::ObjectDriver, Data::ObjectDriver::Driver::DBI, Data::ObjectDriver::Driver::SimplePartition
LICENSE
Data::ObjectDriver is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
AUTHOR & COPYRIGHT
Except where otherwise noted, Data::ObjectDriver is Copyright 2005-2006 Six Apart, cpan@sixapart.com. All rights reserved.