game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
game_database.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// game_database.cpp
4// ==============================================================================
5// SQLite-based game library storage implementation
6// ==============================================================================
7
8#include "game_database.h"
9#include "logger.h"
10#include "util/safe_enum_cast.h"
11
12#include <nlohmann/json.hpp>
13#include <sqlite3.h>
14
15#include <fcntl.h> // open, O_*, used for PID-lockfile
16#include <sys/file.h> // flock, LOCK_EX, LOCK_NB
17#include <unistd.h> // close(2)
18
19#include <algorithm>
20#include <array>
21#include <cerrno> // errno values for flock failure messages
22#include <cstring> // std::strerror
23#include <filesystem>
24#include <fstream>
25#include <sstream>
26
27namespace
28{
29// Bounds for the four enums persisted in the games table. Centralised here
30// so a future enum addition only needs the kMax bump in one spot. Verified
31// against core/include/models/game.h on 2026-05-02.
32constexpr int kMaxGameSource = static_cast<int>(GameSource::Unknown); // 7
33constexpr int kMaxGameRunner = static_cast<int>(GameRunner::ScummVM); // 4
34constexpr int kMaxGameStatus = static_cast<int>(GameStatus::Updating); // 6
35constexpr int kMaxCompletionStatus = static_cast<int>(CompletionStatus::Played); // 6
36} // namespace
37
38namespace fs = std::filesystem;
39using json = nlohmann::json;
40
41// ==============================================================================
42// Schema Definition — Single unified schema, no migrations
43// ==============================================================================
44
45static const char* SCHEMA_SQL = R"SQL(
46
47-- Games table: Every field is a dedicated column for queryability
48CREATE TABLE IF NOT EXISTS games (
49 -- Core
50 id TEXT PRIMARY KEY NOT NULL,
51 name TEXT NOT NULL,
52 source INTEGER NOT NULL DEFAULT 0,
53 runner INTEGER NOT NULL DEFAULT 0,
54 status INTEGER NOT NULL DEFAULT 0,
55 is_favorite INTEGER NOT NULL DEFAULT 0,
56 install_path TEXT,
57 install_size_bytes INTEGER DEFAULT 0,
58
59 -- Runner configuration (JSON blob — complex opaque config)
60 runner_config TEXT,
61
62 -- Config templates (JSON blob — named presets map)
63 config_templates TEXT,
64 active_template_name TEXT,
65
66 -- Statistics
67 times_launched INTEGER DEFAULT 0,
68 total_play_time_seconds INTEGER DEFAULT 0,
69 last_played INTEGER DEFAULT 0,
70 date_added INTEGER DEFAULT 0,
71 date_installed INTEGER DEFAULT 0,
72
73 -- Launch tracking
74 last_launch_command TEXT,
75 last_proton_version TEXT,
76 last_exit_reason TEXT DEFAULT 'unknown',
77 last_exit_time INTEGER DEFAULT 0,
78 crash_count INTEGER DEFAULT 0,
79 last_environment_vars TEXT,
80
81 -- Descriptive metadata
82 developer TEXT,
83 publisher TEXT,
84 release_year INTEGER DEFAULT 0,
85 description TEXT,
86 user_rating REAL DEFAULT 0,
87
88 -- Image paths
89 image_vertical_cover TEXT,
90 image_hero TEXT,
91 image_logo TEXT,
92 image_header TEXT,
93 image_capsule TEXT,
94 image_icon TEXT,
95
96 -- Genres and tags (JSON arrays)
97 genres TEXT,
98 tags TEXT,
99
100 -- Steam-specific
101 steam_app_id INTEGER DEFAULT 0,
102 steam_installed INTEGER DEFAULT 1,
103 steam_launch_options TEXT,
104 steam_build_id TEXT,
105 steam_playtime_2weeks INTEGER DEFAULT 0,
106 steam_last_launch INTEGER DEFAULT 0,
107 steam_last_exit INTEGER DEFAULT 0,
108 steam_type TEXT,
109 steam_categories TEXT,
110 steam_user_tags TEXT,
111 steam_state_flags INTEGER DEFAULT 0,
112 steam_bytes_downloaded INTEGER DEFAULT 0,
113 steam_bytes_to_download INTEGER DEFAULT 0,
114 steam_is_downloading INTEGER DEFAULT 0,
115 steam_is_update_pending INTEGER DEFAULT 0,
116
117 -- ProtonDB compatibility cache
118 protondb_tier TEXT,
119 protondb_confidence TEXT,
120 protondb_score REAL DEFAULT 0,
121 protondb_last_updated INTEGER DEFAULT 0,
122
123 -- Cloud save
124 cloud_save_enabled INTEGER DEFAULT 0,
125 cloud_save_supported INTEGER DEFAULT 0,
126 cloud_save_sync_state INTEGER DEFAULT 0,
127 cloud_save_storage_bytes INTEGER DEFAULT 0,
128 cloud_save_last_sync INTEGER DEFAULT 0,
129
130 -- DLC
131 dlc_count INTEGER DEFAULT 0,
132
133 -- Completion tracking
134 completion_status INTEGER DEFAULT 0,
135 user_notes TEXT,
136
137 -- HowLongToBeat
138 hltb_id INTEGER DEFAULT 0,
139 hltb_matched_name TEXT,
140 hltb_main_story REAL DEFAULT 0,
141 hltb_main_extras REAL DEFAULT 0,
142 hltb_completionist REAL DEFAULT 0,
143 hltb_all_styles REAL DEFAULT 0,
144 hltb_last_updated INTEGER DEFAULT 0,
145
146 -- Timestamps
147 created_at INTEGER DEFAULT (strftime('%s', 'now')),
148 updated_at INTEGER DEFAULT (strftime('%s', 'now'))
149);
150
151-- Collections
152CREATE TABLE IF NOT EXISTS collections (
153 id INTEGER PRIMARY KEY AUTOINCREMENT,
154 name TEXT UNIQUE NOT NULL
155);
156
157CREATE TABLE IF NOT EXISTS game_collections (
158 game_id TEXT NOT NULL,
159 collection_id INTEGER NOT NULL,
160 PRIMARY KEY (game_id, collection_id),
161 FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE,
162 FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE
163);
164
165-- Game sessions
166CREATE TABLE IF NOT EXISTS game_sessions (
167 id INTEGER PRIMARY KEY AUTOINCREMENT,
168 game_id TEXT NOT NULL,
169 start_time INTEGER NOT NULL,
170 end_time INTEGER,
171 duration_seconds INTEGER DEFAULT 0,
172 runner INTEGER NOT NULL,
173 proton_version TEXT,
174 exit_reason TEXT DEFAULT 'unknown',
175 environment_vars TEXT,
176 notes TEXT,
177 avg_fps REAL DEFAULT 0,
178 min_fps REAL DEFAULT 0,
179 avg_frametime REAL DEFAULT 0,
180 exit_code INTEGER DEFAULT 0,
181 FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
182);
183
184-- Launch history
185CREATE TABLE IF NOT EXISTS launch_history (
186 id INTEGER PRIMARY KEY AUTOINCREMENT,
187 game_id TEXT NOT NULL,
188 timestamp INTEGER NOT NULL,
189 success INTEGER NOT NULL DEFAULT 1,
190 error_message TEXT,
191 runner INTEGER NOT NULL,
192 proton_version TEXT,
193 time_to_launch_ms INTEGER,
194 FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
195);
196
197-- Runner statistics (aggregated)
198CREATE TABLE IF NOT EXISTS runner_stats (
199 runner INTEGER PRIMARY KEY,
200 total_games INTEGER DEFAULT 0,
201 total_sessions INTEGER DEFAULT 0,
202 total_play_time_seconds INTEGER DEFAULT 0,
203 total_launches INTEGER DEFAULT 0,
204 successful_launches INTEGER DEFAULT 0,
205 failed_launches INTEGER DEFAULT 0,
206 total_crashes INTEGER DEFAULT 0,
207 updated_at INTEGER DEFAULT (strftime('%s', 'now'))
208);
209
210-- Daily playtime aggregation
211CREATE TABLE IF NOT EXISTS daily_playtime (
212 date TEXT NOT NULL,
213 game_id TEXT NOT NULL,
214 play_time_seconds INTEGER DEFAULT 0,
215 session_count INTEGER DEFAULT 0,
216 PRIMARY KEY (date, game_id),
217 FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
218);
219
220-- Indexes
221CREATE INDEX IF NOT EXISTS idx_games_name ON games(name);
222CREATE INDEX IF NOT EXISTS idx_games_source ON games(source);
223CREATE INDEX IF NOT EXISTS idx_games_runner ON games(runner);
224CREATE INDEX IF NOT EXISTS idx_games_favorite ON games(is_favorite);
225CREATE INDEX IF NOT EXISTS idx_games_last_played ON games(last_played);
226CREATE INDEX IF NOT EXISTS idx_games_play_time ON games(total_play_time_seconds);
227CREATE INDEX IF NOT EXISTS idx_games_date_added ON games(date_added);
228CREATE INDEX IF NOT EXISTS idx_games_status ON games(status);
229CREATE INDEX IF NOT EXISTS idx_games_steam_app_id ON games(steam_app_id);
230CREATE INDEX IF NOT EXISTS idx_games_developer ON games(developer);
231CREATE INDEX IF NOT EXISTS idx_games_publisher ON games(publisher);
232CREATE INDEX IF NOT EXISTS idx_games_completion_status ON games(completion_status);
233CREATE INDEX IF NOT EXISTS idx_games_protondb_tier ON games(protondb_tier);
234CREATE INDEX IF NOT EXISTS idx_games_has_cover ON games(image_vertical_cover) WHERE image_vertical_cover IS NOT NULL;
235CREATE INDEX IF NOT EXISTS idx_sessions_game_id ON game_sessions(game_id);
236CREATE INDEX IF NOT EXISTS idx_sessions_start_time ON game_sessions(start_time);
237CREATE INDEX IF NOT EXISTS idx_sessions_duration ON game_sessions(duration_seconds);
238CREATE INDEX IF NOT EXISTS idx_launch_game_id ON launch_history(game_id);
239CREATE INDEX IF NOT EXISTS idx_launch_timestamp ON launch_history(timestamp);
240CREATE INDEX IF NOT EXISTS idx_launch_success ON launch_history(success);
241CREATE INDEX IF NOT EXISTS idx_daily_date ON daily_playtime(date);
242
243-- Full-text search
244CREATE VIRTUAL TABLE IF NOT EXISTS games_fts USING fts5(
245 name,
246 description,
247 developer,
248 publisher,
249 genres,
250 tags,
251 content='games',
252 content_rowid='rowid'
253);
254
255-- FTS sync triggers
256CREATE TRIGGER IF NOT EXISTS games_ai AFTER INSERT ON games BEGIN
257 INSERT INTO games_fts(rowid, name, description, developer, publisher, genres, tags)
258 VALUES(NEW.rowid, NEW.name, NEW.description, NEW.developer, NEW.publisher, NEW.genres, NEW.tags);
259END;
260
261CREATE TRIGGER IF NOT EXISTS games_ad AFTER DELETE ON games BEGIN
262 INSERT INTO games_fts(games_fts, rowid, name, description, developer, publisher, genres, tags)
263 VALUES('delete', OLD.rowid, OLD.name, OLD.description, OLD.developer, OLD.publisher, OLD.genres, OLD.tags);
264END;
265
266CREATE TRIGGER IF NOT EXISTS games_au AFTER UPDATE ON games BEGIN
267 INSERT INTO games_fts(games_fts, rowid, name, description, developer, publisher, genres, tags)
268 VALUES('delete', OLD.rowid, OLD.name, OLD.description, OLD.developer, OLD.publisher, OLD.genres, OLD.tags);
269 INSERT INTO games_fts(rowid, name, description, developer, publisher, genres, tags)
270 VALUES(NEW.rowid, NEW.name, NEW.description, NEW.developer, NEW.publisher, NEW.genres, NEW.tags);
271END;
272
273-- Schema version (single row)
274CREATE TABLE IF NOT EXISTS schema_version (
275 version INTEGER PRIMARY KEY
276);
277
278)SQL";
279
280// ==============================================================================
281// Column list for SELECT queries (used everywhere for consistency)
282// 69 columns, indices 0-68
283// ==============================================================================
284
285static const char* GAME_COLUMNS = R"(
286 g.id, g.name, g.source, g.runner, g.status, g.is_favorite,
287 g.install_path, g.install_size_bytes, g.runner_config,
288 g.config_templates, g.active_template_name,
289 g.times_launched, g.total_play_time_seconds, g.last_played, g.date_added, g.date_installed,
290 g.last_launch_command, g.last_proton_version, g.last_exit_reason, g.last_exit_time,
291 g.crash_count, g.last_environment_vars,
292 g.developer, g.publisher, g.release_year, g.description, g.user_rating,
293 g.image_vertical_cover, g.image_hero, g.image_logo, g.image_header, g.image_capsule, g.image_icon,
294 g.genres, g.tags,
295 g.steam_app_id, g.steam_installed, g.steam_launch_options, g.steam_build_id,
296 g.steam_playtime_2weeks, g.steam_last_launch, g.steam_last_exit, g.steam_type,
297 g.steam_categories, g.steam_user_tags,
298 g.steam_state_flags, g.steam_bytes_downloaded, g.steam_bytes_to_download,
299 g.steam_is_downloading, g.steam_is_update_pending,
300 g.protondb_tier, g.protondb_confidence, g.protondb_score, g.protondb_last_updated,
301 g.cloud_save_enabled, g.cloud_save_supported, g.cloud_save_sync_state, g.cloud_save_storage_bytes, g.cloud_save_last_sync,
302 g.dlc_count,
303 g.completion_status, g.user_notes,
304 g.hltb_id, g.hltb_matched_name, g.hltb_main_story, g.hltb_main_extras, g.hltb_completionist, g.hltb_all_styles, g.hltb_last_updated
305)";
306
307// Column index constants for gameFromStatement
309{
379 COL_COUNT // sentinel: total number of columns = 69
380};
381
382// ==============================================================================
383// JSON array helpers
384// ==============================================================================
385
386static std::string jsonArrayFromStrings(const std::vector<std::string>& vec)
387{
388 json arr = json::array();
389 for (const auto& s : vec)
390 arr.push_back(s);
391 return arr.dump();
392}
393
394static std::vector<std::string> stringsFromJsonArray(const std::string& str)
395{
396 std::vector<std::string> result;
397 if (str.empty() || str == "[]")
398 return result;
399 try
400 {
401 json arr = json::parse(str);
402 if (arr.is_array())
403 {
404 for (const auto& item : arr)
405 {
406 if (item.is_string())
407 result.push_back(item.get<std::string>());
408 }
409 }
410 }
411 catch (const json::exception&)
412 {
413 // Fallback: try comma-separated format
414 }
415 return result;
416}
417
418static std::string jsonFromEnvVars(const std::map<std::string, std::string>& vars)
419{
420 json obj = json::object();
421 for (const auto& [k, v] : vars)
422 obj[k] = v;
423 return obj.dump();
424}
425
426static std::map<std::string, std::string> envVarsFromJson(const std::string& str)
427{
428 std::map<std::string, std::string> result;
429 if (str.empty() || str == "{}")
430 return result;
431 try
432 {
433 json obj = json::parse(str);
434 if (obj.is_object())
435 {
436 for (auto& [k, v] : obj.items())
437 {
438 if (v.is_string())
439 result[k] = v.get<std::string>();
440 }
441 }
442 }
443 catch (const json::exception&)
444 {
445 }
446 return result;
447}
448
449// ==============================================================================
450// Constructor / Destructor
451// ==============================================================================
452
454
459
460// Init-list order matches declaration order in the header (db_, lastError_,
461// dbPath_, lockFd_, stmtCache_) so -Wreorder-ctor stays clean.
463 : db_(other.db_), lastError_(std::move(other.lastError_)), dbPath_(std::move(other.dbPath_)),
464 lockFd_(other.lockFd_), stmtCache_(std::move(other.stmtCache_))
465{
466 // Transferring `lockFd_` is critical: the flock(2) advisory lock attaches
467 // to the open file description, so as long as the fd stays open in *any*
468 // process the lock is held. If we forgot to move the fd, `~other` would
469 // close it and release the lock while `*this` is still actively writing
470 // — letting a second launcher instance corrupt our writes.
471 other.db_ = nullptr;
472 other.stmtCache_.clear();
473 other.lockFd_ = -1;
474}
475
477{
478 if (this != &other)
479 {
480 // Releases lockFd_ on `*this` via close() before stealing `other`'s.
481 close();
482 db_ = other.db_;
483 lastError_ = std::move(other.lastError_);
484 dbPath_ = std::move(other.dbPath_);
485 stmtCache_ = std::move(other.stmtCache_);
486 lockFd_ = other.lockFd_;
487 other.db_ = nullptr;
488 other.stmtCache_.clear();
489 other.lockFd_ = -1;
490 }
491 return *this;
492}
493
494// ==============================================================================
495// Database Lifecycle
496// ==============================================================================
497
498bool GameDatabase::open(const std::string& path)
499{
500 std::lock_guard<std::recursive_mutex> lock(mutex_);
501
502 if (db_)
503 {
504 lastError_ = "Database already open";
505 return false;
506 }
507
508 // Ensure directory exists
509 fs::path dbPath(path);
510 if (dbPath.has_parent_path())
511 {
512 std::error_code ec;
513 fs::create_directories(dbPath.parent_path(), ec);
514 if (ec)
515 {
516 lastError_ = "Failed to create directory: " + ec.message();
517 return false;
518 }
519 }
520
521 // Multi-process exclusion via advisory file lock. SQLite WAL allows
522 // safe concurrent reads/writes across processes at the SQL-statement
523 // level, but the launcher's own update flow (e.g. game-scan + write)
524 // expects app-transaction-level isolation. Two launcher instances
525 // racing on the same DB during autostart-vs-manual-launch would
526 // interleave writes; the lockfile makes the second instance fail
527 // fast with a clear error rather than silently merge state.
528 //
529 // We use flock(2) on a sidecar `.lock` file (NOT on the DB itself,
530 // which SQLite already manages via its own locking protocol). flock
531 // is advisory-only on Linux per flock(2), but every well-behaved
532 // launcher instance respects it. The lock auto-releases when the
533 // process exits or close()s the fd.
534 {
535 std::string lockPath = path + ".lock";
536 int fd = ::open(lockPath.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
537 if (fd < 0)
538 {
539 lastError_ =
540 "Cannot create lockfile " + lockPath + ": " + std::string(std::strerror(errno));
541 return false;
542 }
543 if (::flock(fd, LOCK_EX | LOCK_NB) != 0)
544 {
545 // Capture flock's errno before close(2), which is permitted
546 // to overwrite errno per POSIX close(3p). Reading errno after
547 // a subsequent libc call is undefined-by-spec
548 // (clang-analyzer-unix.Errno).
549 const int flockErrno = errno;
550 ::close(fd);
551 // EWOULDBLOCK / EAGAIN = held by another process.
552 if (flockErrno == EWOULDBLOCK)
553 {
554 lastError_ = "Another launcher instance is already using this database "
555 "(lockfile " +
556 lockPath + " held).";
557 }
558 else
559 {
560 lastError_ =
561 "flock failed on " + lockPath + ": " + std::string(std::strerror(flockErrno));
562 }
563 return false;
564 }
565 // Hand the fd to the instance state so it lives as long as the DB.
566 lockFd_ = fd;
567 }
568
569 // Open database
570 int rc = sqlite3_open(path.c_str(), &db_);
571 if (rc != SQLITE_OK)
572 {
573 lastError_ = sqlite3_errmsg(db_);
574 sqlite3_close(db_);
575 db_ = nullptr;
576 if (lockFd_ >= 0)
577 {
578 ::close(lockFd_);
579 lockFd_ = -1;
580 }
581 return false;
582 }
583
584 dbPath_ = path;
585
586 // Performance pragmas. We then verify journal_mode actually flipped to
587 // WAL — `PRAGMA journal_mode=WAL` silently falls back to the previous
588 // mode on filesystems that don't support WAL (e.g. NFS without locking
589 // emulation, see https://www.sqlite.org/wal.html#noshm). A silent
590 // fallback to 'delete' or 'truncate' would degrade crash-safety; we'd
591 // rather log loudly so the user can move the DB to a local FS.
592 executeSQL("PRAGMA journal_mode=WAL");
593 executeSQL("PRAGMA synchronous=NORMAL");
594 executeSQL("PRAGMA cache_size=-64000");
595 executeSQL("PRAGMA temp_store=MEMORY");
596 executeSQL("PRAGMA mmap_size=268435456");
597 executeSQL("PRAGMA foreign_keys=ON");
598 executeSQL("PRAGMA busy_timeout=5000");
599
600 {
601 sqlite3_stmt* probe = nullptr;
602 if (sqlite3_prepare_v2(db_, "PRAGMA journal_mode", -1, &probe, nullptr) == SQLITE_OK &&
603 sqlite3_step(probe) == SQLITE_ROW)
604 {
605 const char* mode = reinterpret_cast<const char*>(sqlite3_column_text(probe, 0));
606 std::string actual = mode ? mode : "(null)";
607 // WAL mode reports as the literal string "wal" (lowercase) per
608 // https://www.sqlite.org/pragma.html#pragma_journal_mode .
609 if (actual != "wal")
610 {
611 Logger::warn("[GameDatabase] PRAGMA journal_mode=WAL was rejected; "
612 "filesystem reports '{}' instead. Crash-safety is reduced; "
613 "consider moving the database off NFS/SMB.",
614 actual);
615 }
616 }
617 if (probe)
618 sqlite3_finalize(probe);
619 }
620 {
621 sqlite3_stmt* probe = nullptr;
622 if (sqlite3_prepare_v2(db_, "PRAGMA foreign_keys", -1, &probe, nullptr) == SQLITE_OK &&
623 sqlite3_step(probe) == SQLITE_ROW)
624 {
625 // foreign_keys returns 1/0; build sans foreign_keys support
626 // returns the same as the input.
627 if (sqlite3_column_int(probe, 0) != 1)
628 {
629 Logger::warn("[GameDatabase] PRAGMA foreign_keys=ON was not applied; "
630 "your sqlite library may have been built without "
631 "SQLITE_FOREIGN_KEY support.");
632 }
633 }
634 if (probe)
635 sqlite3_finalize(probe);
636 }
637
638 // Create schema
639 if (!createSchema())
640 {
641 sqlite3_close(db_);
642 db_ = nullptr;
643 if (lockFd_ >= 0)
644 {
645 ::close(lockFd_);
646 lockFd_ = -1;
647 }
648 return false;
649 }
650
651 Logger::info("Opened game database: {}", path);
652 return true;
653}
654
656{
657 std::lock_guard<std::recursive_mutex> lock(mutex_);
658
659 if (db_)
660 {
661 clearStatementCache();
662 sqlite3_close(db_);
663 db_ = nullptr;
664 Logger::info("Closed game database");
665 }
666 // Always release the lock fd, even if db_ was already null (e.g. open()
667 // failed late but the lock was acquired earlier). Closing the fd releases
668 // the flock(2) advisory lock.
669 //
670 // We deliberately do NOT unlink() the `.lock` sidecar here. The 0-byte file
671 // left behind is harmless (the next open() re-flocks the same inode), and
672 // removing it would reintroduce the classic flock+unlink race: after we
673 // unlink, another process that opened the *same path* before the unlink
674 // still holds its flock on the now-nameless inode, while a third process
675 // creates a fresh `.lock` file (new inode) and flocks *that* successfully —
676 // so two instances would both believe they hold the single-instance lock.
677 if (lockFd_ >= 0)
678 {
679 ::close(lockFd_);
680 lockFd_ = -1;
681 }
682}
683
684// ==============================================================================
685// Prepared Statement Cache
686// ==============================================================================
687
688sqlite3_stmt* GameDatabase::getCachedStatement(const char* sql) const
689{
690 auto it = stmtCache_.find(sql);
691 if (it != stmtCache_.end())
692 {
693 sqlite3_reset(it->second);
694 sqlite3_clear_bindings(it->second);
695 return it->second;
696 }
697
698 sqlite3_stmt* stmt = nullptr;
699 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
700 if (rc != SQLITE_OK)
701 {
702 lastError_ = sqlite3_errmsg(db_);
703 return nullptr;
704 }
705
706 stmtCache_[sql] = stmt;
707 return stmt;
708}
709
710void GameDatabase::clearStatementCache()
711{
712 for (auto& [sql, stmt] : stmtCache_)
713 {
714 if (stmt)
715 sqlite3_finalize(stmt);
716 }
717 stmtCache_.clear();
718}
719
721{
722 std::lock_guard<std::recursive_mutex> lock(mutex_);
723 return db_ != nullptr;
724}
725
726std::string GameDatabase::lastError() const
727{
728 std::lock_guard<std::recursive_mutex> lock(mutex_);
729 return lastError_;
730}
731
732// ==============================================================================
733// CRUD Operations
734// ==============================================================================
735
737{
738 std::lock_guard<std::recursive_mutex> lock(mutex_);
739
740 if (!db_)
741 {
742 lastError_ = "Database not open";
743 return false;
744 }
745
746 if (game.id.empty())
747 {
748 lastError_ = "Cannot insert game with empty ID";
749 return false;
750 }
751
752 // Only start our own transaction if not already inside one (e.g. called from saveToDisk)
753 bool ownTransaction = sqlite3_get_autocommit(db_) != 0;
754 if (ownTransaction)
755 executeSQL("BEGIN TRANSACTION");
756
757 std::string runnerConfigJson = game.serializeRunnerConfig();
758 std::string envVarsJson = jsonFromEnvVars(game.statistics.lastEnvironmentVars);
759 std::string genresJson = jsonArrayFromStrings(game.metadata.genres);
760 std::string tagsJson = jsonArrayFromStrings(game.metadata.tags);
761 std::string steamCategoriesJson = jsonArrayFromStrings(game.metadata.steamCategories);
762 std::string steamUserTagsJson = jsonArrayFromStrings(game.metadata.steamUserCategories);
763
764 // Serialize config templates to JSON
765 std::string configTemplatesJson;
766 if (!game.configTemplates.empty())
767 {
768 json templates = json::object();
769 for (const auto& [name, config] : game.configTemplates)
770 {
771 // Store each template's runner config JSON
772 Game tempGame;
773 tempGame.runnerConfig = config;
774 templates[name] = json::parse(tempGame.serializeRunnerConfig());
775 }
776 configTemplatesJson = templates.dump();
777 }
778
779 const char* sql = R"SQL(
780 INSERT INTO games (
781 id, name, source, runner, status, is_favorite,
782 install_path, install_size_bytes, runner_config,
783 config_templates, active_template_name,
784 times_launched, total_play_time_seconds, last_played, date_added, date_installed,
785 last_launch_command, last_proton_version, last_exit_reason, last_exit_time,
786 crash_count, last_environment_vars,
787 developer, publisher, release_year, description, user_rating,
788 image_vertical_cover, image_hero, image_logo, image_header, image_capsule, image_icon,
789 genres, tags,
790 steam_app_id, steam_installed, steam_launch_options, steam_build_id,
791 steam_playtime_2weeks, steam_last_launch, steam_last_exit, steam_type,
792 steam_categories, steam_user_tags,
793 steam_state_flags, steam_bytes_downloaded, steam_bytes_to_download,
794 steam_is_downloading, steam_is_update_pending,
795 protondb_tier, protondb_confidence, protondb_score, protondb_last_updated,
796 cloud_save_enabled, cloud_save_supported, cloud_save_sync_state, cloud_save_storage_bytes, cloud_save_last_sync,
797 dlc_count,
798 completion_status, user_notes,
799 hltb_id, hltb_matched_name, hltb_main_story, hltb_main_extras, hltb_completionist, hltb_all_styles, hltb_last_updated
800 ) VALUES (
801 ?, ?, ?, ?, ?, ?,
802 ?, ?, ?,
803 ?, ?,
804 ?, ?, ?, ?, ?,
805 ?, ?, ?, ?,
806 ?, ?,
807 ?, ?, ?, ?, ?,
808 ?, ?, ?, ?, ?, ?,
809 ?, ?,
810 ?, ?, ?, ?,
811 ?, ?, ?, ?,
812 ?, ?,
813 ?, ?, ?,
814 ?, ?,
815 ?, ?, ?, ?,
816 ?, ?, ?, ?, ?,
817 ?,
818 ?, ?,
819 ?, ?, ?, ?, ?, ?, ?
820 )
821 )SQL";
822
823 sqlite3_stmt* stmt;
824 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
825 if (rc != SQLITE_OK)
826 {
827 lastError_ = sqlite3_errmsg(db_);
828 if (ownTransaction)
829 executeSQL("ROLLBACK");
830 return false;
831 }
832
833 int p = 1; // bind parameter index
834
835 // Core (1-6)
836 sqlite3_bind_text(stmt, p++, game.id.c_str(), -1, SQLITE_TRANSIENT);
837 sqlite3_bind_text(stmt, p++, game.name.c_str(), -1, SQLITE_TRANSIENT);
838 sqlite3_bind_int(stmt, p++, static_cast<int>(game.source));
839 sqlite3_bind_int(stmt, p++, static_cast<int>(game.runner));
840 sqlite3_bind_int(stmt, p++, static_cast<int>(game.status));
841 sqlite3_bind_int(stmt, p++, game.isFavorite ? 1 : 0);
842
843 // Install (7-8)
844 sqlite3_bind_text(stmt, p++, game.installPath.c_str(), -1, SQLITE_TRANSIENT);
845 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.installSizeBytes));
846
847 // Runner config JSON (9)
848 sqlite3_bind_text(stmt, p++, runnerConfigJson.c_str(), -1, SQLITE_TRANSIENT);
849
850 // Config templates (10-11)
851 if (configTemplatesJson.empty())
852 sqlite3_bind_null(stmt, p++);
853 else
854 sqlite3_bind_text(stmt, p++, configTemplatesJson.c_str(), -1, SQLITE_TRANSIENT);
855 sqlite3_bind_text(stmt, p++, game.activeTemplateName.c_str(), -1, SQLITE_TRANSIENT);
856
857 // Statistics (12-16)
858 sqlite3_bind_int(stmt, p++, game.statistics.timesLaunched);
859 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.totalPlayTimeSeconds));
860 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.lastPlayed));
861 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.dateAdded));
862 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.dateInstalled));
863
864 // Launch tracking (17-22)
865 sqlite3_bind_text(stmt, p++, game.statistics.lastLaunchCommand.c_str(), -1, SQLITE_TRANSIENT);
866 sqlite3_bind_text(stmt, p++, game.statistics.lastProtonVersion.c_str(), -1, SQLITE_TRANSIENT);
867 sqlite3_bind_text(stmt, p++, game.statistics.lastExitReason.c_str(), -1, SQLITE_TRANSIENT);
868 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.lastExitTime));
869 sqlite3_bind_int(stmt, p++, game.statistics.crashCount);
870 sqlite3_bind_text(stmt, p++, envVarsJson.c_str(), -1, SQLITE_TRANSIENT);
871
872 // Descriptive metadata (23-27)
873 sqlite3_bind_text(stmt, p++, game.metadata.developer.c_str(), -1, SQLITE_TRANSIENT);
874 sqlite3_bind_text(stmt, p++, game.metadata.publisher.c_str(), -1, SQLITE_TRANSIENT);
875 sqlite3_bind_int(stmt, p++, game.metadata.releaseYear);
876 sqlite3_bind_text(stmt, p++, game.metadata.description.c_str(), -1, SQLITE_TRANSIENT);
877 sqlite3_bind_double(stmt, p++, game.metadata.userRating);
878
879 // Image paths (28-33)
880 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.verticalCover.c_str(), -1,
881 SQLITE_TRANSIENT);
882 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.heroImage.c_str(), -1, SQLITE_TRANSIENT);
883 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.logo.c_str(), -1, SQLITE_TRANSIENT);
884 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.header.c_str(), -1, SQLITE_TRANSIENT);
885 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.capsule.c_str(), -1, SQLITE_TRANSIENT);
886 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.icon.c_str(), -1, SQLITE_TRANSIENT);
887
888 // Arrays (34-35)
889 sqlite3_bind_text(stmt, p++, genresJson.c_str(), -1, SQLITE_TRANSIENT);
890 sqlite3_bind_text(stmt, p++, tagsJson.c_str(), -1, SQLITE_TRANSIENT);
891
892 // Steam-specific (36-50)
893 sqlite3_bind_int(stmt, p++, game.metadata.steamAppId);
894 sqlite3_bind_int(stmt, p++, game.metadata.steamInstalled ? 1 : 0);
895 sqlite3_bind_text(stmt, p++, game.metadata.steamLaunchOptions.c_str(), -1, SQLITE_TRANSIENT);
896 sqlite3_bind_text(stmt, p++, game.metadata.steamBuildId.c_str(), -1, SQLITE_TRANSIENT);
897 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.steamPlaytime2Weeks));
898 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamLastLaunch));
899 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamLastExit));
900 sqlite3_bind_text(stmt, p++, game.metadata.steamType.c_str(), -1, SQLITE_TRANSIENT);
901 sqlite3_bind_text(stmt, p++, steamCategoriesJson.c_str(), -1, SQLITE_TRANSIENT);
902 sqlite3_bind_text(stmt, p++, steamUserTagsJson.c_str(), -1, SQLITE_TRANSIENT);
903 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.steamStateFlags));
904 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamBytesDownloaded));
905 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamBytesToDownload));
906 sqlite3_bind_int(stmt, p++, game.metadata.steamIsDownloading ? 1 : 0);
907 sqlite3_bind_int(stmt, p++, game.metadata.steamIsUpdatePending ? 1 : 0);
908
909 // ProtonDB (51-54)
910 sqlite3_bind_text(stmt, p++, game.metadata.protondbTier.c_str(), -1, SQLITE_TRANSIENT);
911 sqlite3_bind_text(stmt, p++, game.metadata.protondbConfidence.c_str(), -1, SQLITE_TRANSIENT);
912 sqlite3_bind_double(stmt, p++, game.metadata.protondbScore);
913 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.protondbLastUpdated));
914
915 // Cloud save (55-59)
916 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.enabled ? 1 : 0);
917 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.supported ? 1 : 0);
918 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.lastSyncState);
919 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.cloudSave.storageBytes));
920 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.cloudSave.lastSyncTime));
921
922 // DLC (60)
923 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.dlc.size()));
925 // Completion (61-62)
926 sqlite3_bind_int(stmt, p++, static_cast<int>(game.completionStatus));
927 sqlite3_bind_text(stmt, p++, game.userNotes.c_str(), -1, SQLITE_TRANSIENT);
928
929 // HLTB (63-69)
930 sqlite3_bind_int(stmt, p++, game.hltbInfo.hltbId);
931 sqlite3_bind_text(stmt, p++, game.hltbInfo.matchedName.c_str(), -1, SQLITE_TRANSIENT);
932 sqlite3_bind_double(stmt, p++, game.hltbInfo.mainStoryHours);
933 sqlite3_bind_double(stmt, p++, game.hltbInfo.mainPlusExtrasHours);
934 sqlite3_bind_double(stmt, p++, game.hltbInfo.completionistHours);
935 sqlite3_bind_double(stmt, p++, game.hltbInfo.allStylesHours);
936 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.hltbInfo.lastUpdated));
937
938 rc = sqlite3_step(stmt);
939 sqlite3_finalize(stmt);
940
941 if (rc != SQLITE_DONE)
942 {
943 lastError_ = sqlite3_errmsg(db_);
944 if (ownTransaction)
945 executeSQL("ROLLBACK");
946 return false;
947 }
948
949 // Add to collections — rollback entire insert if any collection fails
950 for (const auto& collection : game.collections)
951 {
952 if (!addGameToCollectionInternal(game.id, collection))
953 {
954 if (ownTransaction)
955 executeSQL("ROLLBACK");
956 lastError_ = "Failed to add game to collection: " + collection;
957 return false;
958 }
959 }
960
961 if (ownTransaction)
962 executeSQL("COMMIT");
963 return true;
964}
965
966bool GameDatabase::updateGame(const Game& game)
967{
968 std::lock_guard<std::recursive_mutex> lock(mutex_);
969
970 if (!db_)
971 {
972 lastError_ = "Database not open";
973 return false;
974 }
975
976 bool ownTransaction = sqlite3_get_autocommit(db_) != 0;
977 if (ownTransaction)
978 executeSQL("BEGIN TRANSACTION");
979
980 std::string runnerConfigJson = game.serializeRunnerConfig();
981 std::string envVarsJson = jsonFromEnvVars(game.statistics.lastEnvironmentVars);
982 std::string genresJson = jsonArrayFromStrings(game.metadata.genres);
983 std::string tagsJson = jsonArrayFromStrings(game.metadata.tags);
984 std::string steamCategoriesJson = jsonArrayFromStrings(game.metadata.steamCategories);
985 std::string steamUserTagsJson = jsonArrayFromStrings(game.metadata.steamUserCategories);
986
987 std::string configTemplatesJson;
988 if (!game.configTemplates.empty())
989 {
990 json templates = json::object();
991 for (const auto& [name, config] : game.configTemplates)
992 {
993 Game tempGame;
994 tempGame.runnerConfig = config;
995 templates[name] = json::parse(tempGame.serializeRunnerConfig());
996 }
997 configTemplatesJson = templates.dump();
998 }
999
1000 const char* sql = R"SQL(
1001 UPDATE games SET
1002 name = ?, source = ?, runner = ?, status = ?, is_favorite = ?,
1003 install_path = ?, install_size_bytes = ?, runner_config = ?,
1004 config_templates = ?, active_template_name = ?,
1005 times_launched = ?, total_play_time_seconds = ?, last_played = ?, date_added = ?, date_installed = ?,
1006 last_launch_command = ?, last_proton_version = ?, last_exit_reason = ?, last_exit_time = ?,
1007 crash_count = ?, last_environment_vars = ?,
1008 developer = ?, publisher = ?, release_year = ?, description = ?, user_rating = ?,
1009 image_vertical_cover = ?, image_hero = ?, image_logo = ?, image_header = ?, image_capsule = ?, image_icon = ?,
1010 genres = ?, tags = ?,
1011 steam_app_id = ?, steam_installed = ?, steam_launch_options = ?, steam_build_id = ?,
1012 steam_playtime_2weeks = ?, steam_last_launch = ?, steam_last_exit = ?, steam_type = ?,
1013 steam_categories = ?, steam_user_tags = ?,
1014 steam_state_flags = ?, steam_bytes_downloaded = ?, steam_bytes_to_download = ?,
1015 steam_is_downloading = ?, steam_is_update_pending = ?,
1016 protondb_tier = ?, protondb_confidence = ?, protondb_score = ?, protondb_last_updated = ?,
1017 cloud_save_enabled = ?, cloud_save_supported = ?, cloud_save_sync_state = ?, cloud_save_storage_bytes = ?, cloud_save_last_sync = ?,
1018 dlc_count = ?,
1019 completion_status = ?, user_notes = ?,
1020 hltb_id = ?, hltb_matched_name = ?, hltb_main_story = ?, hltb_main_extras = ?, hltb_completionist = ?, hltb_all_styles = ?, hltb_last_updated = ?,
1021 updated_at = strftime('%s', 'now')
1022 WHERE id = ?
1023 )SQL";
1024
1025 sqlite3_stmt* stmt;
1026 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1027 if (rc != SQLITE_OK)
1028 {
1029 lastError_ = sqlite3_errmsg(db_);
1030 if (ownTransaction)
1031 executeSQL("ROLLBACK");
1032 return false;
1033 }
1034
1035 int p = 1;
1036
1037 // Core (1-5, no id — that's in WHERE)
1038 sqlite3_bind_text(stmt, p++, game.name.c_str(), -1, SQLITE_TRANSIENT);
1039 sqlite3_bind_int(stmt, p++, static_cast<int>(game.source));
1040 sqlite3_bind_int(stmt, p++, static_cast<int>(game.runner));
1041 sqlite3_bind_int(stmt, p++, static_cast<int>(game.status));
1042 sqlite3_bind_int(stmt, p++, game.isFavorite ? 1 : 0);
1043
1044 // Install (6-7)
1045 sqlite3_bind_text(stmt, p++, game.installPath.c_str(), -1, SQLITE_TRANSIENT);
1046 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.installSizeBytes));
1047
1048 // Runner config (8)
1049 sqlite3_bind_text(stmt, p++, runnerConfigJson.c_str(), -1, SQLITE_TRANSIENT);
1050
1051 // Config templates (9-10)
1052 if (configTemplatesJson.empty())
1053 sqlite3_bind_null(stmt, p++);
1054 else
1055 sqlite3_bind_text(stmt, p++, configTemplatesJson.c_str(), -1, SQLITE_TRANSIENT);
1056 sqlite3_bind_text(stmt, p++, game.activeTemplateName.c_str(), -1, SQLITE_TRANSIENT);
1057
1058 // Statistics (11-15)
1059 sqlite3_bind_int(stmt, p++, game.statistics.timesLaunched);
1060 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.totalPlayTimeSeconds));
1061 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.lastPlayed));
1062 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.dateAdded));
1063 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.dateInstalled));
1064
1065 // Launch tracking (16-21)
1066 sqlite3_bind_text(stmt, p++, game.statistics.lastLaunchCommand.c_str(), -1, SQLITE_TRANSIENT);
1067 sqlite3_bind_text(stmt, p++, game.statistics.lastProtonVersion.c_str(), -1, SQLITE_TRANSIENT);
1068 sqlite3_bind_text(stmt, p++, game.statistics.lastExitReason.c_str(), -1, SQLITE_TRANSIENT);
1069 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.statistics.lastExitTime));
1070 sqlite3_bind_int(stmt, p++, game.statistics.crashCount);
1071 sqlite3_bind_text(stmt, p++, envVarsJson.c_str(), -1, SQLITE_TRANSIENT);
1072
1073 // Descriptive metadata (22-26)
1074 sqlite3_bind_text(stmt, p++, game.metadata.developer.c_str(), -1, SQLITE_TRANSIENT);
1075 sqlite3_bind_text(stmt, p++, game.metadata.publisher.c_str(), -1, SQLITE_TRANSIENT);
1076 sqlite3_bind_int(stmt, p++, game.metadata.releaseYear);
1077 sqlite3_bind_text(stmt, p++, game.metadata.description.c_str(), -1, SQLITE_TRANSIENT);
1078 sqlite3_bind_double(stmt, p++, game.metadata.userRating);
1079
1080 // Image paths (27-32)
1081 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.verticalCover.c_str(), -1,
1082 SQLITE_TRANSIENT);
1083 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.heroImage.c_str(), -1, SQLITE_TRANSIENT);
1084 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.logo.c_str(), -1, SQLITE_TRANSIENT);
1085 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.header.c_str(), -1, SQLITE_TRANSIENT);
1086 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.capsule.c_str(), -1, SQLITE_TRANSIENT);
1087 sqlite3_bind_text(stmt, p++, game.metadata.imagePaths.icon.c_str(), -1, SQLITE_TRANSIENT);
1088
1089 // Arrays (33-34)
1090 sqlite3_bind_text(stmt, p++, genresJson.c_str(), -1, SQLITE_TRANSIENT);
1091 sqlite3_bind_text(stmt, p++, tagsJson.c_str(), -1, SQLITE_TRANSIENT);
1092
1093 // Steam-specific (35-49)
1094 sqlite3_bind_int(stmt, p++, game.metadata.steamAppId);
1095 sqlite3_bind_int(stmt, p++, game.metadata.steamInstalled ? 1 : 0);
1096 sqlite3_bind_text(stmt, p++, game.metadata.steamLaunchOptions.c_str(), -1, SQLITE_TRANSIENT);
1097 sqlite3_bind_text(stmt, p++, game.metadata.steamBuildId.c_str(), -1, SQLITE_TRANSIENT);
1098 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.steamPlaytime2Weeks));
1099 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamLastLaunch));
1100 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamLastExit));
1101 sqlite3_bind_text(stmt, p++, game.metadata.steamType.c_str(), -1, SQLITE_TRANSIENT);
1102 sqlite3_bind_text(stmt, p++, steamCategoriesJson.c_str(), -1, SQLITE_TRANSIENT);
1103 sqlite3_bind_text(stmt, p++, steamUserTagsJson.c_str(), -1, SQLITE_TRANSIENT);
1104 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.steamStateFlags));
1105 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamBytesDownloaded));
1106 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.steamBytesToDownload));
1107 sqlite3_bind_int(stmt, p++, game.metadata.steamIsDownloading ? 1 : 0);
1108 sqlite3_bind_int(stmt, p++, game.metadata.steamIsUpdatePending ? 1 : 0);
1109
1110 // ProtonDB (50-53)
1111 sqlite3_bind_text(stmt, p++, game.metadata.protondbTier.c_str(), -1, SQLITE_TRANSIENT);
1112 sqlite3_bind_text(stmt, p++, game.metadata.protondbConfidence.c_str(), -1, SQLITE_TRANSIENT);
1113 sqlite3_bind_double(stmt, p++, game.metadata.protondbScore);
1114 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.protondbLastUpdated));
1115
1116 // Cloud save (54-58)
1117 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.enabled ? 1 : 0);
1118 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.supported ? 1 : 0);
1119 sqlite3_bind_int(stmt, p++, game.metadata.cloudSave.lastSyncState);
1120 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.cloudSave.storageBytes));
1121 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.metadata.cloudSave.lastSyncTime));
1123 // DLC (59)
1124 sqlite3_bind_int(stmt, p++, static_cast<int>(game.metadata.dlc.size()));
1125
1126 // Completion (60-61)
1127 sqlite3_bind_int(stmt, p++, static_cast<int>(game.completionStatus));
1128 sqlite3_bind_text(stmt, p++, game.userNotes.c_str(), -1, SQLITE_TRANSIENT);
1129
1130 // HLTB (62-68)
1131 sqlite3_bind_int(stmt, p++, game.hltbInfo.hltbId);
1132 sqlite3_bind_text(stmt, p++, game.hltbInfo.matchedName.c_str(), -1, SQLITE_TRANSIENT);
1133 sqlite3_bind_double(stmt, p++, game.hltbInfo.mainStoryHours);
1134 sqlite3_bind_double(stmt, p++, game.hltbInfo.mainPlusExtrasHours);
1135 sqlite3_bind_double(stmt, p++, game.hltbInfo.completionistHours);
1136 sqlite3_bind_double(stmt, p++, game.hltbInfo.allStylesHours);
1137 sqlite3_bind_int64(stmt, p++, static_cast<sqlite3_int64>(game.hltbInfo.lastUpdated));
1138
1139 // WHERE id = ? (69)
1140 sqlite3_bind_text(stmt, p++, game.id.c_str(), -1, SQLITE_TRANSIENT);
1141
1142 rc = sqlite3_step(stmt);
1143 sqlite3_finalize(stmt);
1144
1145 if (rc != SQLITE_DONE)
1146 {
1147 lastError_ = sqlite3_errmsg(db_);
1148 if (ownTransaction)
1149 executeSQL("ROLLBACK");
1150 return false;
1151 }
1152
1153 // Update collections atomically: delete old, insert new
1154 {
1155 const char* deleteSql = "DELETE FROM game_collections WHERE game_id = ?";
1156 sqlite3_stmt* deleteStmt;
1157 if (sqlite3_prepare_v2(db_, deleteSql, -1, &deleteStmt, nullptr) == SQLITE_OK)
1158 {
1159 sqlite3_bind_text(deleteStmt, 1, game.id.c_str(), -1, SQLITE_TRANSIENT);
1160 int delRc = sqlite3_step(deleteStmt);
1161 sqlite3_finalize(deleteStmt);
1162 if (delRc != SQLITE_DONE)
1163 {
1164 if (ownTransaction)
1165 executeSQL("ROLLBACK");
1166 lastError_ = sqlite3_errmsg(db_);
1167 return false;
1168 }
1169 }
1170 }
1171 for (const auto& collection : game.collections)
1172 {
1173 if (!addGameToCollectionInternal(game.id, collection))
1174 {
1175 if (ownTransaction)
1176 executeSQL("ROLLBACK");
1177 lastError_ = "Failed to add game to collection: " + collection;
1178 return false;
1179 }
1180 }
1181
1182 if (ownTransaction)
1183 executeSQL("COMMIT");
1184 return true;
1185}
1186
1187bool GameDatabase::deleteGame(const std::string& gameId)
1188{
1189 std::lock_guard<std::recursive_mutex> lock(mutex_);
1190
1191 if (!db_)
1192 {
1193 lastError_ = "Database not open";
1194 return false;
1195 }
1196
1197 const char* sql = "DELETE FROM games WHERE id = ?";
1198
1199 sqlite3_stmt* stmt;
1200 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1201 if (rc != SQLITE_OK)
1202 {
1203 lastError_ = sqlite3_errmsg(db_);
1204 return false;
1205 }
1206
1207 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1208
1209 rc = sqlite3_step(stmt);
1210 sqlite3_finalize(stmt);
1211
1212 if (rc != SQLITE_DONE)
1213 {
1214 lastError_ = sqlite3_errmsg(db_);
1215 return false;
1216 }
1217
1218 return true;
1219}
1220
1221bool GameDatabase::updateGameImages(const std::string& gameId, const GameImagePaths& images)
1222{
1223 std::lock_guard<std::recursive_mutex> lock(mutex_);
1224
1225 if (!db_)
1226 {
1227 lastError_ = "Database not open";
1228 return false;
1229 }
1230
1231 static const char* sql = R"SQL(
1232 UPDATE games SET
1233 image_vertical_cover = ?,
1234 image_hero = ?,
1235 image_logo = ?,
1236 image_header = ?,
1237 image_capsule = ?,
1238 image_icon = ?,
1239 updated_at = strftime('%s', 'now')
1240 WHERE id = ?
1241 )SQL";
1242
1243 sqlite3_stmt* stmt = getCachedStatement(sql);
1244 if (!stmt)
1245 {
1246 lastError_ = "Failed to prepare updateGameImages statement";
1247 return false;
1248 }
1249
1250 sqlite3_bind_text(stmt, 1, images.verticalCover.c_str(), -1, SQLITE_TRANSIENT);
1251 sqlite3_bind_text(stmt, 2, images.heroImage.c_str(), -1, SQLITE_TRANSIENT);
1252 sqlite3_bind_text(stmt, 3, images.logo.c_str(), -1, SQLITE_TRANSIENT);
1253 sqlite3_bind_text(stmt, 4, images.header.c_str(), -1, SQLITE_TRANSIENT);
1254 sqlite3_bind_text(stmt, 5, images.capsule.c_str(), -1, SQLITE_TRANSIENT);
1255 sqlite3_bind_text(stmt, 6, images.icon.c_str(), -1, SQLITE_TRANSIENT);
1256 sqlite3_bind_text(stmt, 7, gameId.c_str(), -1, SQLITE_TRANSIENT);
1257
1258 int rc = sqlite3_step(stmt);
1259 if (rc != SQLITE_DONE)
1260 {
1261 lastError_ = sqlite3_errmsg(db_);
1262 return false;
1263 }
1264
1265 return true;
1266}
1267
1268std::vector<Game> GameDatabase::getGamesWithoutCoverArt(int limit) const
1269{
1270 std::lock_guard<std::recursive_mutex> lock(mutex_);
1271
1272 std::vector<Game> results;
1273 if (!db_)
1274 {
1275 lastError_ = "Database not open";
1276 return results;
1277 }
1278
1279 std::string sql = "SELECT " + std::string(GAME_COLUMNS) +
1280 " FROM games g"
1281 " WHERE g.steam_app_id > 0 AND ("
1282 " (g.image_vertical_cover IS NULL OR g.image_vertical_cover = '') OR"
1283 " (g.image_hero IS NULL OR g.image_hero = '')"
1284 ")";
1285
1286 if (limit > 0)
1287 sql += " LIMIT ?";
1288
1289 sqlite3_stmt* stmt;
1290 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr);
1291 if (rc != SQLITE_OK)
1292 {
1293 lastError_ = sqlite3_errmsg(db_);
1294 return results;
1295 }
1296
1297 if (limit > 0)
1298 sqlite3_bind_int(stmt, 1, limit);
1299
1300 while (sqlite3_step(stmt) == SQLITE_ROW)
1301 results.push_back(gameFromStatement(stmt));
1302 sqlite3_finalize(stmt);
1303
1304 return results;
1305}
1306
1307std::optional<Game> GameDatabase::getGame(const std::string& gameId) const
1308{
1309 std::lock_guard<std::recursive_mutex> lock(mutex_);
1310
1311 if (!db_)
1312 {
1313 lastError_ = "Database not open";
1314 return std::nullopt;
1315 }
1316
1317 std::string sqlStr = "SELECT " + std::string(GAME_COLUMNS) + " FROM games g WHERE g.id = ?";
1318
1319 sqlite3_stmt* stmt;
1320 int rc = sqlite3_prepare_v2(db_, sqlStr.c_str(), -1, &stmt, nullptr);
1321 if (rc != SQLITE_OK)
1322 {
1323 lastError_ = sqlite3_errmsg(db_);
1324 return std::nullopt;
1325 }
1326
1327 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1328
1329 rc = sqlite3_step(stmt);
1330 if (rc != SQLITE_ROW)
1331 {
1332 sqlite3_finalize(stmt);
1333 return std::nullopt;
1334 }
1335
1336 Game game = gameFromStatement(stmt);
1337 sqlite3_finalize(stmt);
1338
1339 // Load collections
1340 const char* collSql = R"SQL(
1341 SELECT c.name FROM collections c
1342 JOIN game_collections gc ON c.id = gc.collection_id
1343 WHERE gc.game_id = ?
1344 )SQL";
1345
1346 sqlite3_stmt* collStmt;
1347 if (sqlite3_prepare_v2(db_, collSql, -1, &collStmt, nullptr) == SQLITE_OK)
1348 {
1349 sqlite3_bind_text(collStmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1350 while (sqlite3_step(collStmt) == SQLITE_ROW)
1351 {
1352 const char* name = reinterpret_cast<const char*>(sqlite3_column_text(collStmt, 0));
1353 if (name)
1354 game.collections.push_back(std::string(name));
1355 }
1356 sqlite3_finalize(collStmt);
1357 }
1358
1359 return game;
1360}
1361
1362bool GameDatabase::gameExists(const std::string& gameId) const
1363{
1364 std::lock_guard<std::recursive_mutex> lock(mutex_);
1365
1366 if (!db_)
1367 return false;
1368
1369 static const char* sql = "SELECT 1 FROM games WHERE id = ?";
1370
1371 sqlite3_stmt* stmt = getCachedStatement(sql);
1372 if (!stmt)
1373 {
1374 lastError_ = "Failed to prepare gameExists statement";
1375 return false;
1376 }
1377
1378 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1379
1380 int rc = sqlite3_step(stmt);
1381 return rc == SQLITE_ROW;
1382}
1383
1384// ==============================================================================
1385// Query Operations
1386// ==============================================================================
1387
1388std::vector<Game> GameDatabase::queryGames(const DatabaseFilterOptions& filter,
1389 const DatabaseSortOptions& sort, int limit,
1390 int offset) const
1391{
1392 std::lock_guard<std::recursive_mutex> lock(mutex_);
1393
1394 std::vector<Game> results;
1395
1396 if (!db_)
1397 {
1398 lastError_ = "Database not open";
1399 return results;
1400 }
1401
1402 std::string sql = "SELECT DISTINCT " + std::string(GAME_COLUMNS) + " FROM games g";
1403
1404 if (!filter.collection.empty())
1405 {
1406 sql += R"SQL(
1407 JOIN game_collections gc ON g.id = gc.game_id
1408 JOIN collections c ON gc.collection_id = c.id
1409 )SQL";
1410 }
1411
1412 // Build WHERE clause with parameterized queries
1413 std::vector<std::string> conditions;
1414 std::vector<std::pair<int, std::string>> stringBindings;
1415 std::vector<std::pair<int, int>> intBindings;
1416 int paramIndex = 1;
1417
1418 if (!filter.searchQuery.empty())
1419 {
1420 // Escape LIKE special characters to prevent unintended wildcard matching
1421 std::string escaped;
1422 escaped.reserve(filter.searchQuery.size());
1423 for (char c : filter.searchQuery)
1424 {
1425 if (c == '%' || c == '_' || c == '\\')
1426 escaped += '\\';
1427 escaped += c;
1428 }
1429 conditions.push_back("g.name LIKE ? ESCAPE '\\'");
1430 stringBindings.push_back({paramIndex++, "%" + escaped + "%"});
1431 }
1432 if (filter.favoritesOnly)
1433 conditions.push_back("g.is_favorite = 1");
1434 if (filter.installedOnly)
1435 {
1436 conditions.push_back("g.status = ?");
1437 intBindings.push_back({paramIndex++, static_cast<int>(GameStatus::Installed)});
1438 }
1439 if (filter.sourceFilter.has_value())
1440 {
1441 conditions.push_back("g.source = ?");
1442 intBindings.push_back({paramIndex++, static_cast<int>(*filter.sourceFilter)});
1443 }
1444 if (filter.runnerFilter.has_value())
1445 {
1446 conditions.push_back("g.runner = ?");
1447 intBindings.push_back({paramIndex++, static_cast<int>(*filter.runnerFilter)});
1448 }
1449 if (!filter.collection.empty())
1450 {
1451 conditions.push_back("c.name = ?");
1452 stringBindings.push_back({paramIndex++, filter.collection});
1453 }
1454
1455 if (!conditions.empty())
1456 {
1457 sql += " WHERE ";
1458 for (size_t i = 0; i < conditions.size(); ++i)
1459 {
1460 if (i > 0)
1461 sql += " AND ";
1462 sql += conditions[i];
1463 }
1464 }
1465
1466 // ORDER BY
1467 sql += " ORDER BY ";
1468 switch (sort.field)
1469 {
1471 sql += "g.name COLLATE NOCASE";
1472 break;
1474 sql += "g.last_played";
1475 break;
1477 sql += "g.total_play_time_seconds";
1478 break;
1480 sql += "g.date_added";
1481 break;
1483 sql += "g.source";
1484 break;
1486 sql += "g.runner";
1487 break;
1488 }
1489 sql += (sort.order == DatabaseSortOptions::Order::Descending) ? " DESC" : " ASC";
1490
1491 if (limit > 0)
1493 sql += " LIMIT ?";
1494 intBindings.push_back({paramIndex++, limit});
1495 if (offset > 0)
1496 {
1497 sql += " OFFSET ?";
1498 intBindings.push_back({paramIndex++, offset});
1499 }
1500 }
1501
1502 sqlite3_stmt* stmt;
1503 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr);
1504 if (rc != SQLITE_OK)
1505 {
1506 lastError_ = sqlite3_errmsg(db_);
1507 return results;
1508 }
1509
1510 for (const auto& [idx, value] : stringBindings)
1511 sqlite3_bind_text(stmt, idx, value.c_str(), -1, SQLITE_TRANSIENT);
1512 for (const auto& [idx, value] : intBindings)
1513 sqlite3_bind_int(stmt, idx, value);
1514
1515 while (sqlite3_step(stmt) == SQLITE_ROW)
1516 results.push_back(gameFromStatement(stmt));
1517
1518 sqlite3_finalize(stmt);
1519
1520 // Load collections only for the returned games (scoped to result set to avoid full-table scan)
1521 if (!results.empty())
1522 {
1523 std::unordered_map<std::string, std::vector<std::string>> collectionsMap;
1524
1525 // Build parameterized IN-clause using ? placeholders — no string concat with IDs
1526 std::string collSqlStr = "SELECT gc.game_id, c.name "
1527 "FROM game_collections gc "
1528 "JOIN collections c ON c.id = gc.collection_id "
1529 "WHERE gc.game_id IN (";
1530 for (size_t i = 0; i < results.size(); ++i)
1531 {
1532 if (i > 0)
1533 collSqlStr += ',';
1534 collSqlStr += '?';
1535 }
1536 collSqlStr += ") ORDER BY gc.game_id, c.name";
1537
1538 sqlite3_stmt* collStmt = nullptr;
1539 if (sqlite3_prepare_v2(db_, collSqlStr.c_str(), -1, &collStmt, nullptr) == SQLITE_OK)
1540 {
1541 for (size_t i = 0; i < results.size(); ++i)
1542 {
1543 sqlite3_bind_text(collStmt, static_cast<int>(i + 1), results[i].id.c_str(), -1,
1544 SQLITE_TRANSIENT);
1545 }
1546 while (sqlite3_step(collStmt) == SQLITE_ROW)
1547 {
1548 const char* gameId =
1549 reinterpret_cast<const char*>(sqlite3_column_text(collStmt, 0));
1550 const char* collName =
1551 reinterpret_cast<const char*>(sqlite3_column_text(collStmt, 1));
1552 if (gameId && collName)
1553 collectionsMap[std::string(gameId)].push_back(std::string(collName));
1555 sqlite3_finalize(collStmt);
1556 }
1557 else
1558 {
1559 Logger::error("[GameDatabase] Failed to prepare collection query: {}",
1560 sqlite3_errmsg(db_));
1561 }
1562
1563 for (auto& game : results)
1564 {
1565 auto it = collectionsMap.find(game.id);
1566 if (it != collectionsMap.end())
1567 game.collections = std::move(it->second);
1568 }
1569 }
1570
1571 return results;
1572}
1573
1574std::vector<Game> GameDatabase::getAllGames() const
1575{
1576 return queryGames();
1577}
1578
1580{
1581 std::lock_guard<std::recursive_mutex> lock(mutex_);
1582
1583 if (!db_)
1584 return 0;
1585
1586 std::string sql = "SELECT COUNT(*) FROM games g";
1587
1588 std::vector<std::string> conditions;
1589 std::vector<std::pair<int, int>> intBindings;
1590 int paramIdx = 1;
1591
1592 if (filter.favoritesOnly)
1593 conditions.push_back("is_favorite = 1");
1594 if (filter.installedOnly)
1595 {
1596 conditions.push_back("status = ?");
1597 intBindings.push_back({paramIdx++, static_cast<int>(GameStatus::Installed)});
1598 }
1599 if (filter.sourceFilter.has_value())
1600 {
1601 conditions.push_back("source = ?");
1602 intBindings.push_back({paramIdx++, static_cast<int>(*filter.sourceFilter)});
1603 }
1604 if (filter.runnerFilter.has_value())
1605 {
1606 conditions.push_back("runner = ?");
1607 intBindings.push_back({paramIdx++, static_cast<int>(*filter.runnerFilter)});
1608 }
1609
1610 if (!conditions.empty())
1611 {
1612 sql += " WHERE ";
1613 for (size_t i = 0; i < conditions.size(); ++i)
1614 {
1615 if (i > 0)
1616 sql += " AND ";
1617 sql += conditions[i];
1618 }
1619 }
1620
1621 sqlite3_stmt* stmt;
1622 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr);
1623 if (rc != SQLITE_OK)
1624 return 0;
1625
1626 for (const auto& [idx, value] : intBindings)
1627 sqlite3_bind_int(stmt, idx, value);
1628
1629 rc = sqlite3_step(stmt);
1630 int count = (rc == SQLITE_ROW) ? sqlite3_column_int(stmt, 0) : 0;
1631 sqlite3_finalize(stmt);
1632
1633 return count;
1635
1636std::vector<Game> GameDatabase::searchGames(const std::string& query, int limit) const
1637{
1638 std::lock_guard<std::recursive_mutex> lock(mutex_);
1639
1640 std::vector<Game> results;
1641 if (!db_ || query.empty())
1642 return results;
1643
1644 // Try FTS search first
1645 std::string sql = "SELECT " + std::string(GAME_COLUMNS) +
1646 " FROM games g JOIN games_fts ON g.rowid = games_fts.rowid"
1647 " WHERE games_fts MATCH ? ORDER BY rank LIMIT ?";
1648
1649 sqlite3_stmt* stmt;
1650 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr);
1651
1652 if (rc != SQLITE_OK)
1653 {
1654 // Fall back to LIKE search (with ESCAPE clause)
1655 sql =
1656 "SELECT " + std::string(GAME_COLUMNS) +
1657 " FROM games g WHERE g.name LIKE ? ESCAPE '\\' ORDER BY g.name COLLATE NOCASE LIMIT ?";
1658
1659 rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt, nullptr);
1660 if (rc != SQLITE_OK)
1661 {
1662 lastError_ = sqlite3_errmsg(db_);
1663 return results;
1664 }
1665
1666 // Escape LIKE metacharacters so they are treated as literals
1667 std::string escaped;
1668 escaped.reserve(query.size() * 2);
1669 for (char c : query)
1670 {
1671 if (c == '%' || c == '_' || c == '\\')
1672 escaped += '\\';
1673 escaped += c;
1674 }
1675 std::string likeQuery = "%" + escaped + "%";
1676 sqlite3_bind_text(stmt, 1, likeQuery.c_str(), -1, SQLITE_TRANSIENT);
1677 }
1678 else
1679 {
1680 // Sanitize FTS5 query: wrap each word in double quotes to prevent
1681 // FTS5 syntax injection (operators like AND, OR, NOT, *, etc.)
1682 std::string sanitized;
1683 std::istringstream words(query);
1684 std::string word;
1685 while (words >> word)
1686 {
1687 // Remove any existing double quotes from the word
1688 word.erase(std::remove(word.begin(), word.end(), '"'), word.end());
1689 if (word.empty())
1690 continue;
1691 if (!sanitized.empty())
1692 sanitized += ' ';
1693 sanitized += '"' + word + '"';
1694 }
1695 if (sanitized.empty())
1696 {
1697 sqlite3_finalize(stmt);
1698 return results;
1699 }
1700 sqlite3_bind_text(stmt, 1, sanitized.c_str(), -1, SQLITE_TRANSIENT);
1701 }
1703 sqlite3_bind_int(stmt, 2, limit);
1704
1705 while (sqlite3_step(stmt) == SQLITE_ROW)
1706 results.push_back(gameFromStatement(stmt));
1707
1708 sqlite3_finalize(stmt);
1709 return results;
1710}
1711
1712// ==============================================================================
1713// Collection Operations
1714// ==============================================================================
1715
1716std::vector<std::string> GameDatabase::getCollections() const
1717{
1718 std::lock_guard<std::recursive_mutex> lock(mutex_);
1719
1720 std::vector<std::string> collections;
1721 if (!db_)
1722 return collections;
1723
1724 const char* sql = "SELECT name FROM collections ORDER BY name";
1725
1726 sqlite3_stmt* stmt;
1727 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1728 if (rc != SQLITE_OK)
1729 return collections;
1730
1731 while (sqlite3_step(stmt) == SQLITE_ROW)
1732 {
1733 const char* name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
1734 if (name)
1735 collections.push_back(name);
1736 }
1737
1738 sqlite3_finalize(stmt);
1739 return collections;
1740}
1741
1742bool GameDatabase::addCollection(const std::string& name)
1743{
1744 std::lock_guard<std::recursive_mutex> lock(mutex_);
1745
1746 if (!db_)
1747 return false;
1748
1749 const char* sql = "INSERT OR IGNORE INTO collections (name) VALUES (?)";
1750
1751 sqlite3_stmt* stmt;
1752 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1753 if (rc != SQLITE_OK)
1754 return false;
1755
1756 sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_TRANSIENT);
1757 rc = sqlite3_step(stmt);
1758 sqlite3_finalize(stmt);
1759
1760 return rc == SQLITE_DONE;
1761}
1762
1763bool GameDatabase::removeCollection(const std::string& name)
1764{
1765 std::lock_guard<std::recursive_mutex> lock(mutex_);
1766
1767 if (!db_)
1768 return false;
1769
1770 const char* sql = "DELETE FROM collections WHERE name = ?";
1771
1772 sqlite3_stmt* stmt;
1773 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1774 if (rc != SQLITE_OK)
1775 return false;
1776
1777 sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_TRANSIENT);
1778 rc = sqlite3_step(stmt);
1779 sqlite3_finalize(stmt);
1780
1781 return rc == SQLITE_DONE;
1782}
1783
1784bool GameDatabase::addGameToCollection(const std::string& gameId, const std::string& collection)
1785{
1786 std::lock_guard<std::recursive_mutex> lock(mutex_);
1787 return addGameToCollectionInternal(gameId, collection);
1788}
1789
1790bool GameDatabase::addGameToCollectionInternal(const std::string& gameId,
1791 const std::string& collection)
1792{
1793 if (!db_)
1794 return false;
1795
1796 // Ensure collection exists. Previously this swallowed prepare_v2
1797 // failures silently — if the prepare failed, the second INSERT below
1798 // would silently match no rows (because the collection wouldn't exist
1799 // and the SELECT-by-name would return zero rows), and the function
1800 // would return true (rc == SQLITE_DONE). The user would think they
1801 // added a game to a collection that doesn't exist. Log so the
1802 // failure is at least observable in the launcher log.
1803 {
1804 const char* sql = "INSERT OR IGNORE INTO collections (name) VALUES (?)";
1805 sqlite3_stmt* stmt = nullptr;
1806 const int prepRc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1807 if (prepRc == SQLITE_OK)
1808 {
1809 sqlite3_bind_text(stmt, 1, collection.c_str(), -1, SQLITE_TRANSIENT);
1810 sqlite3_step(stmt);
1811 sqlite3_finalize(stmt);
1812 }
1813 else
1814 {
1815 Logger::warn("[GameDatabase] Failed to prepare collection-insert ('{}'): {} ({})",
1816 collection, sqlite3_errmsg(db_), prepRc);
1817 return false;
1818 }
1819 }
1820
1821 const char* sql = R"SQL(
1822 INSERT OR IGNORE INTO game_collections (game_id, collection_id)
1823 SELECT ?, id FROM collections WHERE name = ?
1824 )SQL";
1825
1826 sqlite3_stmt* stmt;
1827 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1828 if (rc != SQLITE_OK)
1829 return false;
1830
1831 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1832 sqlite3_bind_text(stmt, 2, collection.c_str(), -1, SQLITE_TRANSIENT);
1833 rc = sqlite3_step(stmt);
1834 sqlite3_finalize(stmt);
1835
1836 return rc == SQLITE_DONE;
1837}
1838
1839bool GameDatabase::removeGameFromCollection(const std::string& gameId,
1840 const std::string& collection)
1841{
1842 std::lock_guard<std::recursive_mutex> lock(mutex_);
1843 return removeGameFromCollectionInternal(gameId, collection);
1844}
1845
1846bool GameDatabase::removeGameFromCollectionInternal(const std::string& gameId,
1847 const std::string& collection)
1848{
1849 if (!db_)
1850 return false;
1851
1852 const char* sql = R"SQL(
1853 DELETE FROM game_collections
1854 WHERE game_id = ?
1855 AND collection_id = (SELECT id FROM collections WHERE name = ?)
1856 )SQL";
1857
1858 sqlite3_stmt* stmt;
1859 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
1860 if (rc != SQLITE_OK)
1861 return false;
1862
1863 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1864 sqlite3_bind_text(stmt, 2, collection.c_str(), -1, SQLITE_TRANSIENT);
1865 rc = sqlite3_step(stmt);
1866 sqlite3_finalize(stmt);
1867
1868 return rc == SQLITE_DONE;
1870
1871// ==============================================================================
1872// JSON Export/Import (using nlohmann/json)
1873// ==============================================================================
1874
1875bool GameDatabase::exportToJson(const std::string& path) const
1876{
1877 auto games = getAllGames();
1878
1879 if (games.empty())
1880 {
1881 std::lock_guard<std::recursive_mutex> lock(mutex_);
1882 if (!db_)
1883 {
1884 lastError_ = "Database not open";
1885 return false;
1886 }
1887 }
1888
1889 json arr = json::array();
1890
1891 for (const auto& g : games)
1892 {
1893 json obj;
1894
1895 // Core
1896 obj["id"] = g.id;
1897 obj["name"] = g.name;
1898 obj["source"] = static_cast<int>(g.source);
1899 obj["runner"] = static_cast<int>(g.runner);
1900 obj["status"] = static_cast<int>(g.status);
1901 obj["isFavorite"] = g.isFavorite;
1902 obj["installPath"] = g.installPath;
1903 obj["installSizeBytes"] = g.installSizeBytes;
1904
1905 // Runner config and metadata as nested JSON
1906 obj["runnerConfig"] = json::parse(g.serializeRunnerConfig());
1907 obj["metadata"] = json::parse(g.serializeMetadata());
1908
1909 // Statistics
1910 obj["timesLaunched"] = g.statistics.timesLaunched;
1911 obj["totalPlayTimeSeconds"] = g.statistics.totalPlayTimeSeconds;
1912 obj["lastPlayed"] = static_cast<int64_t>(g.statistics.lastPlayed);
1913 obj["dateAdded"] = static_cast<int64_t>(g.statistics.dateAdded);
1914 obj["dateInstalled"] = static_cast<int64_t>(g.statistics.dateInstalled);
1915 obj["lastLaunchCommand"] = g.statistics.lastLaunchCommand;
1916 obj["lastProtonVersion"] = g.statistics.lastProtonVersion;
1917 obj["lastExitReason"] = g.statistics.lastExitReason;
1918 obj["lastExitTime"] = static_cast<int64_t>(g.statistics.lastExitTime);
1919 obj["crashCount"] = g.statistics.crashCount;
1920
1921 // Environment vars
1922 json envObj = json::object();
1923 for (const auto& [k, v] : g.statistics.lastEnvironmentVars)
1924 envObj[k] = v;
1925 obj["lastEnvironmentVars"] = envObj;
1926
1927 // Completion
1928 obj["completionStatus"] = static_cast<int>(g.completionStatus);
1929 obj["userNotes"] = g.userNotes;
1930
1931 // HLTB
1932 obj["hltbId"] = g.hltbInfo.hltbId;
1933 obj["hltbMatchedName"] = g.hltbInfo.matchedName;
1934 obj["hltbMainStory"] = g.hltbInfo.mainStoryHours;
1935 obj["hltbMainExtras"] = g.hltbInfo.mainPlusExtrasHours;
1936 obj["hltbCompletionist"] = g.hltbInfo.completionistHours;
1937 obj["hltbAllStyles"] = g.hltbInfo.allStylesHours;
1938 obj["hltbLastUpdated"] = static_cast<int64_t>(g.hltbInfo.lastUpdated);
1939
1940 // Collections
1941 obj["collections"] = g.collections;
1942
1943 arr.push_back(obj);
1944 }
1945
1946 std::ofstream file(path);
1947 if (!file.is_open())
1948 {
1949 lastError_ = "Failed to open file for writing";
1950 return false;
1951 }
1952
1953 file << arr.dump(2);
1954 Logger::info("Exported {} games to JSON: {}", games.size(), path);
1955 return true;
1956}
1957
1958int GameDatabase::importFromJson(const std::string& path, bool overwriteExisting)
1959{
1960 std::ifstream file(path);
1961 if (!file.is_open())
1962 {
1963 lastError_ = "Failed to open file for reading: " + path;
1964 return -1;
1965 }
1966
1967 json arr;
1968 try
1969 {
1970 arr = json::parse(file);
1971 }
1972 catch (const json::exception& e)
1973 {
1974 lastError_ = std::string("JSON parse error: ") + e.what();
1975 return -1;
1976 }
1977
1978 if (!arr.is_array())
1979 {
1980 lastError_ = "Expected JSON array at top level";
1981 return -1;
1982 }
1983
1984 int imported = 0;
1985 int skipped = 0;
1986 int errors = 0;
1987
1988 for (const auto& obj : arr)
1989 {
1990 Game game;
1991
1992 try
1993 {
1994 game.id = obj.value("id", "");
1995 game.name = obj.value("name", "");
1996
1997 if (game.id.empty() || game.name.empty())
1998 {
1999 Logger::warn("Skipping game with missing id or name in JSON import");
2000 ++errors;
2001 continue;
2002 }
2003
2004 game.source =
2005 core::safeEnumCast(obj.value("source", 0), GameSource::Unknown, kMaxGameSource);
2006 game.runner =
2007 core::safeEnumCast(obj.value("runner", 0), GameRunner::Native, kMaxGameRunner);
2008 game.status = core::safeEnumCast(obj.value("status", 0), GameStatus::NotInstalled,
2009 kMaxGameStatus);
2010 game.isFavorite = obj.value("isFavorite", false);
2011 game.installPath = obj.value("installPath", "");
2012 game.installSizeBytes = obj.value("installSizeBytes", static_cast<uint64_t>(0));
2013
2014 // Runner config
2015 if (obj.contains("runnerConfig") && obj["runnerConfig"].is_object())
2016 game.deserializeRunnerConfig(obj["runnerConfig"].dump());
2017
2018 // Metadata
2019 if (obj.contains("metadata") && obj["metadata"].is_object())
2020 game.deserializeMetadata(obj["metadata"].dump());
2022 // Statistics
2023 game.statistics.totalPlayTimeSeconds = obj.value("totalPlayTimeSeconds", 0.0);
2024 game.statistics.timesLaunched = obj.value("timesLaunched", 0);
2025 game.statistics.lastPlayed =
2026 static_cast<time_t>(obj.value("lastPlayed", static_cast<int64_t>(0)));
2028 static_cast<time_t>(obj.value("dateAdded", static_cast<int64_t>(0)));
2030 static_cast<time_t>(obj.value("dateInstalled", static_cast<int64_t>(0)));
2031 game.statistics.lastLaunchCommand = obj.value("lastLaunchCommand", "");
2032 game.statistics.lastProtonVersion = obj.value("lastProtonVersion", "");
2033 game.statistics.lastExitReason = obj.value("lastExitReason", "");
2035 static_cast<time_t>(obj.value("lastExitTime", static_cast<int64_t>(0)));
2036 game.statistics.crashCount = obj.value("crashCount", 0);
2037
2038 // Environment vars
2039 if (obj.contains("lastEnvironmentVars") && obj["lastEnvironmentVars"].is_object())
2040 {
2041 for (auto& [k, v] : obj["lastEnvironmentVars"].items())
2042 {
2043 if (v.is_string())
2044 game.statistics.lastEnvironmentVars[k] = v.get<std::string>();
2045 }
2046 }
2047
2048 // Completion
2049 game.completionStatus =
2050 core::safeEnumCast(obj.value("completionStatus", 0), CompletionStatus::NotPlayed,
2051 kMaxCompletionStatus);
2052 game.userNotes = obj.value("userNotes", "");
2053
2054 // HLTB
2055 game.hltbInfo.hltbId = obj.value("hltbId", 0);
2056 game.hltbInfo.matchedName = obj.value("hltbMatchedName", "");
2057 game.hltbInfo.mainStoryHours = obj.value("hltbMainStory", 0.0);
2058 game.hltbInfo.mainPlusExtrasHours = obj.value("hltbMainExtras", 0.0);
2059 game.hltbInfo.completionistHours = obj.value("hltbCompletionist", 0.0);
2060 game.hltbInfo.allStylesHours = obj.value("hltbAllStyles", 0.0);
2061 game.hltbInfo.lastUpdated =
2062 static_cast<time_t>(obj.value("hltbLastUpdated", static_cast<int64_t>(0)));
2063 game.hltbInfo.found = (game.hltbInfo.hltbId > 0);
2064
2065 // Collections
2066 if (obj.contains("collections") && obj["collections"].is_array())
2067 {
2068 for (const auto& c : obj["collections"])
2069 {
2070 if (c.is_string())
2071 game.collections.push_back(c.get<std::string>());
2072 }
2073 }
2074 }
2075 catch (const json::exception& e)
2076 {
2077 Logger::warn("Failed to parse game from JSON: {}", e.what());
2078 ++errors;
2079 continue;
2080 }
2081
2082 bool exists = gameExists(game.id);
2083 if (exists && !overwriteExisting)
2084 {
2085 Logger::debug("Skipping existing game '{}' (overwrite disabled)", game.name);
2086 ++skipped;
2087 continue;
2088 }
2089
2090 bool ok = exists ? updateGame(game) : insertGame(game);
2091 if (ok)
2092 ++imported;
2093 else
2094 {
2095 Logger::warn("Failed to {} game '{}': {}", exists ? "update" : "insert", game.name,
2096 lastError_);
2097 ++errors;
2098 }
2100
2101 Logger::info("JSON import complete: {} imported, {} skipped, {} errors (from {} total)",
2102 imported, skipped, errors, arr.size());
2103 return imported;
2104}
2106// ==============================================================================
2107// Maintenance
2108// ==============================================================================
2109
2112 std::lock_guard<std::recursive_mutex> lock(mutex_);
2113 return executeSQL("VACUUM");
2114}
2115
2117{
2118 std::lock_guard<std::recursive_mutex> lock(mutex_);
2119 auto r = getSchemaVersionInternal();
2120 return r.state == SchemaVersionState::Found ? r.version : 0;
2121}
2122
2123GameDatabase::SchemaVersionResult GameDatabase::getSchemaVersionInternal() const
2124{
2125 SchemaVersionResult out{SchemaVersionState::NoTable, 0};
2126 if (!db_)
2127 return out;
2128
2129 // Step 1: probe for the schema_version table itself. SELECT MAX(...) on a
2130 // missing table is a prepare error, which would conflate "no table" with
2131 // "version 0" — the bug fixed here.
2132 const char* checkSql =
2133 "SELECT name FROM sqlite_master WHERE type='table' AND name='schema_version'";
2134 sqlite3_stmt* check = nullptr;
2135 if (sqlite3_prepare_v2(db_, checkSql, -1, &check, nullptr) != SQLITE_OK)
2136 {
2137 return out; // out.state == NoTable
2138 }
2139 bool tableExists = (sqlite3_step(check) == SQLITE_ROW);
2140 sqlite3_finalize(check);
2141 if (!tableExists)
2142 {
2143 return out; // out.state == NoTable
2144 }
2145
2146 // Step 2: query the version. MAX(...) on an empty table returns NULL,
2147 // which sqlite3_column_int turns into 0; we instead look at the column
2148 // type to know whether a real row was present.
2149 const char* sql = "SELECT MAX(version) FROM schema_version";
2150 sqlite3_stmt* stmt = nullptr;
2151 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK)
2152 {
2153 // Table exists per step 1 but prepare failed — corruption, locked
2154 // DB, etc. Returning `Empty` here would let createSchema() stamp
2155 // the version row over a damaged DB, hiding the underlying issue.
2156 // Surface as a distinct Error so the caller can refuse-to-open.
2157 Logger::error("[GameDatabase] schema_version table present but SELECT "
2158 "MAX(version) failed: {}",
2159 sqlite3_errmsg(db_));
2160 out.state = SchemaVersionState::Error;
2161 return out;
2162 }
2163
2164 int rc = sqlite3_step(stmt);
2165 if (rc == SQLITE_ROW && sqlite3_column_type(stmt, 0) != SQLITE_NULL)
2166 {
2167 out.state = SchemaVersionState::Found;
2168 out.version = sqlite3_column_int(stmt, 0);
2169 }
2170 else
2171 {
2172 out.state = SchemaVersionState::Empty;
2173 }
2174 sqlite3_finalize(stmt);
2175 return out;
2176}
2177
2178// ==============================================================================
2179// Transaction Support
2180// ==============================================================================
2181
2183{
2184 std::lock_guard<std::recursive_mutex> lock(mutex_);
2185 return executeSQL("BEGIN TRANSACTION");
2186}
2187
2189{
2190 std::lock_guard<std::recursive_mutex> lock(mutex_);
2191 return executeSQL("COMMIT");
2192}
2193
2195{
2196 std::lock_guard<std::recursive_mutex> lock(mutex_);
2197 return executeSQL("ROLLBACK");
2198}
2199
2200bool GameDatabase::withTransaction(const std::function<bool()>& func)
2201{
2202 std::lock_guard<std::recursive_mutex> lock(mutex_);
2203
2204 if (!executeSQL("BEGIN TRANSACTION"))
2205 return false;
2206
2207 try
2208 {
2209 if (func())
2210 return executeSQL("COMMIT");
2211 else
2212 {
2213 executeSQL("ROLLBACK");
2214 return false;
2215 }
2216 }
2217 catch (...)
2218 {
2219 executeSQL("ROLLBACK");
2220 throw;
2221 }
2222}
2223
2224// ==============================================================================
2225// Schema Creation + Migration
2226// ==============================================================================
2227//
2228// Strategy:
2229// - Fresh DB (no `games` table) → createSchema() builds at SCHEMA_VERSION.
2230// - Existing DB at SCHEMA_VERSION → no-op.
2231// - Existing DB older than SCHEMA_VERSION → runMigrations() walks v→v+1.
2232// - Existing DB *newer* than SCHEMA_VERSION → refuse-to-open (downgrade safety).
2233//
2234// Each migration step is an idempotent function that takes the DB from
2235// `from` to `from+1` inside a transaction. SQLite supports ALTER TABLE …
2236// ADD COLUMN since 3.2; for column rename / drop see https://www.sqlite.org/lang_altertable.html
2237// (the table-rebuild dance). Always update schema_version inside the same
2238// transaction as the schema change so a crash mid-step rolls back cleanly.
2239
2240bool GameDatabase::runMigrations(int fromVersion)
2241{
2242 // Migration registry. Each entry is `{from_version, step_function}`
2243 // moving the schema from `from` to `from + 1`. The closure receives a
2244 // reference to `*this` so it can call `executeSQL`. It returns true on
2245 // success; false rolls back the *entire* migration transaction.
2246 //
2247 // To add a migration: bump SCHEMA_VERSION and append an entry, e.g.
2248 //
2249 // {5, [](GameDatabase& db) {
2250 // return db.executeSQL("ALTER TABLE games ADD COLUMN ... TEXT DEFAULT ''");
2251 // }},
2252 //
2253 // Each step MUST NOT touch `schema_version` itself — this loop bumps
2254 // the row only after the step succeeds, inside the same transaction
2255 // so a crash mid-step rolls both back. SQLite supports `ALTER TABLE
2256 // ... ADD COLUMN` since 3.2 and `... RENAME COLUMN` since 3.25 (see
2257 // https://www.sqlite.org/lang_altertable.html); for column drops or
2258 // type changes, the canonical 12-step rebuild dance is required.
2259 //
2260 // The previous implementation used a switch-with-only-default and a
2261 // top-level "INSERT OR REPLACE schema_version" after the switch body.
2262 // A future case that returned `false` mid-step would have fallen
2263 // through to that INSERT and silently stamped the next version even
2264 // though the data change failed. The struct-array approach makes the
2265 // step's success signal load-bearing on the loop body so that footgun
2266 // is gone.
2267 using StepFn = bool (*)(GameDatabase&);
2268 struct Step
2269 {
2270 int from;
2271 StepFn fn;
2272 };
2273 // std::array<Step, N> instead of a C array because C-array zero-length
2274 // is a non-standard extension. std::array<T, 0> is well-formed in C++17
2275 // and supports range-for (zero iterations) without warnings.
2276 //
2277 // To add a migration, bump N and append an entry. Example:
2278 // static constexpr std::array<Step, 1> kSteps{{
2279 // {5, [](GameDatabase& db) {
2280 // return db.executeSQL("ALTER TABLE games ADD COLUMN ... TEXT DEFAULT ''");
2281 // }},
2282 // }};
2283 static constexpr std::array<Step, 0> kSteps{};
2284
2285 Logger::info("[GameDatabase] Running migrations from v{} to v{}", fromVersion, SCHEMA_VERSION);
2286
2287 if (!executeSQL("BEGIN TRANSACTION"))
2288 {
2289 lastError_ = "Failed to begin migration transaction";
2290 return false;
2291 }
2292
2293 for (int v = fromVersion; v < SCHEMA_VERSION; ++v)
2294 {
2295 // Find the registered step for `v -> v+1`.
2296 const Step* step = nullptr;
2297 for (const auto& s : kSteps)
2298 {
2299 if (s.from == v)
2300 {
2301 step = &s;
2302 break;
2303 }
2304 }
2305 if (!step)
2306 {
2307 Logger::error("[GameDatabase] No migration step registered for v{}; aborting.", v);
2308 executeSQL("ROLLBACK");
2309 lastError_ = "No migration step for v" + std::to_string(v);
2310 return false;
2311 }
2312
2313 if (!step->fn(*this))
2314 {
2315 Logger::error("[GameDatabase] Migration step v{} -> v{} failed; rolling back.", v,
2316 v + 1);
2317 executeSQL("ROLLBACK");
2318 // Step should have set lastError_; if not, fill in something useful.
2319 if (lastError_.empty())
2320 lastError_ = "Migration step v" + std::to_string(v) + " failed";
2321 return false;
2322 }
2323
2324 // Step succeeded — record the new version inside the same
2325 // transaction so a subsequent step's failure rolls both back.
2326 if (!executeSQL("INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2327 std::to_string(v + 1) + ")"))
2328 {
2329 executeSQL("ROLLBACK");
2330 lastError_ = "Failed to record schema_version v" + std::to_string(v + 1);
2331 return false;
2332 }
2333 }
2334
2335 if (!executeSQL("COMMIT"))
2336 {
2337 executeSQL("ROLLBACK");
2338 lastError_ = "Failed to commit migration transaction";
2339 return false;
2340 }
2341 Logger::info("[GameDatabase] Migrations complete; now at v{}", SCHEMA_VERSION);
2342 return true;
2343}
2344
2345bool GameDatabase::createSchema()
2346{
2347 // Check if schema exists
2348 const char* checkSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='games'";
2349 sqlite3_stmt* stmt;
2350 int rc = sqlite3_prepare_v2(db_, checkSql, -1, &stmt, nullptr);
2351 if (rc != SQLITE_OK)
2352 {
2353 lastError_ = sqlite3_errmsg(db_);
2354 return false;
2355 }
2356
2357 bool schemaExists = (sqlite3_step(stmt) == SQLITE_ROW);
2358 sqlite3_finalize(stmt);
2359
2360 if (!schemaExists)
2361 {
2362 // Create fresh schema
2363 char* errMsg = nullptr;
2364 rc = sqlite3_exec(db_, SCHEMA_SQL, nullptr, nullptr, &errMsg);
2365 if (rc != SQLITE_OK)
2366 {
2367 lastError_ = errMsg ? errMsg : "Failed to create schema";
2368 sqlite3_free(errMsg);
2369 return false;
2370 }
2371
2372 // Set schema version
2373 executeSQL("INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2374 std::to_string(SCHEMA_VERSION) + ")");
2375
2376 Logger::info("Created database schema version {}", SCHEMA_VERSION);
2377 }
2378 else
2379 {
2380 // Schema exists — check version and migrate if needed.
2381 SchemaVersionResult ver = getSchemaVersionInternal();
2382 int currentVersion = (ver.state == SchemaVersionState::Found) ? ver.version : 0;
2383
2384 if (ver.state == SchemaVersionState::Error)
2385 {
2386 // schema_version table is present but querying it failed
2387 // (corruption, lock, malformed row). Refuse rather than stamp
2388 // — overwriting would mask the underlying damage and may
2389 // delete recoverable user data.
2390 Logger::error("[GameDatabase] Cannot determine schema version of '{}' — "
2391 "table query failed. Refusing to open.",
2392 dbPath_);
2393 lastError_ = "Cannot determine schema version (DB may be corrupt or locked)";
2394 return false;
2395 }
2396
2397 if (ver.state == SchemaVersionState::NoTable || ver.state == SchemaVersionState::Empty)
2398 {
2399 // `games` table exists but no schema_version recorded. This
2400 // means a partial CREATE crashed mid-way OR the user's DB was
2401 // created by a launcher version pre-dating schema_version. Be
2402 // conservative: stamp the version table with SCHEMA_VERSION on
2403 // the bet that the existing tables are at the latest schema,
2404 // log loudly, and hand control back. If structure has actually
2405 // drifted, downstream queries will fail and surface a clear
2406 // SQLite error.
2407 Logger::warn("[GameDatabase] schema_version unrecorded; assuming current "
2408 "schema and stamping v{}.",
2409 SCHEMA_VERSION);
2410 executeSQL("INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2411 std::to_string(SCHEMA_VERSION) + ")");
2412 }
2413 else if (currentVersion > SCHEMA_VERSION)
2414 {
2415 // Downgrade: refuse, never overwrite a future-version DB. A
2416 // packager-shipped older launcher would otherwise destroy a
2417 // user's library on first run.
2418 Logger::error("[GameDatabase] Database at '{}' was written by a newer launcher "
2419 "(schema v{}); this build supports up to v{}. Refusing to open.",
2420 dbPath_, currentVersion, SCHEMA_VERSION);
2421 lastError_ = "Database is newer than this launcher (v" +
2422 std::to_string(currentVersion) + " > v" + std::to_string(SCHEMA_VERSION) +
2423 ")";
2424 return false;
2425 }
2426 else if (currentVersion < SCHEMA_VERSION)
2427 {
2428 // Migrate up. runMigrations() walks v→v+1 in a transaction.
2429 if (!runMigrations(currentVersion))
2430 {
2431 // lastError_ already set inside runMigrations().
2432 return false;
2433 }
2434 }
2435 // currentVersion == SCHEMA_VERSION: schema is current, nothing to do.
2436 }
2437
2438 return true;
2439}
2440
2441// ==============================================================================
2442// Private Helper Methods
2443// ==============================================================================
2444
2445bool GameDatabase::executeSQL(const std::string& sql)
2446{
2447 if (!db_)
2448 {
2449 lastError_ = "Database not open";
2450 return false;
2451 }
2452
2453 char* errMsg = nullptr;
2454 int rc = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &errMsg);
2455 if (rc != SQLITE_OK)
2456 {
2457 lastError_ = errMsg ? errMsg : "SQL execution failed";
2458 sqlite3_free(errMsg);
2459 return false;
2460 }
2461
2462 return true;
2463}
2464
2465Game GameDatabase::gameFromStatement(sqlite3_stmt* stmt) const
2466{
2467 Game game;
2468
2469 auto getText = [](sqlite3_stmt* s, int col) -> std::string
2470 {
2471 const char* text = reinterpret_cast<const char*>(sqlite3_column_text(s, col));
2472 return text ? text : "";
2473 };
2474
2475 // Core
2476 game.id = getText(stmt, COL_ID);
2477 game.name = getText(stmt, COL_NAME);
2478 game.source = core::safeEnumCast(sqlite3_column_int(stmt, COL_SOURCE), GameSource::Unknown,
2479 kMaxGameSource);
2480 game.runner = core::safeEnumCast(sqlite3_column_int(stmt, COL_RUNNER), GameRunner::Native,
2481 kMaxGameRunner);
2482 game.status = core::safeEnumCast(sqlite3_column_int(stmt, COL_STATUS), GameStatus::NotInstalled,
2483 kMaxGameStatus);
2484 game.isFavorite = sqlite3_column_int(stmt, COL_IS_FAVORITE) != 0;
2485 game.installPath = getText(stmt, COL_INSTALL_PATH);
2486 {
2487 int64_t v = sqlite3_column_int64(stmt, COL_INSTALL_SIZE_BYTES);
2488 game.installSizeBytes = v >= 0 ? static_cast<uint64_t>(v) : 0u;
2489 }
2490
2491 // Derive platform from runner for backward compatibility
2493
2494 // Runner config (JSON blob)
2495 std::string runnerConfigJson = getText(stmt, COL_RUNNER_CONFIG);
2496 if (!runnerConfigJson.empty())
2497 game.deserializeRunnerConfig(runnerConfigJson);
2498
2499 // Config templates (JSON blob)
2500 std::string configTemplatesJson = getText(stmt, COL_CONFIG_TEMPLATES);
2501 if (!configTemplatesJson.empty())
2502 {
2503 try
2504 {
2505 json templates = json::parse(configTemplatesJson);
2506 if (templates.is_object())
2507 {
2508 for (auto& [name, configJson] : templates.items())
2509 {
2510 Game tempGame;
2511 tempGame.deserializeRunnerConfig(configJson.dump());
2512 game.configTemplates[name] = tempGame.runnerConfig;
2513 }
2514 }
2515 }
2516 catch (const json::exception& e)
2517 {
2518 Logger::warn("[GameDatabase] Failed to parse configTemplates JSON for game {}: {}",
2519 game.id, e.what());
2520 }
2521 }
2522 game.activeTemplateName = getText(stmt, COL_ACTIVE_TEMPLATE_NAME);
2523
2524 // Statistics
2525 game.statistics.timesLaunched = sqlite3_column_int(stmt, COL_TIMES_LAUNCHED);
2527 static_cast<double>(sqlite3_column_int64(stmt, COL_TOTAL_PLAY_TIME));
2528 game.statistics.lastPlayed = static_cast<time_t>(sqlite3_column_int64(stmt, COL_LAST_PLAYED));
2529 game.statistics.dateAdded = static_cast<time_t>(sqlite3_column_int64(stmt, COL_DATE_ADDED));
2531 static_cast<time_t>(sqlite3_column_int64(stmt, COL_DATE_INSTALLED));
2532
2533 // Launch tracking
2534 game.statistics.lastLaunchCommand = getText(stmt, COL_LAST_LAUNCH_CMD);
2535 game.statistics.lastProtonVersion = getText(stmt, COL_LAST_PROTON_VER);
2536 game.statistics.lastExitReason = getText(stmt, COL_LAST_EXIT_REASON);
2538 static_cast<time_t>(sqlite3_column_int64(stmt, COL_LAST_EXIT_TIME));
2539 game.statistics.crashCount = sqlite3_column_int(stmt, COL_CRASH_COUNT);
2540
2541 // Environment vars (JSON object)
2542 std::string envJson = getText(stmt, COL_LAST_ENV_VARS);
2544
2545 // Descriptive metadata
2546 game.metadata.developer = getText(stmt, COL_DEVELOPER);
2547 game.metadata.publisher = getText(stmt, COL_PUBLISHER);
2548 game.metadata.releaseYear = sqlite3_column_int(stmt, COL_RELEASE_YEAR);
2549 game.metadata.description = getText(stmt, COL_DESCRIPTION);
2550 game.metadata.userRating = static_cast<float>(sqlite3_column_double(stmt, COL_USER_RATING));
2551
2552 // Image paths
2553 game.metadata.imagePaths.verticalCover = getText(stmt, COL_IMG_VERTICAL);
2554 game.metadata.imagePaths.heroImage = getText(stmt, COL_IMG_HERO);
2555 game.metadata.imagePaths.logo = getText(stmt, COL_IMG_LOGO);
2556 game.metadata.imagePaths.header = getText(stmt, COL_IMG_HEADER);
2557 game.metadata.imagePaths.capsule = getText(stmt, COL_IMG_CAPSULE);
2558 game.metadata.imagePaths.icon = getText(stmt, COL_IMG_ICON);
2559
2560 // Genres and tags (JSON arrays)
2561 game.metadata.genres = stringsFromJsonArray(getText(stmt, COL_GENRES));
2562 game.metadata.tags = stringsFromJsonArray(getText(stmt, COL_TAGS));
2563
2564 // Steam-specific
2565 game.metadata.steamAppId = sqlite3_column_int(stmt, COL_STEAM_APP_ID);
2566 game.metadata.steamInstalled = sqlite3_column_int(stmt, COL_STEAM_INSTALLED) != 0;
2568 game.metadata.steamBuildId = getText(stmt, COL_STEAM_BUILD_ID);
2570 static_cast<uint32_t>(sqlite3_column_int(stmt, COL_STEAM_PLAYTIME_2W));
2572 static_cast<time_t>(sqlite3_column_int64(stmt, COL_STEAM_LAST_LAUNCH));
2573 game.metadata.steamLastExit =
2574 static_cast<time_t>(sqlite3_column_int64(stmt, COL_STEAM_LAST_EXIT));
2575 game.metadata.steamType = getText(stmt, COL_STEAM_TYPE);
2579 static_cast<uint32_t>(sqlite3_column_int(stmt, COL_STEAM_STATE_FLAGS));
2580 {
2581 int64_t vDl = sqlite3_column_int64(stmt, COL_STEAM_BYTES_DL);
2582 int64_t vToDl = sqlite3_column_int64(stmt, COL_STEAM_BYTES_TO_DL);
2583 game.metadata.steamBytesDownloaded = vDl >= 0 ? static_cast<uint64_t>(vDl) : 0u;
2584 game.metadata.steamBytesToDownload = vToDl >= 0 ? static_cast<uint64_t>(vToDl) : 0u;
2585 }
2586 game.metadata.steamIsDownloading = sqlite3_column_int(stmt, COL_STEAM_IS_DL) != 0;
2587 game.metadata.steamIsUpdatePending = sqlite3_column_int(stmt, COL_STEAM_IS_UPDATE) != 0;
2588
2589 // Derive isSteamGame from source
2591
2592 // ProtonDB
2593 game.metadata.protondbTier = getText(stmt, COL_PROTONDB_TIER);
2595 game.metadata.protondbScore =
2596 static_cast<float>(sqlite3_column_double(stmt, COL_PROTONDB_SCORE));
2598 static_cast<time_t>(sqlite3_column_int64(stmt, COL_PROTONDB_LAST_UPDATED));
2599
2600 // Cloud save
2601 game.metadata.cloudSave.enabled = sqlite3_column_int(stmt, COL_CLOUD_ENABLED) != 0;
2602 game.metadata.cloudSave.supported = sqlite3_column_int(stmt, COL_CLOUD_SUPPORTED) != 0;
2603 game.metadata.cloudSave.lastSyncState = sqlite3_column_int(stmt, COL_CLOUD_SYNC_STATE);
2604 {
2605 int64_t v = sqlite3_column_int64(stmt, COL_CLOUD_STORAGE_BYTES);
2606 game.metadata.cloudSave.storageBytes = v >= 0 ? static_cast<uint64_t>(v) : 0u;
2607 }
2609 static_cast<time_t>(sqlite3_column_int64(stmt, COL_CLOUD_LAST_SYNC));
2610
2611 // DLC count (actual DLC details are in metadata JSON for file export)
2612 // Column 59 is dlc_count — we don't set it here since dlc vector comes from metadata
2613
2614 // Completion
2615 game.completionStatus = core::safeEnumCast(sqlite3_column_int(stmt, COL_COMPLETION_STATUS),
2616 CompletionStatus::NotPlayed, kMaxCompletionStatus);
2617 game.userNotes = getText(stmt, COL_USER_NOTES);
2618
2619 // HLTB
2620 game.hltbInfo.hltbId = sqlite3_column_int(stmt, COL_HLTB_ID);
2621 game.hltbInfo.matchedName = getText(stmt, COL_HLTB_MATCHED_NAME);
2622 game.hltbInfo.mainStoryHours = sqlite3_column_double(stmt, COL_HLTB_MAIN_STORY);
2623 game.hltbInfo.mainPlusExtrasHours = sqlite3_column_double(stmt, COL_HLTB_MAIN_EXTRAS);
2624 game.hltbInfo.completionistHours = sqlite3_column_double(stmt, COL_HLTB_COMPLETIONIST);
2625 game.hltbInfo.allStylesHours = sqlite3_column_double(stmt, COL_HLTB_ALL_STYLES);
2626 game.hltbInfo.lastUpdated =
2627 static_cast<time_t>(sqlite3_column_int64(stmt, COL_HLTB_LAST_UPDATED));
2628 game.hltbInfo.found = (game.hltbInfo.hltbId > 0);
2629
2630 return game;
2631}
2632
2633// ==============================================================================
2634// Session & Launch Tracking
2635// ==============================================================================
2636
2637int64_t GameDatabase::startSession(const std::string& gameId, GameRunner runner,
2638 const std::string& protonVersion)
2639{
2640 std::lock_guard<std::recursive_mutex> lock(mutex_);
2641
2642 if (!db_)
2643 {
2644 lastError_ = "Database not open";
2645 return 0;
2646 }
2647
2648 const char* sql = R"SQL(
2649 INSERT INTO game_sessions (game_id, start_time, runner, proton_version)
2650 VALUES (?, strftime('%s', 'now'), ?, ?)
2651 )SQL";
2652
2653 sqlite3_stmt* stmt;
2654 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2655 if (rc != SQLITE_OK)
2656 {
2657 lastError_ = sqlite3_errmsg(db_);
2658 return 0;
2659 }
2660
2661 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2662 sqlite3_bind_int(stmt, 2, static_cast<int>(runner));
2663 sqlite3_bind_text(stmt, 3, protonVersion.c_str(), -1, SQLITE_TRANSIENT);
2664
2665 rc = sqlite3_step(stmt);
2666 sqlite3_finalize(stmt);
2667
2668 if (rc != SQLITE_DONE)
2669 {
2670 lastError_ = sqlite3_errmsg(db_);
2671 return 0;
2672 }
2673
2674 int64_t sessionId = sqlite3_last_insert_rowid(db_);
2675 Logger::debug("Started session {} for game {}", sessionId, gameId);
2676 return sessionId;
2677}
2678
2679bool GameDatabase::endSession(int64_t sessionId, const std::string& exitReason)
2680{
2681 std::lock_guard<std::recursive_mutex> lock(mutex_);
2682
2683 if (!db_)
2684 {
2685 lastError_ = "Database not open";
2686 return false;
2687 }
2688
2689 const char* sql = R"SQL(
2690 UPDATE game_sessions
2691 SET end_time = strftime('%s', 'now'),
2692 duration_seconds = strftime('%s', 'now') - start_time,
2693 exit_reason = ?
2694 WHERE id = ?
2695 )SQL";
2696
2697 sqlite3_stmt* stmt;
2698 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2699 if (rc != SQLITE_OK)
2700 {
2701 lastError_ = sqlite3_errmsg(db_);
2702 return false;
2703 }
2704
2705 sqlite3_bind_text(stmt, 1, exitReason.c_str(), -1, SQLITE_TRANSIENT);
2706 sqlite3_bind_int64(stmt, 2, sessionId);
2707
2708 rc = sqlite3_step(stmt);
2709 sqlite3_finalize(stmt);
2710
2711 if (rc != SQLITE_DONE)
2712 {
2713 lastError_ = sqlite3_errmsg(db_);
2714 return false;
2715 }
2717 // Update daily playtime and runner stats
2718 const char* getSql = "SELECT game_id, duration_seconds, runner FROM game_sessions WHERE id = ?";
2719 rc = sqlite3_prepare_v2(db_, getSql, -1, &stmt, nullptr);
2720 if (rc == SQLITE_OK)
2721 {
2722 sqlite3_bind_int64(stmt, 1, sessionId);
2723 if (sqlite3_step(stmt) == SQLITE_ROW)
2724 {
2725 // Copy to std::string before finalize — sqlite3_column_text pointer is invalidated by
2726 // finalize
2727 const char* rawGameId = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
2728 std::string gameIdStr = rawGameId ? rawGameId : "";
2729 int duration = sqlite3_column_int(stmt, 1);
2730 int runnerVal = sqlite3_column_int(stmt, 2);
2731 sqlite3_finalize(stmt);
2732
2733 const char* gameId = gameIdStr.empty() ? nullptr : gameIdStr.c_str();
2734 if (gameId && duration > 0)
2735 {
2736 // Update daily playtime
2737 const char* dailySql = R"SQL(
2738 INSERT INTO daily_playtime (date, game_id, play_time_seconds, session_count)
2739 VALUES (date('now'), ?, ?, 1)
2740 ON CONFLICT(date, game_id) DO UPDATE SET
2741 play_time_seconds = play_time_seconds + excluded.play_time_seconds,
2742 session_count = session_count + 1
2743 )SQL";
2744
2745 sqlite3_stmt* dailyStmt;
2746 if (sqlite3_prepare_v2(db_, dailySql, -1, &dailyStmt, nullptr) == SQLITE_OK)
2747 {
2748 sqlite3_bind_text(dailyStmt, 1, gameId, -1, SQLITE_TRANSIENT);
2749 sqlite3_bind_int(dailyStmt, 2, duration);
2750 sqlite3_step(dailyStmt);
2751 sqlite3_finalize(dailyStmt);
2752 }
2753
2754 // Update runner_stats
2755 const char* runnerPlaytimeSql = R"SQL(
2756 INSERT INTO runner_stats (runner, total_play_time_seconds, total_sessions)
2757 VALUES (?, ?, 1)
2758 ON CONFLICT(runner) DO UPDATE SET
2759 total_play_time_seconds = total_play_time_seconds + excluded.total_play_time_seconds,
2760 total_sessions = total_sessions + 1,
2761 updated_at = strftime('%s', 'now')
2762 )SQL";
2763
2764 sqlite3_stmt* runnerStmt;
2765 if (sqlite3_prepare_v2(db_, runnerPlaytimeSql, -1, &runnerStmt, nullptr) ==
2766 SQLITE_OK)
2767 {
2768 sqlite3_bind_int(runnerStmt, 1, runnerVal);
2769 sqlite3_bind_int(runnerStmt, 2, duration);
2770 sqlite3_step(runnerStmt);
2771 sqlite3_finalize(runnerStmt);
2772 }
2773 }
2774 }
2775 else
2776 {
2777 sqlite3_finalize(stmt);
2778 }
2779 }
2780
2781 Logger::debug("Ended session {} with reason: {}", sessionId, exitReason);
2782 return true;
2783}
2784
2785std::vector<PlaySession> GameDatabase::getRecentSessions(const std::string& gameId, int limit) const
2786{
2787 std::lock_guard<std::recursive_mutex> lock(mutex_);
2788 std::vector<PlaySession> sessions;
2789
2790 if (!db_)
2791 return sessions;
2792
2793 const char* sql = R"SQL(
2794 SELECT id, start_time, end_time, duration_seconds,
2795 proton_version, exit_reason, exit_code,
2796 avg_fps, min_fps, avg_frametime
2797 FROM game_sessions
2798 WHERE game_id = ?
2799 ORDER BY start_time DESC
2800 LIMIT ?
2801 )SQL";
2802
2803 sqlite3_stmt* stmt = nullptr;
2804 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK)
2805 {
2806 lastError_ = std::string("Failed to prepare getRecentSessions: ") + sqlite3_errmsg(db_);
2807 return sessions;
2809
2810 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2811 sqlite3_bind_int(stmt, 2, limit);
2812
2813 while (sqlite3_step(stmt) == SQLITE_ROW)
2814 {
2815 PlaySession session;
2816 session.sessionId = sqlite3_column_int64(stmt, 0);
2817 session.startTime = static_cast<time_t>(sqlite3_column_int64(stmt, 1));
2818 session.endTime = static_cast<time_t>(sqlite3_column_int64(stmt, 2));
2819 session.durationSeconds = static_cast<double>(sqlite3_column_int64(stmt, 3));
2820 const char* protonVer = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4));
2821 session.protonVersion = protonVer ? protonVer : "";
2822 const char* exitReasonStr = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 5));
2823 session.exitReason = exitReasonStr ? exitReasonStr : "";
2824 session.exitCode = sqlite3_column_int(stmt, 6);
2825 session.avgFps = static_cast<float>(sqlite3_column_double(stmt, 7));
2826 session.minFps = static_cast<float>(sqlite3_column_double(stmt, 8));
2827 session.avgFrametime = static_cast<float>(sqlite3_column_double(stmt, 9));
2828 sessions.push_back(std::move(session));
2829 }
2830
2831 sqlite3_finalize(stmt);
2832 return sessions;
2833}
2834
2835bool GameDatabase::recordLaunch(const std::string& gameId, bool success, GameRunner runner,
2836 const std::string& protonVersion, const std::string& errorMessage,
2837 int timeToLaunchMs)
2838{
2839 std::lock_guard<std::recursive_mutex> lock(mutex_);
2840
2841 if (!db_)
2842 {
2843 lastError_ = "Database not open";
2844 return false;
2845 }
2846
2847 const char* sql = R"SQL(
2848 INSERT INTO launch_history (game_id, timestamp, success, error_message, runner, proton_version, time_to_launch_ms)
2849 VALUES (?, strftime('%s', 'now'), ?, ?, ?, ?, ?)
2850 )SQL";
2851
2852 sqlite3_stmt* stmt;
2853 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2854 if (rc != SQLITE_OK)
2855 {
2856 lastError_ = sqlite3_errmsg(db_);
2857 return false;
2858 }
2859
2860 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2861 sqlite3_bind_int(stmt, 2, success ? 1 : 0);
2862 sqlite3_bind_text(stmt, 3, errorMessage.c_str(), -1, SQLITE_TRANSIENT);
2863 sqlite3_bind_int(stmt, 4, static_cast<int>(runner));
2864 sqlite3_bind_text(stmt, 5, protonVersion.c_str(), -1, SQLITE_TRANSIENT);
2865 sqlite3_bind_int(stmt, 6, timeToLaunchMs);
2866
2867 rc = sqlite3_step(stmt);
2868 sqlite3_finalize(stmt);
2869
2870 if (rc != SQLITE_DONE)
2871 {
2872 lastError_ = sqlite3_errmsg(db_);
2873 return false;
2874 }
2875
2876 // Update runner stats
2877 const char* runnerStatsSql = R"SQL(
2878 INSERT INTO runner_stats (runner, total_launches, successful_launches, failed_launches)
2879 VALUES (?, 1, ?, ?)
2880 ON CONFLICT(runner) DO UPDATE SET
2881 total_launches = total_launches + 1,
2882 successful_launches = successful_launches + excluded.successful_launches,
2883 failed_launches = failed_launches + excluded.failed_launches,
2884 updated_at = strftime('%s', 'now')
2885 )SQL";
2886
2887 rc = sqlite3_prepare_v2(db_, runnerStatsSql, -1, &stmt, nullptr);
2888 if (rc == SQLITE_OK)
2889 {
2890 sqlite3_bind_int(stmt, 1, static_cast<int>(runner));
2891 sqlite3_bind_int(stmt, 2, success ? 1 : 0);
2892 sqlite3_bind_int(stmt, 3, success ? 0 : 1);
2893 sqlite3_step(stmt);
2894 sqlite3_finalize(stmt);
2895 }
2896 else
2897 {
2898 Logger::warn("Failed to update runner stats: {}", sqlite3_errmsg(db_));
2899 }
2900
2901 Logger::debug("Recorded launch for game {}: success={}", gameId, success);
2902 return true;
2903}
2904
2905bool GameDatabase::updateDailyPlaytime(const std::string& gameId, int playTimeSeconds)
2906{
2907 std::lock_guard<std::recursive_mutex> lock(mutex_);
2908
2909 if (!db_)
2910 {
2911 lastError_ = "Database not open";
2912 return false;
2913 }
2914
2915 const char* sql = R"SQL(
2916 INSERT INTO daily_playtime (date, game_id, play_time_seconds, session_count)
2917 VALUES (date('now'), ?, ?, 0)
2918 ON CONFLICT(date, game_id) DO UPDATE SET
2919 play_time_seconds = play_time_seconds + excluded.play_time_seconds
2920 )SQL";
2921
2922 sqlite3_stmt* stmt;
2923 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2924 if (rc != SQLITE_OK)
2926 lastError_ = sqlite3_errmsg(db_);
2927 return false;
2928 }
2929
2930 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2931 sqlite3_bind_int(stmt, 2, playTimeSeconds);
2932
2933 rc = sqlite3_step(stmt);
2934 sqlite3_finalize(stmt);
2935
2936 return rc == SQLITE_DONE;
2937}
2938
2939// ==============================================================================
2940// Analytics Queries
2941// ==============================================================================
2942
2943int64_t GameDatabase::getTotalPlaytime(const std::string& startDate,
2944 const std::string& endDate) const
2945{
2946 std::lock_guard<std::recursive_mutex> lock(mutex_);
2947
2948 if (!db_)
2949 return 0;
2950
2951 const char* sql = R"SQL(
2952 SELECT COALESCE(SUM(play_time_seconds), 0)
2953 FROM daily_playtime
2954 WHERE date BETWEEN ? AND ?
2955 )SQL";
2956
2957 sqlite3_stmt* stmt;
2958 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2959 if (rc != SQLITE_OK)
2960 return 0;
2961
2962 sqlite3_bind_text(stmt, 1, startDate.c_str(), -1, SQLITE_TRANSIENT);
2963 sqlite3_bind_text(stmt, 2, endDate.c_str(), -1, SQLITE_TRANSIENT);
2964
2965 int64_t total = 0;
2966 if (sqlite3_step(stmt) == SQLITE_ROW)
2967 total = sqlite3_column_int64(stmt, 0);
2968 sqlite3_finalize(stmt);
2969
2970 return total;
2971}
2973std::vector<std::pair<std::string, int64_t>>
2974GameDatabase::getPlaytimeByGame(const std::string& startDate, const std::string& endDate,
2975 int limit) const
2976{
2977 std::lock_guard<std::recursive_mutex> lock(mutex_);
2978
2979 std::vector<std::pair<std::string, int64_t>> results;
2980 if (!db_)
2981 return results;
2982
2983 const char* sql = R"SQL(
2984 SELECT game_id, SUM(play_time_seconds) as total
2985 FROM daily_playtime
2986 WHERE date BETWEEN ? AND ?
2987 GROUP BY game_id
2988 ORDER BY total DESC
2989 LIMIT ?
2990 )SQL";
2991
2992 sqlite3_stmt* stmt;
2993 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
2994 if (rc != SQLITE_OK)
2995 return results;
2996
2997 sqlite3_bind_text(stmt, 1, startDate.c_str(), -1, SQLITE_TRANSIENT);
2998 sqlite3_bind_text(stmt, 2, endDate.c_str(), -1, SQLITE_TRANSIENT);
2999 sqlite3_bind_int(stmt, 3, limit);
3001 while (sqlite3_step(stmt) == SQLITE_ROW)
3002 {
3003 const char* gameId = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
3004 int64_t playTime = sqlite3_column_int64(stmt, 1);
3005 if (gameId)
3006 results.emplace_back(gameId, playTime);
3007 }
3008 sqlite3_finalize(stmt);
3009
3010 return results;
3011}
3012
3013std::vector<std::pair<std::string, int64_t>>
3014GameDatabase::getPlaytimeByDay(const std::string& startDate, const std::string& endDate) const
3015{
3016 std::lock_guard<std::recursive_mutex> lock(mutex_);
3017
3018 std::vector<std::pair<std::string, int64_t>> results;
3019 if (!db_)
3020 return results;
3021
3022 const char* sql = R"SQL(
3023 SELECT date, SUM(play_time_seconds) as total
3024 FROM daily_playtime
3025 WHERE date BETWEEN ? AND ?
3026 GROUP BY date
3027 ORDER BY date ASC
3028 )SQL";
3029
3030 sqlite3_stmt* stmt;
3031 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
3032 if (rc != SQLITE_OK)
3033 return results;
3034
3035 sqlite3_bind_text(stmt, 1, startDate.c_str(), -1, SQLITE_TRANSIENT);
3036 sqlite3_bind_text(stmt, 2, endDate.c_str(), -1, SQLITE_TRANSIENT);
3037
3038 while (sqlite3_step(stmt) == SQLITE_ROW)
3039 {
3040 const char* date = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
3041 int64_t playTime = sqlite3_column_int64(stmt, 1);
3042 if (date)
3043 results.emplace_back(date, playTime);
3044 }
3045 sqlite3_finalize(stmt);
3046
3047 return results;
3048}
3049
3050std::vector<std::pair<GameRunner, int64_t>> GameDatabase::getRunnerStats() const
3051{
3052 std::lock_guard<std::recursive_mutex> lock(mutex_);
3053
3054 std::vector<std::pair<GameRunner, int64_t>> results;
3055 if (!db_)
3056 return results;
3057
3058 const char* sql = R"SQL(
3059 SELECT runner, total_play_time_seconds
3060 FROM runner_stats
3061 ORDER BY total_play_time_seconds DESC
3062 )SQL";
3063
3064 sqlite3_stmt* stmt;
3065 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
3066 if (rc != SQLITE_OK)
3067 return results;
3068
3069 while (sqlite3_step(stmt) == SQLITE_ROW)
3070 {
3071 GameRunner runner =
3072 core::safeEnumCast(sqlite3_column_int(stmt, 0), GameRunner::Native, kMaxGameRunner);
3073 int64_t playTime = sqlite3_column_int64(stmt, 1);
3074 results.emplace_back(runner, playTime);
3075 }
3076 sqlite3_finalize(stmt);
3077
3078 return results;
3079}
3080
3081std::vector<std::pair<GameSource, int>> GameDatabase::getSourceStats() const
3082{
3083 std::lock_guard<std::recursive_mutex> lock(mutex_);
3084
3085 std::vector<std::pair<GameSource, int>> results;
3086 if (!db_)
3087 return results;
3088
3089 const char* sql = R"SQL(
3090 SELECT source, COUNT(*) as count
3091 FROM games
3092 GROUP BY source
3093 ORDER BY count DESC
3094 )SQL";
3095
3096 sqlite3_stmt* stmt;
3097 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
3098 if (rc != SQLITE_OK)
3099 return results;
3100
3101 while (sqlite3_step(stmt) == SQLITE_ROW)
3102 {
3103 GameSource source =
3104 core::safeEnumCast(sqlite3_column_int(stmt, 0), GameSource::Unknown, kMaxGameSource);
3105 int count = sqlite3_column_int(stmt, 1);
3106 results.emplace_back(source, count);
3107 }
3108 sqlite3_finalize(stmt);
3109
3110 return results;
3111}
3112
3113std::vector<Game> GameDatabase::getMostPlayedGames(int limit) const
3114{
3115 DatabaseFilterOptions filter;
3116 DatabaseSortOptions sort;
3119
3120 return queryGames(filter, sort, limit, 0);
3121}
3122
3123std::vector<Game> GameDatabase::getRecentlyPlayedGames(int limit) const
3124{
3125 DatabaseFilterOptions filter;
3126 DatabaseSortOptions sort;
3129
3130 return queryGames(filter, sort, limit, 0);
3131}
3132
3133std::pair<int, int> GameDatabase::getGameCrashStats(const std::string& gameId) const
3134{
3135 std::lock_guard<std::recursive_mutex> lock(mutex_);
3136
3137 if (!db_)
3138 return {0, 0};
3139
3140 const char* sql = R"SQL(
3141 SELECT
3142 SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as crashes,
3143 COUNT(*) as total
3144 FROM launch_history
3145 WHERE game_id = ?
3146 )SQL";
3147
3148 sqlite3_stmt* stmt;
3149 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
3150 if (rc != SQLITE_OK)
3151 return {0, 0};
3152
3153 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
3154
3155 int crashes = 0;
3156 int total = 0;
3157 if (sqlite3_step(stmt) == SQLITE_ROW)
3158 {
3159 crashes = sqlite3_column_int(stmt, 0);
3160 total = sqlite3_column_int(stmt, 1);
3161 }
3162 sqlite3_finalize(stmt);
3163
3164 return {crashes, total};
3165}
3166
3167double GameDatabase::getAverageSessionDuration(const std::string& gameId) const
3168{
3169 std::lock_guard<std::recursive_mutex> lock(mutex_);
3170
3171 if (!db_)
3172 return 0.0;
3173
3174 const char* sql = R"SQL(
3175 SELECT AVG(duration_seconds)
3176 FROM game_sessions
3177 WHERE game_id = ? AND duration_seconds > 0
3178 )SQL";
3179
3180 sqlite3_stmt* stmt;
3181 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
3182 if (rc != SQLITE_OK)
3183 return 0.0;
3184
3185 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
3186
3187 double avg = 0.0;
3188 if (sqlite3_step(stmt) == SQLITE_ROW)
3189 avg = sqlite3_column_double(stmt, 0);
3190 sqlite3_finalize(stmt);
3191
3192 return avg;
3193}
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.
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
GameMetadata metadata
Descriptive information and media.
Definition game.h:785
void deserializeMetadata(const std::string &json)
Deserialize metadata from JSON.
Definition game.cpp:888
std::string userNotes
User's personal notes about the game.
Definition game.h:813
std::vector< std::string > collections
Collections this game belongs to.
Definition game.h:804
std::string installPath
Installation directory path.
Definition game.h:819
CompletionStatus completionStatus
User's completion status.
Definition game.h:810
bool isFavorite
Is this marked as a favorite game?
Definition game.h:803
std::string name
Display name shown in UI.
Definition game.h:774
std::string serializeRunnerConfig() const
Serialize runner configuration to JSON.
Definition game.cpp:647
std::string id
Unique identifier (auto-generated or user-specified).
Definition game.h:773
void syncPlatformFromRunner()
Sync the deprecated platform field from the current runner and source.
Definition game.h:912
GameStatistics statistics
Play statistics and usage tracking.
Definition game.h:786
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
Definition game.h:777
GameRunnerConfig runnerConfig
How to launch and run the game.
Definition game.h:784
GameStatus status
Current installation and execution status.
Definition game.h:778
HowLongToBeatInfo hltbInfo
Time-to-beat estimates.
Definition game.h:812
std::map< std::string, GameRunnerConfig > configTemplates
Named configuration templates (presets) that can be switched between Key is template name (e....
Definition game.h:794
uint64_t installSizeBytes
Installation size in bytes.
Definition game.h:820
std::string activeTemplateName
Currently active template name (empty = using runnerConfig directly).
Definition game.h:797
void deserializeRunnerConfig(const std::string &json)
Deserialize runner configuration from JSON.
Definition game.cpp:724
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
Definition game.h:775
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
GameSource
Where the game was acquired from (store/service/local).
Definition game.h:39
@ Steam
Steam store/platform.
Definition game.h:41
@ Unknown
Unknown or unspecified source.
Definition game.h:47
@ NotInstalled
Game is in library but not installed.
Definition game.h:98
@ Updating
Game is being updated.
Definition game.h:104
@ Installed
Game is installed and ready to play.
Definition game.h:99
GameRunner
Runner/compatibility layer for executing the game.
Definition game.h:81
@ ScummVM
ScummVM engine.
Definition game.h:86
@ Native
Native Linux executable (no compatibility layer).
Definition game.h:82
@ Played
Played but no clear completion criteria (e.g., multiplayer).
Definition game.h:122
@ NotPlayed
Never played (backlog).
Definition game.h:116
static const char * SCHEMA_SQL
static std::vector< std::string > stringsFromJsonArray(const std::string &str)
static std::string jsonFromEnvVars(const std::map< std::string, std::string > &vars)
@ COL_PROTONDB_LAST_UPDATED
@ COL_PROTONDB_CONFIDENCE
@ COL_STEAM_BYTES_TO_DL
@ COL_IMG_VERTICAL
@ COL_IMG_CAPSULE
@ COL_HLTB_ALL_STYLES
@ COL_STEAM_PLAYTIME_2W
@ COL_CLOUD_SUPPORTED
@ COL_IMG_HEADER
@ COL_CRASH_COUNT
@ COL_STEAM_TYPE
@ COL_HLTB_MAIN_STORY
@ COL_IMG_LOGO
@ COL_CONFIG_TEMPLATES
@ COL_IS_FAVORITE
@ COL_INSTALL_PATH
@ COL_USER_NOTES
@ COL_CLOUD_ENABLED
@ COL_LAST_PROTON_VER
@ COL_STEAM_IS_DL
@ COL_HLTB_COMPLETIONIST
@ COL_ACTIVE_TEMPLATE_NAME
@ COL_RUNNER
@ COL_NAME
@ COL_STEAM_APP_ID
@ COL_STEAM_STATE_FLAGS
@ COL_STEAM_BYTES_DL
@ COL_PROTONDB_TIER
@ COL_RELEASE_YEAR
@ COL_DATE_ADDED
@ COL_STATUS
@ COL_HLTB_MAIN_EXTRAS
@ COL_COUNT
@ COL_LAST_EXIT_TIME
@ COL_ID
@ COL_LAST_ENV_VARS
@ COL_DEVELOPER
@ COL_HLTB_LAST_UPDATED
@ COL_IMG_HERO
@ COL_CLOUD_SYNC_STATE
@ COL_LAST_LAUNCH_CMD
@ COL_STEAM_CATEGORIES
@ COL_INSTALL_SIZE_BYTES
@ COL_TOTAL_PLAY_TIME
@ COL_STEAM_BUILD_ID
@ COL_DESCRIPTION
@ COL_DLC_COUNT
@ COL_COMPLETION_STATUS
@ COL_STEAM_LAST_LAUNCH
@ COL_HLTB_ID
@ COL_STEAM_LAST_EXIT
@ COL_GENRES
@ COL_TIMES_LAUNCHED
@ COL_SOURCE
@ COL_CLOUD_LAST_SYNC
@ COL_IMG_ICON
@ COL_HLTB_MATCHED_NAME
@ COL_USER_RATING
@ COL_STEAM_LAUNCH_OPTS
@ COL_LAST_EXIT_REASON
@ COL_STEAM_INSTALLED
@ COL_STEAM_USER_TAGS
@ COL_PROTONDB_SCORE
@ COL_DATE_INSTALLED
@ COL_LAST_PLAYED
@ COL_RUNNER_CONFIG
@ COL_TAGS
@ COL_CLOUD_STORAGE_BYTES
@ COL_PUBLISHER
@ COL_STEAM_IS_UPDATE
static std::string jsonArrayFromStrings(const std::vector< std::string > &vec)
static std::map< std::string, std::string > envVarsFromJson(const std::string &str)
static const char * GAME_COLUMNS
nlohmann::json json
constexpr E safeEnumCast(int v, E def, int kMax) noexcept
Bounds-checked cast from int to enum.
uint64_t storageBytes
Cloud storage used in bytes.
Definition game.h:521
time_t lastSyncTime
Last successful sync timestamp.
Definition game.h:522
bool enabled
Cloud saves enabled for this game.
Definition game.h:518
bool supported
Game supports Steam Cloud.
Definition game.h:519
int lastSyncState
0=synced, 1=uploading, 2=downloading, 3=error
Definition game.h:520
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
std::string header
Small header image (header.jpg, 460x215).
Definition game.h:500
std::string capsule
Store capsule image (capsule_616x353.jpg).
Definition game.h:501
std::string logo
Game logo with transparency (logo.png).
Definition game.h:499
std::string icon
Small square icon (icon.jpg).
Definition game.h:502
std::string verticalCover
Vertical cover art (library_600x900.jpg).
Definition game.h:497
std::string heroImage
Wide banner/hero image (library_hero.jpg).
Definition game.h:498
float userRating
User rating (0.0-5.0 scale).
Definition game.h:571
time_t steamLastLaunch
Last launch timestamp from Steam.
Definition game.h:580
std::vector< std::string > steamCategories
Steam categories (Single-player, Multi-player, etc.).
Definition game.h:584
bool isSteamGame
True if imported from Steam.
Definition game.h:574
bool steamInstalled
True if Steam game is installed (set during Steam import).
Definition game.h:576
time_t steamLastExit
Last exit timestamp from Steam.
Definition game.h:581
std::string steamType
Steam app type: game, dlc, demo, tool, music, etc.
Definition game.h:582
uint64_t steamBytesDownloaded
Bytes downloaded so far.
Definition game.h:588
int steamAppId
Steam App ID (0 if not a Steam game).
Definition game.h:575
float protondbScore
Cached score (0.0-1.0).
Definition game.h:603
GameImagePaths imagePaths
Paths to all available image assets.
Definition game.h:562
uint32_t steamStateFlags
Steam StateFlags from appmanifest.
Definition game.h:587
CloudSaveInfo cloudSave
Steam Cloud save information.
Definition game.h:596
std::string description
Game description text.
Definition game.h:565
std::string developer
Developer/studio name.
Definition game.h:568
bool steamIsUpdatePending
Update available but not yet started.
Definition game.h:591
std::string steamBuildId
Steam build ID.
Definition game.h:578
uint32_t steamPlaytime2Weeks
Playtime in last 2 weeks (minutes).
Definition game.h:579
std::string steamLaunchOptions
Steam launch options from localconfig.vdf.
Definition game.h:577
uint64_t steamBytesToDownload
Total bytes to download.
Definition game.h:589
std::vector< std::string > tags
User-defined tags for organization.
Definition game.h:567
std::vector< std::string > steamUserCategories
User-defined categories from Steam (tags section).
Definition game.h:595
time_t protondbLastUpdated
When ProtonDB data was last fetched.
Definition game.h:604
int releaseYear
Year the game was released.
Definition game.h:570
std::string publisher
Publisher name.
Definition game.h:569
std::string protondbTier
Cached tier: "platinum", "gold", "silver", "bronze", "borked", "native".
Definition game.h:601
std::vector< DLCInfo > dlc
Installed DLC for this game.
Definition game.h:597
std::vector< std::string > genres
Game genres (RPG, FPS, Strategy, etc.).
Definition game.h:566
std::string protondbConfidence
Cached confidence: "strong", "good", "weak".
Definition game.h:602
bool steamIsDownloading
Currently downloading/updating.
Definition game.h:590
time_t lastExitTime
Unix timestamp of last exit.
Definition game.h:727
std::string lastExitReason
Reason game stopped: "normal", "crash", "timeout", "unknown".
Definition game.h:726
std::string lastProtonVersion
Proton version used in last launch.
Definition game.h:721
time_t dateInstalled
Unix timestamp when installed.
Definition game.h:717
std::map< std::string, std::string > lastEnvironmentVars
Environment variables from last launch.
Definition game.h:723
std::string lastLaunchCommand
Full command used for last launch (with env vars).
Definition game.h:720
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
Definition game.h:714
time_t lastPlayed
Unix timestamp of last play session.
Definition game.h:715
int timesLaunched
Number of times game was launched.
Definition game.h:713
time_t dateAdded
Unix timestamp when added to library.
Definition game.h:716
int crashCount
Number of times game has crashed.
Definition game.h:728
time_t lastUpdated
When this data was fetched.
Definition game.h:683
double allStylesHours
Average across all playstyles.
Definition game.h:680
double completionistHours
100% completion
Definition game.h:679
int hltbId
HowLongToBeat game ID.
Definition game.h:673
bool found
Whether a match was found.
Definition game.h:684
std::string matchedName
Name matched on HLTB.
Definition game.h:674
double mainPlusExtrasHours
Main + side content.
Definition game.h:678
double mainStoryHours
Main story/campaign only.
Definition game.h:677
Record of a single game play session.
Definition game.h:630
time_t startTime
Unix timestamp when session started.
Definition game.h:632
float minFps
Minimum FPS during session.
Definition game.h:643
std::string exitReason
"normal", "crash", "timeout", "force_stop"
Definition game.h:638
int64_t sessionId
Unique session ID (auto-generated).
Definition game.h:631
double durationSeconds
Session duration in seconds.
Definition game.h:634
time_t endTime
Unix timestamp when session ended (0 if still running).
Definition game.h:633
float avgFrametime
Average frametime in ms.
Definition game.h:644
int exitCode
Process exit code.
Definition game.h:639
std::string protonVersion
Proton/Wine version used.
Definition game.h:637
float avgFps
Average FPS during session (0 if not captured).
Definition game.h:642
@ Game
Game-specific fixes.