Skip to content

Commit

Permalink
Fixed issue: Added a call to the getValue method (laravel#48652)
Browse files Browse the repository at this point in the history
* Fixed issue: Added a call to the getValue method. Without this, raw SQL queries in conditions throw an exception.

* Added check to prevent call on types other than Expression

* Added new test cases for the modified method

* Refactored the variable names

* Fixed a StyleCI issue

* Update Grammar.php

---------

Co-authored-by: Bojan Lozo <bojanlo@maestralsolutions.com>
Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
3 people authored and timacdonald committed Oct 24, 2023
1 parent 6c0bf78 commit 10843be
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Query/Grammars/Grammar.php
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Database\Query\Grammars;

use Illuminate\Contracts\Database\Query\Expression;
use Illuminate\Database\Concerns\CompilesJsonPaths;
use Illuminate\Database\Grammar as BaseGrammar;
use Illuminate\Database\Query\Builder;
Expand Down Expand Up @@ -246,7 +247,7 @@ protected function concatenateWhereClauses($query, $sql)
*/
protected function whereRaw(Builder $query, $where)
{
return $where['sql'];
return $where['sql'] instanceof Expression ? $where['sql']->getValue($this) : $where['sql'];
}

/**
Expand Down
44 changes: 44 additions & 0 deletions tests/Database/DatabaseQueryGrammarTest.php
@@ -0,0 +1,44 @@
<?php

namespace Illuminate\Tests\Database;

use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Query\Grammars\Grammar;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

class DatabaseQueryGrammarTest extends TestCase
{
protected function tearDown(): void
{
m::close();
}

public function testWhereRawReturnsStringWhenExpressionPassed()
{
$builder = m::mock(Builder::class);
$grammar = new Grammar;
$reflection = new ReflectionClass($grammar);
$method = $reflection->getMethod('whereRaw');
$expressionArray = ['sql' => new Expression('select * from "users"')];

$rawQuery = $method->invoke($grammar, $builder, $expressionArray);

$this->assertSame('select * from "users"', $rawQuery);
}

public function testWhereRawReturnsStringWhenStringPassed()
{
$builder = m::mock(Builder::class);
$grammar = new Grammar;
$reflection = new ReflectionClass($grammar);
$method = $reflection->getMethod('whereRaw');
$stringArray = ['sql' => 'select * from "users"'];

$rawQuery = $method->invoke($grammar, $builder, $stringArray);

$this->assertSame('select * from "users"', $rawQuery);
}
}

0 comments on commit 10843be

Please sign in to comment.