Skip to content

Commit 4bc33aa

Browse files
committed
fix: cast Postgre batch subquery values so updateBatch() and deleteBatch() accept mixed PHP types
1 parent 092c8f3 commit 4bc33aa

5 files changed

Lines changed: 189 additions & 6 deletions

File tree

‎system/Database/Postgre/Builder.php‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -395,14 +395,24 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
395395
if (isset($this->QBOptions['setQueryAsData'])) {
396396
$data = $this->QBOptions['setQueryAsData'];
397397
} else {
398+
$updateFields = $this->QBOptions['updateFields'] ?? [];
399+
398400
$data = implode(
399401
" UNION ALL\n",
400402
array_map(
401-
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
402-
static fn ($key, $index): string => $index . ' ' . $key,
403+
fn (array $value): string => sprintf('SELECT %s', implode(', ', array_map(
404+
function (string $key, float|int|string $index) use ($table, $updateFields): string {
405+
$column = array_search($key, $updateFields, true);
406+
407+
return sprintf(
408+
'%s %s',
409+
$this->cast((string) $index, $this->getFieldType($table, is_string($column) ? $column : $key)),
410+
$key,
411+
);
412+
},
403413
$keys,
404414
$value,
405-
)),
415+
))),
406416
$values,
407417
),
408418
) . "\n";
@@ -437,6 +447,11 @@ private function getFieldType(string $table, string $fieldName): ?string
437447
foreach ($this->db->getFieldData($table) as $field) {
438448
$type = $field->type;
439449

450+
// information_schema reports enum, domain and array columns as `USER-DEFINED` or `ARRAY`, which are not castable names.
451+
if ($type === 'USER-DEFINED' || $type === 'ARRAY') {
452+
continue;
453+
}
454+
440455
// If `character` (or `char`) lacks a specifier, it is equivalent
441456
// to `character(1)`.
442457
// See https://www.postgresql.org/docs/current/datatype-character.html
@@ -613,14 +628,24 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
613628
if (isset($this->QBOptions['setQueryAsData'])) {
614629
$data = $this->QBOptions['setQueryAsData'];
615630
} else {
631+
$constraints = $this->QBOptions['constraints'] ?? [];
632+
616633
$data = implode(
617634
" UNION ALL\n",
618635
array_map(
619-
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
620-
static fn ($key, $index): string => $index . ' ' . $key,
636+
fn (array $value): string => sprintf('SELECT %s', implode(', ', array_map(
637+
function (string $key, float|int|string $index) use ($table, $constraints): string {
638+
$column = array_search($key, $constraints, true);
639+
640+
return sprintf(
641+
'%s %s',
642+
$this->cast((string) $index, $this->getFieldType($table, is_string($column) ? $column : $key)),
643+
$key,
644+
);
645+
},
621646
$keys,
622647
$value,
623-
)),
648+
))),
624649
$values,
625650
),
626651
) . "\n";

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\Database\BaseBuilder;
1717
use CodeIgniter\Database\Exceptions\DatabaseException;
18+
use CodeIgniter\Database\Postgre\Builder as PostgreBuilder;
1819
use CodeIgniter\Test\CIUnitTestCase;
1920
use CodeIgniter\Test\Mock\MockConnection;
2021
use CodeIgniter\Test\Mock\MockQuery;
@@ -469,4 +470,38 @@ public function testSetWithAndWithoutEscape(): void
469470
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledUpdate()));
470471
$this->assertSame($expectedBinds, $builder->getBinds());
471472
}
473+
474+
public function testUpdateBatchPostgreDoesNotCastEnumAndArrayColumns(): void
475+
{
476+
$db = new class (['DBDriver' => 'Postgre']) extends MockConnection {
477+
protected function _fieldData(string $table): array
478+
{
479+
return [
480+
(object) ['name' => 'id', 'type' => 'integer', 'max_length' => 32],
481+
(object) ['name' => 'mood', 'type' => 'USER-DEFINED', 'max_length' => null],
482+
(object) ['name' => 'tags', 'type' => 'ARRAY', 'max_length' => null],
483+
];
484+
}
485+
};
486+
487+
$builder = new PostgreBuilder('jobs', $db);
488+
$sql = $builder->testMode()->updateBatch([
489+
['id' => 1, 'mood' => 'happy', 'tags' => '{a}'],
490+
['id' => 2, 'mood' => 'sad', 'tags' => '{b}'],
491+
], 'id');
492+
493+
$expected = <<<'EOF'
494+
UPDATE "jobs"
495+
SET
496+
"mood" = _u."mood",
497+
"tags" = _u."tags"
498+
FROM (
499+
SELECT CAST(1 AS INTEGER) "id", 'happy' "mood", '{a}' "tags" UNION ALL
500+
SELECT CAST(2 AS INTEGER) "id", 'sad' "mood", '{b}' "tags"
501+
) _u
502+
WHERE "jobs"."id" = CAST(_u."id" AS INTEGER)
503+
EOF;
504+
505+
$this->assertSame([$expected], $sql);
506+
}
472507
}

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,46 @@ public function testDeleteBatchPreventsSQLInjectionInWhere(): void
119119
$this->seeInDatabase('user', ['email' => 'derek@world.com', 'name' => 'Derek Jones']);
120120
}
121121

