Files
JetCore/SqlBind.cpp
T
brad ArantandClaude Opus 5.5 a18d1358b0 Add <bind> bound parameters for <sql> (phase 1)
Implements phase 1 of docs/design-sql-bound-parameters.md: <bind> supplies
the value for the next ? placeholder of the enclosing <sql>, with typed
validation (int, decimal, date, datetime, bool, ident with allow list),
null="empty", and refusal to change the connection character set.

- SqlBind.*: MySQL-free placeholder scanning and binding logic
- __bind.*, __sql, __mysql: runtime wiring
- Tag.cpp, jetc/JetParser.cpp: bind is a void tag in both
- jetc/JetCodegen: emit sized ZString literals for text holding a NUL,
  which previously truncated the compiled page
- tests: unit tests, end-to-end test against MySQL (interpreted and
  jetc-compiled), and the generator for the binary test page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:55:23 -08:00

306 lines
11 KiB
C++

#include "SqlBind.h"
#include "Exception.h"
#include <cctype>
namespace jet {
namespace {
std::string lower(std::string s) {
for(char &c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
std::string trim(const std::string &s) {
size_t b = 0, e = s.size();
while(b < e && std::isspace((unsigned char)s[b])) ++b;
while(e > b && std::isspace((unsigned char)s[e - 1])) --e;
return s.substr(b, e - b);
}
std::string where(int position) {
return "bind " + std::to_string(position) + ": ";
}
bool allDigits(const std::string &s, size_t from, size_t to) {
if(from >= to) return false;
for(size_t i = from; i < to; ++i)
if(!std::isdigit((unsigned char)s[i])) return false;
return true;
}
// ^-?[0-9]{1,maxDigits}$
bool isInteger(const std::string &s, size_t maxDigits) {
size_t start = (!s.empty() && s[0] == '-') ? 1 : 0;
size_t digits = s.size() - start;
return digits >= 1 && digits <= maxDigits && allDigits(s, start, s.size());
}
// ^-?[0-9]{1,30}(\.[0-9]{1,30})?$
bool isDecimal(const std::string &s) {
size_t dot = s.find('.');
if(dot == std::string::npos) return isInteger(s, 30);
std::string frac = s.substr(dot + 1);
return isInteger(s.substr(0, dot), 30) && frac.size() >= 1 && frac.size() <= 30 && allDigits(frac, 0, frac.size());
}
int num(const std::string &s, size_t at, size_t len) {
return std::stoi(s.substr(at, len));
}
// YYYY-MM-DD with a real month and day range.
bool isDate(const std::string &s) {
if(s.size() != 10 || s[4] != '-' || s[7] != '-') return false;
if(!allDigits(s, 0, 4) || !allDigits(s, 5, 7) || !allDigits(s, 8, 10)) return false;
int month = num(s, 5, 2), day = num(s, 8, 2);
return month >= 1 && month <= 12 && day >= 1 && day <= 31;
}
// YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS
bool isDateTime(const std::string &s) {
if(s.size() != 16 && s.size() != 19) return false;
if(!isDate(s.substr(0, 10)) || s[10] != ' ' || s[13] != ':') return false;
if(!allDigits(s, 11, 13) || !allDigits(s, 14, 16)) return false;
if(num(s, 11, 2) > 23 || num(s, 14, 2) > 59) return false;
if(s.size() == 19) {
if(s[16] != ':' || !allDigits(s, 17, 19) || num(s, 17, 2) > 59) return false;
}
return true;
}
// Walks query and calls onPlaceholder(index) for every '?' that is
// outside '...', "...", `...`, -- / # line comments and /* */
// comments. With NO_BACKSLASH_ESCAPES off, a backslash escapes the
// next character inside '...' and "..."; with it on, it doesn't.
// A doubled quote ('', "", ``) is an escaped quote in every mode.
template<typename F>
void scan(const std::string &q, bool noBackslashEscapes, F onPlaceholder) {
size_t i = 0, n = q.size();
while(i < n) {
char c = q[i];
if(c == '\'' || c == '"' || c == '`') {
char quote = c;
++i;
while(i < n) {
if(quote != '`' && !noBackslashEscapes && q[i] == '\\') { i += 2; continue; }
if(q[i] == quote) {
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
++i;
break;
}
++i;
}
continue;
}
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
while(i < n && q[i] != '\n') ++i;
continue;
}
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
size_t end = q.find("*/", i + 2);
i = (end == std::string::npos) ? n : end + 2;
continue;
}
if(c == '?') onPlaceholder(i);
++i;
}
}
// Lowercased words ([a-z0-9_@.$]) outside quotes and comments.
std::vector<std::string> words(const std::string &q) {
std::vector<std::string> out;
std::string cur;
size_t i = 0, n = q.size();
auto flush = [&]() { if(!cur.empty()) { out.push_back(lower(cur)); cur.clear(); } };
while(i < n) {
char c = q[i];
if(c == '\'' || c == '"' || c == '`') {
flush();
char quote = c;
++i;
while(i < n) {
if(quote != '`' && q[i] == '\\') { i += 2; continue; }
if(q[i] == quote) {
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
++i;
break;
}
++i;
}
out.push_back("'"); // a literal stands between words
continue;
}
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
flush();
while(i < n && q[i] != '\n') ++i;
continue;
}
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
flush();
size_t end = q.find("*/", i + 2);
i = (end == std::string::npos) ? n : end + 2;
continue;
}
if(std::isalnum((unsigned char)c) || c == '_' || c == '@' || c == '.' || c == '$')
cur += c;
else
flush();
++i;
}
flush();
return out;
}
}
BoundValue makeBoundValue(const std::string &value,
const std::string &typeIn,
const std::string &nullModeIn,
bool hasAllow,
const std::string &allow,
int position) {
std::string type = typeIn.empty() ? "string" : lower(trim(typeIn));
std::string nullMode = lower(trim(nullModeIn));
if(nullMode != "" && nullMode != "empty")
throw coreutils::Exception(where(position) + "null must be \"empty\".");
if(hasAllow && type != "ident")
throw coreutils::Exception(where(position) + "allow is only valid with type=\"ident\".");
BoundValue b;
if(nullMode == "empty" && value.empty()) {
b.kind = BoundValue::SQLNULL;
return b;
}
if(type == "string") {
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "int") {
if(!isInteger(value, 19))
throw coreutils::Exception(where(position) + "value is not a valid int.");
b.kind = BoundValue::BARE;
b.text = value;
} else if(type == "decimal") {
if(!isDecimal(value))
throw coreutils::Exception(where(position) + "value is not a valid decimal.");
b.kind = BoundValue::BARE;
b.text = value;
} else if(type == "bool") {
std::string v = lower(value);
b.kind = BoundValue::BARE;
if(v == "1" || v == "true" || v == "yes")
b.text = "1";
else if(v == "0" || v == "false" || v == "no")
b.text = "0";
else
throw coreutils::Exception(where(position) + "value is not a valid bool.");
} else if(type == "date") {
if(!isDate(value))
throw coreutils::Exception(where(position) + "value is not a valid date (YYYY-MM-DD).");
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "datetime") {
if(!isDateTime(value))
throw coreutils::Exception(where(position) + "value is not a valid datetime (YYYY-MM-DD HH:MM[:SS]).");
b.kind = BoundValue::QUOTED;
b.text = value;
} else if(type == "ident") {
if(!hasAllow)
throw coreutils::Exception(where(position) + "type=\"ident\" requires an allow list.");
// Match case-insensitively, but emit the allow list's own spelling:
// what reaches the query always comes from the page, never the request.
std::string match;
bool found = false;
size_t start = 0;
while(start <= allow.size()) {
size_t comma = allow.find(',', start);
if(comma == std::string::npos) comma = allow.size();
std::string entry = trim(allow.substr(start, comma - start));
if(!entry.empty() && lower(entry) == lower(value)) {
match = entry;
found = true;
break;
}
start = comma + 1;
}
if(!found)
throw coreutils::Exception(where(position) + "value is not in the allow list.");
b.kind = BoundValue::BARE;
std::string m = lower(match);
if(m == "asc" || m == "desc") {
b.text = (m == "asc") ? "ASC" : "DESC";
} else {
b.text = "`";
for(char c : match) {
if(c == '`') b.text += '`';
b.text += c;
}
b.text += "`";
}
} else
throw coreutils::Exception(where(position) + "unknown type \"" + type + "\".");
return b;
}
size_t countPlaceholders(const std::string &query, bool noBackslashEscapes) {
size_t count = 0;
scan(query, noBackslashEscapes, [&](size_t) { ++count; });
return count;
}
std::string bindPlaceholders(const std::string &query,
const std::vector<BoundValue> &values,
bool noBackslashEscapes,
const std::function<std::string(const std::string &)> &quoteEscape) {
std::vector<size_t> at;
scan(query, noBackslashEscapes, [&](size_t i) { at.push_back(i); });
if(at.size() != values.size())
throw coreutils::Exception("sql: " + std::to_string(at.size()) + " placeholders but " +
std::to_string(values.size()) + " bind values");
std::string out;
out.reserve(query.size() + 32 * values.size());
size_t last = 0;
for(size_t k = 0; k < at.size(); ++k) {
out.append(query, last, at[k] - last);
const BoundValue &v = values[k];
if(v.kind == BoundValue::SQLNULL)
out += "NULL";
else if(v.kind == BoundValue::BARE)
out += v.text;
else {
out += '\'';
out += quoteEscape(v.text);
out += '\'';
}
last = at[k] + 1;
}
out.append(query, last, std::string::npos);
return out;
}
bool isCharsetChange(const std::string &query) {
std::vector<std::string> w = words(query);
if(w.empty() || w[0] != "set")
return false;
for(size_t i = 1; i < w.size(); ++i) {
const std::string &x = w[i];
if(x == "names" || x == "charset")
return true;
if(x == "character" && i + 1 < w.size() && w[i + 1] == "set")
return true;
// character_set_client, @@character_set_client, @@session.character_set_client, ...
for(const char *var : {"character_set_client", "character_set_connection", "collation_connection"}) {
std::string v(var);
if(x.size() >= v.size() && x.compare(x.size() - v.size(), v.size(), v) == 0)
return true;
}
}
return false;
}
}