Migrate Auth/Brewery/Location repositories to pure Dapper; rename Timer to RowVersion (#237)

* Integrate Spectre.Console into seed application, use async data loading

* Replace stored-procedure repositories with Dapper-based repositories

Removes the USP_* stored procedures for Auth, Location, and Brewery
data access in favour of services built with Dapper.

Adds a new Features.Locations slice and optimistic concurrency support
for the Brewery slice.

* Add new documentation for Dapper migration/database schema

* Update FluentAssertions to most recent open source ver

* Update XML doc comment in backend projects

* Modify brewery location dto to include denormalized data

* - Updated column names from 'Timer' to 'RowVersion' in schema.sql for
- Introduced new BeerPost entity and updated BreweryPost and BreweryPostLocation entities to use 'RowVersion' for concurrency.
- Modified UserAccount, UserCredential, UserVerification, City, StateProvince, and Country entities to use 'RowVersion' instead of 'Timer'.
- Updated tests and command handlers to reflect changes in concurrency token from 'Timer' to 'RowVersion'.
- Adjusted BreweryDto and BreweryDtoMapper to include 'RowVersion' and updated mapping logic accordingly.
- Ensured all repository methods and interfaces are aligned with the new concurrency handling approach.

* updates

* Add BeerStyle entity and related properties; refactor BreweryDto to remove BeerPosts

* Fix Api.Specs test failures: stale Timer column refs and missing test.user fixture

* Remove repository tests, usages of registration dto used in repo

* archive old stored procs/functions

* update stale docs

* Add instructions for generating cryptographically secure base64 secrets on macOS/Linux and Windows
This commit is contained in:
2026-08-21 13:09:13 -04:00
committed by GitHub
parent a4da01586d
commit 6297cb141c
151 changed files with 2790 additions and 1988 deletions

View File

@@ -3,6 +3,9 @@ using MediatR;
namespace Features.UserManagement.Commands.UpdateUser;
/// <summary>
/// Handles <see cref="UpdateUserCommand" />.
/// </summary>
public class UpdateUserHandler(IUserAccountRepository repository)
: IRequestHandler<UpdateUserCommand>
{

View File

@@ -1,4 +1,5 @@
using Domain.Entities;
using Domain.Exceptions;
using Features.UserManagement.Queries.GetAllUsers;
using Features.UserManagement.Queries.GetUserById;
using MediatR;
@@ -6,10 +7,14 @@ using Microsoft.AspNetCore.Mvc;
namespace Features.UserManagement.Controllers;
/// <summary>
/// Exposes read endpoints for user accounts.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class UserController(IMediator mediator) : ControllerBase
{
/// <summary>Gets a page of user accounts, ordered by creation date descending.</summary>
/// <param name="limit"><c>null</c> for no limit.</param>
/// <param name="offset"><c>null</c> for no offset.</param>
[HttpGet]
@@ -22,6 +27,10 @@ public class UserController(IMediator mediator) : ControllerBase
return Ok(users);
}
/// <summary>Gets the user account with the given ID.</summary>
/// <exception cref="NotFoundException">
/// Thrown when no user account exists with the given ID, resulting in a 404 response.
/// </exception>
[HttpGet("{id:guid}")]
public async Task<ActionResult<UserAccount>> GetById(Guid id)
{

View File

@@ -3,8 +3,15 @@ using Microsoft.Extensions.DependencyInjection;
namespace Features.UserManagement.DependencyInjection;
/// <summary>
/// Registers the services used by the Features.UserManagement slice.
/// </summary>
public static class FeaturesUserManagementServiceCollectionExtensions
{
/// <summary>
/// Registers <see cref="IUserAccountRepository" /> and its Dapper-based implementation.
/// </summary>
/// <returns>The same <paramref name="services" /> instance, for chaining.</returns>
public static IServiceCollection AddFeaturesUserManagement(this IServiceCollection services)
{
services.AddScoped<IUserAccountRepository, UserAccountRepository>();

View File

@@ -4,6 +4,9 @@ using MediatR;
namespace Features.UserManagement.Queries.GetAllUsers;
/// <summary>
/// Handles <see cref="GetAllUsersQuery" />.
/// </summary>
public class GetAllUsersHandler(IUserAccountRepository repository)
: IRequestHandler<GetAllUsersQuery, IEnumerable<UserAccount>>
{

View File

@@ -3,4 +3,9 @@ using MediatR;
namespace Features.UserManagement.Queries.GetAllUsers;
/// <summary>
/// Requests a page of user accounts, ordered by creation date descending.
/// </summary>
/// <param name="Limit"><c>null</c> for no limit.</param>
/// <param name="Offset"><c>null</c> for no offset.</param>
public record GetAllUsersQuery(int? Limit, int? Offset) : IRequest<IEnumerable<UserAccount>>;

View File

@@ -5,6 +5,9 @@ using MediatR;
namespace Features.UserManagement.Queries.GetUserById;
/// <summary>
/// Handles <see cref="GetUserByIdQuery" />.
/// </summary>
public class GetUserByIdHandler(IUserAccountRepository repository)
: IRequestHandler<GetUserByIdQuery, UserAccount>
{

View File

@@ -3,4 +3,7 @@ using MediatR;
namespace Features.UserManagement.Queries.GetUserById;
/// <summary>
/// Requests the user account with the given ID.
/// </summary>
public record GetUserByIdQuery(Guid UserAccountId) : IRequest<UserAccount>;

View File

@@ -1,4 +1,5 @@
using Domain.Entities;
using Domain.Exceptions;
namespace Features.UserManagement.Repository;
@@ -7,30 +8,26 @@ namespace Features.UserManagement.Repository;
/// </summary>
public interface IUserAccountRepository
{
/// <summary>
/// Retrieves a user account by its unique identifier, or <c>null</c> if not found.
/// </summary>
/// <summary>Returns <c>null</c> if no user account exists with the given ID.</summary>
Task<UserAccount?> GetByIdAsync(Guid id);
/// <summary>
/// Retrieves all user accounts, optionally paginated.
/// </summary>
/// <summary>Returns user accounts ordered by creation date descending.</summary>
/// <param name="limit"><c>null</c> for no limit.</param>
/// <param name="offset"><c>null</c> for no offset.</param>
Task<IEnumerable<UserAccount>> GetAllAsync(int? limit, int? offset);
/// <summary>Updates the mutable fields of an existing user account.</summary>
/// <param name="userAccount">Must have a valid <c>UserAccountId</c>.</param>
/// <exception cref="NotFoundException">Thrown when no user account exists with the given ID.</exception>
Task UpdateAsync(UserAccount userAccount);
/// <summary>Deletes the user account with the given ID.</summary>
/// <exception cref="NotFoundException">Thrown when no user account exists with the given ID.</exception>
Task DeleteAsync(Guid id);
/// <summary>
/// Retrieves a user account by username, or <c>null</c> if not found.
/// </summary>
/// <summary>Returns <c>null</c> if no user account exists with the given username.</summary>
Task<UserAccount?> GetByUsernameAsync(string username);
/// <summary>
/// Retrieves a user account by email address, or <c>null</c> if not found.
/// </summary>
/// <summary>Returns <c>null</c> if no user account exists with the given email address.</summary>
Task<UserAccount?> GetByEmailAsync(string email);
}

View File

@@ -1,149 +1,118 @@
using System.Data;
using System.Data.Common;
using Dapper;
using Domain.Entities;
using Domain.Exceptions;
using Infrastructure.Sql;
namespace Features.UserManagement.Repository;
/// <summary>
/// ADO.NET-based implementation of <see cref="IUserAccountRepository" /> backed by SQL Server
/// stored procedures.
/// Dapper-based implementation of <see cref="IUserAccountRepository" />.
/// </summary>
public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
: Repository<UserAccount>(connectionFactory),
IUserAccountRepository
{
/// <summary>Uses the <c>usp_GetUserAccountById</c> stored procedure.</summary>
/// <inheritdoc />
public async Task<UserAccount?> GetByIdAsync(Guid id)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountById";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@UserAccountId", id);
await using DbDataReader reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
"""
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
FROM dbo.UserAccount
WHERE UserAccountID = @UserAccountId
""",
new { UserAccountId = id }
);
}
/// <summary>
/// Uses the <c>usp_GetAllUserAccounts</c> stored procedure. The <c>@Limit</c> and <c>@Offset</c>
/// parameters are only added when their corresponding argument has a value.
/// </summary>
/// <inheritdoc />
/// <remarks>
/// Always applies pagination via <c>OFFSET</c>/<c>FETCH</c>, ordered by creation date descending.
/// A <c>null</c> <paramref name="limit" />/<paramref name="offset" /> is treated as "no limit"/"no offset".
/// </remarks>
public async Task<IEnumerable<UserAccount>> GetAllAsync(int? limit, int? offset)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_GetAllUserAccounts";
command.CommandType = CommandType.StoredProcedure;
if (limit.HasValue)
AddParameter(command, "@Limit", limit.Value);
if (offset.HasValue)
AddParameter(command, "@Offset", offset.Value);
await using DbDataReader reader = await command.ExecuteReaderAsync();
List<UserAccount> users = new();
while (await reader.ReadAsync())
users.Add(MapToEntity(reader));
return users;
return await connection.QueryAsync<UserAccount>(
"""
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
FROM dbo.UserAccount
ORDER BY CreatedAt DESC
OFFSET @Offset ROWS FETCH NEXT @Limit ROWS ONLY
""",
new { Offset = offset ?? 0, Limit = limit ?? int.MaxValue }
);
}
/// <summary>
/// Updates a user account's username, first name, last name, email, and date of birth using
/// the <c>usp_UpdateUserAccount</c> stored procedure.
/// </summary>
/// <inheritdoc />
public async Task UpdateAsync(UserAccount userAccount)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_UpdateUserAccount";
command.CommandType = CommandType.StoredProcedure;
int rows = await connection.ExecuteAsync(
"""
UPDATE dbo.UserAccount
SET Username = @Username, FirstName = @FirstName, LastName = @LastName,
DateOfBirth = @DateOfBirth, Email = @Email
WHERE UserAccountId = @UserAccountId
""",
new
{
UserAccountId = userAccount.UserAccountId,
userAccount.Username,
userAccount.FirstName,
userAccount.LastName,
userAccount.DateOfBirth,
userAccount.Email,
}
);
AddParameter(command, "@UserAccountId", userAccount.UserAccountId);
AddParameter(command, "@Username", userAccount.Username);
AddParameter(command, "@FirstName", userAccount.FirstName);
AddParameter(command, "@LastName", userAccount.LastName);
AddParameter(command, "@Email", userAccount.Email);
AddParameter(command, "@DateOfBirth", userAccount.DateOfBirth);
await command.ExecuteNonQueryAsync();
if (rows == 0)
throw new NotFoundException("User account not found.");
}
/// <summary>Uses the <c>usp_DeleteUserAccount</c> stored procedure.</summary>
/// <inheritdoc />
public async Task DeleteAsync(Guid id)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_DeleteUserAccount";
command.CommandType = CommandType.StoredProcedure;
int rows = await connection.ExecuteAsync(
"""
DELETE FROM dbo.UserAccount
WHERE UserAccountId = @UserAccountId
""",
new { UserAccountId = id }
);
AddParameter(command, "@UserAccountId", id);
await command.ExecuteNonQueryAsync();
if (rows == 0)
throw new NotFoundException("User account not found.");
}
/// <summary>Uses the <c>usp_GetUserAccountByUsername</c> stored procedure.</summary>
/// <inheritdoc />
public async Task<UserAccount?> GetByUsernameAsync(string username)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountByUsername";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@Username", username);
await using DbDataReader reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
"""
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
FROM dbo.UserAccount
WHERE Username = @Username
""",
new { Username = username }
);
}
/// <summary>Uses the <c>usp_GetUserAccountByEmail</c> stored procedure.</summary>
/// <inheritdoc />
public async Task<UserAccount?> GetByEmailAsync(string email)
{
await using DbConnection connection = await CreateConnection();
await using DbCommand command = connection.CreateCommand();
command.CommandText = "usp_GetUserAccountByEmail";
command.CommandType = CommandType.StoredProcedure;
AddParameter(command, "@Email", email);
await using DbDataReader reader = await command.ExecuteReaderAsync();
return await reader.ReadAsync() ? MapToEntity(reader) : null;
}
protected override UserAccount MapToEntity(DbDataReader reader)
{
return new UserAccount
{
UserAccountId = reader.GetGuid(reader.GetOrdinal("UserAccountId")),
Username = reader.GetString(reader.GetOrdinal("Username")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName")),
Email = reader.GetString(reader.GetOrdinal("Email")),
CreatedAt = reader.GetDateTime(reader.GetOrdinal("CreatedAt")),
UpdatedAt = reader.IsDBNull(reader.GetOrdinal("UpdatedAt"))
? null
: reader.GetDateTime(reader.GetOrdinal("UpdatedAt")),
DateOfBirth = reader.GetDateTime(reader.GetOrdinal("DateOfBirth")),
Timer = reader.IsDBNull(reader.GetOrdinal("Timer")) ? null : (byte[])reader["Timer"],
};
}
/// <summary>Converts <c>null</c> values to <see cref="DBNull.Value" /> when adding the parameter.</summary>
private static void AddParameter(DbCommand command, string name, object? value)
{
DbParameter p = command.CreateParameter();
p.ParameterName = name;
p.Value = value ?? DBNull.Value;
command.Parameters.Add(p);
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
"""
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
FROM dbo.UserAccount
WHERE Email = @Email
""",
new { Email = email }
);
}
}