From d04e4311699b10a7ef6108a246d5b4d25e51b31e Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Sun, 4 Feb 2024 17:54:10 -0500 Subject: [PATCH] smarter updates --- src/fetchCollection.js | 50 ++++++++++++++++++++++++++++++++------ src/scripts/updateUsers.js | 1 + 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/fetchCollection.js b/src/fetchCollection.js index 237e577..a944c22 100644 --- a/src/fetchCollection.js +++ b/src/fetchCollection.js @@ -77,15 +77,51 @@ export async function update_user_games(db, username) { 'INSERT into game (username, bgg_id, name, thumbnail, notes,price,updated_at) VALUES(@username,@bgg_id,@name,@thumbnail,@notes,@price,@updated_at)', ); + const update = db.prepare( + 'UPDATE game set notes=@notes, price=@price, updated_at=@updated_at where username=@username and bgg_id=@bgg_id', + ); + + const game_present = db.prepare( + 'SELECT notes, price from game where username = ? AND bgg_id = ?', + ); + + const already_there = games + .map(({ bgg_id }) => bgg_id) + .map((id) => `'${id}'`) + .join(','); await db - .prepare('DELETE FROM game where username = @username') - .run({ username }); + .prepare( + `DELETE FROM game where username = @username AND bgg_id not in (${already_there})`, + ) + .run({ + username, + }); for (let game of games) { - insert.run({ - username, - updated_at, - ...game, - }); + console.log(game.name); + const existing_game = game_present.get(username, game.bgg_id); + if (existing_game) { + if ( + ['notes', 'price'].some( + (attr) => existing_game[attr] != game[attr], + ) + ) { + console.log('updating game'); + update.run({ + ...game, + updated_at, + username, + }); + } else { + console.log("didn't change"); + } + } else { + console.log('new game!'); + insert.run({ + username, + updated_at, + ...game, + }); + } } } diff --git a/src/scripts/updateUsers.js b/src/scripts/updateUsers.js index 7a05fb2..994d093 100644 --- a/src/scripts/updateUsers.js +++ b/src/scripts/updateUsers.js @@ -6,6 +6,7 @@ const users = db.prepare('SELECT username from bgg_user').all(); await Promise.all( users.map(({ username }) => { + console.log(username); return update_user_games(db, username) .then(() => console.log(username, 'is done')) .catch((e) => console.error(e));