DBIx::OO(3pm)
๐ DBIx::OO(3pm) ๐
User Contributed Perl Documentation ยท DBIx::OO(3pm)
okay bestie sit down, hydrate, and let me tell you about DBIx::OO โ a whole module that turns your database into Perl objects. yes. your tables. as objects. slay. ๐ซถ
โจ NAME โจ
DBIx::OO โ Database to Perl objects abstraction
๐ SYNOPSIS ๐
package MyDB;
use base 'DBIx::OO';
# We need to overwrite get_dbh since it's 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('dbi:mysql:test', 'user', 'passwd')
if !defined $dbh;
return $dbh;
}
package MyDB::Users;
use base 'MyDB';
__PACKAGE__->table('Users');
__PACKAGE__->columns(P => [ 'id' ],
E => [qw/ first_name last_name email /]);
__PACKAGE__->has_many(pages => 'MyDB::Pages', 'user');
package MyDB::Pages;
use base 'MyDB';
__PACKAGE__->table('Pages');
__PACKAGE__->columns(P => [ 'id' ],
E => [qw/ title content user /]);
__PACKAGE__->has_a(user => 'MyDB::Users');
package main;
my $u = MyDB::Users->create({ id => 'userid',
first_name => 'Q',
last_name => 'W' });
my $foo = MyDB::Users->retrieve('userid');
my @p = @{ $foo->fk_pages };
print "User: ", $foo->first_name, " ", $foo->last_name, " pages:\n";
foreach (@p) {
print $_->title, "\n";
}
$foo->first_name('John');
$foo->last_name('Doe');
# or
$foo->set(first_name => 'John', last_name => 'Doe');
$foo->update;
๐จ IMPORTANT NOTE ๐จ
fr fr read this one. This code has only been tested with MySQL. That's what the author uses. There just isn't a lot of spare time to test/fix it for other DBMS-es โ and like, it shouldn't be too difficult, but for now this is it. Volunteers are welcome!! ๐
๐ธ DESCRIPTION ๐ธ
This module was inspired by the absolutely wonderful Class::DBI. It's a database-to-Perl-Objects abstraction layer, and it lets you talk to a database using plain, normal Perl syntax. it's giving convenience. it's giving vibes. ๐ฆ
๐ญ Why another Class::DBI "clone"?
- The author had the feeling that Class::DBI is no longer maintained. (Turns out that doesn't seem to be the case, because:)
- Their code got broken multiple times by Class::DBI upgrades. ๐ญ
- Class::DBI doesn't quote table or field names, which makes it straight-up impossible to use a column named, say,
'group'with MySQL. - They wanted to know very well what happens "under the hood". main character energy, honestly.
- They hoped this module would be faster than CDBI. Not sure that's actually the case, but it for sure has fewer features. :-)
- There's more than one way to do it. periodt.
All in all, it's now used in production code, so this thing is here to stay. ๐
โจ Features โจ
- retrieve, search, create, update, delete โ just like Class::DBI, there are functions to retrieve an object by the primary key, search a table and create multiple objects at once, create a new object, and update an existing object.
- manage fields with convenient accessors โ same as Class::DBI: every declared column in a table gets an accessor. Usually the accessor has the same name as the column name, but heads up, there are cases where that's just not possible โ names like
can,get,set, etc. โ because DBIx::OO or its parent objects already define those functions and they mean something totally different.
When the column name can't be used, it gets prefixed with col_ โ so if you have a table with a column named can, its accessor is named col_can. iykyk. ๐
- has_a, has_many, has_mapping โ a few types of table relationships are supported. They bring some nice features, though overall they're not as flexible as Class::DBI's. The syntax is pretty different too, so be sure to actually check the documentation of these functions.
- JOIN-s โ
has_aalso creates a search function that lets you retrieve data from both tables using a JOIN construct. This can drastically reduce the number of SQL queries needed to fetch a list of objects. ๐ฅ
๐ Missing features:
- NO caching of any kind โ DBIx::OO does not cache objects. Which means you can have the same DB record living in multiple Perl objects at once. Sometimes that can put you in trouble (not if you're careful though).
At some point the author might want to implement object uniqueness like Class::DBI does, but not for now.
- NO triggers โ triggers are nice, but they can cause considerable performance problems when misused.
UPDATE: the only trigger that currently exists is before_set() โ check its documentation.
- A lot others โ constraints, integrity maintenance, etc. By contrast, Class::DBI has a lot of nice features, but the performance price you pay for them is just too big, honestly. The hope is for this module to stay small and be fast.
๐ QUICK START ๐
You need to subclass DBIx::OO to provide an implementation of the get_dbh() method. That function is pure virtual and it should retrieve the database handler โ as returned by DBI->connect โ for the database you want to use. You can totally use an interim package for that, like MyDB in the example above.
Then each derived package handles exactly one table, and should set up its columns and relationships. one table per package, that's the rule bestie. โจ
๐ API DOCUMENTATION ๐
new()
Right now, new() takes no arguments and constructs an empty object. You normally shouldn't need to call this directly. lowkey leave it alone. ๐
get_dbh()
This method should return a database handler, as returned by DBI->connect. The default implementation croaks, so you need to overwrite it in your subclasses. And to write it only once, you can use an intermediate object. ๐
table($table_name)
Call this method in each derived package to tell DBIx::OO which table you want that package to use.
__PACKAGE__->table('Users')
columns(group[=> cols, ...])
Sets/retrieves the columns of the current package.
Same vibe as 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 gets fetched whenever the object is first instantiated. You can specify any other group names here too, and they'll simply group the retrieval of columns.
Example:
__PACKAGE__->columns(P => [ 'id' ],
E => [ 'name', 'description' ],
X => [ 'c1', 'big_content1', 'big_title1' ],
Y => [ 'c2', 'big_content2', 'big_title2' ]);
The code above defines 4 groups. When an object is first instantiated, it will fetch 'id', 'name' and 'description'. When you say $obj->c1, it will fetch 'c1, 'big_content1' and 'big_title1', because they're all in the same group. When you say $obj->c2 it will fetch 'c2', 'big_content2' and 'big_title2'. That's pretty much like Class::DBI. ๐
To retrieve columns, you pass a group name.
Notes
- Class::DBI lets you call
columns()multiple times, passing one group at a time. This module should allow that too, but it's untested and might be buggy. The suggestion is: define all your groups in one shot, like in the example above. no cap. - Group
'P'is required. I mean that. It will not guess the primary key column like Class::DBI does. ๐ซ
clone_columns(@except)
Even though it's public, you probably won't need this one. It returns a list of column names that would be cloned in a clone() operation. By default it excludes any columns in the "P" group (primary keys), but you can pass a list of other names to exclude as well.
defaults(%hash)
With this function you can declare some default values for your columns. They'll be used unless alternative values are specified when a record is inserted (e.g. with create()). Example:
__PACKAGE__->defaults(created => ['now()'],
hidden => 1,
modified_by => \&get_current_user_id);
You can specify any scalar supported by SQL::Abstract's insert operation. For instance, an array reference specifies literal SQL (won't be quoted). Additionally, you can pass code references, in which case the subroutine gets called right when the data is inserted, and its return value will be used. cute, right? ๐
get(field_name[, field_name, ...])
Retrieves the value of one or more columns. If you pass more column names, it returns an array of values, in the right order.
set(field => value[, field => value, ...])
Sets one or more columns to the specified value(s).
This function calls "before_set" right before modifying the object data, passing a hash reference to the new values. ๐
before_set
By default this function does nothing. It gets called by the framework right before setting column values. A hash reference with the columns to be set will be passed. You can modify this hash if you want to. For example, assuming you have an Users table with an MD5 password and you want to create the MD5 right when the column is set, you can do this:
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('foo');
$u->password('foobar');
print $u->password;
# be8cd58c70ad7dc935802fdb051869fe
The $is_create argument will be true (1) if this function is called as a result of a create() command. ๐
id()
Returns the value(s) of the primary key(s). If the primary key consists of more columns, this method returns an array with the values, in the order the PK column names were specified.
Currently this is equivalent to $self->get(@{ $self->columns('P') }).
transaction_start(), transaction_rollback(), transaction_commit()
Use these functions to start, commit or rollback a DB transaction. They simply call begin_work, rollback and commit methods on the DB handle returned by get_dbh(). no drama, just transactions. ๐ง
get_accessor_name()
There are a few column names that just can't be allowed 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:
idcanourcolumnstablegetsetcount
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 of the above forbidden names as accessors โ basically nothing will work. ๐
get_fk_name
This function returns the name of a foreign key accessor, as defined by has_a/has_many. The default returns "fk_$name" โ thus prepending "fk_".
If you want the Class::DBI behavior, you can override this function in your derived module:
sub get_fk_name { return $_[1]; }
(the first argument is gonna be an object ref. or a package name, bestie, so like, heads up)
ngl I think the Class::DBI model is kinda unwise. SO many times my columns got inflated into whole objects when I was literally just expecting an ID back?? like girl what. Having the code do implicit work for you is cute and all, but you can lowkey spend hours debugging when it guesses wrong โ which is exactly why DBIx::OO defaults to slapping a "fk_" in front of the foreign-object accessors. you'll get used to it. periodt. ๐
โจ "has_a/has_many" โจ
__PACKAGE__->has_a(name, type[, mapping[, order ]]);
__PACKAGE__->has_many(name, type[, mapping[, order[, limit[, offset ]]]]);
okay so this creates a relationship between two packages. in the simplest form you just say:
__PACKAGE__->has_a(user => Users);
this declaration makes a relation between __PACKAGE__ (assuming it's got a column called 'user') and the 'Users' package. it's assuming that 'user' from the current package points to the primary key of the Users package. ๐ซถ
and the declaration creates a method called 'fk_user', which you can call to grab the pointed-at object. example:
package Pages;
use base 'MyDB';
__PACKAGE__->columns('P' => [ 'id' ],
'E' => [ 'user', ... ]);
__PACKAGE__->has_a(user => 'Users');
my $p = Pages->retrieve(1);
my $u = $p->fk_user;
print $u->first_name;
in more complex situations, you might need to point at a different field than the target package's primary key. you'd call it like this:
Users->has_many(pages => Pages, 'user');
my $u = Users->retrieve('foo');
my @pages = @{ $u->fk_pages };
the above says that a User has many pages, and that they're determined by mapping the 'user' field of the Pages package to the primary key of the "Users" package. iconic.
has_many() also defines a little utility function that lets us easily count the number of rows in the referenced table, without actually retrieving their data. example:
print $u->count_pages;
you can specify a WHERE clause too, in SQL::Abstract syntax:
print $u->count_pages(keywords => { -like => '%dhtml%' });
the above returns the number of DHTML pages that belong to the user. ๐ฅ
in EVEN more complex cases, you wanna 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:
## FIXME: find a good example
has_many() is super similar to has_a, but the accessor it creates just returns multiple values (as an array ref). we can pass some arguments too โ either to has_a/has_many declarations, or to the accessor itself.
@pages = @{ $u->fk_pages('created', 10, 5) }
the above will retrieve the user's pages ordered by 'created', starting at OFFSET 5 and LIMIT-ing to 10 results.
you can use has_a even when there's not a direct mapping. example: a page can have multiple revisions, but we can also easily access the first/last revision:
Pages->has_many(revisions => 'Revisions', 'page');
Pages->has_a(first_revision => 'Revisions', 'page', 'created');
Pages->has_a(last_revision => 'Revisions', 'page', '^created');
has_a() will LIMIT the result to one. ordering the results by 'created', we make sure we actually retrieve what we need. note that by prefixing the column name with a '^' character, we're asking the module to do a DESC ordering. ๐
(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 ;-)
๐ Join ๐
has_a() will additionally create a join function. it lets you select data from 2 tables using a single SQL query. example:
package MyDB::Users;
MyDB::Users->table('Users');
MyDB::Users->has_a(profile => 'Profiles');
package MyDB::Profiles;
MyDB::Profiles->table('Profiles');
@data = Users->search_join_profile;
foreach (@data) {
my $user = $_->{Users}; # the key is the SQL B<table> name
my $profile = $_->{Profiles};
print $user->id, " has address: ", $profile->address;
}
the above only does 1 SELECT. note that the join search function returns an array of hashes that map from the SQL table name to the DBIx::OO instance. โจ
you can pass additional WHERE, ORDER, LIMIT and OFFSET clauses to the join functions as well:
@data = Users->search_join_profile({ 'Users.last_name' => 'Doe' },
'Users.nickname',
10);
the above fetches the first 10 members of the Doe family ordered by nickname. slay.
due to lack of support from the SQL::Abstract side, the JOIN is actually a select like this:
SELECT ... FROM table1, table2 WHERE table1.foreign = table2.id
in the future I hope to add better support for this โ that is, use "INNER JOIN" and eventually support other JOIN types as well. ๐
๐ฆ Notes ๐ฆ
- the
"fk_"accessors will actually retrieve data at each call. therefore:
$p1 = $user->fk_pages;
$p2 = $user->fk_pages;
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 it. it's best to keep a reference to the returned object(s) rather than calling fk_pages() all over the place. ๐
has_many()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 LIMIT your results.
๐ "might_have()" ๐
alias to has_a().
๐ "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:
Users: id, first_name, etc.
Groups: id, description, etc.
Users_To_Groups: user, group
this is quite classical, I suppose, for declaring 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:
SELECT group FROM Users_To_Group where user = '$user'
but since you usually need the Group objects directly, you could speed things up with a join:
SELECT Groups.id, Groups.description, ... FROM Groups, Users_To_Groups
WHERE Users_To_Groups.group = Groups.id
AND Users_To_Groups.user = '$user';
the relationship declared with has_mapping() does exactly that. you'd call it like this:
package Users;
__PACKAGE__->table('Users');
__PACKAGE__->columns(P => [ 'id' ], ...);
__PACKAGE__->has_mapping(groups, 'Groups',
'Users_To_Groups', 'user', 'group');
package Groups;
__PACKAGE__->table('Groups');
__PACKAGE__->columns(P => [ 'id' ], ...);
# You can get the reverse mapping as well:
__PACKAGE__->has_mapping(users, 'Users',
'Users_To_Groups', 'group', 'user');
package Users_To_Groups;
__PACKAGE__->table('Users_To_Groups');
__PACKAGE__->columns(P => [ 'user', 'group' ]);
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.
๐ธ Arguments ๐ธ
I started with an example because the function itself is quite complicated, fr fr. here's the argument documentation:
- name โ this is used to name the accessors. by default we'll prepend a
"fk_"(seeget_fk_name). - type โ the type of the target objects.
- 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.
- map1 โ specifies how we map from the current package (
__PACKAGE__) to the"maptype"object. this can be a scalar or a hash ref. if it's a scalar, we'll assume that__PACKAGE__has a simple primary key (not multiple) and"map1"is the name of the column from"maptype"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"maptype". if that sounds horrible, check the example below. ๐ญ - map2 โ similar to
"map1", but"map2"specifies the mapping from"maptype"to the target"type". if a scalar, it'll be the name of the column from"maptype"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. - order, limit, offset โ similar to
has_many, these can specify default ORDER BY and/or LIMIT/OFFSET clauses for the resulting query.
๐ Example ๐
here's the mapping overview:
map1 map2
__PACKAGE__ ===> C<maptype> ===> C<type>
current package table that holds the target package
the mapping
โญ "create" โญ
my $u = Users->create({ id => 'foo',
first_name => 'John',
last_name => 'Doe' });
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. ๐ซถ
๐ clone(@except) ๐
clones an object, returning a hash (reference) suitable for create(). here's how you'd call it:
my $val = $page->clone;
my $new_page = Pages->create($val);
or, supposing you don't want to copy the value of the "created" field:
my $val = $page->clone('created');
my $new_page = Pages->create($val);
๐ง "init_from_data($data)" ๐ง
initializes one or more objects from the given data. $data 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).
the hashes simply contain the data, as retrieved from the database. that is, map column name to field value.
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 wanna initialize DBIx::OO objects without the penalty of going through the DB again. โจ
๐ "retrieve" ๐
my $u = Users->retrieve('foo');
Ok bestie, so retrieve is literally the glow-up you need to grab an object from the database. You gotta pass its ID (that's the value of the primary key). If your primary key is a whole squad of columns, you can pass the values in order as an array, or you can pass a hash reference. Returns undef if no objects were found โ like, ghosted. ๐ป
"search($where, $order, $limit, $offset)"
$a = Users->search({ created => [ '>=', '2006-01-01 00:00:00' ]});
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 DB. The syntax of $where and $order are described in SQL::Abstract.
In scalar context it will return a reference to the array.
The $limit and $offset arguments are added by DBIx::OO and allow you to limit/paginate your query. Slay for pagination! ๐
UPDATE 0.0.7:
Certain queries are difficult to express in SQL::Abstract syntax. The search accepts a literal WHERE clause too, but until version 0.0.7 there was no way to specify bind variables. For example, now you can do this:
@admins = Users->search("mode & ? <> 0 and created > ?",
undef, undef, undef,
MODE_FLAGS->{admin},
strftime('%Y-%m-%d', localtime)).
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. No cap, that's the tea. โ
"retrieve_all()"
retrieve_all() is an alias to search() โ since with no arguments it fetches all objects. Iconic shortcut energy. โจ
"update"
$u->set(first_name => 'Foo',
last_name => 'Bar');
$u->update;
Saves any modified columns to the database. Periodt, your changes are locked in. ๐
"delete"
$u = Users->retrieve('foo');
$u->delete;
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 undelete(). It's giving phoenix rising from the ashes. ๐ฅ
"undelete"
$u = Users->retrieve('foo');
$u->delete; # record's gone
$u->undelete; # resurrected
This function can "ressurect" 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 delete() function. :-)
Other (useless) thing you can do with it is manually emulating the create() function:
$u = new Users;
$u->{values}{id} = 'foo';
$u->first_name('Foo');
$u->last_name('Bar');
$u->undelete;
Note we can't call the column accessors, nor use set/get, before we have a primary key. Main character rule: no primary key, no vibes. ๐ โโ๏ธ
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 "under the hood". iykyk ๐ง
"revert", or "discard_changes"
$u = Users->retrieve('foo');
$u->first_name(undef);
$u->revert;
Discards any changes to the object, reverting to the state in the database. Note this doesn't SELECT new data, it just reverts to values saved in the "modified" hash. See "under the hood" for more info. It's like Ctrl+Z but for your object's soul. โฉ๏ธ
"discard_changes()" is an alias to "revert()".
get_sql_abstract
Returns the instance of SQL::Abstract::WithLimit (our custom derivative) suitable for generating SQL. This is cached (will be created only the first time get_sql_abstract is called). One and done, bestie. ๐
count
Returns the result of an SQL COUNT(*) for the specified where clause. Call this as a package method, for example:
$number_of_romanians = Users->count({ country => 'RO' });
The argument is an SQL::Abstract where clause. Counting cuties, one query at a time. ๐ข
"disable_fk_checks()", "enable_fk_checks()"
Enable or disable foreign key checks in the backend DB server. These are hard-coded in MySQL syntax for now so be careful not to use them with other servers. ;-) โ ๏ธ Warning: MySQL-only vibes, don't try this at home with Postgres. ๐จ
"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 "big" idea.
package MyDB::Users;
use base 'MyDB';
__PACKAGE__->table('Users');
__PACKAGE__->columns(P => [ 'id' ],
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)
}}
OK, now you can write this make_database.pl script:
/usr/bin/perl -w
use MyDB;
MyDB->autocreate(qw( MyDB::Users ));
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. Set it and forget it, queen. ๐
Later. You sold a billion copies of your software, customers are happy but they are crying loud for an "email" 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, append the following to your get_autocreate_data section:
#### (users:1) ####
# (note that we incremented the version number)
# add the 'email' 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);
Now you can just tell your users to run make_database.pl again and everything gets updated. Upgrade era, no cap. ๐
The #### (foo:N) #### syntax is meant simply to declare an ID and a version number. "foo" can be anything you want -- it doesn't have to be the table name. You can actually create multiple tables, if you need to. Flexible? We love to see it. ๐
autopopulate
This is supposed to initialize tables. Untested and may not work -- don't use it. ๐ Do not pass go, do not collect $200. ๐
get_autocreate_data
See the documentation of "autocreate". Go read that section, bestie. ๐
CAVEATS
There are a number of problems you might encounter, mostly related to the fact that we don't cache objects. Buckle up, buttercup. ๐ฆ
Concurrent objects
$u1 = Users->retrieve('foo');
$u2 = Users->retrieve('foo');
$u1 and $u2 now point to different objects, but both point to the same record in the database. Now the problem:
$u1->first_name('Foo');
$u2->first_name('Bar');
$u1->update;
Which one gets set? 'Foo', but $u2 has uncommitted changes. When you further say $u2->update, it will set the name to 'Bar'. If you say $u2->revert, it will revert to whatever was there before 'Foo'. This can lead to potential problems. It's giving drama between two objects. ๐ญ
Class::DBI (almost) doesn't have this problem (it can appear when you have multiple processes accessing the database concurrently, such as httpd processes). So if you're running a web server, be extra careful. ๐
UNDER THE HOOD
A DBIx::OO object is a hash blessed into the DBIx::OO package. The hash currently contains 2 keys:
valuesโ A hash containing thefield => valuepairs that are currently retrieved from the database. Your data's home base. ๐modifiedโ Another hash that mapsfield_name => 'original value'for the fields that were modified and not yet committed of the current object. The receipts of what you changed. ๐งพ
If a field is not present in values and is requested with get(), then the database will be queried for it and for all other fields that aren't present in "values" but are listed in the Essential group.
If a field is present in modified, then it will be saved in the DB on the next update() call. An object can discard these operations with the discard() method. Discard restores the values using those stored in the "modified" hash. It's like a save point in a video game. ๐ฎ
Each operation plays around these hashes. For instance, when you call search(), a single SQL will run and then we'll iterate over the results, create objects and assign the SELECT-ed values to the values hash. Efficiency queen. ๐
A retrieve() 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 DB. 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 values -- but it's good to call it because retrieve() should return undef if the object can't be found in the DB. Better safe than sorry, bestie. ๐ก๏ธ
BUGS
Yeah, the documentation sucks. Other bugs? Not me reading the docs and finding this. ๐
SEE ALSO
SQL::Abstract, Class::DBI, DBIx::Class Go check these out if you're curious. ๐
AUTHOR
Mihai Bazon, <mihai.bazon@gmail.com> http://www.dynarch.com/ http://www.bazon.net/mishoo/
COPYRIGHT
Copyright (c) Mihai Bazon 2006. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Free as in freedom, periodt. ๐๏ธ
THANKS
I'd like to thank irc.n0i.net -- our small but wonderful community that's always there when you need it. Shoutout to the group chat! ๐ซถ
DISCLAIMER OF WARRANTY
BECAUSE 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 "AS IS" 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.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED 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 (INCLUDING 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), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Basically: it's free, use at your own risk, no take-backs. We're not liable if your database ghosts you. ๐ญ
And that's the whole page, bestie! This was for DBIx::OO(3pm), from perl v5.34.0, dated 2022-06-13. Stay slay, keep your queries cute, and may your primary keys always be unique. ๐โจ
๐ฆ where this page comes from
- debian bookworm: libdbix-oo-perl 0.0.9-6 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libdbix-oo-perl 0.0.9-6 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libdbix-oo-perl 0.0.9-6 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libdbix-oo-perl 0.0.9-6 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libdbix-oo-perl 0.0.9-6 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms