Skip to content

Commit b86f337

Browse files
authored
fix: resolve schema-qualified table names in getFieldData() and protectIdentifiers() (#10604)
* fix: resolve schema-qualified table names in `getFieldData()` and `protectIdentifiers()` * address reviews
1 parent 99c3f24 commit b86f337

7 files changed

Lines changed: 84 additions & 5 deletions

File tree

‎system/Database/BaseConnection.php‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,7 +1315,7 @@ public function protectIdentifiers($item, bool $prefixSingle = false, ?bool $pro
13151315
// In some cases, especially 'from', we end up running through
13161316
// protect_identifiers twice. This algorithm won't work when
13171317
// it contains the escapeChar so strip it out.
1318-
$item = trim($item, $this->escapeChar);
1318+
$item = $this->trimEscapeChar($item);
13191319

13201320
// Is there a table prefix? If not, no need to insert it
13211321
if ($this->DBPrefix !== '') {
@@ -1336,9 +1336,15 @@ public function protectIdentifiers($item, bool $prefixSingle = false, ?bool $pro
13361336
return $item . $alias;
13371337
}
13381338

1339+
private function trimEscapeChar(string $item): string
1340+
{
1341+
return trim($item, is_array($this->escapeChar) ? implode('', $this->escapeChar) : $this->escapeChar);
1342+
}
1343+
13391344
private function protectDotItem(string $item, string $alias, bool $protectIdentifiers, bool $fieldExists): string
13401345
{
1341-
$parts = explode('.', $item);
1346+
$parts = array_map($this->trimEscapeChar(...), explode('.', $item));
1347+
$item = implode('.', $parts);
13421348

13431349
// Does the first segment of the exploded item match
13441350
// one of the aliases previously identified? If so,

‎system/Database/Postgre/Connection.php‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -325,11 +325,20 @@ protected function _listColumns($table = ''): string
325325
*/
326326
protected function _fieldData(string $table): array
327327
{
328+
$parts = explode('.', $table);
329+
$table = array_pop($parts);
330+
$schema = array_pop($parts);
331+
328332
$sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default", "is_nullable"
329333
FROM "information_schema"."columns"
330334
WHERE LOWER("table_name") = '
331-
. $this->escape(strtolower($table))
332-
. ' ORDER BY "ordinal_position"';
335+
. $this->escape(strtolower($table));
336+
337+
if ($schema !== null) {
338+
$sql .= ' AND LOWER("table_schema") = ' . $this->escape(strtolower($schema));
339+
}
340+
341+
$sql .= ' ORDER BY "ordinal_position"';
333342

334343
if (($query = $this->query($sql)) === false) {
335344
throw new DatabaseException(lang('Database.failGetFieldData'));

‎system/Database/SQLSRV/Connection.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,12 +314,20 @@ protected function _enableForeignKeyChecks()
314314
*/
315315
protected function _fieldData(string $table): array
316316
{
317+
$parts = explode('.', $table);
318+
$table = array_pop($parts);
319+
$schema = array_pop($parts);
320+
317321
$sql = 'SELECT
318322
COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION,
319323
COLUMN_DEFAULT, IS_NULLABLE
320324
FROM INFORMATION_SCHEMA.COLUMNS
321325
WHERE TABLE_NAME= ' . $this->escape(($table));
322326

327+
if ($schema !== null) {
328+
$sql .= ' AND TABLE_SCHEMA = ' . $this->escape($schema);
329+
}
330+
323331
if (($query = $this->query($sql)) === false) {
324332
throw new DatabaseException(lang('Database.failGetFieldData'));
325333
}

‎system/Database/SQLite3/Connection.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,12 @@ public function getFieldNames($tableName)
270270
*/
271271
protected function _fieldData(string $table): array
272272
{
273-
if (false === $query = $this->query('PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')')) {
273+
$parts = explode('.', $table);
274+
$table = array_pop($parts);
275+
$schema = array_pop($parts);
276+
$pragma = ($schema === null ? '' : $this->escapeIdentifiers($schema) . '.') . 'TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')';
277+
278+
if (false === $query = $this->query('PRAGMA ' . $pragma)) {
274279
throw new DatabaseException(lang('Database.failGetFieldData'));
275280
}
276281

‎tests/system/Database/BaseConnectionTest.php‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,11 @@ public static function provideProtectIdentifiers(): iterable
372372
'quoted table alias' => [false, true, false, '"jobs" "j"', '"jobs" "j"'],
373373
'quoted table alias prefix' => [true, true, false, '"jobs" "j"', '"test_jobs" "j"'],
374374

375+
'schema.table' => [false, true, false, 'tenant.jobs', '"tenant"."test_jobs"'],
376+
'schema.table prefix' => [true, true, false, 'tenant.jobs', '"tenant"."test_jobs"'],
377+
'quoted schema.table prefix' => [true, true, false, '"tenant"."test_jobs"', '"tenant"."test_jobs"'],
378+
'quoted schema.table no-protect' => [true, false, false, '"tenant"."test_jobs"', 'tenant.test_jobs'],
379+
375380
'table.*' => [false, true, true, 'jobs.*', '"test_jobs".*'], // Prefixed because it has segments
376381
'table.* prefix' => [true, true, true, 'jobs.*', '"test_jobs".*'],
377382
'table.column' => [false, true, true, 'users.id', '"test_users"."id"'], // Prefixed because it has segments
@@ -434,6 +439,27 @@ public static function provideProtectIdentifiers(): iterable
434439
];
435440
}
436441

442+
public function testProtectIdentifiersWithBracketEscapeChar(): void
443+
{
444+
$db = new MockConnection($this->options);
445+
$db->escapeChar = ['[', ']'];
446+
447+
$this->assertSame('[test_jobs]', $db->protectIdentifiers('jobs', true, true, false));
448+
$this->assertSame('[test_jobs]', $db->protectIdentifiers('[test_jobs]', true, true, false));
449+
$this->assertSame('test_jobs', $db->protectIdentifiers('[test_jobs]', true, false, false));
450+
$this->assertSame('[test_jobs].[id]', $db->protectIdentifiers('jobs.id'));
451+
$this->assertSame('[test_jobs].[id]', $db->protectIdentifiers('[test_jobs].[id]'));
452+
$this->assertSame('test_jobs.id', $db->protectIdentifiers('[test_jobs].[id]', true, false));
453+
}
454+
455+
public function testProtectIdentifiersStripsQuotesFromDottedItemWithoutPrefix(): void
456+
{
457+
$db = new MockConnection([...$this->options, 'DBPrefix' => '']);
458+
459+
$this->assertSame('public.jobs', $db->protectIdentifiers('"public"."jobs"', true, false, false));
460+
$this->assertSame('"public"."jobs"', $db->protectIdentifiers('"public"."jobs"', true, true, false));
461+
}
462+
437463
/**
438464
* These tests are intended to confirm the current behavior.
439465
*/

‎tests/system/Database/Live/AbstractGetFieldDataTestCase.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,30 @@ protected function tearDown(): void
5757
$this->forge->dropTable($this->table, true);
5858
}
5959

60+
protected function qualifiedTableName(): string
61+
{
62+
return match ($this->db->DBDriver) {
63+
'MySQLi' => $this->db->getDatabase() . '.' . $this->table,
64+
'OCI8' => $this->db->username . '.' . $this->table,
65+
'Postgre' => 'public.' . $this->table,
66+
'SQLite3' => 'main.' . $this->table,
67+
'SQLSRV' => 'dbo.' . $this->table,
68+
default => $this->markTestSkipped('No qualified table name is defined for ' . $this->db->DBDriver . '.'),
69+
};
70+
}
71+
72+
public function testGetFieldDataWithQualifiedTableName(): void
73+
{
74+
$this->createTableForDefault();
75+
76+
$toArray = static fn (stdClass $field): array => (array) $field;
77+
78+
$this->assertSame(
79+
array_map($toArray, $this->db->getFieldData($this->table)),
80+
array_map($toArray, $this->db->getFieldData($this->qualifiedTableName())),
81+
);
82+
}
83+
6084
protected function createTableForDefault(): void
6185
{
6286
$this->forge->dropTable($this->table, true);

‎user_guide_src/source/changelogs/v4.7.5.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ Bugs Fixed
5454
- **Cookie:** Fixed a bug where ``Cookie`` instances allowed invalid characters in path, domain, and prefix attributes rejected by ``setcookie()`` and ``setrawcookie()``.
5555
- **Database:** Fixed a bug where rebuilding a SQLite3 table (e.g., ``Forge::dropColumn()``, ``Forge::modifyColumn()``, ``Forge::dropForeignKey()`` and ``Forge::dropPrimaryKey()``) corrupted the table names referenced by its foreign keys when ``DBPrefix`` was set.
5656
- **Database:** Fixed a bug where Postgre query failures were silently ignored when ``DBDebug`` was enabled and PHP warnings were disabled. A ``DatabaseException`` is now thrown.
57+
- **Database:** Fixed a bug where ``getFieldData()`` failed for a schema-qualified table name on Postgre, SQLSRV and SQLite3, and where ``protectIdentifiers()`` prefixed an already protected segment of a dotted identifier a second time.
5758
- **Debug:** Fixed a bug where ``Timer::start()`` treated ``0.0`` as an empty value and substituted the current time.
5859
- **Files:** Fixed a bug where ``File::move()`` and ``UploadedFile::move()`` set executable and overly permissive file permissions (``0777 & ~umask()`` instead of ``0666 & ~umask()``), and ``UploadedFile::move()`` targeted the parent directory instead of the destination file for ``chmod()``.
5960
- **Helpers:** Fixed a bug where ``get_dir_file_info()`` returned incomplete entries for subdirectories and missing files instead of omitting them.

0 commit comments

Comments
 (0)