import Database from 'better-sqlite3'; import path from 'path'; const DB_PATH = 'database.db'; //path.join(__dirname, '../../../', 'release/app', 'database.db'), let isInit = false; export type Game = { id?: number; game_id: number; title: string; formatted_title: string; path: string; img_cover: string; img_background: string; is_running: number; }; function initDB() { if (!isInit) { createDB(DB_PATH); isInit = true; } } function createDB(pathToDB) { let db = Database( pathToDB, { fileMustExist: false }, ); setupTable(db); } function setupTable(db) { db.exec( `CREATE TABLE IF NOT EXISTS "games" ( "id" INTEGER, "game_id" INTEGER, "title" TEXT, "formatted_title" TEXT, "path" TEXT, "img_cover" TEXT, "img_background" TEXT, "is_running" INTEGER, PRIMARY KEY("id" AUTOINCREMENT) )` ); } export function connect() { initDB(); return Database( DB_PATH, { fileMustExist: true }, ); } export function addGame(game: Game) { const db = connect(); const stm = db.prepare( `INSERT INTO games (game_id, title, formatted_title, path, img_cover, img_background, is_running) VALUES (@game_id, @title, @formatted_title, @path, @img_cover, @img_background, @is_running)`, ); stm.run(game); } export function updateGame(game: Game) { const db = connect(); const { game_id, title, formatted_title, path, img_cover, img_background, is_running } = game; const stm = db.prepare( 'UPDATE games SET game_id = @game_id, title = @title, formatted_title = @formatted_title, path = @path, img_cover = @img_cover, img_background = @img_background, is_running = @is_running, WHERE id = @id', ); stm.run({ game_id, title, formatted_title, path, img_cover, img_background, is_running }); } export function deleteGame(id: number) { const db = connect(); const stm = db.prepare('DELETE FROM games WHERE id = @id'); stm.run({ id }); } export function getAllGames() { const db = connect(); const stm = db.prepare('SELECT * FROM games'); return stm.all() as Game[]; } export function getGame(id: number) { const db = connect(); const stm = db.prepare('SELECT * FROM games where id = @id'); return stm.get({ id }) as Game; }