smarter updates

This commit is contained in:
Yanick Champoux 2024-02-04 17:54:10 -05:00
parent 3b7c70ee4e
commit d04e431169
2 changed files with 44 additions and 7 deletions

View File

@ -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)', '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 await db
.prepare('DELETE FROM game where username = @username') .prepare(
.run({ username }); `DELETE FROM game where username = @username AND bgg_id not in (${already_there})`,
)
.run({
username,
});
for (let game of games) { for (let game of games) {
insert.run({ console.log(game.name);
username, const existing_game = game_present.get(username, game.bgg_id);
updated_at, if (existing_game) {
...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,
});
}
} }
} }

View File

@ -6,6 +6,7 @@ const users = db.prepare('SELECT username from bgg_user').all();
await Promise.all( await Promise.all(
users.map(({ username }) => { users.map(({ username }) => {
console.log(username);
return update_user_games(db, username) return update_user_games(db, username)
.then(() => console.log(username, 'is done')) .then(() => console.log(username, 'is done'))
.catch((e) => console.error(e)); .catch((e) => console.error(e));