Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBIx::Class example

In this example below:

my $rs = $schema->resultset('CD')->search(
{
  'artist.name' => 'Bob Marley'
  'liner_notes.notes' => { 'like', '%some text%' },
},
{
  join     => [qw/ artist liner_notes /],
  order_by => [qw/ artist.name /],
}
);

The DBIx cookbook says that this is the sql that will be generated:

# Equivalent SQL:
# SELECT cd.*, artist.*, liner_notes.* FROM cd
# JOIN artist ON cd.artist = artist.id
# JOIN liner_notes ON cd.id = liner_notes.cd
# WHERE artist.name = 'Bob Marley'
# ORDER BY artist.name

But from the rest of the cookbook, I've been lead to believe that the query would only select cd.*, unless of course prefetch was used like so:

my $rs = $schema->resultset('CD')->search(
{
  'artist.name' => 'Bob Marley'
  'liner_notes.notes' => { 'like', '%some text%' },
},
{
  join     => [qw/ artist liner_notes /],
  order_by => [qw/ artist.name /],
  prefetch => [qw/ artist liner_notes/],
}
);

Below is the statement that leads me to believe this:

[Prefetch] allows you to fetch results from related tables in advance

Can anyone explain to me either what I'm missing here? Or not? Thanks a lot!

like image 723
srchulo Avatar asked Oct 07 '22 12:10

srchulo


1 Answers

The Equivalent SQL contradicts the previous section of the cookbook and looks like an error.

Join will use the columns from the joined tables when performing the query and applying the filter and sorting conditions, but it won't return the columns for the joined tables. This means that if you do $cd->artist->name then it will need it to do an additional SELECT artist.* FROM artist WHERE artist.id = ? to get the artist's name each time you call that statement.

Prefetch is used to select all columns from the prefetch tables as well. It is more efficient to use prefetch when you actually need those columns, e.g. so you can do $cd->artist->name without needing it to do the additional query. But if you don't need those columns then you have an unnecessary performance hit for loading up that data.

like image 85
stevenl Avatar answered Oct 11 '22 13:10

stevenl