mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: support batches on embedded replicas
Execute replica batch commands in order through the existing local connection and expose their buffered results through DbDataReader. Keep replica batches non-atomic unless callers attach an explicit transaction, and keep active batch readers inside the sync-operation lifetime gate. Reset expired remote batch sessions without replaying a possibly partially applied batch. Invalidate an expired transaction stream rather than allowing later statements to escape its transaction. Tests: dotnet build Turso.Data.csproj (net8.0, net9.0, net10.0); dotnet test Turso.Tests.csproj (207 passed, 1 skipped)
This commit is contained in:
@@ -122,9 +122,9 @@ await replica.SyncAsync();
|
||||
|
||||
`Sync Interval` is the automatic pull period in seconds. `AutomaticSyncStatus` and `AutomaticSyncStatusChanged` expose waiting, running, retrying, faulted, and stopped states along with attempt times, the last pull result, the next attempt, and terminal failures. Automatic sync retries transient transport, I/O, and timeout failures twice; other failures are terminal and are also surfaced by `Close`.
|
||||
|
||||
Connection-string replicas also map `Sync Client Name`, `Sync Long Poll Timeout`, `Bootstrap If Empty`, `Partial Bootstrap Prefix`/`Query`, `Partial Sync Segment Size`/`Prefetch`, `Remote Encryption Cipher`/`Key`, `Push Operations Threshold`, `Pull Bytes Threshold`, `Force Logical MVCC Pull`, and `Sync Experimental Features` to `TursoSyncDatabaseOptions`. Local `Encryption Cipher` and `Encryption Key` do not configure remote replica encryption. Replica batches are not supported yet.
|
||||
Connection-string replicas also map `Sync Client Name`, `Sync Long Poll Timeout`, `Bootstrap If Empty`, `Partial Bootstrap Prefix`/`Query`, `Partial Sync Segment Size`/`Prefetch`, `Remote Encryption Cipher`/`Key`, `Push Operations Threshold`, `Pull Bytes Threshold`, `Force Logical MVCC Pull`, and `Sync Experimental Features` to `TursoSyncDatabaseOptions`. Local `Encryption Cipher` and `Encryption Key` do not configure remote replica encryption.
|
||||
|
||||
Remote mode also supports ADO.NET `DbBatch` for latency-sensitive workloads that should be sent in one Hrana batch:
|
||||
Direct remote and opened embedded replica connections support ADO.NET `DbBatch`:
|
||||
|
||||
```C#
|
||||
await using var batch = connection.CreateBatch();
|
||||
@@ -144,6 +144,28 @@ batch.BatchCommands.Add(select);
|
||||
await using var reader = await batch.ExecuteReaderAsync();
|
||||
```
|
||||
|
||||
Direct remote batches are sent in one Hrana request. Replica batches execute each
|
||||
command sequentially against the local replica connection and expose each result
|
||||
through `NextResult`. They are not implicitly atomic. Use an explicit transaction
|
||||
when every command must commit or roll back together:
|
||||
|
||||
```C#
|
||||
await using var transaction = await replica.BeginTransactionAsync();
|
||||
await using var batch = replica.CreateBatch();
|
||||
batch.Transaction = transaction;
|
||||
|
||||
var first = batch.CreateBatchCommand();
|
||||
first.CommandText = "INSERT INTO customers(name) VALUES ('Alice')";
|
||||
batch.BatchCommands.Add(first);
|
||||
|
||||
var second = batch.CreateBatchCommand();
|
||||
second.CommandText = "INSERT INTO customers(name) VALUES ('Bob')";
|
||||
batch.BatchCommands.Add(second);
|
||||
|
||||
await batch.ExecuteNonQueryAsync();
|
||||
await transaction.CommitAsync();
|
||||
```
|
||||
|
||||
Use `TursoSyncDatabase` when an application needs an embedded replica with explicit sync control and advanced sync configuration:
|
||||
|
||||
```C#
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Text.Json;
|
||||
using Turso.Raw.Public;
|
||||
|
||||
namespace Turso;
|
||||
@@ -87,13 +88,23 @@ public sealed class TursoBatch : DbBatch
|
||||
public override object? ExecuteScalar()
|
||||
{
|
||||
using var reader = ExecuteDbDataReader(CommandBehavior.Default);
|
||||
return reader.Read() ? reader.GetValue(0) : null;
|
||||
if (_connection?.IsRemote == true)
|
||||
return reader.Read() ? reader.GetValue(0) : null;
|
||||
|
||||
return ReadScalar(reader);
|
||||
}
|
||||
|
||||
public override async Task<object?> ExecuteScalarAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await using var reader = await ExecuteDbDataReaderAsync(CommandBehavior.Default, cancellationToken).ConfigureAwait(false);
|
||||
return await reader.ReadAsync(cancellationToken).ConfigureAwait(false) ? reader.GetValue(0) : null;
|
||||
if (_connection?.IsRemote == true)
|
||||
{
|
||||
return await reader.ReadAsync(cancellationToken).ConfigureAwait(false)
|
||||
? reader.GetValue(0)
|
||||
: null;
|
||||
}
|
||||
|
||||
return await ReadScalarAsync(reader, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public override void Prepare()
|
||||
@@ -119,7 +130,7 @@ public sealed class TursoBatch : DbBatch
|
||||
{
|
||||
var results = ExecuteBatch(wantRows: true, CancellationToken.None).GetAwaiter().GetResult();
|
||||
SetRecordsAffected(results);
|
||||
return new TursoRemoteDataReader(_connection, results, behavior);
|
||||
return CreateDataReader(results, behavior);
|
||||
}
|
||||
|
||||
protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(
|
||||
@@ -128,19 +139,159 @@ public sealed class TursoBatch : DbBatch
|
||||
{
|
||||
var results = await ExecuteBatch(wantRows: true, cancellationToken).ConfigureAwait(false);
|
||||
SetRecordsAffected(results);
|
||||
return new TursoRemoteDataReader(_connection, results, behavior);
|
||||
return await CreateDataReaderAsync(results, behavior, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private Task<IReadOnlyList<RemoteStatementResult>> ExecuteBatch(bool wantRows, CancellationToken cancellationToken)
|
||||
private async Task<IReadOnlyList<RemoteStatementResult>> ExecuteBatch(
|
||||
bool wantRows,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return Task.FromCanceled<IReadOnlyList<RemoteStatementResult>>(cancellationToken);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var connection = ValidateBatch();
|
||||
if (!connection.IsRemote)
|
||||
throw new NotSupportedException("Turso batch execution is currently supported only for remote connections.");
|
||||
if (connection.IsRemote)
|
||||
{
|
||||
return await connection
|
||||
.ExecuteRemoteBatchAsync(_batchCommands.AsReadOnly(), Timeout, wantRows, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return connection.ExecuteRemoteBatchAsync(_batchCommands.AsReadOnly(), Timeout, wantRows, cancellationToken);
|
||||
if (connection.SyncDatabase is null)
|
||||
throw new NotSupportedException("Turso batch execution requires a direct remote or embedded replica connection.");
|
||||
|
||||
var results = new List<RemoteStatementResult>(_batchCommands.Count);
|
||||
foreach (var batchCommand in _batchCommands.AsReadOnly())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using var command = new TursoCommand(connection)
|
||||
{
|
||||
CommandText = batchCommand.CommandText,
|
||||
CommandTimeout = Timeout,
|
||||
Transaction = _transaction,
|
||||
};
|
||||
foreach (TursoParameter parameter in batchCommand.Parameters)
|
||||
command.Parameters.Add(parameter);
|
||||
|
||||
results.Add(wantRows
|
||||
? await BufferResultAsync(command, cancellationToken).ConfigureAwait(false)
|
||||
: new RemoteStatementResult
|
||||
{
|
||||
AffectedRowCount = checked((ulong)Math.Max(
|
||||
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false),
|
||||
0)),
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private DbDataReader CreateDataReader(
|
||||
IReadOnlyList<RemoteStatementResult> results,
|
||||
CommandBehavior behavior)
|
||||
{
|
||||
IDisposable? syncOperation = null;
|
||||
try
|
||||
{
|
||||
if (_connection?.SyncDatabase is not null)
|
||||
syncOperation = _connection.EnterSyncOperation();
|
||||
|
||||
var reader = new TursoRemoteDataReader(_connection, results, behavior, syncOperation);
|
||||
syncOperation = null;
|
||||
return reader;
|
||||
}
|
||||
finally
|
||||
{
|
||||
syncOperation?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<DbDataReader> CreateDataReaderAsync(
|
||||
IReadOnlyList<RemoteStatementResult> results,
|
||||
CommandBehavior behavior,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
IDisposable? syncOperation = null;
|
||||
try
|
||||
{
|
||||
if (_connection?.SyncDatabase is not null)
|
||||
{
|
||||
syncOperation = await _connection
|
||||
.EnterSyncOperationAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var reader = new TursoRemoteDataReader(_connection, results, behavior, syncOperation);
|
||||
syncOperation = null;
|
||||
return reader;
|
||||
}
|
||||
finally
|
||||
{
|
||||
syncOperation?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<RemoteStatementResult> BufferResultAsync(
|
||||
TursoCommand command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var reader = await command
|
||||
.ExecuteReaderAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var columns = new List<RemoteColumn>(reader.FieldCount);
|
||||
for (var ordinal = 0; ordinal < reader.FieldCount; ordinal++)
|
||||
{
|
||||
columns.Add(new RemoteColumn
|
||||
{
|
||||
Name = reader.GetName(ordinal),
|
||||
DeclType = reader.GetDataTypeName(ordinal),
|
||||
});
|
||||
}
|
||||
|
||||
var rows = new List<List<RemoteResponseValue>>();
|
||||
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var row = new List<RemoteResponseValue>(reader.FieldCount);
|
||||
for (var ordinal = 0; ordinal < reader.FieldCount; ordinal++)
|
||||
row.Add(ToBufferedValue(reader.GetValue(ordinal)));
|
||||
rows.Add(row);
|
||||
}
|
||||
|
||||
return new RemoteStatementResult
|
||||
{
|
||||
Columns = columns,
|
||||
Rows = rows,
|
||||
AffectedRowCount = checked((ulong)Math.Max(reader.RecordsAffected, 0)),
|
||||
};
|
||||
}
|
||||
|
||||
private static RemoteResponseValue ToBufferedValue(object value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
DBNull => new RemoteResponseValue { Type = "null" },
|
||||
byte[] bytes => new RemoteResponseValue
|
||||
{
|
||||
Type = "blob",
|
||||
Base64 = Convert.ToBase64String(bytes),
|
||||
},
|
||||
double number => new RemoteResponseValue
|
||||
{
|
||||
Type = "float",
|
||||
Value = JsonSerializer.SerializeToElement(number),
|
||||
},
|
||||
long number => new RemoteResponseValue
|
||||
{
|
||||
Type = "integer",
|
||||
Value = JsonSerializer.SerializeToElement(number),
|
||||
},
|
||||
string text => new RemoteResponseValue
|
||||
{
|
||||
Type = "text",
|
||||
Value = JsonSerializer.SerializeToElement(text),
|
||||
},
|
||||
_ => throw new InvalidOperationException(
|
||||
$"Cannot buffer a batch value of type {value.GetType().FullName}."),
|
||||
};
|
||||
}
|
||||
|
||||
private TursoConnection ValidateBatch()
|
||||
@@ -181,4 +332,31 @@ public sealed class TursoBatch : DbBatch
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
private static object? ReadScalar(DbDataReader reader)
|
||||
{
|
||||
do
|
||||
{
|
||||
if (reader.FieldCount > 0 && reader.Read())
|
||||
return reader.GetValue(0);
|
||||
} while (reader.NextResult());
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<object?> ReadScalarAsync(
|
||||
DbDataReader reader,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
do
|
||||
{
|
||||
if (reader.FieldCount > 0
|
||||
&& await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return reader.GetValue(0);
|
||||
}
|
||||
} while (await reader.NextResultAsync(cancellationToken).ConfigureAwait(false));
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public class TursoConnection : DbConnection
|
||||
private TursoSyncDatabase? _syncDatabase;
|
||||
private TursoReplicaRegistry.Lease? _replicaLease;
|
||||
private TursoAutomaticSyncCoordinator? _automaticSyncCoordinator;
|
||||
private readonly HashSet<TursoDataReader> _syncReaders = [];
|
||||
private readonly HashSet<DbDataReader> _syncReaders = [];
|
||||
private readonly object _syncReadersLock = new();
|
||||
private readonly object _automaticSyncLock = new();
|
||||
private readonly System.Collections.Concurrent.ConcurrentQueue<AutomaticSyncNotification>
|
||||
@@ -52,7 +52,9 @@ public class TursoConnection : DbConnection
|
||||
? ConnectionState.Open
|
||||
: ConnectionState.Closed;
|
||||
|
||||
public override bool CanCreateBatch => _connectionOptions.IsRemote && !_connectionOptions.IsReplica;
|
||||
public override bool CanCreateBatch =>
|
||||
_connectionOptions.IsRemote && !_connectionOptions.IsReplica
|
||||
|| _syncDatabase is not null;
|
||||
|
||||
protected override DbProviderFactory DbProviderFactory => TursoFactory.Instance;
|
||||
|
||||
@@ -170,7 +172,7 @@ public class TursoConnection : DbConnection
|
||||
protected override DbBatch CreateDbBatch()
|
||||
{
|
||||
if (!CanCreateBatch)
|
||||
throw new NotSupportedException("Turso batch execution is currently supported only for remote connections.");
|
||||
throw new NotSupportedException("Turso batch execution requires a direct remote or embedded replica connection.");
|
||||
|
||||
return new TursoBatch(this);
|
||||
}
|
||||
@@ -251,13 +253,20 @@ public class TursoConnection : DbConnection
|
||||
return _syncDatabase?.EnterConnectionOperation();
|
||||
}
|
||||
|
||||
internal void RegisterSyncReader(TursoDataReader reader)
|
||||
internal async ValueTask<IDisposable?> EnterSyncOperationAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return _syncDatabase is null
|
||||
? null
|
||||
: await _syncDatabase.EnterConnectionOperationAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal void RegisterSyncReader(DbDataReader reader)
|
||||
{
|
||||
lock (_syncReadersLock)
|
||||
_syncReaders.Add(reader);
|
||||
}
|
||||
|
||||
internal void UnregisterSyncReader(TursoDataReader reader)
|
||||
internal void UnregisterSyncReader(DbDataReader reader)
|
||||
{
|
||||
lock (_syncReadersLock)
|
||||
_syncReaders.Remove(reader);
|
||||
@@ -301,8 +310,15 @@ public class TursoConnection : DbConnection
|
||||
return await remoteClient.ExecuteBatchAsync(batchCommands, commandTimeout, wantRows, closeAfter, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (TursoRemoteSqlException)
|
||||
catch (TursoRemoteSqlException exception)
|
||||
{
|
||||
if (exception.IsStreamExpired)
|
||||
{
|
||||
if (_remoteTransactionActive)
|
||||
InvalidateRemoteSession();
|
||||
else
|
||||
remoteClient.ResetSession();
|
||||
}
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
@@ -738,7 +754,7 @@ public class TursoConnection : DbConnection
|
||||
|
||||
private void CloseSyncReaders()
|
||||
{
|
||||
TursoDataReader[] readers;
|
||||
DbDataReader[] readers;
|
||||
lock (_syncReadersLock)
|
||||
readers = [.. _syncReaders];
|
||||
|
||||
|
||||
@@ -40,6 +40,11 @@ internal sealed class TursoRemoteClient : IDisposable
|
||||
|
||||
public bool HasOpenSession => _baton is not null;
|
||||
|
||||
public void ResetSession()
|
||||
{
|
||||
_baton = null;
|
||||
}
|
||||
|
||||
public async Task<RemoteStatementResult> ExecuteAsync(
|
||||
string sql,
|
||||
TursoParameterCollection parameters,
|
||||
@@ -342,11 +347,20 @@ internal sealed class TursoRemoteClient : IDisposable
|
||||
private static TursoException CreateRemoteError(RemoteError? error)
|
||||
{
|
||||
if (error is null)
|
||||
return new TursoRemoteSqlException("Remote SQL execution failed.");
|
||||
return new TursoRemoteSqlException(
|
||||
"Remote SQL execution failed.",
|
||||
remoteErrorCode: null,
|
||||
remoteErrorMessage: null);
|
||||
|
||||
return string.IsNullOrWhiteSpace(error.Code)
|
||||
? new TursoRemoteSqlException($"Remote SQL execution failed: {error.Message}")
|
||||
: new TursoRemoteSqlException($"Remote SQL execution failed: {error.Message} ({error.Code})");
|
||||
? new TursoRemoteSqlException(
|
||||
$"Remote SQL execution failed: {error.Message}",
|
||||
remoteErrorCode: null,
|
||||
error.Message)
|
||||
: new TursoRemoteSqlException(
|
||||
$"Remote SQL execution failed: {error.Message} ({error.Code})",
|
||||
error.Code,
|
||||
error.Message);
|
||||
}
|
||||
|
||||
private void UpdateSession(RemotePipelineResponse response, bool closeAfter)
|
||||
@@ -570,7 +584,26 @@ internal sealed class RemoteError
|
||||
public string? Code { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class TursoRemoteSqlException(string message) : TursoException(message);
|
||||
internal sealed class TursoRemoteSqlException(
|
||||
string message,
|
||||
string? remoteErrorCode,
|
||||
string? remoteErrorMessage) : TursoException(message)
|
||||
{
|
||||
public bool IsStreamExpired
|
||||
=> remoteErrorCode is not null
|
||||
&& (remoteErrorCode.Equals("STREAM_EXPIRED", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("STREAM_NOT_FOUND", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("BATON_EXPIRED", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("HRANA_STREAM_EXPIRED", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("HRANA_STREAM_NOT_FOUND", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("BA_STREAM_EXPIRED", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorCode.Equals("BA_STREAM_NOT_FOUND", StringComparison.OrdinalIgnoreCase))
|
||||
|| remoteErrorMessage is not null
|
||||
&& (remoteErrorMessage.Contains("stream expired", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorMessage.Contains("stream has expired", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorMessage.Contains("stream not found", StringComparison.OrdinalIgnoreCase)
|
||||
|| remoteErrorMessage.Contains("baton expired", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal sealed class RemoteBatchResult
|
||||
{
|
||||
|
||||
@@ -12,6 +12,8 @@ internal sealed class TursoRemoteDataReader : DbDataReader
|
||||
private readonly IReadOnlyList<RemoteStatementResult> _results;
|
||||
private readonly CommandBehavior _behavior;
|
||||
private readonly int _recordsAffected;
|
||||
private IDisposable? _syncOperation;
|
||||
private TursoConnection? _syncConnection;
|
||||
private int _resultIndex;
|
||||
private int _rowIndex = -1;
|
||||
private bool _isClosed;
|
||||
@@ -21,7 +23,11 @@ internal sealed class TursoRemoteDataReader : DbDataReader
|
||||
{
|
||||
}
|
||||
|
||||
public TursoRemoteDataReader(TursoConnection? connection, IReadOnlyList<RemoteStatementResult> results, CommandBehavior behavior)
|
||||
public TursoRemoteDataReader(
|
||||
TursoConnection? connection,
|
||||
IReadOnlyList<RemoteStatementResult> results,
|
||||
CommandBehavior behavior,
|
||||
IDisposable? syncOperation = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(results);
|
||||
|
||||
@@ -30,6 +36,13 @@ internal sealed class TursoRemoteDataReader : DbDataReader
|
||||
_behavior = behavior;
|
||||
foreach (var result in results)
|
||||
_recordsAffected = checked(_recordsAffected + (int)result.AffectedRowCount);
|
||||
|
||||
_syncOperation = syncOperation;
|
||||
if (syncOperation is not null && connection is not null)
|
||||
{
|
||||
_syncConnection = connection;
|
||||
connection.RegisterSyncReader(this);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool GetBoolean(int ordinal)
|
||||
@@ -229,8 +242,15 @@ internal sealed class TursoRemoteDataReader : DbDataReader
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && !_isClosed && (_behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection)
|
||||
_connection?.Close();
|
||||
if (disposing && !_isClosed)
|
||||
{
|
||||
_syncOperation?.Dispose();
|
||||
_syncOperation = null;
|
||||
_syncConnection?.UnregisterSyncReader(this);
|
||||
_syncConnection = null;
|
||||
if ((_behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection)
|
||||
_connection?.Close();
|
||||
}
|
||||
|
||||
_isClosed = true;
|
||||
base.Dispose(disposing);
|
||||
|
||||
@@ -268,6 +268,14 @@ public sealed class TursoSyncDatabase : IDisposable, IAsyncDisposable
|
||||
return new ConnectionOperationLease(_operationLock);
|
||||
}
|
||||
|
||||
internal async ValueTask<IDisposable> EnterConnectionOperationAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ThrowIfIoReentrant();
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _resourcesDisposed) != 0, this);
|
||||
await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ConnectionOperationLease(_operationLock);
|
||||
}
|
||||
|
||||
internal void ThrowIfIoReentrant()
|
||||
{
|
||||
if (_ioCallbackDepth.Value != 0)
|
||||
|
||||
@@ -75,13 +75,13 @@ public class TursoRemoteTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestCanCreateBatchIsRemoteOnly()
|
||||
public void TestCanCreateBatchRejectsLocalConnections()
|
||||
{
|
||||
using var localConnection = new TursoConnection("Data Source=:memory:");
|
||||
localConnection.CanCreateBatch.Should().BeFalse();
|
||||
localConnection.Invoking(x => x.CreateBatch())
|
||||
.Should().Throw<NotSupportedException>()
|
||||
.WithMessage("Turso batch execution is currently supported only for remote connections.");
|
||||
.WithMessage("Turso batch execution requires a direct remote or embedded replica connection.");
|
||||
|
||||
using var remoteConnection = new TursoConnection("Data Source=https://example.com");
|
||||
remoteConnection.CanCreateBatch.Should().BeTrue();
|
||||
@@ -1170,6 +1170,131 @@ public class TursoRemoteTests
|
||||
.WithMessage("Remote batch returned an unexpected result shape: 1 results, 0 errors, expected 1.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestPartiallyEvaluatedExpiredBatchIsNotRetried()
|
||||
{
|
||||
const string expiredBatchJson = """
|
||||
{
|
||||
"baton": "stale",
|
||||
"results": [{
|
||||
"type": "ok",
|
||||
"response": {
|
||||
"type": "batch",
|
||||
"result": {
|
||||
"step_results": [
|
||||
{ "cols": [], "rows": [], "affected_row_count": 1 },
|
||||
null
|
||||
],
|
||||
"step_errors": [
|
||||
null,
|
||||
{ "message": "stream expired", "code": "STREAM_EXPIRED" }
|
||||
]
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
""";
|
||||
const string executeJson = """
|
||||
{
|
||||
"baton": "fresh",
|
||||
"results": [{
|
||||
"type": "ok",
|
||||
"response": {
|
||||
"type": "execute",
|
||||
"result": {
|
||||
"cols": [{ "name": "value", "decltype": "INTEGER" }],
|
||||
"rows": [[{ "type": "integer", "value": "2" }]],
|
||||
"affected_row_count": 0
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
""";
|
||||
const string closeJson = """
|
||||
{
|
||||
"results": [{
|
||||
"type": "ok",
|
||||
"response": { "type": "close" }
|
||||
}]
|
||||
}
|
||||
""";
|
||||
|
||||
using var server = new TestRemoteServer(expiredBatchJson, executeJson, closeJson);
|
||||
using var connection = new TursoConnection($"Data Source={server.Url};Read Your Writes=True");
|
||||
connection.Open();
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (1)"));
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (2)"));
|
||||
|
||||
var batchAction = async () => await batch.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
|
||||
await batchAction.Should().ThrowAsync<TursoException>()
|
||||
.WithMessage("Remote SQL execution failed: stream expired (STREAM_EXPIRED)");
|
||||
using var command = new TursoCommand(connection, "SELECT 2");
|
||||
(await command.ExecuteScalarAsync()).Should().Be(2L);
|
||||
server.RequestBodies.Should().HaveCount(2);
|
||||
using var nextRequest = JsonDocument.Parse(server.RequestBodies[1]);
|
||||
nextRequest.RootElement.TryGetProperty("baton", out _).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestExpiredBatchClosesAnActiveRemoteTransaction()
|
||||
{
|
||||
const string beginJson = """
|
||||
{
|
||||
"baton": "transaction",
|
||||
"results": [{
|
||||
"type": "ok",
|
||||
"response": {
|
||||
"type": "execute",
|
||||
"result": {
|
||||
"cols": [],
|
||||
"rows": [],
|
||||
"affected_row_count": 0
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
""";
|
||||
const string expiredBatchJson = """
|
||||
{
|
||||
"baton": "stale",
|
||||
"results": [{
|
||||
"type": "ok",
|
||||
"response": {
|
||||
"type": "batch",
|
||||
"result": {
|
||||
"step_results": [
|
||||
{ "cols": [], "rows": [], "affected_row_count": 1 },
|
||||
null
|
||||
],
|
||||
"step_errors": [
|
||||
null,
|
||||
{ "message": "stream expired", "code": "STREAM_EXPIRED" }
|
||||
]
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
""";
|
||||
|
||||
using var server = new TestRemoteServer(beginJson, expiredBatchJson);
|
||||
using var connection = new TursoConnection($"Data Source={server.Url};Read Your Writes=True");
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.Transaction = transaction;
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (1)"));
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (2)"));
|
||||
|
||||
var batchAction = async () => await batch.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
|
||||
await batchAction.Should().ThrowAsync<TursoException>()
|
||||
.WithMessage("Remote SQL execution failed: stream expired (STREAM_EXPIRED)");
|
||||
connection.State.Should().Be(System.Data.ConnectionState.Closed);
|
||||
server.RequestBodies.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestSyncRequiresReplicaConnection()
|
||||
{
|
||||
|
||||
171
bindings/dotnet/src/Turso.Tests/TursoReplicaBatchTests.cs
Normal file
171
bindings/dotnet/src/Turso.Tests/TursoReplicaBatchTests.cs
Normal file
@@ -0,0 +1,171 @@
|
||||
using AwesomeAssertions;
|
||||
using Turso.Raw.Public;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
public sealed class TursoReplicaBatchTests
|
||||
{
|
||||
[Test]
|
||||
public async Task ReplicaBatchReturnsOrderedResultsAndAffectedRows()
|
||||
{
|
||||
using var unopenedReplica = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False");
|
||||
unopenedReplica.CanCreateBatch.Should().BeFalse();
|
||||
|
||||
await using var database = await CreateDatabaseAsync();
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.CanCreateBatch.Should().BeTrue();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)");
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
|
||||
var insert = new TursoBatchCommand("INSERT INTO items(name) VALUES ($name)");
|
||||
insert.Parameters.AddWithValue("$name", "alice");
|
||||
batch.BatchCommands.Add(insert);
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("SELECT id, name FROM items ORDER BY id"));
|
||||
|
||||
await using var reader = await batch.ExecuteReaderAsync();
|
||||
|
||||
reader.Read().Should().BeFalse();
|
||||
reader.NextResult().Should().BeTrue();
|
||||
reader.Read().Should().BeTrue();
|
||||
reader.GetInt64(0).Should().Be(1);
|
||||
reader.GetString(1).Should().Be("alice");
|
||||
reader.Read().Should().BeFalse();
|
||||
reader.NextResult().Should().BeFalse();
|
||||
insert.RecordsAffected.Should().Be(1);
|
||||
batch.BatchCommands[1].RecordsAffected.Should().Be(0);
|
||||
reader.RecordsAffected.Should().Be(1);
|
||||
await reader.DisposeAsync();
|
||||
|
||||
await using var scalarBatch = (TursoBatch)connection.CreateBatch();
|
||||
scalarBatch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items(name) VALUES ('bob')"));
|
||||
scalarBatch.BatchCommands.Add(new TursoBatchCommand("SELECT name FROM items WHERE id = 2"));
|
||||
(await scalarBatch.ExecuteScalarAsync(CancellationToken.None)).Should().Be("bob");
|
||||
}
|
||||
|
||||
[TestCase(true)]
|
||||
[TestCase(false)]
|
||||
public async Task ReplicaBatchParticipatesInExplicitTransaction(bool commit)
|
||||
{
|
||||
await using var database = await CreateDatabaseAsync();
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
using var transaction = (TursoTransaction)connection.BeginTransaction();
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.Transaction = transaction;
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (1)"));
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (2)"));
|
||||
|
||||
(await batch.ExecuteNonQueryAsync(CancellationToken.None)).Should().Be(2);
|
||||
if (commit)
|
||||
transaction.Commit();
|
||||
else
|
||||
transaction.Rollback();
|
||||
|
||||
using var count = new TursoCommand(connection, "SELECT COUNT(*) FROM items");
|
||||
count.ExecuteScalar().Should().Be(commit ? 2L : 0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReplicaBatchWithoutTransactionStopsAfterFailureWithoutRollingBackPriorCommands()
|
||||
{
|
||||
await using var database = await CreateDatabaseAsync();
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (1)"));
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO missing VALUES (2)"));
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (3)"));
|
||||
|
||||
var action = async () => await batch.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
|
||||
await action.Should().ThrowAsync<TursoException>();
|
||||
using var values = new TursoCommand(connection, "SELECT group_concat(value) FROM items");
|
||||
values.ExecuteScalar().Should().Be("1");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CanceledReplicaBatchDoesNotExecuteCommands()
|
||||
{
|
||||
await using var database = await CreateDatabaseAsync();
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("INSERT INTO items VALUES (1)"));
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
|
||||
var action = async () => await batch.ExecuteNonQueryAsync(cancellation.Token);
|
||||
|
||||
await action.Should().ThrowAsync<OperationCanceledException>();
|
||||
using var count = new TursoCommand(connection, "SELECT COUNT(*) FROM items");
|
||||
count.ExecuteScalar().Should().Be(0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ActiveReplicaBatchReaderBlocksSyncUntilDisposed()
|
||||
{
|
||||
var handler = new BlockingHttpHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
await using var database = await CreateDatabaseAsync(httpClient);
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("SELECT 1"));
|
||||
var reader = await batch.ExecuteReaderAsync();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
var pull = database.PullAsync(cancellation.Token);
|
||||
await Task.Delay(100);
|
||||
|
||||
handler.RequestStarted.Task.IsCompleted.Should().BeFalse();
|
||||
await reader.DisposeAsync();
|
||||
await handler.RequestStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
cancellation.Cancel();
|
||||
var pullAction = async () => await pull;
|
||||
await pullAction.Should().ThrowAsync<OperationCanceledException>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClosingReplicaClosesActiveBatchReader()
|
||||
{
|
||||
await using var database = await CreateDatabaseAsync();
|
||||
var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
await using var batch = (TursoBatch)connection.CreateBatch();
|
||||
batch.BatchCommands.Add(new TursoBatchCommand("SELECT 1"));
|
||||
var reader = await batch.ExecuteReaderAsync();
|
||||
|
||||
connection.Close();
|
||||
|
||||
reader.IsClosed.Should().BeTrue();
|
||||
connection.State.Should().Be(System.Data.ConnectionState.Closed);
|
||||
await reader.DisposeAsync();
|
||||
await connection.DisposeAsync();
|
||||
}
|
||||
|
||||
private static Task<TursoSyncDatabase> CreateDatabaseAsync(HttpClient? httpClient = null)
|
||||
{
|
||||
return TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class BlockingHttpHandler : HttpMessageHandler
|
||||
{
|
||||
public TaskCompletionSource RequestStarted { get; } =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestStarted.TrySetResult();
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
|
||||
throw new InvalidOperationException("The blocking sync request unexpectedly completed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user