SQL utilities
@toshihiko/sql-utils exports three string helpers. Use driver-bound parameters for user-controlled values whenever possible.
escape()
escape(value: string): stringEscapes newline, quotes, tab, null byte, carriage return, backspace, substitute character, and backslash with MySQL-style backslash sequences.
escape("O'Reilly"); // O\'ReillyThe runtime implementation returns a non-string input unchanged for compatibility, although the public TypeScript signature accepts a string.
escapeLike()
escapeLike(value: string): stringEscapes % and _ with a backslash. It does not perform the general escaping done by escape().
const pattern = `%${escapeLike(input)}%`;
await database.execute(
'SELECT * FROM users WHERE name LIKE ?',
[pattern],
);sqlNameToColumn()
sqlNameToColumn(
sql: string,
fragmentMap: Record<string, string>,
): stringReplaces logical identifiers in an SQL fragment while preserving:
- text inside single or double quotes;
- recognized SQL keywords;
- function names before
(.
Backtick-quoted identifiers are always eligible for mapping.
sqlNameToColumn(
'ORDER BY createdAt DESC, `displayName` ASC',
{ createdAt: 'created_at', displayName: 'display_name' },
);
// ORDER BY created_at DESC, `display_name` ASCThis helper tokenizes only the syntax needed by Toshihiko's compatible SQL fragments. It is not a general SQL parser.
Core compatibility export
The core package exposes the first two functions through Escaper:
import { Escaper } from 'toshihiko';
Escaper.escape(value);
Escaper.escapeLike(value);sqlNameToColumn() is available only from @toshihiko/sql-utils.
