Skip to content

Commit da1a0c7

Browse files
michalsnclaude
andauthored
Merge commit from fork
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8cf6fad commit da1a0c7

13 files changed

Lines changed: 999 additions & 31 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2959,9 +2959,6 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
29592959
),
29602960
);
29612961

2962-
// convert binds in where
2963-
$this->convertWhereBindsForBatch();
2964-
29652962
$sql .= ' ' . $this->compileWhereHaving('QBWhere');
29662963

29672964
$this->QBOptions['sql'] = trim($sql);
@@ -2983,35 +2980,50 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
29832980
) . "\n";
29842981
}
29852982

2986-
return str_replace('{:_table_:}', $data, $sql);
2983+
return $this->compileBatchBinds(str_replace('{:_table_:}', $data, $sql));
29872984
}
29882985

29892986
/**
2990-
* Escapes and substitutes the WHERE binds into the QBWhere conditions
2991-
* for batch delete queries.
2987+
* Escapes and substitutes the binds into a compiled batch query.
29922988
*
2993-
* The bound values respect their escape flag and are escaped the same way
2994-
* as a regular query (see Query::matchNamedBinds()), instead of being
2995-
* injected into the SQL as raw, unescaped values.
2989+
* This must run after the batch data has been rendered into the SQL, so
2990+
* that a bound value containing `{:_table_:}` is never mixed with the
2991+
* batch data. The bound values are substituted by Query, the same way as
2992+
* in a regular query (see Query::matchNamedBinds()), so they respect their
2993+
* escape flag and placeholders inside the already escaped batch data are
2994+
* left untouched.
29962995
*
29972996
* @used-by _deleteBatch()
29982997
*/
2999-
protected function convertWhereBindsForBatch(): void
2998+
protected function compileBatchBinds(string $sql): string
30002999
{
3001-
$replacers = [];
3000+
if ($this->binds === []) {
3001+
return $sql;
3002+
}
30023003

3003-
foreach ($this->binds as $field => $bind) {
3004-
$escapedValue = $bind[1] ? $this->db->escape($bind[0]) : $bind[0];
3004+
return (new Query($this->db))
3005+
->setQuery($sql, $this->binds, false)
3006+
->getQuery();
3007+
}
30053008

3006-
if (is_array($bind[0])) {
3007-
$escapedValue = '(' . implode(',', $escapedValue) . ')';
3008-
}
3009+
/**
3010+
* Escapes and substitutes the WHERE binds into the QBWhere conditions
3011+
* for batch delete queries.
3012+
*
3013+
* @deprecated 4.7.6 No longer used. The binds are substituted into the
3014+
* compiled batch query by compileBatchBinds() instead.
3015+
*/
3016+
protected function convertWhereBindsForBatch(): void
3017+
{
3018+
foreach ($this->QBWhere as $key => $where) {
3019+
$condition = $where['condition'];
30093020

3010-
$replacers[':' . $field . ':'] = (string) $escapedValue;
3011-
}
3021+
$sql = (new Query($this->db))
3022+
->setQuery((string) $condition, $this->binds, false)
3023+
->getQuery();
30123024

3013-
foreach ($this->QBWhere as $key => $where) {
3014-
$this->QBWhere[$key]['condition'] = strtr($where['condition'], $replacers);
3025+
// Keep RawSql conditions as RawSql, as they are compiled differently.
3026+
$this->QBWhere[$key]['condition'] = $condition instanceof RawSql ? $condition->with($sql) : $sql;
30153027
}
30163028
}
30173029

‎system/Database/OCI8/Builder.php‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -459,9 +459,6 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
459459
),
460460
);
461461

462-
// convert binds in where
463-
$this->convertWhereBindsForBatch();
464-
465462
$sql .= ' ' . str_replace(
466463
'WHERE ',
467464
'AND ',
@@ -494,7 +491,7 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
494491
) . " FROM DUAL\n";
495492
}
496493

497-
return str_replace('{:_table_:}', $data, $sql);
494+
return $this->compileBatchBinds(str_replace('{:_table_:}', $data, $sql));
498495
}
499496

