game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
GameDatabase Class Reference

SQLite-based storage for the game library. More...

#include <game_database.h>

Public Member Functions

 GameDatabase ()
 GameDatabase (const GameDatabase &)=delete
 GameDatabase (GameDatabase &&other) noexcept
 ~GameDatabase ()
bool addCollection (const std::string &name)
 Add a collection.
bool addGameToCollection (const std::string &gameId, const std::string &collection)
 Add game to collection.
bool beginTransaction ()
 Begin a transaction.
void close ()
 Close the database.
bool commitTransaction ()
 Commit current transaction.
bool deleteGame (const std::string &gameId)
 Delete a game by ID.
bool endSession (int64_t sessionId, const std::string &exitReason="normal")
 End a game session.
bool exportToJson (const std::string &path) const
 Export all games to JSON.
bool gameExists (const std::string &gameId) const
 Check if a game exists.
std::vector< Game > getAllGames () const
 Get all games (convenience method).
double getAverageSessionDuration (const std::string &gameId) const
 Get average session duration for a game.
std::vector< std::string > getCollections () const
 Get all collection names.
std::optional< Game > getGame (const std::string &gameId) const
 Get a game by ID.
int getGameCount (const DatabaseFilterOptions &filter={}) const
 Get total game count.
std::pair< int, int > getGameCrashStats (const std::string &gameId) const
 Get crash statistics for a game.
std::vector< Game > getGamesWithoutCoverArt (int limit=0) const
 Get games that are missing cover art.
std::vector< Game > getMostPlayedGames (int limit=10) const
 Get most played games.
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.
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.
std::vector< Game > getRecentlyPlayedGames (int limit=10) const
 Get recently played games.
std::vector< PlaySession > getRecentSessions (const std::string &gameId, int limit=20) const
 Get recent play sessions for a game.
std::vector< std::pair< GameRunner, int64_t > > getRunnerStats () const
 Get runner usage statistics.
int getSchemaVersion () const
 Get database schema version.
std::vector< std::pair< GameSource, int > > getSourceStats () const
 Get source statistics (games per source).
int64_t getTotalPlaytime (const std::string &startDate, const std::string &endDate) const
 Get total playtime for a specific date range.
int importFromJson (const std::string &path, bool overwriteExisting=false)
 Import games from JSON.
bool insertGame (const Game &game)
 Insert a new game.
bool isOpen () const
 Check if database is open.
std::string lastError () const
 Get last error message.
bool open (const std::string &path)
 Open or create the database.
GameDatabase & operator= (const GameDatabase &)=delete
GameDatabase & operator= (GameDatabase &&other) noexcept
std::vector< Game > queryGames (const DatabaseFilterOptions &filter={}, const DatabaseSortOptions &sort={}, int limit=0, int offset=0) const
 Query games with filtering and sorting.
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 removeCollection (const std::string &name)
 Remove a collection.
bool removeGameFromCollection (const std::string &gameId, const std::string &collection)
 Remove game from collection.
bool rollbackTransaction ()
 Rollback current transaction.
std::vector< Game > searchGames (const std::string &query, int limit=50) const
 Search games by name (uses FTS if available).
int64_t startSession (const std::string &gameId, GameRunner runner, const std::string &protonVersion="")
 Record a game session start.
bool updateDailyPlaytime (const std::string &gameId, int playTimeSeconds)
 Update daily playtime aggregation.
bool updateGame (const Game &game)
 Update an existing game.
bool updateGameImages (const std::string &gameId, const GameImagePaths &images)
 Update only the image paths for a game (efficient partial update).
bool vacuum ()
 Vacuum database to reclaim space.
bool withTransaction (const std::function< bool()> &func)
 Execute a function within a transaction.

Detailed Description

SQLite-based storage for the game library.

Manages all game data persistence using SQLite. Provides methods for CRUD operations, filtered queries, and data migration.

Usage Example

