From edf547de2e08fe4f77f4e2d1cc6490b093138ca6 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Mon, 4 Nov 2024 19:07:55 +0100 Subject: [PATCH] Fix handling query with multiple subselect JOIN clauses (#341) --- src/Regex.php | 8 ++++++++ tests/Queries/SelectTest.php | 18 +++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Regex.php b/src/Regex.php index e24b0ca..d2643c0 100644 --- a/src/Regex.php +++ b/src/Regex.php @@ -126,6 +126,14 @@ public function sqlParameter(string $subject, &$matches = null) */ public function tableAlias(string $subject, &$matches = null) { + if ( + preg_match( + '/^\s*(\(.*\))\s+(?:AS\s+)?([' . self::SQLCHARS . ']+)\s+ON\s/uis', + $subject, + $matches + ) + ) + return 1; return preg_match( '/`?([' . self::SQLCHARS . ']+[.:]?[' . self::SQLCHARS . '*]*)`?(\s+AS)?(\s+`?([' . self::SQLCHARS . ']*)`?)?/ui', $subject, diff --git a/tests/Queries/SelectTest.php b/tests/Queries/SelectTest.php index ea22d69..5a6ebad 100644 --- a/tests/Queries/SelectTest.php +++ b/tests/Queries/SelectTest.php @@ -285,4 +285,20 @@ public function testFetchColumn() self::assertEquals(false, $statement); self::assertEquals(false, $statement2); } -} \ No newline at end of file + + public function testMulitpleSubselectJoinClauses(): void + { + $query = $this->fluent->from('user') + -> disableSmartJoin() + -> leftJoin( + "(SELECT user_id, count(*) AS count FROM comment GROUP BY user_id) comments ON user.id = comments.user_id" + ) + -> leftJoin( + "(SELECT user_id, count(*) AS count FROM article GROUP BY user_id) articles ON user.id = articles.user_id" + ) + ->select("comments.count AS total_comments") + ->select("articles.count AS total_articles"); + self::assertEquals('SELECT user.*, comments.count AS total_comments, articles.count AS total_articles FROM user LEFT JOIN (SELECT user_id, count(*) AS count FROM comment GROUP BY user_id) comments ON user.id = comments.user_id LEFT JOIN (SELECT user_id, count(*) AS count FROM article GROUP BY user_id) articles ON user.id = articles.user_id', + $query->getQuery(false)); + } +}