Skip to content

Commit 6db12a5

Browse files
Adds toRawSql() to Query Builders (#5898)
Co-authored-by: 李铭昕 <[email protected]>
1 parent 52d2f4a commit 6db12a5

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/Query/Grammars/PostgresGrammar.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,28 @@ public function compileTruncate(Builder $query): array
152152
return ['truncate ' . $this->wrapTable($query->from) . ' restart identity cascade' => []];
153153
}
154154

155+
/**
156+
* Substitute the given bindings into the given raw SQL query.
157+
*
158+
* @param string $sql
159+
* @param array $bindings
160+
* @return string
161+
*/
162+
public function substituteBindingsIntoRawSql($sql, $bindings)
163+
{
164+
$query = parent::substituteBindingsIntoRawSql($sql, $bindings);
165+
166+
foreach ($this->operators as $operator) {
167+
if (! str_contains($operator, '?')) {
168+
continue;
169+
}
170+
171+
$query = str_replace(str_replace('?', '??', $operator), $operator, $query);
172+
}
173+
174+
return $query;
175+
}
176+
155177
/**
156178
* Compile an update from statement into SQL.
157179
*
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
/**
5+
* This file is part of Hyperf.
6+
*
7+
* @link https://www.hyperf.io
8+
* @document https://hyperf.wiki
9+
* @contact [email protected]
10+
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
11+
*/
12+
namespace HyperfTest\Database\PgSQL\Cases;
13+
14+
use Hyperf\Database\Connection;
15+
use Hyperf\Database\PgSQL\Query\Grammars\PostgresGrammar;
16+
use Mockery as m;
17+
use PHPUnit\Framework\TestCase;
18+
19+
/**
20+
* @internal
21+
* @coversNothing
22+
*/
23+
class DatabasePostgresQueryGrammarTest extends TestCase
24+
{
25+
protected function tearDown(): void
26+
{
27+
m::close();
28+
}
29+
30+
public function testToRawSql()
31+
{
32+
$connection = m::mock(Connection::class);
33+
$connection->shouldReceive('escape')->with('foo', false)->andReturn("'foo'");
34+
$grammar = new PostgresGrammar();
35+
36+
$bindings = array_map(fn ($value) => $connection->escape($value, false), ['foo']);
37+
38+
$query = $grammar->substituteBindingsIntoRawSql(
39+
'select * from "users" where \'{}\' ?? \'Hello\\\'\\\'World?\' AND "email" = ?',
40+
$bindings,
41+
);
42+
43+
$this->assertSame('select * from "users" where \'{}\' ? \'Hello\\\'\\\'World?\' AND "email" = \'foo\'', $query);
44+
}
45+
}

0 commit comments

Comments
 (0)