.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "DBIx::OO 3pm"
.TH DBIx::OO 3pm "2022-06-13" "perl v5.34.0" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
DBIx::OO \- Database to Perl objects abstraction
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 2
\& package MyDB;
\& use base \*(AqDBIx::OO\*(Aq;
\&
\& # We need to overwrite get_dbh since it\*(Aqs an abstract function.
\& # The way you connect to the DB is really your job; this function
\& # should return the database handle. The default get_dbh() croaks.
\&
\& my $dbh;
\& sub get_dbh {
\& $dbh = DBI\->connect_cached(\*(Aqdbi:mysql:test\*(Aq, \*(Aquser\*(Aq, \*(Aqpasswd\*(Aq)
\& if !defined $dbh;
\& return $dbh;
\& }
\&
\& package MyDB::Users;
\& use base \*(AqMyDB\*(Aq;
\&
\& _\|_PACKAGE_\|_\->table(\*(AqUsers\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ],
\& E => [qw/ first_name last_name email /]);
\& _\|_PACKAGE_\|_\->has_many(pages => \*(AqMyDB::Pages\*(Aq, \*(Aquser\*(Aq);
\&
\& package MyDB::Pages;
\& use base \*(AqMyDB\*(Aq;
\&
\& _\|_PACKAGE_\|_\->table(\*(AqPages\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ],
\& E => [qw/ title content user /]);
\& _\|_PACKAGE_\|_\->has_a(user => \*(AqMyDB::Users\*(Aq);
\&
\& package main;
\&
\& my $u = MyDB::Users\->create({ id => \*(Aquserid\*(Aq,
\& first_name => \*(AqQ\*(Aq,
\& last_name => \*(AqW\*(Aq });
\&
\& my $foo = MyDB::Users\->retrieve(\*(Aquserid\*(Aq);
\& my @p = @{ $foo\->fk_pages };
\& print "User: ", $foo\->first_name, " ", $foo\->last_name, " pages:\en";
\& foreach (@p) {
\& print $_\->title, "\en";
\& }
\&
\& $foo\->first_name(\*(AqJohn\*(Aq);
\& $foo\->last_name(\*(AqDoe\*(Aq);
\ or
\& $foo\->set(first_name => \*(AqJohn\*(Aq, last_name => \*(AqDoe\*(Aq);
\& $foo\->update;
.Ve
.SH "IMPORTANT NOTE"
.IX Header "IMPORTANT NOTE"
This code is tested only with MySQL. That's what I use. I don't have
too much time to test/fix it for other DBMS-es (it shouldn't be too
difficult though), but for now this is it... Volunteers are welcome.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This module has been inspired by the wonderful Class::DBI. It is a
database-to-Perl-Objects abstraction layer, allowing you to interact
with a database using common Perl syntax.
.ie n .SS "Why another Class::DBI ""clone""?"
.el .SS "Why another Class::DBI ``clone''?"
.IX Subsection "Why another Class::DBI clone?"
.IP "1." 4
I had the feeling that Class::DBI is no longer maintained. This
doesn't seem to be the case, because:
.IP "2." 4
My code was broken multiple times by Class::DBI upgrades.
.IP "3." 4
Class::DBI doesn't quote table or field names, making it impossible to
use a column named, say, 'group' with MySQL.
.IP "4." 4
I wanted to know very well what happens \*(L"under the hood\*(R".
.IP "5." 4
I hoped my module would be faster than \s-1CDBI.\s0 I'm not sure this
is the case, but it certainly has less features. :\-)
.IP "6." 4
There's more than one way to do it.
.PP
All in all, I now use it in production code so this thing is here to
stay.
.SS "Features"
.IX Subsection "Features"
.IP "\fBretrieve, search, create, update, delete\fR" 4
.IX Item "retrieve, search, create, update, delete"
As Class::DBI, we have functions to retrieve an object by the primary
key, search a table and create multiple objects at once, create a new
object, update an existing object.
.IP "\fBmanage fields with convenient accessors\fR" 4
.IX Item "manage fields with convenient accessors"
Same like Class::DBI, we provide accessors for each declared column in
a table. Usually accessors will have the same name as the column
name, but note that there are cases when we can't do that, such as
\&\*(L"can\*(R", \*(L"get\*(R", \*(L"set\*(R", etc. \*(-- because DBIx::OO or parent objects
already define these functions and have a different meaning.
.Sp
When it is not possible to use the column name, it is prefixed with
\&\*(L"col_\*(R" \*(-- so if you have a table with a column named \*(L"can\*(R", its
accessor will be named \*(L"col_can\*(R".
.IP "\fBhas_a, has_many, has_mapping\fR" 4
.IX Item "has_a, has_many, has_mapping"
We support a few types of table relationships. They provide a few
nice features, though overally are not as flexible as Class::DBI's.
The syntax is quite different too, be sure to check the
documentation of these functions.
.IP "\fB\s-1JOIN\s0\fR\-s" 4
.IX Item "JOIN-s"
has_a also creates a search function that allows you to retrieve data
from both tables using a \s-1JOIN\s0 construct. This can drastically reduce
the number of \s-1SQL\s0 queries required to fetch a list of objects.
.SS "Missing features:"
.IX Subsection "Missing features:"
.IP "\fB\s-1NO\s0 caching of any kind\fR" 4
.IX Item "NO caching of any kind"
DBIx::OO does not cache objects. This means that you can have the
same \s-1DB\s0 record in multiple Perl objects. Sometimes this can put you
in trouble (not if you're careful though).
.Sp
At some point I might want to implement object uniqueness like
Class::DBI, but not for now.
.IP "\fB\s-1NO\s0 triggers\fR" 4
.IX Item "NO triggers"
Triggers are nice, but can cause considerable performance problems
when misused.
.Sp
\&\s-1UPDATE:\s0 The only trigger that currently exists is \fBbefore_set()\fR, check
its documentation.
.IP "\fBA lot others\fR" 4
.IX Item "A lot others"
Constraints, integrity maintenance, etc. By contrast Class::DBI has a
lot of nice features, but I think the performance price we pay for
them is just too big. I hope this module to stay small and be fast.
.SH "QUICK START"
.IX Header "QUICK START"
You need to subclass DBIx::OO in order to provide an
implementation to the \fBget_dbh\fR() method. This function is pure
virtual and should retrieve the database handler, as returned by
\&\fB\s-1DBI\-\s0>connect\fR, for the database that you want to use. You can
use an interim package for that, as we did in our example above
(\fBMyDB\fR).
.PP
Then, each derived package will handle exactly one table, should setup
columns and relationships.
.SH "API DOCUMENTATION"
.IX Header "API DOCUMENTATION"
.ie n .SS """new()"""
.el .SS "\f(CWnew()\fP"
.IX Subsection "new()"
Currently, \fB\fBnew()\fB\fR takes no arguments and constructs an empty object.
You normally shouldn't need to call this directly.
.ie n .SS """get_dbh()"""
.el .SS "\f(CWget_dbh()\fP"
.IX Subsection "get_dbh()"
This method should return a database handler, as returned by
\&\s-1DBI\-\s0>connect. The default implementation croaks, so you \fIneed\fR to
overwrite it in your subclasses. To write it only once, you can use
an intermediate object.
.ie n .SS """table($table_name)"""
.el .SS "\f(CWtable($table_name)\fP"
.IX Subsection "table($table_name)"
Call this method in each derived package to inform DBIx::OO of the
table that you wish that package to use.
.PP
.Vb 1
\& _\|_PACKAGE_\|_\->table(\*(AqUsers\*(Aq)
.Ve
.ie n .SS """columns(group[=> cols, ...])"""
.el .SS "\f(CWcolumns(group[=> cols, ...])\fP"
.IX Subsection "columns(group[=> cols, ...])"
Sets/retrieves the columns of the current package.
.PP
Similarly to Class::DBI, DBIx::OO uses a sort of column grouping.
The 'P' group is always the primary key. The 'E' group is the
essential group\*(--which will be fetched whenever the object is first
instantiated. You can specify any other groups names here, and they
will simply group retrieval of columns.
.PP
Example:
.PP
.Vb 4
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ],
\& E => [ \*(Aqname\*(Aq, \*(Aqdescription\*(Aq ],
\& X => [ \*(Aqc1\*(Aq, \*(Aqbig_content1\*(Aq, \*(Aqbig_title1\*(Aq ],
\& Y => [ \*(Aqc2\*(Aq, \*(Aqbig_content2\*(Aq, \*(Aqbig_title2\*(Aq ]);
.Ve
.PP
The above code defines 4 groups. When an object is first
instantiated, it will fetch 'id', 'name' and 'description'. When you
say \f(CW$obj\fR\->c1, it will fetch 'c1, 'big_content1' and 'big_title1',
because they are in the same group. When you say \f(CW$obj\fR\->c2 it will
fetch 'c2', 'big_content2' and 'big_title2'. That's pretty much like
Class::DBI.
.PP
To retrieve columns, you pass a group name.
.PP
\fINotes\fR
.IX Subsection "Notes"
.IP "\(bu" 4
Class::DBI allows you to call \fBcolumns()\fR multiple times, passing one
group at a time. Our module should allow this too, but it's untested
and might be buggy. We suggest defining all groups in one shot, like
the example above.
.IP "\(bu" 4
Group 'P' is \fIrequired\fR. I mean that. We won't guess the primary
key column like Class::DBI does.
.ie n .SS """clone_columns(@except)"""
.el .SS "\f(CWclone_columns(@except)\fP"
.IX Subsection "clone_columns(@except)"
Though public, it's likely you won't need this function. It returns
a list of column names that would be cloned in a \fBclone()\fR operation.
By default it excludes any columns in the "\fBP\fR" group (primary keys)
but you can pass a list of other names to exclude as well.
.ie n .SS """defaults(%hash)"""
.el .SS "\f(CWdefaults(%hash)\fP"
.IX Subsection "defaults(%hash)"
Using this function you can declare some default values for your
columns. They will be used unless alternative values are specified
when a record is inserted (e.g. with \fBcreate()\fR). Example:
.PP
.Vb 3
\& _\|_PACKAGE_\|_\->defaults(created => [\*(Aqnow()\*(Aq],
\& hidden => 1,
\& modified_by => \e&get_current_user_id);
.Ve
.PP
You can specify any scalar supported by SQL::Abstract's insert
operation. For instance, an array reference specifies literal \s-1SQL\s0
(won't be quoted). Additionally, you can pass code references, in
which case the subroutine will be called right when the data is
inserted and its return value will be used.
.ie n .SS """get(field_name[, field_name, ...])"""
.el .SS "\f(CWget(field_name[, field_name, ...])\fP"
.IX Subsection "get(field_name[, field_name, ...])"
Retrieves the value of one or more columns. If you pass more column
names, it will return an array of values, in the right order.
.ie n .SS """set(field => value[, field => value, ...])"""
.el .SS "\f(CWset(field => value[, field => value, ...])\fP"
.IX Subsection "set(field => value[, field => value, ...])"
Sets one or more columns to the specified value(s).
.PP
This function calls \f(CW\*(C`before_set\*(C'\fR right before modifying the object
data, passing a hash reference to the new values.
.ie n .SS """before_set"""
.el .SS "\f(CWbefore_set\fP"
.IX Subsection "before_set"
By default this function does nothing. It will be called by the
framework right before setting column values. A hash reference with
columns to be set will be passed. You can modify this hash if you
wish. For example, assuming you have an Users table with a \s-1MD5\s0
password and you want to create the \s-1MD5\s0 right when the column is set,
you can do this:
.PP
.Vb 1
\& package Users;
\&
\& ...
\&
\& sub before_set {
\& my ($self, $h, $is_create) = @_;
\& if (exists $h\->{password}) {
\& $h\->{password} = make_md5_passwd($h\->{password});
\& }
\& }
\&
\& my $u = Users\->retrieve(\*(Aqfoo\*(Aq);
\& $u\->password(\*(Aqfoobar\*(Aq);
\& print $u\->password;
\& # be8cd58c70ad7dc935802fdb051869fe
.Ve
.PP
The \f(CW$is_create\fR argument will be true (1) if this function is called as
a result of a \fBcreate()\fR command.
.ie n .SS """id()"""
.el .SS "\f(CWid()\fP"
.IX Subsection "id()"
Returns the value(s) of the primary key(s). If the primary key
consists of more columns, this method will return an array with the
values, in the order the \s-1PK\s0 column names were specified.
.PP
Currently this is equivalent to \f(CW$self\fR\->get(@{ \f(CW$self\fR\->columns('P') }).
.ie n .SS """transaction_start()"", ""transaction_rollback()"", ""transaction_commit()"""
.el .SS "\f(CWtransaction_start()\fP, \f(CWtransaction_rollback()\fP, \f(CWtransaction_commit()\fP"
.IX Subsection "transaction_start(), transaction_rollback(), transaction_commit()"
Use these functions to start, commit or rollback a \s-1DB\s0 transaction.
These simply call begin_work, rollback and commit methods on the \s-1DB\s0
handle returned by \fBget_dbh()\fR.
.ie n .SS """get_accessor_name()"""
.el .SS "\f(CWget_accessor_name()\fP"
.IX Subsection "get_accessor_name()"
There are a few column names that we can't allow as accessor names.
This function receives a column name and returns the name of the
accessor for that field. By default it prefixes forbidden names with
\&'col_'. The forbidden names are:
.PP
.Vb 8
\& \- id
\& \- can
\& \- our
\& \- columns
\& \- table
\& \- get
\& \- set
\& \- count
.Ve
.PP
If you don't like this behavior you can override this function in your
classes to return something else. However, be very careful about
allowing any the above forbidden names as accessors\*(--basically nothing
will work.
.ie n .SS """get_fk_name"""
.el .SS "\f(CWget_fk_name\fP"
.IX Subsection "get_fk_name"
This function returns the name of a foreign key accessor, as defined
by has_a/has_many. The default returns
\&\*(L"fk_$name\*(R"\-\-thus prepending \*(L"fk_\*(R".
.PP
If you want the Class::DBI behavior, you can override this function in
your derived module:
.PP
.Vb 1
\& sub get_fk_name { return $_[1]; }
.Ve
.PP
(the first argument will be object ref. or package)
.PP
I think the Class::DBI model is unwise. Many times I found my columns
inflated to objects when I was in fact expecting to get an \s-1ID.\s0 Having
the code do implicit work for you is nice, but you can spend hours
debugging when it gets it wrong\*(--which is why, DBIx::OO will by
default prepend a \*(L"fk_\*(R" to foreign objects accessors. You'll get use
to it.
.ie n .SS """has_a/has_many"""
.el .SS "\f(CWhas_a/has_many\fP"
.IX Subsection "has_a/has_many"
.Vb 2
\& _\|_PACKAGE_\|_\->has_a(name, type[, mapping[, order ]]);
\& _\|_PACKAGE_\|_\->has_many(name, type[, mapping[, order[, limit[, offset ]]]]);
.Ve
.PP
Creates a relationship between two packages. In the simplest form,
you call:
.PP
.Vb 1
\& _\|_PACKAGE_\|_\->has_a(user => Users);
.Ve
.PP
This declaration creates a relation between _\|_PACKAGE_\|_ (assuming it
has a column named 'user') and 'Users' package. It is assuming that
\&'user' from the current package points to the primary key of the Users
package.
.PP
The declaration creates a method named 'fk_user', which you can call
in order to retrieve the pointed object. Example:
.PP
.Vb 5
\& package Pages;
\& use base \*(AqMyDB\*(Aq;
\& _\|_PACKAGE_\|_\->columns(\*(AqP\*(Aq => [ \*(Aqid\*(Aq ],
\& \*(AqE\*(Aq => [ \*(Aquser\*(Aq, ... ]);
\& _\|_PACKAGE_\|_\->has_a(user => \*(AqUsers\*(Aq);
\&
\& my $p = Pages\->retrieve(1);
\& my $u = $p\->fk_user;
\& print $u\->first_name;
.Ve
.PP
In more complex cases, you might need to point to a different field
than the primary key of the target package. You can call it like
this:
.PP
.Vb 3
\& Users\->has_many(pages => Pages, \*(Aquser\*(Aq);
\& my $u = Users\->retrieve(\*(Aqfoo\*(Aq);
\& my @pages = @{ $u\->fk_pages };
.Ve
.PP
The above specifies that an User has many pages, and that they are
determined by mapping the 'user' field of the Pages package to the
\&\fIprimary key\fR of the \f(CW\*(C`Users\*(C'\fR package.
.PP
\&\fBhas_many()\fR also defines an utility function that allows us to easily
count the number of rows in the referenced table, without retrieving
their data. Example:
.PP
.Vb 1
\& print $u\->count_pages;
.Ve
.PP
You can specify an \s-1WHERE\s0 clause too, in SQL::Abstract syntax:
.PP
.Vb 1
\& print $u\->count_pages(keywords => { \-like => \*(Aq%dhtml%\*(Aq });
.Ve
.PP
The above returns the number of \s-1DHTML\s0 pages that belong to the user.
.PP
In even more complex cases, you want to map one or more arbitrary
columns of one package to columns of another package, so you can pass
a hash reference that describes the column mapping:
.PP
.Vb 1
\& ## FIXME: find a good example
.Ve
.PP
\&\fBhas_many()\fR is very similar to has_a, but the accessor it creates
simply returns multiple values (as an array ref). We can pass some
arguments too, either to has_a/has_many declarations, or to the
accessor.
.PP
.Vb 1
\& @pages = @{ $u\->fk_pages(\*(Aqcreated\*(Aq, 10, 5) }
.Ve
.PP
The above will retrieve the user's pages ordered by 'created',
starting at \s-1OFFSET 5\s0 and LIMIT-ing to 10 results.
.PP
You can use has_a even if there's not a direct mapping. Example, a
page can have multiple revisions, but we can also easily access the
first/last revision:
.PP
.Vb 3
\& Pages\->has_many(revisions => \*(AqRevisions\*(Aq, \*(Aqpage\*(Aq);
\& Pages\->has_a(first_revision => \*(AqRevisions\*(Aq, \*(Aqpage\*(Aq, \*(Aqcreated\*(Aq);
\& Pages\->has_a(last_revision => \*(AqRevisions\*(Aq, \*(Aqpage\*(Aq, \*(Aq^created\*(Aq);
.Ve
.PP
\&\fBhas_a()\fR will \s-1LIMIT\s0 the result to one. Ordering the results by
\&'created', we make sure that we actually retrieve what we need.
\&\fBNote\fR that by prefixing the column name with a '^' character, we're
asking the module to do a \s-1DESC\s0 ordering.
.PP
(Of course, it's a lot faster if we had first_revision and
last_revision as columns in the Pages table that link to Revision id,
but we just wanted to point out that the above is possible ;\-)
.PP
\fIJoin\fR
.IX Subsection "Join"
.PP
\&\fBhas_a()\fR will additionally create a join function. It allows you to
select data from 2 tables using a single \s-1SQL\s0 query. Example:
.PP
.Vb 3
\& package MyDB::Users;
\& MyDB::Users\->table(\*(AqUsers\*(Aq);
\& MyDB::Users\->has_a(profile => \*(AqProfiles\*(Aq);
\&
\& package MyDB::Profiles;
\& MyDB::Profiles\->table(\*(AqProfiles\*(Aq);
\&
\& @data = Users\->search_join_profile;
\& foreach (@data) {
\& my $user = $_\->{Users}; # the key is the SQL B
name
\& my $profile = $_\->{Profiles};
\& print $user\->id, " has address: ", $profile\->address;
\& }
.Ve
.PP
The above only does 1 \s-1SELECT.\s0 Note that the join search function
returns an array of hashes that map from the \s-1SQL\s0 table name to the
DBIx::OO instance.
.PP
You can pass additional \s-1WHERE, ORDER, LIMIT\s0 and \s-1OFFSET\s0 clauses to the
join functions as well:
.PP
.Vb 3
\& @data = Users\->search_join_profile({ \*(AqUsers.last_name\*(Aq => \*(AqDoe\*(Aq },
\& \*(AqUsers.nickname\*(Aq,
\& 10);
.Ve
.PP
The above fetches the first 10 members of the Doe family ordered by
nickname.
.PP
Due to lack of support from SQL::Abstract side, the \s-1JOIN\s0 is actually a
select like this:
.PP
.Vb 1
\& SELECT ... FROM table1, table2 WHERE table1.foreign = table2.id
.Ve
.PP
In the future I hope to add better support for this, that is, use
\&\*(L"\s-1INNER JOIN\*(R"\s0 and eventually support other \s-1JOIN\s0 types as well.
.PP
\fINotes\fR
.IX Subsection "Notes"
.IP "1." 4
The \f(CW\*(C`fk_\*(C'\fR accessors will actually retrieve data at each call.
Therefore:
.Sp
.Vb 2
\& $p1 = $user\->fk_pages;
\& $p2 = $user\->fk_pages;
.Ve
.Sp
will retrieve 2 different arrays, containing different sets of objects
(even if they point to the same records), hitting the database twice.
This is subject to change, but for now you have to be careful about
this. It's best to keep a reference to the returned object(s) rather
than calling \fBfk_pages()\fR all over the place.
.IP "2." 4
\&\fBhas_many()\fR creates accessors that select multiple objects. The
database will be hit once, though, and multiple objects are created
from the returned data. If this isn't desirable, feel free to \s-1LIMIT\s0
your results.
.ie n .SS """might_have()"""
.el .SS "\f(CWmight_have()\fP"
.IX Subsection "might_have()"
Alias to \fBhas_a()\fR.
.ie n .SS """has_mapping(name, type, maptype, map1, map2, order, limit, offset)"""
.el .SS "\f(CWhas_mapping(name, type, maptype, map1, map2, order, limit, offset)\fP"
.IX Subsection "has_mapping(name, type, maptype, map1, map2, order, limit, offset)"
You can use has_mapping to map one object to another using an
intermediate table. You can have these tables:
.PP
.Vb 3
\& Users: id, first_name, etc.
\& Groups: id, description, etc.
\& Users_To_Groups: user, group
.Ve
.PP
This is quite classical, I suppose, to declare many-to-many
relationships. The Users_To_Groups contains records that map one user
to one group. To get the ID-s of all groups that a certain user
belongs to, you would say:
.PP
.Vb 1
\& SELECT group FROM Users_To_Group where user = \*(Aq$user\*(Aq
.Ve
.PP
But since you usually need the Group objects directly, you could speed
things up with a join:
.PP
.Vb 3
\& SELECT Groups.id, Groups.description, ... FROM Groups, Users_To_Groups
\& WHERE Users_To_Groups.group = Groups.id
\& AND Users_To_Groups.user = \*(Aq$user\*(Aq;
.Ve
.PP
The relationship declared with \fBhas_mapping()\fR does exactly that. You
would call it like this:
.PP
.Vb 3
\& package Users;
\& _\|_PACKAGE_\|_\->table(\*(AqUsers\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ], ...);
\&
\& _\|_PACKAGE_\|_\->has_mapping(groups, \*(AqGroups\*(Aq,
\& \*(AqUsers_To_Groups\*(Aq, \*(Aquser\*(Aq, \*(Aqgroup\*(Aq);
\&
\& package Groups;
\& _\|_PACKAGE_\|_\->table(\*(AqGroups\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ], ...);
\&
\& # You can get the reverse mapping as well:
\& _\|_PACKAGE_\|_\->has_mapping(users, \*(AqUsers\*(Aq,
\& \*(AqUsers_To_Groups\*(Aq, \*(Aqgroup\*(Aq, \*(Aquser\*(Aq);
\&
\& package Users_To_Groups;
\& _\|_PACKAGE_\|_\->table(\*(AqUsers_To_Groups\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aquser\*(Aq, \*(Aqgroup\*(Aq ]);
.Ve
.PP
Note that Users_To_Groups has a multiple primary key. This isn't
required, but you should at least have an unique index for the (user,
group) pair.
.PP
\fIArguments\fR
.IX Subsection "Arguments"
.PP
I started with an example because the function itself is quite
complicated. Here are arguments documentation:
.IP "name" 4
.IX Item "name"
This is used to name the accessors. By default we will prepend a
\&\*(L"fk_\*(R" (see get_fk_name).
.IP "type" 4
.IX Item "type"
The type of the target objects.
.IP "maptype" 4
.IX Item "maptype"
The mapping object type. This is the name of the object that maps one
type to another. Even though you'll probably never need to
instantiate such an object, it still has to be declared.
.IP "map1" 4
.IX Item "map1"
Specifies how we map from current package (_\|_PACKAGE_\|_) to the
\&\f(CW\*(C`maptype\*(C'\fR object. This can be a scalar or an hash ref. If it's a
scalar, we will assume that _\|_PACKAGE_\|_ has a simple primary key (not
multiple) and \f(CW\*(C`map1\*(C'\fR is the name of the column from \f(CW\*(C`maptype\*(C'\fR that
we should map this key to. If it's a hash reference, it should
directly specify the mapping; the keys will be taken from _\|_PACKAGE_\|_
and the values from \f(CW\*(C`maptype\*(C'\fR. If that sounds horrible, check the
example below.
.IP "map2" 4
.IX Item "map2"
Similar to \f(CW\*(C`map1\*(C'\fR, but \f(CW\*(C`map2\*(C'\fR specifies the mapping from \f(CW\*(C`maptype\*(C'\fR
to the target \f(CW\*(C`type\*(C'\fR. If a scalar, it will be the name of the column
from \f(CW\*(C`maptype\*(C'\fR that maps to the primary key of the target package
(assumed to be a simple primary key). If a hash reference, it
specifies the full mapping.
.IP "order, limit, offset" 4
.IX Item "order, limit, offset"
Similar to has_many, these can specify default \s-1ORDER BY\s0 and/or
\&\s-1LIMIT/OFFSET\s0 clauses for the resulted query.
.PP
\fIExample\fR
.IX Subsection "Example"
.PP
Here's the mapping overview:
.PP
.Vb 4
\& map1 map2
\& _\|_PACKAGE_\|_ ===> C ===> C
\& current package table that holds the target package
\& the mapping
.Ve
.ie n .SS """create"""
.el .SS "\f(CWcreate\fP"
.IX Subsection "create"
.Vb 3
\& my $u = Users\->create({ id => \*(Aqfoo\*(Aq,
\& first_name => \*(AqJohn\*(Aq,
\& last_name => \*(AqDoe\*(Aq });
.Ve
.PP
Creates a new record and stores it in the database. Returns the newly
created object. We recommend passing a hash reference, but you can
pass a hash by value as well.
.SS "clone(@except)"
.IX Subsection "clone(@except)"
Clones an object, returning a hash (reference) suitable for \fBcreate()\fR.
Here's how you would call it:
.PP
.Vb 2
\& my $val = $page\->clone;
\& my $new_page = Pages\->create($val);
.Ve
.PP
Or, supposing you don't want to copy the value of the \*(L"created\*(R" field:
.PP
.Vb 2
\& my $val = $page\->clone(\*(Aqcreated\*(Aq);
\& my $new_page = Pages\->create($val);
.Ve
.ie n .SS """init_from_data($data)"""
.el .SS "\f(CWinit_from_data($data)\fP"
.IX Subsection "init_from_data($data)"
Initializes one or more objects from the given data. \f(CW$data\fR can be a
hashref (in which case a single object will be created and returned)
or an arrayref (multiple objects will be created and returned as an
array reference).
.PP
The hashes simply contain the data, as retrieved from the database.
That is, map column name to field value.
.PP
This method is convenient in those cases where you already have the
data (suppose you SELECT-ed it in a different way than using DBIx::OO)
and want to initialize DBIx::OO objects without the penalty of going
through the \s-1DB\s0 again.
.ie n .SS """retrieve"""
.el .SS "\f(CWretrieve\fP"
.IX Subsection "retrieve"
.Vb 1
\& my $u = Users\->retrieve(\*(Aqfoo\*(Aq);
.Ve
.PP
Retrieves an object from the database. You need to pass its \s-1ID\s0 (the
value of the primary key). If the primary key consists on more
columns, you can pass the values in order as an array, or you can pass
a hash reference.
.PP
Returns undef if no objects were found.
.ie n .SS """search($where, $order, $limit, $offset)"""
.el .SS "\f(CWsearch($where, $order, $limit, $offset)\fP"
.IX Subsection "search($where, $order, $limit, $offset)"
.Vb 1
\& $a = Users\->search({ created => [ \*(Aq>=\*(Aq, \*(Aq2006\-01\-01 00:00:00\*(Aq ]});
.Ve
.PP
Searches the database and returns an array of objects that match the
search criteria. All arguments are optional. If you pass no
arguments, it will return an array containing all objects in the \s-1DB.\s0
The syntax of \f(CW$where\fR and \f(CW$order\fR are described in
SQL::Abstract.
.PP
In scalar context it will return a reference to the array.
.PP
The \f(CW$limit\fR and \f(CW$offset\fR arguments are added by DBIx::OO and allow you
to limit/paginate your query.
.PP
\&\s-1UPDATE 0.0.7:\s0
.PP
Certain queries are difficult to express in SQL::Abstract syntax. The
search accepts a literal \s-1WHERE\s0 clause too, but until version 0.0.7
there was no way to specify bind variables. For example, now you can
do this:
.PP
.Vb 4
\& @admins = Users\->search("mode & ? <> 0 and created > ?",
\& undef, undef, undef,
\& MODE_FLAGS\->{admin},
\& strftime(\*(Aq%Y\-%m\-%d\*(Aq, localtime)).
.Ve
.PP
In order to pass bind variables, you must pass order, limit and offset
(give undef if you don't care about them) and add your bind variables
immediately after.
.ie n .SS """retrieve_all()"""
.el .SS "\f(CWretrieve_all()\fP"
.IX Subsection "retrieve_all()"
\&\fBretrieve_all()\fR is an alias to \fBsearch()\fR \*(-- since with no arguments it
fetches all objects.
.ie n .SS """update"""
.el .SS "\f(CWupdate\fP"
.IX Subsection "update"
.Vb 3
\& $u\->set(first_name => \*(AqFoo\*(Aq,
\& last_name => \*(AqBar\*(Aq);
\& $u\->update;
.Ve
.PP
Saves any modified columns to the database.
.ie n .SS """delete"""
.el .SS "\f(CWdelete\fP"
.IX Subsection "delete"
.Vb 2
\& $u = Users\->retrieve(\*(Aqfoo\*(Aq);
\& $u\->delete;
.Ve
.PP
Removes the object's record from the database. Note that the Perl
object remains intact and you can actually revive it (if you're not
losing it) using \fBundelete()\fR.
.ie n .SS """undelete"""
.el .SS "\f(CWundelete\fP"
.IX Subsection "undelete"
.Vb 3
\& $u = Users\->retrieve(\*(Aqfoo\*(Aq);
\& $u\->delete; # record\*(Aqs gone
\& $u\->undelete; # resurrected
.Ve
.PP
This function can \*(L"ressurect\*(R" an object that has been deleted (that
is, it re-INSERT-s the record into the database), provided that you
still have a reference to the object. I'm not sure how useful it is,
but it helped me test the \fBdelete()\fR function. :\-)
.PP
Other (useless) thing you can do with it is manually emulating the
\&\fBcreate()\fR function:
.PP
.Vb 5
\& $u = new Users;
\& $u\->{values}{id} = \*(Aqfoo\*(Aq;
\& $u\->first_name(\*(AqFoo\*(Aq);
\& $u\->last_name(\*(AqBar\*(Aq);
\& $u\->undelete;
.Ve
.PP
Note we can't call the column accessors, nor use set/get, before we
have a primary key.
.PP
This method is not too useful in itself, but it helps understanding
the internals of DBIx::OO. If you want to read more about this, see
\&\*(L"under the hood\*(R".
.ie n .SS """revert"", or ""discard_changes"""
.el .SS "\f(CWrevert\fP, or \f(CWdiscard_changes\fP"
.IX Subsection "revert, or discard_changes"
.Vb 3
\& $u = Users\->retrieve(\*(Aqfoo\*(Aq);
\& $u\->first_name(undef);
\& $u\->revert;
.Ve
.PP
Discards any changes to the object, reverting to the state in the
database. Note this doesn't \s-1SELECT\s0 new data, it just reverts to
values saved in the \f(CW\*(C`modified\*(C'\fR hash. See \*(L"under the hood\*(R" for more
info.
.PP
\&\f(CW\*(C`discard_changes()\*(C'\fR is an alias to \f(CW\*(C`revert()\*(C'\fR.
.SS "get_sql_abstract"
.IX Subsection "get_sql_abstract"
Returns the instance of SQL::Abstract::WithLimit (our custom
derivative) suitable for generating \s-1SQL.\s0 This is cached (will be
created only the first time get_sql_abstract is called).
.SS "count"
.IX Subsection "count"
Returns the result of an \s-1SQL COUNT\s0(*) for the specified where clause.
Call this as a package method, for example:
.PP
.Vb 1
\& $number_of_romanians = Users\->count({ country => \*(AqRO\*(Aq });
.Ve
.PP
The argument is an SQL::Abstract where clause.
.ie n .SS """disable_fk_checks()"", ""enable_fk_checks()"""
.el .SS "\f(CWdisable_fk_checks()\fP, \f(CWenable_fk_checks()\fP"
.IX Subsection "disable_fk_checks(), enable_fk_checks()"
Enable or disable foreign key checks in the backend \s-1DB\s0 server. These
are hard-coded in MySQL syntax for now so be careful not to use them
with other servers. ;\-)
.ie n .SS """autocreate(@packages)"""
.el .SS "\f(CWautocreate(@packages)\fP"
.IX Subsection "autocreate(@packages)"
You can use this facility to automatically create / upgrade your
database. It takes a very simple (rudimentary even) approach, but we
found it to be useful. Here's the \*(L"big\*(R" idea.
.PP
.Vb 2
\& package MyDB::Users;
\& use base \*(AqMyDB\*(Aq;
\&
\& _\|_PACKAGE_\|_\->table(\*(AqUsers\*(Aq);
\& _\|_PACKAGE_\|_\->columns(P => [ \*(Aqid\*(Aq ],
\& E => [qw/ first_name last_name /]);
\&
\&
\& sub get_autocreate_data {q{
\& #### (users:0) ####
\&
\& CREATE TABLE Users ( id VARCHAR(32) NOT NULL PRIMARY KEY,
\& first_name VARCHAR(64),
\& last_name VARCHAR(64) );
\&
\& # you can put Perl comments too.
\&
\& CREATE INDEX idx_Users_first_name ON Users(first_name)
\& }}
.Ve
.PP
\&\s-1OK,\s0 now you can write this make_database.pl script:
.PP
.Vb 1
\& /usr/bin/perl \-w
\&
\& use MyDB;
\& MyDB\->autocreate(qw( MyDB::Users ));
.Ve
.PP
When you run this script the first time, it will create the Users
table. (An internal _dbix_oo_versions table gets created as well;
we're using it inside DBIx::OO in order to keep track of existing
table versions). Note that if you run it again, it doesn't do
anything\*(--the database is up to date.
.PP
Later. You sold a billion copies of your software, customers are
happy but they are crying loud for an \*(L"email\*(R" field in their user
profiles, also wondering what was your idea to index on first_name and
not on last_name! In order to make it easy for them to upgrade their
databases, you need to modify MyDB::Users. Besides declaring the
\&'email' column using _\|_PACKAGE_\|_\->columns, \fBappend\fR the following to
your get_autocreate_data section:
.PP
.Vb 1
\& #### (users:1) ####
\&
\& # (note that we incremented the version number)
\&
\& # add the \*(Aqemail\*(Aq field
\& ALTER TABLE Users ADD (email VARCHAR(128));
\&
\& # index it
\& CREATE UNIQUE INDEX idx_Users_email ON Users(email);
\&
\& # and add that last_name index
\& CREATE INDEX idx_Users_last_name ON Users(last_name);
.Ve
.PP
Now you can just tell your users to run make_database.pl again and
everything gets updated.
.PP
The #### (foo:N) #### syntax is meant simply to declare an \s-1ID\s0 and a
version number. \*(L"foo\*(R" can be anything you want \*(-- it doesn't have to
be the table name. You can actually create multiple tables, if you
need to.
.SS "autopopulate"
.IX Subsection "autopopulate"
This is supposed to initialize tables. Untested and may not work \*(--
don't use it.
.SS "get_autocreate_data"
.IX Subsection "get_autocreate_data"
See the documentation of \*(L"autocreate\*(R".
.SH "CAVEATS"
.IX Header "CAVEATS"
There are a number of problems you might encounter, mostly related to
the fact that we don't cache objects.
.SS "Concurrent objects"
.IX Subsection "Concurrent objects"
.Vb 2
\& $u1 = Users\->retrieve(\*(Aqfoo\*(Aq);
\& $u2 = Users\->retrieve(\*(Aqfoo\*(Aq);
.Ve
.PP
\&\f(CW$u1\fR and \f(CW$u2\fR now point to different objects, but both point to
the same record in the database. Now the problem:
.PP
.Vb 3
\& $u1\->first_name(\*(AqFoo\*(Aq);
\& $u2\->first_name(\*(AqBar\*(Aq);
\& $u1\->update;
.Ve
.PP
Which one gets set? 'Foo', but \f(CW$u2\fR has uncommitted changes. When you
further say \f(CW$u2\fR\->update, it will set the name to 'Bar'. If you say
\&\f(CW$u2\fR\->revert, it will revert to whatever was there \fIbefore\fR 'Foo'.
This can lead to potential problems.
.PP
Class::DBI (almost) doesn't have this problem (it can appear when you
have multiple processes accessing the database concurrently, such as
httpd processes).
.SH "UNDER THE HOOD"
.IX Header "UNDER THE HOOD"
A DBIx::OO object is a hash blessed into the DBIx::OO package.
The hash currently contains 2 keys:
.IP "\fBvalues\fR" 4
.IX Item "values"
A hash containing the field => value pairs that are currently
retrieved from the database.
.IP "\fBmodified\fR" 4
.IX Item "modified"
Another hash that maps field_name => 'original value' for the fields
that were modified and not yet committed of the current object.
.PP
If a field is not present in \fBvalues\fR and is requested with \fBget()\fR,
then the database will be queried for it and for all other fields that
aren't present in \*(L"values\*(R" but are listed in the \fBE\fRssential group.
.PP
If a field is present in \fBmodified\fR, then it will be saved in the \s-1DB\s0
on the next \fBupdate()\fR call. An object can discard these operations
with the \fBdiscard()\fR method. Discard restores the values using those
stored in the \f(CW\*(C`modified\*(C'\fR hash.
.PP
Each operation plays around these hashes. For instance, when you call
\&\fBsearch()\fR, a single \s-1SQL\s0 will run and then we'll iterate over the
results, create objects and assign the SELECT-ed values to the
\&\fBvalues\fR hash.
.PP
A \fBretrieve()\fR operation creates a new object and assign the passed
value to its primary key, then it will call the internal
_retrieve_columns([ 'P', 'E' ]) function in order to fetch essential
object data from the \s-1DB.\s0 Note that a call to _retrieve_columns is not
actually necessary, since it will happen anyway the first time you
want to retrieve a field that doesn't exist in \fBvalues\fR \*(-- but it's
good to call it because \fBretrieve()\fR should return \fBundef\fR if the
object can't be found in the \s-1DB.\s0
.SH "BUGS"
.IX Header "BUGS"
Yeah, the documentation sucks. Other bugs?
.SH "SEE ALSO"
.IX Header "SEE ALSO"
SQL::Abstract, Class::DBI, DBIx::Class
.SH "AUTHOR"
.IX Header "AUTHOR"
Mihai Bazon,
http://www.dynarch.com/
http://www.bazon.net/mishoo/
.SH "COPYRIGHT"
.IX Header "COPYRIGHT"
Copyright (c) Mihai Bazon 2006. All rights reserved.
.PP
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
.SH "THANKS"
.IX Header "THANKS"
I'd like to thank irc.n0i.net \*(-- our small but wonderful community
that's always there when you need it.
.SH "DISCLAIMER OF WARRANTY"
.IX Header "DISCLAIMER OF WARRANTY"
\&\s-1BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE SOFTWARE \*(L"AS IS\*(R" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.\s0
.PP
\&\s-1IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
SOFTWARE\s0 (\s-1INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE\s0), \s-1EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.\s0