framework icon indicating copy to clipboard operation
framework copied to clipboard

Return collection from the query builder

Open JosephSilber opened this issue 11 years ago • 176 comments

This issue was created to get community feedback.


It would be awesome if we could have the query builder return a collection:

$collection = DB::table('posts')->get();

Given that PHP in some situations infamously does not treat ArrayAccess objects as arrays, this would be breaking BC. This will obviously be targeted for the next release of Laravel.

Pros

  1. Makes it consistent with Eloquent. You'll find countless questions on StackOverflow asking why some collection method can't be called on a query builder result.
  2. It's just much cleaner than this: collect(DB::table('posts')->get()). Laravel prides itself on making all these tiny interactions more enjoyable. This should not be any different.
  3. Native PHP arrays are just useless :smile:

Cons

  1. It's a breaking change. Some people's tests might fail because they're using array_* or typehinting for an array. If their code can't be updated to use a collection, they'll have to append ->all() to their results.

If people don't have good test coverage, they'll have to search their codebase for ->get( and manually tack on ->all() wherever necessary. Not the end of the world, but definitely a breaking change.


Overall I think this change is well worth it and would love some feedback from the community. If you use the query builder directly, please leave a comment below with your thoughts either way, or if I missed any pros/cons.

Thank you :heart:

JosephSilber avatar Oct 04 '15 03:10 JosephSilber

:-1:

Not a fan of this, in my use case we appreciate that the query builder use simple array because it just what we need, and only use Collection if we need to. Having it return as Collection and then manipulate it again as another collection is just redundant.

If both QB and Eloquent a collection, what would even be the benefit to choose QB when you already including additional process to it. We used QB because we want fast array, you can throw that it just 0.001 sec per x but it the main reason why I would use QB for certain things instead of Eloquent (if not why would even anyone bother to use QB).

Why is Model::find(x)->update() isn't the same with Model::update(), why not "consistency" a factor here?

PHP arrays are just evil

What?

Native PHP arrays are just useless

Collection methods are wrap around array_* native functions. It's not useless.

crynobone avatar Oct 04 '15 03:10 crynobone

:+1:

I'm a huge fan of this. Consistency is so valuable, and I wind up doing collect(DB::table('posts')->get()) almost 100% of the time. I really don't see any practical downsides, other than the "We can make do without it" arguement that gets brought up a lot. That doesn't really make sense to me.

hipsterjazzbo avatar Oct 04 '15 05:10 hipsterjazzbo

The idealist in me would very much enjoy this. It makes most sense being a collection, and it would provide good consistency (it's weird for one get() to be a collection and another an array).

As you said, though, the backwards compatibility penalty is in a really bad shape (and hugely because of PHP's wonky non-object arrays). I know a great deal of legacy code that typehints QB return values with arrays (again, because PHP to my knowledge has no clean and consistent way to typehint that accepts both arrays and collections, grumble grumble). This same issue applies to code that uses the array_x functions. This is a fairly major compatibility break, as it can easily affect pretty much any codebase, component or package that uses the Query Builder.

So while I agree with the sentiment, I don't think it'll be possible unless we solve the compatibility issue.

An alternate resolution I've pondered in the past would be to provide a configurable return class for the QB (and, be extension, probably Eloquent as well). This has an additional side-benefit: users would be able to use their custom collection classes (their own classes, another framework's collection, an extension of laravel's collection etc). This doesn't solve the whole issue, though, and potentially make it worse: a person might be using a package that demands the array-returning QB while another package wants it returning collections.

rizqidjamaluddin avatar Oct 04 '15 06:10 rizqidjamaluddin

Makes it consistent with Eloquent. You'll find countless questions on StackOverflow asking why some collection method can't be called on a query builder result.

It's weird for one get() to be a collection and another an array

IMHO, collections and consistency between query builder and Eloquent. Though I assume this would have to be for 5.2 because breaking, with mention in upgrade notes?

jesseleite avatar Oct 05 '15 04:10 jesseleite

I'm with @HipsterJazzbo, every time I run DB::select or whatever, I tend to wrap it in a new collection.

jbrooksuk avatar Oct 05 '15 07:10 jbrooksuk

If we do make this change, 5.2 is a good place to make it IMO.

GrahamCampbell avatar Oct 05 '15 10:10 GrahamCampbell

I was meaning rather than holding off until 5.3, I'd rather we did it in 5.2 if at all.

GrahamCampbell avatar Oct 05 '15 10:10 GrahamCampbell

Even Laravel Doctrine is now returning collections!

JosephSilber avatar Oct 07 '15 02:10 JosephSilber

I'll have to agree with both sides here; @crynobone makes a very good point that arrays are, for accessing data, faster. And indeed, collection methods merely wrap around array functions. That being said, I believe if performance is an issue, you've got more issues such as running an entire framework (or inefficient SQL queries or tons of other things that aren't completely optimised for special scenarios).

Now, I would appreciate this actually being implemented. However, if you want a middle ground, you can always offer the option; allow the user whether to have collections returned or not (and default to true). This would allow the users who actually want arrays returned, for performance or else, to get that.

Other than that, I'm totally in favour of this.

phroggyy avatar Oct 07 '15 19:10 phroggyy

@phroggyy Where would you give them the option to set collections/arrays as default return type? /config/database.php? I agree though, if performance is an issue, you probably have more problems affecting performance than just Collection instantiation on your result set.

That said, I'm still in definitely favour of Collections for consistency between Eloquent and Query Builder get() methods.

jesseleite avatar Oct 07 '15 20:10 jesseleite

Database config or a static variable on the Collection. ke 7. lokakuuta 2015 klo 22.44 Jesse Leite [email protected] kirjoitti:

@phroggyy https://github.com/phroggyy Where would you give them the option to set collections/arrays as default return type? /config/database.php? I agree though, if performance is an issue, you probably have more problems affecting performance than just Collection instantiation on your result set.

That said, I'm still in definitely favour of Collections for consistency between Eloquent and Query Builder get() methods.

— Reply to this email directly or view it on GitHub https://github.com/laravel/framework/issues/10478#issuecomment-146321947 .

phroggyy avatar Oct 07 '15 20:10 phroggyy

Sorry to everyone who proposed it, but having it be configurable is just giving us the worst of both worlds.

Not only will it lead to even more confusion, but it'll lead to terrible inconsistency for packages and such.

Having it configurable is not on the table. The question is whether we should change it or not.


Performance is a non-issue.

This is nothing like Eloquent. Eloquent has to spin up separate model objects for each record. If you fetch hundreds or thousands of records, that could occasionally be a problem.

A collection is a single object, regardless of how many records you fetch. You can always just call all() on the results to have a simple array. You'd have created one single throw-away object. No biggie.

JosephSilber avatar Oct 07 '15 21:10 JosephSilber

Very good point. So stating clearly this time: I'm all in favour of this for consistency. ke 7. lokakuuta 2015 klo 23.05 Joseph Silber [email protected] kirjoitti:

Sorry to everyone who proposed it, but having it be configurable is a terribly stupid idea.

Not only will it lead to even more confusion, but it'll lead to terrible inconsistency for packages and such.

Having it configurable is not on the table. The question is whether we

should change it or not.

Performance is a non-issue. This is nothing like Eloquent. Eloquent has to spin up models for each record in the database. If you're querying thousands of records, that could occasionally be a problem. But a collection is a single object, regardless of how many records you have.

— Reply to this email directly or view it on GitHub https://github.com/laravel/framework/issues/10478#issuecomment-146329192 .

phroggyy avatar Oct 07 '15 21:10 phroggyy

Performance is a non-issue.

Yeh, returning collections rather than arrays takes very little time to execute in comparison to any database queries.

GrahamCampbell avatar Oct 07 '15 22:10 GrahamCampbell

:+1: The upgrade doesn't look too painful to me. And if you are not ready for such difficulties you can always stay on L5.1 LTS.

arrilot avatar Oct 07 '15 22:10 arrilot

Yeh, returning collections rather than arrays takes very little time to execute in comparison to any database queries.

Regardless if you trying to process 10,000 rows or 100,000 rows? We use query builder for low level analytics process, and extra seconds is not what we're looking for.

crynobone avatar Oct 07 '15 22:10 crynobone

@crynobone Yes. Even if you're processing 17 billion records. It doesn't matter.

Like I said, this is not Eloquent.

You get one single wrapper collection object, and that's it. It's still the same array underneath it all.

JosephSilber avatar Oct 07 '15 23:10 JosephSilber

I'd support it be a BC change on the next BC-accepting version of Laravel (5.2 presumably). I also agree that making it configurable is a tad strange - though it's with precedent, given Model::newCollection. But I digress.

Worth noting that packages will want to maintain a 5.1 and 5.2 branch separately for this purpose, given 5.1's LTS. No different than packages maintaining an L4 branch really.

The performance penalty for a single collection object is pretty much negligible since it basically just wraps the array - if you want to get out of the collection using ->all(), the only loss is the bit of memory set for that temporary collection.

rizqidjamaluddin avatar Oct 08 '15 01:10 rizqidjamaluddin

<?php

ini_set('memory_limit', '1024M');

require "vendor/autoload.php";

use Symfony\Component\Stopwatch\Stopwatch;

function formatSeconds($ms) {
    return ($ms/1000000).'sec';
}

function formatBytes($size, $precision = 2) {
    $base = log($size, 1024);
    $suffixes = array('', 'k', 'M', 'G', 'T');

    return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}

$stopwatch = new Stopwatch();

$data = array_fill(0, $argv[1], [
    'uuid' => 1,
    'latitude' => 0,
    'longitude' => 0,
    'other' => '<foo>5</foo><bar>3</foo>',
    'speed' => 50,
]);

$stopwatch->start('iterate');

$speeding = [];

foreach ($data as $item) {
    if ($item['speed'] > 100) {
        $speeding[] = $item['uuid'];
    }
}

$iterate = $stopwatch->stop('iterate');

var_dump(
    formatSeconds($iterate->getDuration()), formatBytes($iterate->getMemory()), formatBytes(memory_get_peak_usage(true))
);

vs

<?php

ini_set('memory_limit', '1024M');

require "vendor/autoload.php";

use Illuminate\Support\Collection;
use Symfony\Component\Stopwatch\Stopwatch;

function formatSeconds($ms) {
    return ($ms/1000000).'sec';
}

function formatBytes($size, $precision = 2) {
    $base = log($size, 1024);
    $suffixes = array('', 'k', 'M', 'G', 'T');

    return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}

$stopwatch = new Stopwatch();

$fill = array_fill(0, $argv[1], [
    'uuid' => 1,
    'latitude' => 0,
    'longitude' => 0,
    'other' => '<foo>5</foo><bar>3</foo>',
    'speed' => 50,
]);

$stopwatch->start('iterate');

$data = Collection::make($fill);
$speeding = [];

foreach ($data as $item) {
    if ($item['speed'] > 100) {
        $speeding[] = $item['uuid'];
    }
}

$iterate = $stopwatch->stop('iterate');

var_dump(
    formatSeconds($iterate->getDuration()), formatBytes($iterate->getMemory()), formatBytes(memory_get_peak_usage(true))
);

Sure you can say the performance increase is minimal, but peak memory?

newplot

With only memory_limits=1024M, Collection can make out to 5.3 mill records while simple array can reach double that value at 10.6 mill. Now this is only single process.

crynobone avatar Oct 08 '15 01:10 crynobone

@crynobone don't loop over the collection. Change the loop in your second example to this:

foreach ($data->all() as $item) {
    if ($item['speed'] > 100) {
        $speeding[] = $item['uuid'];
    }
}

Like I said, if you really care about this tiny difference in performance, get the array from the collection right away. The only overhead you'll now have is creating and throwing away the collection object, which is truly negligible.

JosephSilber avatar Oct 08 '15 02:10 JosephSilber