Skip to content

Commit

Permalink
Escape identifiers that need it
Browse files Browse the repository at this point in the history
Signed-off-by: Kamil Tekiela <[email protected]>
  • Loading branch information
kamil-tekiela committed Aug 29, 2023
1 parent 52ffc49 commit d1d83ed
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 @@ -675,7 +676,11 @@ private static function getModeFromString(string $mode): int
*/
public static function escape(string $str, string $quote = '`')
{
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) || static::doesIdentifierRequireQuoting($str)
)
) {
return $str;
}

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

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

public 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 d1d83ed

Please sign in to comment.