122+
public function testDeleteBatchWithMixedConstraintValueTypesInTextColumn(): void
123+
{
124+
if ($this->db->DBDriver === 'SQLSRV') {
125+
$this->markTestSkipped('SQL Server cannot compare `text` columns with `=`.');
126+
}
127+
128+
if ($this->db->DBDriver === 'OCI8') {
129+
$this->markTestSkipped('TODO: the OCI8 builder does not cast mixed `UNION ALL` values yet. Remove this skip once it does.');
130+
}
131+
132+
$table = 'type_test';
133+
134+
$builder = $this->db->table($table);
135+
$builder->truncate();
136+
137+
foreach (['Example', '587', 'kept'] as $i => $text) {
138+
$builder->insert([
139+
'type_varchar' => 'test' . $i,
140+
'type_char' => 'char',
141+
'type_text' => $text,
142+
'type_smallint' => 32767,
143+
'type_integer' => 2_147_483_647,
144+
'type_bigint' => 9_223_372_036_854_775_807,
145+
'type_float' => 10.1,
146+
'type_numeric' => 123.23,
147+
'type_date' => '2023-12-0' . ($i + 1),
148+
'type_datetime' => '2023-12-21 12:00:00',
149+
]);
150+
}
151+
152+
$this->db->table($table)
153+
->setData([['text' => 'Example'], ['text' => 587]], null, 'data')
154+
->onConstraint(['type_text' => 'text'])
155+
->deleteBatch();
156+
157+
$this->dontSeeInDatabase($table, ['type_varchar' => 'test0']);
158+
$this->dontSeeInDatabase($table, ['type_varchar' => 'test1']);
159+
$this->seeInDatabase($table, ['type_varchar' => 'test2']);
160+
}
161+
122162
public function testDeleteBatchConstraintsDate(): void
123163
{
124164
$table = 'type_test';

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

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,88 @@ public static function provideUpdateBatch(): iterable
278278
];
279279
}
280280

281+
public function testUpdateBatchWithMixedValueTypesInTextColumn(): void
282+
{
283+
if ($this->db->DBDriver === 'SQLSRV') {
284+
$this->markTestSkipped('SQL Server cannot compare `text` columns with `=`.');
285+
}
286+
287+
if ($this->db->DBDriver === 'OCI8') {
288+
$this->markTestSkipped('TODO: the OCI8 builder does not cast mixed `UNION ALL` values yet. Remove this skip once it does.');
289+
}
290+
291+
$table = 'type_test';
292+
293+
$builder = $this->db->table($table);
294+
$builder->truncate();
295+
296+
for ($i = 1; $i < 3; $i++) {
297+
$builder->insert([
298+
'type_varchar' => 'test' . $i,
299+
'type_char' => 'char' . $i,
300+
'type_text' => 'text',
301+
'type_smallint' => 32767,
302+
'type_integer' => 2_147_483_647,
303+
'type_bigint' => 9_223_372_036_854_775_807,
304+
'type_float' => 10.1,
305+
'type_numeric' => 123.23,
306+
'type_date' => '2023-12-0' . $i,
307+
'type_datetime' => '2023-12-21 12:00:00',
308+
]);
309+
}
310+
311+
$this->db->table($table)->updateBatch([
312+
['type_varchar' => 'test1', 'type_text' => 'Example'],
313+
['type_varchar' => 'test2', 'type_text' => 587],
314+
], 'type_varchar');
315+
316+
$this->seeInDatabase($table, ['type_varchar' => 'test1', 'type_text' => 'Example']);
317+
$this->seeInDatabase($table, ['type_varchar' => 'test2', 'type_text' => '587']);
318+
}
319+
320+
public function testUpdateBatchWithMappedUpdateFieldsAndMixedValueTypes(): void
321+
{
322+
if ($this->db->DBDriver === 'SQLSRV') {
323+
$this->markTestSkipped('SQL Server cannot compare `text` columns with `=`.');
324+
}
325+
326+
if ($this->db->DBDriver === 'OCI8') {
327+
$this->markTestSkipped('TODO: the OCI8 builder does not cast mixed `UNION ALL` values yet. Remove this skip once it does.');
328+
}
329+
330+
$table = 'type_test';
331+
332+
$builder = $this->db->table($table);
333+
$builder->truncate();
334+
335+
for ($i = 1; $i < 3; $i++) {
336+
$builder->insert([
337+
'type_varchar' => 'test' . $i,
338+
'type_char' => 'char' . $i,
339+
'type_text' => 'text',
340+
'type_smallint' => 32767,
341+
'type_integer' => 2_147_483_647,
342+
'type_bigint' => 9_223_372_036_854_775_807,
343+
'type_float' => 10.1,
344+
'type_numeric' => 123.23,
345+
'type_date' => '2023-12-0' . $i,
346+
'type_datetime' => '2023-12-21 12:00:00',
347+
]);
348+
}
349+
350+
$this->db->table($table)
351+
->setData([
352+
['type_varchar' => 'test1', 'text' => 'Example'],
353+
['type_varchar' => 'test2', 'text' => 587],
354+
], null, 'data')
355+
->updateFields(['type_text' => 'text'])
356+
->onConstraint('type_varchar')
357+
->updateBatch();
358+
359+
$this->seeInDatabase($table, ['type_varchar' => 'test1', 'type_text' => 'Example']);
360+
$this->seeInDatabase($table, ['type_varchar' => 'test2', 'type_text' => '587']);
361+
}
362+
281363
public function testUpdateWithWhereSameColumn(): void
282364
{
283365
$this->db->table('user')->update(['country' => 'CA'], ['country' => 'US']);

‎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 ``updateBatch()`` and ``deleteBatch()`` failed on PostgreSQL when the rows supplied different PHP types (e.g., a string and an integer) for the same column, because the ``UNION ALL`` subquery values were not cast to the column type.
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)