From cd1386b9e7ed63484a32f878f0374b46ac46fef9 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 27 Sep 2026 21:20:51 +0300 Subject: [PATCH] Adopts the persistence toolkit across the repositories --- .../Actions/IApplyUpdateRepositoryAction.cs | 24 +++ .../MusicLibrary/IAlbumRepository.cs | 1 + .../MusicLibrary/ITrackRepository.cs | 1 + .../Authorization/RoleRepository.cs | 31 +++- .../BookLibrary/BookRepository.cs | 69 +++----- .../Libraries/LibraryRepository.cs | 14 +- .../Libraries/LibraryScanRepository.cs | 13 +- .../MusicLibrary/AlbumRepository.cs | 91 ++++------ .../MusicLibrary/ArtistRepository.cs | 166 ++++++++++++++---- .../MusicLibrary/TrackRepository.cs | 76 ++++---- .../ScheduledJobExecutionRepository.cs | 5 +- .../Scheduling/ScheduledJobRepository.cs | 5 +- .../Repositories/Themes/ThemeRepository.cs | 4 +- .../Core/Repositories/Users/UserRepository.cs | 36 ++-- .../Users/UserSettingsRepository.cs | 4 +- 15 files changed, 313 insertions(+), 227 deletions(-) create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs new file mode 100644 index 00000000..929ee559 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs @@ -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; + +/// +/// Interface defining the "apply update" action for interacting with a generic persistence medium. +/// +/// The type used for the apply update action. It should implement . +public interface IApplyUpdateRepositoryAction where TModel : IStorageEntity +{ + /// + /// Applies the editable values of onto the already tracked model, without loading it again. + /// + /// The tracked model whose editable values are updated. + /// The model carrying the desired values. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ApplyUpdateAsync(TModel tracked, TModel data, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs index 5a12079b..f4103045 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs @@ -19,6 +19,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; public interface IAlbumRepository : IRepository, IInsertRepositoryAction, IUpdateRepositoryAction, + IApplyUpdateRepositoryAction, IGetByIdRepositoryAction { /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index a3d09249..b2720f5f 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -19,6 +19,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; public interface ITrackRepository : IRepository, IInsertRepositoryAction, IUpdateRepositoryAction, + IApplyUpdateRepositoryAction, IGetByIdRepositoryAction { /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs index 5cf0856d..83941416 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs @@ -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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index 0209e6e5..f0fca470 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -65,18 +65,16 @@ internal sealed class BookRepository : IBookRepository if (doesBookPathExist) return Errors.WrittenContent.BookAlreadyExists; - // Fetch existing tags and genres. - List existingTags = await _luminaDbContext.Set() - .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> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveGenresResult.IsFailure) + return resolveGenresResult.Errors; - List existingGenres = await _luminaDbContext.Set() - .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 reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundBook.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result 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; } - /// - /// Reconciles the tags and genres of against the ones carried by , reusing the stored tags and genres whose names already exist. - /// - /// The tracked book whose tags and genres are reconciled. - /// The book carrying the desired tags and genres. - /// Cancellation token that can be used to stop the execution. - 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 tagNames = [.. data.Tags.Select(tag => tag.Name!)]; - List genreNames = [.. data.Genres.Select(genre => genre.Name!)]; - List existingTags = await _luminaDbContext.Set() - .Where(tag => tagNames.Contains(tag.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .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); - } - /// /// Sorts a books query by the given field name, defaulting to . /// @@ -600,7 +571,7 @@ internal sealed class BookRepository : IBookRepository /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker) { - return sortBy?.ToLower() switch + return sortBy?.ToLowerInvariant() switch { "languagecode" => sortOrder == SortOrder.Descending ? booksQuery.OrderByDescending(book => book.LanguageCode) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index f41c8eaf..c5168a61 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -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); diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index 093c8cee..4c8a1c2a 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -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; } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs index 8d513811..a4d6a119 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -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 tagNames = [.. album.Tags.Select(tag => tag.Name!) - .Concat(album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!))) - .Distinct()]; - List 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> 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> 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 existingTags = await _luminaDbContext.Set() - .Where(tag => tagNames.Contains(tag.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .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 /// An representing either a successful operation, or an error. public async Task> 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); + } + + /// + /// Applies the editable data of onto the already tracked , 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. + /// + /// The tracked album whose editable data is applied. + /// The album carrying the desired data. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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 reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result 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; } - /// - /// Reconciles the tags and genres of against the ones carried by , reusing the stored tags and genres whose names already exist. - /// - /// The tracked album whose tags and genres are reconciled. - /// The album carrying the desired tags and genres. - /// Cancellation token that can be used to stop the execution. - 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 tagNames = [.. data.Tags.Select(tag => tag.Name!)]; - List genreNames = [.. data.Genres.Select(genre => genre.Name!)]; - List existingTags = await _luminaDbContext.Set() - .Where(tag => tagNames.Contains(tag.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .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); - } - /// /// Gets an album by its Id. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs index 8714a8f3..7387003e 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -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 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 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> 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 existingTags = await _luminaDbContext.Set() - .Where(tag => tagNames.Contains(tag.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .Where(genre => genreNames.Contains(genre.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); + Result> 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 /// An representing either a successful operation, or an error. public async Task> 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> 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> 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 updateAlbumResult = await _albumRepository.UpdateAsync(incomingAlbum, cancellationToken).ConfigureAwait(false); + Result 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 updateTrackResult = await _trackRepository.UpdateAsync(incomingTrack, cancellationToken).ConfigureAwait(false); + Result 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? filterSpecification = BuildFilterSpecification(libraryFilter); + if (filterSpecification is not null) + artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); - IQueryable orderedArtistsQuery = artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id); + IQueryable 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? filterSpecification = BuildFilterSpecification(libraryFilter); + if (filterSpecification is not null) + artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); - IQueryable liteRowsQuery = artistsQuery - .OrderBy(artist => artist.Name) - .ThenBy(artist => artist.Id) + IQueryable 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 }; } + + /// + /// Builds a filter specification for querying artists. + /// + /// The model containing the parameters used to filter the results. + /// A filter specification that can be used to query artists matching the provided criteria. + private static FilterSpecification? BuildFilterSpecification(LibraryFilterDto libraryFilter) + { + // Include the search term filter, if provided. + if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) + return new ArtistSearchSpecification(libraryFilter.SearchTerm); + + return null; + } + + /// + /// Sorts an artists query by the given field name, defaulting to . + /// + /// The query to sort. + /// The field to sort by (case-insensitive). + /// The direction of the sorting. + /// An ordered artists query. + private static IOrderedQueryable ApplySorting(IQueryable 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), + }; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index 6b39c2f7..de46fe87 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -53,17 +53,16 @@ internal sealed class TrackRepository : ITrackRepository if (getExistingPathsResult.Value.Count > 0) return Errors.Music.TrackAlreadyExists; - // Fetch existing tags and genres. - List existingTags = await _luminaDbContext.Set() - .Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .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> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, track.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + Result> 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); + } + + /// + /// Applies the editable data of onto the already tracked , 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. + /// + /// The tracked track whose editable data is applied. + /// The track carrying the desired data. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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 reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result 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; } - /// - /// Reconciles the tags and genres of against the ones carried by , reusing the stored tags and genres whose names already exist. - /// - /// The tracked track whose tags and genres are reconciled. - /// The track carrying the desired tags and genres. - /// Cancellation token that can be used to stop the execution. - 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 tagNames = [.. data.Tags.Select(tag => tag.Name!)]; - List genreNames = [.. data.Genres.Select(genre => genre.Name!)]; - List existingTags = await _luminaDbContext.Set() - .Where(tag => tagNames.Contains(tag.Name!)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .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); - } - /// /// Gets a track by its Id. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs index db0c5fab..ae14ea56 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs @@ -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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs index c8139a84..60f7ec50 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs @@ -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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs index bdbe711f..7cdd6973 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 2417fe17..2ee42ed7 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -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 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); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs index cdd3fea1..b540ce1c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs @@ -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; } }