optimization sql

This commit is contained in:
Artemy
2025-07-01 15:05:49 +07:00
parent 5883f3e340
commit cdae63b223
10 changed files with 81 additions and 58 deletions
@@ -52,13 +52,13 @@ public class InviteUserController : Controller
_logger.LogInformation("Getting all active invitations by administrator"); _logger.LogInformation("Getting all active invitations by administrator");
var read = await _repository.GetAllAsync(); var read = await _repository.GetAllAsync();
var result = read.Where(x => x.IsActive == true).ToList(); var result = read.Where(x => x.IsActive).ToList();
List<InvitationDto> dtos = new List<InvitationDto>(); List<InvitationResponses> dtos = new List<InvitationResponses>();
foreach (var inv in result) foreach (var inv in result)
{ {
dtos.Add(new InvitationDto(){ dtos.Add(new InvitationResponses(){
Id = inv.Id, Id = inv.Id,
Description = inv.Description, Description = inv.Description,
IsAdmin = inv.IsAdmin, IsAdmin = inv.IsAdmin,
@@ -67,6 +67,7 @@ public class InviteUserController : Controller
CreatedAt = inv.DateCreated, CreatedAt = inv.DateCreated,
EndAt = inv.EndDate, EndAt = inv.EndDate,
IsActive = inv.IsActive, IsActive = inv.IsActive,
ParticipantCount = inv.Users.Count,
}); });
} }
@@ -87,11 +88,11 @@ public class InviteUserController : Controller
_logger.LogInformation("Getting all invitations by administrator"); _logger.LogInformation("Getting all invitations by administrator");
var read = await _repository.GetAllAsync(); var read = await _repository.GetAllAsync();
List<InvitationDto> dtos = new List<InvitationDto>(); List<InvitationResponses> dtos = new List<InvitationResponses>();
foreach (var inv in read) foreach (var inv in read)
{ {
dtos.Add(new InvitationDto(){ dtos.Add(new InvitationResponses(){
Id = inv.Id, Id = inv.Id,
Description = inv.Description, Description = inv.Description,
IsAdmin = inv.IsAdmin, IsAdmin = inv.IsAdmin,
@@ -100,6 +101,7 @@ public class InviteUserController : Controller
CreatedAt = inv.DateCreated, CreatedAt = inv.DateCreated,
EndAt = inv.EndDate, EndAt = inv.EndDate,
IsActive = inv.IsActive, IsActive = inv.IsActive,
ParticipantCount = inv.Users.Count,
}); });
} }
@@ -120,7 +122,7 @@ public class InviteUserController : Controller
_logger.LogInformation("Getting invitations {id} by administrator"); _logger.LogInformation("Getting invitations {id} by administrator");
var read = await _repository.FindByIdAsync(id); var read = await _repository.FindByIdAsync(id);
var response = new InvitationDto(){ var response = new InvitationResponses(){
Id = read.Id, Id = read.Id,
Description = read.Description, Description = read.Description,
IsAdmin = read.IsAdmin, IsAdmin = read.IsAdmin,
@@ -129,9 +131,9 @@ public class InviteUserController : Controller
CreatedAt = read.DateCreated, CreatedAt = read.DateCreated,
EndAt = read.EndDate, EndAt = read.EndDate,
IsActive = read.IsActive, IsActive = read.IsActive,
ParticipantCount = read.Users.Count,
}; };
return Ok(response); return Ok(response);
} }
catch (Exception e) catch (Exception e)
@@ -67,19 +67,29 @@ public static class ConfigurationProgramExtensions
public static void AddGovorDbContext(this IServiceCollection services, IConfiguration configuration) public static void AddGovorDbContext(this IServiceCollection services, IConfiguration configuration)
{ {
var useMySql = configuration.GetValue<bool>("UseMySql"); // Получаем значение из конфигурации var useMySql = configuration.GetValue<bool>("UseMySql");
if (useMySql) if (useMySql)
{ {
services.AddDbContext<GovorDbContext>(options => services.AddDbContext<GovorDbContext>(options =>
options.UseMySql(configuration.GetConnectionString(nameof(GovorDbContext)), {
new MySqlServerVersion(new Version(8, 0, 21)))); options
.UseMySql(
configuration.GetConnectionString(nameof(GovorDbContext)),
new MySqlServerVersion(new Version(8, 0, 21))
);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
} }
else else
{ {
services.AddDbContext<GovorDbContext>(options => services.AddDbContext<GovorDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString(nameof(GovorDbContext)))); {
options.UseNpgsql(configuration.GetConnectionString(nameof(GovorDbContext)));
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
} }
} }
} }
@@ -1,6 +1,6 @@
namespace Govor.Contracts.DTOs; namespace Govor.Contracts.DTOs;
public class InvitationDto public class InvitationResponses
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public bool IsAdmin { get; set; } public bool IsAdmin { get; set; }
@@ -9,5 +9,6 @@ public class InvitationDto
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTime EndAt { get; set; } public DateTime EndAt { get; set; }
public int MaxParticipants { get; set; } public int MaxParticipants { get; set; }
public int ParticipantCount { get; set; }
public string Description { get; set; } public string Description { get; set; }
} }
+3 -5
View File
@@ -16,6 +16,7 @@ public class AdminsRepository(GovorDbContext context, IObjectValidator<Admin> va
return await _context.Admins return await _context.Admins
.AsNoTracking() .AsNoTracking()
.Include(a => a.User) .Include(a => a.User)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("Database is empty")); .ToListOrThrowIfEmpty(new NotFoundException("Database is empty"));
} }
@@ -24,6 +25,7 @@ public class AdminsRepository(GovorDbContext context, IObjectValidator<Admin> va
return await _context.Admins return await _context.Admins
.AsNoTracking() .AsNoTracking()
.Include(a => a.User) .Include(a => a.User)
.AsSplitQuery()
.FirstOrDefaultAsync(u => u.UserId == id) .FirstOrDefaultAsync(u => u.UserId == id)
?? throw new NotFoundByKeyException<Guid>(id, "User with given id does not exist"); ?? throw new NotFoundByKeyException<Guid>(id, "User with given id does not exist");
} }
@@ -60,11 +62,7 @@ public class AdminsRepository(GovorDbContext context, IObjectValidator<Admin> va
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(admin.UserId); throw new UpdateException($"Not found admin by given id {admin.UserId}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found admin by given id {admin.UserId}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1,4 +1,12 @@
using Govor.Core;
namespace Govor.Data.Repositories.Exceptions; namespace Govor.Data.Repositories.Exceptions;
public class UpdateException(string s, Exception ex) public class UpdateException : GovorCoreException
: Exception(s, ex); {
public UpdateException(string s)
: base(s) { }
public UpdateException(string s, Exception ex)
: base(s, ex) { }
}
@@ -24,6 +24,7 @@ public class FriendshipsRepository : IFriendshipsRepository
.AsNoTracking() .AsNoTracking()
.Include(x => x.Requester) .Include(x => x.Requester)
.Include(x => x.Addressee) .Include(x => x.Addressee)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("Database is empty")); .ToListOrThrowIfEmpty(new NotFoundException("Database is empty"));
} }
@@ -33,6 +34,7 @@ public class FriendshipsRepository : IFriendshipsRepository
.AsNoTracking() .AsNoTracking()
.Include(x => x.Requester) .Include(x => x.Requester)
.Include(x => x.Addressee) .Include(x => x.Addressee)
.AsSplitQuery()
.FirstOrDefaultAsync(x => x.Id == id) .FirstOrDefaultAsync(x => x.Id == id)
?? throw new NotFoundByKeyException<Guid>(id, "Friendship with given id was not found"); ?? throw new NotFoundByKeyException<Guid>(id, "Friendship with given id was not found");
} }
@@ -43,6 +45,7 @@ public class FriendshipsRepository : IFriendshipsRepository
.AsNoTracking() .AsNoTracking()
.Include(x => x.Requester) .Include(x => x.Requester)
.Include(x => x.Addressee) .Include(x => x.Addressee)
.AsSplitQuery()
.Where(x => x.RequesterId == userId) .Where(x => x.RequesterId == userId)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(userId, "Friendship with given user id was not found")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(userId, "Friendship with given user id was not found"));
} }
@@ -81,11 +84,7 @@ public class FriendshipsRepository : IFriendshipsRepository
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(friendship.Id); throw new UpdateException($"Not found friendship by given id {friendship.Id}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found friendship by given id {friendship.Id}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
+5 -5
View File
@@ -23,6 +23,7 @@ public class InvitesRepository : IInvitesRepository
return await _context.Invitations return await _context.Invitations
.AsNoTracking() .AsNoTracking()
.Include(i => i.Users) .Include(i => i.Users)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("Database is empty")); .ToListOrThrowIfEmpty(new NotFoundException("Database is empty"));
} }
@@ -31,6 +32,7 @@ public class InvitesRepository : IInvitesRepository
return await _context.Invitations return await _context.Invitations
.AsNoTracking() .AsNoTracking()
.Include(i => i.Users) .Include(i => i.Users)
.AsSplitQuery()
.FirstOrDefaultAsync(i => i.Id == id) .FirstOrDefaultAsync(i => i.Id == id)
?? throw new NotFoundByKeyException<Guid>(id, "Invitation with given id does not exist"); ?? throw new NotFoundByKeyException<Guid>(id, "Invitation with given id does not exist");
} }
@@ -40,6 +42,7 @@ public class InvitesRepository : IInvitesRepository
return await _context.Invitations return await _context.Invitations
.AsNoTracking() .AsNoTracking()
.Include(i => i.Users) .Include(i => i.Users)
.AsSplitQuery()
.FirstOrDefaultAsync(i => i.Code == code) .FirstOrDefaultAsync(i => i.Code == code)
?? throw new NotFoundByKeyException<string>(code, "Invitation with given code does not exist"); ?? throw new NotFoundByKeyException<string>(code, "Invitation with given code does not exist");
} }
@@ -49,6 +52,7 @@ public class InvitesRepository : IInvitesRepository
return await _context.Invitations return await _context.Invitations
.AsNoTracking() .AsNoTracking()
.Include(i => i.Users) .Include(i => i.Users)
.AsSplitQuery()
.Where(i => i.IsAdmin) .Where(i => i.IsAdmin)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<bool>(true, "Admins invites do not exist")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<bool>(true, "Admins invites do not exist"));
} }
@@ -94,11 +98,7 @@ public class InvitesRepository : IInvitesRepository
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(invitation.Id, "Invitation with given data invalid"); throw new UpdateException($"Not found invitation by given id {invitation.Id}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found invitation by given id {invitation.Id}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -23,6 +23,7 @@ public class MediaAttachmentsRepository : IMediaAttachmentsRepository
return await _context.MediaAttachments return await _context.MediaAttachments
.AsNoTracking() .AsNoTracking()
.Include(ma => ma.Message) .Include(ma => ma.Message)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("No media attachments found.")); .ToListOrThrowIfEmpty(new NotFoundException("No media attachments found."));
} }
@@ -31,6 +32,7 @@ public class MediaAttachmentsRepository : IMediaAttachmentsRepository
return await _context.MediaAttachments return await _context.MediaAttachments
.AsNoTracking() .AsNoTracking()
.Include(ma => ma.Message) .Include(ma => ma.Message)
.AsSplitQuery()
.Where(m => m.MessageId == messageId) .Where(m => m.MessageId == messageId)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(messageId, "No media attachments found by given message Id")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(messageId, "No media attachments found by given message Id"));
} }
@@ -40,6 +42,7 @@ public class MediaAttachmentsRepository : IMediaAttachmentsRepository
return await _context.MediaAttachments return await _context.MediaAttachments
.AsNoTracking() .AsNoTracking()
.Include(ma => ma.Message) .Include(ma => ma.Message)
.AsSplitQuery()
.FirstOrDefaultAsync(m => m.Id == id) .FirstOrDefaultAsync(m => m.Id == id)
?? throw new NotFoundByKeyException<Guid>(id, "No media attachments found by given Id"); ?? throw new NotFoundByKeyException<Guid>(id, "No media attachments found by given Id");
} }
@@ -80,11 +83,7 @@ public class MediaAttachmentsRepository : IMediaAttachmentsRepository
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(attachments.Id); throw new UpdateException($"Not found attachments by given id {attachments.Id}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found attachments by given id {attachments.Id}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -22,6 +22,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("No messages found in the database")); .ToListOrThrowIfEmpty(new NotFoundException("No messages found in the database"));
} }
@@ -30,6 +31,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.FirstOrDefaultAsync(m => m.Id == messageId) .FirstOrDefaultAsync(m => m.Id == messageId)
?? throw new NotFoundByKeyException<Guid>(messageId, "Message with given id does not exist"); ?? throw new NotFoundByKeyException<Guid>(messageId, "Message with given id does not exist");
} }
@@ -39,6 +41,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.Where(m => m.SenderId == senderId) .Where(m => m.SenderId == senderId)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(senderId, "Messages with given sender id do not exist")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(senderId, "Messages with given sender id do not exist"));
} }
@@ -48,6 +51,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.Where(m => m.RecipientId == receiverId) .Where(m => m.RecipientId == receiverId)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(receiverId, "Messages with given recipient id do not exist")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(receiverId, "Messages with given recipient id do not exist"));
} }
@@ -57,6 +61,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.Where(m => m.SenderId == senderId .Where(m => m.SenderId == senderId
&& m.RecipientId == receiverId && m.RecipientId == receiverId
&& m.RecipientType == recipientType) && m.RecipientType == recipientType)
@@ -68,6 +73,7 @@ public class MessagesRepository : IMessagesRepository
return await _context.Messages return await _context.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.ReplyToMessage) .Include(m => m.ReplyToMessage)
.AsSplitQuery()
.Where(m => m.SentAt == date) .Where(m => m.SentAt == date)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<DateTime>(date, "Messages sent at date do not exist")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<DateTime>(date, "Messages sent at date do not exist"));
} }
@@ -116,11 +122,7 @@ public class MessagesRepository : IMessagesRepository
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(message.Id); throw new UpdateException($"Not found message by given id {message.Id}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found message by given id {message.Id}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
+9 -5
View File
@@ -25,6 +25,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundException("Users in Database not exists")); .ToListOrThrowIfEmpty(new NotFoundException("Users in Database not exists"));
} }
@@ -38,6 +39,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.FirstOrDefaultAsync(x => x.Id == id) .FirstOrDefaultAsync(x => x.Id == id)
?? throw new NotFoundByKeyException<Guid>(id, "User with given id does not exist"); ?? throw new NotFoundByKeyException<Guid>(id, "User with given id does not exist");
} }
@@ -53,6 +55,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<Guid>>(ids,"Users with given ids not found")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<Guid>>(ids,"Users with given ids not found"));
} }
@@ -66,6 +69,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.FirstOrDefaultAsync(x => x.Username == username) .FirstOrDefaultAsync(x => x.Username == username)
?? throw new NotFoundByKeyException<string>(username, "User with given username does not exist"); ?? throw new NotFoundByKeyException<string>(username, "User with given username does not exist");
} }
@@ -77,6 +81,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.Where(u => u.Id != currentUserId && .Where(u => u.Id != currentUserId &&
u.Username.ToLower().Contains(query.ToLower()) && u.Username.ToLower().Contains(query.ToLower()) &&
!_context.Friendships.Any(f => !_context.Friendships.Any(f =>
@@ -99,6 +104,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<string>>(usernames, "Users with given usernames not found")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<string>>(usernames, "Users with given usernames not found"));
} }
@@ -113,6 +119,7 @@ public class UsersRepository : IUsersRepository
.Include(u => u.Invite) .Include(u => u.Invite)
.Include(u => u.ReceivedFriendRequests) .Include(u => u.ReceivedFriendRequests)
.Include(u => u.SentFriendRequests) .Include(u => u.SentFriendRequests)
.AsSplitQuery()
.ToListOrThrowIfEmpty(new NotFoundByKeyException<DateOnly>(createdDate, "Users with given created date do not exist")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<DateOnly>(createdDate, "Users with given created date do not exist"));
} }
@@ -151,14 +158,11 @@ public class UsersRepository : IUsersRepository
.SetProperty(u => u.CreatedOn, user.CreatedOn) .SetProperty(u => u.CreatedOn, user.CreatedOn)
.SetProperty(u => u.PasswordHash, user.PasswordHash) .SetProperty(u => u.PasswordHash, user.PasswordHash)
.SetProperty(u => u.WasOnline, user.WasOnline) .SetProperty(u => u.WasOnline, user.WasOnline)
.SetProperty(u => u.InviteId, user.InviteId)
); );
if (rowsAffected == 0) if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(user.Id); throw new UpdateException($"Not found user by given id {user.Id}");
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found user by given id {user.Id}", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {