using System.Globalization; using Khaemhat.Core.Common; using Khaemhat.Core.Entities; using Khaemhat.Data.Mapping; using Khaemhat.Data.Querying; namespace Khaemhat.Data.Execution; /// /// The repository of SPEC ยง5.1 for one entity type in one unit of work. Insert, update and delete statements are /// cached per dialect (); queries go through . /// /// The entity type. /// The key type. public sealed class Repository : IRepository where T : class, IEntity, new() { private readonly UnitOfWork _unitOfWork; private readonly EntityMap _map; private readonly QueryBuilder _builder; internal Repository(UnitOfWork unitOfWork, EntityMap map) { _unitOfWork = unitOfWork; _map = map; _builder = new QueryBuilder(map, unitOfWork.Dialect); } /// public Task GetAsync(TKey id, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(id); return _unitOfWork.QuerySingleAsync(_builder.SelectByKey(id), cancellationToken); } /// public Task FindAsync(Query query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); return _unitOfWork.QuerySingleAsync(_builder.Select(query.Take(1)), cancellationToken); } /// public async Task> ListAsync(Query query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); var items = await _unitOfWork.QueryAsync(_builder.Select(query), cancellationToken).ConfigureAwait(false); long total = query.Limit is null && query.Offset == 0 ? items.Count : await CountAsync(query, cancellationToken).ConfigureAwait(false); return new PagedResult(items, total, query.Offset, query.Limit); } /// public async Task CountAsync(Query query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); return (int)await _unitOfWork.QuerySingleAsync(_builder.Count(query), cancellationToken).ConfigureAwait(false); } /// public async Task InsertAsync(T entity, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(entity); if (entity is IAuditable audit) { audit.CreatedAt = _unitOfWork.Context.UtcNow; audit.CreatedBy = _unitOfWork.Context.CurrentUser; audit.UpdatedAt = null; audit.UpdatedBy = null; audit.RowVersion = 1; } var statement = CommandCache.Get(_map, CachedStatementKind.Insert, _unitOfWork.Dialect); var parameters = Parameters(statement, entity, overrides: null); if (!_map.Key.IsIdentity) { await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken).ConfigureAwait(false); return entity.Id; } var generated = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteScalarAsync(ct), cancellationToken) .ConfigureAwait(false); var key = (TKey)ClrConverter.ConvertTo(_unitOfWork.Dialect.FromDbValue(generated, _map.Key.Type), typeof(TKey))!; entity.Id = key; return key; } /// public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(entity); var statement = CommandCache.Get(_map, CachedStatementKind.Update, _unitOfWork.Dialect); var now = _unitOfWork.Context.UtcNow; var user = _unitOfWork.Context.CurrentUser; var overrides = new Dictionary { [AuditRole.UpdatedAt] = now, [AuditRole.UpdatedBy] = user }; var parameters = Parameters(statement, entity, overrides); var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken) .ConfigureAwait(false); if (affected == 0) { var version = entity is IAuditable a ? a.RowVersion : 0; throw new ConcurrencyException(_map.Table, Convert.ToString(entity.Id, CultureInfo.InvariantCulture) ?? string.Empty, version); } if (entity is IAuditable audit) { audit.UpdatedAt = now; audit.UpdatedBy = user; audit.RowVersion++; } } /// public async Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(id); var statement = CommandCache.Get(_map, CachedStatementKind.Delete, _unitOfWork.Dialect); var parameters = new[] { new SqlParameterValue("p0", _map.Key.ToProvider(id), _map.Key.Type) }; var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken) .ConfigureAwait(false); return affected > 0; } private static List Parameters(CachedStatement statement, T entity, Dictionary? overrides) { var parameters = new List(statement.Parameters.Count); for (var i = 0; i < statement.Parameters.Count; i++) { var column = statement.Parameters[i]; var value = overrides is not null && column.Audit != AuditRole.None && overrides.TryGetValue(column.Audit, out var replaced) ? replaced : column.GetValue(entity); parameters.Add(new SqlParameterValue("p" + i.ToString(CultureInfo.InvariantCulture), column.ToProvider(value), column.Type)); } return parameters; } }