if (!db.open("~/.local/share/gamelauncher/library.db")) {
Logger::error("Failed to open database: {}", db.lastError());
return;
}
// Add a game
Game game;
game.name = "My Game";
db.insertGame(game);
// Query games
auto favorites = db.queryGames({.favoritesOnly = true});
std::vector< Game > queryGames(const DatabaseFilterOptions &filter={}, const DatabaseSortOptions &sort={}, int limit=0, int offset=0) const
Query games with filtering and sorting.
bool insertGame(const Game &game)
Insert a new game.
bool open(const std::string &path)
Open or create the database.
std::string lastError() const
Get last error message.
Complete representation of a game in the library.
Definition game.h:767
std::string name
Display name shown in UI.
Definition game.h:774
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124

Definition at line 107 of file game_database.h.

Constructor & Destructor Documentation

◆ GameDatabase() [1/3]

GameDatabase::GameDatabase ( )
default

◆ ~GameDatabase()

GameDatabase::~GameDatabase ( )

Definition at line 455 of file game_database.cpp.

References close().

◆ GameDatabase() [2/3]

GameDatabase::GameDatabase ( const GameDatabase & )
delete

References GameDatabase().

◆ GameDatabase() [3/3]

GameDatabase::GameDatabase ( GameDatabase && other)
noexcept

Definition at line 462 of file game_database.cpp.

References GameDatabase().

Member Function Documentation

◆ addCollection()

bool GameDatabase::addCollection ( const std::string & name)

Add a collection.

Parameters
nameCollection name
Returns
true on success

Definition at line 1660 of file game_database.cpp.

◆ addGameToCollection()

bool GameDatabase::addGameToCollection ( const std::string & gameId,
const std::string & collection )

Add game to collection.

Parameters
gameIdGame ID
collectionCollection name
Returns
true on success

Definition at line 1702 of file game_database.cpp.

◆ beginTransaction()

bool GameDatabase::beginTransaction ( )

Begin a transaction.

Returns
true on success

Definition at line 2093 of file game_database.cpp.

References Game::name, and Logger::warn().

◆ close()

void GameDatabase::close ( )

Close the database.

Definition at line 655 of file game_database.cpp.

References close(), and Logger::info().

Referenced by ~GameDatabase(), close(), open(), and operator=().

◆ commitTransaction()

bool GameDatabase::commitTransaction ( )

Commit current transaction.

Returns
true on success

Definition at line 2099 of file game_database.cpp.

◆ deleteGame()

bool GameDatabase::deleteGame ( const std::string & gameId)

Delete a game by ID.

Parameters
gameIdID of game to delete
Returns
true on success

Definition at line 1122 of file game_database.cpp.

◆ endSession()

bool GameDatabase::endSession ( int64_t sessionId,
const std::string & exitReason = "normal" )

End a game session.

Parameters
sessionIdSession ID from startSession
exitReasonHow the session ended (normal, crash, etc.)
Returns
true on success

Definition at line 2587 of file game_database.cpp.

References COL_CLOUD_ENABLED, COL_CLOUD_STORAGE_BYTES, COL_CLOUD_SUPPORTED, COL_CLOUD_SYNC_STATE, COL_PROTONDB_CONFIDENCE, COL_PROTONDB_LAST_UPDATED, COL_PROTONDB_SCORE, COL_PROTONDB_TIER, COL_STEAM_IS_UPDATE, and Steam.

◆ exportToJson()

bool GameDatabase::exportToJson ( const std::string & path) const

Export all games to JSON.

Parameters
pathOutput file path
Returns
true on success

Definition at line 1786 of file game_database.cpp.

◆ gameExists()

bool GameDatabase::gameExists ( const std::string & gameId) const

Check if a game exists.

Parameters
gameIdID to check
Returns
true if game exists

Definition at line 1283 of file game_database.cpp.

◆ getAllGames()

std::vector< Game > GameDatabase::getAllGames ( ) const

