Path: redb/redb.Core/Data/IRedbConnection.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Data/IRedbConnection.cs ---- using System; using System.Collections.Generic; using System.Data.Common; using System.Threading; using System.Threading.Tasks; namespace redb.Core.Data { /// /// Database connection abstraction for REDB. /// Replaces DbContext with pure ADO.NET approach. /// All methods automatically use CurrentTransaction if active. /// public interface IRedbConnection : IAsyncDisposable, IDisposable { /// True once the connection has been disposed - its scope has ended (V4, review). bool IsDisposed { get; } /// /// Connection string used for this connection. /// string ConnectionString { get; } /// /// Currently active transaction (null if no transaction). /// All operations automatically use this transaction. /// IRedbTransaction? CurrentTransaction { get; } /// /// Whether any transaction is active — explicit (CurrentTransaction) or ambient (TransactionScope). /// Use this instead of checking CurrentTransaction directly. /// EF Core pattern: checks both CurrentTransaction and Transaction.Current. /// bool IsInTransaction { get; } /// /// Get underlying DbConnection for advanced operations (e.g., COPY protocol). /// This ensures all operations use the same connection and transaction. /// Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default); /// /// Lends the connection this redb connection works on for the caller's own commands, in the transaction /// redb's commands run in: redb's explicit transaction (, /// ), else the ambient /// (its one connection per database), else no transaction. /// Build the commands with : it binds the transaction the /// driver requires (SQLite always, SQL Server in an explicit transaction). /// /// The lease enters the same command gates a redb command enters, so it is one command's hold: release it /// with await using as soon as the commands are done. While it is held, redb on this connection or in /// the same ambient transaction is refused at once. What the holder must never do is listed on /// . /// /// /// The lease is on this connection only, so on the connection of the redb service the caller resolved. A named /// redb service has a connection of its own; an explicit transaction belongs to the DI scope that began it, and a /// connection of another scope lends its own connection outside that transaction. Inside a /// every scope of the same database lends the scope's /// connection. /// /// /// For a long-lived owner of the connection (EF Core, PostgreSQL COPY, SqlBulkCopy) use /// instead: it holds no gate, so its work and redb's must run /// strictly one after the other. /// /// /// The default body throws : a connection outside the redb providers /// has to lend its connection itself. /// /// /// Cancels opening the connection. Task LeaseAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException( $"{GetType().FullName} does not lend its connection: implement IRedbConnection.LeaseAsync."); // === QUERY METHODS === /// /// Execute SQL query and return list of mapped objects. /// /// Result type (must have parameterless constructor). /// SQL query with parameters ($1, $2, etc.). /// Query parameters. /// List of mapped objects. Task> QueryAsync(string sql, params object[] parameters) where T : new(); /// Cancellable form: parameters as an explicit array (params cannot precede ct). Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new(); /// /// Execute SQL query and return first result or null. /// /// Result type. /// SQL query with parameters. /// Query parameters. /// First result or null. Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new(); /// Cancellable form. Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new(); /// /// Execute SQL query and return scalar value. /// /// Scalar type. /// SQL query with parameters. /// Query parameters. /// Scalar value or default. Task ExecuteScalarAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === SYNCHRONOUS COUNTERPARTS (thread-pool-free lazy path) === // The sync getter of RedbListItem.Object must reach the database without a single // thread-pool continuation: on a saturated pool a blocked thread waiting for pool-scheduled // continuations degrades (or, pre-2026-09 fixes, deadlocks). These run the whole call on // the calling thread down to ADO.NET. The defaults fall back to blocking on the async // form, so third-party implementations keep compiling - but the fallback is pool-coupled; // the in-tree providers override with true sync ADO calls. /// Synchronous : runs on the calling thread down to ADO.NET. T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new() => QueryFirstOrDefaultAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. T? ExecuteScalar(string sql, params object[] parameters) => ExecuteScalarAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. string? ExecuteJson(string sql, params object[] parameters) => ExecuteJsonAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. List Query(string sql, params object[] parameters) where T : new() => QueryAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// Synchronous : runs on the calling thread down to ADO.NET. int Execute(string sql, params object[] parameters) => ExecuteAsync(sql, parameters).ConfigureAwait(false).GetAwaiter().GetResult(); /// /// Execute SQL query and return list of scalar values (first column only). /// Use for simple queries like SELECT _id FROM ... that return single column. /// /// Scalar type (long, int, string, etc.). /// SQL query with parameters. /// Query parameters. /// List of scalar values. Task> QueryScalarListAsync(string sql, params object[] parameters); /// Cancellable form. Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute SQL command (INSERT, UPDATE, DELETE) and return affected rows count. /// /// SQL command with parameters. /// Command parameters. /// Number of affected rows. Task ExecuteAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken); // === TRANSACTION METHODS === /// /// Begin new transaction. /// Sets CurrentTransaction property. /// All subsequent operations will use this transaction. /// /// Transaction object. /// /// BR-1 (owner decision 2026-09-02): optional isolation level for THIS transaction. Null keeps /// each provider's default, exactly as before. PostgreSQL/MSSQL apply it to the opened /// transaction; SQLite accepts it for portability and stays a single serial writer. Under /// elevated levels the database may abort the loser (PG 40001, MSSQL 3960): retry the WHOLE /// transaction - see DbErrorClassifier.IsSerializationFailure. /// Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default); // === ATOMIC OPERATIONS (SaveChanges replacement) === /// /// Execute multiple operations atomically (all-or-nothing). /// If no transaction is active, creates one automatically. /// Ensures atomicity like EF SaveChanges(). /// /// Operations to execute atomically. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default); /// /// Atomic execution under an explicit isolation level (BR-1). An active or ambient transaction /// wins: operations join it and its level is NOT changed. /// Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default); /// /// Execute multiple operations atomically and return result. /// If no transaction is active, creates one automatically. /// /// Result type. /// Operations to execute atomically. /// Operation result. /// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes). Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default); /// Result-returning form of the isolation-level overload (BR-1). Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default); // === RAW SQL === /// /// Execute raw SQL function returning JSON. /// Commonly used for PostgreSQL functions like get_object_json(). /// /// SQL query returning JSON. /// Query parameters. /// JSON string or null. Task ExecuteJsonAsync(string sql, params object[] parameters); /// Cancellable form. Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken); /// /// Execute raw SQL function returning multiple JSON rows. /// /// SQL query returning JSON rows. /// Query parameters. /// List of JSON strings. Task> ExecuteJsonListAsync(string sql, params object[] parameters); /// Cancellable form. Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken); } }