Skip to content

Commit

Permalink
Avoid building a field multiple times if clause has synonyms.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan Ungureanu committed Oct 10, 2015
1 parent cd62cf6 commit 42c34dd
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,20 @@ public function build()
*/
$query = '';

/**
* Clauses which were built already.
*
* It is required to keep track of built clauses because some fields,
* for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
* `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
*
* A clause is considered built just after fields' value
* (`$this->field`) was used in building.
*
* @var array
*/
$built = array();

foreach (static::$CLAUSES as $clause) {
/**
* The name of the clause.
Expand Down Expand Up @@ -144,6 +158,15 @@ public function build()
continue;
}

// Checking if this field was already built.
if ($type & 1) {
if (!empty($built[$field])) {
continue;
}

$built[$field] = true;
}

// Checking if the name of the clause should be added.
if ($type & 2) {
$query .= $name . ' ';
Expand Down
26 changes: 26 additions & 0 deletions tests/Builder/SelectStatementTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace SqlParser\Tests\Builder;

use SqlParser\Parser;

use SqlParser\Tests\TestCase;

class SelectStatementTest extends TestCase
{

public function testBuilder()
{
$query = 'SELECT * FROM t1 LEFT JOIN (t2, t3, t4) '
. 'ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)';

$parser = new Parser($query);
$stmt = $parser->statements[0];

$this->assertEquals(
'SELECT * FROM t1 LEFT JOIN (t2, t3, t4) '
. 'ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c) ',
$stmt->build()
);
}
}

0 comments on commit 42c34dd

Please sign in to comment.