1#ifndef FRAY_HISTORY_MANAGER_HPP
2#define FRAY_HISTORY_MANAGER_HPP
62 using Statement = std::unique_ptr<sqlite3_stmt,
decltype(&sqlite3_finalize)>;
78 sqlite3_stmt* raw =
nullptr;
79 if (sqlite3_prepare_v2(db, sql, -1, &raw,
nullptr) != SQLITE_OK)
81 log::engineError(
"Failed to prepare history statement: %s", sqlite3_errmsg(db));
82 sqlite3_finalize(raw);
83 return Statement(
nullptr, sqlite3_finalize);
96 sqlite3_stmt* statement,
98 const std::string& value)
100 return sqlite3_bind_text64(statement, index, value.data(), value.size(), SQLITE_TRANSIENT,
101 SQLITE_UTF8) == SQLITE_OK;
114 if (sqlite3_exec(db, sql,
nullptr,
nullptr,
nullptr) == SQLITE_OK)
129 "CREATE TABLE IF NOT EXISTS fray_history_nodes ("
130 "node_id INTEGER PRIMARY KEY AUTOINCREMENT, "
131 "domain TEXT NOT NULL, "
132 "revision INTEGER NOT NULL, "
133 "parent_id INTEGER, "
134 "sequence INTEGER NOT NULL, "
135 "payload TEXT NOT NULL, "
136 "created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), "
137 "UNIQUE (domain, revision))") &&
139 "CREATE TABLE IF NOT EXISTS fray_history_heads ("
140 "domain TEXT PRIMARY KEY NOT NULL, "
141 "node_id INTEGER NOT NULL)");
150 sqlite3_stmt* statement)
153 node.
id = sqlite3_column_int64(statement, 0);
154 node.
domain.assign(
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 1)),
155 static_cast<std::size_t
>(sqlite3_column_bytes(statement, 1)));
156 node.
revision =
static_cast<std::uint64_t
>(sqlite3_column_int64(statement, 2));
157 node.
parentId = sqlite3_column_int64(statement, 3);
158 node.
sequence = sqlite3_column_int64(statement, 4);
159 node.
payload.assign(
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 5)),
160 static_cast<std::size_t
>(sqlite3_column_bytes(statement, 5)));
168 "node_id, domain, revision, COALESCE(parent_id, 0), sequence, payload";
182 const std::string& domain,
183 std::optional<std::int64_t> number,
184 std::optional<Node>& found)
188 return errors::FAILED_HISTORY;
189 auto statement =
prepare(db, sql);
190 if (!statement || (!domain.empty() && !
bindText(statement.get(), 1, domain)) ||
191 (number && sqlite3_bind_int64(statement.get(), 2, *number) != SQLITE_OK))
192 return errors::FAILED_HISTORY;
193 const int step = sqlite3_step(statement.get());
194 if (step == SQLITE_ROW)
196 else if (step != SQLITE_DONE)
199 return errors::FAILED_HISTORY;
225 const std::string& domain,
226 std::uint64_t revision,
227 const std::string& payload,
231 if (domain.empty() || revision >
static_cast<std::uint64_t
>(INT64_MAX))
234 return errors::FAILED_HISTORY;
236 return _state.withDatabase([&](sqlite3* db) ->
F_err
239 return errors::FAILED_HISTORY;
240 const auto fail = [db]
243 return errors::FAILED_HISTORY;
245 std::optional<Node> existing;
247 " FROM fray_history_nodes WHERE domain = ?1 AND revision = ?2").c_str(),
248 domain,
static_cast<std::int64_t
>(revision), existing) != errors::NONE)
251 return run(db,
"COMMIT") ? errors::NONE : fail();
252 std::optional<Node>
head;
254 " FROM fray_history_nodes WHERE node_id = "
255 "(SELECT node_id FROM fray_history_heads WHERE domain = ?1)").c_str(),
256 domain, std::nullopt,
head) != errors::NONE)
259 "INSERT INTO fray_history_nodes (domain, revision, parent_id, sequence, payload) "
260 "VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(sequence), 0) + 1 FROM fray_history_nodes), ?4)");
261 if (!insert || !
bindText(insert.get(), 1, domain) ||
262 sqlite3_bind_int64(insert.get(), 2,
static_cast<std::int64_t
>(revision)) != SQLITE_OK ||
263 (
head ? sqlite3_bind_int64(insert.get(), 3,
head->id) : sqlite3_bind_null(insert.get(), 3)) !=
265 !
bindText(insert.get(), 4, payload) || sqlite3_step(insert.get()) != SQLITE_DONE)
270 const std::int64_t
id = sqlite3_last_insert_rowid(db);
272 "INSERT INTO fray_history_heads (domain, node_id) VALUES (?1, ?2) "
273 "ON CONFLICT(domain) DO UPDATE SET node_id = excluded.node_id");
274 if (!point || !
bindText(point.get(), 1, domain) ||
275 sqlite3_bind_int64(point.get(), 2,
id) != SQLITE_OK ||
276 sqlite3_step(point.get()) != SQLITE_DONE)
278 log::engineError(
"Failed to move the history head: %s", sqlite3_errmsg(db));
281 if (!
run(db,
"COMMIT"))
295 const std::string& domain,
296 std::optional<Node>& node)
298 return _state.withDatabase([&](sqlite3* db)
301 " FROM fray_history_nodes WHERE node_id = "
302 "(SELECT node_id FROM fray_history_heads WHERE domain = ?1)").c_str(),
303 domain, std::nullopt, node);
315 const std::string& domain,
316 std::uint64_t revision,
317 std::optional<Node>& node)
319 return _state.withDatabase([&](sqlite3* db)
322 " FROM fray_history_nodes WHERE domain = ?1 AND revision = ?2").c_str(),
323 domain,
static_cast<std::int64_t
>(revision), node);
334 const std::string& domain,
335 std::optional<Node>& node)
337 return _state.withDatabase([&](sqlite3* db)
340 " FROM fray_history_nodes WHERE domain = ?1 "
341 "ORDER BY revision DESC LIMIT 1").c_str(),
342 domain, std::nullopt, node);
354 std::optional<Node>& found)
356 return _state.withDatabase([&](sqlite3* db)
359 " FROM fray_history_nodes WHERE node_id = ?2").c_str(),
372 std::optional<Node>& found)
374 return _state.withDatabase([&](sqlite3* db)
377 " FROM fray_history_nodes WHERE parent_id = ?2 "
378 "ORDER BY sequence DESC LIMIT 1").c_str(),
389 std::vector<Node>& nodes)
392 return _state.withDatabase([&](sqlite3* db) ->
F_err
395 return errors::FAILED_HISTORY;
397 " FROM fray_history_nodes WHERE node_id IN (SELECT node_id FROM fray_history_heads)").c_str());
399 return errors::FAILED_HISTORY;
401 while ((step = sqlite3_step(statement.get())) == SQLITE_ROW)
402 nodes.push_back(
readNode(statement.get()));
403 return step == SQLITE_DONE ? errors::NONE : errors::FAILED_HISTORY;
415 const std::string& domain,
418 return _state.withDatabase([&](sqlite3* db) ->
F_err
421 return errors::FAILED_HISTORY;
423 "INSERT INTO fray_history_heads (domain, node_id) "
424 "SELECT domain, node_id FROM fray_history_nodes WHERE domain = ?1 AND node_id = ?2 "
425 "ON CONFLICT(domain) DO UPDATE SET node_id = excluded.node_id");
426 if (!update || !
bindText(update.get(), 1, domain) ||
427 sqlite3_bind_int64(update.get(), 2, nodeId) != SQLITE_OK ||
428 sqlite3_step(update.get()) != SQLITE_DONE || sqlite3_changes(db) == 0)
430 log::engineError(
"Cannot move the history head: no such node in the domain.");
431 return errors::FAILED_HISTORY;
F_err moveHead(const std::string &domain, std::int64_t nodeId)
Moves a domain head to an existing node without deleting branches. Runs on the calling thread under t...
F_err heads(std::vector< Node > &nodes)
Reads all domain heads under the state mutex.
static Node readNode(sqlite3_stmt *statement)
Reads a node from the current row in nodeColumns order.
F_err head(const std::string &domain, std::optional< Node > &node)
Finds the current node for a domain under the state mutex.
F_err find(const std::string &domain, std::uint64_t revision, std::optional< Node > &node)
Finds a domain node by revision under the state mutex.
static bool bindText(sqlite3_stmt *statement, int index, const std::string &value)
Binds a copied UTF-8 string to a statement parameter.
std::unique_ptr< sqlite3_stmt, decltype(&sqlite3_finalize)> Statement
Owns an SQLite statement and finalizes it on destruction.
F_err record(const std::string &domain, std::uint64_t revision, const std::string &payload, bool &created)
Records a new node under the domain head and advances the head transactionally. An existing domain/re...
HistoryManager(state::StateManager &state)
Borrows the state store that owns the project database.
F_err parent(const Node &node, std::optional< Node > &found)
Finds a node’s parent under the state mutex.
static bool ensureTables(sqlite3 *db)
Creates the history node and head tables if absent.
static Statement prepare(sqlite3 *db, const char *sql)
Prepares an SQLite statement and logs failures.
state::StateManager & _state
Non-owning reference to the state store and its database mutex.
F_err latest(const std::string &domain, std::optional< Node > &node)
Finds the highest revision in a domain across all branches under the state mutex.
static constexpr const char * nodeColumns
Column order expected by readNode, with null parents mapped to zero.
F_err child(const Node &node, std::optional< Node > &found)
Finds the most recently recorded child for redo under the state mutex.
static F_err selectNode(sqlite3 *db, const char *sql, const std::string &domain, std::optional< std::int64_t > number, std::optional< Node > &found)
Ensures history tables and reads at most one node.
static bool run(sqlite3 *db, const char *sql)
Executes SQL and logs an SQLite failure.
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
F_void engineError(const F_char *fmt,...)
Log error for Engine.
One recorded history action with domain-defined opaque payload.
std::int64_t parentId
Parent node identifier, or 0 for the first node in a domain.
std::string domain
Domain that owns and interprets this action.
std::uint64_t revision
Recorder-assigned, never-reused revision within the domain.
std::int64_t sequence
Global recording order across domains.
std::string payload
Opaque action data interpreted by its domain.
std::int64_t id
Database identifier of this node.