Skip to main content

Module sql

Module sql 

Source
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:

characterencoded as
'''
NUL (\0)removed
unicode non-charactersspace

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:

characterencoded as
'\'
\\\
NUL (\0)\0
newline (\n)\n
carriage return (\r)\r
tab (\t)\t
backspace (\x08)\b
Control-Z (\x1A)\Z
unicode non-charactersspace

§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_sql for databases that follow the SQL standard (PostgreSQL, SQLite, SQL Server, Oracle). use for_sql_backslash for MySQL/MariaDB when NO_BACKSLASH_ESCAPES is not enabled.
  • do not use for_sql with MySQL unless NO_BACKSLASH_ESCAPES is set — a backslash can be used to escape the closing quote.

Functions§

for_sql
encodes input for safe embedding in a standard SQL string literal ('...').
for_sql_backslash
encodes input for safe embedding in a MySQL/MariaDB string literal ('...') when backslash escaping is active (the default).
write_sql
writes the standard-SQL-encoded form of input to out.
write_sql_backslash
writes the MySQL-backslash-encoded form of input to out.