Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,10 @@ add_library(flapi-lib STATIC
src/request_handler.cpp
src/request_validator.cpp
src/rate_limit_middleware.cpp
src/prepared_template_rewriter.cpp
src/route_translator.cpp
src/security_auditor.cpp
src/sql_parameter_classifier.cpp
src/sql_template_processor.cpp
src/sql_utils.cpp
src/mcp_server.cpp
Expand Down
47 changes: 47 additions & 0 deletions src/include/prepared_template_rewriter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#pragma once

#include <cstddef>
#include <string>
#include <vector>

#include "sql_parameter_classifier.hpp"

namespace flapi {

struct RequestFieldConfig;

// W3.1 (PR A): one entry in the binding plan produced by the rewriter.
// `position` is the 0-indexed `?` slot in the rewritten template; the
// caller binds values in that order via DuckDB's prepared-statement API.
struct PreparedBindingSpec {
std::string field_name;
SqlParameterType type = SqlParameterType::Varchar;
std::size_t position = 0;
};

struct PreparedRewriteResult {
std::string rewritten_template;
std::vector<PreparedBindingSpec> bindings;
};

// Pure helper. Scans a Mustache template and rewrites occurrences of
// `{{ params.X }}` to `?` for parameters X that the classifier marks
// bindable, recording the binding order. Untouched:
// - triple-brace `{{{ params.X }}}` (raw substitution; operators
// migrate these separately)
// - any `{{ params.X }}` inside a Mustache section block
// (`{{#X}}...{{/X}}` or `{{^X}}...{{/X}}`)
// - params whose `RequestFieldConfig` has no typed validator
// - non-`params.*` references like `{{ conn.X }}` or `{{ env.X }}`
//
// The result is suitable for: render-the-rewritten-template-as-Mustache
// (only structural variation remains), then `duckdb_prepare` + bind
// per the plan.
class PreparedTemplateRewriter {
public:
PreparedRewriteResult rewrite(const std::string& template_text,
const std::vector<RequestFieldConfig>& request_fields,
const SqlParameterClassifier& classifier) const;
};

} // namespace flapi
40 changes: 40 additions & 0 deletions src/include/sql_parameter_classifier.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#pragma once

#include <string>

namespace flapi {

struct RequestFieldConfig;

// W3.1 (PR A): how a typed parameter should be bound into a DuckDB
// prepared statement. The classifier maps a `RequestFieldConfig` to one
// of these — `PreparedTemplateRewriter` then uses the result to decide
// whether a `{{ params.X }}` occurrence should become a `?` placeholder.
enum class SqlParameterType {
Integer, // duckdb_bind_int64
Double, // duckdb_bind_double
Boolean, // duckdb_bind_boolean
Date, // duckdb_bind_date (caller parses yyyy-mm-dd)
Time, // duckdb_bind_time (caller parses hh:mm:ss)
Varchar, // duckdb_bind_varchar (default for string-shaped values)
};

struct Bindability {
bool bindable = false;
SqlParameterType type = SqlParameterType::Varchar;
};

// Pure helper. Stateless; safe to construct on demand at the call site.
//
// The classification rule is intentionally conservative: a field without
// any typed validator is NOT considered bindable, so the Mustache path
// remains the safe default during migration. Unknown validator type
// names also fall back to non-bindable for forward compatibility — a
// new validator added in a later version doesn't accidentally route
// through the prepared path before its binder has been written.
class SqlParameterClassifier {
public:
Bindability classify(const RequestFieldConfig& field) const;
};

} // namespace flapi
193 changes: 193 additions & 0 deletions src/prepared_template_rewriter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
#include "prepared_template_rewriter.hpp"

#include <algorithm>

#include "config_manager.hpp"

namespace flapi {

namespace {

// Tag types we recognise while scanning the template. `Sentinel` keeps
// the lexer code small without sprinkling magic chars.
enum class TagKind {
OpenSection, // {{#name}}
OpenInvertedSection, // {{^name}}
CloseSection, // {{/name}}
TripleBrace, // {{{ ... }}}
DoubleBrace, // {{ ... }}
NoTag,
};

struct TagScan {
TagKind kind = TagKind::NoTag;
std::size_t start = 0; // index of the first `{`
std::size_t end = 0; // one past the last `}`
std::string inner; // trimmed content between braces
};

void appendRange(std::string& out, const std::string& src, std::size_t a, std::size_t b) {
out.append(src, a, b - a);
}

std::string trim(std::string s) {
auto begin = std::find_if_not(s.begin(), s.end(), [](char c) { return c == ' ' || c == '\t'; });
s.erase(s.begin(), begin);
auto rend = std::find_if_not(s.rbegin(), s.rend(), [](char c) { return c == ' ' || c == '\t'; });
s.erase(rend.base(), s.end());
return s;
}

bool startsWith(const std::string& s, std::size_t from, const char* prefix) {
std::size_t n = 0;
while (prefix[n] != '\0') ++n;
if (s.size() < from + n) {
return false;
}
return s.compare(from, n, prefix) == 0;
}

// Find the next Mustache-ish tag starting at `from`. Returns NoTag when
// no further `{{` appears in the template.
TagScan nextTag(const std::string& s, std::size_t from) {
TagScan out;
const std::size_t open = s.find("{{", from);
if (open == std::string::npos) {
return out;
}
out.start = open;

// Triple-brace?
if (startsWith(s, open, "{{{")) {
const std::size_t close = s.find("}}}", open + 3);
if (close == std::string::npos) {
return out; // unterminated; treat as no-tag
}
out.kind = TagKind::TripleBrace;
out.end = close + 3;
out.inner = trim(s.substr(open + 3, close - (open + 3)));
return out;
}

const std::size_t close = s.find("}}", open + 2);
if (close == std::string::npos) {
return out;
}
out.end = close + 2;
std::string raw = s.substr(open + 2, close - (open + 2));
if (!raw.empty() && raw.front() == '#') {
out.kind = TagKind::OpenSection;
out.inner = trim(raw.substr(1));
} else if (!raw.empty() && raw.front() == '^') {
out.kind = TagKind::OpenInvertedSection;
out.inner = trim(raw.substr(1));
} else if (!raw.empty() && raw.front() == '/') {
out.kind = TagKind::CloseSection;
out.inner = trim(raw.substr(1));
} else {
out.kind = TagKind::DoubleBrace;
out.inner = trim(raw);
}
return out;
}

// Extract X from "params.X". Returns empty string when the expression
// doesn't have the expected shape.
std::string paramName(const std::string& inner) {
static const std::string kPrefix = "params.";
if (inner.compare(0, kPrefix.size(), kPrefix) != 0) {
return {};
}
return inner.substr(kPrefix.size());
}

const RequestFieldConfig* findField(const std::string& name,
const std::vector<RequestFieldConfig>& fields) {
for (const auto& f : fields) {
if (f.fieldName == name) {
return &f;
}
}
return nullptr;
}

} // namespace

PreparedRewriteResult PreparedTemplateRewriter::rewrite(
const std::string& template_text,
const std::vector<RequestFieldConfig>& request_fields,
const SqlParameterClassifier& classifier) const {

PreparedRewriteResult result;
result.rewritten_template.reserve(template_text.size());

std::size_t cursor = 0;
int section_depth = 0;

while (cursor < template_text.size()) {
const TagScan tag = nextTag(template_text, cursor);
if (tag.kind == TagKind::NoTag) {
appendRange(result.rewritten_template, template_text, cursor, template_text.size());
break;
}

// Copy untouched text up to the tag.
appendRange(result.rewritten_template, template_text, cursor, tag.start);

switch (tag.kind) {
case TagKind::OpenSection:
case TagKind::OpenInvertedSection:
++section_depth;
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
case TagKind::CloseSection:
if (section_depth > 0) {
--section_depth;
}
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
case TagKind::TripleBrace:
// Out of scope for PR A — operators migrate triple-brace
// sites manually (drop surrounding quotes, switch to
// double-brace) before they become bindable.
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
case TagKind::DoubleBrace: {
if (section_depth > 0) {
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
}
const std::string name = paramName(tag.inner);
if (name.empty()) {
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
}
const RequestFieldConfig* field = findField(name, request_fields);
if (field == nullptr) {
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
}
const auto bindability = classifier.classify(*field);
if (!bindability.bindable) {
appendRange(result.rewritten_template, template_text, tag.start, tag.end);
break;
}
result.rewritten_template += '?';
PreparedBindingSpec spec;
spec.field_name = name;
spec.type = bindability.type;
spec.position = result.bindings.size();
result.bindings.push_back(std::move(spec));
break;
}
case TagKind::NoTag:
break; // unreachable; satisfied by the early break above
}

cursor = tag.end;
}

return result;
}

} // namespace flapi
56 changes: 56 additions & 0 deletions src/sql_parameter_classifier.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include "sql_parameter_classifier.hpp"

#include "config_manager.hpp"

namespace flapi {

namespace {

// Returns `true` and sets `out` when `type_name` maps to a bindable
// SqlParameterType; otherwise returns `false` and leaves `out` untouched.
// Comparison is case-sensitive on purpose — see the test rationale.
bool tryMapType(const std::string& type_name, SqlParameterType& out) {
if (type_name == "int" || type_name == "integer") {
out = SqlParameterType::Integer;
return true;
}
if (type_name == "number" || type_name == "float" || type_name == "double") {
out = SqlParameterType::Double;
return true;
}
if (type_name == "boolean" || type_name == "bool") {
out = SqlParameterType::Boolean;
return true;
}
if (type_name == "date") {
out = SqlParameterType::Date;
return true;
}
if (type_name == "time") {
out = SqlParameterType::Time;
return true;
}
if (type_name == "uuid" || type_name == "string" || type_name == "email" ||
type_name == "enum") {
out = SqlParameterType::Varchar;
return true;
}
return false;
}

} // namespace

Bindability SqlParameterClassifier::classify(const RequestFieldConfig& field) const {
Bindability result;
for (const auto& validator : field.validators) {
SqlParameterType mapped = SqlParameterType::Varchar;
if (tryMapType(validator.type, mapped)) {
result.bindable = true;
result.type = mapped;
return result; // first known type wins, for determinism
}
}
return result; // bindable stays false
}

} // namespace flapi
2 changes: 2 additions & 0 deletions test/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ add_executable(flapi_tests
query_executor_test.cpp
rate_limit_middleware_test.cpp
request_handler_test.cpp
prepared_template_rewriter_test.cpp
request_validator_test.cpp
security_auditor_test.cpp
sql_parameter_classifier_test.cpp
sql_template_processor_test.cpp
sql_utils_test.cpp
test_duckdb_raii.cpp
Expand Down
Loading
Loading