cql3: single_quote() util function

`single_quote()` takes a string and transforms it to a string
which can be safely used in CQL commands.
Single quoting involves wrapping the name in single-quotes ('). A sigle-quote
character itself is quoted by doubling it.
Single quoting is necessary for dates, IP addresses or string literals.
This commit is contained in:
Michał Jadwiszczak
2022-11-09 10:35:11 +01:00
parent 9c2a5a755f
commit 0589116991
2 changed files with 31 additions and 11 deletions

View File

@@ -473,27 +473,40 @@ sstring maybe_quote(const sstring& identifier) {
return result;
}
sstring quote(const sstring& identifier) {
template <char C>
static sstring quote_with(const sstring& str) {
static const std::string quote_str{C};
// quote empty string
if (identifier.empty()) {
return "\"\"";
if (str.empty()) {
return make_sstring(quote_str, quote_str);
}
size_t num_quotes = 0;
for (char c : identifier) {
num_quotes += (c == '"');
for (char c : str) {
num_quotes += (c == C);
}
if (num_quotes == 0) {
return make_sstring("\"", identifier, "\"");
return make_sstring(quote_str, str, quote_str);
}
static const std::regex double_quote_re("\"");
static const std::string double_quote_str{C, C};
static const std::regex quote_re(std::string{C});
std::string result;
result.reserve(2 + identifier.size() + num_quotes);
result.push_back('"');
std::regex_replace(std::back_inserter(result), identifier.begin(), identifier.end(), double_quote_re, "\"\"");
result.push_back('"');
result.reserve(2 + str.size() + num_quotes);
result.push_back(C);
std::regex_replace(std::back_inserter(result), str.begin(), str.end(), quote_re, double_quote_str);
result.push_back(C);
return result;
}
sstring quote(const sstring& identifier) {
return quote_with<'"'>(identifier);
}
sstring single_quote(const sstring& str) {
return quote_with<'\''>(str);
}
}
}

View File

@@ -81,6 +81,13 @@ sstring maybe_quote(const sstring& s);
/// quote the identifier name in CQL, so that is what this function does does.
sstring quote(const sstring& s);
/// single_quote() takes a string and transforms it to a string
/// which can be safely used in CQL commands.
/// Single quoting involves wrapping the name in single-quotes ('). A sigle-quote
/// character itself is quoted by doubling it.
/// Single quoting is necessary for dates, IP addresses or string literals.
sstring single_quote(const sstring& s);
// Check whether timestamp is not too far in the future as this probably
// indicates its incorrectness (for example using other units than microseconds).
void validate_timestamp(const query_options& options, const std::unique_ptr<attributes>& attrs);