From 40e117ae4daa4c49943ab47c948cf5d53f04f616 Mon Sep 17 00:00:00 2001 From: Florent Destremau Date: Sat, 9 Mar 2024 13:36:12 +0100 Subject: [PATCH] Force typing for Postgresql::`date_trunc` so it can be used in a condition (#415) --- src/Query/Postgresql/DateTrunc.php | 2 +- tests/Query/Postgresql/DateTruncTest.php | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Query/Postgresql/DateTrunc.php b/src/Query/Postgresql/DateTrunc.php index 8ea90b51..5c517e08 100644 --- a/src/Query/Postgresql/DateTrunc.php +++ b/src/Query/Postgresql/DateTrunc.php @@ -28,7 +28,7 @@ public function parse(Parser $parser): void public function getSql(SqlWalker $sqlWalker): string { return sprintf( - 'DATE_TRUNC(%s, %s)', + 'DATE_TRUNC(%s::text, %s::timestamp)', $this->fieldText->dispatch($sqlWalker), $this->fieldTimestamp->dispatch($sqlWalker) ); diff --git a/tests/Query/Postgresql/DateTruncTest.php b/tests/Query/Postgresql/DateTruncTest.php index 34aeb26a..92d2bad2 100644 --- a/tests/Query/Postgresql/DateTruncTest.php +++ b/tests/Query/Postgresql/DateTruncTest.php @@ -2,7 +2,9 @@ namespace DoctrineExtensions\Tests\Query\Postgresql; +use DateTime; use Doctrine\ORM\QueryBuilder; +use DoctrineExtensions\Tests\Entities\Date; use DoctrineExtensions\Tests\Query\PostgresqlTestCase; class DateTruncTest extends PostgresqlTestCase @@ -14,7 +16,19 @@ public function testDateTrunc(): void ->select("date_trunc('YEAR', dt.created)") ->from('DoctrineExtensions\Tests\Entities\Date', 'dt'); - $expected = "SELECT DATE_TRUNC('YEAR', d0_.created) AS sclr_0 FROM Date d0_"; + $expected = "SELECT DATE_TRUNC('YEAR'::text, d0_.created::timestamp) AS sclr_0 FROM Date d0_"; + + $this->assertEquals($expected, $queryBuilder->getQuery()->getSQL()); + } + + public function testDateTruncCondition(): void + { + $queryBuilder = $this->entityManager->getRepository(Date::class) + ->createQueryBuilder('dt') + ->where("date_trunc('YEAR', dt.created) = date_trunc('YEAR', :date)") + ->setParameter('date', new DateTime('2010-01-01')); + + $expected = "SELECT d0_.id AS id_0, d0_.created AS created_1 FROM Date d0_ WHERE DATE_TRUNC('YEAR'::text, d0_.created::timestamp) = DATE_TRUNC('YEAR'::text, ?::timestamp)"; $this->assertEquals($expected, $queryBuilder->getQuery()->getSQL()); }