|
13 | 13 |
|
14 | 14 | namespace CodeIgniter\Database; |
15 | 15 |
|
| 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; |
16 | 21 | use Stringable; |
17 | 22 |
|
18 | 23 | /** |
@@ -284,10 +289,263 @@ protected function matchNamedBinds(string $sql, array $binds): string |
284 | 289 | $escapedValue = '(' . implode(',', $escapedValue) . ')'; |
285 | 290 | } |
286 | 291 |
|
287 | | - $replacers[":{$placeholder}:"] = $escapedValue; |
| 292 | + $replacers[":{$placeholder}:"] = (string) $escapedValue; |
288 | 293 | } |
289 | 294 |
|
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; |
291 | 549 | } |
292 | 550 |
|
293 | 551 | /** |
|
0 commit comments