Skip to content

PHPORM-60 Fix Query on whereDate, whereDay, whereMonth, whereYear #2572

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

Merged
merged 7 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ All notable changes to this project will be documented in this file.
- Fix validation of unique values when the validated value is found as part of an existing value. [#21](https://github.com/GromNaN/laravel-mongodb/pull/21) by [@GromNaN](https://github.com/GromNaN).
- Support `%` and `_` in `like` expression [#17](https://github.com/GromNaN/laravel-mongodb/pull/17) by [@GromNaN](https://github.com/GromNaN).
- Change signature of `Query\Builder::__constructor` to match the parent class [#26](https://github.com/GromNaN/laravel-mongodb-private/pull/26) by [@GromNaN](https://github.com/GromNaN).
- Fix Query on `whereDate`, `whereDay`, `whereMonth`, `whereYear`, `whereTime` to use MongoDB operators [#2570](https://github.com/jenssegers/laravel-mongodb/pull/2376) by [@Davpyu](https://github.com/Davpyu) and [@GromNaN](https://github.com/GromNaN).

## [3.9.2] - 2022-09-01

Expand Down
107 changes: 79 additions & 28 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Jenssegers\Mongodb\Connection;
Expand Down Expand Up @@ -115,6 +116,7 @@ class Builder extends BaseBuilder
* @var array
*/
protected $conversion = [
'=' => 'eq',
'!=' => 'ne',
'<>' => 'ne',
'<' => 'lt',
Expand Down Expand Up @@ -1075,7 +1077,7 @@ protected function compileWhereBasic(array $where): array
$operator = $operator === 'regex' ? '=' : 'not';
}

if (! isset($operator) || $operator == '=') {
if (! isset($operator) || $operator === '=' || $operator === 'eq') {
$query = [$column => $value];
} else {
$query = [$column => ['$'.$operator => $value]];
Expand Down Expand Up @@ -1180,12 +1182,35 @@ protected function compileWhereBetween(array $where): array
*/
protected function compileWhereDate(array $where): array
{
extract($where);

$where['operator'] = $operator;
$where['value'] = $value;
$startOfDay = new UTCDateTime(Carbon::parse($where['value'])->startOfDay());
$endOfDay = new UTCDateTime(Carbon::parse($where['value'])->endOfDay());

return $this->compileWhereBasic($where);
return match($where['operator']) {
'eq', '=' => [
$where['column'] => [
'$gte' => $startOfDay,
'$lte' => $endOfDay,
],
],
'ne' => [
$where['column'] => [
'$not' => [
'$gte' => $startOfDay,
'$lte' => $endOfDay,
],
],
],
'lt', 'gte' => [
$where['column'] => [
'$'.$where['operator'] => $startOfDay,
],
],
'gt', 'lte' => [
$where['column'] => [
'$'.$where['operator'] => $endOfDay,
],
],
};
}

/**
Expand All @@ -1194,12 +1219,16 @@ protected function compileWhereDate(array $where): array
*/
protected function compileWhereMonth(array $where): array
{
extract($where);

$where['operator'] = $operator;
$where['value'] = $value;

return $this->compileWhereBasic($where);
return [
'$expr' => [
'$'.$where['operator'] => [
[
'$month' => '$'.$where['column'],
],
(int) $where['value'],
],
],
];
}

/**
Expand All @@ -1208,12 +1237,16 @@ protected function compileWhereMonth(array $where): array
*/
protected function compileWhereDay(array $where): array
{
extract($where);

$where['operator'] = $operator;
$where['value'] = $value;

return $this->compileWhereBasic($where);
return [
'$expr' => [
'$'.$where['operator'] => [
[
'$dayOfMonth' => '$'.$where['column'],
],
(int) $where['value'],
],
],
];
}

/**
Expand All @@ -1222,12 +1255,16 @@ protected function compileWhereDay(array $where): array
*/
protected function compileWhereYear(array $where): array
{
extract($where);

$where['operator'] = $operator;
$where['value'] = $value;

return $this->compileWhereBasic($where);
return [
'$expr' => [
'$'.$where['operator'] => [
[
'$year' => '$'.$where['column'],
],
(int) $where['value'],
],
],
];
}

/**
Expand All @@ -1236,12 +1273,26 @@ protected function compileWhereYear(array $where): array
*/
protected function compileWhereTime(array $where): array
{
extract($where);
if (! is_string($where['value']) || ! preg_match('/^[0-2][0-9](:[0-6][0-9](:[0-6][0-9])?)?$/', $where['value'], $matches)) {
throw new \InvalidArgumentException(sprintf('Invalid time format, expected HH:MM:SS, HH:MM or HH, got "%s"', is_string($where['value']) ? $where['value'] : get_debug_type($where['value'])));
}

$where['operator'] = $operator;
$where['value'] = $value;
$format = match (count($matches)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever use of count($matches).

1 => '%H',
2 => '%H:%M',
3 => '%H:%M:%S',
};

return $this->compileWhereBasic($where);
return [
'$expr' => [
'$'.$where['operator'] => [
[
'$dateToString' => ['date' => '$'.$where['column'], 'format' => $format],
],
$where['value'],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We talked about validating user input. Should we enforce a string in the format HH:MM:SS and permit trailing components to be omitted (e.g. allow HH:MM or even just HH)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed with support for various time formats.

],
],
];
}

/**
Expand Down
9 changes: 5 additions & 4 deletions tests/Models/Birthday.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
*
* @property string $name
* @property string $birthday
* @property string $day
* @property string $month
* @property string $year
* @property string $time
*/
class Birthday extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'birthday';
protected $fillable = ['name', 'birthday', 'day', 'month', 'year', 'time'];
protected $fillable = ['name', 'birthday'];

protected $casts = [
'birthday' => 'datetime',
];
}
182 changes: 182 additions & 0 deletions tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,170 @@ function (Builder $builder) {
fn (Builder $builder) => $builder->where('name', 'not regex', '/^acme$/si'),
];

yield 'where date' => [
['find' => [['created_at' => [
'$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')),
'$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '2018-09-30'),
];

yield 'where date DateTimeImmutable' => [
['find' => [['created_at' => [
'$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')),
'$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '=', new DateTimeImmutable('2018-09-30 15:00:00 +02:00')),
];

yield 'where date !=' => [
['find' => [['created_at' => [
'$not' => [
'$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')),
'$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')),
],
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '!=', '2018-09-30'),
];

yield 'where date <' => [
['find' => [['created_at' => [
'$lt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '<', '2018-09-30'),
];

yield 'where date >=' => [
['find' => [['created_at' => [
'$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '>=', '2018-09-30'),
];

yield 'where date >' => [
['find' => [['created_at' => [
'$gt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '>', '2018-09-30'),
];

yield 'where date <=' => [
['find' => [['created_at' => [
'$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')),
]], []]],
fn (Builder $builder) => $builder->whereDate('created_at', '<=', '2018-09-30'),
];

yield 'where day' => [
['find' => [['$expr' => [
'$eq' => [
['$dayOfMonth' => '$created_at'],
5,
],
]], []]],
fn (Builder $builder) => $builder->whereDay('created_at', 5),
];

yield 'where day > string' => [
['find' => [['$expr' => [
'$gt' => [
['$dayOfMonth' => '$created_at'],
5,
],
]], []]],
fn (Builder $builder) => $builder->whereDay('created_at', '>', '05'),
];

yield 'where month' => [
['find' => [['$expr' => [
'$eq' => [
['$month' => '$created_at'],
10,
],
]], []]],
fn (Builder $builder) => $builder->whereMonth('created_at', 10),
];

yield 'where month > string' => [
['find' => [['$expr' => [
'$gt' => [
['$month' => '$created_at'],
5,
],
]], []]],
fn (Builder $builder) => $builder->whereMonth('created_at', '>', '05'),
];

yield 'where year' => [
['find' => [['$expr' => [
'$eq' => [
['$year' => '$created_at'],
2023,
],
]], []]],
fn (Builder $builder) => $builder->whereYear('created_at', 2023),
];

yield 'where year > string' => [
['find' => [['$expr' => [
'$gt' => [
['$year' => '$created_at'],
2023,
],
]], []]],
fn (Builder $builder) => $builder->whereYear('created_at', '>', '2023'),
];

yield 'where time HH:MM:SS' => [
['find' => [['$expr' => [
'$eq' => [
['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']],
'10:11:12',
],
]], []]],
fn (Builder $builder) => $builder->whereTime('created_at', '10:11:12'),
];

yield 'where time HH:MM' => [
['find' => [['$expr' => [
'$eq' => [
['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M']],
'10:11',
],
]], []]],
fn (Builder $builder) => $builder->whereTime('created_at', '10:11'),
];

yield 'where time HH' => [
['find' => [['$expr' => [
'$eq' => [
['$dateToString' => ['date' => '$created_at', 'format' => '%H']],
'10',
],
]], []]],
fn (Builder $builder) => $builder->whereTime('created_at', '10'),
];

yield 'where time DateTime' => [
['find' => [['$expr' => [
'$eq' => [
['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']],
'10:11:12',
],
]], []]],
fn (Builder $builder) => $builder->whereTime('created_at', new \DateTimeImmutable('2023-08-22 10:11:12')),
];

yield 'where time >' => [
['find' => [['$expr' => [
'$gt' => [
['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']],
'10:11:12',
],
]], []]],
fn (Builder $builder) => $builder->whereTime('created_at', '>', '10:11:12'),
];

/** @see DatabaseQueryBuilderTest::testBasicSelectDistinct */
yield 'distinct' => [
['distinct' => ['foo', [], []]],
Expand Down Expand Up @@ -774,6 +938,24 @@ public static function provideExceptions(): iterable
'Missing expected ending delimiter "/" in regular expression "/foo#bar"',
fn (Builder $builder) => $builder->where('name', 'regex', '/foo#bar'),
];

yield 'whereTime with invalid time' => [
\InvalidArgumentException::class,
'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "10:11:12:13"',
fn (Builder $builder) => $builder->whereTime('created_at', '10:11:12:13'),
];

yield 'whereTime out of range' => [
\InvalidArgumentException::class,
'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "23:70"',
fn (Builder $builder) => $builder->whereTime('created_at', '23:70'),
];

yield 'whereTime invalid type' => [
\InvalidArgumentException::class,
'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "stdClass"',
fn (Builder $builder) => $builder->whereTime('created_at', new \stdClass()),
];
}

/** @dataProvider getEloquentMethodsNotSupported */
Expand Down
Loading