game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_database.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_database.h
4// ==============================================================================
5// SQLite-based game library storage
6// ==============================================================================
7// Provides persistent storage for the game library using SQLite, offering:
8// - ACID-compliant transactions for data safety
9// - Indexed queries for fast filtering and searching
10// - Single-file storage for easy backup/portability
11// - Automatic migration from legacy .game files
12//
13// ## Thread Safety
14// All public methods are thread-safe. The database uses WAL mode for
15// concurrent read access during writes.
16// ==============================================================================
17
18#pragma once
19
20#include "game.h"
21
22#include <cstdint>
23#include <functional>
24#include <memory>
25#include <mutex>
26#include <optional>
27#include <string>
28#include <unordered_map>
29#include <utility>
30#include <vector>
31
32// Forward declare sqlite3 to avoid including header in public interface
33struct sqlite3;
34struct sqlite3_stmt;
35
36// ==============================================================================
37// Database Query Options
38// ==============================================================================
39
40/**
41 * @struct DatabaseFilterOptions
42 * @brief Filter options for database queries
43 */
45{
46 std::string searchQuery; // Full-text search on name/description
47 bool favoritesOnly = false; // Only return favorites
48 bool installedOnly = false; // Only return installed games
49 std::optional<GameSource> sourceFilter; // Filter by source (nullopt = all)
50 std::optional<GameRunner> runnerFilter; // Filter by runner (nullopt = all)
51 std::string collection; // Filter by collection name
52};
53
54/**
55 * @struct DatabaseSortOptions
56 * @brief Sort options for database queries
57 */
78
79// ==============================================================================
80// GameDatabase Class
81// ==============================================================================
82
83/**
84 * @class GameDatabase
85 * @brief SQLite-based storage for the game library
86 *
87 * Manages all game data persistence using SQLite. Provides methods for
88 * CRUD operations, filtered queries, and data migration.
89 *
90 * ## Usage Example
91 * @code
92 * GameDatabase db;
93 * if (!db.open("~/.local/share/gamelauncher/library.db")) {
94 * Logger::error("Failed to open database: {}", db.lastError());
95 * return;
96 * }
97 *
98 * // Add a game
99 * Game game;
100 * game.name = "My Game";
101 * db.insertGame(game);
102 *
103 * // Query games
104 * auto favorites = db.queryGames({.favoritesOnly = true});
105 * @endcode
106 */
108{
109 public:
112
113 // Non-copyable, movable
114 GameDatabase(const GameDatabase&) = delete;
116 GameDatabase(GameDatabase&& other) noexcept;
117 GameDatabase& operator=(GameDatabase&& other) noexcept;
118
119 // ==========================================================================
120 // Database Lifecycle
121 // ==========================================================================
122
123 /**
124 * @brief Open or create the database
125 * @param path Path to the database file
126 * @return true on success, false on failure (check lastError())
127 *
128 * Creates the database and tables if they don't exist.
129 * Runs any pending schema migrations.
130 */
131 bool open(const std::string& path);
132
133 /**
134 * @brief Close the database
135 */
136 void close();
137
138 /**
139 * @brief Check if database is open
140 */
141 bool isOpen() const;
142
143 /**
144 * @brief Get last error message
145 */
146 std::string lastError() const;
147
148 // ==========================================================================
149 // CRUD Operations
150 // ==========================================================================
151
152 /**
153 * @brief Insert a new game
154 * @param game Game to insert (id will be used as primary key)
155 * @return true on success
156 */
157 bool insertGame(const Game& game);
158
159 /**
160 * @brief Update an existing game
161 * @param game Game with updated data (matched by id)
162 * @return true on success
163 */
164 bool updateGame(const Game& game);
165
166 /**
167 * @brief Update only the image paths for a game (efficient partial update)
168 * @param gameId ID of game to update
169 * @param images New image paths to set
170 * @return true on success
171 */
172 bool updateGameImages(const std::string& gameId, const GameImagePaths& images);
173
174 /**
175 * @brief Get games that are missing cover art
176 * @param limit Maximum number to return (0 = no limit)
177 * @return Vector of games with no vertical cover path set
178 */
179 std::vector<Game> getGamesWithoutCoverArt(int limit = 0) const;
180
181 /**
182 * @brief Delete a game by ID
183 * @param gameId ID of game to delete
184 * @return true on success
185 */
186 bool deleteGame(const std::string& gameId);
187
188 /**
189 * @brief Get a game by ID
190 * @param gameId ID of game to retrieve
191 * @return Game if found, nullopt otherwise
192 */
193 std::optional<Game> getGame(const std::string& gameId) const;
194
195 /**
196 * @brief Check if a game exists
197 * @param gameId ID to check
198 * @return true if game exists
199 */
200 bool gameExists(const std::string& gameId) const;
201
202 // ==========================================================================
203 // Query Operations
204 // ==========================================================================
205
206 /**
207 * @brief Query games with filtering and sorting
208 * @param filter Filter options
209 * @param sort Sort options
210 * @param limit Maximum results (0 = no limit)
211 * @param offset Skip first N results
212 * @return Vector of matching games
213 */
214 std::vector<Game> queryGames(const DatabaseFilterOptions& filter = {},
215 const DatabaseSortOptions& sort = {}, int limit = 0,
216 int offset = 0) const;
217
218 /**
219 * @brief Get all games (convenience method)
220 * @return Vector of all games
221 */
222 std::vector<Game> getAllGames() const;
223
224 /**
225 * @brief Get total game count
226 * @param filter Optional filter (empty = all games)
227 * @return Number of games matching filter
228 */
229 int getGameCount(const DatabaseFilterOptions& filter = {}) const;
230
231 /**
232 * @brief Search games by name (uses FTS if available)
233 * @param query Search query
234 * @param limit Maximum results
235 * @return Vector of matching games
236 */
237 std::vector<Game> searchGames(const std::string& query, int limit = 50) const;
238
239 // ==========================================================================
240 // Collection Operations
241 // ==========================================================================
242
243 /**
244 * @brief Get all collection names
245 * @return Vector of collection names
246 */
247 std::vector<std::string> getCollections() const;
248
249 /**
250 * @brief Add a collection
251 * @param name Collection name
252 * @return true on success
253 */
254 bool addCollection(const std::string& name);
255
256 /**
257 * @brief Remove a collection
258 * @param name Collection name
259 * @return true on success
260 */
261 bool removeCollection(const std::string& name);
262
263 /**
264 * @brief Add game to collection
265 * @param gameId Game ID
266 * @param collection Collection name
267 * @return true on success
268 */
269 bool addGameToCollection(const std::string& gameId, const std::string& collection);
270
271 /**
272 * @brief Remove game from collection
273 * @param gameId Game ID
274 * @param collection Collection name
275 * @return true on success
276 */
277 bool removeGameFromCollection(const std::string& gameId, const std::string& collection);
278
279 /**
280 * @brief Export all games to JSON
281 * @param path Output file path
282 * @return true on success
283 */
284 bool exportToJson(const std::string& path) const;
285
286 /**
287 * @brief Import games from JSON
288 * @param path Input file path
289 * @param overwriteExisting Overwrite games with same ID
290 * @return Number of games imported, -1 on error
291 */
292 int importFromJson(const std::string& path, bool overwriteExisting = false);
293
294 /**
295 * @brief Vacuum database to reclaim space
296 * @return true on success
297 */
298 bool vacuum();
299
300 /**
301 * @brief Get database schema version
302 */
303 int getSchemaVersion() const;
304
305 // ==========================================================================
306 // Transaction Support
307 // ==========================================================================
308
309 /**
310 * @brief Begin a transaction
311 * @return true on success
312 */
313 bool beginTransaction();
314
315 /**
316 * @brief Commit current transaction
317 * @return true on success
318 */
319 bool commitTransaction();
320
321 /**
322 * @brief Rollback current transaction
323 * @return true on success
324 */
325 bool rollbackTransaction();
326
327 /**
328 * @brief Execute a function within a transaction
329 * @param func Function to execute
330 * @return true if function succeeded and transaction committed
331 *
332 * Automatically rolls back on exception or if func returns false.
333 */
334 bool withTransaction(const std::function<bool()>& func);
335
336 // ==========================================================================
337 // Session & Launch Tracking (V2)
338 // ==========================================================================
339
340 /**
341 * @brief Record a game session start
342 * @param gameId Game ID
343 * @param runner Runner used
344 * @param protonVersion Proton version (if applicable)
345 * @return Session ID for later updates, 0 on error
346 */
347 int64_t startSession(const std::string& gameId, GameRunner runner,
348 const std::string& protonVersion = "");
349
350 /**
351 * @brief End a game session
352 * @param sessionId Session ID from startSession
353 * @param exitReason How the session ended (normal, crash, etc.)
354 * @return true on success
355 */
356 bool endSession(int64_t sessionId, const std::string& exitReason = "normal");
357
358 /**
359 * @brief Get recent play sessions for a game
360 * @param gameId Game ID
361 * @param limit Maximum number of sessions to return
362 * @return Vector of PlaySession records, most recent first
363 */
364 std::vector<PlaySession> getRecentSessions(const std::string& gameId, int limit = 20) const;
365
366 /**
367 * @brief Record a launch attempt (success or failure)
368 * @param gameId Game ID
369 * @param success Whether launch succeeded
370 * @param runner Runner used
371 * @param protonVersion Proton version (if applicable)
372 * @param errorMessage Error message if failed
373 * @param timeToLaunchMs Time taken to launch in milliseconds
374 * @return true on success
375 */
376 bool recordLaunch(const std::string& gameId, bool success, GameRunner runner,
377 const std::string& protonVersion = "", const std::string& errorMessage = "",
378 int timeToLaunchMs = 0);
379
380 /**
381 * @brief Update daily playtime aggregation
382 * @param gameId Game ID
383 * @param playTimeSeconds Playtime to add
384 * @return true on success
385 */
386 bool updateDailyPlaytime(const std::string& gameId, int playTimeSeconds);
387
388 // ==========================================================================
389 // Analytics Queries (V2)
390 // ==========================================================================
391
392 /**
393 * @brief Get total playtime for a specific date range
394 * @param startDate Start date (YYYY-MM-DD)
395 * @param endDate End date (YYYY-MM-DD)
396 * @return Total playtime in seconds
397 */
398 int64_t getTotalPlaytime(const std::string& startDate, const std::string& endDate) const;
399
400 /**
401 * @brief Get playtime by game for a date range
402 * @param startDate Start date (YYYY-MM-DD)
403 * @param endDate End date (YYYY-MM-DD)
404 * @param limit Max results
405 * @return Vector of pairs (gameId, playTimeSeconds) sorted by playtime desc
406 */
407 std::vector<std::pair<std::string, int64_t>> getPlaytimeByGame(const std::string& startDate,
408 const std::string& endDate,
409 int limit = 10) const;
410
411 /**
412 * @brief Get playtime by day for a date range
413 * @param startDate Start date (YYYY-MM-DD)
414 * @param endDate End date (YYYY-MM-DD)
415 * @return Vector of pairs (date, playTimeSeconds) sorted by date
416 */
417 std::vector<std::pair<std::string, int64_t>> getPlaytimeByDay(const std::string& startDate,
418 const std::string& endDate) const;
419
420 /**
421 * @brief Get runner usage statistics
422 * @return Vector of pairs (runner, totalPlayTimeSeconds) sorted by playtime desc
423 */
424 std::vector<std::pair<GameRunner, int64_t>> getRunnerStats() const;
425
426 /**
427 * @brief Get source statistics (games per source)
428 * @return Vector of pairs (source, gameCount) sorted by count desc
429 */
430 std::vector<std::pair<GameSource, int>> getSourceStats() const;
431
432 /**
433 * @brief Get most played games
434 * @param limit Max results
435 * @return Vector of Games sorted by total playtime desc
436 */
437 std::vector<Game> getMostPlayedGames(int limit = 10) const;
438
439 /**
440 * @brief Get recently played games
441 * @param limit Max results
442 * @return Vector of Games sorted by last played desc
443 */
444 std::vector<Game> getRecentlyPlayedGames(int limit = 10) const;
445
446 /**
447 * @brief Get crash statistics for a game
448 * @param gameId Game ID
449 * @return Pair of (crashCount, totalLaunches)
450 */
451 std::pair<int, int> getGameCrashStats(const std::string& gameId) const;
452
453 /**
454 * @brief Get average session duration for a game
455 * @param gameId Game ID
456 * @return Average session duration in seconds
457 */
458 double getAverageSessionDuration(const std::string& gameId) const;
459
460 private:
461 // Schema creation + migration framework. createSchema() is called when
462 // no `games` table exists (fresh DB). When a `games` table is found but
463 // its schema_version is older than SCHEMA_VERSION, runMigrations() walks
464 // the registered v→v+1 step functions in order. A future-version DB
465 // (downgrade scenario) is rejected with a clear error rather than
466 // overwritten.
467 bool createSchema();
468 bool runMigrations(int fromVersion);
469
470 // Helper methods
471 bool executeSQL(const std::string& sql);
472 Game gameFromStatement(sqlite3_stmt* stmt) const;
473
474 // Result kind for getSchemaVersionInternal — distinguishes the four
475 // states the caller cares about so we don't conflate "missing table"
476 // with "version 0" or quietly stamp over a corrupt DB.
477 enum class SchemaVersionState
478 {
479 NoTable, ///< schema_version table doesn't exist
480 Empty, ///< table exists but has no rows
481 Found, ///< table exists and has at least one row
482 Error ///< table exists but the query failed (corruption / lock / etc.)
483 };
484 struct SchemaVersionResult
485 {
486 SchemaVersionState state;
487 int version = 0; ///< Only meaningful when state == Found
488 };
489 SchemaVersionResult getSchemaVersionInternal() const;
490
491 // Internal collection helpers (caller must already hold mutex_)
492 bool addGameToCollectionInternal(const std::string& gameId, const std::string& collection);
493 bool removeGameFromCollectionInternal(const std::string& gameId, const std::string& collection);
494
495 // Members
496 sqlite3* db_ = nullptr;
497 mutable std::recursive_mutex mutex_;
498 mutable std::string lastError_;
499 std::string dbPath_;
500
501 // Advisory file-lock fd guarding multi-process access to dbPath_.
502 // -1 when not held. Acquired in open(), released in close()/destructor.
503 // See open() for rationale (flock on a `<dbPath>.lock` sidecar).
504 int lockFd_ = -1;
505
506 // Prepared statement cache
507 mutable std::unordered_map<std::string, sqlite3_stmt*> stmtCache_;
508 sqlite3_stmt* getCachedStatement(const char* sql) const;
509 void clearStatementCache();
510
511 // Current schema version. Bump when adding/removing/altering tables AND
512 // append a step function in runMigrations() that takes an existing DB
513 // from `SCHEMA_VERSION - 1` to the new value. Never delete user data.
514 static constexpr int SCHEMA_VERSION = 5;
515};
std::vector< Game > queryGames(const DatabaseFilterOptions &filter={}, const DatabaseSortOptions &sort={}, int limit=0, int offset=0) const
Query games with filtering and sorting.
std::vector< std::pair< GameSource, int > > getSourceStats() const
Get source statistics (games per source).
bool updateGame(const Game &game)
Update an existing game.
bool updateDailyPlaytime(const std::string &gameId, int playTimeSeconds)
Update daily playtime aggregation.
std::vector< Game > searchGames(const std::string &query, int limit=50) const
Search games by name (uses FTS if available).
std::vector< std::pair< std::string, int64_t > > getPlaytimeByDay(const std::string &startDate, const std::string &endDate) const
Get playtime by day for a date range.
bool removeGameFromCollection(const std::string &gameId, const std::string &collection)
Remove game from collection.
void close()
Close the database.
std::optional< Game > getGame(const std::string &gameId) const
Get a game by ID.
bool exportToJson(const std::string &path) const
Export all games to JSON.
bool insertGame(const Game &game)
Insert a new game.
GameDatabase(const GameDatabase &)=delete
bool isOpen() const
Check if database is open.
int64_t getTotalPlaytime(const std::string &startDate, const std::string &endDate) const
Get total playtime for a specific date range.
bool commitTransaction()
Commit current transaction.
bool addCollection(const std::string &name)
Add a collection.
bool deleteGame(const std::string &gameId)
Delete a game by ID.
bool vacuum()
Vacuum database to reclaim space.
bool recordLaunch(const std::string &gameId, bool success, GameRunner runner, const std::string &protonVersion="", const std::string &errorMessage="", int timeToLaunchMs=0)
Record a launch attempt (success or failure).
bool addGameToCollection(const std::string &gameId, const std::string &collection)
Add game to collection.
int importFromJson(const std::string &path, bool overwriteExisting=false)
Import games from JSON.
bool beginTransaction()
Begin a transaction.
bool withTransaction(const std::function< bool()> &func)
Execute a function within a transaction.
std::vector< Game > getRecentlyPlayedGames(int limit=10) const
Get recently played games.
bool open(const std::string &path)
Open or create the database.
std::vector< Game > getMostPlayedGames(int limit=10) const
Get most played games.
std::vector< std::pair< GameRunner, int64_t > > getRunnerStats() const
Get runner usage statistics.
int64_t startSession(const std::string &gameId, GameRunner runner, const std::string &protonVersion="")
Record a game session start.
bool endSession(int64_t sessionId, const std::string &exitReason="normal")
End a game session.
std::pair< int, int > getGameCrashStats(const std::string &gameId) const
Get crash statistics for a game.
bool gameExists(const std::string &gameId) const
Check if a game exists.
std::vector< PlaySession > getRecentSessions(const std::string &gameId, int limit=20) const
Get recent play sessions for a game.
std::vector< std::string > getCollections() const
Get all collection names.
std::vector< Game > getGamesWithoutCoverArt(int limit=0) const
Get games that are missing cover art.
bool updateGameImages(const std::string &gameId, const GameImagePaths &images)
Update only the image paths for a game (efficient partial update).
double getAverageSessionDuration(const std::string &gameId) const
Get average session duration for a game.
std::vector< Game > getAllGames() const
Get all games (convenience method).
std::string lastError() const
Get last error message.
bool rollbackTransaction()
Rollback current transaction.
int getSchemaVersion() const
Get database schema version.
std::vector< std::pair< std::string, int64_t > > getPlaytimeByGame(const std::string &startDate, const std::string &endDate, int limit=10) const
Get playtime by game for a date range.
bool removeCollection(const std::string &name)
Remove a collection.
int getGameCount(const DatabaseFilterOptions &filter={}) const
Get total game count.
GameDatabase & operator=(const GameDatabase &)=delete
Complete representation of a game in the library.
Definition game.h:767
GameRunner
Runner/compatibility layer for executing the game.
Definition game.h:81
Filter options for database queries.
std::optional< GameSource > sourceFilter
std::optional< GameRunner > runnerFilter
Sort options for database queries.
Paths to various game image assets.
Definition game.h:496
@ Game
Game-specific fixes.