Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
* `ExtractYear` time function to extract the year from date/datetime columns

## [1.5.0] - 2025-02-14
### Added
* Laravel 12 support
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,12 +360,25 @@ Schema::table('users', function (Blueprint $table): void {

#### Time
```php
use Tpetry\QueryExpressions\Function\Time\ExtractYear;
use Tpetry\QueryExpressions\Function\Time\Now;
use Tpetry\QueryExpressions\Function\Time\TimestampBin;

new ExtractYear(string|Expression $column);
new Now();
new TimestampBin(string|Expression $expression, DateInterval $step, ?DateTimeInterface $origin = null);

// Extract year for filtering or grouping
User::select([
new Alias(new ExtractYear('created_at'), 'registration_year'),
new Count('*'),
])->groupBy(new ExtractYear('created_at'))->get();

// Use with CountFilter for year-based aggregations
Movie::select([
new Alias(new CountFilter(new Equal(new ExtractYear('released_at'), new Value(2024))), 'released_2024'),
])->get();

BlogVisit::select([
'url',
new TimestampBin('created_at', DateInterval::createFromDateString('5 minutes')),
Expand Down
31 changes: 31 additions & 0 deletions src/Function/Time/ExtractYear.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Tpetry\QueryExpressions\Function\Time;

use Illuminate\Contracts\Database\Query\Expression;
use Illuminate\Database\Grammar;
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
use Tpetry\QueryExpressions\Concerns\StringizeExpression;

class ExtractYear implements Expression
{
use IdentifiesDriver;
use StringizeExpression;

public function __construct(
private readonly string|Expression $column,
) {}

public function getValue(Grammar $grammar): string
{
$column = $this->stringize($grammar, $this->column);

return match ($this->identify($grammar)) {
'mariadb', 'mysql', 'sqlsrv' => "year({$column})",
'pgsql' => "extract(year from {$column})::int",
'sqlite' => "cast(strftime('%Y', {$column}) as integer)",
};
}
}
27 changes: 27 additions & 0 deletions tests/Function/Time/ExtractYearTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Query\Expression;
use Illuminate\Database\Schema\Blueprint;
use Tpetry\QueryExpressions\Function\Time\ExtractYear;

it('can extract the year from a column')
->expect(new ExtractYear('val'))
->toBeExecutable(function (Blueprint $table) {
$table->date('val');
})
->toBeMysql('year(`val`)')
->toBePgsql('extract(year from "val")::int')
->toBeSqlite('cast(strftime(\'%Y\', "val") as integer)')
->toBeSqlsrv('year([val])');

it('can extract the year from an expression')
->expect(new ExtractYear(new Expression('current_date')))
->toBeExecutable(function (Blueprint $table) {
$table->date('val');
})
->toBeMysql('year(current_date)')
->toBePgsql('extract(year from current_date)::int')
->toBeSqlite('cast(strftime(\'%Y\', current_date) as integer)')
->toBeSqlsrv('year(current_date)');