Adopts the persistence toolkit across the repositories

This commit is contained in:
BinaryAlley committed 2026-09-27 21:20:51 +03:00
1 parent a632f4ced7
commit cd1386b9e7
15 files changed
+313 -227

No files matched your search

@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Primitives;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
/// <summary>
/// Interface defining the "apply update" action for interacting with a generic persistence medium.
/// </summary>
/// <typeparam name="TModel">The type used for the apply update action. It should implement <see cref="IStorageEntity"/>.</typeparam>
public interface IApplyUpdateRepositoryAction<TModel> where TModel : IStorageEntity
{
/// <summary>
/// Applies the editable values of <paramref name="data"/> onto the already tracked <paramref name="tracked"/> model, without loading it again.
/// </summary>
/// <param name="tracked">The tracked model whose editable values are updated.</param>
/// <param name="data">The model carrying the desired values.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ApplyUpdateAsync(TModel tracked, TModel data, CancellationToken cancellationToken);
}
@@ -19,6 +19,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
public interface IAlbumRepository : IRepository<AlbumEntity>,
IInsertRepositoryAction<AlbumEntity>,
IUpdateRepositoryAction<AlbumEntity>,
IApplyUpdateRepositoryAction<AlbumEntity>,
IGetByIdRepositoryAction<AlbumEntity, Guid>
{
/// <summary>
@@ -19,6 +19,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
public interface ITrackRepository : IRepository<TrackEntity>,
IInsertRepositoryAction<TrackEntity>,
IUpdateRepositoryAction<TrackEntity>,
IApplyUpdateRepositoryAction<TrackEntity>,
IGetByIdRepositoryAction<TrackEntity, Guid>
{
/// <summary>
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
@@ -114,6 +115,7 @@ internal sealed class RoleRepository : IRoleRepository
return await _luminaDbContext.Roles
.Include(role => role.RolePermissions)
.ThenInclude(library => library.Permission)
.AsSplitQuery()
.FirstOrDefaultAsync(role => role.RoleName == roleType, cancellationToken)
.ConfigureAwait(false);
}
@@ -131,11 +133,10 @@ internal sealed class RoleRepository : IRoleRepository
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission);
}
.ThenInclude(rolePermission => rolePermission.Permission)
.AsSplitQuery();
return await query.FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -151,17 +152,29 @@ internal sealed class RoleRepository : IRoleRepository
RoleEntity? foundRole = await _luminaDbContext.Roles
.Include(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.AsSplitQuery()
.FirstOrDefaultAsync(role => role.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundRole is null)
return Errors.Authorization.RoleNotFound;
// Update the scalar properties.
_luminaDbContext.Entry(foundRole).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundRole, data);
// Update the owned entities, whose changes are not tracked by EF automatically.
foundRole.RolePermissions.Clear();
foreach (RolePermissionEntity rolePermission in data.RolePermissions)
foundRole.RolePermissions.Add(rolePermission);
// A permission participation is matched by its permission. Matched participations keep their identity and their audit columns, so a permission
// that is referenced elsewhere is never deleted and re-inserted just because another field of the role was edited.
CollectionReconciler.Reconcile(
foundRole.RolePermissions,
data.RolePermissions,
existingRolePermission => existingRolePermission.PermissionId,
incomingRolePermission => incomingRolePermission.PermissionId,
shouldReplace: (existingRolePermission, incomingRolePermission) => false,
createNew: incomingRolePermission => new RolePermissionEntity
{
RoleId = foundRole.Id,
PermissionId = incomingRolePermission.PermissionId,
Permission = incomingRolePermission.Permission,
Role = foundRole
});
return Result.Updated;
}
@@ -65,18 +65,16 @@ internal sealed class BookRepository : IBookRepository
if (doesBookPathExist)
return Errors.WrittenContent.BookAlreadyExists;
// Fetch existing tags and genres.
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Resolve the tags and genres of the book to a single instance per name, replacing the stored ones where they exist, so that the shared tables are not duplicated.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Replace tags and genres in the book with existing ones.
book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
book.Tags = [.. SharedReferenceResolver.Normalize(book.Tags, resolveTagsResult.Value)];
book.Genres = [.. SharedReferenceResolver.Normalize(book.Genres, resolveGenresResult.Value)];
_luminaDbContext.Books.Add(book);
return Result.Created;
@@ -215,7 +213,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.Include(book => book.Artwork);
.Include(book => book.Artwork)
.AsSplitQuery();
}
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
@@ -503,6 +502,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.AsSplitQuery()
.FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
@@ -521,7 +521,13 @@ internal sealed class BookRepository : IBookRepository
foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc;
foundBook.MetadataProvider = metadataProvider;
await ReconcileTagsAndGenresAsync(foundBook, data, cancellationToken).ConfigureAwait(false);
// Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundBook.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileTagsResult.IsFailure)
return reconcileTagsResult.Errors;
Result<Updated> reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundBook.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileGenresResult.IsFailure)
return reconcileGenresResult.Errors;
// ISBNs are owned value objects with no identity anyone could reference, so an ISBN whose format changed is replaced as a whole, while the ones that did not
// change are left exactly as they are stored. Matching by the ISBN value keeps an update in place instead of recreating every ISBN of the book.
@@ -556,41 +562,6 @@ internal sealed class BookRepository : IBookRepository
return Result.Updated;
}
/// <summary>
/// Reconciles the tags and genres of <paramref name="foundBook"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
/// </summary>
/// <param name="foundBook">The tracked book whose tags and genres are reconciled.</param>
/// <param name="data">The book carrying the desired tags and genres.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task ReconcileTagsAndGenresAsync(BookEntity foundBook, BookEntity data, CancellationToken cancellationToken)
{
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
CollectionReconciler.Reconcile(
foundBook.Tags,
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
CollectionReconciler.Reconcile(
foundBook.Genres,
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
existingGenre => existingGenre.Name!,
incomingGenre => incomingGenre.Name!,
shouldReplace: (existingGenre, incomingGenre) => false,
createNew: incomingGenre => incomingGenre);
}
/// <summary>
/// Sorts a books query by the given field name, defaulting to <see cref="BookEntity.Title"/>.
/// </summary>
@@ -600,7 +571,7 @@ internal sealed class BookRepository : IBookRepository
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.</param>
private static IOrderedQueryable<BookEntity> ApplySorting(IQueryable<BookEntity> booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker)
{
return sortBy?.ToLower() switch
return sortBy?.ToLowerInvariant() switch
{
"languagecode" => sortOrder == SortOrder.Descending
? booksQuery.OrderByDescending(book => book.LanguageCode)
@@ -62,10 +62,9 @@ internal sealed class LibraryRepository : ILibraryRepository
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(library => library.ContentLocations);
}
.Include(library => library.ContentLocations)
.AsSplitQuery();
return await query.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -78,6 +77,7 @@ internal sealed class LibraryRepository : ILibraryRepository
{
return await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.AsSplitQuery()
.Where(library => library.IsEnabled)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -91,6 +91,7 @@ internal sealed class LibraryRepository : ILibraryRepository
{
return await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.AsSplitQuery()
.Where(library => library.IsEnabled && !library.IsLocked)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -113,10 +114,9 @@ internal sealed class LibraryRepository : ILibraryRepository
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(library => library.ContentLocations);
}
.Include(library => library.ContentLocations)
.AsSplitQuery();
// If no pagination was requested, return all the media libraries.
if (paginationData is null)
@@ -161,6 +161,7 @@ internal sealed class LibraryRepository : ILibraryRepository
{
LibraryEntity? foundLibrary = await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.AsSplitQuery()
.FirstOrDefaultAsync(library => library.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundLibrary is null)
return Errors.Library.LibraryNotFound;
@@ -191,6 +192,7 @@ internal sealed class LibraryRepository : ILibraryRepository
{
LibraryEntity? library = await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.AsSplitQuery()
.FirstOrDefaultAsync(library => library.Id == id, cancellationToken)
.ConfigureAwait(false);
@@ -2,6 +2,7 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
@@ -60,11 +61,10 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(libraryScan => libraryScan.Library)
.Include(libraryScan => libraryScan.User);
}
.Include(libraryScan => libraryScan.User)
.AsSplitQuery();
return await query.FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -77,6 +77,7 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
{
return await _luminaDbContext.LibraryScans
.Include(library => library.Library)
.AsSplitQuery()
.Where(library => library.LibraryId == libraryId && library.CreatedOnUtc >= DateTime.UtcNow.AddMonths(-1))
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -90,6 +91,7 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
{
return await _luminaDbContext.LibraryScans
.Include(library => library.Library)
.AsSplitQuery()
.Where(library => library.Status == LibraryScanJobStatus.Running)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -104,11 +106,12 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
{
LibraryScanEntity? foundLibraryScan = await _luminaDbContext.LibraryScans
.Include(libraryScan => libraryScan.Library)
.AsSplitQuery()
.FirstOrDefaultAsync(libraryScan => libraryScan.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundLibraryScan is null)
return Errors.LibraryScanning.LibraryScanNotFound;
// Update scalar properties.
_luminaDbContext.Entry(foundLibraryScan).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibraryScan, data);
return Result.Updated;
}
}
@@ -55,29 +55,24 @@ internal sealed class AlbumRepository : IAlbumRepository
if (checkTrackPathsResult.IsFailure)
return checkTrackPathsResult.Errors;
// Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated.
List<string> tagNames = [.. album.Tags.Select(tag => tag.Name!)
.Concat(album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!)))
.Distinct()];
List<string> genreNames = [.. album.Genres.Select(genre => genre.Name!)
.Concat(album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!)))
.Distinct()];
// Resolve the tags and genres referenced by the album and its tracks to a single instance per name, replacing the stored ones where they exist, so that
// neither a stored row nor a name shared by the album and its tracks of the same request is tracked more than once.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext, album.Tags.Concat(album.Tracks.SelectMany(track => track.Tags)), Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext, album.Genres.Concat(album.Tracks.SelectMany(track => track.Genres)), Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Replace the tags and genres of the album and of its tracks with the existing ones, so that the shared tables are not duplicated.
album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)];
album.Genres = [.. SharedReferenceResolver.Normalize(album.Genres, resolveGenresResult.Value)];
foreach (TrackEntity track in album.Tracks)
{
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)];
track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)];
}
_luminaDbContext.Albums.Add(album);
@@ -116,15 +111,30 @@ internal sealed class AlbumRepository : IAlbumRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(AlbumEntity data, CancellationToken cancellationToken)
{
// Every collection that is reconciled must be loaded, so that the reconciliation can see the rows that are already stored and leave the unchanged ones alone.
AlbumEntity? foundAlbum = await _luminaDbContext.Albums
.Include(repositoryAlbum => repositoryAlbum.Tags)
.Include(repositoryAlbum => repositoryAlbum.Genres)
.Include(repositoryAlbum => repositoryAlbum.Ratings)
.Include(repositoryAlbum => repositoryAlbum.Contributors)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundAlbum is null)
return Errors.Music.AlbumNotFound;
return await ApplyUpdateAsync(foundAlbum, data, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Applies the editable data of <paramref name="data"/> onto the already tracked <paramref name="foundAlbum"/>, without loading it, so that a caller that already
/// loaded the album graph, like the artist repository, does not make the album repository load it again.
/// </summary>
/// <param name="foundAlbum">The tracked album whose editable data is applied.</param>
/// <param name="data">The album carrying the desired data.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> ApplyUpdateAsync(AlbumEntity foundAlbum, AlbumEntity data, CancellationToken cancellationToken)
{
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
Guid artistId = foundAlbum.ArtistId;
Guid libraryId = foundAlbum.LibraryId;
@@ -132,7 +142,13 @@ internal sealed class AlbumRepository : IAlbumRepository
foundAlbum.ArtistId = artistId;
foundAlbum.LibraryId = libraryId;
await ReconcileTagsAndGenresAsync(foundAlbum, data, cancellationToken).ConfigureAwait(false);
// Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileTagsResult.IsFailure)
return reconcileTagsResult.Errors;
Result<Updated> reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileGenresResult.IsFailure)
return reconcileGenresResult.Errors;
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the album.
@@ -157,41 +173,6 @@ internal sealed class AlbumRepository : IAlbumRepository
return Result.Updated;
}
/// <summary>
/// Reconciles the tags and genres of <paramref name="foundAlbum"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
/// </summary>
/// <param name="foundAlbum">The tracked album whose tags and genres are reconciled.</param>
/// <param name="data">The album carrying the desired tags and genres.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task ReconcileTagsAndGenresAsync(AlbumEntity foundAlbum, AlbumEntity data, CancellationToken cancellationToken)
{
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
CollectionReconciler.Reconcile(
foundAlbum.Tags,
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
CollectionReconciler.Reconcile(
foundAlbum.Genres,
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
existingGenre => existingGenre.Name!,
incomingGenre => incomingGenre.Name!,
shouldReplace: (existingGenre, incomingGenre) => false,
createNew: incomingGenre => incomingGenre);
}
/// <summary>
/// Gets an album by its Id.
/// </summary>
@@ -5,7 +5,9 @@ using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -66,33 +68,33 @@ internal sealed class ArtistRepository : IArtistRepository
if (checkTrackPathsResult.IsFailure)
return checkTrackPathsResult.Errors;
// Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated.
List<string> tagNames = [.. artist.Albums
.SelectMany(album => album.Tags.Select(tag => tag.Name!))
.Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!))))
.Distinct()];
List<string> genreNames = [.. artist.Albums
.SelectMany(album => album.Genres.Select(genre => genre.Name!))
.Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!))))
.Distinct()];
// Resolve the tags and genres referenced anywhere in the aggregate to a single instance per name, replacing the stored ones where they exist, so that
// neither a stored row nor a name shared by several albums or tracks of the same request is tracked more than once.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
artist.Albums.SelectMany(album => album.Tags).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
Errors.Metadata.TagNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
artist.Albums.SelectMany(album => album.Genres).Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
Errors.Metadata.GenreNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
// Replace the tags and genres of every album and track of the aggregate with the existing ones, so that the shared tables are not duplicated.
foreach (AlbumEntity album in artist.Albums)
{
album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)];
album.Genres = [.. SharedReferenceResolver.Normalize(album.Genres, resolveGenresResult.Value)];
foreach (TrackEntity track in album.Tracks)
{
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)];
track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)];
}
}
@@ -108,10 +110,37 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(ArtistEntity data, CancellationToken cancellationToken)
{
// The whole aggregate is loaded once, including every collection that the album and track repositories reconcile, so that those repositories can apply the
// edit to the already tracked children instead of loading each album and each track again.
ArtistEntity? foundArtist = await _luminaDbContext.Artists
.Include(repositoryArtist => repositoryArtist.Contributors)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tags)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Genres)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Ratings)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Contributors)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Tags)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Genres)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Ratings)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Moods)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Isrcs)
.Include(repositoryArtist => repositoryArtist.Albums)
.ThenInclude(album => album.Tracks)
.ThenInclude(track => track.Contributors)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundArtist is null)
return Errors.Music.ArtistNotFound;
@@ -138,6 +167,35 @@ internal sealed class ArtistRepository : IArtistRepository
if (checkNewTrackPathsResult.IsFailure)
return checkNewTrackPathsResult.Errors;
// Normalize the tags and genres carried by the desired aggregate, so that a name shared by several albums or tracks is represented by a single instance,
// and a name that is already stored is reused, before the album and track repositories reconcile their own collections.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
data.Albums.SelectMany(album => album.Tags).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags))),
Errors.Metadata.TagNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(
_luminaDbContext,
data.Albums.SelectMany(album => album.Genres).Concat(data.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres))),
Errors.Metadata.GenreNameCannotBeEmpty,
cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
foreach (AlbumEntity dataAlbum in data.Albums)
{
dataAlbum.Tags = [.. SharedReferenceResolver.Normalize(dataAlbum.Tags, resolveTagsResult.Value)];
dataAlbum.Genres = [.. SharedReferenceResolver.Normalize(dataAlbum.Genres, resolveGenresResult.Value)];
foreach (TrackEntity dataTrack in dataAlbum.Tracks)
{
dataTrack.Tags = [.. SharedReferenceResolver.Normalize(dataTrack.Tags, resolveTagsResult.Value)];
dataTrack.Genres = [.. SharedReferenceResolver.Normalize(dataTrack.Genres, resolveGenresResult.Value)];
}
}
// Reconcile the albums by their Id: albums that are no longer present are removed, new albums are inserted, and existing
// albums and their tracks are updated in place, so that persisted entities keep their identity across an edit. An album whose data did
// not change produces no write statement, because its own repository only applies the values that actually changed.
@@ -156,7 +214,7 @@ internal sealed class ArtistRepository : IArtistRepository
continue;
}
Result<Updated> updateAlbumResult = await _albumRepository.UpdateAsync(incomingAlbum, cancellationToken).ConfigureAwait(false);
Result<Updated> updateAlbumResult = await _albumRepository.ApplyUpdateAsync(existingAlbum, incomingAlbum, cancellationToken).ConfigureAwait(false);
if (updateAlbumResult.IsFailure)
return updateAlbumResult.Errors;
@@ -242,7 +300,7 @@ internal sealed class ArtistRepository : IArtistRepository
continue;
}
Result<Updated> updateTrackResult = await _trackRepository.UpdateAsync(incomingTrack, cancellationToken).ConfigureAwait(false);
Result<Updated> updateTrackResult = await _trackRepository.ApplyUpdateAsync(existingTrack, incomingTrack, cancellationToken).ConfigureAwait(false);
if (updateTrackResult.IsFailure)
return updateTrackResult.Errors;
}
@@ -371,10 +429,11 @@ internal sealed class ArtistRepository : IArtistRepository
artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId);
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower()));
FilterSpecification<ArtistEntity>? filterSpecification = BuildFilterSpecification(libraryFilter);
if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistEntity> orderedArtistsQuery = artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id);
IQueryable<ArtistEntity> orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending);
// If no pagination was requested, return all the artists of the library.
if (paginationData is null)
@@ -434,20 +493,18 @@ internal sealed class ArtistRepository : IArtistRepository
if (!shouldTrackEntities)
artistsQuery = artistsQuery.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
artistsQuery = artistsQuery
.Include(artist => artist.Contributors)
.Include(artist => artist.Albums);
}
.Include(artist => artist.Albums)
.AsSplitQuery();
artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId);
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower()));
FilterSpecification<ArtistEntity>? filterSpecification = BuildFilterSpecification(libraryFilter);
if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistLiteRow> liteRowsQuery = artistsQuery
.OrderBy(artist => artist.Name)
.ThenBy(artist => artist.Id)
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending)
.Select(artist => new ArtistLiteRow
{
Id = artist.Id,
@@ -487,4 +544,47 @@ internal sealed class ArtistRepository : IArtistRepository
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Builds a filter specification for querying artists.
/// </summary>
/// <param name="libraryFilter">The model containing the parameters used to filter the results.</param>
/// <returns>A filter specification that can be used to query artists matching the provided criteria.</returns>
private static FilterSpecification<ArtistEntity>? BuildFilterSpecification(LibraryFilterDto libraryFilter)
{
// Include the search term filter, if provided.
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
return new ArtistSearchSpecification(libraryFilter.SearchTerm);
return null;
}
/// <summary>
/// Sorts an artists query by the given field name, defaulting to <see cref="ArtistEntity.Name"/>.
/// </summary>
/// <param name="artistsQuery">The query to sort.</param>
/// <param name="sortBy">The field to sort by (case-insensitive).</param>
/// <param name="sortOrder">The direction of the sorting.</param>
/// <returns>An ordered artists query.</returns>
private static IOrderedQueryable<ArtistEntity> ApplySorting(IQueryable<ArtistEntity> artistsQuery, string? sortBy, SortOrder sortOrder)
{
return sortBy?.ToLowerInvariant() switch
{
"website" => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.Website).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.Website).ThenBy(artist => artist.Id),
"musicbrainzartistid" => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.MusicBrainzArtistId).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.MusicBrainzArtistId).ThenBy(artist => artist.Id),
"createdonutc" => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.CreatedOnUtc).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.CreatedOnUtc).ThenBy(artist => artist.Id),
"updatedonutc" => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id),
_ => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.Name).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id),
};
}
}
@@ -53,17 +53,16 @@ internal sealed class TrackRepository : ITrackRepository
if (getExistingPathsResult.Value.Count > 0)
return Errors.Music.TrackAlreadyExists;
// Fetch existing tags and genres.
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
// Resolve the tags and genres of the track to a single instance per name, replacing the stored ones where they exist, so that the shared tables are not duplicated.
Result<IReadOnlyDictionary<string, TagEntity>> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, track.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveTagsResult.IsFailure)
return resolveTagsResult.Errors;
Result<IReadOnlyDictionary<string, GenreEntity>> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, track.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (resolveGenresResult.IsFailure)
return resolveGenresResult.Errors;
// Replace tags and genres in the track with existing ones, so that the shared tables are not duplicated.
track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)];
track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)];
_luminaDbContext.Tracks.Add(track);
return Result.Created;
@@ -106,10 +105,24 @@ internal sealed class TrackRepository : ITrackRepository
.Include(repositoryTrack => repositoryTrack.Contributors)
.Include(repositoryTrack => repositoryTrack.Moods)
.Include(repositoryTrack => repositoryTrack.Isrcs)
.AsSplitQuery()
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundTrack is null)
return Errors.Music.TrackNotFound;
return await ApplyUpdateAsync(foundTrack, data, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Applies the editable data of <paramref name="data"/> onto the already tracked <paramref name="foundTrack"/>, without loading it, so that a caller that already
/// loaded the track graph, like the artist repository, does not make the track repository load it again.
/// </summary>
/// <param name="foundTrack">The tracked track whose editable data is applied.</param>
/// <param name="data">The track carrying the desired data.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> ApplyUpdateAsync(TrackEntity foundTrack, TrackEntity data, CancellationToken cancellationToken)
{
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
Guid albumId = foundTrack.AlbumId;
Guid libraryId = foundTrack.LibraryId;
@@ -117,7 +130,13 @@ internal sealed class TrackRepository : ITrackRepository
foundTrack.AlbumId = albumId;
foundTrack.LibraryId = libraryId;
await ReconcileTagsAndGenresAsync(foundTrack, data, cancellationToken).ConfigureAwait(false);
// Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted.
Result<Updated> reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileTagsResult.IsFailure)
return reconcileTagsResult.Errors;
Result<Updated> reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false);
if (reconcileGenresResult.IsFailure)
return reconcileGenresResult.Errors;
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the track.
@@ -159,41 +178,6 @@ internal sealed class TrackRepository : ITrackRepository
return Result.Updated;
}
/// <summary>
/// Reconciles the tags and genres of <paramref name="foundTrack"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
/// </summary>
/// <param name="foundTrack">The tracked track whose tags and genres are reconciled.</param>
/// <param name="data">The track carrying the desired tags and genres.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task ReconcileTagsAndGenresAsync(TrackEntity foundTrack, TrackEntity data, CancellationToken cancellationToken)
{
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(tag => tagNames.Contains(tag.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
.Where(genre => genreNames.Contains(genre.Name!))
.ToListAsync(cancellationToken).ConfigureAwait(false);
CollectionReconciler.Reconcile(
foundTrack.Tags,
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
existingTag => existingTag.Name!,
incomingTag => incomingTag.Name!,
shouldReplace: (existingTag, incomingTag) => false,
createNew: incomingTag => incomingTag);
CollectionReconciler.Reconcile(
foundTrack.Genres,
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
existingGenre => existingGenre.Name!,
incomingGenre => incomingGenre.Name!,
shouldReplace: (existingGenre, incomingGenre) => false,
createNew: incomingGenre => incomingGenre);
}
/// <summary>
/// Gets a track by its Id.
/// </summary>
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -75,8 +76,8 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe
?? await _luminaDbContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundExecution is null)
return Errors.Scheduling.ScheduledJobExecutionNotFound;
// Update scalar properties.
_luminaDbContext.Entry(foundExecution).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundExecution, data);
return Result.Updated;
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -156,8 +157,8 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository
?? await _luminaDbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundScheduledJob is null)
return Errors.Scheduling.ScheduledJobNotFound;
// Update scalar properties.
_luminaDbContext.Entry(foundScheduledJob).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundScheduledJob, data);
return Result.Updated;
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
@@ -62,7 +63,8 @@ internal sealed class ThemeRepository : IThemeRepository
if (foundTheme is null)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Entry(foundTheme).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTheme, data);
return Result.Updated;
}
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
@@ -116,6 +117,7 @@ internal sealed class UserRepository : IUserRepository
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRole!.Role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.AsSplitQuery()
.FirstOrDefaultAsync(user => user.Username == username, cancellationToken)
.ConfigureAwait(false);
}
@@ -135,35 +137,35 @@ internal sealed class UserRepository : IUserRepository
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRole!.Role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.AsSplitQuery()
.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken)
.ConfigureAwait(false);
if (foundUser is null)
return Errors.Users.UserDoesNotExist;
// Update scalar properties.
_luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundUser, data);
// Update user permissions.
List<UserPermissionEntity> existingPermissions = [.. foundUser.UserPermissions];
foreach (UserPermissionEntity permission in existingPermissions)
_luminaDbContext.UserPermissions.Remove(permission);
foreach (UserPermissionEntity permission in data.UserPermissions)
{
_luminaDbContext.UserPermissions.Add(new UserPermissionEntity
// A permission participation is matched by its permission. Matched participations keep their identity and their audit columns, so a permission
// that is referenced elsewhere is never deleted and re-inserted just because another field of the user was edited.
CollectionReconciler.Reconcile(
foundUser.UserPermissions,
data.UserPermissions,
existingUserPermission => existingUserPermission.PermissionId,
incomingUserPermission => incomingUserPermission.PermissionId,
shouldReplace: (existingUserPermission, incomingUserPermission) => false,
createNew: incomingUserPermission => new UserPermissionEntity
{
UserId = foundUser.Id,
PermissionId = permission.PermissionId,
Permission = permission.Permission,
PermissionId = incomingUserPermission.PermissionId,
Permission = incomingUserPermission.Permission,
User = foundUser
});
}
// Update user role.
if (foundUser.UserRole != null)
_luminaDbContext.UserRoles.Remove(foundUser.UserRole);
if (data.UserRole is not null)
{
_luminaDbContext.UserRoles.Add(new UserRoleEntity
{
UserId = foundUser.Id,
@@ -171,7 +173,6 @@ internal sealed class UserRepository : IUserRepository
Role = data.UserRole.Role,
User = foundUser
});
}
return Result.Updated;
}
@@ -187,15 +188,14 @@ internal sealed class UserRepository : IUserRepository
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRole!.Role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission);
}
.ThenInclude(rolePermission => rolePermission.Permission)
.AsSplitQuery();
return await query.FirstOrDefaultAsync(user => user.Id == id, cancellationToken)
.ConfigureAwait(false);
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -87,7 +88,8 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository
if (foundSettings is null)
return Errors.UserSettings.UserSettingsNotFound;
_luminaDbContext.Entry(foundSettings).CurrentValues.SetValues(data);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundSettings, data);
return Result.Updated;
}
}