Get all games (convenience method).

Returns
Vector of all games

Definition at line 1492 of file game_database.cpp.

◆ getAverageSessionDuration()

double GameDatabase::getAverageSessionDuration ( const std::string & gameId) const

Get average session duration for a game.

Parameters
gameIdGame ID
Returns
Average session duration in seconds

Definition at line 3000 of file game_database.cpp.

◆ getCollections()

std::vector< std::string > GameDatabase::getCollections ( ) const

Get all collection names.

Returns
Vector of collection names

Definition at line 1634 of file game_database.cpp.

◆ getGame()

std::optional< Game > GameDatabase::getGame ( const std::string & gameId) const

Get a game by ID.

Parameters
gameIdID of game to retrieve
Returns
Game if found, nullopt otherwise

Definition at line 1232 of file game_database.cpp.

◆ getGameCount()

int GameDatabase::getGameCount ( const DatabaseFilterOptions & filter = {}) const

Get total game count.

Parameters
filterOptional filter (empty = all games)
Returns
Number of games matching filter

Definition at line 1497 of file game_database.cpp.

◆ getGameCrashStats()

std::pair< int, int > GameDatabase::getGameCrashStats ( const std::string & gameId) const

Get crash statistics for a game.

Parameters
gameIdGame ID
Returns
Pair of (crashCount, totalLaunches)

Definition at line 2972 of file game_database.cpp.

◆ getGamesWithoutCoverArt()

std::vector< Game > GameDatabase::getGamesWithoutCoverArt ( int limit = 0) const

Get games that are missing cover art.

Parameters
limitMaximum number to return (0 = no limit)
Returns
Vector of games with no vertical cover path set

Definition at line 1193 of file game_database.cpp.

◆ getMostPlayedGames()

std::vector< Game > GameDatabase::getMostPlayedGames ( int limit = 10) const

Get most played games.

Parameters
limitMax results
Returns
Vector of Games sorted by total playtime desc

Definition at line 2952 of file game_database.cpp.

◆ getPlaytimeByDay()

std::vector< std::pair< std::string, int64_t > > GameDatabase::getPlaytimeByDay ( const std::string & startDate,
const std::string & endDate ) const

Get playtime by day for a date range.

Parameters
startDateStart date (YYYY-MM-DD)
endDateEnd date (YYYY-MM-DD)
Returns
Vector of pairs (date, playTimeSeconds) sorted by date

Definition at line 2868 of file game_database.cpp.

◆ getPlaytimeByGame()

std::vector< std::pair< std::string, int64_t > > GameDatabase::getPlaytimeByGame ( const std::string & startDate,
const std::string & endDate,
int limit = 10 ) const

Get playtime by game for a date range.

Parameters
startDateStart date (YYYY-MM-DD)
endDateEnd date (YYYY-MM-DD)
limitMax results
Returns
Vector of pairs (gameId, playTimeSeconds) sorted by playtime desc

Definition at line 2835 of file game_database.cpp.

◆ getRecentlyPlayedGames()

std::vector< Game > GameDatabase::getRecentlyPlayedGames ( int limit = 10) const

Get recently played games.

Parameters
limitMax results
Returns
Vector of Games sorted by last played desc

Definition at line 2962 of file game_database.cpp.

◆ getRecentSessions()

std::vector< PlaySession > GameDatabase::getRecentSessions ( const std::string & gameId,
int limit = 20 ) const

Get recent play sessions for a game.

Parameters
gameIdGame ID
limitMaximum number of sessions to return
Returns
Vector of PlaySession records, most recent first

Definition at line 2674 of file game_database.cpp.

◆ getRunnerStats()

std::vector< std::pair< GameRunner, int64_t > > GameDatabase::getRunnerStats ( ) const

Get runner usage statistics.

Returns
Vector of pairs (runner, totalPlayTimeSeconds) sorted by playtime desc

Definition at line 2898 of file game_database.cpp.

