Database: Fix degenerate parenthesized joins
authorBrad Jorsch <bjorsch@wikimedia.org>
Wed, 29 Nov 2017 20:42:27 +0000 (15:42 -0500)
committerBrad Jorsch <bjorsch@wikimedia.org>
Wed, 29 Nov 2017 20:42:27 +0000 (15:42 -0500)
The SQL standard supports parenthesized joins like

    a JOIN (b JOIN c ON (...)) ON (...)

But it doesn't support parenthesizing a single table name, i.e. a
one-table "join", like

    a JOIN (b) ON (...)

Detect the degenerate single-table case and omit the parentheses.

Bug: T181674
Change-Id: I82cacd80465092aa67ff19bdcfd6682001bf12ab

includes/libs/rdbms/database/Database.php
tests/phpunit/includes/libs/rdbms/database/DatabaseTest.php

index e04566e..b936779 100644 (file)
@@ -2019,9 +2019,19 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
 
                        if ( is_array( $table ) ) {
                                // A parenthesized group
-                               $joinedTable = '('
-                                       . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
-                                       . ')';
+                               if ( count( $table ) > 1 ) {
+                                       $joinedTable = '('
+                                               . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
+                                               . ')';
+                               } else {
+                                       // Degenerate case
+                                       $innerTable = reset( $table );
+                                       $innerAlias = key( $table );
+                                       $joinedTable = $this->tableNameWithAlias(
+                                               $innerTable,
+                                               is_string( $innerAlias ) ? $innerAlias : $innerTable
+                                       );
+                               }
                        } else {
                                $joinedTable = $this->tableNameWithAlias( $table, $alias );
                        }
index ee7ad2f..7933f19 100644 (file)
@@ -120,6 +120,13 @@ class DatabaseTest extends PHPUnit_Framework_TestCase {
                                ],
                                'table1 LEFT JOIN (table2 JOIN table3 ON ((t2_id = t3_id))) ON ((t1_id = t2_id))'
                        ],
+                       'join with degenerate parenthesized group' => [
+                               [ 'table1', 'n' => [ 't2' => 'table2' ] ],
+                               [
+                                       'n' => [ 'LEFT JOIN', 't1_id = t2_id' ],
+                               ],
+                               'table1 LEFT JOIN table2 t2 ON ((t1_id = t2_id))'
+                       ],
                ];
        }