Files
NTBug/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs
T

112 lines
5.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Data;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Statistics;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Notifications;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MySqlConnector;
namespace Helpdesk.Infrastructure.Persistence;
/// <summary>
/// EF Core slouží jen k mapování – schéma vytvářejí SQL migrace v <c>db/migrations</c> (kap. 12.5).
/// Názvy sloupců jsou snake_case (EFCore.NamingConventions), tabulky jsou pojmenované explicitně.
/// </summary>
public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> options, FieldEncryptor encryptor)
: DbContext(options), IAppDbContext
{
public DbSet<User> Users => Set<User>();
public DbSet<AuthToken> AuthTokens => Set<AuthToken>();
public DbSet<Building> Buildings => Set<Building>();
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
public DbSet<Issue> Issues => Set<Issue>();
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
public DbSet<Attachment> Attachments => Set<Attachment>();
public DbSet<Proposal> Proposals => Set<Proposal>();
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
public DbSet<ProposalVote> ProposalVotes => Set<ProposalVote>();
public DbSet<ProposalScore> ProposalScores => Set<ProposalScore>();
public DbSet<Notification> Notifications => Set<Notification>();
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException exception) when (
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory))
{
throw new ConflictException("Kategorie se stejným názvem již existuje.");
}
}
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
{
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
var rows = await Proposals.FromSql($"SELECT * FROM proposal WHERE id = {id} FOR UPDATE").ToListAsync(ct);
return rows.SingleOrDefault();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
modelBuilder.ApplyConfiguration(new AuthTokenConfiguration());
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
modelBuilder.ApplyConfiguration(new IssueConfiguration());
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
modelBuilder.Entity<IssueTiming>().HasNoKey().ToSqlQuery("""
SELECT issue_id,
TIMESTAMPDIFF(MICROSECOND, created_at, first_assigned_at) AS microseconds_to_assignment,
TIMESTAMPDIFF(MICROSECOND, created_at, closed_at) AS microseconds_to_closure
FROM v_issue_lifecycle
""");
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration());
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
var pushDevice = modelBuilder.Entity<PushDevice>();
pushDevice.ToTable("push_device");
pushDevice.Property(x => x.FcmToken).HasMaxLength(512);
pushDevice.HasIndex(x => x.FcmToken).IsUnique();
}
public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) =>
Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token})
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id)
""", ct);
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
configurationBuilder.Properties<DateTime?>().HaveConversion<UtcDateTimeConverter>();
}
private sealed class UtcDateTimeConverter() : ValueConverter<DateTime, DateTime>(
v => v.Kind == DateTimeKind.Utc ? v : v.ToUniversalTime(),
v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
}