56 lines
2.3 KiB
C#
56 lines
2.3 KiB
C#
using Dapper;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace NTP.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// Thin Dapper wrapper: every call automatically uses the scoped connection, enlists in the active
|
|
/// transaction, applies the configured command timeout and honours the CancellationToken.
|
|
/// Dapper sets OracleCommand.BindByName = true, so :Name parameters bind by name, not position.
|
|
/// </summary>
|
|
public abstract class OracleRepositoryBase(IDbSession session, ILogger logger)
|
|
{
|
|
protected IDbSession Session { get; } = session;
|
|
|
|
private CommandDefinition Command(string sql, object? param, CancellationToken ct)
|
|
{
|
|
if (logger.IsEnabled(LogLevel.Debug))
|
|
logger.LogDebug("Oracle SQL: {Sql}", sql);
|
|
|
|
return new CommandDefinition(sql, param, Session.Transaction, Session.CommandTimeoutSeconds,
|
|
cancellationToken: ct);
|
|
}
|
|
|
|
protected async Task<IReadOnlyList<T>> QueryAsync<T>(string sql, object? param = null, CancellationToken ct = default)
|
|
{
|
|
var connection = await Session.GetConnectionAsync(ct);
|
|
var rows = await connection.QueryAsync<T>(Command(sql, param, ct));
|
|
return rows.AsList();
|
|
}
|
|
|
|
protected async Task<T?> QuerySingleOrDefaultAsync<T>(string sql, object? param = null, CancellationToken ct = default)
|
|
{
|
|
var connection = await Session.GetConnectionAsync(ct);
|
|
return await connection.QuerySingleOrDefaultAsync<T>(Command(sql, param, ct));
|
|
}
|
|
|
|
/// <summary>First row or default (use with an ORDER BY for determinism).</summary>
|
|
protected async Task<T?> QueryFirstAsync<T>(string sql, object? param = null, CancellationToken ct = default)
|
|
{
|
|
var connection = await Session.GetConnectionAsync(ct);
|
|
return await connection.QueryFirstOrDefaultAsync<T>(Command(sql, param, ct));
|
|
}
|
|
|
|
protected async Task<T> ExecuteScalarAsync<T>(string sql, object? param = null, CancellationToken ct = default)
|
|
{
|
|
var connection = await Session.GetConnectionAsync(ct);
|
|
return (await connection.ExecuteScalarAsync<T>(Command(sql, param, ct)))!;
|
|
}
|
|
|
|
protected async Task<int> ExecuteAsync(string sql, object? param = null, CancellationToken ct = default)
|
|
{
|
|
var connection = await Session.GetConnectionAsync(ct);
|
|
return await connection.ExecuteAsync(Command(sql, param, ct));
|
|
}
|
|
}
|