Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

escape_string

(EXPERIMENTAL) Escapes a string, making it safe for query composition.

Synopsis

Defined in header <boost/mysql/escape_string.hpp>

template<
    class OutputString>
error_code
escape_string(
    string_view input,
    const format_options& opts,
    quoting_context quot_ctx,
    OutputString& output);
Description

Given a string input, computes a string with special characters escaped, and places it in output. This function is a low-level building block for composing client-side queries with runtime string values without incurring in SQL injection vulnerabilities. If you can, prefer using higher-level functions like format_sql.

Escaping rules are different depending on the context a string is being used in. quot_ctx identifies where the string will appear in a query. Possible values are:

By default, MySQL treats backslash characters as escapes in string values (for instance, the string "\n" is treated as a newline). This behavior is enabled by default, but can be disabled by enabling the NO_BACKSLASH_ESCAPES SQL mode. When enabled, backslashes no longer have a special meaning, which changes the escaping rules. opts.backslash_escapes should be set to true if backslashes represent escapes (i.e. NO_BACKSLASH_ESCAPES is not enabled), and false otherwise.

MySQL can be configured to treat double-quoted strings as identifiers instead of values. This is enabled by activating the ANSI_QUOTES or ANSI SQL modes. Servers don't report whether this mode is enabled to clients. This SQL mode is not directly supported by this function.

opts.charsetshould identify the connection's character set (as given by the character_set_client session variable). The character set is used to iterate over the input string. It must be an ASCII-compatible character set (like utf8mb4_charset). All character sets allowed by character_set_client satisfy this requirement.

You can use any_connection::format_opts to retrieve an opts value suitable for your connection.

Exception safety

Basic guarantee. Memory allocations may throw.

Complexity

Linear in input.size().

Errors

client_errc::invalid_encoding if input contains a string that is not valid according to opts.charset.


PrevUpHomeNext