Added methods for inserting games and groups into the db

This commit is contained in:
2025-11-12 12:04:33 +01:00
parent b6700bafd9
commit d07943add9
5 changed files with 58 additions and 5 deletions

View File

@@ -41,6 +41,27 @@ class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
);
}
Future<void> addGame(Game game) async {
await db.transaction(() async {
for (final p in game.players ?? []) {
await db.playerDao.addPlayer(p);
await db.playerGameDao.addPlayerToGame(game.id, p.id);
}
if (game.group != null) {
await db.groupDao.addGroup(game.group!);
await db.groupGameDao.addGroupToGame(game.id, game.group!.id);
}
await into(gameTable).insert(
GameTableCompanion.insert(
id: game.id,
name: game.name,
winnerId: Value(game.winner),
),
mode: InsertMode.insertOrReplace,
);
});
}
/// Retrieves the number of games in the database.
Future<int> getGameCount() async {
final count =

View File

@@ -32,11 +32,26 @@ class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
}
/// Adds a new group with the given [id] and [name] to the database.
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<void> addGroup(String id, String name) async {
await into(
groupTable,
).insert(GroupTableCompanion.insert(id: id, name: name));
/// This method also adds the group's members to the [PlayerGroupTable].
Future<void> addGroup(Group group) async {
await db.transaction(() async {
await into(
groupTable,
).insert(GroupTableCompanion.insert(id: group.id, name: group.name));
await db.batch(
(b) => b.insertAll(
db.playerGroupTable,
group.members
.map(
(member) => PlayerGroupTableCompanion.insert(
playerId: member.id,
groupId: group.id,
),
)
.toList(),
),
);
});
}
/// Deletes the group with the given [id] from the database.

View File

@@ -30,4 +30,12 @@ class GroupGameDao extends DatabaseAccessor<AppDatabase>
final group = await db.groupDao.getGroupById(result.groupId);
return group;
}
/// Associates a group with a game by inserting a record into the
/// [GroupGameTable].
Future<void> addGroupToGame(String gameId, String groupId) async {
await into(
groupGameTable,
).insert(GroupGameTableCompanion.insert(groupId: groupId, gameId: gameId));
}
}

View File

@@ -37,4 +37,12 @@ class PlayerGameDao extends DatabaseAccessor<AppDatabase>
final players = await Future.wait(futures);
return players.whereType<Player>().toList();
}
/// Associates a player with a game by inserting a record into the
/// [PlayerGameTable].
Future<void> addPlayerToGame(String gameId, String playerId) async {
await into(playerGameTable).insert(
PlayerGameTableCompanion.insert(playerId: playerId, gameId: gameId),
);
}
}

View File

@@ -3,6 +3,7 @@ import 'package:drift/drift.dart';
class GameTable extends Table {
TextColumn get id => text()();
TextColumn get name => text()();
// todo: winner id needs to be deleted when corresponding player gets deleted
TextColumn get winnerId => text().nullable()();
@override