Skip to content

Commit

Permalink
Merge pull request #8786 from ping-yee/240414_sqlsrv
Browse files Browse the repository at this point in the history
fix: [SQLSRV] Query Builder always sets "<database>"."<schema>". to the table name.
  • Loading branch information
kenjis authored May 2, 2024
2 parents f2aaa69 + 4ac35c0 commit 4d1d361
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions system/Database/SQLSRV/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,23 @@ private function getFullName(string $table): string
}

if ($this->db->escapeChar === '"') {
if (str_contains($table, '.') && ! str_starts_with($table, '.') && ! str_ends_with($table, '.')) {
$dbInfo = explode('.', $table);
$database = $this->db->getDatabase();
$table = $dbInfo[0];

if (count($dbInfo) === 3) {
$database = str_replace('"', '', $dbInfo[0]);
$schema = str_replace('"', '', $dbInfo[1]);
$tableName = str_replace('"', '', $dbInfo[2]);
} else {
$schema = str_replace('"', '', $dbInfo[0]);
$tableName = str_replace('"', '', $dbInfo[1]);
}

return '"' . $database . '"."' . $schema . '"."' . str_replace('"', '', $tableName) . '"' . $alias;
}

return '"' . $this->db->getDatabase() . '"."' . $this->db->schema . '"."' . str_replace('"', '', $table) . '"' . $alias;
}

Expand Down
28 changes: 28 additions & 0 deletions tests/system/Database/Builder/FromTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,32 @@ public function testFromSubqueryWithSQLSRV(): void

$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8697
*/
public function testConstructorWithMultipleSegmentTableWithSQLSRV(): void
{
$this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']);

$builder = new SQLSRVBuilder('database.dbo.table', $this->db);

$expectedSQL = 'SELECT * FROM "database"."dbo"."table"';

$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8697
*/
public function testConstructorWithMultipleSegmentTableWithoutDatabaseWithSQLSRV(): void
{
$this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']);

$builder = new SQLSRVBuilder('dbo.table', $this->db);

$expectedSQL = 'SELECT * FROM "test"."dbo"."table"';

$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}
}

0 comments on commit 4d1d361

Please sign in to comment.