Skip to content

Commit

Permalink
Change TournamentCreator and MatchScheduler to use async database que…
Browse files Browse the repository at this point in the history
…ries
  • Loading branch information
axunonb committed Jan 23, 2024
1 parent 284fe6b commit 316e2d8
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 51 deletions.
33 changes: 17 additions & 16 deletions TournamentManager/TournamentManager/Data/MatchRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,13 @@ public virtual async Task<int> GetMatchCountAsync(PredicateExpression filter, Ca
/// of the tournament rounds.
/// </summary>
/// <returns>Returns true if matches were found, else false.</returns>
public virtual bool AnyCompleteMatchesExist(long tournamentId)
public virtual async Task<bool> AnyCompleteMatchesExistAsync(long tournamentId, CancellationToken cancellationToken)
{
using var da = _dbContext.GetNewAdapter();
var metaData = new LinqMetaData(da);
if ((from matchEntity in metaData.Match
if ((await (from matchEntity in metaData.Match
where matchEntity.Round.TournamentId == tournamentId && matchEntity.IsComplete
select matchEntity.Id).AsEnumerable().Any())
select matchEntity.Id).Take(1).ToListAsync(cancellationToken)).Count == 0)
{
da.CloseConnection();
return true;
Expand All @@ -300,14 +300,15 @@ public virtual bool AnyCompleteMatchesExist(long tournamentId)
/// a tournament round.
/// </summary>
/// <param name="round">RoundEntity (only Id will be used)</param>
/// <param name="cancellationToken"></param>
/// <returns>Returns true if matches were found, else false.</returns>
public virtual bool AnyCompleteMatchesExist(RoundEntity round)
public virtual async Task<bool> AnyCompleteMatchesExistAsync(RoundEntity round, CancellationToken cancellationToken)
{
using var da = _dbContext.GetNewAdapter();
var metaData = new LinqMetaData(da);
if ((from matchEntity in metaData.Match
if ((await (from matchEntity in metaData.Match
where matchEntity.Round.Id == round.Id && matchEntity.IsComplete
select matchEntity.Id).AsEnumerable().Any())
select matchEntity.Id).Take(1).ToListAsync(cancellationToken)).Count != 0)
{
da.CloseConnection();
return true;
Expand All @@ -322,44 +323,44 @@ public virtual bool AnyCompleteMatchesExist(RoundEntity round)
/// Find out whether all matches of a tournament with a given Id are completed
/// </summary>
/// <returns>Returns true if all matches are completed, else false.</returns>
public virtual bool AllMatchesCompleted(TournamentEntity tournament)
public virtual async Task<bool> AllMatchesCompletedAsync(TournamentEntity tournament, CancellationToken cancellationToken)
{
using var da = _dbContext.GetNewAdapter();
var metaData = new LinqMetaData(da);

if ((from matchEntity in metaData.Match
if ((await (from matchEntity in metaData.Match
where matchEntity.Round.TournamentId == tournament.Id && !matchEntity.IsComplete
select matchEntity.Id).AsEnumerable().Any())
select matchEntity.Id).Take(1).ToListAsync(cancellationToken)).Count == 0)
{
da.CloseConnection();
return false;
return true;
}

da.CloseConnection();

return true;
return false;
}

/// <summary>
/// Find out whether all matches of a round with a gived Id are completed
/// </summary>
/// <returns>Returns true if all matches are completed, else false.</returns>
public virtual bool AllMatchesCompleted(RoundEntity round)
public virtual async Task<bool> AllMatchesCompletedAsync(RoundEntity round, CancellationToken cancellationToken)
{
using var da = _dbContext.GetNewAdapter();
var metaData = new LinqMetaData(da);

if ((from matchEntity in metaData.Match
if (( await (from matchEntity in metaData.Match
where matchEntity.Round.Id == round.Id && !matchEntity.IsComplete
select matchEntity.Id).AsEnumerable().Any())
select matchEntity.Id).Take(1).ToListAsync(cancellationToken)).Count == 0)
{
da.CloseConnection();
return false;
return true;
}

da.CloseConnection();

return true;
return false;
}

/// <summary>
Expand Down
22 changes: 5 additions & 17 deletions TournamentManager/TournamentManager/Data/RoundRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,10 @@ public virtual async Task<List<RoundLegPeriodRow>> GetRoundLegPeriodAsync(IPredi
public virtual async Task<RoundEntity?> GetRoundWithLegsAsync(long roundId, CancellationToken cancellationToken)
{
using var da = _dbContext.GetNewAdapter();
var result = (await da.FetchQueryAsync(
new QueryFactory().Round.Where(RoundFields.Id == roundId)
.WithPath(RoundEntity.PrefetchPathRoundLegs), cancellationToken)).Cast<RoundEntity>().ToList();
return result.FirstOrDefault();
}

public virtual RoundEntity GetRoundWithLegs(long roundId)
{
var round = new RoundEntity(roundId);
IPrefetchPath2 prefetchPathRoundLegs = new PrefetchPath2(EntityType.RoundEntity)
{
RoundEntity.PrefetchPathRoundLegs
};

using var da = _dbContext.GetNewAdapter();
da.FetchEntity(round, prefetchPathRoundLegs);
var metaData = new LinqMetaData(da);
var round = await metaData.Round.Where(r => r.Id == roundId)
.WithPath(new PathEdge<RoundEntity>(RoundEntity.PrefetchPathRoundLegs))
.FirstOrDefaultAsync(cancellationToken);
da.CloseConnection();
return round;
}
Expand Down Expand Up @@ -99,4 +87,4 @@ public virtual async Task<List<RoundEntity>> GetRoundsWithTypeAsync(PredicateExp
return ((EntityCollection<RoundEntity>) await da.FetchQueryAsync<RoundEntity>(
new QueryFactory().Round.WithPath(RoundEntity.PrefetchPathRoundType).Where(filter), cancellationToken)).ToList();
}
}
}
4 changes: 2 additions & 2 deletions TournamentManager/TournamentManager/Plan/MatchScheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task ScheduleFixturesForTournament(bool keepExisting, CancellationT
{
await LoadEntitiesAsync(cancellationToken);

if (_appDb.MatchRepository.AnyCompleteMatchesExist(_tenantContext.TournamentContext.MatchPlanTournamentId))
if (await _appDb.MatchRepository.AnyCompleteMatchesExistAsync(_tenantContext.TournamentContext.MatchPlanTournamentId, cancellationToken))
throw new InvalidOperationException("Completed matches exist for this tournament. Generating fixtures aborted.");

foreach (var round in _tournament.Rounds)
Expand All @@ -79,7 +79,7 @@ public async Task ScheduleFixturesForRound(RoundEntity round, bool keepExisting,
{
await LoadEntitiesAsync(cancellationToken);

if (_appDb.MatchRepository.AnyCompleteMatchesExist(round))
if (await _appDb.MatchRepository.AnyCompleteMatchesExistAsync(round, cancellationToken))
throw new InvalidOperationException($"Completed matches exist for round '{round.Id}'. Generating fixtures aborted.");

// We load all tournament matches, so that we can check for venues occupied by existing matches in memory.
Expand Down
36 changes: 20 additions & 16 deletions TournamentManager/TournamentManager/TournamentCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ public static TournamentCreator Instance(IAppDb appDb)
/// not exist. For start and end date of leg data 1 year is added.
/// </summary>
/// <param name="fromTournamentId">Existing source tournament id.</param>
/// <param name="cancellationToken"></param>
/// <returns>True, if creation was successful, false otherwise.</returns>
public async Task<bool> CopyTournament (long fromTournamentId)
public async Task<bool> CopyTournament (long fromTournamentId, CancellationToken cancellationToken)
{
var now = DateTime.UtcNow;
var tournament =
Expand Down Expand Up @@ -80,8 +81,9 @@ await _appDb.TournamentRepository.GetTournamentAsync(
/// <param name="fromTournamentId">Existing source tournament id.</param>
/// <param name="toTournamentId">Existing target tournament id.</param>
/// <param name="excludeRoundId">List of round id's to be excluded (empty list for 'none')</param>
/// <param name="cancellationToken"></param>
/// <returns>True, if creation was successful, false otherwise.</returns>
public bool CopyRound(long fromTournamentId, long toTournamentId, IList<long> excludeRoundId)
public async Task<bool> CopyRound(long fromTournamentId, long toTournamentId, IList<long> excludeRoundId, CancellationToken cancellationToken)
{
const string transactionName = "CloneRounds";
var now = DateTime.UtcNow;
Expand All @@ -94,7 +96,8 @@ public bool CopyRound(long fromTournamentId, long toTournamentId, IList<long> ex
var roundsWithLegs = new Queue<RoundEntity>();
foreach (var r in roundIds)
{
roundsWithLegs.Enqueue(_appDb.RoundRepository.GetRoundWithLegs(r));
var round = await _appDb.RoundRepository.GetRoundWithLegsAsync(r, cancellationToken);
if (round != null) roundsWithLegs.Enqueue(round);
}

foreach (var r in roundIds)
Expand Down Expand Up @@ -137,7 +140,7 @@ public bool CopyRound(long fromTournamentId, long toTournamentId, IList<long> ex
}

// save recursively (new round with the new round legs)
if (! da.SaveEntity(newRound, true, true))
if (! await da.SaveEntityAsync(newRound, true, true, cancellationToken))
{
// roll back if any round fails
da.Rollback(transactionName);
Expand All @@ -146,11 +149,11 @@ public bool CopyRound(long fromTournamentId, long toTournamentId, IList<long> ex
}

// commit only after all rounds are processed successfully
da.Commit();
await da.CommitAsync(cancellationToken);
return true;
}

public bool SetLegDates(IEnumerable<RoundEntity> rounds , int sequenceNo, DateTime start, DateTime end)
public async Task<bool> SetLegDates(IEnumerable<RoundEntity> rounds , int sequenceNo, DateTime start, DateTime end, CancellationToken cancellationToken)
{
//const string transactionName = "SetLegDates";
var now = DateTime.UtcNow;
Expand All @@ -164,7 +167,7 @@ public bool SetLegDates(IEnumerable<RoundEntity> rounds , int sequenceNo, DateTi
roundEntities.Clear();
foreach (var rid in roundIds)
{
roundEntities.Add(_appDb.RoundRepository.GetRoundWithLegs(rid));
roundEntities.Add((await _appDb.RoundRepository.GetRoundWithLegsAsync(rid, cancellationToken))!);
}

var tournamentId = roundEntities.First().TournamentId;
Expand All @@ -182,14 +185,14 @@ public bool SetLegDates(IEnumerable<RoundEntity> rounds , int sequenceNo, DateTi
leg.EndDateTime = end;
leg.ModifiedOn = now;

if (!da.SaveEntity(leg, false, false))
if (!await da.SaveEntityAsync(leg, false, false, cancellationToken))
{
da.Rollback();
return false;
}
}
}
//da.Commit();
//await da.CommitAsync(cancellationToken);

return true;
}
Expand All @@ -198,10 +201,11 @@ public bool SetLegDates(IEnumerable<RoundEntity> rounds , int sequenceNo, DateTi
/// If all matches of a tournament are completed, the rounds and the tournament are set to &quot;completed&quot;.
/// </summary>
/// <param name="tournamentId">The Tournament to be set as &quot;completed&quot;</param>
/// <param name="cancellationToken"></param>
/// <exception cref="ArgumentException">Throws an exception if any match of the tournament is not completed yet.</exception>
public async Task SetTournamentCompleted(long tournamentId)
public async Task SetTournamentCompleted(long tournamentId, CancellationToken cancellationToken)
{
if (!new MatchRepository(_appDb.DbContext).AllMatchesCompleted(new TournamentEntity(tournamentId)))
if (!await (_appDb.MatchRepository.AllMatchesCompletedAsync(new TournamentEntity(tournamentId), cancellationToken)))
{
throw new ArgumentException($"Tournament {tournamentId} contains incomplete matches.");
}
Expand All @@ -211,29 +215,29 @@ public async Task SetTournamentCompleted(long tournamentId)

foreach (var round in tournament.Rounds)
{
SetRoundCompleted(round);
await SetRoundCompleted(round, cancellationToken);
}

tournament.IsComplete = true;
tournament.ModifiedOn = now;

using var da = _appDb.DbContext.GetNewAdapter();
if (!await da.SaveEntityAsync(tournament))
if (!await da.SaveEntityAsync(tournament, cancellationToken))
{
throw new ArgumentException($"Tournament Id {tournamentId} could not be saved to persistent storage.");
}
}

public virtual void SetRoundCompleted(RoundEntity round)
public virtual async Task SetRoundCompleted(RoundEntity round, CancellationToken cancellationToken)
{
if (!new MatchRepository(_appDb.DbContext).AllMatchesCompleted(round))
if (!await (_appDb.MatchRepository.AllMatchesCompletedAsync(round, cancellationToken)))
throw new ArgumentException($"Round {round.Id} has uncompleted matches.");

using var da = _appDb.DbContext.GetNewAdapter();
da.FetchEntity(round);
round.IsComplete = true;
round.ModifiedOn = DateTime.UtcNow;
da.SaveEntity(round);
await da.SaveEntityAsync(round, cancellationToken);
da.CloseConnection();
}
}

0 comments on commit 316e2d8

Please sign in to comment.