From 42c34ddd1fee261da43331e855c80bc432d66247 Mon Sep 17 00:00:00 2001 From: Dan Ungureanu Date: Sat, 10 Oct 2015 15:37:25 +0300 Subject: [PATCH] Avoid building a field multiple times if clause has synonyms. --- src/Statement.php | 23 +++++++++++++++++++++++ tests/Builder/SelectStatementTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 tests/Builder/SelectStatementTest.php diff --git a/src/Statement.php b/src/Statement.php index 3fe3f42c1..b15dc3dac 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -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. @@ -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 . ' '; diff --git a/tests/Builder/SelectStatementTest.php b/tests/Builder/SelectStatementTest.php new file mode 100644 index 000000000..58e8dc61d --- /dev/null +++ b/tests/Builder/SelectStatementTest.php @@ -0,0 +1,26 @@ +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() + ); + } +}