12#include <nlohmann/json.hpp>
38namespace fs = std::filesystem;
39using json = nlohmann::json;
47-- Games table: Every field is a dedicated column for queryability
48CREATE TABLE IF NOT EXISTS games (
50 id TEXT PRIMARY KEY 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,
57 install_size_bytes INTEGER DEFAULT 0,
59 -- Runner configuration (JSON blob — complex opaque config)
62 -- Config templates (JSON blob — named presets map)
63 config_templates TEXT,
64 active_template_name TEXT,
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,
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,
81 -- Descriptive metadata
84 release_year INTEGER DEFAULT 0,
86 user_rating REAL DEFAULT 0,
89 image_vertical_cover TEXT,
96 -- Genres and tags (JSON arrays)
101 steam_app_id INTEGER DEFAULT 0,
102 steam_installed INTEGER DEFAULT 1,
103 steam_launch_options TEXT,
105 steam_playtime_2weeks INTEGER DEFAULT 0,
106 steam_last_launch INTEGER DEFAULT 0,
107 steam_last_exit INTEGER DEFAULT 0,
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,
117 -- ProtonDB compatibility cache
119 protondb_confidence TEXT,
120 protondb_score REAL DEFAULT 0,
121 protondb_last_updated INTEGER DEFAULT 0,
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,
131 dlc_count INTEGER DEFAULT 0,
133 -- Completion tracking
134 completion_status INTEGER DEFAULT 0,
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,
147 created_at INTEGER DEFAULT (strftime('%s', 'now')),
148 updated_at INTEGER DEFAULT (strftime('%s', 'now'))
152CREATE TABLE IF NOT EXISTS collections (
153 id INTEGER PRIMARY KEY AUTOINCREMENT,
154 name TEXT UNIQUE NOT NULL
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
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,
171 duration_seconds INTEGER DEFAULT 0,
172 runner INTEGER NOT NULL,
174 exit_reason TEXT DEFAULT 'unknown',
175 environment_vars 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
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,
191 runner INTEGER NOT NULL,
193 time_to_launch_ms INTEGER,
194 FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
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'))
210-- Daily playtime aggregation
211CREATE TABLE IF NOT EXISTS daily_playtime (
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
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);
244CREATE VIRTUAL TABLE IF NOT EXISTS games_fts USING fts5(
252 content_rowid='rowid'
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);
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);
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);
273-- Schema version (single row)
274CREATE TABLE IF NOT EXISTS schema_version (
275 version INTEGER PRIMARY KEY
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,
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,
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
388 json arr = json::array();
389 for (
const auto& s : vec)
396 std::vector<std::string> result;
397 if (str.empty() || str ==
"[]")
401 json arr = json::parse(str);
404 for (
const auto& item : arr)
406 if (item.is_string())
407 result.push_back(item.get<std::string>());
411 catch (
const json::exception&)
420 json obj = json::object();
421 for (
const auto& [k, v] : vars)
428 std::map<std::string, std::string> result;
429 if (str.empty() || str ==
"{}")
433 json obj = json::parse(str);
436 for (
auto& [k, v] : obj.items())
439 result[k] = v.get<std::string>();
443 catch (
const json::exception&)
463 : db_(other.db_), lastError_(std::move(other.lastError_)), dbPath_(std::move(other.dbPath_)),
464 lockFd_(other.lockFd_), stmtCache_(std::move(other.stmtCache_))
472 other.stmtCache_.clear();
483 lastError_ = std::move(other.lastError_);
484 dbPath_ = std::move(other.dbPath_);
485 stmtCache_ = std::move(other.stmtCache_);
486 lockFd_ = other.lockFd_;
488 other.stmtCache_.clear();
500 std::lock_guard<std::recursive_mutex> lock(mutex_);
504 lastError_ =
"Database already open";
509 fs::path dbPath(path);
510 if (dbPath.has_parent_path())
513 fs::create_directories(dbPath.parent_path(), ec);
516 lastError_ =
"Failed to create directory: " + ec.message();
535 std::string lockPath = path +
".lock";
536 int fd =
::open(lockPath.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
540 "Cannot create lockfile " + lockPath +
": " + std::string(std::strerror(errno));
543 if (::flock(fd, LOCK_EX | LOCK_NB) != 0)
549 const int flockErrno = errno;
552 if (flockErrno == EWOULDBLOCK)
554 lastError_ =
"Another launcher instance is already using this database "
556 lockPath +
" held).";
561 "flock failed on " + lockPath +
": " + std::string(std::strerror(flockErrno));
570 int rc = sqlite3_open(path.c_str(), &db_);
573 lastError_ = sqlite3_errmsg(db_);
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");
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)
605 const char* mode =
reinterpret_cast<const char*
>(sqlite3_column_text(probe, 0));
606 std::string actual = mode ? mode :
"(null)";
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.",
618 sqlite3_finalize(probe);
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)
627 if (sqlite3_column_int(probe, 0) != 1)
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.");
635 sqlite3_finalize(probe);
657 std::lock_guard<std::recursive_mutex> lock(mutex_);
661 clearStatementCache();
688sqlite3_stmt* GameDatabase::getCachedStatement(
const char* sql)
const
690 auto it = stmtCache_.find(sql);
691 if (it != stmtCache_.end())
693 sqlite3_reset(it->second);
694 sqlite3_clear_bindings(it->second);
698 sqlite3_stmt* stmt =
nullptr;
699 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
702 lastError_ = sqlite3_errmsg(db_);
706 stmtCache_[sql] = stmt;
710void GameDatabase::clearStatementCache()
712 for (
auto& [sql, stmt] : stmtCache_)
715 sqlite3_finalize(stmt);
722 std::lock_guard<std::recursive_mutex> lock(mutex_);
723 return db_ !=
nullptr;
728 std::lock_guard<std::recursive_mutex> lock(mutex_);
738 std::lock_guard<std::recursive_mutex> lock(mutex_);
742 lastError_ =
"Database not open";
748 lastError_ =
"Cannot insert game with empty ID";
753 bool ownTransaction = sqlite3_get_autocommit(db_) != 0;
755 executeSQL(
"BEGIN TRANSACTION");
765 std::string configTemplatesJson;
768 json templates = json::object();
776 configTemplatesJson = templates.dump();
779 const char* sql = R
"SQL(
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,
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,
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
824 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
827 lastError_ = sqlite3_errmsg(db_);
829 executeSQL(
"ROLLBACK");
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);
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));
848 sqlite3_bind_text(stmt, p++, runnerConfigJson.c_str(), -1, SQLITE_TRANSIENT);
851 if (configTemplatesJson.empty())
852 sqlite3_bind_null(stmt, p++);
854 sqlite3_bind_text(stmt, p++, configTemplatesJson.c_str(), -1, SQLITE_TRANSIENT);
870 sqlite3_bind_text(stmt, p++, envVarsJson.c_str(), -1, SQLITE_TRANSIENT);
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);
889 sqlite3_bind_text(stmt, p++, genresJson.c_str(), -1, SQLITE_TRANSIENT);
890 sqlite3_bind_text(stmt, p++, tagsJson.c_str(), -1, SQLITE_TRANSIENT);
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);
923 sqlite3_bind_int(stmt, p++,
static_cast<int>(game.
metadata.
dlc.size()));
927 sqlite3_bind_text(stmt, p++, game.
userNotes.c_str(), -1, SQLITE_TRANSIENT);
938 rc = sqlite3_step(stmt);
939 sqlite3_finalize(stmt);
941 if (rc != SQLITE_DONE)
943 lastError_ = sqlite3_errmsg(db_);
945 executeSQL(
"ROLLBACK");
952 if (!addGameToCollectionInternal(game.
id, collection))
955 executeSQL(
"ROLLBACK");
956 lastError_ =
"Failed to add game to collection: " + collection;
962 executeSQL(
"COMMIT");
968 std::lock_guard<std::recursive_mutex> lock(mutex_);
972 lastError_ =
"Database not open";
976 bool ownTransaction = sqlite3_get_autocommit(db_) != 0;
978 executeSQL(
"BEGIN TRANSACTION");
987 std::string configTemplatesJson;
990 json templates = json::object();
997 configTemplatesJson = templates.dump();
1000 const char* sql = R
"SQL(
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 = ?,
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')
1026 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1027 if (rc != SQLITE_OK)
1029 lastError_ = sqlite3_errmsg(db_);
1031 executeSQL(
"ROLLBACK");
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);
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));
1049 sqlite3_bind_text(stmt, p++, runnerConfigJson.c_str(), -1, SQLITE_TRANSIENT);
1052 if (configTemplatesJson.empty())
1053 sqlite3_bind_null(stmt, p++);
1055 sqlite3_bind_text(stmt, p++, configTemplatesJson.c_str(), -1, SQLITE_TRANSIENT);
1071 sqlite3_bind_text(stmt, p++, envVarsJson.c_str(), -1, SQLITE_TRANSIENT);
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);
1090 sqlite3_bind_text(stmt, p++, genresJson.c_str(), -1, SQLITE_TRANSIENT);
1091 sqlite3_bind_text(stmt, p++, tagsJson.c_str(), -1, SQLITE_TRANSIENT);
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);
1124 sqlite3_bind_int(stmt, p++,
static_cast<int>(game.
metadata.
dlc.size()));
1128 sqlite3_bind_text(stmt, p++, game.
userNotes.c_str(), -1, SQLITE_TRANSIENT);
1140 sqlite3_bind_text(stmt, p++, game.
id.c_str(), -1, SQLITE_TRANSIENT);
1142 rc = sqlite3_step(stmt);
1143 sqlite3_finalize(stmt);
1145 if (rc != SQLITE_DONE)
1147 lastError_ = sqlite3_errmsg(db_);
1149 executeSQL(
"ROLLBACK");
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)
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)
1165 executeSQL(
"ROLLBACK");
1166 lastError_ = sqlite3_errmsg(db_);
1173 if (!addGameToCollectionInternal(game.
id, collection))
1176 executeSQL(
"ROLLBACK");
1177 lastError_ =
"Failed to add game to collection: " + collection;
1183 executeSQL(
"COMMIT");
1189 std::lock_guard<std::recursive_mutex> lock(mutex_);
1193 lastError_ =
"Database not open";
1197 const char* sql =
"DELETE FROM games WHERE id = ?";
1200 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1201 if (rc != SQLITE_OK)
1203 lastError_ = sqlite3_errmsg(db_);
1207 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1209 rc = sqlite3_step(stmt);
1210 sqlite3_finalize(stmt);
1212 if (rc != SQLITE_DONE)
1214 lastError_ = sqlite3_errmsg(db_);
1223 std::lock_guard<std::recursive_mutex> lock(mutex_);
1227 lastError_ =
"Database not open";
1231 static const char* sql = R
"SQL(
1233 image_vertical_cover = ?,
1239 updated_at = strftime('%s', 'now')
1243 sqlite3_stmt* stmt = getCachedStatement(sql);
1246 lastError_ =
"Failed to prepare updateGameImages statement";
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);
1258 int rc = sqlite3_step(stmt);
1259 if (rc != SQLITE_DONE)
1261 lastError_ = sqlite3_errmsg(db_);
1270 std::lock_guard<std::recursive_mutex> lock(mutex_);
1272 std::vector<Game> results;
1275 lastError_ =
"Database not open";
1279 std::string sql =
"SELECT " + std::string(
GAME_COLUMNS) +
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 = '')"
1290 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt,
nullptr);
1291 if (rc != SQLITE_OK)
1293 lastError_ = sqlite3_errmsg(db_);
1298 sqlite3_bind_int(stmt, 1, limit);
1300 while (sqlite3_step(stmt) == SQLITE_ROW)
1301 results.push_back(gameFromStatement(stmt));
1302 sqlite3_finalize(stmt);
1309 std::lock_guard<std::recursive_mutex> lock(mutex_);
1313 lastError_ =
"Database not open";
1314 return std::nullopt;
1317 std::string sqlStr =
"SELECT " + std::string(
GAME_COLUMNS) +
" FROM games g WHERE g.id = ?";
1320 int rc = sqlite3_prepare_v2(db_, sqlStr.c_str(), -1, &stmt,
nullptr);
1321 if (rc != SQLITE_OK)
1323 lastError_ = sqlite3_errmsg(db_);
1324 return std::nullopt;
1327 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1329 rc = sqlite3_step(stmt);
1330 if (rc != SQLITE_ROW)
1332 sqlite3_finalize(stmt);
1333 return std::nullopt;
1336 Game game = gameFromStatement(stmt);
1337 sqlite3_finalize(stmt);
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 = ?
1346 sqlite3_stmt* collStmt;
1347 if (sqlite3_prepare_v2(db_, collSql, -1, &collStmt,
nullptr) == SQLITE_OK)
1349 sqlite3_bind_text(collStmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1350 while (sqlite3_step(collStmt) == SQLITE_ROW)
1352 const char* name =
reinterpret_cast<const char*
>(sqlite3_column_text(collStmt, 0));
1356 sqlite3_finalize(collStmt);
1364 std::lock_guard<std::recursive_mutex> lock(mutex_);
1369 static const char* sql =
"SELECT 1 FROM games WHERE id = ?";
1371 sqlite3_stmt* stmt = getCachedStatement(sql);
1374 lastError_ =
"Failed to prepare gameExists statement";
1378 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
1380 int rc = sqlite3_step(stmt);
1381 return rc == SQLITE_ROW;
1392 std::lock_guard<std::recursive_mutex> lock(mutex_);
1394 std::vector<Game> results;
1398 lastError_ =
"Database not open";
1402 std::string sql =
"SELECT DISTINCT " + std::string(
GAME_COLUMNS) +
" FROM games g";
1407 JOIN game_collections gc ON g.id = gc.game_id
1408 JOIN collections c ON gc.collection_id = c.id
1413 std::vector<std::string> conditions;
1414 std::vector<std::pair<int, std::string>> stringBindings;
1415 std::vector<std::pair<int, int>> intBindings;
1421 std::string escaped;
1425 if (c ==
'%' || c ==
'_' || c ==
'\\')
1429 conditions.push_back(
"g.name LIKE ? ESCAPE '\\'");
1430 stringBindings.push_back({paramIndex++,
"%" + escaped +
"%"});
1433 conditions.push_back(
"g.is_favorite = 1");
1436 conditions.push_back(
"g.status = ?");
1441 conditions.push_back(
"g.source = ?");
1442 intBindings.push_back({paramIndex++,
static_cast<int>(*filter.
sourceFilter)});
1446 conditions.push_back(
"g.runner = ?");
1447 intBindings.push_back({paramIndex++,
static_cast<int>(*filter.
runnerFilter)});
1451 conditions.push_back(
"c.name = ?");
1452 stringBindings.push_back({paramIndex++, filter.
collection});
1455 if (!conditions.empty())
1458 for (
size_t i = 0; i < conditions.size(); ++i)
1462 sql += conditions[i];
1467 sql +=
" ORDER BY ";
1471 sql +=
"g.name COLLATE NOCASE";
1474 sql +=
"g.last_played";
1477 sql +=
"g.total_play_time_seconds";
1480 sql +=
"g.date_added";
1494 intBindings.push_back({paramIndex++, limit});
1498 intBindings.push_back({paramIndex++, offset});
1503 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt,
nullptr);
1504 if (rc != SQLITE_OK)
1506 lastError_ = sqlite3_errmsg(db_);
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);
1515 while (sqlite3_step(stmt) == SQLITE_ROW)
1516 results.push_back(gameFromStatement(stmt));
1518 sqlite3_finalize(stmt);
1521 if (!results.empty())
1523 std::unordered_map<std::string, std::vector<std::string>> collectionsMap;
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)
1536 collSqlStr +=
") ORDER BY gc.game_id, c.name";
1538 sqlite3_stmt* collStmt =
nullptr;
1539 if (sqlite3_prepare_v2(db_, collSqlStr.c_str(), -1, &collStmt,
nullptr) == SQLITE_OK)
1541 for (
size_t i = 0; i < results.size(); ++i)
1543 sqlite3_bind_text(collStmt,
static_cast<int>(i + 1), results[i].
id.c_str(), -1,
1546 while (sqlite3_step(collStmt) == SQLITE_ROW)
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);
1559 Logger::error(
"[GameDatabase] Failed to prepare collection query: {}",
1560 sqlite3_errmsg(db_));
1563 for (
auto& game : results)
1565 auto it = collectionsMap.find(game.
id);
1566 if (it != collectionsMap.end())
1581 std::lock_guard<std::recursive_mutex> lock(mutex_);
1586 std::string sql =
"SELECT COUNT(*) FROM games g";
1588 std::vector<std::string> conditions;
1589 std::vector<std::pair<int, int>> intBindings;
1593 conditions.push_back(
"is_favorite = 1");
1596 conditions.push_back(
"status = ?");
1601 conditions.push_back(
"source = ?");
1602 intBindings.push_back({paramIdx++,
static_cast<int>(*filter.
sourceFilter)});
1606 conditions.push_back(
"runner = ?");
1607 intBindings.push_back({paramIdx++,
static_cast<int>(*filter.
runnerFilter)});
1610 if (!conditions.empty())
1613 for (
size_t i = 0; i < conditions.size(); ++i)
1617 sql += conditions[i];
1622 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt,
nullptr);
1623 if (rc != SQLITE_OK)
1626 for (
const auto& [idx, value] : intBindings)
1627 sqlite3_bind_int(stmt, idx, value);
1629 rc = sqlite3_step(stmt);
1630 int count = (rc == SQLITE_ROW) ? sqlite3_column_int(stmt, 0) : 0;
1631 sqlite3_finalize(stmt);
1638 std::lock_guard<std::recursive_mutex> lock(mutex_);
1640 std::vector<Game> results;
1641 if (!db_ || query.empty())
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 ?";
1650 int rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt,
nullptr);
1652 if (rc != SQLITE_OK)
1657 " FROM games g WHERE g.name LIKE ? ESCAPE '\\' ORDER BY g.name COLLATE NOCASE LIMIT ?";
1659 rc = sqlite3_prepare_v2(db_, sql.c_str(), -1, &stmt,
nullptr);
1660 if (rc != SQLITE_OK)
1662 lastError_ = sqlite3_errmsg(db_);
1667 std::string escaped;
1668 escaped.reserve(query.size() * 2);
1669 for (
char c : query)
1671 if (c ==
'%' || c ==
'_' || c ==
'\\')
1675 std::string likeQuery =
"%" + escaped +
"%";
1676 sqlite3_bind_text(stmt, 1, likeQuery.c_str(), -1, SQLITE_TRANSIENT);
1682 std::string sanitized;
1683 std::istringstream words(query);
1685 while (words >> word)
1688 word.erase(std::remove(word.begin(), word.end(),
'"'), word.end());
1691 if (!sanitized.empty())
1693 sanitized +=
'"' + word +
'"';
1695 if (sanitized.empty())
1697 sqlite3_finalize(stmt);
1700 sqlite3_bind_text(stmt, 1, sanitized.c_str(), -1, SQLITE_TRANSIENT);
1703 sqlite3_bind_int(stmt, 2, limit);
1705 while (sqlite3_step(stmt) == SQLITE_ROW)
1706 results.push_back(gameFromStatement(stmt));
1708 sqlite3_finalize(stmt);
1718 std::lock_guard<std::recursive_mutex> lock(mutex_);
1720 std::vector<std::string> collections;
1724 const char* sql =
"SELECT name FROM collections ORDER BY name";
1727 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1728 if (rc != SQLITE_OK)
1731 while (sqlite3_step(stmt) == SQLITE_ROW)
1733 const char* name =
reinterpret_cast<const char*
>(sqlite3_column_text(stmt, 0));
1735 collections.push_back(name);
1738 sqlite3_finalize(stmt);
1744 std::lock_guard<std::recursive_mutex> lock(mutex_);
1749 const char* sql =
"INSERT OR IGNORE INTO collections (name) VALUES (?)";
1752 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1753 if (rc != SQLITE_OK)
1756 sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_TRANSIENT);
1757 rc = sqlite3_step(stmt);
1758 sqlite3_finalize(stmt);
1760 return rc == SQLITE_DONE;
1765 std::lock_guard<std::recursive_mutex> lock(mutex_);
1770 const char* sql =
"DELETE FROM collections WHERE name = ?";
1773 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1774 if (rc != SQLITE_OK)
1777 sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_TRANSIENT);
1778 rc = sqlite3_step(stmt);
1779 sqlite3_finalize(stmt);
1781 return rc == SQLITE_DONE;
1786 std::lock_guard<std::recursive_mutex> lock(mutex_);
1787 return addGameToCollectionInternal(gameId, collection);
1790bool GameDatabase::addGameToCollectionInternal(
const std::string& gameId,
1791 const std::string& collection)
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)
1809 sqlite3_bind_text(stmt, 1, collection.c_str(), -1, SQLITE_TRANSIENT);
1811 sqlite3_finalize(stmt);
1815 Logger::warn(
"[GameDatabase] Failed to prepare collection-insert ('{}'): {} ({})",
1816 collection, sqlite3_errmsg(db_), prepRc);
1821 const char* sql = R
"SQL(
1822 INSERT OR IGNORE INTO game_collections (game_id, collection_id)
1823 SELECT ?, id FROM collections WHERE name = ?
1827 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1828 if (rc != SQLITE_OK)
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);
1836 return rc == SQLITE_DONE;
1840 const std::string& collection)
1842 std::lock_guard<std::recursive_mutex> lock(mutex_);
1843 return removeGameFromCollectionInternal(gameId, collection);
1846bool GameDatabase::removeGameFromCollectionInternal(
const std::string& gameId,
1847 const std::string& collection)
1852 const char* sql = R
"SQL(
1853 DELETE FROM game_collections
1855 AND collection_id = (SELECT id FROM collections WHERE name = ?)
1859 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
1860 if (rc != SQLITE_OK)
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);
1868 return rc == SQLITE_DONE;
1881 std::lock_guard<std::recursive_mutex> lock(mutex_);
1884 lastError_ =
"Database not open";
1889 json arr = json::array();
1891 for (
const auto& g : games)
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;
1906 obj[
"runnerConfig"] = json::parse(g.serializeRunnerConfig());
1907 obj[
"metadata"] = json::parse(g.serializeMetadata());
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;
1922 json envObj = json::object();
1923 for (
const auto& [k, v] : g.statistics.lastEnvironmentVars)
1925 obj[
"lastEnvironmentVars"] = envObj;
1928 obj[
"completionStatus"] =
static_cast<int>(g.completionStatus);
1929 obj[
"userNotes"] = g.userNotes;
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);
1941 obj[
"collections"] = g.collections;
1946 std::ofstream file(path);
1947 if (!file.is_open())
1949 lastError_ =
"Failed to open file for writing";
1953 file << arr.dump(2);
1954 Logger::info(
"Exported {} games to JSON: {}", games.size(), path);
1960 std::ifstream file(path);
1961 if (!file.is_open())
1963 lastError_ =
"Failed to open file for reading: " + path;
1970 arr = json::parse(file);
1972 catch (
const json::exception& e)
1974 lastError_ = std::string(
"JSON parse error: ") + e.what();
1978 if (!arr.is_array())
1980 lastError_ =
"Expected JSON array at top level";
1988 for (
const auto& obj : arr)
1994 game.
id = obj.value(
"id",
"");
1995 game.
name = obj.value(
"name",
"");
1997 if (game.
id.empty() || game.
name.empty())
1999 Logger::warn(
"Skipping game with missing id or name in JSON import");
2010 game.
isFavorite = obj.value(
"isFavorite",
false);
2012 game.
installSizeBytes = obj.value(
"installSizeBytes",
static_cast<uint64_t
>(0));
2015 if (obj.contains(
"runnerConfig") && obj[
"runnerConfig"].is_object())
2019 if (obj.contains(
"metadata") && obj[
"metadata"].is_object())
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)));
2035 static_cast<time_t
>(obj.value(
"lastExitTime",
static_cast<int64_t
>(0)));
2039 if (obj.contains(
"lastEnvironmentVars") && obj[
"lastEnvironmentVars"].is_object())
2041 for (
auto& [k, v] : obj[
"lastEnvironmentVars"].items())
2051 kMaxCompletionStatus);
2052 game.
userNotes = obj.value(
"userNotes",
"");
2062 static_cast<time_t
>(obj.value(
"hltbLastUpdated",
static_cast<int64_t
>(0)));
2066 if (obj.contains(
"collections") && obj[
"collections"].is_array())
2068 for (
const auto& c : obj[
"collections"])
2075 catch (
const json::exception& e)
2077 Logger::warn(
"Failed to parse game from JSON: {}", e.what());
2083 if (exists && !overwriteExisting)
2095 Logger::warn(
"Failed to {} game '{}': {}", exists ?
"update" :
"insert", game.
name,
2101 Logger::info(
"JSON import complete: {} imported, {} skipped, {} errors (from {} total)",
2102 imported, skipped, errors, arr.size());
2112 std::lock_guard<std::recursive_mutex> lock(mutex_);
2113 return executeSQL(
"VACUUM");
2118 std::lock_guard<std::recursive_mutex> lock(mutex_);
2119 auto r = getSchemaVersionInternal();
2120 return r.state == SchemaVersionState::Found ? r.version : 0;
2123GameDatabase::SchemaVersionResult GameDatabase::getSchemaVersionInternal()
const
2125 SchemaVersionResult out{SchemaVersionState::NoTable, 0};
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)
2139 bool tableExists = (sqlite3_step(check) == SQLITE_ROW);
2140 sqlite3_finalize(check);
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)
2157 Logger::error(
"[GameDatabase] schema_version table present but SELECT "
2158 "MAX(version) failed: {}",
2159 sqlite3_errmsg(db_));
2160 out.state = SchemaVersionState::Error;
2164 int rc = sqlite3_step(stmt);
2165 if (rc == SQLITE_ROW && sqlite3_column_type(stmt, 0) != SQLITE_NULL)
2167 out.state = SchemaVersionState::Found;
2168 out.version = sqlite3_column_int(stmt, 0);
2172 out.state = SchemaVersionState::Empty;
2174 sqlite3_finalize(stmt);
2184 std::lock_guard<std::recursive_mutex> lock(mutex_);
2185 return executeSQL(
"BEGIN TRANSACTION");
2190 std::lock_guard<std::recursive_mutex> lock(mutex_);
2191 return executeSQL(
"COMMIT");
2196 std::lock_guard<std::recursive_mutex> lock(mutex_);
2197 return executeSQL(
"ROLLBACK");
2202 std::lock_guard<std::recursive_mutex> lock(mutex_);
2204 if (!executeSQL(
"BEGIN TRANSACTION"))
2210 return executeSQL(
"COMMIT");
2213 executeSQL(
"ROLLBACK");
2219 executeSQL(
"ROLLBACK");
2240bool GameDatabase::runMigrations(
int fromVersion)
2283 static constexpr std::array<Step, 0> kSteps{};
2285 Logger::info(
"[GameDatabase] Running migrations from v{} to v{}", fromVersion, SCHEMA_VERSION);
2287 if (!executeSQL(
"BEGIN TRANSACTION"))
2289 lastError_ =
"Failed to begin migration transaction";
2293 for (
int v = fromVersion; v < SCHEMA_VERSION; ++v)
2296 const Step* step =
nullptr;
2297 for (
const auto& s : kSteps)
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);
2313 if (!step->fn(*
this))
2315 Logger::error(
"[GameDatabase] Migration step v{} -> v{} failed; rolling back.", v,
2317 executeSQL(
"ROLLBACK");
2319 if (lastError_.empty())
2320 lastError_ =
"Migration step v" + std::to_string(v) +
" failed";
2326 if (!executeSQL(
"INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2327 std::to_string(v + 1) +
")"))
2329 executeSQL(
"ROLLBACK");
2330 lastError_ =
"Failed to record schema_version v" + std::to_string(v + 1);
2335 if (!executeSQL(
"COMMIT"))
2337 executeSQL(
"ROLLBACK");
2338 lastError_ =
"Failed to commit migration transaction";
2341 Logger::info(
"[GameDatabase] Migrations complete; now at v{}", SCHEMA_VERSION);
2345bool GameDatabase::createSchema()
2348 const char* checkSql =
"SELECT name FROM sqlite_master WHERE type='table' AND name='games'";
2350 int rc = sqlite3_prepare_v2(db_, checkSql, -1, &stmt,
nullptr);
2351 if (rc != SQLITE_OK)
2353 lastError_ = sqlite3_errmsg(db_);
2357 bool schemaExists = (sqlite3_step(stmt) == SQLITE_ROW);
2358 sqlite3_finalize(stmt);
2363 char* errMsg =
nullptr;
2364 rc = sqlite3_exec(db_,
SCHEMA_SQL,
nullptr,
nullptr, &errMsg);
2365 if (rc != SQLITE_OK)
2367 lastError_ = errMsg ? errMsg :
"Failed to create schema";
2368 sqlite3_free(errMsg);
2373 executeSQL(
"INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2374 std::to_string(SCHEMA_VERSION) +
")");
2376 Logger::info(
"Created database schema version {}", SCHEMA_VERSION);
2381 SchemaVersionResult ver = getSchemaVersionInternal();
2382 int currentVersion = (ver.state == SchemaVersionState::Found) ? ver.version : 0;
2384 if (ver.state == SchemaVersionState::Error)
2390 Logger::error(
"[GameDatabase] Cannot determine schema version of '{}' — "
2391 "table query failed. Refusing to open.",
2393 lastError_ =
"Cannot determine schema version (DB may be corrupt or locked)";
2397 if (ver.state == SchemaVersionState::NoTable || ver.state == SchemaVersionState::Empty)
2407 Logger::warn(
"[GameDatabase] schema_version unrecorded; assuming current "
2408 "schema and stamping v{}.",
2410 executeSQL(
"INSERT OR REPLACE INTO schema_version (version) VALUES (" +
2411 std::to_string(SCHEMA_VERSION) +
")");
2413 else if (currentVersion > SCHEMA_VERSION)
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) +
2426 else if (currentVersion < SCHEMA_VERSION)
2429 if (!runMigrations(currentVersion))
2445bool GameDatabase::executeSQL(
const std::string& sql)
2449 lastError_ =
"Database not open";
2453 char* errMsg =
nullptr;
2454 int rc = sqlite3_exec(db_, sql.c_str(),
nullptr,
nullptr, &errMsg);
2455 if (rc != SQLITE_OK)
2457 lastError_ = errMsg ? errMsg :
"SQL execution failed";
2458 sqlite3_free(errMsg);
2465Game GameDatabase::gameFromStatement(sqlite3_stmt* stmt)
const
2469 auto getText = [](sqlite3_stmt* s,
int col) -> std::string
2471 const char* text =
reinterpret_cast<const char*
>(sqlite3_column_text(s, col));
2472 return text ? text :
"";
2496 if (!runnerConfigJson.empty())
2501 if (!configTemplatesJson.empty())
2505 json templates = json::parse(configTemplatesJson);
2506 if (templates.is_object())
2508 for (
auto& [name, configJson] : templates.items())
2516 catch (
const json::exception& e)
2518 Logger::warn(
"[GameDatabase] Failed to parse configTemplates JSON for game {}: {}",
2638 const std::string& protonVersion)
2640 std::lock_guard<std::recursive_mutex> lock(mutex_);
2644 lastError_ =
"Database not open";
2648 const char* sql = R
"SQL(
2649 INSERT INTO game_sessions (game_id, start_time, runner, proton_version)
2650 VALUES (?, strftime('%s', 'now'), ?, ?)
2654 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2655 if (rc != SQLITE_OK)
2657 lastError_ = sqlite3_errmsg(db_);
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);
2665 rc = sqlite3_step(stmt);
2666 sqlite3_finalize(stmt);
2668 if (rc != SQLITE_DONE)
2670 lastError_ = sqlite3_errmsg(db_);
2674 int64_t sessionId = sqlite3_last_insert_rowid(db_);
2675 Logger::debug(
"Started session {} for game {}", sessionId, gameId);
2681 std::lock_guard<std::recursive_mutex> lock(mutex_);
2685 lastError_ =
"Database not open";
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,
2698 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2699 if (rc != SQLITE_OK)
2701 lastError_ = sqlite3_errmsg(db_);
2705 sqlite3_bind_text(stmt, 1, exitReason.c_str(), -1, SQLITE_TRANSIENT);
2706 sqlite3_bind_int64(stmt, 2, sessionId);
2708 rc = sqlite3_step(stmt);
2709 sqlite3_finalize(stmt);
2711 if (rc != SQLITE_DONE)
2713 lastError_ = sqlite3_errmsg(db_);
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)
2722 sqlite3_bind_int64(stmt, 1, sessionId);
2723 if (sqlite3_step(stmt) == SQLITE_ROW)
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);
2733 const char* gameId = gameIdStr.empty() ? nullptr : gameIdStr.c_str();
2734 if (gameId && duration > 0)
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
2745 sqlite3_stmt* dailyStmt;
2746 if (sqlite3_prepare_v2(db_, dailySql, -1, &dailyStmt,
nullptr) == SQLITE_OK)
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);
2755 const char* runnerPlaytimeSql = R
"SQL(
2756 INSERT INTO runner_stats (runner, total_play_time_seconds, total_sessions)
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')
2764 sqlite3_stmt* runnerStmt;
2765 if (sqlite3_prepare_v2(db_, runnerPlaytimeSql, -1, &runnerStmt,
nullptr) ==
2768 sqlite3_bind_int(runnerStmt, 1, runnerVal);
2769 sqlite3_bind_int(runnerStmt, 2, duration);
2770 sqlite3_step(runnerStmt);
2771 sqlite3_finalize(runnerStmt);
2777 sqlite3_finalize(stmt);
2781 Logger::debug(
"Ended session {} with reason: {}", sessionId, exitReason);
2787 std::lock_guard<std::recursive_mutex> lock(mutex_);
2788 std::vector<PlaySession> sessions;
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
2799 ORDER BY start_time DESC
2803 sqlite3_stmt* stmt = nullptr;
2804 if (sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr) != SQLITE_OK)
2806 lastError_ = std::string(
"Failed to prepare getRecentSessions: ") + sqlite3_errmsg(db_);
2810 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2811 sqlite3_bind_int(stmt, 2, limit);
2813 while (sqlite3_step(stmt) == SQLITE_ROW)
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));
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));
2831 sqlite3_finalize(stmt);
2836 const std::string& protonVersion,
const std::string& errorMessage,
2839 std::lock_guard<std::recursive_mutex> lock(mutex_);
2843 lastError_ =
"Database not open";
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'), ?, ?, ?, ?, ?)
2853 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2854 if (rc != SQLITE_OK)
2856 lastError_ = sqlite3_errmsg(db_);
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);
2867 rc = sqlite3_step(stmt);
2868 sqlite3_finalize(stmt);
2870 if (rc != SQLITE_DONE)
2872 lastError_ = sqlite3_errmsg(db_);
2877 const char* runnerStatsSql = R
"SQL(
2878 INSERT INTO runner_stats (runner, total_launches, successful_launches, failed_launches)
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')
2887 rc = sqlite3_prepare_v2(db_, runnerStatsSql, -1, &stmt, nullptr);
2888 if (rc == SQLITE_OK)
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);
2894 sqlite3_finalize(stmt);
2901 Logger::debug(
"Recorded launch for game {}: success={}", gameId, success);
2907 std::lock_guard<std::recursive_mutex> lock(mutex_);
2911 lastError_ =
"Database not open";
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
2923 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2924 if (rc != SQLITE_OK)
2926 lastError_ = sqlite3_errmsg(db_);
2930 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
2931 sqlite3_bind_int(stmt, 2, playTimeSeconds);
2933 rc = sqlite3_step(stmt);
2934 sqlite3_finalize(stmt);
2936 return rc == SQLITE_DONE;
2944 const std::string& endDate)
const
2946 std::lock_guard<std::recursive_mutex> lock(mutex_);
2951 const char* sql = R
"SQL(
2952 SELECT COALESCE(SUM(play_time_seconds), 0)
2954 WHERE date BETWEEN ? AND ?
2958 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2959 if (rc != SQLITE_OK)
2962 sqlite3_bind_text(stmt, 1, startDate.c_str(), -1, SQLITE_TRANSIENT);
2963 sqlite3_bind_text(stmt, 2, endDate.c_str(), -1, SQLITE_TRANSIENT);
2966 if (sqlite3_step(stmt) == SQLITE_ROW)
2967 total = sqlite3_column_int64(stmt, 0);
2968 sqlite3_finalize(stmt);
2973std::vector<std::pair<std::string, int64_t>>
2977 std::lock_guard<std::recursive_mutex> lock(mutex_);
2979 std::vector<std::pair<std::string, int64_t>> results;
2983 const char* sql = R
"SQL(
2984 SELECT game_id, SUM(play_time_seconds) as total
2986 WHERE date BETWEEN ? AND ?
2993 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
2994 if (rc != SQLITE_OK)
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)
3003 const char* gameId =
reinterpret_cast<const char*
>(sqlite3_column_text(stmt, 0));
3004 int64_t playTime = sqlite3_column_int64(stmt, 1);
3006 results.emplace_back(gameId, playTime);
3008 sqlite3_finalize(stmt);
3013std::vector<std::pair<std::string, int64_t>>
3016 std::lock_guard<std::recursive_mutex> lock(mutex_);
3018 std::vector<std::pair<std::string, int64_t>> results;
3022 const char* sql = R
"SQL(
3023 SELECT date, SUM(play_time_seconds) as total
3025 WHERE date BETWEEN ? AND ?
3031 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
3032 if (rc != SQLITE_OK)
3035 sqlite3_bind_text(stmt, 1, startDate.c_str(), -1, SQLITE_TRANSIENT);
3036 sqlite3_bind_text(stmt, 2, endDate.c_str(), -1, SQLITE_TRANSIENT);
3038 while (sqlite3_step(stmt) == SQLITE_ROW)
3040 const char* date =
reinterpret_cast<const char*
>(sqlite3_column_text(stmt, 0));
3041 int64_t playTime = sqlite3_column_int64(stmt, 1);
3043 results.emplace_back(date, playTime);
3045 sqlite3_finalize(stmt);
3052 std::lock_guard<std::recursive_mutex> lock(mutex_);
3054 std::vector<std::pair<GameRunner, int64_t>> results;
3058 const char* sql = R
"SQL(
3059 SELECT runner, total_play_time_seconds
3061 ORDER BY total_play_time_seconds DESC
3065 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
3066 if (rc != SQLITE_OK)
3069 while (sqlite3_step(stmt) == SQLITE_ROW)
3073 int64_t playTime = sqlite3_column_int64(stmt, 1);
3074 results.emplace_back(runner, playTime);
3076 sqlite3_finalize(stmt);
3083 std::lock_guard<std::recursive_mutex> lock(mutex_);
3085 std::vector<std::pair<GameSource, int>> results;
3089 const char* sql = R
"SQL(
3090 SELECT source, COUNT(*) as count
3097 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
3098 if (rc != SQLITE_OK)
3101 while (sqlite3_step(stmt) == SQLITE_ROW)
3105 int count = sqlite3_column_int(stmt, 1);
3106 results.emplace_back(source, count);
3108 sqlite3_finalize(stmt);
3115 DatabaseFilterOptions filter;
3116 DatabaseSortOptions sort;
3125 DatabaseFilterOptions filter;
3126 DatabaseSortOptions sort;
3135 std::lock_guard<std::recursive_mutex> lock(mutex_);
3140 const char* sql = R
"SQL(
3142 SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as crashes,
3149 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
3150 if (rc != SQLITE_OK)
3153 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
3157 if (sqlite3_step(stmt) == SQLITE_ROW)
3159 crashes = sqlite3_column_int(stmt, 0);
3160 total = sqlite3_column_int(stmt, 1);
3162 sqlite3_finalize(stmt);
3164 return {crashes, total};
3169 std::lock_guard<std::recursive_mutex> lock(mutex_);
3174 const char* sql = R
"SQL(
3175 SELECT AVG(duration_seconds)
3177 WHERE game_id = ? AND duration_seconds > 0
3181 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt,
nullptr);
3182 if (rc != SQLITE_OK)
3185 sqlite3_bind_text(stmt, 1, gameId.c_str(), -1, SQLITE_TRANSIENT);
3188 if (sqlite3_step(stmt) == SQLITE_ROW)
3189 avg = sqlite3_column_double(stmt, 0);
3190 sqlite3_finalize(stmt);
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.
GameMetadata metadata
Descriptive information and media.
void deserializeMetadata(const std::string &json)
Deserialize metadata from JSON.
std::string userNotes
User's personal notes about the game.
std::vector< std::string > collections
Collections this game belongs to.
std::string installPath
Installation directory path.
CompletionStatus completionStatus
User's completion status.
bool isFavorite
Is this marked as a favorite game?
std::string name
Display name shown in UI.
std::string serializeRunnerConfig() const
Serialize runner configuration to JSON.
std::string id
Unique identifier (auto-generated or user-specified).
void syncPlatformFromRunner()
Sync the deprecated platform field from the current runner and source.
GameStatistics statistics
Play statistics and usage tracking.
GameRunner runner
Runner/compatibility layer to use (Native, Proton, Wine, etc.).
GameRunnerConfig runnerConfig
How to launch and run the game.
GameStatus status
Current installation and execution status.
HowLongToBeatInfo hltbInfo
Time-to-beat estimates.
std::map< std::string, GameRunnerConfig > configTemplates
Named configuration templates (presets) that can be switched between Key is template name (e....
uint64_t installSizeBytes
Installation size in bytes.
std::string activeTemplateName
Currently active template name (empty = using runnerConfig directly).
void deserializeRunnerConfig(const std::string &json)
Deserialize runner configuration from JSON.
GameSource source
Where the game was acquired from (Steam, GOG, Local, etc.).
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
GameSource
Where the game was acquired from (store/service/local).
@ Steam
Steam store/platform.
@ Unknown
Unknown or unspecified source.
@ NotInstalled
Game is in library but not installed.
@ Updating
Game is being updated.
@ Installed
Game is installed and ready to play.
GameRunner
Runner/compatibility layer for executing the game.
@ Native
Native Linux executable (no compatibility layer).
@ Played
Played but no clear completion criteria (e.g., multiplayer).
@ NotPlayed
Never played (backlog).
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_ACTIVE_TEMPLATE_NAME
@ COL_CLOUD_STORAGE_BYTES
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
constexpr int kMaxCompletionStatus
constexpr int kMaxGameStatus
constexpr int kMaxGameSource
constexpr int kMaxGameRunner
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.
time_t lastSyncTime
Last successful sync timestamp.
bool enabled
Cloud saves enabled for this game.
bool supported
Game supports Steam Cloud.
int lastSyncState
0=synced, 1=uploading, 2=downloading, 3=error
Filter options for database queries.
std::optional< GameSource > sourceFilter
std::optional< GameRunner > runnerFilter
Sort options for database queries.
Paths to various game image assets.
std::string header
Small header image (header.jpg, 460x215).
std::string capsule
Store capsule image (capsule_616x353.jpg).
std::string logo
Game logo with transparency (logo.png).
std::string icon
Small square icon (icon.jpg).
std::string verticalCover
Vertical cover art (library_600x900.jpg).
std::string heroImage
Wide banner/hero image (library_hero.jpg).
time_t lastExitTime
Unix timestamp of last exit.
std::string lastExitReason
Reason game stopped: "normal", "crash", "timeout", "unknown".
std::string lastProtonVersion
Proton version used in last launch.
time_t dateInstalled
Unix timestamp when installed.
std::map< std::string, std::string > lastEnvironmentVars
Environment variables from last launch.
std::string lastLaunchCommand
Full command used for last launch (with env vars).
double totalPlayTimeSeconds
Total play time in seconds (for all sessions).
time_t lastPlayed
Unix timestamp of last play session.
int timesLaunched
Number of times game was launched.
time_t dateAdded
Unix timestamp when added to library.
int crashCount
Number of times game has crashed.
time_t lastUpdated
When this data was fetched.
double allStylesHours
Average across all playstyles.
double completionistHours
100% completion
int hltbId
HowLongToBeat game ID.
bool found
Whether a match was found.
std::string matchedName
Name matched on HLTB.
double mainPlusExtrasHours
Main + side content.
double mainStoryHours
Main story/campaign only.
Record of a single game play session.
time_t startTime
Unix timestamp when session started.
float minFps
Minimum FPS during session.
std::string exitReason
"normal", "crash", "timeout", "force_stop"
int64_t sessionId
Unique session ID (auto-generated).
double durationSeconds
Session duration in seconds.
time_t endTime
Unix timestamp when session ended (0 if still running).
float avgFrametime
Average frametime in ms.
int exitCode
Process exit code.
std::string protonVersion
Proton/Wine version used.
float avgFps
Average FPS during session (0 if not captured).
@ Game
Game-specific fixes.