Skip to content

Commit

Permalink
Merge pull request #501 from kamil-tekiela/Escape-identifiers-that-ne…
Browse files Browse the repository at this point in the history
…ed-it

Escape identifiers that need it
  • Loading branch information
MauricioFauth authored Sep 5, 2023
2 parents 03b0bca + b299035 commit b737500
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use function intval;
use function is_int;
use function is_numeric;
use function preg_match;
use function str_replace;
use function str_starts_with;
use function strlen;
Expand Down Expand Up @@ -673,7 +674,11 @@ private static function getModeFromString(string $mode): int
*/
public static function escape(string $str, string $quote = '`'): string
{
if ((static::$mode & self::SQL_MODE_NO_ENCLOSING_QUOTES) && (! static::isKeyword($str, true))) {
if (
(static::$mode & self::SQL_MODE_NO_ENCLOSING_QUOTES) && ! (
static::isKeyword($str, true) || self::doesIdentifierRequireQuoting($str)
)
) {
return $str;
}

Expand Down Expand Up @@ -725,4 +730,9 @@ public static function hasMode(int|null $flag = null): bool

return (self::$mode & $flag) === $flag;
}

private static function doesIdentifierRequireQuoting(string $identifier): bool
{
return preg_match('/^[$]|^\d+$|[^0-9a-zA-Z$_\x80-\xffff]/', $identifier) === 1;
}
}
4 changes: 4 additions & 0 deletions tests/Lexer/ContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ public function testEscape(): void
{
Context::setMode(Context::SQL_MODE_NO_ENCLOSING_QUOTES);
$this->assertEquals('test', Context::escape('test'));
$this->assertEquals('`123`', Context::escape('123'));
$this->assertEquals('`$test`', Context::escape('$test'));
$this->assertEquals('`te st`', Context::escape('te st'));
$this->assertEquals('`te.st`', Context::escape('te.st'));

Context::setMode(Context::SQL_MODE_ANSI_QUOTES);
$this->assertEquals('"test"', Context::escape('test'));
Expand Down

0 comments on commit b737500

Please sign in to comment.