Expand description
SQL string literal encoders.
encodes untrusted strings for safe embedding in SQL string literals.
for_sql— safe for standard SQL string literals ('...')for_sql_backslash— safe for MySQL/MariaDB string literals with backslash escaping enabled ('...')
§encoding rules
§standard SQL (for_sql)
standard SQL escapes single quotes by doubling them:
| character | encoded as |
|---|---|
' | '' |
NUL (\0) | removed |
| unicode non-characters | space |
all other characters (including backslash) pass through unchanged — they have no special meaning in standard SQL string literals.
§MySQL/MariaDB backslash escaping (for_sql_backslash)
MySQL and MariaDB (when NO_BACKSLASH_ESCAPES is not set) use C-style
backslash escape sequences:
| character | encoded as |
|---|---|
' | \' |
\ | \\ |
NUL (\0) | \0 |
newline (\n) | \n |
carriage return (\r) | \r |
tab (\t) | \t |
backspace (\x08) | \b |
Control-Z (\x1A) | \Z |
| unicode non-characters | space |
§security notes
- parameterized queries are always preferred. these encoders exist for cases where parameterized queries are not possible (e.g. DDL, dynamic identifiers, legacy code).
- know your dialect. use
for_sqlfor databases that follow the SQL standard (PostgreSQL, SQLite, SQL Server, Oracle). usefor_sql_backslashfor MySQL/MariaDB whenNO_BACKSLASH_ESCAPESis not enabled. - do not use
for_sqlwith MySQL unlessNO_BACKSLASH_ESCAPESis set — a backslash can be used to escape the closing quote.
Functions§
- for_sql
- encodes
inputfor safe embedding in a standard SQL string literal ('...'). - for_
sql_ backslash - encodes
inputfor safe embedding in a MySQL/MariaDB string literal ('...') when backslash escaping is active (the default). - write_
sql - writes the standard-SQL-encoded form of
inputtoout. - write_
sql_ backslash - writes the MySQL-backslash-encoded form of
inputtoout.