500497
/**

‎system/Database/Postgre/Builder.php‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -640,9 +640,6 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
640640
),
641641
);
642642

643-
// convert binds in where
644-
$this->convertWhereBindsForBatch();
645-
646643
$sql .= ' ' . str_replace(
647644
'WHERE ',
648645
'AND ',
@@ -674,6 +671,6 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
674671
) . "\n";
675672
}
676673

677-
return str_replace('{:_table_:}', $data, $sql);
674+
return $this->compileBatchBinds(str_replace('{:_table_:}', $data, $sql));
678675
}
679676
}

‎system/Database/Query.php‎

Lines changed: 260 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@
1313

1414
namespace CodeIgniter\Database;
1515

16+
use CodeIgniter\Database\MySQLi\Connection as MySQLiConnection;
17+
use CodeIgniter\Database\OCI8\Connection as OCI8Connection;
18+
use CodeIgniter\Database\Postgre\Connection as PostgreConnection;
19+
use CodeIgniter\Database\SQLite3\Connection as SQLite3Connection;
20+
use CodeIgniter\Database\SQLSRV\Connection as SQLSRVConnection;
1621
use Stringable;
1722

1823
/**
@@ -284,10 +289,263 @@ protected function matchNamedBinds(string $sql, array $binds): string
284289
$escapedValue = '(' . implode(',', $escapedValue) . ')';
285290
}
286291

287-
$replacers[":{$placeholder}:"] = $escapedValue;
292+
$replacers[":{$placeholder}:"] = (string) $escapedValue;
288293
}
289294

290-
return strtr($sql, $replacers);
295+
return $this->replaceNamedPlaceholders($sql, $replacers);
296+
}
297+
298+
/**
299+
* Works like strtr(), but leaves quoted strings, quoted identifiers
300+
* and comments untouched, so that values already rendered into the SQL
301+
* (escaped values, compiled subqueries) are never treated as placeholders.
302+
*
303+
* @param array<string, string> $replacers
304+
*/
305+
private function replaceNamedPlaceholders(string $sql, array $replacers): string
306+
{
307+
if (strpbrk($sql, '\'"`#[$') === false && ! str_contains($sql, '--') && ! str_contains($sql, '/*')) {
308+
return strtr($sql, $replacers);
309+
}
310+
311+
$maxLength = max(array_map(strlen(...), array_keys($replacers)));
312+
$isMySQL = $this->db instanceof MySQLiConnection;
313+
$isSQLSRV = $this->db instanceof SQLSRVConnection;
314+
$isPostgre = $this->db instanceof PostgreConnection;
315+
$isSQLite = $this->db instanceof SQLite3Connection;
316+
$isOCI8 = $this->db instanceof OCI8Connection;
317+
318+
// Backslash escapes matter only when there is a backslash in the SQL.
319+
$backslashEscapes = str_contains($sql, '\\')
320+
&& $this->db instanceof BaseConnection
321+
&& $this->db->escapeString('\\') !== '\\';
322+
323+
// Multibyte characters matter only when there is a non-ASCII byte in the SQL.
324+
$multibyte = preg_match('/[\x80-\xff]/', $sql) === 1
325+
? $this->getMultibyteCharPattern($isMySQL, $isPostgre)
326+
: null;
327+
328+
$stop = ':\'"`-/#[$' . ($multibyte === null ? '' : implode('', array_map(chr(...), range(0x80, 0xFF))));
329+
$multibyteEnd = -1;
330+
$length = strlen($sql);
331+
$result = '';
332+
$offset = 0;
333+
334+
while ($offset < $length) {
335+
$position = $offset + strcspn($sql, $stop, $offset);
336+
$result .= substr($sql, $offset, $position - $offset);
337+
338+
if ($position >= $length) {
339+
break;
340+
}
341+
342+
$char = $sql[$position];
343+
$next = $sql[$position + 1] ?? '';
344+
$end = $position + 1;
345+
346+
if ($multibyte !== null && ord($char) >= 0x80) {
347+
$end = $position + $this->getCharLength($sql, $position, $multibyte);
348+
$multibyteEnd = $end;
349+
} elseif ($char === ':') {
350+
$placeholder = $this->findPlaceholderAt($sql, $position, $replacers, $maxLength);
351+
352+
if ($placeholder !== null) {
353+
$result .= $replacers[$placeholder];
354+
$offset = $position + strlen($placeholder);
355+
356+
continue;
357+
}
358+
} elseif (
359+
$char === '\'' && $isOCI8
360+
&& preg_match('/(?<![\w$#])[nN]?[qQ]\z/', substr($sql, max(0, $position - 3), min(3, $position))) === 1
361+
&& preg_match('/\S/', $sql[$position + 1] ?? ' ') === 1
362+
) {
363+
// Oracle alternative quoting: q'[...]', q'{...}', q'<...>', q'(...)' or q'X...X'
364+
$close = strpos($sql, strtr($sql[$position + 1], '[{<(', ']}>)') . '\'', $position + 2);
365+
$end = $close === false ? $length : $close + 2;
366+
} elseif ($char === '\'') {
367+
// PostgreSQL E'...' strings always use backslash escapes.
368+
$isEscapeString = $isPostgre
369+
&& $position > 0
370+
&& $multibyteEnd !== $position
371+
&& ($sql[$position - 1] === 'E' || $sql[$position - 1] === 'e')
372+
&& ($position === 1 || preg_match('/[\w$\x80-\xff]/', $sql[$position - 2]) !== 1);
373+
374+
$end = $this->findQuotedEnd($sql, $position, '\'', $backslashEscapes || $isEscapeString, $multibyte);
375+
} elseif ($char === '"') {
376+
// Only MySQL uses "..." for strings; elsewhere it quotes
377+
// identifiers, in which a backslash is never an escape.
378+
$end = $this->findQuotedEnd($sql, $position, '"', $backslashEscapes && $isMySQL, $multibyte);
379+
} elseif ($char === '`') {
380+
$end = $this->findQuotedEnd($sql, $position, '`', false);
381+
} elseif ($char === '[' && ($isSQLSRV || $isSQLite)) {
382+
$end = $this->findQuotedEnd($sql, $position, ']', false);
383+
} elseif (
384+
$char === '$' && $isPostgre
385+
&& ($position === 0 || preg_match('/[\w$\x80-\xff]/', $sql[$position - 1]) !== 1)
386+
&& preg_match('/\G\$(?:[A-Za-z_\x80-\xff][\w\x80-\xff]*)?\$/', $sql, $match, 0, $position) === 1
387+
) {
388+
// PostgreSQL dollar-quoted strings: $$...$$ or $tag$...$tag$
389+
$close = strpos($sql, $match[0], $position + strlen($match[0]));
390+
$end = $close === false ? $length : $close + strlen($match[0]);
391+
} elseif (
392+
($char === '-' && $next === '-' && (! $isMySQL || ord($sql[$position + 2] ?? ' ') <= 32))
393+
|| ($char === '#' && $isMySQL)
394+
) {
395+
// MySQL requires whitespace after "--" and also supports "#" comments.
396+
$newLine = strpos($sql, "\n", $position);
397+
$end = $newLine === false ? $length : $newLine;
398+
} elseif ($char === '/' && $next === '*' && (! $isMySQL || ($sql[$position + 2] ?? '') !== '!')) {
399+
// MySQL executes /*! ... */ comments, so they are not skipped.
400+
// PostgreSQL and SQL Server allow nested block comments.
401+
$end = $this->findCommentEnd($sql, $position, $isPostgre || $isSQLSRV);
402+
}
403+
404+
$result .= substr($sql, $position, $end - $position);
405+
$offset = $end;
406+
}
407+
408+
return $result;
409+
}
410+
411+
/**
412+
* Returns the longest placeholder that starts at the given position,
413+
* matching the strtr() behavior.
414+
*
415+
* @param array<string, string> $replacers
416+
*/
417+
private function findPlaceholderAt(string $sql, int $position, array $replacers, int $maxLength): ?string
418+
{
419+
$candidates = [];
420+
$colon = $position;
421+
422+
while (($colon = strpos($sql, ':', $colon + 1)) !== false && $colon - $position < $maxLength) {
423+
$candidates[] = substr($sql, $position, $colon - $position + 1);
424+
}
425+
426+
foreach (array_reverse($candidates) as $candidate) {
427+
if (array_key_exists($candidate, $replacers)) {
428+
return $candidate;
429+
}
430+
}
431+
432+
return null;
433+
}
434+
435+
/**
436+
* Returns a pattern matching one multibyte character for connection
437+
* charsets in which a trailing byte may be an ASCII byte, such as
438+
* a backslash, or null when the charset does not need it.
439+
*/
440+
private function getMultibyteCharPattern(bool $isMySQL, bool $isPostgre): ?string
441+
{
442+
if (! $this->db instanceof BaseConnection) {
443+
return null;
444+
}
445+
446+
// Same rules as my_ismbchar() in MySQL: invalid sequences are single bytes.
447+
if ($isMySQL) {
448+
return match (strtolower($this->db->charset)) {
449+
'big5' => '/\G[\xa1-\xf9][\x40-\x7e\xa1-\xfe]/',
450+
'gbk' => '/\G[\x81-\xfe][\x40-\x7e\x80-\xfe]/',
451+
'gb18030' => '/\G[\x81-\xfe](?:[\x30-\x39][\x81-\xfe][\x30-\x39]|[\x40-\x7e\x80-\xfe])/',
452+
'cp932', 'sjis' => '/\G[\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc]/',
453+
default => null,
454+
};
455+
}
456+
457+
// Same rules as pg_encoding_mblen() in libpq; PostgreSQL ignores case
458+
// and non-alphanumeric characters in encoding names.
459+
if ($isPostgre) {
460+
return match (strtolower((string) preg_replace('/[^A-Za-z0-9]/', '', $this->db->charset))) {
461+
'big5', 'win950', 'windows950', 'gbk', 'win936', 'windows936' => '/\G[\x80-\xff][\x00-\xff]/',
462+
'gb18030' => '/\G[\x80-\xff](?:[\x30-\x39][\x00-\xff]{2}|[\x00-\xff])/',
463+
'mskanji', 'shiftjis', 'shiftjis2004', 'sjis', 'win932', 'windows932' => '/\G[\x80-\xa0\xe0-\xff][\x00-\xff]/',
464+
default => null,
465+
};
466+
}
467+
468+
return null;
469+
}
470+
471+
/**
472+
* Returns the length in bytes of the character at the given position.
473+
*/
474+
private function getCharLength(string $sql, int $position, string $multibyte): int
475+
{
476+
return preg_match($multibyte, $sql, $match, 0, $position) === 1 ? strlen($match[0]) : 1;
477+
}
478+
479+
/**
480+
* Returns the position just after the end of the block comment
481+
* that starts at the given position.
482+
*/
483+
private function findCommentEnd(string $sql, int $position, bool $nested): int
484+
{
485+
if (! $nested) {
486+
$close = strpos($sql, '*/', $position + 2);
487+
488+
return $close === false ? strlen($sql) : $close + 2;
489+
}
490+
491+
$depth = 0;
492+
$offset = $position;
493+
494+
while (preg_match('~/\*|\*/~', $sql, $match, PREG_OFFSET_CAPTURE, $offset) === 1) {
495+
$offset = $match[0][1] + 2;
496+
$depth += $match[0][0] === '/*' ? 1 : -1;
497+
498+
if ($depth === 0) {
499+
return $offset;
500+
}
501+
}
502+
503+
return strlen($sql);
504+
}
505+
506+
/**
507+
* Returns the position just after the closing quote of the quoted
508+
* string or identifier that starts at the given position.
509+
*/
510+
private function findQuotedEnd(string $sql, int $position, string $quote, bool $backslashEscapes, ?string $multibyte = null): int
511+
{
512+
$stop = $backslashEscapes ? $quote . '\\' : $quote;
513+
$length = strlen($sql);
514+
$offset = $position + 1;
515+
516+
if ($multibyte !== null) {
517+
$stop .= implode('', array_map(chr(...), range(0x80, 0xFF)));
518+
}
519+
520+
while ($offset < $length) {
521+
$offset += strcspn($sql, $stop, $offset);
522+
523+
if ($offset >= $length) {
524+
break;
525+
}
526+
527+
if ($multibyte !== null && ord($sql[$offset]) >= 0x80) {
528+
$offset += $this->getCharLength($sql, $offset, $multibyte);
529+
530+
continue;
531+
}
532+
533+
if ($sql[$offset] === '\\') {
534+
$offset += 2;
535+
536+
continue;
537+
}
538+
539+
if (($sql[$offset + 1] ?? '') === $quote) {
540+
$offset += 2;
541+
542+
continue;
543+
}
544+
545+
return $offset + 1;
546+
}
547+
548+
return $length;
291549
}
292550

293551
/**

0 commit comments

Comments
 (0)