Capstone: a constexpr SQL in C++26 #
Why a constexpr EDSL #
A domain‑specific language (DSL) that runs at compile time gives the same safety as a Lisp macro system but without textual substitution. The query is parsed, type‑checked, and turned into data while the compiler translates the translation unit, so a malformed query produces a compilation error instead of a runtime failure. This idea follows the term‑rewriting view of templates (chapter 16) and the compile‑time execution model (chapter 18).
The lineage is clear. Deane and Turner demonstrated a constexpr JSON parser that turned a string literal into a constexpr data structure. CTParser and the CTRE library later showed how regular‑expression‑based parsers can live in consteval functions. More recently, mkitzan’s constexpr‑sql project combined those ideas to build a tiny SQL‑like EDSL. The capstone brings those ingredients together in a single, self‑contained example.
A constexpr EDSL is not a new parser library bolted onto the build. It uses the same term‑rewriting machinery as the template system applied to a string literal. The query becomes compiler data, not a runtime command, so the compiler checks every branch as it evaluates. A compile‑time failure is the cheapest failure because it occurs before the binary exists and names the exact erroneous query text. Consequently, the compiler acts as the test runner and the query literal serves as the fixture, eliminating the need for a separate runtime test harness.
A compile-time failure is the cheapest kind of failure, because it happens before the binary exists and names the exact query text that is wrong. A runtime test needs a runner, an assertion library, and a suite to maintain. Here the compiler is the runner and the query literal is the fixture.
The building blocks #
The capstone re‑uses exactly the mechanisms introduced earlier:
fixed_stringNTTP (chapter 19) carries the query literal as a non‑type template parameter.consteval(chapter 18) forces the parser to run during translation.constexprcontainers:std::arrayandstd::vectorwith transient allocation hold tables and query results entirely at compile time.if constexprselects between the supported comparison operators without generating unreachable code.
No other library is required. The whole program lives in a single source file, and each piece (fixed_string, consteval, and constexpr containers) is a plain, non‑exotic component whose combination yields a real, self‑checking domain language without any runtime component.
The schema as aggregates #
A table row is a plain aggregate struct, exactly as in chapter 3:
struct Row {
int id;
int value;
};
A table is a constexpr array of those rows:
constexpr Row table[] = {
{1, 10},
{2, 20},
{3, 30},
};
Column names are represented by fixed_string NTTPs. The parser extracts the name from the query text, stores it in a constexpr structure, and later matches it against the members of Row.
Keeping the schema as aggregates is deliberate. Because Row is an aggregate and the table is a constexpr array, the compiler can fold the whole table into a constant at translation time, with no allocation, no constructor, and no pointer indirection at runtime. The same reasoning that made std::array the right container in chapter 11 applies here with extra force.
The aggregate discipline also pays off when the schema grows. Adding a column is a one-line change to Row, and the parser and evaluator read the members by name through fixed_string, so no extra wiring is needed for the new field.
Parsing the query at compile time #
The parser is a tiny recursive‑descent engine written as a consteval function. It operates on the character buffer of a fixed_string and produces a Query object.
template<std::size_t N>
struct fixed_string {
char data[N + 1]{};
constexpr fixed_string(const char (&s)[N + 1]) {
for (std::size_t i = 0; i < N; ++i) data[i] = s[i];
data[N] = '\0';
}
constexpr const char* c_str() const { return data; }
};
struct Query {
fixed_string<16> select; // column after SELECT
fixed_string<16> where; // column after WHERE
char op; // comparison operator, currently '>' only
int rhs; // right‑hand side constant
};
// Very small helper that skips whitespace
consteval const char* skip_ws(const char* p) {
while (*p == ' ' || *p == '\t' || *p == '\n') ++p;
return p;
}
// Reads an identifier up to the next whitespace or delimiter
consteval std::size_t read_ident(const char* p, char* out) {
std::size_t i = 0;
while (*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != ',' && *p != ';') {
out[i++] = *p++;
}
out[i] = '\0';
return i;
}
consteval int read_number(const char* p, const char*& end) {
int value = 0;
while (*p >= '0' && *p <= '9') {
value = value * 10 + (*p - '0');
++p;
}
end = p;
return value;
}
// Compile‑time parser for the supported subset
consteval Query parse_query(const char* qs) {
const char* p = qs;
p = skip_ws(p);
// SELECT keyword (assumed present)
p += 6; // skip "SELECT"
p = skip_ws(p);
char sel[17]{}; read_ident(p, sel);
p += std::char_traits<char>::length(sel);
p = skip_ws(p);
// FROM keyword (ignored, table name is fixed)
p += 4; // skip "FROM"
p = skip_ws(p);
while (*p && *p != ' ') ++p; // skip table identifier
p = skip_ws(p);
// WHERE keyword
p += 5; // skip "WHERE"
p = skip_ws(p);
char wh[17]{}; read_ident(p, wh);
p += std::char_traits<char>::length(wh);
p = skip_ws(p);
// operator – only '>' is accepted
char op = *p;
++p; p = skip_ws(p);
const char* num_end;
int rhs = read_number(p, num_end);
Query q{};
q.select = fixed_string<16>{sel};
q.where = fixed_string<16>{wh};
q.op = op;
q.rhs = rhs;
return q;
}
If the input deviates from the supported grammar, a static_assert aborts compilation with a clear diagnostic.
The parser is deliberately simple: it walks the buffer, skips whitespace, reads a column name, skips the fixed keywords, and parses one number. There is no token vector and no abstract syntax tree. Each keyword offset is hard-coded because the grammar fixes the order, so the scanner never needs lookahead. This is the minimum structure that still shows the shape of a real recursive-descent parser.
Producing the result rows #
The evaluator walks the constexpr table, applies the predicate, and writes matching values into a fixed‑size std::array. The size of the array is the maximum possible number of rows. The unused slots remain zero.
consteval std::array<int, 3> eval(const Query& q) {
std::array<int, 3> out{{0, 0, 0}};
std::size_t idx = 0;
for (const Row& r : table) {
int lhs = (std::string_view(q.where.c_str()) == "value") ? r.value : 0;
bool ok = false;
if (q.op == '>') ok = lhs > q.rhs;
if (ok) {
out[idx++] = (std::string_view(q.select.c_str()) == "id") ? r.id : r.value;
}
}
return out;
}
Returning a fixed-size array is a deliberate simplification. A std::vector is more natural, but a fixed array makes the compile-time result easier to reason about and avoids relying on the details of transient allocation. The WHERE column is looked up by name at compile time with a string comparison against the members.
The static_assert test suite #
The capstone follows the chapter‑18 convention of using static_assert as the only test harness. The main function prints a short marker so that the CTest PASS_REGULAR_EXPRESSION matches something.
int main() {
// The query is parsed at compile time; any syntax error aborts compilation.
constexpr auto q = parse_query("SELECT id FROM table WHERE value > 15");
static_assert(std::string_view(q.select.c_str()) == "id", "wrong SELECT column");
static_assert(std::string_view(q.where.c_str()) == "value", "wrong WHERE column");
static_assert(q.rhs == 15, "wrong constant");
constexpr auto result = eval(q);
static_assert(result[0] == 2, "first matching id");
static_assert(result[1] == 3, "second matching id");
std::cout << "constexpr‑SQL capstone OK" << '\n';
}
If any of the static_asserts fail, compilation stops and the programmer receives the message. The binary itself prints only a marker. The real verification lives in the compile‑time checks.
Compiling this file is the test. If any assertion fails, the build stops before a single instruction is executed, and the diagnostic names the failed predicate and the offending constant. There is nothing to run, nothing to instrument, and no chance of a false green from a test that forgot to check. This is the chapter-18 convention applied to a whole program.
Where the capstone stops #
The implementation deliberately covers a narrow subset of SQL: a single SELECT column, a single table name (hard‑coded), and a single numeric column in the WHERE clause with the > operator. Extending the parser to recognise additional comparison operators, logical conjunctions, multiple columns, or joins calls for a larger grammar, more token types, and a recursive-descent engine that can build an abstract syntax tree. The same compile-time techniques, namely consteval functions, if constexpr dispatch, and constexpr containers, apply, but the code size grows quickly.
None of the omitted features is impossible. Each is simply more code. A <= operator is one more branch. String columns need a length-aware comparison. Multiple columns need the parser to build a small list of names. The point of the subset is to show the technique works and to keep the example short enough to read in one pass.
Static reflection preview (PROSE ONLY) #
C++26 defines a static‑reflection proposal (P2996) that introduces the ^^T operator, std::meta::info, and splicing syntax. In theory those facilities can replace the hand‑written tokenizer with a compile‑time inspection of the query string literal, and they can generate the Query structure automatically.
Not yet deployable.
The feature currently compiles only with GCC 16 (partial support) and is absent from Clang 22.1.8, which the book’s toolchain pins. The capstone therefore implements the parser manually.
When reflection lands, much of this machinery collapses. A compiler-provided ^^T splice can walk the query literal and build the Query directly, and a future library can generate the evaluator from the schema. Until then, the manual parser is the honest, portable baseline that every compiler supports.
Try this #
Extend the parser to support a second comparison operator (<). Add a static_assert that a query using < selects the correct rows.