export { Database }; const initSqlJs = window.initSqlJs; const BASE_QUERY = "SELECT recipes.rowid AS id, recipes.name AS name, category, recipes.book, path, (page_offset + page) AS page, IIF(favorites.recipe_id IS NULL, FALSE, TRUE) AS is_favorite, IIF(tested.recipe_id IS NULL, FALSE, TRUE) AS is_tested, IIF(excluded.recipe_id IS NULL, FALSE, TRUE) AS is_excluded FROM recipes LEFT JOIN favorites ON (recipes.rowid == favorites.recipe_id) LEFT JOIN tested ON (recipes.rowid == tested.recipe_id) LEFT JOIN excluded ON (recipes.rowid == excluded.recipe_id) JOIN books ON recipes.book = books.name WHERE page != '' AND is_actually_in_book = 1"; class Database { constructor() { this.baseDBPath = "/_base.db"; this.userDBPathPrefix = "/user/db/"; } async init() { const sqlPromise = initSqlJs({ locateFile: (file) => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.12.0/${file}`, }); const bufPromise = fetch(this.baseDBPath).then((res) => res.arrayBuffer()); const [SQL, buf] = await Promise.all([sqlPromise, bufPromise]); this.SQL = SQL; this.baseDB = new this.SQL.Database(new Uint8Array(buf)); } async login(username) { const buf = await fetch(`${this.userDBPathPrefix}${username}.db`).then((res) => res.arrayBuffer()); this.DB = new this.SQL.Database(new Uint8Array(buf)); this.DB.exec(`ATTACH DATABASE "${this.baseDB.filename}" AS _base;`); } search(resultCallback, term, favorite = false, tested = false, excluded = false) { let query = BASE_QUERY; if (favorite) { query += " AND is_favorite = TRUE"; } if (tested) { query += " AND is_tested = TRUE"; } if (!excluded) { query += " AND is_excluded = FALSE"; } if (term) { query += " AND recipes.name LIKE $term"; this.DB.each(query, { $term: term + "%" }, resultCallback); this.DB.each(query, { $term: "%" + term + "%" }, resultCallback); } else { this.DB.each(query, {}, resultCallback); } } getRecipe(id) { const stmt = this.DB.prepare(BASE_QUERY + " AND recipes.rowid = $id"); return stmt.getAsObject({ $id: id }); } async setAttribute(username, id, attribute, state = true) { if (username === "guest") { console.log("Not updating anything: logged in as guest"); return; } let url = "/update.php?id=" + id + "&username=" + encodeURI(username) + "&attr=" + encodeURI(attribute); if (!state) url = url + "&remove"; const response = await fetch(url); if (!response.ok) { throw new Error(`Response status: ${response.status}`); } if (!state) { this.DB.run("DELETE FROM " + attribute + " WHERE recipe_id = $recipeId", { $recipeId: id }); } else { this.DB.run("INSERT INTO " + attribute + "(recipe_id) VALUES ($recipeId)", { $recipeId: id }); } } async setFavorite(username, id, state = true) { this.setAttribute(username, id, "favorites", state); } async setTested(username, id, state = true) { this.setAttribute(username, id, "tested", state); } async setExcluded(username, id, state = true) { this.setAttribute(username, id, "excluded", state); } }