◆ getSchemaVersion()

int GameDatabase::getSchemaVersion ( ) const

Get database schema version.

Definition at line 2027 of file game_database.cpp.

References GameStatistics::lastEnvironmentVars, and Game::statistics.

◆ getSourceStats()

std::vector< std::pair< GameSource, int > > GameDatabase::getSourceStats ( ) const

Get source statistics (games per source).

Returns
Vector of pairs (source, gameCount) sorted by count desc

Definition at line 2925 of file game_database.cpp.

◆ getTotalPlaytime()

int64_t GameDatabase::getTotalPlaytime ( const std::string & startDate,
const std::string & endDate ) const

Get total playtime for a specific date range.

Parameters
startDateStart date (YYYY-MM-DD)
endDateEnd date (YYYY-MM-DD)
Returns
Total playtime in seconds

Definition at line 2808 of file game_database.cpp.

◆ importFromJson()

int GameDatabase::importFromJson ( const std::string & path,
bool overwriteExisting = false )

Import games from JSON.

Parameters
pathInput file path
overwriteExistingOverwrite games with same ID
Returns
Number of games imported, -1 on error

Definition at line 1869 of file game_database.cpp.

◆ insertGame()

bool GameDatabase::insertGame ( const Game & game)

Insert a new game.

Parameters
gameGame to insert (id will be used as primary key)
Returns
true on success

Definition at line 736 of file game_database.cpp.

References Game::activeTemplateName, GameImagePaths::capsule, GameMetadata::cloudSave, Game::configTemplates, GameStatistics::crashCount, GameStatistics::dateAdded, GameStatistics::dateInstalled, GameMetadata::description, GameMetadata::developer, GameMetadata::dlc, CloudSaveInfo::enabled, GameMetadata::genres, GameImagePaths::header, GameImagePaths::heroImage, GameImagePaths::icon, Game::id, GameMetadata::imagePaths, Game::installPath, Game::installSizeBytes, Game::isFavorite, jsonArrayFromStrings(), jsonFromEnvVars(), GameStatistics::lastEnvironmentVars, GameStatistics::lastExitReason, GameStatistics::lastExitTime, GameStatistics::lastLaunchCommand, GameStatistics::lastPlayed, GameStatistics::lastProtonVersion, CloudSaveInfo::lastSyncState, CloudSaveInfo::lastSyncTime, GameImagePaths::logo, Game::metadata, Game::name, GameMetadata::protondbConfidence, GameMetadata::protondbLastUpdated, GameMetadata::protondbScore, GameMetadata::protondbTier, GameMetadata::publisher, GameMetadata::releaseYear, Game::runner, Game::runnerConfig, Game::serializeRunnerConfig(), Game::source, Game::statistics, Game::status, GameMetadata::steamAppId, GameMetadata::steamBuildId, GameMetadata::steamBytesDownloaded, GameMetadata::steamBytesToDownload, GameMetadata::steamCategories, GameMetadata::steamInstalled, GameMetadata::steamIsDownloading, GameMetadata::steamIsUpdatePending, GameMetadata::steamLastExit, GameMetadata::steamLastLaunch, GameMetadata::steamLaunchOptions, GameMetadata::steamPlaytime2Weeks, GameMetadata::steamStateFlags, GameMetadata::steamType, GameMetadata::steamUserCategories, CloudSaveInfo::storageBytes, CloudSaveInfo::supported, GameMetadata::tags, GameStatistics::timesLaunched, GameStatistics::totalPlayTimeSeconds, GameMetadata::userRating, and GameImagePaths::verticalCover.

◆ isOpen()

bool GameDatabase::isOpen ( ) const

Check if database is open.

Definition at line 720 of file game_database.cpp.

◆ lastError()

std::string GameDatabase::lastError ( ) const

Get last error message.

Definition at line 726 of file game_database.cpp.

◆ open()

bool GameDatabase::open ( const std::string & path)

