Skip to content

Commit dd4ebfd

Browse files
committed
fix: cast Postgre batch subquery values so updateBatch() and deleteBatch() accept mixed PHP types
1 parent 99c3f24 commit dd4ebfd

5 files changed

Lines changed: 263 additions & 11 deletions

File tree

‎system/Database/Postgre/Builder.php‎

Lines changed: 35 additions & 11 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,11 +447,15 @@ private function getFieldType(string $table, string $fieldName): ?string
437447
foreach ($this->db->getFieldData($table) as $field) {
438448
$type = $field->type;
439449

440-
// If `character` (or `char`) lacks a specifier, it is equivalent
441-
// to `character(1)`.
442-
// See https://www.postgresql.org/docs/current/datatype-character.html
443-
if ($field->type === 'character') {
444-
$type = $field->type . '(' . $field->max_length . ')';
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+
455+
// `character` without a length is `character(1)` and `character(n)` truncates on cast,
456+
// while `bpchar` keeps the full value.
457+
if ($type === 'character') {
458+
$type = 'bpchar';
445459
}
446460

447461
$this->QBOptions['fieldTypes'][$table][$field->name] = $type;
@@ -613,14 +627,24 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
613627
if (isset($this->QBOptions['setQueryAsData'])) {
614628
$data = $this->QBOptions['setQueryAsData'];
615629
} else {
630+
$constraints = $this->QBOptions['constraints'] ?? [];
631+
616632
$data = implode(
617633
" UNION ALL\n",
618634
array_map(
619-
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
620-
static fn ($key, $index): string => $index . ' ' . $key,
635+
fn (array $value): string => sprintf('SELECT %s', implode(', ', array_map(
636+
function (string $key, float|int|string $index) use ($table, $constraints): string {
637+
$column = array_search($key, $constraints, true);
638+
639+
return sprintf(
640+
'%s %s',
641+
$this->cast((string) $index, $this->getFieldType($table, is_string($column) ? $column : $key)),
642+
$key,
643+
);
644+
},
621645
$keys,
622646
$value,
623-
)),
647+
))),
624648
$values,
625649
),
626650
) . "\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: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,81 @@ 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+
162+
public function testDeleteBatchDoesNotTruncateConstraintValueForCharColumn(): void
163+
{
164+
if ($this->db->DBDriver === 'OCI8') {
165+
$this->markTestSkipped('TODO: Oracle resolves a `UNION ALL` of `CHAR` literals with different lengths to `VARCHAR2`, so the OCI8 builder must cast them. Remove this skip once it does.');
166+
}
167+
168+
$table = 'type_test';
169+
170+
$builder = $this->db->table($table);
171+
$builder->truncate();
172+
173+
for ($i = 0; $i < 2; $i++) {
174+
$builder->insert([
175+
'type_varchar' => 'test' . $i,
176+
'type_char' => 'char' . $i,
177+
'type_text' => 'text',
178+
'type_smallint' => 32767,
179+
'type_integer' => 2_147_483_647,
180+
'type_bigint' => 9_223_372_036_854_775_807,
181+
'type_float' => 10.1,
182+
'type_numeric' => 123.23,
183+
'type_date' => '2023-12-0' . ($i + 1),
184+
'type_datetime' => '2023-12-21 12:00:00',
185+
]);
186+
}
187+
188+
$this->db->table($table)
189+
->setData([['char' => 'char0 X'], ['char' => 'char1']], null, 'data')
190+
->onConstraint(['type_char' => 'char'])
191+
->deleteBatch();
192+
193+
$this->seeInDatabase($table, ['type_varchar' => 'test0']);
194+
$this->dontSeeInDatabase($table, ['type_varchar' => 'test1']);
195+
}
196+
122197
public function testDeleteBatchConstraintsDate(): void
123198
{
124199
$table = 'type_test';

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,123 @@ 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 testUpdateBatchDoesNotTruncateConstraintValueForCharColumn(): void
321+
{
322+
if ($this->db->DBDriver === 'OCI8') {
323+
$this->markTestSkipped('TODO: Oracle resolves a `UNION ALL` of `CHAR` literals with different lengths to `VARCHAR2`, so the OCI8 builder must cast them. Remove this skip once it does.');
324+
}
325+
326+
$table = 'type_test';
327+
328+
$builder = $this->db->table($table);
329+
$builder->truncate();
330+
331+
for ($i = 1; $i < 3; $i++) {
332+
$builder->insert([
333+
'type_varchar' => 'test' . $i,
334+
'type_char' => 'char' . $i,
335+
'type_text' => 'text',
336+
'type_smallint' => 32767,
337+
'type_integer' => 2_147_483_647,
338+
'type_bigint' => 9_223_372_036_854_775_807,
339+
'type_float' => 10.1,
340+
'type_numeric' => 123.23,
341+
'type_date' => '2023-12-0' . $i,
342+
'type_datetime' => '2023-12-21 12:00:00',
343+
]);
344+
}
345+
346+
$this->db->table($table)->updateBatch([
347+
['type_char' => 'char1 X', 'type_text' => 'changed'],
348+
['type_char' => 'char2', 'type_text' => 'changed'],
349+
], 'type_char');
350+
351+
$this->seeInDatabase($table, ['type_varchar' => 'test1', 'type_text' => 'text']);
352+
$this->seeInDatabase($table, ['type_varchar' => 'test2', 'type_text' => 'changed']);
353+
}
354+
355+
public function testUpdateBatchWithMappedUpdateFieldsAndMixedValueTypes(): void
356+
{
357+
if ($this->db->DBDriver === 'SQLSRV') {
358+
$this->markTestSkipped('SQL Server cannot compare `text` columns with `=`.');
359+
}
360+
361+
if ($this->db->DBDriver === 'OCI8') {
362+
$this->markTestSkipped('TODO: the OCI8 builder does not cast mixed `UNION ALL` values yet. Remove this skip once it does.');
363+
}
364+
365+
$table = 'type_test';
366+
367+
$builder = $this->db->table($table);
368+
$builder->truncate();
369+
370+
for ($i = 1; $i < 3; $i++) {
371+
$builder->insert([
372+
'type_varchar' => 'test' . $i,
373+
'type_char' => 'char' . $i,
374+
'type_text' => 'text',
375+
'type_smallint' => 32767,
376+
'type_integer' => 2_147_483_647,
377+
'type_bigint' => 9_223_372_036_854_775_807,
378+
'type_float' => 10.1,
379+
'type_numeric' => 123.23,
380+
'type_date' => '2023-12-0' . $i,
381+
'type_datetime' => '2023-12-21 12:00:00',
382+
]);
383+
}
384+
385+
$this->db->table($table)
386+
->setData([
387+
['type_varchar' => 'test1', 'text' => 'Example'],
388+
['type_varchar' => 'test2', 'text' => 587],
389+
], null, 'data')
390+
->updateFields(['type_text' => 'text'])
391+
->onConstraint('type_varchar')
392+
->updateBatch();
393+
394+
$this->seeInDatabase($table, ['type_varchar' => 'test1', 'type_text' => 'Example']);
395+
$this->seeInDatabase($table, ['type_varchar' => 'test2', 'type_text' => '587']);
396+
}
397+
281398
public function testUpdateWithWhereSameColumn(): void
282399
{
283400
$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)