Skip to content

Commit 41970be

Browse files
committed
fix: track aliases in raw JOIN tables (#9070)
1 parent 642c492 commit 41970be

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3737,8 +3737,8 @@ protected function _delete(string $table): string
37373737
protected function trackAliases($table)
37383738
{
37393739
if ($table instanceof RawSql) {
3740-
if (preg_match('/\)\s+(?:AS\s+)?([a-z_][a-z0-9_]*)\s*$/i', (string) $table, $matches)) {
3741-
$this->db->addTableAlias($matches[1]);
3740+
if (preg_match('/(?:\)\s+|^[^\s()]+\s+)(?:AS\s+)?("[a-z_][a-z0-9_]*"|`[a-z_][a-z0-9_]*`|\[[a-z_][a-z0-9_]*\]|[a-z_][a-z0-9_]*)\s*$/i', (string) $table, $matches)) {
3741+
$this->db->addTableAlias(trim($matches[1], '"`[]'));
37423742
}
37433743

37443744
return null;

‎tests/system/Database/Builder/JoinTest.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,30 @@ public function testJoinRawSqlTableWithPrefix(): void
148148
$this->assertSameSql($expectedSQL, $builder->getCompiledSelect());
149149
}
150150

151+
public function testJoinRawSqlOrdinaryTableAliasWithPrefix(): void
152+
{
153+
$this->db = new MockConnection(['DBPrefix' => 'ci_']);
154+
$builder = new BaseBuilder('users', $this->db);
155+
156+
$builder->join(new RawSql('posts recent'), 'recent.user_id = users.id');
157+
158+
$expectedSQL = 'SELECT * FROM "ci_users" JOIN posts recent ON "recent"."user_id" = "ci_users"."id"';
159+
160+
$this->assertSameSql($expectedSQL, $builder->getCompiledSelect());
161+
}
162+
163+
public function testJoinRawSqlQuotedSubqueryAliasWithPrefix(): void
164+
{
165+
$this->db = new MockConnection(['DBPrefix' => 'ci_']);
166+
$builder = new BaseBuilder('users', $this->db);
167+
168+
$builder->join(new RawSql('(SELECT user_id FROM posts) AS "recent"'), 'recent.user_id = users.id');
169+
170+
$expectedSQL = 'SELECT * FROM "ci_users" JOIN (SELECT user_id FROM posts) AS "recent" ON "recent"."user_id" = "ci_users"."id"';
171+
172+
$this->assertSameSql($expectedSQL, $builder->getCompiledSelect());
173+
}
174+
151175
public function testPostgreJoinRawSqlTable(): void
152176
{
153177
$builder = new PostgreBuilder('users', $this->db);

0 commit comments

Comments
 (0)