Open or create the database.

Parameters
pathPath to the database file
Returns
true on success, false on failure (check lastError())

Creates the database and tables if they don't exist. Runs any pending schema migrations.

Definition at line 498 of file game_database.cpp.

References close(), Logger::info(), open(), and Logger::warn().

Referenced by open().

◆ operator=() [1/2]

GameDatabase & GameDatabase::operator= ( const GameDatabase & )
delete

References GameDatabase().

◆ operator=() [2/2]

GameDatabase & GameDatabase::operator= ( GameDatabase && other)
noexcept

Definition at line 476 of file game_database.cpp.

References GameDatabase(), and close().

◆ queryGames()

std::vector< Game > GameDatabase::queryGames ( const DatabaseFilterOptions & filter = {},
const DatabaseSortOptions & sort = {},
int limit = 0,
int offset = 0 ) const

Query games with filtering and sorting.

Parameters
filterFilter options
sortSort options
limitMaximum results (0 = no limit)
offsetSkip first N results
Returns
Vector of matching games

Definition at line 1309 of file game_database.cpp.

◆ recordLaunch()

bool GameDatabase::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).

Parameters
gameIdGame ID
successWhether launch succeeded
runnerRunner used
protonVersionProton version (if applicable)
errorMessageError message if failed
timeToLaunchMsTime taken to launch in milliseconds
Returns
true on success

Definition at line 2716 of file game_database.cpp.

◆ removeCollection()

bool GameDatabase::removeCollection ( const std::string & name)

Remove a collection.

Parameters
nameCollection name
Returns
true on success

Definition at line 1681 of file game_database.cpp.

◆ removeGameFromCollection()

bool GameDatabase::removeGameFromCollection ( const std::string & gameId,
const std::string & collection )

Remove game from collection.

Parameters
gameIdGame ID
collectionCollection name
Returns
true on success

Definition at line 1754 of file game_database.cpp.

◆ rollbackTransaction()

bool GameDatabase::rollbackTransaction ( )

Rollback current transaction.

Returns
true on success

Definition at line 2105 of file game_database.cpp.

◆ searchGames()

std::vector< Game > GameDatabase::searchGames ( const std::string & query,
int limit = 50 ) const

Search games by name (uses FTS if available).

Parameters
querySearch query
limitMaximum results
Returns
Vector of matching games

Definition at line 1554 of file game_database.cpp.

◆ startSession()

int64_t GameDatabase::startSession ( const std::string & gameId,
GameRunner runner,
const std::string & protonVersion = "" )

◆ updateDailyPlaytime()

bool GameDatabase::updateDailyPlaytime ( const std::string & gameId,
int playTimeSeconds )

Update daily playtime aggregation.

Parameters
gameIdGame ID
playTimeSecondsPlaytime to add
Returns
true on success

Definition at line 2775 of file game_database.cpp.

◆ updateGame()

bool GameDatabase::updateGame ( const Game & game)

Update an existing game.

Parameters
gameGame with updated data (matched by id)
Returns
true on success

Definition at line 924 of file game_database.cpp.

◆ updateGameImages()

bool GameDatabase::updateGameImages ( const std::string & gameId,
const GameImagePaths & images )

Update only the image paths for a game (efficient partial update).

Parameters
gameIdID of game to update
imagesNew image paths to set
Returns
true on success

Definition at line 1156 of file game_database.cpp.

References Game::id.

◆ vacuum()

bool GameDatabase::vacuum ( )

Vacuum database to reclaim space.

Returns
true on success

Definition at line 2021 of file game_database.cpp.

◆ withTransaction()

bool GameDatabase::withTransaction ( const std::function< bool()> & func)

Execute a function within a transaction.

Parameters
funcFunction to execute
Returns
true if function succeeded and transaction committed

Automatically rolls back on exception or if func returns false.

Definition at line 2111 of file game_database.cpp.


The documentation for this class was generated from the following files: