Skip to content

Commit 42c34dd

Browse files
committed
Avoid building a field multiple times if clause has synonyms.
1 parent cd62cf6 commit 42c34dd

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/Statement.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,20 @@ public function build()
108108
*/
109109
$query = '';
110110

111+
/**
112+
* Clauses which were built already.
113+
*
114+
* It is required to keep track of built clauses because some fields,
115+
* for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
116+
* `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
117+
*
118+
* A clause is considered built just after fields' value
119+
* (`$this->field`) was used in building.
120+
*
121+
* @var array
122+
*/
123+
$built = array();
124+
111125
foreach (static::$CLAUSES as $clause) {
112126
/**
113127
* The name of the clause.
@@ -144,6 +158,15 @@ public function build()
144158
continue;
145159
}
146160

161+
// Checking if this field was already built.
162+
if ($type & 1) {
163+
if (!empty($built[$field])) {
164+
continue;
165+
}
166+
167+
$built[$field] = true;
168+
}
169+
147170
// Checking if the name of the clause should be added.
148171
if ($type & 2) {
149172
$query .= $name . ' ';

tests/Builder/SelectStatementTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace SqlParser\Tests\Builder;
4+
5+
use SqlParser\Parser;
6+
7+
use SqlParser\Tests\TestCase;
8+
9+
class SelectStatementTest extends TestCase
10+
{
11+
12+
public function testBuilder()
13+
{
14+
$query = 'SELECT * FROM t1 LEFT JOIN (t2, t3, t4) '
15+
. 'ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)';
16+
17+
$parser = new Parser($query);
18+
$stmt = $parser->statements[0];
19+
20+
$this->assertEquals(
21+
'SELECT * FROM t1 LEFT JOIN (t2, t3, t4) '
22+
. 'ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c) ',
23+
$stmt->build()
24+
);
25+
}
26+
}

0 commit comments

Comments
 (0)