Skip to content

Commit 4d1d361

Browse files
authored
Merge pull request #8786 from ping-yee/240414_sqlsrv
fix: [SQLSRV] Query Builder always sets "<database>"."<schema>". to the table name.
2 parents f2aaa69 + 4ac35c0 commit 4d1d361

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

system/Database/SQLSRV/Builder.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,23 @@ private function getFullName(string $table): string
297297
}
298298

299299
if ($this->db->escapeChar === '"') {
300+
if (str_contains($table, '.') && ! str_starts_with($table, '.') && ! str_ends_with($table, '.')) {
301+
$dbInfo = explode('.', $table);
302+
$database = $this->db->getDatabase();
303+
$table = $dbInfo[0];
304+
305+
if (count($dbInfo) === 3) {
306+
$database = str_replace('"', '', $dbInfo[0]);
307+
$schema = str_replace('"', '', $dbInfo[1]);
308+
$tableName = str_replace('"', '', $dbInfo[2]);
309+
} else {
310+
$schema = str_replace('"', '', $dbInfo[0]);
311+
$tableName = str_replace('"', '', $dbInfo[1]);
312+
}
313+
314+
return '"' . $database . '"."' . $schema . '"."' . str_replace('"', '', $tableName) . '"' . $alias;
315+
}
316+
300317
return '"' . $this->db->getDatabase() . '"."' . $this->db->schema . '"."' . str_replace('"', '', $table) . '"' . $alias;
301318
}
302319

tests/system/Database/Builder/FromTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,32 @@ public function testFromSubqueryWithSQLSRV(): void
153153

154154
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
155155
}
156+
157+
/**
158+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8697
159+
*/
160+
public function testConstructorWithMultipleSegmentTableWithSQLSRV(): void
161+
{
162+
$this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']);
163+
164+
$builder = new SQLSRVBuilder('database.dbo.table', $this->db);
165+
166+
$expectedSQL = 'SELECT * FROM "database"."dbo"."table"';
167+
168+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
169+
}
170+
171+
/**
172+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8697
173+
*/
174+
public function testConstructorWithMultipleSegmentTableWithoutDatabaseWithSQLSRV(): void
175+
{
176+
$this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']);
177+
178+
$builder = new SQLSRVBuilder('dbo.table', $this->db);
179+
180+
$expectedSQL = 'SELECT * FROM "test"."dbo"."table"';
181+
182+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
183+
}
156184
}

0 commit comments

Comments
 (0)