Skip to content

Commit ca2787a

Browse files
committed
introduce LastDayOfMonth
1 parent 7e52d18 commit ca2787a

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/Function/Time/LastDayOfMonth.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tpetry\QueryExpressions\Function\Time;
6+
7+
use Illuminate\Contracts\Database\Query\Expression;
8+
use Illuminate\Database\Grammar;
9+
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
10+
use Tpetry\QueryExpressions\Concerns\StringizeExpression;
11+
12+
class LastDayOfMonth implements Expression
13+
{
14+
use IdentifiesDriver;
15+
use StringizeExpression;
16+
17+
public function __construct(
18+
private readonly string|Expression $expression,
19+
) {
20+
}
21+
22+
public function getValue(Grammar $grammar)
23+
{
24+
$expression = $this->stringize($grammar, $this->expression);
25+
26+
return match ($this->identify($grammar)) {
27+
'mariadb', 'mysql' => "LAST_DAY({$expression})",
28+
'pgsql' => "DATE_TRUNC('month', {$expression}) + interval '1 month - 1 day'",
29+
'sqlite' => "DATE({$expression}, 'start of month', '+1 month', '-1 day')",
30+
'sqlsrv' => "EOMONTH({$expression})",
31+
};
32+
}
33+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Illuminate\Database\Query\Expression;
6+
use Illuminate\Database\Schema\Blueprint;
7+
use Illuminate\Support\Facades\DB;
8+
use Tpetry\QueryExpressions\Function\Time\LastDayOfMonth;
9+
use Tpetry\QueryExpressions\Value\Value;
10+
11+
12+
it('can compute the last day of month of a column')
13+
->expect(new LastDayOfMonth('date'))
14+
->toBeExecutable()
15+
->toBeMysql('LAST_DAY(`date`)')
16+
->toBePgsql('DATE_TRUNC(\'month\', "date") + interval \'1 month - 1 day\'')
17+
->toBeSqlite('DATE("date", \'start of month\', \'+1 month\', \'-1 day\')')
18+
->toBeSqlsrv('EOMONTH([date])');
19+
20+
it('can compute the last day of month of a date')
21+
->expect(new LastDayOfMonth(new Value('2024-01-03')))
22+
->toBeExecutable()
23+
->toBeMysql("LAST_DAY('2024-01-03')")
24+
->toBePgsql("DATE_TRUNC('month', '2024-01-03') + interval '1 month - 1 day'")
25+
->toBeSqlite("DATE('2024-01-03', 'start of month', '+1 month', '-1 day')")
26+
->toBeSqlsrv('EOMONTH(\'2024-01-03\')');

0 commit comments

Comments
 (0)