Skip to content

Commit 885e57b

Browse files
authored
Merge branch 'develop' into fix/sqlsrv-builder-upsert-batch-escape
2 parents 14efc34 + 451d539 commit 885e57b

7 files changed

Lines changed: 263 additions & 10 deletions

File tree

‎.github/scripts/run-random-tests.sh‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,10 @@ cleanup_finished_pids() {
665665
active+=("$pid")
666666
fi
667667
done
668-
bg_pids=("${active[@]:-}")
668+
bg_pids=()
669+
if [[ ${#active[@]} -gt 0 ]]; then
670+
bg_pids=("${active[@]}")
671+
fi
669672
}
670673

671674
spawn_limited_job() {

‎composer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
"phpunit/phpcov": "^9.0.2 || ^10.0",
3030
"phpunit/phpunit": "^10.5.16 || ^11.2",
3131
"predis/predis": "^3.0",
32-
"rector/rector": "2.8.3",
32+
"rector/rector": "2.8.4",
3333
"shipmonk/phpstan-baseline-per-identifier": "^2.0"
3434
},
3535
"replace": {

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Release Date: Unreleased
1818

1919
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
2020
- **Database:** Fixed a bug where `SQLSRV\Builder::_upsertBatch()` concatenated `$table` unescaped into `Object_ID()`, causing syntax errors for table names with quotes or special characters.
21+
- **Database:** Fixed a bug where `SQLSRV\Forge::_alterTable()` interpolated table and column names without escaping in default constraint lookups.
2122
- **HTTP:** Fixed a bug where `UploadedFile::move()` and `UploadedFile::store()` on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Filenames ending in a period or space or containing a colon are now rejected, including explicitly supplied names.
2223
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
2324
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.

‎system/Database/OCI8/Result.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public function getFieldNames(): array
3636

3737
public function getFieldData(): array
3838
{
39-
return array_map(fn ($fieldIndex) => (object) [
39+
return array_map(fn ($fieldIndex): stdClass => (object) [
4040
'name' => oci_field_name($this->resultID, $fieldIndex),
4141
'type' => oci_field_type($this->resultID, $fieldIndex),
4242
'max_length' => oci_field_size($this->resultID, $fieldIndex),

‎system/Database/SQLSRV/Forge.php‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,18 @@ protected function _alterTable(string $alterType, string $table, $processedField
195195
}
196196
}
197197

198-
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
198+
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
199+
$escapedFullTable = $this->db->escape($fullTable);
199200

200201
// Drop default constraints
201202
$fields = implode(',', $this->db->escape((array) $columnNamesToDrop));
202203

203204
$sql = <<<SQL
204205
SELECT name
205206
FROM sys.default_constraints
206-
WHERE parent_object_id = OBJECT_ID('{$fullTable}')
207+
WHERE parent_object_id = OBJECT_ID(N{$escapedFullTable})
207208
AND parent_column_id IN (
208-
SELECT column_id FROM sys.columns WHERE name IN ({$fields}) AND object_id = OBJECT_ID(N'{$fullTable}')
209+
SELECT column_id FROM sys.columns WHERE name IN ({$fields}) AND object_id = OBJECT_ID(N{$escapedFullTable})
209210
)
210211
SQL;
211212

@@ -244,8 +245,9 @@ protected function _alterTable(string $alterType, string $table, $processedField
244245
}
245246

246247
if (($field['default'] ?? '') !== '') {
247-
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
248-
$colName = $field['name']; // bare, for sys.columns lookup
248+
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
249+
$escapedFullTable = $this->db->escape($fullTable);
250+
$escapedColName = $this->db->escape($field['name']);
249251

250252
// find the existing default constraint name for this column
251253
$findSql = <<<SQL
@@ -254,8 +256,8 @@ protected function _alterTable(string $alterType, string $table, $processedField
254256
JOIN sys.columns c
255257
ON dc.parent_object_id = c.object_id
256258
AND dc.parent_column_id = c.column_id
257-
WHERE dc.parent_object_id = OBJECT_ID(N'{$fullTable}')
258-
AND c.name = N'{$colName}';
259+
WHERE dc.parent_object_id = OBJECT_ID(N{$escapedFullTable})
260+
AND c.name = N{$escapedColName};
259261
SQL;
260262

261263
$toDrop = $this->db->query($findSql)->getRowArray();
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\AutoReview;
15+
16+
use FilesystemIterator;
17+
use PHPUnit\Framework\Attributes\CoversNothing;
18+
use PHPUnit\Framework\Attributes\DataProvider;
19+
use PHPUnit\Framework\Attributes\Group;
20+
use PHPUnit\Framework\TestCase;
21+
use RecursiveDirectoryIterator;
22+
use RecursiveIteratorIterator;
23+
24+
/**
25+
* @internal
26+
*/
27+
#[CoversNothing]
28+
#[Group('AutoReview')]
29+
final class RunRandomTestsTest extends TestCase
30+
{
31+
private string $project;
32+
private string $timeoutCommand;
33+
34+
protected function setUp(): void
35+
{
36+
parent::setUp();
37+
38+
if (is_windows()) {
39+
$this->markTestSkipped('The random test runner requires Bash and GNU coreutils.');
40+
}
41+
42+
exec('command -v timeout || command -v gtimeout', $output, $exitCode);
43+
44+
if ($exitCode !== 0) {
45+
$this->markTestSkipped('The random test runner test requires timeout or gtimeout.');
46+
}
47+
48+
$this->timeoutCommand = $output[0];
49+
$this->project = sys_get_temp_dir() . '/ci4-random-tests-' . bin2hex(random_bytes(4));
50+
51+
foreach (['.github/scripts', 'vendor/bin', 'tests/system/First', 'tests/system/Second'] as $directory) {
52+
mkdir($this->project . '/' . $directory, 0777, true);
53+
}
54+
55+
copy(ROOTPATH . '.github/scripts/run-random-tests.sh', $this->project . '/.github/scripts/run-random-tests.sh');
56+
file_put_contents($this->project . '/.github/scripts/random-tests-config.txt', "First\nSecond\n");
57+
file_put_contents($this->project . '/vendor/bin/phpunit', <<<'BASH'
58+
#!/usr/bin/env bash
59+
printf '%s\n' "$1" >> calls.log
60+
sleep 0.05
61+
62+
BASH);
63+
chmod($this->project . '/vendor/bin/phpunit', 0755);
64+
}
65+
66+
protected function tearDown(): void
67+
{
68+
if (isset($this->project)) {
69+
$files = new RecursiveIteratorIterator(
70+
new RecursiveDirectoryIterator($this->project, FilesystemIterator::SKIP_DOTS),
71+
RecursiveIteratorIterator::CHILD_FIRST,
72+
);
73+
74+
foreach ($files as $file) {
75+
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
76+
}
77+
78+
rmdir($this->project);
79+
}
80+
81+
parent::tearDown();
82+
}
83+
84+
#[DataProvider('provideRunsEveryComponentOnEachRepetition')]
85+
public function testRunsEveryComponentOnEachRepetition(int $maxJobs): void
86+
{
87+
// Bound the command so a scheduler regression fails instead of hanging PHPUnit.
88+
exec(sprintf(
89+
'%s --kill-after=1s 5s bash %s --max-jobs %d --repeat 2 --timeout 0 2>&1',
90+
escapeshellarg($this->timeoutCommand),
91+
escapeshellarg($this->project . '/.github/scripts/run-random-tests.sh'),
92+
$maxJobs,
93+
), $output, $exitCode);
94+
$output = implode("\n", $output);
95+
96+
$this->assertSame(0, $exitCode, $output);
97+
$this->assertStringContainsString('All components passed random execution tests!', $output);
98+
99+
$calls = file($this->project . '/calls.log', FILE_IGNORE_NEW_LINES);
100+
101+
$this->assertIsArray($calls);
102+
$this->assertCount(4, $calls);
103+
104+
foreach (['First', 'Second'] as $component) {
105+
$this->assertCount(2, array_keys($calls, 'tests/system/' . $component, true));
106+
}
107+
}
108+
109+
/**
110+
* @return iterable<string, array{int}>
111+
*/
112+
public static function provideRunsEveryComponentOnEachRepetition(): iterable
113+
{
114+
yield 'one job' => [1];
115+
116+
yield 'two jobs' => [2];
117+
}
118+
}
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database\Forge;
15+
16+
use CodeIgniter\Database\ResultInterface;
17+
use CodeIgniter\Database\SQLSRV\Connection;
18+
use CodeIgniter\Database\SQLSRV\Forge;
19+
use CodeIgniter\Database\SQLSRV\Result;
20+
use CodeIgniter\Test\CIUnitTestCase;
21+
use PHPUnit\Framework\Attributes\Group;
22+
23+
/**
24+
* @internal
25+
*/
26+
#[Group('Others')]
27+
final class SQLSRVForgeTest extends CIUnitTestCase
28+
{
29+
public function testModifyColumnEscapesTableNameAndColumnNameInDefaultConstraintLookup(): void
30+
{
31+
$db = new class () extends Connection {
32+
/**
33+
* @var list<string>
34+
*/
35+
public array $queries = [];
36+
37+
public function __construct()
38+
{
39+
$this->DBDriver = 'SQLSRV';
40+
$this->schema = 'dbo';
41+
$this->escapeChar = ['[', ']'];
42+
$this->connID = false;
43+
$this->pretend = true;
44+
}
45+
46+
public function initialize(): void
47+
{
48+
}
49+
50+
/**
51+
* @param array<array-key, mixed>|string|null $binds
52+
*/
53+
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = ''): ResultInterface
54+
{
55+
$this->queries[] = $sql;
56+
57+
return new class ($this->connID, $this->resultID) extends Result {
58+
public function getRowArray(int $n = 0): array
59+
{
60+
return ['constraint_name' => 'df_test'];
61+
}
62+
};
63+
}
64+
};
65+
66+
$forge = new Forge($db);
67+
68+
$forge->modifyColumn("user's", [
69+
"col'name" => [
70+
'type' => 'VARCHAR',
71+
'default' => "'default_val'",
72+
],
73+
]);
74+
75+
$this->assertNotEmpty($db->queries);
76+
$findSql = $db->queries[0];
77+
78+
$this->assertStringContainsString("OBJECT_ID(N'[dbo].[user''s]')", $findSql);
79+
$this->assertStringContainsString("c.name = N'col''name'", $findSql);
80+
}
81+
82+
public function testDropColumnEscapesTableNameInDefaultConstraintLookup(): void
83+
{
84+
$db = new class () extends Connection {
85+
/**
86+
* @var list<string>
87+
*/
88+
public array $queries = [];
89+
90+
public function __construct()
91+
{
92+
$this->DBDriver = 'SQLSRV';
93+
$this->schema = 'dbo';
94+
$this->escapeChar = ['[', ']'];
95+
$this->connID = false;
96+
$this->pretend = true;
97+
}
98+
99+
public function initialize(): void
100+
{
101+
}
102+
103+
/**
104+
* @param array<array-key, mixed>|string|null $binds
105+
*/
106+
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = ''): ResultInterface
107+
{
108+
$this->queries[] = $sql;
109+
110+
return new class ($this->connID, $this->resultID) extends Result {
111+
public function getResultArray(): array
112+
{
113+
return [];
114+
}
115+
};
116+
}
117+
};
118+
119+
$forge = new Forge($db);
120+
121+
$forge->dropColumn("user's", "col'name");
122+
123+
$this->assertCount(3, $db->queries);
124+
$dropDefaultSql = $db->queries[1];
125+
126+
$this->assertStringContainsString("parent_object_id = OBJECT_ID(N'[dbo].[user''s]')", $dropDefaultSql);
127+
$this->assertStringContainsString("object_id = OBJECT_ID(N'[dbo].[user''s]')", $dropDefaultSql);
128+
}
129+
}

0 commit comments

Comments
 (0)