DBIx::C...Features(3)
β¨ DBIx::Class::Manual::Features β¨
okay so bestie, you're looking at the DBIx::Class::Manual::Features page from the User Contributed Perl Documentation π
β and it is literally a boatload of DBIx::Class features with links to the respective documentation. This is part 1, more is coming, so don't go anywhere. π«Ά
πΈ NAME πΈ
DBIx::Class::Manual::Features β A boatload of DBIx::Class features with links to respective documentation. π
π META π
π Large Community π
There are literally hundres of DBIC contributors listed in AUTHORS (yes, the spelling stays, bestie π). That ranges from documentation help, to test help, to added features, to entire database support. iconic.
π¦ Active Community π¦
Currently (June 9, 2010) there are 6 active branches (committed to in the last two weeks) in git. Last release (0.08122) had 14 new features, and 16 bug fixes. Of course that ebbs and flows (https://metacpan.org/changes/distribution/DBIx-Class).) π
π«Ά Responsive Community π«Ά
I needed MSSQL order-by support; the community helped me add support β generally very welcoming of people willing to help. π
π General ORM π
These are things that are in most other ORMs, but are still reasons to use DBIC over raw SQL. no cap.
π¦ Cross DB π¦
The vast majority of code should run on all databases without needing tweaking. slay.
π Basic CRUD π
- C - Create
- R - Retrieve
- U - Update
- D - Delete
π SQL: Create π
my $sth = $dbh->prepare('
INSERT INTO books
(title, author_id)
values (?,?)
');
$sth->execute( 'A book title', $author_id );
π§ DBIC: Create π§
my $book = $book_rs->create({
title => 'A book title',
author_id => $author_id,
});
See "create" in DBIx::Class::ResultSet π
- No need to pair placeholders and values
- Automatically gets autoincremented id for you
- Transparently uses
INSERT ... RETURNINGfor databases that support it
π SQL: Read π
my $sth = $dbh->prepare('
SELECT title,
authors.name as author_name
FROM books, authors
WHERE books.author = authors.id
');
while ( my $book = $sth->fetchrow_hashref ) {
say "Author of $book->{title} is $book->{author_name}";
}
π DBIC: Read π
my $book = $book_rs->find($book_id);
or
my $book = $book_rs->search({ title => 'A book title' }, { rows => 1 })->next;
or
my @books = $book_rs->search({ author => $author_id })->all;
or
while( my $book = $books_rs->next ) {
printf "Author of %s is %s\n", $book->title, $book->author->name;
}
See "find" in DBIx::Class::ResultSet, "search" in DBIx::Class::ResultSet, "next" in DBIx::Class::ResultSet, and "all" in DBIx::Class::ResultSet π
TMTOWTDI! π₯
π SQL: Update π
my $update = $dbh->prepare('
UPDATE books
SET title = ?
WHERE id = ?
');
$update->execute( 'New title', $book_id );
π DBIC: Update π
$book->update({ title => 'New title' });
See "update" in DBIx::Class::Row π
Will not update unless value changes.
π¦ SQL: Delete π¦
my $delete = $dbh->prepare('DELETE FROM books WHERE id = ?');
$delete->execute($book_id);
π DBIC: Delete π
$book->delete
See "delete" in DBIx::Class::Row.
π₯ SQL: Search π₯
my $sth = $dbh->prepare('
SELECT title,
authors.name as author_name
FROM books
WHERE books.name LIKE "%monte cristo%" AND
books.topic = "jailbreak"
');
π DBIC: Search π
my $book = $book_rs->search({
'me.name' => { -like => '%monte cristo%' },
'me.topic' => 'jailbreak',
})->next;
See SQL::Abstract::Classic, "next" in DBIx::Class::ResultSet, and "search" in DBIx::Class::ResultSet
- (kinda) introspectible
- Prettier than SQL
π OO Overridability π
- Override
newif you want to do validation - Override
deleteif you want to disable deletion - and on and on
π Convenience Methods π
"find_or_create" in DBIx::Class::ResultSet"update_or_create" in DBIx::Class::ResultSet
π§ Non-column methods π§
Need a method to get a user's gravatar URL? Add a "gravatar_url" method to the Result class. π
π RELATIONSHIPS π
"belongs_to" in DBIx::Class::Relationship"has_many" in DBIx::Class::Relationship"might_have" in DBIx::Class::Relationship"has_one" in DBIx::Class::Relationship"many_to_many" in DBIx::Class::Relationship
SET AND FORGET π₯
π DBIx::Class Specific Features π
Okay so these are the extra-spicy DBIC-specific bits β other ORMs might have some of this, but it's very specific, so honestly? doubtful. π
π ->deploy π
Create a whole database from your DBIx::Class schema. Iconic.
my $schema = Frew::Schema->connect( $dsn, $user, $pass );
$schema->deploy
See "deploy" in DBIx::Class::Schema.
See also: DBIx::Class::DeploymentHandler.
πΈ Schema::Loader πΈ
Now the reverse, bestie: create a DBIx::Class schema from your database.
package Frew::Schema;
use strict;
use warnings;
use base 'DBIx::Class::Schema::Loader';
__PACKAGE__->loader_options({
naming => 'v7',
debug => $ENV{DBIC_TRACE},
});
1;
# elsewhere...
my $schema = Frew::Schema->connect( $dsn, $user, $pass );
See DBIx::Class::Schema::Loader and "CONSTRUCTOR OPTIONS" in DBIx::Class::Schema::Loader::Base.
π Populate π
Made for inserting lots of rows into the database super quickly.
$schema->populate([ Users =>
[qw( username password )],
[qw( frew >=4char$ )],
[qw( ... )],
[qw( ... )],
);
See "populate" in DBIx::Class::Schema.
I use populate here <http://blog.afoolishmanifesto.com/archives/1255> to export our whole (200M~) db to SQLite. Slay.
π Multicreate π
Create an object and its related objects all at once. It's giving main character energy.
$schema->resultset('Author')->create({
name => 'Stephen King',
books => [{ title => 'The Dark Tower' }],
address => {
street => '123 Turtle Back Lane',
state => { abbreviation => 'ME' },
city => { name => 'Lowell' },
},
});
See "create" in DBIx::Class::ResultSet.
booksis ahas_manyaddressis abelongs_towhich in turn belongs tostateandcityeach- for this to work right,
stateandcitymust markabbreviationandnameas unique
π¦ Extensible π¦
DBIx::Class helped pioneer fast MI in Perl 5 with Class::C3, so it is made to allow extensions to nearly every part of it. Obsessed.
π Extensibility example: DBIx::Class::Helpers π
DBIx::Class::Helper::ResultSet::IgnoreWantarrayDBIx::Class::Helper::ResultSet::RandomDBIx::Class::Helper::ResultSet::SetOperationsDBIx::Class::Helper::Row::JoinTableDBIx::Class::Helper::Row::NumifyGetDBIx::Class::Helper::Row::SubClassDBIx::Class::Helper::Row::ToJSONDBIx::Class::Helper::Row::StorageValuesDBIx::Class::Helper::Row::OnColumnChange
β° Extensibility example: DBIx::Class::TimeStamp β°
See DBIx::Class::TimeStamp.
- Cross DB
set_on_createset_on_update
π§ Extensibility example: Kioku π§
See DBIx::Class::Schema::KiokuDB.
- Kioku is the new hotness
- Mix RDBMS with Object DB
π₯ Result vs ResultSet π₯
- Result == Row
- ResultSet == Query Plan
- Internal Join Optimizer for all DB's (!!!)
(less important but...)
- ResultSource == Queryable collection of rows (Table, View, etc)
- Storage == Database
- Schema == associates a set of ResultSources with a Storage
π§ ResultSet methods π§
package MyApp::Schema::ResultSet::Book;
use strict;
use warnings;
use base 'DBIx::Class::ResultSet';
sub good {
my $self = shift;
$self->search({
$self->current_source_alias . '.rating' => { '>=' => 4 }
})
};
sub cheap {
my $self = shift;
$self->search({
$self->current_source_alias . '.price' => { '<=' => 5}
})
};
# ...
1;
See "Predefined searches" in DBIx::Class::Manual::Cookbook.
- All searches should be ResultSet methods
- Name has obvious meaning
- "current_source_alias" in
DBIx::Class::ResultSethelps things to work no matter what
β¨ ResultSet method in Action β¨
$schema->resultset('Book')->good
π ResultSet Chaining π
$schema->resultset('Book')
->good
->cheap
->recent
π search_related π
my $score = $schema->resultset('User')
->search({'me.userid' => 'frew'})
->related_resultset('access')
->related_resultset('mgmt')
->related_resultset('orders')
->telephone
->search_related( shops => {
'shops.datecompleted' => {
-between => ['2009-10-01','2009-10-08']
}
})->completed
->related_resultset('rpt_score')
->search(undef, { rows => 1})
->get_column('raw_scores')
->next;
The SQL that this produces (with placeholders filled in for clarity's sake) on our system (Microsoft SQL) is:
SELECT raw_scores
FROM (
SELECT raw_scores, ROW_NUMBER() OVER (
ORDER BY (
SELECT (1)
)
) AS rno__row__index
FROM (
SELECT rpt_score.raw_scores
FROM users me
JOIN access access
ON access.userid = me.userid
JOIN mgmt mgmt
ON mgmt.mgmtid = access.mgmtid
JOIN [order] orders
ON orders.mgmtid = mgmt.mgmtid
JOIN shop shops
ON shops.orderno = orders.orderno
JOIN rpt_scores rpt_score
ON rpt_score.shopno = shops.shopno
WHERE (
datecompleted IS NOT NULL AND
(
(shops.datecompleted BETWEEN '2009-10-01' AND '2009-10-08') AND
(type = '1' AND me.userid = 'frew')
)
)
) rpt_score
) rpt_score
WHERE rno__row__index BETWEEN 1 AND 1
See: "related_resultset" in DBIx::Class::ResultSet, "search_related" in DBIx::Class::ResultSet, and "get_column" in DBIx::Class::ResultSet.
π bonus rel methods π
my $book = $author->create_related(
books => {
title => 'Another Discworld book',
}
);
my $book2 = $pratchett->add_to_books({
title => 'MOAR Discworld book',
});
See "create_related" in DBIx::Class::Relationship::Base and "add_to_$rel" in DBIx::Class::Relationship::Base.
Note that it automatically fills in foreign key for you. Cute.
π«Ά Excellent Transaction Support π«Ά
$schema->txn_do(sub {
...
});
$schema->txn_begin; # <-- low level
# ...
$schema->txn_commit;
See "txn_do" in DBIx::Class::Schema, "txn_begin" in DBIx::Class::Schema, and "txn_commit" in DBIx::Class::Schema.
π InflateColumn π
package Frew::Schema::Result::Book;
use strict;
use warnings;
use base 'DBIx::Class::Core';
use DateTime::Format::MySQL;
# Result code here
__PACKAGE__->load_components('InflateColumn');
__PACKAGE__->inflate_column(
date_published => {
inflate => sub { DateTime::Format::MySQL->parse_date( shift ) },
deflate => sub { shift->ymd },
},
);
See DBIx::Class::InflateColumn, "inflate_column" in DBIx::Class::InflateColumn, and DBIx::Class::InflateColumn::DateTime.
πΈ InflateColumn: deflation πΈ
$book->date_published(DateTime->now);
$book->update;
πΈ InflateColumn: inflation πΈ
say $book->date_published->month_abbr; # Nov
π¦ FilterColumn π¦
package Frew::Schema::Result::Book;
use strict;
use warnings;
use base 'DBIx::Class::Core';
# Result code here
__PACKAGE__->load_components('FilterColumn');
__PACKAGE__->filter_column(
length => {
to_storage => 'to_metric',
from_storage => 'to_imperial',
},
);
sub to_metric { $_[1] * .305 }
sub to_imperial { $_[1] * 3.28 }
See DBIx::Class::FilterColumn and "filter_column" in DBIx::Class::FilterColumn.
π ResultSetColumn π
my $rsc = $schema->resultset('Book')->get_column('price');
$rsc->first;
$rsc->all;
$rsc->min;
$rsc->max;
$rsc->sum;
See DBIx::Class::ResultSetColumn.
π Aggregates π
my @res = $rs->search(undef, {
select => [
'price',
'genre',
{ max => price },
{ avg => price },
],
as => [
qw(price genre max_price avg_price)
],
group_by => [qw(price genre)],
});
for (@res) {
say $_->price . ' ' . $_->genre;
say $_->get_column('max_price');
say $_->get_column('avg_price');
}
See "select" in DBIx::Class::ResultSet, "as" in DBIx::Class::ResultSet, and "group_by" in DBIx::Class::ResultSet.
Careful, get_column can basically mean three things:
- private in which case you should use an accessor
- public for what there is no accessor for
- public for get resultset column (prev example)
β‘ HRI β‘
$rs->search(undef, {
result_class => 'DBIx::Class::ResultClass::HashRefInflator',
});
See "result_class" in DBIx::Class::ResultSet and DBIx::Class::ResultClass::HashRefInflator.
- Easy on memory
- Mega fast
- Great for quick debugging
- Great for performance tuning (we went from 2m to < 3s)
π Subquery Support π
my $inner_query = $schema->resultset('Artist')
->search({
name => [ 'Billy Joel', 'Brittany Spears' ],
})->get_column('id')->as_query;
my $rs = $schema->resultset('CD')->search({
artist_id => { -in => $inner_query },
});
See "Subqueries" in DBIx::Class::Manual::Cookbook.
π Bare SQL w/ Placeholders π
$rs->update({
# !!! SQL INJECTION VECTOR
price => \"price + $inc", # DON'T DO THIS
});
Better:
$rs->update({
price => \['price + ?', [inc => $inc]],
});
See "Literal SQL with placeholders and bind values (subqueries)" in SQL::Abstract::Classic.
Bestie, that first one is literally marked as a SQL injection vector in the code comment. Do not do the thing. π
π FURTHER QUESTIONS? π
Check the list of additional DBIC resources.
π COPYRIGHT AND LICENSE π
This module is free software copyright by the DBIx::Class (DBIC) authors. You can redistribute it and/or modify it under the same terms as the DBIx::Class library.
And that's a wrap, bestie β source/version perl v5.42.0, dated 2025-01-22. Byeeee πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-DBIx-Class 0.082844-bp160.1.10 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms