载入中...
搜索中...
未找到
Database.h
浏览该文件的文档.
1#pragma once
2#include "common/Export.h"
3
4
5#include "common/Module.h"
6#include "common/Result.h"
7
8#include <cstdint>
9#include <functional>
10#include <memory>
11#include <stdexcept>
12#include <string>
13#include <unordered_map>
14#include <utility>
15#include <variant>
16#include <vector>
17
18namespace Poco::Data {
19class Session;
20}
21
22namespace eve::database {
23
24class Model;
25class Query;
26
27using Value = std::variant<std::monostate, std::int64_t, double, std::string, bool>;
28using Row = std::unordered_map<std::string, Value>;
29
31template <class T>
33struct Field {
34 std::string name;
36 std::function<Value(const T&)> read;
38 std::function<void(T&, const Value&)> write;
39 std::string sqlType = "TEXT";
40 bool primaryKey = false;
41};
42
43template <class T>
45struct Mapping {
46 std::string table;
47 std::vector<Field<T>> fields;
48
50 Row toRow(const T& object) const {
51 Row row;
52 for (const auto& field : fields) row[field.name] = field.read(object);
53 return row;
54 }
55
57 T fromRow(const Row& row) const {
58 T object{};
59 for (const auto& field : fields) {
60 auto it = row.find(field.name);
61 if (it != row.end()) field.write(object, it->second);
62 }
63 return object;
64 }
65};
66
72public:
74 Connection(std::string connector, std::string connectionString);
77
78 Connection(const Connection&) = delete;
79 Connection& operator=(const Connection&) = delete;
80
82 bool isConnected() const;
84 void close();
86 [[nodiscard]] eve::Result<void> beginTransaction();
88 [[nodiscard]] eve::Result<void> commitTransaction();
90 [[nodiscard]] eve::Result<void> rollbackTransaction();
92 bool begin();
94 bool commit();
96 bool rollback();
98 bool isInTransaction() const;
100 bool inTransaction() const;
102 int execute(const std::string& sql);
104 std::vector<Row> query(const std::string& sql);
106 std::string queryJson(const std::string& sql);
108 int insert(const std::string& table, const Row& values);
110 int upsert(const std::string& table, const Row& values);
112 int update(const std::string& table, const Row& values, const std::string& whereClause);
114 int remove(const std::string& table, const std::string& whereClause);
115
117 int insertJson(const std::string& table, const std::string& json);
119 int upsertJson(const std::string& table, const std::string& json);
121 int updateJson(const std::string& table, const std::string& json, const std::string& whereClause);
122
124 int updateByKey(const std::string& table, const Row& values, const std::string& key, const Value& id);
126 int removeByKey(const std::string& table, const std::string& key, const Value& id);
128 std::vector<Row> queryByKey(const std::string& table, const std::string& key, const Value& id);
134 Model* model(std::string table, std::string primaryKey = "id");
140 Query* from(std::string table);
141
143 template <class T>
145 int save(const Mapping<T>& mapping, const T& object) {
147 return insert(mapping.table, mapping.toRow(object));
148 }
149
151 template <class Range, class Mapper>
153 int exportECS(const std::string& table, const Range& entities, Mapper mapper) {
154 int count = 0;
156 execute("BEGIN");
157 try {
158 for (const auto& entity : entities) count += insert(table, mapper(entity));
160 execute("COMMIT");
161 } catch (...) {
162 try {
164 execute("ROLLBACK");
165 } catch (...) {
166 }
167 throw;
168 }
169 return count;
170 }
171
172private:
173 std::unique_ptr<Poco::Data::Session> session_;
174 int transactionDepth_ = 0;
175};
176
179public:
181 Query(Connection* connection, std::string table);
182
188 Query* select(const std::string& column);
194 Query* selectAs(const std::string& column, const std::string& alias);
200 Query* selectExpr(const std::string& expression, const std::string& alias = {});
206 Query* selectJson(const std::string& columnsJson);
212 Query* distinct(bool enabled);
213
219 Query* innerJoin(const std::string& table, const std::string& leftColumn, const std::string& rightColumn);
225 Query* leftJoin(const std::string& table, const std::string& leftColumn, const std::string& rightColumn);
226
232 Query* where(const std::string& column, const std::string& op, Value value);
238 Query* whereJson(const std::string& column, const std::string& op, const std::string& valueJson);
244 Query* orWhere(const std::string& column, const std::string& op, Value value);
250 Query* orWhereJson(const std::string& column, const std::string& op, const std::string& valueJson);
256 Query* whereIn(const std::string& column, const std::string& valuesJson);
262 Query* whereNotIn(const std::string& column, const std::string& valuesJson);
268 Query* whereBetween(const std::string& column, Value low, Value high);
274 Query* whereBetweenJson(const std::string& column, const std::string& lowJson, const std::string& highJson);
280 Query* whereNull(const std::string& column);
286 Query* whereNotNull(const std::string& column);
292 Query* whereAnyJson(const std::string& predicatesJson);
298 Query* orWhereAnyJson(const std::string& predicatesJson);
299
305 Query* groupBy(const std::string& column);
311 Query* groupByJson(const std::string& columnsJson);
317 Query* having(const std::string& columnOrExpr, const std::string& op, Value value);
323 Query* havingJson(const std::string& columnOrExpr, const std::string& op, const std::string& valueJson);
324
330 Query* orderBy(const std::string& column, bool ascending = true);
336 Query* limit(int count);
342 Query* offset(int count);
344 std::vector<Row> all();
346 std::string allJson();
348 std::string firstJson();
350 int count();
351
352private:
353 struct Predicate {
354 bool combineWithOr = false;
355 std::string sql;
356 };
357 struct Join {
358 std::string type; // INNER / LEFT
359 std::string table;
360 std::string left;
361 std::string right;
362 };
363
364 std::string selectSql(bool countOnly, int forcedLimit = -1) const;
369 Query* addComparison(bool combineWithOr, const std::string& column, const std::string& op, Value value);
374 Query* addIn(bool negate, const std::string& column, const std::string& valuesJson);
379 Query* addJoin(std::string type, std::string table, std::string leftColumn, std::string rightColumn);
384 Query* addAnyGroup(bool combineWithOr, const std::string& predicatesJson);
385
386 Connection* connection_;
387 std::string table_;
388 std::vector<std::string> columns_;
389 std::vector<Join> joins_;
390 std::vector<Predicate> predicates_;
391 std::vector<std::string> groups_;
392 std::vector<std::string> havings_;
393 std::vector<std::string> ordering_;
394 int limit_ = -1;
395 int offset_ = 0;
396 bool distinct_ = false;
397};
398
400template <class T>
403public:
405 Repository(Connection& connection, Mapping<T> mapping) : connection_(connection), mapping_(std::move(mapping)) {}
406
408 void createTable(bool ifNotExists = true) {
409 if (mapping_.fields.empty()) throw std::invalid_argument("ORM mapping has no fields");
410 std::string sql = "CREATE TABLE ";
411 if (ifNotExists) sql += "IF NOT EXISTS ";
412 sql += mapping_.table + " (";
413 for (std::size_t i = 0; i < mapping_.fields.size(); ++i) {
414 const auto& field = mapping_.fields[i];
415 if (i) sql += ',';
416 sql += field.name + " " + field.sqlType;
417 if (field.primaryKey) sql += " PRIMARY KEY";
418 }
419 connection_.execute(sql + ")");
420 }
421
423 int insert(const T& object) { return connection_.insert(mapping_.table, mapping_.toRow(object)); }
424
426 std::vector<T> all() {
427 std::vector<T> objects;
428 for (const auto& row : connection_.query("SELECT * FROM " + mapping_.table))
429 objects.push_back(mapping_.fromRow(row));
430 return objects;
431 }
432
434 bool find(const Value& id, T& object) {
435 auto rows = connection_.queryByKey(mapping_.table, primaryKey().name, id);
436 if (rows.empty()) return false;
437 object = mapping_.fromRow(rows.front());
438 return true;
439 }
440
442 int update(const T& object) {
443 const auto& key = primaryKey();
444 Row values = mapping_.toRow(object);
445 Value id = values.at(key.name);
446 values.erase(key.name);
447 return connection_.updateByKey(mapping_.table, values, key.name, id);
448 }
449
451 int remove(const Value& id) { return connection_.removeByKey(mapping_.table, primaryKey().name, id); }
452
454 std::vector<T> select(const std::function<void(Query&)>& configure) {
456 Query query(&connection_, mapping_.table);
458 configure(query);
459 std::vector<T> objects;
460 for (const auto& row : query.all()) objects.push_back(mapping_.fromRow(row));
461 return objects;
462 }
463
464private:
465 const Field<T>& primaryKey() const {
466 for (const auto& field : mapping_.fields)
467 if (field.primaryKey) return field;
468 throw std::logic_error("ORM mapping requires one primary key field");
469 }
470
471 Connection& connection_;
472 Mapping<T> mapping_;
473};
474
477public:
479 Model(Connection* connection, std::string table, std::string primaryKey);
481 int insertJson(const std::string& json);
483 std::string allJson();
485 std::string findJson(const std::string& idJson);
487 int updateJson(const std::string& idJson, const std::string& json);
489 int remove(const std::string& idJson);
491 Query* query();
492
493private:
494 Connection* connection_;
495 std::string table_;
496 std::string primaryKey_;
497};
498
503class Database : public Module {
504public:
507 Database() = default;
509 ~Database() override = default;
510
512 Connection* connect(std::string connector, std::string connectionString);
514 Connection* connectSQLite(std::string path);
515};
516
517} // namespace eve::database
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
#define EVENGINE_API_FOUNDATION
每个链接组(link group)各自的导出宏。
Definition Export.h:106
int rows
HexVec3 left
HexVec3 right
size_t offset
std::string from
bool all
std::string path
Definition PlayHost.cpp:111
std::vector< ecs::EntityHandle > entities
std::set< std::string > values
Object::Ptr value
const EntityFact * entity
glm::mat4 model
Move-only, checked operation results for the common layer.
size_t begin
unsigned column
int count
Json object
int limit
Definition TreeMesh.cpp:166
EVENGINE_API_FOUNDATION public API.
Definition Module.h:48
Move-only operation result carrying either a value or Status.
Definition Result.h:176
SQLite connection with a small ORM layer on top of Poco::Data. Tables/columns are quoted identifiers;...
Definition Database.h:71
int save(const Mapping< T > &mapping, const T &object)
ORM helper: persists one mapped object.
Definition Database.h:145
std::vector< Row > query(const std::string &sql)
Runs a SELECT and returns every row as name/value maps.
Definition Database.cpp:243
Connection & operator=(const Connection &)=delete
std::vector< Row > queryByKey(const std::string &table, const std::string &key, const Value &id)
Selects rows where key == id.
Definition Database.cpp:322
int insert(const std::string &table, const Row &values)
Inserts a row map; returns the affected row count.
Definition Database.cpp:261
Connection(const Connection &)=delete
int removeByKey(const std::string &table, const std::string &key, const Value &id)
Deletes a single row by primary key value.
Definition Database.cpp:318
int exportECS(const std::string &table, const Range &entities, Mapper mapper)
ORM helper: persists a range of mapped entities in one transaction.
Definition Database.h:153
int execute(const std::string &sql)
Executes a statement; returns the affected row count.
Definition Database.cpp:238
int updateByKey(const std::string &table, const Row &values, const std::string &key, const Value &id)
Updates a single row by primary key value.
Definition Database.cpp:314
Database module (eve.Database): SQLite connection factory. Script: db <- eve.Database(); conn <- db....
Definition Database.h:503
Database()=default
Constructs a Database.
Connection * connectSQLite(std::string path)
Opens a SQLite database file (":memory:" is supported).
Definition Database.cpp:635
~Database() override=default
Releases Database resources.
Connection * connect(std::string connector, std::string connectionString)
Opens a connection with an explicit Poco connector name.
Definition Database.cpp:632
Runtime ORM model exposed to Squirrel.
Definition Database.h:476
Composable filtered/sorted/paged query shared by C++ and scripts.
Definition Database.h:178
Typed active-record repository built from a Mapping<T>.
Definition Database.h:402
std::vector< T > all()
All.
Definition Database.h:426
std::vector< T > select(const std::function< void(Query &)> &configure)
Select.
Definition Database.h:454
int update(const T &object)
Updates update.
Definition Database.h:442
int insert(const T &object)
Inserts insert.
Definition Database.h:423
bool find(const Value &id, T &object)
Finds find.
Definition Database.h:434
void createTable(bool ifNotExists=true)
Creates table.
Definition Database.h:408
Repository(Connection &connection, Mapping< T > mapping)
Constructs a Repository.
Definition Database.h:405
int remove(const Value &id)
Removes remove.
Definition Database.h:451
StateValue objects
Definition Snapshot.cpp:110
std::unordered_map< std::string, Value > Row
Definition Database.h:28
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
bool enabled
A named field used by the small, explicit ORM mapping layer.
Definition Database.h:33
std::function< void(T &, const Value &)> write
Void.
Definition Database.h:38
std::string sqlType
Definition Database.h:39
std::string name
Definition Database.h:34
std::function< Value(const T &)> read
Value.
Definition Database.h:36
Mapping public API.
Definition Database.h:45
T fromRow(const Row &row) const
From row.
Definition Database.h:57
std::string table
Definition Database.h:46
std::vector< Field< T > > fields
Definition Database.h:47
Row toRow(const T &object) const
To row.
Definition Database.h:50