Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow resetting offset and limit #31

Merged
merged 2 commits into from
Sep 19, 2017

Conversation

bpolaszek
Copy link
Contributor

Hello @shadowhand,

I hope you're doing well.

I've figured out the current SelectQuery does not allow to reset limit() and offset() (their definitions do not allow null values). The only way to reset them is to set them to 0, but here's what it does with an example use case:

require_once __DIR__ . '/vendor/autoload.php';

use Latitude\QueryBuilder\SelectQuery;
use Latitude\QueryBuilder\Expression as e;
use Latitude\QueryBuilder\Conditions as c;

$query = SelectQuery::make();
$query->from('my_table');
$query->orderBy(['id', 'desc']);
$query->where(
    c::make('foo = bar')
);
$query->offset(50);
$query->limit(10);

$count = clone $query; // Create a COUNT(*) query for pagination, with the same WHERE conditions
$count->columns(e::make('COUNT(*)'));
$count->limit(0); // Reset limit to count all rows
$count->offset(0); // Reset offset to count all rows

print $query->sql();
print PHP_EOL;
print $count->sql();

Here's what it currently produces:

SELECT * FROM my_table WHERE foo = bar ORDER BY id DESC LIMIT 10 OFFSET 50
SELECT COUNT(*) FROM my_table WHERE foo = bar ORDER BY id DESC OFFSET 0

The 2nd statement is not valid SQL (at least, MySQL kicks me out) because the intended behaviour was not to set the limit and offset to 0 but to remove these parts from the query.

The solution

With this PR null values will be allowed:

$count->limit(null);
$count->offset(null);

Now outputs:

SELECT * FROM my_table WHERE foo = bar ORDER BY id DESC LIMIT 10 OFFSET 50
SELECT COUNT(*) FROM my_table WHERE foo = bar ORDER BY id DESC

BC breaks

$count->limit(0);
$count->offset(0);

Will now output:

SELECT * FROM my_table WHERE date_added BETWEEN ? and ? ORDER BY id DESC LIMIT 10 OFFSET 50
SELECT COUNT(*) FROM my_table WHERE date_added BETWEEN ? and ? ORDER BY  LIMIT 0 OFFSET 0

But at least this is now valid SQL.

@bpolaszek bpolaszek changed the title Allow null values to reset some parts Allow resetting offset and limit Sep 19, 2017
@shadowhand
Copy link
Owner

Works for me, thanks!

@shadowhand shadowhand merged commit a03c550 into shadowhand:master Sep 19, 2017
@bpolaszek
Copy link
Contributor Author

Thanks @shadowhand !

shadowhand added a commit that referenced this pull request Sep 19, 2017
@shadowhand
Copy link
Owner

Released in version 2.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants