Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
QueryBuilder.hpp
Go to the documentation of this file.
1#pragma once
3#include <string>
4#include <string_view>
5#include <vector>
6#include <memory>
7#include <optional>
8#include <coroutine>
9#include <sstream>
10#include <stdexcept>
11#include <type_traits>
12#include <limits>
13#include <charconv>
14#include <cstdlib>
15#include <orbit/http/json.hpp>
17#ifdef ORBIT_ENABLE_POSTGRES
18// database::query_async, used for every client that is not MySQL/MariaDB.
20#endif
21
22namespace orbit::orm {
23
28using Params = std::vector<std::optional<std::string>>;
29
30namespace detail {
31
38inline bool is_identifier(std::string_view s) {
39 if (s.empty()) return false;
40 bool part_start = true;
41 for (char c : s) {
42 if (c == '.') {
43 if (part_start) return false;
44 part_start = true;
45 continue;
46 }
47 bool alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
48 bool digit = (c >= '0' && c <= '9');
49 if (!(alpha || (digit && !part_start))) return false;
50 part_start = false;
51 }
52 return !part_start;
53}
54
55inline const std::string& checked_identifier(const std::string& s) {
56 if (!is_identifier(s)) throw std::invalid_argument("Invalid SQL identifier: " + s);
57 return s;
58}
59
63inline bool is_reserved_word(std::string_view s) {
64 static const char* const words[] = {
65 "all", "and", "any", "as", "asc", "between", "both", "by", "case", "check", "column", "constraint",
66 "create", "cross", "current_date", "current_time", "current_timestamp", "current_user", "default",
67 "delete", "desc", "distinct", "do", "else", "end", "except", "exists", "false", "fetch", "for",
68 "foreign", "from", "full", "grant", "group", "having", "in", "index", "inner", "insert", "intersect",
69 "into", "is", "join", "key", "leading", "left", "like", "limit", "natural", "not", "null", "offset",
70 "on", "only", "or", "order", "outer", "primary", "references", "returning", "right", "select",
71 "session_user", "set", "some", "table", "then", "to", "trailing", "true", "union", "unique", "update",
72 "user", "using", "values", "when", "where", "window", "with"};
73 std::string lower(s);
74 for (char& c : lower) c = static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);
75 for (const char* w : words) {
76 if (lower == w) return true;
77 }
78 return false;
79}
80
84inline constexpr char kQuoteMark = '\x01';
85
91inline std::string ident(const std::string& name) {
93 std::string out;
94 size_t start = 0;
95 while (true) {
96 size_t dot = name.find('.', start);
97 std::string part = name.substr(start, dot == std::string::npos ? std::string::npos : dot - start);
98 if (is_reserved_word(part)) out += kQuoteMark + part + kQuoteMark;
99 else out += part;
100 if (dot == std::string::npos) break;
101 out += '.';
102 start = dot + 1;
103 }
104 return out;
105}
106
108inline std::string render_identifiers(std::string sql, bool mysql) {
109 for (char& c : sql) {
110 if (c == kQuoteMark) c = mysql ? '`' : '"';
111 }
112 return sql;
113}
114
115inline const std::string& checked_operator(const std::string& op) {
116 static const char* const allowed[] = {"=", "!=", "<>", "<", "<=", ">", ">=", "LIKE", "NOT LIKE", "ILIKE", "NOT ILIKE"};
117 for (const char* a : allowed) {
118 if (op == a) return op;
119 }
120 throw std::invalid_argument("Unsupported SQL comparison operator: " + op);
121}
122
123template <typename T>
124std::optional<std::string> to_param(const T& val) {
125 if constexpr (std::is_same_v<T, bool>) {
126 return std::string(val ? "1" : "0"); // valid for PostgreSQL booleans and MySQL TINYINT(1)
127 } else if constexpr (std::is_integral_v<T>) {
128 return std::to_string(val);
129 } else if constexpr (std::is_floating_point_v<T>) {
130 std::ostringstream os;
131 os.precision(std::numeric_limits<T>::max_digits10);
132 os << val;
133 return os.str();
134 } else {
135 return std::string(val);
136 }
137}
138
139inline std::optional<std::string> json_to_param(const nlohmann::json& v) {
140 if (v.is_null()) return std::nullopt;
141 if (v.is_string()) return v.get<std::string>();
142 if (v.is_boolean()) return std::string(v.get<bool>() ? "1" : "0");
143 return v.dump(); // numbers, and objects/arrays as JSON text
144}
145
147inline std::string number_placeholders(const std::string& sql) {
148 std::string out;
149 out.reserve(sql.size() + 8);
150 int n = 0;
151 for (char c : sql) {
152 if (c == '?') out += "$" + std::to_string(++n);
153 else out.push_back(c);
154 }
155 return out;
156}
157
159template <typename Escape>
160std::string inline_literals(const std::string& sql, const Params& params, Escape&& escape) {
161 std::string out;
162 size_t i = 0;
163 for (char c : sql) {
164 if (c != '?') {
165 out.push_back(c);
166 continue;
167 }
168 if (i >= params.size()) throw std::logic_error("Fewer parameters than placeholders");
169 const auto& p = params[i++];
170 out += p ? "'" + escape(*p) + "'" : std::string("NULL");
171 }
172 return out;
173}
174
175} // namespace detail
176
180struct Expr {
181 std::string sql;
183
184 Expr operator&&(const Expr& other) const {
185 Params combined = params;
186 combined.insert(combined.end(), other.params.begin(), other.params.end());
187 return Expr{"(" + sql + " AND " + other.sql + ")", std::move(combined)};
188 }
189
190 Expr operator||(const Expr& other) const {
191 Params combined = params;
192 combined.insert(combined.end(), other.params.begin(), other.params.end());
193 return Expr{"(" + sql + " OR " + other.sql + ")", std::move(combined)};
194 }
195};
196
203class Col {
204public:
205 explicit Col(std::string name) : name_(detail::ident(name)) {}
206
207 template <typename T>
208 Expr operator==(const T& val) const { return make("=", val); }
209
210 template <typename T>
211 Expr operator!=(const T& val) const { return make("!=", val); }
212
213 template <typename T>
214 Expr operator>(const T& val) const { return make(">", val); }
215
216 template <typename T>
217 Expr operator<(const T& val) const { return make("<", val); }
218
219 template <typename T>
220 Expr operator>=(const T& val) const { return make(">=", val); }
221
222 template <typename T>
223 Expr operator<=(const T& val) const { return make("<=", val); }
224
225private:
226 std::string name_;
227
228 template <typename T>
229 Expr make(const char* op, const T& val) const {
230 return Expr{name_ + " " + op + " ?", {detail::to_param(val)}};
231 }
232};
233
242template <typename DBClient>
243constexpr bool is_mysql_client() {
244 return requires(std::shared_ptr<DBClient> c) { c->escape(std::string{}); };
245}
246
247template <typename DBClient>
248auto do_query_async(std::shared_ptr<DBClient> client, const std::string& sql, const Params& params) {
249 constexpr bool mysql = is_mysql_client<DBClient>();
250 std::string rendered = detail::render_identifiers(sql, mysql);
251 if constexpr (mysql) {
252 return client->query_async(detail::inline_literals(rendered, params, [&](const std::string& v) { return client->escape(v); }));
253 } else {
254#ifdef ORBIT_ENABLE_POSTGRES
255 return database::query_async(client, detail::number_placeholders(rendered), params);
256#else
257 static_assert(!std::is_same_v<DBClient, DBClient>,
258 "this ORM client needs PostgreSQL support, which this build of Orbit leaves out (ORBIT_ENABLE_POSTGRES=OFF)");
259#endif
260 }
261}
262
264struct Statement {
265 std::string sql;
267};
268
270enum class Order { Asc, Desc };
271
279class DatabaseError : public std::runtime_error {
280public:
281 using std::runtime_error::runtime_error;
282};
283
284namespace detail {
285
286inline void throw_if_failed(const database::ResultSet& rs) {
287 if (!rs.ok()) throw DatabaseError(rs.error());
288}
289
291inline bool is_unset_key(const nlohmann::json& v) {
292 return v.is_null() || (v.is_number_integer() && v.get<long long>() == 0) ||
293 (v.is_number_unsigned() && v.get<unsigned long long>() == 0) ||
294 (v.is_string() && v.get<std::string>().empty());
295}
296
298inline nlohmann::json typed_value(const std::string& text, const nlohmann::json& proto) {
299 switch (proto.type()) {
300 case nlohmann::json::value_t::string:
301 return text;
302 case nlohmann::json::value_t::boolean:
303 if (text == "t" || text == "true" || text == "TRUE" || text == "1") return true;
304 if (text == "f" || text == "false" || text == "FALSE" || text == "0") return false;
305 break;
306 case nlohmann::json::value_t::number_integer: {
307 long long v = 0;
308 auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), v);
309 if (ec == std::errc() && end == text.data() + text.size()) return v;
310 break;
311 }
312 case nlohmann::json::value_t::number_unsigned: {
313 unsigned long long v = 0;
314 auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), v);
315 if (ec == std::errc() && end == text.data() + text.size()) return v;
316 break;
317 }
318 case nlohmann::json::value_t::number_float: {
319 char* end = nullptr;
320 double v = std::strtod(text.c_str(), &end);
321 if (!text.empty() && end == text.c_str() + text.size()) return v;
322 break;
323 }
326 auto parsed = nlohmann::json::parse(text, nullptr, false);
327 if (!parsed.is_discarded()) return parsed;
328 break;
329 }
330 default:
331 break;
332 }
333 return text; // leaves the mismatch to the model's from_json (reported below)
334}
335
348template <typename ModelType>
349std::vector<ModelType> rows_to_models(const database::ResultSet& rs) {
350 std::vector<ModelType> out;
351 out.reserve(rs.size());
352 nlohmann::json shape;
353 if constexpr (std::is_default_constructible_v<ModelType>) shape = ModelType{};
354 for (const auto& row : rs.rows()) {
355 nlohmann::json j = row.to_json();
356 if (shape.is_object()) {
357 for (const auto& [key, proto] : shape.items()) {
358 auto it = j.find(key);
359 if (it == j.end()) {
360 j[key] = proto; // column not selected: the field's default
361 } else if (!it->is_null()) {
362 auto text = row.get(key);
363 if (text) *it = typed_value(*text, proto);
364 }
365 }
366 }
367 try {
368 out.push_back(j.get<ModelType>());
369 } catch (const nlohmann::json::exception& e) {
370 throw DatabaseError(std::string("row does not fit the model: ") + e.what());
371 }
372 }
373 return out;
374}
375
376} // namespace detail
377
378template <typename DBClient, typename ModelType>
380 using NativeAwaiter = decltype(do_query_async(std::declval<std::shared_ptr<DBClient>>(), std::declval<std::string>(), std::declval<Params>()));
382
383 bool await_ready() const { return native_awaiter.await_ready(); }
384 void await_suspend(std::coroutine_handle<> h) { native_awaiter.await_suspend(h); }
385
386 std::vector<ModelType> await_resume() {
387 database::ResultSet rs = native_awaiter.await_resume();
389 return detail::rows_to_models<ModelType>(rs);
390 }
391};
392
393template <typename DBClient, typename ModelType>
395 using NativeAwaiter = decltype(do_query_async(std::declval<std::shared_ptr<DBClient>>(), std::declval<std::string>(), std::declval<Params>()));
397
398 bool await_ready() const { return native_awaiter.await_ready(); }
399 void await_suspend(std::coroutine_handle<> h) { native_awaiter.await_suspend(h); }
400
401 uint64_t await_resume() {
402 database::ResultSet rs = native_awaiter.await_resume();
403 detail::throw_if_failed(rs); // a failed write is an error, not "0 rows"
404 return rs.affected_rows();
405 }
406};
407
408template <typename DBClient>
410 using NativeAwaiter = decltype(do_query_async(std::declval<std::shared_ptr<DBClient>>(), std::declval<std::string>(), std::declval<Params>()));
412
413 bool await_ready() const { return native_awaiter.await_ready(); }
414 void await_suspend(std::coroutine_handle<> h) { native_awaiter.await_suspend(h); }
415
416 uint64_t await_resume() {
417 database::ResultSet rs = native_awaiter.await_resume();
419 if (rs.size() == 0) return 0;
420 std::string text = rs[0].get(0).value_or("0");
421 uint64_t n = 0;
422 std::from_chars(text.data(), text.data() + text.size(), n);
423 return n;
424 }
425};
426
428template <typename DBClient, typename ModelType>
430 using NativeAwaiter = decltype(do_query_async(std::declval<std::shared_ptr<DBClient>>(), std::declval<std::string>(), std::declval<Params>()));
432
433 bool await_ready() const { return native_awaiter.await_ready(); }
434 void await_suspend(std::coroutine_handle<> h) { native_awaiter.await_suspend(h); }
435
436 ModelType await_resume() {
437 database::ResultSet rs = native_awaiter.await_resume();
439 auto rows = detail::rows_to_models<ModelType>(rs);
440 if (rows.empty()) throw DatabaseError("INSERT ... RETURNING returned no row");
441 return std::move(rows.front());
442 }
443};
444
452template <typename DBClient, typename ModelType>
454public:
456 QueryBuilder(std::shared_ptr<DBClient> db, const std::string& table)
457 : db_(std::move(db)), table_(detail::ident(table)) {}
458
464 QueryBuilder& where(const std::string& field, const std::string& op, const std::string& val) {
465 wheres_.push_back(Expr{detail::ident(field) + " " + detail::checked_operator(op) + " ?", {val}});
466 return *this;
467 }
468
474 QueryBuilder& where(const Expr& expr) {
475 wheres_.push_back(expr);
476 return *this;
477 }
478
481 QueryBuilder& order_by(const std::string& field, Order direction = Order::Asc) {
482 orders_.push_back(detail::ident(field) + (direction == Order::Desc ? " DESC" : " ASC"));
483 return *this;
484 }
485
487 QueryBuilder& limit(uint64_t n) {
488 limit_ = n;
489 return *this;
490 }
491
493 QueryBuilder& offset(uint64_t n) {
494 offset_ = n;
495 return *this;
496 }
497
502 all_rows_ = true;
503 return *this;
504 }
505
514 QueryBuilder& primary_key(const std::string& column) {
515 detail::ident(column); // validates
516 primary_key_ = column;
517 return *this;
518 }
519
526 Statement insert_statement(const ModelType& model, bool returning = false) const {
527 nlohmann::json j = model;
528 if (!j.is_object()) throw std::invalid_argument("a model must serialise to a JSON object");
529 auto key = j.find(primary_key_);
530 if (key != j.end() && detail::is_unset_key(*key)) j.erase(key);
531 if (j.empty()) throw std::invalid_argument("insert needs at least one column besides an unset primary key");
532 std::string cols;
533 std::string vals;
534 Statement st;
535 bool first = true;
536 for (auto& el : j.items()) {
537 if (!first) { cols += ", "; vals += ", "; }
538 cols += detail::ident(el.key());
539 vals += "?";
540 st.params.push_back(detail::json_to_param(el.value()));
541 first = false;
542 }
543 st.sql = "INSERT INTO " + table_ + " (" + cols + ") VALUES (" + vals + ")";
544 if (returning) st.sql += " RETURNING *";
545 return finish(st);
546 }
547
550 Statement st{"SELECT * FROM " + table_, {}};
551 append_where(st);
552 if (!orders_.empty()) {
553 st.sql += " ORDER BY ";
554 for (size_t i = 0; i < orders_.size(); ++i) st.sql += (i ? ", " : "") + orders_[i];
555 }
556 // Integers, not parameters: MySQL rejects a quoted LIMIT value.
557 if (limit_) {
558 st.sql += " LIMIT " + std::to_string(*limit_);
559 } else if (offset_ && is_mysql_client<DBClient>()) {
560 st.sql += " LIMIT 18446744073709551615"; // MySQL has no OFFSET without LIMIT
561 }
562 if (offset_) st.sql += " OFFSET " + std::to_string(*offset_);
563 return finish(st);
564 }
565
568 Statement st{"SELECT COUNT(*) AS n FROM " + table_, {}};
569 append_where(st);
570 return finish(st);
571 }
572
581 if (!changes.is_object() || changes.empty()) {
582 throw std::invalid_argument("update needs a JSON object with at least one column");
583 }
584 require_condition("update");
585 Statement st{"UPDATE " + table_ + " SET ", {}};
586 bool first = true;
587 for (auto& el : changes.items()) {
588 st.sql += (first ? "" : ", ") + detail::ident(el.key()) + " = ?";
589 st.params.push_back(detail::json_to_param(el.value()));
590 first = false;
591 }
592 append_where(st);
593 return finish(st);
594 }
595
599 require_condition("delete");
600 Statement st{"DELETE FROM " + table_, {}};
601 append_where(st);
602 return finish(st);
603 }
604
612
618
629
633 nlohmann::json changes = model;
634 if (changes.is_object()) changes.erase(primary_key_);
635 return update_async(changes);
636 }
637
643
657
674
675private:
676 std::shared_ptr<DBClient> db_;
677 std::string table_;
678 std::vector<Expr> wheres_;
679 std::vector<std::string> orders_;
680 std::optional<uint64_t> limit_;
681 std::optional<uint64_t> offset_;
682 bool all_rows_ = false;
683 std::string primary_key_ = "id";
684
685 void append_where(Statement& st) const {
686 if (wheres_.empty()) return;
687 st.sql += " WHERE ";
688 for (size_t i = 0; i < wheres_.size(); ++i) {
689 if (i > 0) st.sql += " AND ";
690 st.sql += wheres_[i].sql;
691 st.params.insert(st.params.end(), wheres_[i].params.begin(), wheres_[i].params.end());
692 }
693 }
694
695 void require_condition(const char* what) const {
696 if (wheres_.empty() && !all_rows_) {
697 throw std::logic_error(std::string(what) + " without a where() condition; call all() to affect every row");
698 }
699 }
700
702 st.sql = detail::render_identifiers(std::move(st.sql), is_mysql_client<DBClient>());
703 return st;
704 }
705};
706
707} // namespace orm
a class to store JSON values
Definition json.hpp:19401
iterator end() noexcept
returns an iterator to one past the last element
Definition json.hpp:22095
iteration_proxy< iterator > items() noexcept
helper to access iterator member functions in range-based for
Definition json.hpp:22185
constexpr bool is_string() const noexcept
return whether value is a string
Definition json.hpp:20673
static basic_json parse(InputType &&i, const parser_callback_t cb=nullptr, const bool allow_exceptions=true, const bool ignore_comments=false)
deserialize from a compatible input
Definition json.hpp:23317
constexpr bool is_number_integer() const noexcept
return whether value is an integer number
Definition json.hpp:20638
constexpr bool is_boolean() const noexcept
return whether value is a boolean
Definition json.hpp:20624
IteratorType erase(IteratorType pos)
remove element given an iterator
Definition json.hpp:21731
constexpr bool is_object() const noexcept
return whether value is an object
Definition json.hpp:20659
bool empty() const noexcept
checks whether the container is empty.
Definition json.hpp:22208
constexpr value_t type() const noexcept
return the type of the JSON value (explicit)
Definition json.hpp:20596
constexpr bool is_number_unsigned() const noexcept
return whether value is an unsigned integer number
Definition json.hpp:20645
string_t dump(const int indent=-1, const char indent_char=' ', const bool ensure_ascii=false, const error_handler_t error_handler=error_handler_t::strict) const
serialization
Definition json.hpp:20574
constexpr bool is_null() const noexcept
return whether value is null
Definition json.hpp:20617
auto get() const noexcept(noexcept(std::declval< const basic_json_t & >().template get_impl< ValueType >(detail::priority_tag< 4 > {}))) -> decltype(std::declval< const basic_json_t & >().template get_impl< ValueType >(detail::priority_tag< 4 > {}))
get a (pointer) value (explicit)
Definition json.hpp:21046
static basic_json array(initializer_list_t init={})
explicitly create an array from an initializer list
Definition json.hpp:20307
static basic_json object(initializer_list_t init={})
explicitly create an object from an initializer list
Definition json.hpp:20315
iterator find(const typename object_t::key_type &key)
find an element in a JSON object
Definition json.hpp:21953
general exception of the basic_json class
Definition json.hpp:4372
const char * what() const noexcept override
returns the explanatory string
Definition json.hpp:4375
Represents a generic, unified result set from a database query.
Definition ResultSet.hpp:197
const std::string & error() const
Definition ResultSet.hpp:213
const std::vector< Row > & rows() const
Definition ResultSet.hpp:215
uint64_t affected_rows() const
Definition ResultSet.hpp:218
bool ok() const
False if the query failed; error() then says why.
Definition ResultSet.hpp:212
size_t size() const
Definition ResultSet.hpp:216
A database column, allowing C++ operators to build parameterized SQL conditions.
Definition QueryBuilder.hpp:203
Expr operator<(const T &val) const
Definition QueryBuilder.hpp:217
Expr make(const char *op, const T &val) const
Definition QueryBuilder.hpp:229
Expr operator<=(const T &val) const
Definition QueryBuilder.hpp:223
Expr operator>=(const T &val) const
Definition QueryBuilder.hpp:220
Expr operator>(const T &val) const
Definition QueryBuilder.hpp:214
Col(std::string name)
Definition QueryBuilder.hpp:205
Expr operator!=(const T &val) const
Definition QueryBuilder.hpp:211
Expr operator==(const T &val) const
Definition QueryBuilder.hpp:208
std::string name_
Definition QueryBuilder.hpp:226
A query run by the ORM failed, or its rows did not fit the model.
Definition QueryBuilder.hpp:279
A lightweight, JSON-backed ORM Query Builder with bound parameters.
Definition QueryBuilder.hpp:453
QueryBuilder & where(const Expr &expr)
Definition QueryBuilder.hpp:474
bool all_rows_
Definition QueryBuilder.hpp:682
std::vector< std::string > orders_
Definition QueryBuilder.hpp:679
Statement select_statement() const
The SELECT that get_async() runs (placeholders as ?).
Definition QueryBuilder.hpp:549
QueryInsertAwaiter< DBClient, ModelType > insert_async(const ModelType &model)
Executes an INSERT query for a model, binding every value.
Definition QueryBuilder.hpp:653
QueryGetAwaiter< DBClient, ModelType > get_async()
Executes a SELECT query asynchronously and maps results to a vector of ModelType.
Definition QueryBuilder.hpp:608
std::vector< Expr > wheres_
Definition QueryBuilder.hpp:678
QueryBuilder & offset(uint64_t n)
Skips the first n rows (use with order_by() for stable pages).
Definition QueryBuilder.hpp:493
QueryBuilder & order_by(const std::string &field, Order direction=Order::Asc)
Definition QueryBuilder.hpp:481
QueryInsertAwaiter< DBClient, ModelType > remove_async()
Deletes the matching rows; resumes with the number affected.
Definition QueryBuilder.hpp:639
QueryBuilder & limit(uint64_t n)
Returns at most n rows.
Definition QueryBuilder.hpp:487
Statement count_statement() const
The SELECT COUNT(*) that count_async() runs.
Definition QueryBuilder.hpp:567
void append_where(Statement &st) const
Definition QueryBuilder.hpp:685
std::string table_
Definition QueryBuilder.hpp:677
QueryBuilder & primary_key(const std::string &column)
The model's primary key column (default "id").
Definition QueryBuilder.hpp:514
std::optional< uint64_t > offset_
Definition QueryBuilder.hpp:681
QueryBuilder & all()
Definition QueryBuilder.hpp:501
std::string primary_key_
Definition QueryBuilder.hpp:683
std::optional< uint64_t > limit_
Definition QueryBuilder.hpp:680
Statement insert_statement(const ModelType &model, bool returning=false) const
The INSERT that insert_async() runs (create_async() adds RETURNING *). An unset primary key is left o...
Definition QueryBuilder.hpp:526
QueryInsertAwaiter< DBClient, ModelType > update_async(const ModelType &model)
Definition QueryBuilder.hpp:632
QueryCreateAwaiter< DBClient, ModelType > create_async(const ModelType &model)
Inserts model and resumes with the row as stored, including the generated primary key and column defa...
Definition QueryBuilder.hpp:670
Statement delete_statement() const
Definition QueryBuilder.hpp:598
Statement update_statement(const nlohmann::json &changes) const
The UPDATE that update_async() runs.
Definition QueryBuilder.hpp:580
std::shared_ptr< DBClient > db_
Definition QueryBuilder.hpp:676
QueryCountAwaiter< DBClient > count_async()
Counts the matching rows.
Definition QueryBuilder.hpp:614
static Statement finish(Statement st)
Definition QueryBuilder.hpp:701
QueryBuilder(std::shared_ptr< DBClient > db, const std::string &table)
Definition QueryBuilder.hpp:456
QueryBuilder & where(const std::string &field, const std::string &op, const std::string &val)
Adds a WHERE condition. val is bound as a parameter.
Definition QueryBuilder.hpp:464
void require_condition(const char *what) const
Definition QueryBuilder.hpp:695
QueryInsertAwaiter< DBClient, ModelType > update_async(const nlohmann::json &changes)
Updates the matching rows; resumes with the number affected.
Definition QueryBuilder.hpp:625
QueryAwaiter query_async(std::shared_ptr< PostgresClient > client, const std::string &sql)
Creates an awaiter for executing a query on a PostgresClient.
Definition PostgresCoro.hpp:75
constexpr char kQuoteMark
Definition QueryBuilder.hpp:84
std::vector< ModelType > rows_to_models(const database::ResultSet &rs)
Maps result rows to models, converting each column by the type of the model's field rather than by gu...
Definition QueryBuilder.hpp:349
std::string inline_literals(const std::string &sql, const Params &params, Escape &&escape)
Replaces ? placeholders with escaped, quoted literals (for clients without parameter binding).
Definition QueryBuilder.hpp:160
bool is_identifier(std::string_view s)
True for a plain SQL identifier (name) or a qualified one (table.name): ASCII letters,...
Definition QueryBuilder.hpp:38
void throw_if_failed(const database::ResultSet &rs)
Definition QueryBuilder.hpp:286
std::optional< std::string > to_param(const T &val)
Definition QueryBuilder.hpp:124
std::string number_placeholders(const std::string &sql)
Rewrites ? placeholders as PostgreSQL's $1, $2, ...
Definition QueryBuilder.hpp:147
const std::string & checked_operator(const std::string &op)
Definition QueryBuilder.hpp:115
std::optional< std::string > json_to_param(const nlohmann::json &v)
Definition QueryBuilder.hpp:139
const std::string & checked_identifier(const std::string &s)
Definition QueryBuilder.hpp:55
bool is_unset_key(const nlohmann::json &v)
A key that the database should generate: null, 0, or an empty string.
Definition QueryBuilder.hpp:291
bool is_reserved_word(std::string_view s)
Definition QueryBuilder.hpp:63
std::string render_identifiers(std::string sql, bool mysql)
Replaces quote marks with " (PostgreSQL, standard SQL) or a backtick (MySQL).
Definition QueryBuilder.hpp:108
std::string ident(const std::string &name)
Validates an identifier (name or table.name) and marks the parts that are reserved words for quoting.
Definition QueryBuilder.hpp:91
nlohmann::json typed_value(const std::string &text, const nlohmann::json &proto)
Converts a column's text to the JSON type of the model field proto.
Definition QueryBuilder.hpp:298
Definition legacy_namespaces.hpp:23
std::vector< std::optional< std::string > > Params
Values bound to the ? placeholders of an expression, in order. std::nullopt binds SQL NULL.
Definition QueryBuilder.hpp:28
constexpr bool is_mysql_client()
Runs sql (with ? placeholders) on either client type.
Definition QueryBuilder.hpp:243
Order
Sort direction for QueryBuilder::order_by().
Definition QueryBuilder.hpp:270
auto do_query_async(std::shared_ptr< DBClient > client, const std::string &sql, const Params &params)
Definition QueryBuilder.hpp:248
Definition json.hpp:5363
A SQL condition with ? placeholders and the values bound to them.
Definition QueryBuilder.hpp:180
Expr operator||(const Expr &other) const
Definition QueryBuilder.hpp:190
Params params
Definition QueryBuilder.hpp:182
std::string sql
Definition QueryBuilder.hpp:181
Expr operator&&(const Expr &other) const
Definition QueryBuilder.hpp:184
Definition QueryBuilder.hpp:409
bool await_ready() const
Definition QueryBuilder.hpp:413
NativeAwaiter native_awaiter
Definition QueryBuilder.hpp:411
uint64_t await_resume()
Definition QueryBuilder.hpp:416
decltype(do_query_async(std::declval< std::shared_ptr< DBClient > >(), std::declval< std::string >(), std::declval< Params >())) NativeAwaiter
Definition QueryBuilder.hpp:410
void await_suspend(std::coroutine_handle<> h)
Definition QueryBuilder.hpp:414
Resumes with the row an INSERT ... RETURNING * stored.
Definition QueryBuilder.hpp:429
void await_suspend(std::coroutine_handle<> h)
Definition QueryBuilder.hpp:434
decltype(do_query_async(std::declval< std::shared_ptr< DBClient > >(), std::declval< std::string >(), std::declval< Params >())) NativeAwaiter
Definition QueryBuilder.hpp:430
NativeAwaiter native_awaiter
Definition QueryBuilder.hpp:431
bool await_ready() const
Definition QueryBuilder.hpp:433
ModelType await_resume()
Definition QueryBuilder.hpp:436
Definition QueryBuilder.hpp:379
bool await_ready() const
Definition QueryBuilder.hpp:383
void await_suspend(std::coroutine_handle<> h)
Definition QueryBuilder.hpp:384
decltype(do_query_async(std::declval< std::shared_ptr< DBClient > >(), std::declval< std::string >(), std::declval< Params >())) NativeAwaiter
Definition QueryBuilder.hpp:380
NativeAwaiter native_awaiter
Definition QueryBuilder.hpp:381
std::vector< ModelType > await_resume()
Definition QueryBuilder.hpp:386
Definition QueryBuilder.hpp:394
NativeAwaiter native_awaiter
Definition QueryBuilder.hpp:396
bool await_ready() const
Definition QueryBuilder.hpp:398
decltype(do_query_async(std::declval< std::shared_ptr< DBClient > >(), std::declval< std::string >(), std::declval< Params >())) NativeAwaiter
Definition QueryBuilder.hpp:395
void await_suspend(std::coroutine_handle<> h)
Definition QueryBuilder.hpp:399
uint64_t await_resume()
Definition QueryBuilder.hpp:401
A statement with ? placeholders and the values bound to them.
Definition QueryBuilder.hpp:264
std::string sql
Definition QueryBuilder.hpp:265
Params params
Definition QueryBuilder.hpp:266