Skip to content

Commit 0a8e4d7

Browse files
committed
fix: cast Postgre batch subquery values so updateBatch() and deleteBatch() accept mixed PHP types
1 parent b86f337 commit 0a8e4d7

6 files changed

Lines changed: 401 additions & 11 deletions

File tree

‎system/Database/Postgre/Builder.php‎

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -395,14 +395,20 @@ 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+
fn (string $key, float|int|string $index): string => sprintf(
405+
'%s %s',
406+
$this->castValue((string) $index, $this->getSourceType($table, $key, $updateFields)),
407+
$key,
408+
),
403409
$keys,
404410
$value,
405-
)),
411+
))),
406412
$values,
407413
),
408414
) . "\n";
@@ -411,6 +417,38 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
411417
return str_replace('{:_table_:}', $data, $sql);
412418
}
413419

420+
/**
421+
* Returns the type shared by every destination column fed from the source key, or null when they differ.
422+
*
423+
* @param array<array-key, RawSql|string> $map Destination column to source key.
424+
*/
425+
private function getSourceType(string $table, string $key, array $map): ?string
426+
{
427+
$columns = array_filter(array_keys($map, $key, true), is_string(...));
428+
429+
if ($columns === []) {
430+
return $this->getFieldType($table, $key);
431+
}
432+
433+
$types = array_unique(array_map(fn (string $column): ?string => $this->getFieldType($table, $column), $columns));
434+
435+
return count($types) === 1 ? reset($types) : null;
436+
}
437+
438+
/**
439+
* Returns the literal cast to the column type, except a numeric literal for a numeric column, which stays as is so a non-integral value never rounds into a match.
440+
*/
441+
private function castValue(string $value, ?string $type): string
442+
{
443+
$isNumericType = in_array(strtolower((string) $type), ['smallint', 'integer', 'bigint', 'numeric', 'real', 'double precision'], true);
444+
445+
if ($isNumericType && is_numeric($value)) {
446+
return $value;
447+
}
448+
449+
return $this->cast($value, $type);
450+
}
451+
414452
/**
415453
* Returns cast expression.
416454
*
@@ -437,11 +475,15 @@ private function getFieldType(string $table, string $fieldName): ?string
437475
foreach ($this->db->getFieldData($table) as $field) {
438476
$type = $field->type;
439477

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 . ')';
478+
// information_schema reports enum, domain and array columns as `USER-DEFINED` or `ARRAY`, which are not castable names.
479+
if ($type === 'USER-DEFINED' || $type === 'ARRAY') {
480+
continue;
481+
}
482+
483+
// `character` without a length is `character(1)` and `character(n)` truncates on cast,
484+
// while `bpchar` keeps the full value.
485+
if ($type === 'character') {
486+
$type = 'bpchar';
445487
}
446488

447489
$this->QBOptions['fieldTypes'][$table][$field->name] = $type;
@@ -613,14 +655,20 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
613655
if (isset($this->QBOptions['setQueryAsData'])) {
614656
$data = $this->QBOptions['setQueryAsData'];
615657
} else {
658+
$constraints = $this->QBOptions['constraints'] ?? [];
659+
616660
$data = implode(
617661
" UNION ALL\n",
618662
array_map(
619-
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
620-
static fn ($key, $index): string => $index . ' ' . $key,
663+
fn (array $value): string => sprintf('SELECT %s', implode(', ', array_map(
664+
fn (string $key, float|int|string $index): string => sprintf(
665+
'%s %s',
666+
$this->castValue((string) $index, $this->getSourceType($table, $key, $constraints)),
667+
$key,
668+
),
621669
$keys,
622670
$value,
623-
)),
671+
))),
624672
$values,
625673
),
626674
) . "\n";

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace CodeIgniter\Database\Builder;
1515

1616
use CodeIgniter\Database\BaseBuilder;
17+
use CodeIgniter\Database\Postgre\Builder as PostgreBuilder;
1718
use CodeIgniter\Test\CIUnitTestCase;
1819
use CodeIgniter\Test\Mock\MockConnection;
1920
use CodeIgniter\Test\Mock\MockQuery;
@@ -169,4 +170,50 @@ public function testDeleteBatchEscapesWhereInBinds(): void
169170
$this->assertStringContainsString("IN ('anything'' OR ''1''=''1','Ahmadinejad')", $query->getQuery());
170171
$this->assertStringNotContainsString("IN anything' OR '1'='1", $query->getQuery());
171172
}
173+
174+
public function testDeleteBatchPostgreCastsPositionalAndMappedConstraints(): void
175+
{
176+
$db = new class (['DBDriver' => 'Postgre']) extends MockConnection {
177+
protected function _fieldData(string $table): array
178+
{
179+
return [
180+
(object) ['name' => 'id', 'type' => 'integer', 'max_length' => 32],
181+
(object) ['name' => 'name', 'type' => 'text', 'max_length' => null],
182+
];
183+
}
184+
};
185+
186+
$positional = (new PostgreBuilder('jobs', $db))->testMode()
187+
->setData([['id' => 1], ['id' => '2'], ['id' => 1.4]], null, 'data')
188+
->onConstraint('id')
189+
->deleteBatch();
190+
191+
$expected = <<<'EOF'
192+
DELETE FROM "jobs"
193+
USING (
194+
SELECT 1 "id" UNION ALL
195+
SELECT CAST('2' AS INTEGER) "id" UNION ALL
196+
SELECT 1.4 "id"
197+
) "data"
198+
WHERE "jobs"."id" = "data"."id"
199+
EOF;
200+
201+
$this->assertSame($expected, rtrim($positional[0]));
202+
203+
$mapped = (new PostgreBuilder('jobs', $db))->testMode()
204+
->setData([['value' => 'x'], ['value' => 5]], null, 'data')
205+
->onConstraint(['name' => 'value'])
206+
->deleteBatch();
207+
208+
$expected = <<<'EOF'
209+
DELETE FROM "jobs"
210+
USING (
211+
SELECT CAST('x' AS TEXT) "value" UNION ALL
212+
SELECT CAST(5 AS TEXT) "value"
213+
) "data"
214+
WHERE "jobs"."name" = CAST("data"."value" AS TEXT)
215+
EOF;
216+
217+
$this->assertSame($expected, rtrim($mapped[0]));
218+
}
172219
}

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

Lines changed: 69 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,72 @@ 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 1 "id", 'happy' "mood", '{a}' "tags" UNION ALL
500+
SELECT 2 "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+
}
507+
508+
public function testUpdateBatchPostgreDoesNotCastSourceSharedByColumnsOfDifferentTypes(): void
509+
{
510+
$db = new class (['DBDriver' => 'Postgre']) extends MockConnection {
511+
protected function _fieldData(string $table): array
512+
{
513+
return [
514+
(object) ['name' => 'id', 'type' => 'integer', 'max_length' => 32],
515+
(object) ['name' => 'number', 'type' => 'integer', 'max_length' => 32],
516+
(object) ['name' => 'label', 'type' => 'text', 'max_length' => null],
517+
];
518+
}
519+
};
520+
521+
$builder = new PostgreBuilder('jobs', $db);
522+
$sql = $builder->testMode()
523+
->setData([['id' => 1, 'value' => 1.4]], null, 'data')
524+
->updateFields(['number' => 'value', 'label' => 'value'])
525+
->onConstraint('id')
526+
->updateBatch();
527+
528+
$expected = <<<'EOF'
529+
UPDATE "jobs"
530+
SET
531+
"number" = CAST("data"."value" AS INTEGER),
532+
"label" = CAST("data"."value" AS TEXT)
533+
FROM (
534+
SELECT 1 "id", 1.4 "value"
535+
) "data"
536+
WHERE "jobs"."id" = CAST("data"."id" AS INTEGER)
537+
EOF;
538+
539+
$this->assertSame([$expected], $sql);
540+
}
472541
}

‎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';

0 commit comments

Comments
 (0)