using System.Data.Common;
using Khaemhat.Core.Entities;
namespace Khaemhat.Data;
///
/// An open connection to one database, with an optional explicit transaction (SPEC §5.1). Application services open
/// one per operation, call for writes that must be atomic, and dispose it; a transaction not
/// committed is rolled back on dispose.
///
public interface IUnitOfWork : IAsyncDisposable
{
/// The open connection.
DbConnection Connection { get; }
/// The current transaction, if any.
DbTransaction? Transaction { get; }
/// The dialect of the database.
ISqlDialect Dialect { get; }
/// Starts a transaction. On SQLite it also enters the write scope of the database.
/// Cancellation.
/// A task.
Task BeginAsync(CancellationToken cancellationToken = default);
/// Commits the transaction.
/// Cancellation.
/// A task.
Task CommitAsync(CancellationToken cancellationToken = default);
/// Rolls back the transaction.
/// Cancellation.
/// A task.
Task RollbackAsync(CancellationToken cancellationToken = default);
/// The repository of an entity type.
/// The entity type, which needs a registered map.
/// The key type.
/// The repository.
IRepository Repository()
where T : class, IEntity, new();
/// Executes a statement that changes data or schema.
/// The statement.
/// Cancellation.
/// The number of affected rows.
Task ExecuteAsync(SqlFragment sql, CancellationToken cancellationToken = default);
/// Reads the first row (or ), mapped to .
/// A scalar, a mapped entity, or a class/record whose members match the columns by snake_case name.
/// The query.
/// Cancellation.
/// The row, or .
Task QuerySingleAsync(SqlFragment sql, CancellationToken cancellationToken = default);
/// Reads all rows, mapped to .
/// A scalar, a mapped entity, or a class/record whose members match the columns by snake_case name.
/// The query.
/// Cancellation.
/// The rows.
Task> QueryAsync(SqlFragment sql, CancellationToken cancellationToken = default);
///
/// Opens a reader for large results (exports, reports) without loading them in memory. Dispose the reader before
/// running anything else on this unit of work. Values are raw driver values: convert them with
/// .
///
/// The query.
/// Cancellation.
/// The reader.
Task StreamAsync(SqlFragment sql, CancellationToken cancellationToken = default);
}
/// Opens units of work on the system database or on a company database (SPEC §5.1).
public interface IUnitOfWorkFactory
{
/// Opens a unit of work.
/// The system database, or a company.
/// Cancellation.
/// The open unit of work.
Task CreateAsync(DatabaseScope scope, CancellationToken cancellationToken = default);
}
/// Finds the database of a scope: the system database, or a company through the registry.
public interface IDatabaseLocator
{
/// The database of a scope.
/// The scope.
/// Cancellation.
/// The target.
ValueTask LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default);
}