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, so perl 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".
  • 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 the key attribute and supply the entire condition as an argument to find โ€” 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. ๐ŸŽ€


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.


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 in 0.09. Use search() 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 call next on it. Calling resultset('Table')->next repeatedly 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 the result_class will also remove any components that were originally loaded in the source class via load_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_literal is provided for Class::DBI compatibility and should only be used in that context. See search_literal for 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). See update_all if 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 the in_storage status of any result object instances derived from this resultset (this includes the contents of the resultset cache, if any). See delete_all if 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_fetch in DBI). That means it bypasses the new and insert calls on the Result class entirely, including any augmentation of those methods that your components provide. So likeโ€ฆ if you're using something like DBIx::Class::UUIDColumns to 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 of find and understand the significance of the key attribute, as its lack may skew your search, and subsequently result in spurious new objects. ๐Ÿ˜ญ
Note: Take care when using find_or_new with a table having columns with default values that you intend to be automatically supplied by the database (e.g. an auto_increment primary key column). In normal usage, the value of such columns should NOT be included at all in the call to find_or_new, even when set to undef. 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 either new in DBIx::Class::Row or insert in DBIx::Class::Row depending on how early in the create process you need to intervene. See also warning pertaining to new. 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 of find and understand the significance of the key attribute, as its lack may skew your search, and subsequently result in spurious row creation. ๐Ÿ™ˆ
Note: Because find_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, use find_or_create() inside a transaction. Please. For me. ๐Ÿ’€
Note: Take care when using find_or_create with a table having columns with default values that you intend to be automatically supplied by the database (e.g. an auto_increment primary key column). In normal usage, the value of such columns should NOT be included at all in the call to find_or_create, even when set to undef.

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 an auto_increment primary 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 to undef. 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. an auto_increment primary 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 to undef.

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.


  • 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 matching as attribute when you use select โ€” 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 just select with 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 plain as. 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 cache to 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 have Artist->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 ๐Ÿซถ

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