DBIx::C...sultSet(3)
๐ NAME ๐
DBIx::Class::ResultSet โ Represents a query used for fetching a set of results. Literally the query-holding bestie of DBIx::Class, and we're about to get into it.
โจ SYNOPSIS โจ
my $users_rs = $schema->resultset('User');
while( $user = $users_rs->next) {
print $user->username;
}
my $registered_users_rs = $schema->resultset('User')->search({ registered => 1 });
my @cds_in_2005 = $schema->resultset('CD')->search({ year => 2005 })->all();
๐ธ DESCRIPTION ๐ธ
A ResultSet is an object which stores a set of conditions representing a query. It is the backbone of DBIx::Class (i.e. the really important/useful bit). No cap, this is the main character object.
No SQL is executed on the database when a ResultSet is created โ it just stores all the conditions needed to create the query. It's giving "planning the fit, not wearing it yet."
A basic ResultSet representing the data of an entire table is returned by calling "resultset" on a DBIx::Class::Schema and passing in a Source name.
my $users_rs = $schema->resultset('User');
A new ResultSet is returned from calling "search" on an existing ResultSet. The new one will contain all the conditions of the original, plus any new conditions added in the "search" call.
A ResultSet also incorporates an implicit iterator. "next" and "reset" can be used to walk through all the DBIx::Class::Rows the ResultSet represents. Little cursor goblin energy, but make it useful.
The query that the ResultSet represents is only executed against the database when these methods are called: "find", "next", "all", "first", "single", "count".
If a resultset is used in a numeric context it returns the "count". However, if it is used in a boolean context it is always true. So if you want to check if a resultset has any results, you must use if $rs != 0.
Yeah, that boolean thing is the classic trap. A resultset object is still a truthy object even when the query would return zero rows.
๐ EXAMPLES ๐
Chaining resultsets
Let's say you've got a query that needs to be run to return some data to the user. But, you have an authorization system in place that prevents certain users from seeing certain information. So, you want to construct the basic query in one method, but add constraints to it in another. Chaining era.
sub get_data {
my $self = shift;
my $request = $self->get_request; # Get a request object somehow.
my $schema = $self->result_source->schema;
my $cd_rs = $schema->resultset('CD')->search({
title => $request->param('title'),
year => $request->param('year'),
});
$cd_rs = $self->apply_security_policy( $cd_rs );
return $cd_rs->all();
}
sub apply_security_policy {
my $self = shift;
my ($rs) = @_;
return $rs->search({
subversive => 0,
});
}
Resolving conditions and attributes
When a resultset is chained from another resultset (e.g.: my $new_rs = $old_rs->search(\%extra_cond, \%attrs)), conditions and attributes with the same keys need resolving. This is where the merge rules come in, bestie.
- If any of
"columns","select","as"are present, they reset the original selection, and start the selection"clean". - The
"join","prefetch","+columns","+select","+as"attributes are merged into the existing ones from the original resultset. - The
"where"and"having"attributes, and any search conditions, are merged with an SQL"AND"to the existing condition from the original resultset. - All other attributes are overridden by any new ones supplied in the search attributes.
Multiple queries
Since a resultset just defines a query, you can do all sorts of things with it with the same object.
# Don't hit the DB yet.
my $cd_rs = $schema->resultset('CD')->search({
title => 'something',
year => 2009,
});
# Each of these hits the DB individually.
my $count = $cd_rs->count;
my $most_recent = $cd_rs->get_column('date_released')->max();
my @records = $cd_rs->all;
And it's not just limited to SELECT statements.
$cd_rs->delete();
This is even cooler:
$cd_rs->create({ artist => 'Fred' });
Which is the same as:
$schema->resultset('CD')->create({
title => 'something',
year => 2009,
artist => 'Fred'
});
See: "search", "count", "get_column", "all", "create".
Custom ResultSet classes
To add methods to your resultsets, you can subclass DBIx::Class::ResultSet, similar to:
package MyApp::Schema::ResultSet::User;
use strict;
use warnings;
use base 'DBIx::Class::ResultSet';
sub active {
my $self = shift;
$self->search({ $self->current_source_alias . '.active' => 1 });
}
sub unverified {
my $self = shift;
$self->search({ $self->current_source_alias . '.verified' => 0 });
}
sub created_n_days_ago {
my ($self, $days_ago) = @_;
$self->search({
$self->current_source_alias . '.create_date' => {
'<=',
$self->result_source->schema->storage->datetime_parser->format_datetime(
DateTime->now( time_zone => 'UTC' )->subtract( days => $days_ago )
)}
});
}
sub users_to_warn { shift->active->unverified->created_n_days_ago(7) }
1;
See "load_namespaces" in DBIx::Class::Schema on how DBIC can discover and automatically attach Result-specific ResulSet classes.
ResultSet subclassing with Moose and similar constructor-providers
Using Moose or Moo in your ResultSet classes is usually overkill, but you may find it useful if your ResultSets contain a lot of business logic (e.g. has xml_parser, has json, etc) or if you just prefer to organize your code via roles.
In order to write custom ResultSet classes with Moo you need to use the following template. The BUILDARGS is necessary due to the unusual signature of the constructor provided by DBIC "->new($source, \%args)".
use Moo;
extends 'DBIx::Class::ResultSet';
sub BUILDARGS { $_[2] || {} } # ::RS::new() expects my ($class, $rsrc, $args) = @_
...your code...
1;
If you want to build your custom ResultSet classes with Moose, you need a similar, though a little more elaborate template in order to interface the inlining of the Moose-provided object constructor, with the DBIC one.
package MyApp::Schema::ResultSet::User;
use Moose;
use MooseX::NonMoose;
extends 'DBIx::Class::ResultSet';
sub BUILDARGS { $_[2] || {} } # ::RS::new() expects my ($class, $rsrc, $args) = @_
...your code...
__PACKAGE__->meta->make_immutable;
1;
The MooseX::NonMoose is necessary so that the Moose constructor does not entirely overwrite the DBIC one (in contrast Moo does this automatically). Alternatively, you can skip MooseX::NonMoose and get by with just Moose instead by doing:
__PACKAGE__->meta->make_immutable(inline_constructor => 0);
๐ METHODS ๐
new
- Arguments:
$source,\%attrs? - Return Value:
$resultset
The resultset constructor. Takes a source object (usually a DBIx::Class::ResultSourceProxy::Table) and an attribute hash (see "ATTRIBUTES" below). Does not perform any queries -- these are executed as needed by the other methods. Construction is chill; execution is the whole separate vibe.
Generally you never construct a resultset manually. Instead you get one from e.g. a "$schema->resultset('$source_name')" or "$another_resultset->search(...)" (the later called in scalar context):
my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
WARNING โ If called on an object, proxies to"new_result"instead, soperl my $cd = $schema->resultset('CD')->new({ title => 'Spoon' });will return a CD object, not a ResultSet, and is equivalent to:perl my $cd = $schema->resultset('CD')->new_result({ title => 'Spoon' });Please also keep in mind that many internals call"new_result"directly, so overloading this method with the idea of intercepting new result object creation will not work. See also warning pertaining to"create".
search
- Arguments:
$cond | undef, \%attrs? - Return Value:
$resultset (scalar context) | @result_objs (list context)
my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
my $new_rs = $cd_rs->search({ year => 2005 });
my $new_rs = $cd_rs->search([ { year => 2005 }, { year => 2004 } ]);
# year = 2005 OR year = 2004
In list context, "->all()" is called implicitly on the resultset, thus returning a list of result objects instead. To avoid that, use "search_rs".
If you need to pass in additional attributes but no additional condition, call it as "search(undef, \%attrs)".
# "SELECT name, artistid FROM $artist_table"
my @all_artists = $schema->resultset('Artist')->search(undef, {
columns => [qw/name artistid/],
});
For a list of attributes that can be passed to "search", see "ATTRIBUTES". For more examples of using this function, see Searching. For a complete documentation for the first argument, see "WHERE CLAUSES" in SQL::Abstract::Classic and its extension DBIx::Class::SQLMaker.
For more help on using joins with search, see DBIx::Class::Manual::Joining.
CAVEAT
Note that "search" does not process/deflate any of the values passed in the SQL::Abstract::Classic-compatible search condition structure. This is unlike other condition-bound methods "new_result", "create" and "find". The user must ensure manually that any value passed to this method will stringify to something the RDBMS knows how to deal with. A notable example is the handling of DateTime objects, for more info see: "Formatting DateTime objects in queries" in DBIx::Class::Manual::Cookbook.
This caveat is real. search is not doing your deflation chores for you.
search_rs
- Arguments:
$cond,\%attrs? - Return Value:
$resultset
This method does the same exact thing as search() except it will always return a resultset, even in list context. No accidental list-context jumpscare.
search_literal
CAVEAT: "search_literal" is provided for Class::DBI compatibility and should only be used in that context. "search_literal" is a convenience method. It is equivalent to calling "$schema->search(\[])", but if you want to ensure columns are bound correctly, use "search".
See "SEARCHING" in DBIx::Class::Manual::Cookbook and "Searching" in DBIx::Class::Manual::FAQ for searching techniques that do not require "search_literal".
- Arguments:
$sql_fragment,@standalone_bind_values - Return Value:
$resultset (scalar context) | @result_objs (list context)
my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
Pass a literal chunk of SQL to be added to the conditional part of the resultset query.
Example of how to use "search" instead of "search_literal"
my @cds = $cd_rs->search_literal('cdid = ? AND (artist = ? OR artist = ?)', (2, 1, 2));
my @cds = $cd_rs->search(\[ 'cdid = ? AND (artist = ? OR artist = ?)', [ 'cdid', 2 ], [ 'artist', 1 ], [ 'artist', 2 ] ]);
find ๐
Arguments: \%columns_values | @pk_values, { key => $unique_constraint, %attrs }? Return Value: $result | undef
okay so bestie, find is like the โจmain characterโจ of single-row lookups โ it finds and hands you back one row based on whatever criteria you give it. You've got two ways to feed it ๐
- a hashref with exactly the same format as
create(yes, including the whole inferring-foreign-keys-from-related-objects situation ๐ซถ), or - a list of primary key values, in the same order as the primary columns declaration on the
result_source.
In either case, it makes an attempt to combine the conditions that are already chilling on the resultset with the condition you passed to this method. no cap ๐ธ
To help it prep the right query for the storage, you can supply the key attribute โ that's the name of a unique constraint (and the unique constraint matching the primary columns is always named primary, iykyk). If you gave a key attribute and DBIC can't construct a query that satisfies that named unique constraint fully (like, non-NULL values for each column member of the constraint โ all of them, no skipping ๐), it throws an exception. dramatic but fair.
If no key is specified, the search gets carried over all unique constraints which are fully defined by the available condition. ๐ฆ
If no such constraint turns up? find currently defaults to a simple search->(\%column_values) which may or may not do what you expect. lowkey a gamble. Note that this fallback behavior may be deprecated in further versions. If you actually need to search with arbitrary conditions โ use search. And if the query from this fallback produces more than one row, a warning to that effect gets issued, though only the first row is constructed and returned as $result_object. ๐
On top of key, find recognizes and applies standard resultset attributes in the same way search does.
โ ๏ธ Heads up: if you have extra concerns about the correctness of the resulting query, you need to specify thekeyattribute and supply the entire condition as an argument tofindโ because it's not always possible to perform the combination of the resultset condition with the supplied one, especially if the resultset condition contains literal sql. fr fr, it's giving "trust me bro" energy otherwise.
For example, to find a row by its primary key:
my $cd = $schema->resultset('CD')->find(5);
You can also find a row by a specific unique constraint:
my $cd = $schema->resultset('CD')->find(
{
artist => 'Massive Attack',
title => 'Mezzanine',
},
{ key => 'cd_artist_title' }
);
See also find_or_create and update_or_create. ๐
search_related ๐ง
Arguments: $rel_name, $cond?, \%attrs? Return Value: $resultset (scalar context) | @result_objs (list context)
$new_rs = $cd_rs->search_related('artist', {
name => 'Emo-R-Us',
});
Searches the specified relationship, optionally specifying a condition and attributes for matching records. See ATTRIBUTES for more info, bestie ๐
In list context, ->all() gets called implicitly on the resultset, so you get back a list of result objects instead. To avoid that whole situation, use search_related_rs. ๐
See also search_related_rs.
search_related_rs ๐ซ
This method works exactly the same as search_related, except that it guarantees a resultset, even in list context. no surprises, iconic behavior ๐
cursor ๐ฏ
Arguments: none Return Value: $cursor
Returns a storage-driven cursor to the given resultset. See DBIx::Class::Cursor for the whole lore. โจ
single ๐ธ
Arguments: $cond? Return Value: $result | undef
my $cd = $schema->resultset('CD')->single({ year => 2001 });
Inflates the first result without creating a cursor if the resultset has any records in it; if not, returns undef. It's used by find as a lean version of search. like, the low-overhead snack version ๐
So while this method can take an optional search condition (just like search), it's a fast-code-path so it does not recognize search attributes. If you need extra joins or similar, call search and then chain-call single on the DBIx::Class::ResultSet you got back. ๐ซถ
Note ๐
As of 0.08100, this method enforces the assumption that the preceding query returns only one row. If more than one row is returned, you'll receive a warning:
Query returned more than one row
In this case, you should be using next or find instead โ or, if you really know what you're doing, use the rows attribute to explicitly limit the size of the resultset. ๐ญ
This method will also throw an exception if it's called on a resultset prefetching has_many, because such a prefetch implies fetching multiple rows from the database in order to assemble the resulting object. the way that would just break ๐
get_column ๐
Arguments: $cond? Return Value: $resultsetcolumn
my $max_length = $rs->get_column('length')->max;
Returns a DBIx::Class::ResultSetColumn instance for a column of the ResultSet. very demure, very column-focused ๐
search_like ๐ฆ
Arguments: $cond, \%attrs? Return Value: $resultset (scalar context) | @result_objs (list context)
# WHERE title LIKE '%blue%'
$cd_rs = $rs->search_like({ title => '%blue%'});
Performs a search, but uses LIKE instead of = as the condition. Note that this is simply a convenience method, retained for ex-Class::DBI users. You most likely want to use search with specific operators, ngl. ๐
For more information, see DBIx::Class::Manual::Cookbook.
๐จ This method is deprecated and will be removed in0.09. Usesearch()instead. Here's an example conversion, bestie:
->search_like({ foo => 'bar' });
# Becomes
->search({ foo => { like => 'bar' } });
slice ๐
Arguments: $first, $last Return Value: $resultset (scalar context) | @result_objs (list context)
Returns a resultset or object list representing a subset of elements from the resultset that slice is called on. Indexes start from 0, so like โ to get the first three records, call:
my ($one, $two, $three) = $rs->slice(0, 2);
yes, 0, 2 gives you three. that's just how it is. math slay ๐
next โญ๏ธ
Arguments: none Return Value: $result | undef
Returns the next element in the resultset (undef if there is none). ๐ซถ
You can use it to efficiently iterate over records in the resultset:
my $rs = $schema->resultset('CD')->search;
while (my $cd = $rs->next) {
print $cd->title;
}
โ ๏ธ Note that you need to store the resultset object and callnexton it. Callingresultset('Table')->nextrepeatedly will always return the first record from the resultset every single time. do not do this to yourself ๐ญ
result_source ๐ณ
Arguments: $result_source? Return Value: $result_source
An accessor for the primary ResultSource object from which this ResultSet is derived. the origin story, if you will โจ
result_class ๐
Arguments: $result_class? Return Value: $result_class
An accessor for the class to use when creating result objects. Defaults to result_source->result_class โ which in most cases is the name of the table class.
โ ๏ธ Note that changing theresult_classwill also remove any components that were originally loaded in the source class viaload_components. Any overloaded methods in the original source class will not run. tragic, but true ๐
count ๐ข
Arguments: $cond, \%attrs? Return Value: $count
Performs an SQL COUNT with the same query as the resultset was built with, to find the number of elements. Passing arguments is equivalent to $rs->search ($cond, \%attrs)->count. efficient queen behavior ๐
count_rs ๐งฎ
Arguments: $cond, \%attrs? Return Value: $count_rs
Same as count, but returns a DBIx::Class::ResultSetColumn object. This can be very handy for subqueries:
->search( { amount => $some_rs->count_rs->as_query } )
As with regular resultsets, the SQL query will be executed only after the resultset is accessed via next or all. That would return the same single value you'd get via count. ๐ฆ
count_literal ๐
๐ CAVEAT:count_literalis provided for Class::DBI compatibility and should only be used in that context. Seesearch_literalfor further info.
Arguments: $sql_fragment, @standalone_bind_values Return Value: $count
Counts the results in a literal query. Equivalent to calling search_literal with the passed arguments, then count.
all ๐
Arguments: none Return Value: @result_objs
Returns all elements in the resultset. the whole squad, together ๐
reset ๐
Arguments: none Return Value: $self
Resets the resultset's cursor so you can iterate through the elements again. It implicitly resets the storage cursor too, so a subsequent next will trigger another query. fresh start energy โจ
first ๐ฅ
Arguments: none Return Value: $result | undef
Resets the resultset (causing a fresh query to storage) and returns an object for the first result (or undef if the resultset is empty). main character of the row set, obviously ๐
update โ๏ธ
Arguments: \%values Return Value: $underlying_storage_rv
Sets the specified columns in the resultset to the supplied values in a single query. ๐ฏ
โ ๏ธ Note that this will not run any accessor /set_column/ update triggers, nor will it update any result object instances derived from this resultset (this includes the contents of the resultset cache, if any). Seeupdate_allif you need to execute any on-update triggers or cascades defined either by you or a result component. it simply does not care ๐
The return value is a pass-through of what the underlying storage backend returned, and may vary. See execute in DBI for the most common case.
CAVEAT ๐
Note that update does not process/deflate any of the values passed in. This is unlike the corresponding update in DBIx::Class::Row. You โ the user โ must ensure manually that any value passed to this method will stringify to something the RDBMS knows how to deal with. A notable example is the handling of DateTime objects; for more info see: Formatting DateTime objects in queries in DBIx::Class::Manual::Cookbook. ngl this one bites people ๐ญ
update_all ๐
Arguments: \%values Return Value: 1
Fetches all objects and updates them one at a time via update in DBIx::Class::Row. Note that update_all will run DBIC defined triggers, while update will not. see, told you ๐
delete ๐๏ธ
Arguments: none Return Value: $underlying_storage_rv
Deletes the rows matching this resultset in a single query.
โ ๏ธ Note that this will not run any delete triggers, nor will it alter thein_storagestatus of any result object instances derived from this resultset (this includes the contents of the resultset cache, if any). Seedelete_allif you need to execute any on-delete triggers or cascades defined either by you or a result component. so brutal, so fast ๐
The return value is a pass-through of what the underlying storage backend returned, and may vary. See execute in DBI for the most common case.
delete_all โ ๏ธ
Arguments: none Return Value: 1
Fetches all objects and deletes them one at a time via delete in DBIx::Class::Row. Note that delete_all will run DBIC defined triggers, while delete will not. ๐ซถ
populate ๐ฑ
Arguments: [ \@column_list, \@row_values+ ] | [ \%col_data+ ] Return Value: \@result_objects (scalar context) | @result_objects (list context)
Accepts either an arrayref of hashrefs or alternatively an arrayref of arrayrefs. ๐
๐ NOTE
okay bestie, listen up because the context you call this in literally changes what happens โ and that's not a vibe, that's a real technical thing ๐ :
- Void context โ your data gets fed directly into fastpath insertion routines handed to you by the underlying storage (most often
execute_for_fetchin DBI). That means it bypasses thenewandinsertcalls on the Result class entirely, including any augmentation of those methods that your components provide. So likeโฆ if you're using something likeDBIx::Class::UUIDColumnsto make primary keys for you, surprise ๐ซ โ your PKs come out empty. In that case you have to explicitly force scalar or list context to get those values created. No cap. - Non-void (scalar or list) context โ it's simply a wrapper for
create. Depending on list or scalar context you get back either a list of Result objects or an arrayref containing those objects.
When you supply data in the "arrayref of arrayrefs" invocation style, the first element should be a list of column names, and each subsequent element should be a data value in the earlier specified column order. For example:
$schema->resultset("Artist")->populate([
[ qw( artistid name ) ],
[ 100, 'A Formally Unknown Singer' ],
[ 101, 'A singer that jumped the shark two albums ago' ],
[ 102, 'An actually cool singer' ],
]);
For the arrayref of hashrefs style, each hashref should be a structure suitable for passing to create. Multi-create is also permitted with this syntax ๐:
$schema->resultset("Artist")->populate([
{ artistid => 4, name => 'Manufactured Crap', cds => [
{ title => 'My First CD', year => 2006 },
{ title => 'Yet More Tweeny-Pop crap', year => 2007 },
],
},
{ artistid => 5, name => 'Angsty-Whiny Girl', cds => [
{ title => 'My parents sold me to a record company', year => 2005 },
{ title => 'Why Am I So Ugly?', year => 2006 },
{ title => 'I Got Surgery and am now Popular', year => 2007 }
],
},
]);
Now here's the little catch ๐ โ if you attempt a void-context multi-create like in the example above (each Artist also has the related list of CDs), and you don't supply the necessary autoinc foreign key information, this method will proxy to the less efficient create, and then just throw the Result objects away. In that case there are obviously no benefits to using this method over create. Bye ๐.
๐ฆ pager
- Arguments: none
- Return Value:
$pager
Returns a DBIx::Class::ResultSet::Pager object tied to the current resultset. It requires the page attribute to have been previously set on the resultset object, usually via a call to page. So set your page first, bestie, or it's giving nothing โจ.
To get the full count of entries for a paged resultset, call total_entries on the pager object. That's your total, periodt.
๐ธ page
- Arguments:
$page_number - Return Value:
$resultset
Returns a resultset for the $page_number page of the resultset on which page is called, where each page contains a number of rows equal to the 'rows' attribute set on the resultset (10 by default). Ten. A whole ten rows. Iconic default behavior honestly ๐.
๐ง new_result
- Arguments:
\%col_data - Return Value:
$result
Creates a new result object in the resultset's result class and returns it. The row is not inserted into the database at this point โ call insert in DBIx::Class::Row to do that. And if you're ever wondering whether a result object has been inserted or not, calling in_storage in DBIx::Class::Row will tell you ๐ซถ.
Passes the hashref of input on to new in DBIx::Class::Row.
โญ as_query
- Arguments: none
- Return Value:
\[ $sql, @bind_values ]
Returns the SQL query and bind vars associated with the invocant.
This is generally used as the RHS for a subquery. Like, that's its whole moment, and it ate ๐ฅ.
๐ find_or_new
- Arguments:
\%col_data, { key => $unique_constraint, %attrs }? - Return Value:
$result
my $artist = $schema->resultset('Artist')->find_or_new(
{ artist => 'fred' }, { key => 'artists' });
$cd->cd_to_producer->find_or_new({ producer => $producer },
{ key => 'primary' });
Find an existing record from this resultset using find. If none exists, instantiate a new result object and return it. The object will not be saved into your storage until you call insert in DBIx::Class::Row on it. So it's like, a vibe in limbo ๐.
You most likely want this method when looking for existing rows using a unique constraint that is not the primary key, or looking for related rows.
If you want objects to be saved immediately, use find_or_create instead.
Note: Make sure to read the documentation offindand understand the significance of thekeyattribute, as its lack may skew your search, and subsequently result in spurious new objects. ๐ญ
Note: Take care when usingfind_or_newwith a table having columns with default values that you intend to be automatically supplied by the database (e.g. anauto_incrementprimary key column). In normal usage, the value of such columns should NOT be included at all in the call tofind_or_new, even when set toundef. Don't do it. I'm serious ๐.
๐ create
- Arguments:
\%col_data - Return Value:
$result
Attempt to create a single new row, or a row with multiple related rows, in the table represented by the resultset (and related tables). This will not check for duplicate rows before inserting โ use find_or_create to do that. Create is out here trusting you completely ๐
.
To create one row for this resultset, pass a hashref of key/value pairs representing the columns of the table and the values you wish to store. If the appropriate relationships are set up, foreign key fields can also be passed an object representing the foreign row, and the value will be set to its primary key. Slay.
To create related objects, pass a hashref of related-object column values keyed on the relationship name. If the relationship is of type "multi" (has_many in DBIx::Class::Relationship) โ pass an arrayref of hashrefs. The process will correctly identify columns holding foreign keys, and will transparently populate them from the keys of the corresponding relation. This can be applied recursively, and will work correctly for a structure with an arbitrary depth and width, as long as the relationships actually exist and the correct column data has been supplied. Deep and wide, fr fr.
Instead of hashrefs of plain related data (key/value pairs), you may also pass new or inserted objects. New objects (not inserted yet, see new_result), will be inserted into their appropriate tables.
Effectively a shortcut for ->new_result(\%col_data)->insert. That's it. That's the whole method ๐.
Example of creating a new row:
$person_rs->create({
name=>"Some Person",
email=>"somebody@someplace.com"
});
Example of creating a new row and also creating rows in a related has_many or has_one resultset. Note Arrayref:
$artist_rs->create(
{ artistid => 4, name => 'Manufactured Crap', cds => [
{ title => 'My First CD', year => 2006 },
{ title => 'Yet More Tweeny-Pop crap', year => 2007 },
],
},
);
Example of creating a new row and also creating a row in a related belongs_to resultset. Note Hashref:
$cd_rs->create({
title=>"Music for Silly Walks",
year=>2000,
artist => {
name=>"Silly Musician",
}
});
WARNING ๐จ When subclassing ResultSet never attempt to override this method. Since it is a simple shortcut for$self->new_result($attrs)->insert, a lot of the internals simply never call it, so your override will be bypassed more often than not. Override eithernewinDBIx::Class::RoworinsertinDBIx::Class::Rowdepending on how early in thecreateprocess you need to intervene. See also warning pertaining tonew. This one's important bestie, don't skip it ๐ค.
๐ find_or_create
- Arguments:
\%col_data, { key => $unique_constraint, %attrs }? - Return Value:
$result
$cd->cd_to_producer->find_or_create({ producer => $producer },
{ key => 'primary' });
Tries to find a record based on its primary key or unique constraints; if none is found, creates one and returns that instead.
my $cd = $schema->resultset('CD')->find_or_create({
cdid => 5,
artist => 'Massive Attack',
title => 'Mezzanine',
year => 2005,
});
Also takes an optional key attribute, to search by a specific key or unique constraint. For example:
my $cd = $schema->resultset('CD')->find_or_create(
{
artist => 'Massive Attack',
title => 'Mezzanine',
},
{ key => 'cd_artist_title' }
);
Note: Make sure to read the documentation offindand understand the significance of thekeyattribute, as its lack may skew your search, and subsequently result in spurious row creation. ๐
Note: Becausefind_or_create()reads from the database and then possibly inserts based on the result, this method is subject to a race condition ๐ญ. Another process could create a record in the table after the find has completed and before the create has started. To avoid this problem, usefind_or_create()inside a transaction. Please. For me. ๐
Note: Take care when usingfind_or_createwith a table having columns with default values that you intend to be automatically supplied by the database (e.g. anauto_incrementprimary key column). In normal usage, the value of such columns should NOT be included at all in the call tofind_or_create, even when set toundef.
See also find and update_or_create. For information on how to declare unique constraints, see add_unique_constraint in DBIx::Class::ResultSource.
If you need to know if an existing row was found or a new one created, use find_or_new and in_storage in DBIx::Class::Row instead. And don't forget to call insert in DBIx::Class::Row to save the newly created row to the database! ๐
my $cd = $schema->resultset('CD')->find_or_new({
cdid => 5,
artist => 'Massive Attack',
title => 'Mezzanine',
year => 2005,
});
if( !$cd->in_storage ) {
# do some stuff
$cd->insert;
}
๐ update_or_create
- Arguments:
\%col_data, { key => $unique_constraint, %attrs }? - Return Value:
$result
$resultset->update_or_create({ col => $val, ... });
Like find_or_create, but if a row is found it is immediately updated via $found_row->update (\%col_data). Found it? Updated it. Main character energy.
Takes an optional key attribute to search on a specific unique constraint. For example:
# In your application
my $cd = $schema->resultset('CD')->update_or_create(
{
artist => 'Massive Attack',
title => 'Mezzanine',
year => 1998,
},
{ key => 'cd_artist_title' }
);
$cd->cd_to_producer->update_or_create({
producer => $producer,
name => 'harry',
}, {
key => 'primary',
});
๐ Note: bestie pls actually read the docs for"find"and get why the"key"attribute matters โ not having it can skew your search and then, yeah, you get spurious rows just materializing out of nowhere. Not cute.
๐ธ Note: be careful with"update_or_create"on a table that has columns with default values you want the database to fill in for you (like anauto_incrementprimary key column, classic). In normal usage you should NOT include the value of those columns in the"update_or_create"call at all โ like, not even set toundef. Just don't.
Also go see "find" and "find_or_create". And if you wanna know how to declare unique constraints, that's "add_unique_constraint" in DBIx::Class::ResultSource, iykyk โจ
If you actually need to know whether an existing row got updated or a brand new one got created, use "update_or_new" and "in_storage" in DBIx::Class::Row instead. And do NOT forget to call "insert" in DBIx::Class::Row to save that newly created row to the database, bestie, or it just... vibes in memory forever ๐ญ
๐ฆ update_or_new
- Arguments:
\%col_data,{ key => $unique_constraint, %attrs }? - Return Value:
$result
$resultset->update_or_new({ col => $val, ... });
Lowkey it's like "find_or_new" but if a row is found it gets immediately updated via "$found_row->update (\%col_data)". Slay.
For example:
# In your application
my $cd = $schema->resultset('CD')->update_or_new(
{
artist => 'Massive Attack',
title => 'Mezzanine',
year => 1998,
},
{ key => 'cd_artist_title' }
);
if ($cd->in_storage) {
# the cd was updated
}
else {
# the cd is not yet in the database, let's insert it
$cd->insert;
}
๐ Note: again, read the documentation of"find"and understand the significance of the"key"attribute โ if you skip it your search can get skewed and you end up with spurious new objects. We've been over this ๐
๐ Note: take care when using"update_or_new"with a table having columns with default values that you intend to be automatically supplied by the database (e.g. anauto_incrementprimary key column). In normal usage, the value of such columns should NOT be included at all in the call to"update_or_new", even when set toundef.
See also "find", "find_or_create" and "find_or_new". ๐ซถ
๐ get_cache
- Arguments: none
- Return Value:
\@result_objs|undef
Gets the contents of the cache for the resultset, if the cache is set.
The cache gets populated either by using the "prefetch" attribute to "search" or by calling "set_cache". Both valid, pick your fighter โจ
๐ set_cache
- Arguments:
\@result_objs - Return Value:
\@result_objs
Sets the contents of the cache for the resultset. It expects an arrayref of objects of the same class as those the resultset produces. Real talk though: note that if the cache is set, the resultset will return the cached objects rather than re-querying the database โ even if the cache attr is not set. So like, the cache is committed, no take-backs ๐
The contents of the cache can also be populated by using the "prefetch" attribute to "search".
๐ clear_cache
- Arguments: none
- Return Value:
undef
Clears the cache for the resultset. Poof, gone, bye ๐
โญ is_paged
- Arguments: none
- Return Value: true, if the resultset has been paginated
Just a lil vibe check: has this thing been paginated or not.
๐ธ is_ordered
- Arguments: none
- Return Value: true, if the resultset has been ordered with
"order_by".
Same energy as above, but for ordering. Did you order_by or did you not.
๐ฆ related_resultset
- Arguments:
$rel_name - Return Value:
$resultset
Returns a related resultset for the relationship name you hand it. Iconic.
$artist_rs = $schema->resultset('CD')->related_resultset('Artist');
๐ current_source_alias
- Arguments: none
- Return Value:
$source_alias
Returns the current table alias for the result source this resultset is built on โ the one that'll actually show up in the SQL query. Usually it's "me".
So here's the situation ๐ Currently the source alias that refers to the result set returned by a "search"/"find" family method depends on how you got to the resultset: it's "me" by default, but eg. "search_related" aliases it to the related result source name (and keeps "me" referring to the original result set). The long term goal is to make DBIx::Class always alias the current resultset as "me" (and make this method unnecessary). Until then though...
Which means it's currently necessary to use this method in predefined queries (see "Predefined searches" in DBIx::Class::Manual::Cookbook) when you're referring to the source alias of the current result set:
# in a result set class
sub modified_by {
my ($self, $user) = @_;
my $me = $self->current_source_alias;
return $self->search({
"$me.modified" => $user->id,
});
}
The alias of newly created resultsets can be altered by the alias attribute. Fancy โจ
๐ง as_subselect_rs
- Arguments: none
- Return Value:
$resultset
Acts as a barrier to SQL symbols. The resultset you give it gets made into a "virtual view" by including it as a subquery within the from clause. From this point on, any joined tables are inaccessible to ->search on the resultset โ as if it were simply where-filtered without joins. It's giving sealed away in a lil glass case ๐
For example:
my $rs = $schema->resultset('Bar')->search({'x.name' => 'abc'},{ join => 'x' });
# 'x' now pollutes the query namespace
# So the following works as expected
my $ok_rs = $rs->search({'x.other' => 1});
# But this doesn't: instead of finding a 'Bar' related to two x rows (abc and
# def) we look for one row with contradictory terms and join in another table
# (aliased 'x_2') which we never use
my $broken_rs = $rs->search({'x.name' => 'def'});
my $rs2 = $rs->as_subselect_rs;
# doesn't work - 'x' is no longer accessible in $rs2, having been sealed away
my $not_joined_rs = $rs2->search({'x.other' => 1});
# works as expected: finds a 'table' row related to two x rows (abc and def)
my $correctly_joined_rs = $rs2->search({'x.name' => 'def'});
Another example of when one might use this would be to select a subset of columns in a group by clause:
my $rs = $schema->resultset('Bar')->search(undef, {
group_by => [qw{ id foo_id baz_id }],
})->as_subselect_rs->search(undef, {
columns => [qw{ id foo_id }]
});
In the above example normally columns would have to be equal to the group by, but because we isolated the group by into a subselect the above works. We love a loophole that's actually legit ๐ฅ
๐ throw_exception
See "throw_exception" in DBIx::Class::Schema for details.
๐ ATTRIBUTES ๐
Attributes are used to refine a ResultSet in various ways when searching for data. They can be passed to any method which takes an \%attrs argument. See "search", "search_rs", "find", "count".
Default attributes can be set on the result class using "resultset_attributes" in DBIx::Class::ResultSource. (Please read the CAVEATS on that feature before using it! Like, actually please ๐)
These are in no particular order:
๐ order_by
Value: ( $order_by | \@order_by | \%order_by )
Which column(s) to order the results by.
[The full list of suitable values is documented in "ORDER BY CLAUSES" in SQL::Abstract::Classic; the following is a summary of common options.]
If a single column name, or an arrayref of names is supplied, the argument is passed through directly to SQL. The hashref syntax allows for connection-agnostic specification of ordering direction:
For descending order:
order_by => { -desc => [qw/col1 col2 col3/] }
For explicit ascending order:
order_by => { -asc => 'col' }
The old scalarref syntax (i.e. order_by => \'year DESC') is still supported, although you are strongly encouraged to use the hashref syntax as outlined above. Like, strongly. The old way is giving legacy ๐ซ
๐ฆ columns
Value: \@columns | \%columns | $column
Shortcut to request a particular set of columns to be retrieved. Each column spec may be a string (a table column name), or a hash (in which case the key is the "as" value, and the value is used as the "select" expression). It adds the "current_source_alias" onto the start of any column without a "." in it and sets "select" from that, then auto-populates "as" from "select" as normal. (You may also use the "cols" attribute, as in earlier versions of DBIC, but this is deprecated.)
Essentially "columns" does the same as "select" and "as".
columns => [ 'some_column', { dbic_slot => 'another_column' } ]
is the same as
select => [qw(some_column another_column)],
as => [qw(some_column dbic_slot)]
If you want to individually retrieve related columns (in essence perform manual "prefetch") you have to make sure to specify the correct inflation slot chain such that it matches existing relationships:
my $rs = $schema->resultset('Artist')->search({}, {
# required to tell DBIC to collapse has_many relationships
collapse => 1,
join => { cds => 'tracks' },
'+columns' => {
'cds.cdid' => 'cds.cdid',
'cds.tracks.title' => 'tracks.title',
},
});
Like elsewhere, literal SQL or literal values can be included by using a scalar reference or a literal bind value, and these values will be available in the result with "get_column" (see also SQL::Abstract::Classic/Literal SQL and value type operators>):
# equivalent SQL: SELECT 1, 'a string', IF(my_column,?,?) ...
# bind values: $true_value, $false_value
columns => [
{
foo => \1,
bar => \q{'a string'},
baz => \[ 'IF(my_column,?,?)', $true_value, $false_value ],
}
]
๐ +columns
๐จ NOTE: You MUST explicitly quote'+columns'when using this attribute. Not doing so causes Perl to incorrectly interpret"+columns"as a bareword with a unary plus operator before it, which is the same as simply"columns". Yes this is a real trap, no it is not a vibe, protect yourself ๐
Value: \@extra_columns
Indicates additional columns to be selected from storage. Works the same as "columns" but adds columns to the current selection. (You may also use the "include_columns" attribute, as in earlier versions of DBIC, but this is deprecated.)
$schema->resultset('CD')->search(undef, {
'+columns' => ['artist.name'],
join => ['artist']
});
would return all CDs and include a 'name' column to the information passed to object inflation. Note that the 'artist' is the name of the column (or relationship) accessor, and 'name' is the name of the column accessor in the related table. Chef's kiss ๐ค
โญ select
Value: \@select_columns
Indicates which columns should be selected from the storage. You can use column names, or in the case of RDBMS back ends, function or stored procedure names:
$rs = $schema->resultset('Employee')->search(undef, {
select => [
'name',
{ count => 'employeeid' },
{ max => { length => 'name' }, -as => 'longest_name' }
]
});
# Equivalent SQL
SELECT name, COUNT( employeeid ), MAX( LENGTH( name ) ) AS longest_name FROM employee
NOTE: bestie, you will almost always need a matchingasattribute when you useselectโ that's literally how DBIx::Class knows where to put the result of that column. ๐
Also like, important: the as attribute has nothing to do with the SQL-side AS identifier aliasing. Nothing, zero, nada. You can alias a function (so you can use it, say, in an ORDER BY clause) โ but that's done via the -as select function attribute, supplied like in the example above. ๐
๐ธ +select ๐ธ
NOTE: you MUST explicitly quote'+select'when you use this attribute. Do not skip this. If you don't, Perl interprets"+select"as a bareword with a unary plus operator in front of it โ which is literally justselectwith extra steps. Same thing. No cap. ๐ญ
Value: \@extra_select_columns
This one says "hey, also grab these extra columns from storage." It works exactly like select, except instead of replacing the selection with a brand-new explicit list, it adds columns to whatever's already selected. Iconic behavior honestly. โจ
๐ฆ as ๐ฆ
Value: \@inflation_names
This is the DBIC-side name for object inflation, iykyk. Meaning: as tells you the slot name where the column's value gets stored inside the Row object. Then you can get at that value via the get_column method (or via the object accessor, if an accessor with that same name already exists) โ like, look:
$rs = $schema->resultset('Employee')->search(undef, {
select => [
'name',
{ count => 'employeeid' },
{ max => { length => 'name' }, -as => 'longest_name' }
],
as => [qw/
name
employee_count
max_name_length
/],
});
And again, for the people in the back: as has nothing to do with SQL-side identifier aliasing AS. Go look at "select" if you need the details. ๐
So if the object you're searching on already has an accessor matching a column name you listed in as, you just grab the value with the accessor like a normal person:
my $name = $employee->name();
If, on the other hand, no such accessor exists on the object? Then it's get_column o'clock:
my $employee_count = $employee->get_column('employee_count');
And yeah, you can absolutely build your own accessors if you want โ the details live in DBIx::Class::Manual::Cookbook. ๐ซถ
๐ +as ๐
NOTE: you MUST explicitly quote'+as'when you use this attribute. If you don't, Perl goes and interprets"+as"as a bareword with a unary plus before it, which is the exact same as just plainas. We've been over this, bestie. ๐
Value: \@extra_inflation_names
This one adds extra inflation names for selectors you added via +select. See "as" for the whole explanation. โญ
๐ฅ join ๐ฅ
Value: ($rel_name | \@rel_names | \%rel_names)
It holds a list of relationships that should get joined for this query. Like so:
# Get CDs by Nine Inch Nails
my $rs = $schema->resultset('CD')->search(
{ 'artist.name' => 'Nine Inch Nails' },
{ join => 'artist' }
);
It can also hold a hash reference so you can reach the other relation's relations. Example time:
package MyApp::Schema::Track;
use base qw/DBIx::Class/;
__PACKAGE__->table('track');
__PACKAGE__->add_columns(qw/trackid cd position title/);
__PACKAGE__->set_primary_key('trackid');
__PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1;
# In your application
my $rs = $schema->resultset('Artist')->search(
{ 'track.title' => 'Teardrop' },
{
join => { cd => 'track' },
order_by => 'artist.name',
}
);
โ ๏ธ In your conditions you need to use the relationship name (not the table name), because that's what things get aliased as. And the current table is aliased as me, so use me.column_name to dodge ambiguity. Like:
# Get CDs from 1984 with a 'Foo' track
my $rs = $schema->resultset('CD')->search(
{
'me.year' => 1984,
'tracks.name' => 'Foo'
},
{ join => 'tracks' }
);
If you supply the same join twice, it gets aliased to <rel>_2 (and same energy for a third time). For e.g.:
my $rs = $schema->resultset('Artist')->search({
'cds.title' => 'Down to Earth',
'cds_2.title' => 'Popular',
}, {
join => [ qw/cds cds/ ],
});
โฆwhich returns a set of all artists that have both a cd titled 'Down to Earth' and a cd titled 'Popular'. Queen behavior. ๐
If you want to also fetch related objects from other tables, go look at "prefetch" below. ๐
NOTE: an internal join-chain pruner will discard certain joins while it's constructing the actual SQL query โ but only as long as those joins don't affect the retrieved result. What counts, for example: 1:1 left joins that aren't part of the restriction specification (WHERE/HAVING) and aren't part of the query selection either. Bye bestie. ๐
For way more help on using joins with search, see DBIx::Class::Manual::Joining. ๐ง
๐ collapse ๐
Value: (0 | 1)
Set it to a true value and it means: any rows fetched from joined has_many relationships get aggregated into the corresponding "parent" object. So like, this resultset:
my $rs = $schema->resultset('CD')->search({}, {
'+columns' => [ qw/ tracks.title tracks.position / ],
join => 'tracks',
collapse => 1,
});
while executing this query:
SELECT me.*, tracks.title, tracks.position
FROM cd me
LEFT JOIN track tracks
ON tracks.cdid = me.cdid
โฆwill return only as many objects as there are rows in the CD source โ even though the query result itself may span like, many rows. Each of those CD objects will in turn have multiple "Track" objects hidden behind the has_many-generated accessor tracks. Without collapse => 1, the return values of this resultset would be as many CD objects as there are tracks (a "Cartesian product", gross), with each CD object holding exactly one of all the fetched Track data. ๐ญ
When a collapse is requested on a non-ordered resultset, an order by some unique part of the main source (the left-most table) gets inserted automatically. Why? So the resultset can stay "lazy" โ calling $rs->next fetches only as many rows as it needs to build the next object with all its related data. Efficient. We love her. โจ
But if an order_by is already declared, and it orders the resultset in a way that makes collapsing-as-described impossible (e.g. ORDER BY has_many_rel.column or ORDER BY RANDOM()), DBIC automatically switches to "eager" mode and slurps the entire resultset before building the first object returned by next. ๐ซ
Setting this attribute on a resultset that doesn't join any has_many relations is a no-op. Nothing happens. It's giving "I'm just here for the vibes." ๐
For a more in-depth discussion, see "PREFETCHING".
๐ prefetch ๐
Value: ($rel_name | \@rel_names | \%rel_names)
This attribute is shorthand for specifying a join spec, adding all columns from the joined related sources as +columns, and setting collapse to a true value. Think of it as a rough superset of the join attribute. Main character energy, honestly. ๐
For example, these following two queries are equivalent:
my $rs = $schema->resultset('Artist')->search({}, {
prefetch => { cds => ['genre', 'tracks' ] },
});
and
my $rs = $schema->resultset('Artist')->search({}, {
join => { cds => ['genre', 'tracks' ] },
collapse => 1,
'+columns' => [
(map
{ +{ "cds.$_" => "cds.$_" } }
$schema->source('Artist')->related_source('cds')->columns
),
(map
{ +{ "cds.genre.$_" => "genre.$_" } }
$schema->source('Artist')->related_source('cds')->related_source('genre')->columns
),
(map
{ +{ "cds.tracks.$_" => "tracks.$_" } }
$schema->source('Artist')->related_source('cds')->related_source('tracks')->columns
),
],
});
Both of them produce the following SQL:
SELECT me.artistid, me.name, me.rank, me.charfield,
cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track,
genre.genreid, genre.name,
tracks.trackid, tracks.cd, tracks.position, tracks.title, tracks.last_updated_on, tracks.last_updated_at
FROM artist me
LEFT JOIN cd cds
ON cds.artist = me.artistid
LEFT JOIN genre genre
ON genre.genreid = cds.genreid
LEFT JOIN track tracks
ON tracks.cd = cds.cdid
ORDER BY me.artistid
And even though prefetch implies a join, it's totally ok to mix the two together โ the arguments get properly merged and it generally does the right thing. For example, maybe you want this:
my $artists_and_cds_without_genre = $schema->resultset('Artist')->search(
{ 'genre.genreid' => undef },
{
join => { cds => 'genre' },
prefetch => 'cds',
}
);
Which generates the following SQL:
SELECT me.artistid, me.name, me.rank, me.charfield,
cds.cdid, cds.artist, cds.title, cds.year, cds.genreid, cds.single_track
FROM artist me
LEFT JOIN cd cds
ON cds.artist = me.artistid
LEFT JOIN genre genre
ON genre.genreid = cds.genreid
WHERE genre.genreid IS NULL
ORDER BY me.artistid
For a more in-depth discussion, see "PREFETCHING". ๐ธ
๐ฆ alias ๐ฆ
Value: $source_alias
Sets the source alias for the query. Normally this defaults to me, but nested search queries (sub-SELECTs) might need specific aliases set so they can reference inner queries. For example:
my $q = $rs
->related_resultset('CDs')
->related_resultset('Tracks')
->search({
'track.id' => { -ident => 'none_search.id' },
})
->as_query;
my $ids = $self->search({
-not_exists => $q,
}, {
alias => 'none_search',
group_by => 'none_search.id',
})->get_column('id')->as_query;
$self->search({ id => { -in => $ids } })
This attribute is directly tied to "current_source_alias". ๐
๐ page ๐
Value: $page
Makes the resultset paged and says which page to retrieve. Effectively identical to creating a non-paged resultset and then calling ->page($page) on it. Same thing, different font.
If the "rows" attribute isn't specified, it defaults to 10 rows per page. Ten. That's the default. ๐
When you have a paged resultset, "count" will only return the number of rows in the page. To get the total, use the "pager" and call total_entries on it. Don't get it twisted. ๐
โญ rows โญ
Value: $rows
Specifies the maximum number of rows for direct retrieval, or the number of rows per page if the page attribute or method is used. ๐
๐ offset ๐
Value: $offset
Specifies the (zero-based) row number for the first row to be returned โ or the number of the first row of the first page if paging is used. Zero-based, bestie, so index accordingly. โจ
๐ software_limit ๐
Value: (0 | 1)
When you combine this with rows and/or offset, the generated SQL will not include any limit dialect stanzas. Instead, the entire result gets selected as if no limits were specified, and DBIC does the limiting locally by artificially advancing and finishing the resulting cursor.
This is the recommended way of doing resultset limiting when thereโs no sane RDBMS implementation available (e.g. Sybase ASE using the Generic Sub Query hack). Slay for workarounds ๐
๐ธ group_by ๐ธ
Value: \@columns
An arrayref of columns to group by. It can include columns from joined tables.
group_by => [qw/ column1 column2 ... /]
๐ having ๐
Value: $condition
The HAVING operator is a secondary condition applied to the set after the grouping calculations have happened. Basically itโs a constraint just like where โ and it accepts the same SQL::Abstract::Classic syntax โ but it applies to the data as it exists after GROUP BY has taken place. Specifying having without group_by is a logical mistake, and itโs a fatal error on most RDBMS engines. No cap, donโt do it ๐
E.g.
having => { 'count_employee' => { '>=', 100 } }
or with an in-place function, in which case literal SQL is required:
having => \[ 'count(employee) >= ?', 100 ]
โจ distinct โจ
Value: (0 | 1)
Set to 1 to automatically generate a group_by clause based on the selection (including intelligent handling of order_by contents). Note that the group criteria calculation takes place over the final selection. That includes any +columns, +select or order_by additions in subsequent search calls, and standalone columns selected via DBIx::Class::ResultSetColumn (get_column). A notable exception is the extra selections specified via prefetch โ those selections are explicitly excluded from group criteria calculations.
If the final ResultSet also explicitly defines a group_by attribute, this setting is ignored and an appropriate warning is issued. Iconic behavior, honestly ๐
๐ฆ where ๐ฆ
Adds to the WHERE clause.
# only return rows WHERE deleted IS NULL for all searches
__PACKAGE__->resultset_attributes({ where => { deleted => undef } });
Can be overridden by passing { where => undef } as an attribute to a resultset.
For more complicated where clauses see "WHERE CLAUSES" in SQL::Abstract::Classic.
๐ cache ๐
Set to 1 to cache search results. This prevents extra SQL queries if you revisit rows in your ResultSet:
my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
while( my $artist = $resultset->next ) {
... do stuff ...
}
$rs->first; # without cache, this would issue a query
By default, searches are not cached.
For more examples of using these attributes, see DBIx::Class::Manual::Cookbook.
๐ for ๐
Value: ( 'update' | 'shared' | \$scalar )
Set to 'update' for a SELECT ... FOR UPDATE or 'shared' for a SELECT ... FOR SHARED. If \$scalar is passed, this is taken directly and embedded in the query.
๐ฅ PREFETCHING ๐ฅ
DBIx::Class supports arbitrary related data prefetching from multiple related sources. Any combination of relationship types and column sets is supported. If collapsing is requested, thereโs an additional requirement: you gotta select enough data to make every individual object uniquely identifiable. Periodt.
Here are some more involved examples, based on this relationship map:
# Assuming:
My::Schema::CD->belongs_to( artist => 'My::Schema::Artist' );
My::Schema::CD->might_have( liner_note => 'My::Schema::LinerNotes' );
My::Schema::CD->has_many( tracks => 'My::Schema::Track' );
My::Schema::Artist->belongs_to( record_label => 'My::Schema::RecordLabel' );
My::Schema::Track->has_many( guests => 'My::Schema::Guest' );
my $rs = $schema->resultset('Tag')->search(
undef,
{
prefetch => {
cd => 'artist'
}
}
);
The initial search results in SQL like the following:
SELECT tag.*, cd.*, artist.* FROM tag
JOIN cd ON tag.cd = cd.cdid
JOIN artist ON cd.artist = artist.artistid
DBIx::Class has no need to go back to the database when we access the cd or artist relationships, which saves us two SQL statements in this case. Obsessed with the efficiency ๐
Simple prefetches will be joined automatically, so thereโs no need for a join attribute in the above search.
The prefetch attribute can be used with any of the relationship types, and multiple prefetches can be specified together. Below is a more complex example that prefetches a CDโs artist, its liner notes (if present), the cover image, the tracks on that CD, and the guests on those tracks.
my $rs = $schema->resultset('CD')->search(
undef,
{
prefetch => [
{ artist => 'record_label'}, # belongs_to => belongs_to
'liner_note', # might_have
'cover_image', # has_one
{ tracks => 'guests' }, # has_many => has_many
]
}
);
This will produce SQL like the following:
SELECT cd.*, artist.*, record_label.*, liner_note.*, cover_image.*,
tracks.*, guests.*
FROM cd me
JOIN artist artist
ON artist.artistid = me.artistid
JOIN record_label record_label
ON record_label.labelid = artist.labelid
LEFT JOIN track tracks
ON tracks.cdid = me.cdid
LEFT JOIN guest guests
ON guests.trackid = track.trackid
LEFT JOIN liner_notes liner_note
ON liner_note.cdid = me.cdid
JOIN cd_artwork cover_image
ON cover_image.cdid = me.cdid
ORDER BY tracks.cd
Now the artist, record_label, liner_note, cover_image, tracks, and guests of the CD will all be available through the relationship accessors without needing additional queries to the database. Itโs giving one query, many vibes โจ
๐ CAVEATS ๐
Prefetch does a lot of deep magic. As such, it may not behave exactly as you might expect. Lowkey important, bestie.
- Prefetch uses the
cacheto populate the prefetched relationships. This may or may not be what you want. - If you specify a condition on a prefetched relationship, ONLY those rows that match the prefetched condition will be fetched into that relationship. This means that adding prefetch to a
search()may alter what is returned by traversing a relationship. So, if you haveArtist->has_many(CDs)and you do
my $artist_rs = $schema->resultset('Artist')->search({
'cds.year' => 2008,
}, {
join => 'cds',
});
my $count = $artist_rs->first->cds->count;
my $artist_rs_prefetch = $artist_rs->search( {}, { prefetch => 'cds' } );
my $prefetch_count = $artist_rs_prefetch->first->cds->count;
cmp_ok( $count, '==', $prefetch_count, "Counts should be the same" );
That cmp_ok() may or may not pass depending on the datasets involved. In other words, the WHERE condition would apply to the entire dataset, just like it would in regular SQL. If you want to add a condition only to the โright sideโ of a LEFT JOIN โ consider declaring and using a relationship with a custom condition.
๐ฎ DBIC BIND VALUES ๐ฎ
Because DBIC may need more information to bind values than just the column name and value itself, it uses a special format for both passing and receiving bind values. Each bind value should be composed of an arrayref of [ \%args => $val ]. The format of \%args is currently:
๐ง dbd_attrs ๐ง
If present (in any form), this is what is being passed directly to bind_param. Note that different DBDโs expect different bind args. (e.g. DBD::SQLite takes a single numerical type, while DBD::Pg takes a hashref if bind options.)
If this is specified, all other bind options described below are ignored.
๐ง sqlt_datatype ๐ง
If present, this is used to infer the actual bind attribute by passing to $resolved_storage->bind_attribute_by_data_type(). Defaults to the data_type from the add_columns column info.
Note that the data type is somewhat freeform (hence the sqlt_ prefix); currently drivers are expected to โDo the Right Thingโ when given a common datatype name. (Not ideal, but thatโs what we got at this point.)
๐ง sqlt_size ๐ง
Currently used to correctly allocate buffers for bind_param_inout(). Defaults to size from the add_columns column info, or to a sensible value based on the data_type.
๐ง dbic_colname ๐ง
Used to fill in missing sqlt_datatype and sqlt_size attributes (if they are explicitly specified they are never overridden). Also used by some weird DBDs, where the column name should be available at bind_param time (e.g. Oracle).
For backwards compatibility and convenience, the following shortcuts are supported:
[ $name => $val ] === [ { dbic_colname => $name }, $val ]
[ \$dt => $val ] === [ { sqlt_datatype => $dt }, $val ]
[ undef, $val ] === [ {}, $val ]
$val === [ {}, $val ]
โ FURTHER QUESTIONS? โ
Check the list of additional DBIC resources. Go off, bestie ๐ซถ
๐ 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.
Source/version cutie check: this page is from perl v5.42.0, dated 2025-01-22, and itโs DBIx::C...sultSet(3) โ read it, love it, use it responsibly ๐๐
๐ฆ 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