bindings/dotnet: add HTTP client packages

Add managed clients for the Turso Platform API and serverless SQL-over-HTTP workloads.

Generate the Platform client during MSBuild from the pinned OpenAPI specification, keep generated artifacts out of version control, and use cross-platform generation paths.

Include package metadata, NuGet publishing integration, and regression coverage for Platform extensions plus Serverless transaction and lifecycle behavior.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Marc-André Moreau
2026-07-13 11:05:38 -04:00
parent 3e1301213a
commit 1e9754dcb2
23 changed files with 5626 additions and 1 deletions

View File

@@ -429,6 +429,8 @@ jobs:
files=(
src/Turso.Data.Sqlite/bin/Release/Turso.Data.Sqlite.*.nupkg
src/Turso.Data.Sqlite.NativeAot/bin/Release/Turso.Data.Sqlite.NativeAot.*.nupkg
src/Turso.Platform.Client/bin/Release/Turso.Platform.Client.*.nupkg
src/Turso.Serverless.Client/bin/Release/Turso.Serverless.Client.*.nupkg
)
if [ ${#files[@]} -eq 0 ]; then
echo "No NuGet packages found to upload"

View File

@@ -484,4 +484,8 @@ $RECYCLE.BIN/
*.swp
src/Turso.Native/*
rs_compiled/*
rs_compiled/*
# Derived from Turso.Platform.Client/openapi.json during MSBuild compilation.
src/Turso.Platform.Client/TursoPlatformClient.generated.cs
src/Turso.Platform.Client/openapi.transformed.json

View File

@@ -109,6 +109,12 @@ build-dotnet:
dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Data/Turso.Data.csproj
dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Data.Sqlite/Turso.Data.Sqlite.csproj
dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.EntityFrameworkCore.Sqlite/Turso.EntityFrameworkCore.Sqlite.csproj
dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Platform.Client/Turso.Platform.Client.csproj
dotnet build $(DOTNET_RELEASE_OPT) ./src/Turso.Serverless.Client/Turso.Serverless.Client.csproj
# Generate the Turso Platform API client from the pinned OpenAPI spec.
generate-platform-client:
dotnet build ./src/Turso.Platform.Client/Turso.Platform.Client.csproj
build: build-rust build-dotnet
@@ -133,3 +139,5 @@ pack:
dotnet pack -c Release ./src/Turso.Data.Sqlite/Turso.Data.Sqlite.csproj
dotnet pack -c Release ./src/Turso.EntityFrameworkCore.Sqlite/Turso.EntityFrameworkCore.Sqlite.csproj
$(MAKE) pack-nativeaot-static
dotnet pack -c Release ./src/Turso.Platform.Client/Turso.Platform.Client.csproj
dotnet pack -c Release ./src/Turso.Serverless.Client/Turso.Serverless.Client.csproj

View File

@@ -19,5 +19,7 @@
<Project Path="src\Turso.Data.Sqlite\Turso.Data.Sqlite.csproj" />
<Project Path="src\Turso.EntityFrameworkCore.Sqlite\Turso.EntityFrameworkCore.Sqlite.csproj" />
<Project Path="src\Turso.Data\Turso.Data.csproj" />
<Project Path="src\Turso.Platform.Client\Turso.Platform.Client.csproj" />
<Project Path="src\Turso.Serverless.Client\Turso.Serverless.Client.csproj" />
<Project Path="src\Turso.Raw\Turso.Raw.csproj" Type="Classic C#" />
</Solution>

View File

@@ -0,0 +1,57 @@
# Turso.Platform.Client
.NET client for the [Turso Platform API](https://docs.turso.tech/api-reference/introduction) (`https://api.turso.tech`): manage databases, groups, auth tokens, organizations, members and invites.
Unlike the `Turso` and `Turso.Data.Sqlite` packages, this is a pure managed HTTP client — it has no native component.
## Getting started
```C#
using Turso.Platform.Client;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", platformApiToken);
var client = new TursoPlatformClient(httpClient);
// Create a database
var created = await client.CreateDatabaseAsync(organizationSlug, new CreateDatabaseInput
{
Name = "my-database",
Group = "default",
});
// Mint a database auth token
var token = await client.CreateDatabaseTokenAsync(organizationSlug, "my-database");
// List databases
var databases = await client.ListDatabasesAsync(organizationSlug);
```
The client is generated with [NSwag](https://github.com/RicoSuter/NSwag) from the official OpenAPI specification published in [tursodatabase/turso-docs](https://github.com/tursodatabase/turso-docs) (`api-reference/openapi.json`).
## Regenerating the client
The pinned upstream spec lives at `openapi.json` next to this file and is kept byte-identical to
the published one. Because the spec leaves its request/response schemas anonymous, NSwag would
generate counter names (`Response17`, `Body3`); the `tools/OpenApiTitler` project first derives
proper names from each `operationId` (`ListDatabasesResponse`, `CreateGroupRequest`) and collapses
the repeated `{ error: string }` payloads into one shared `ErrorResponse`.
Every `dotnet build`, test, or pack generates the transformed document and C# client under the
project's ignored `obj` directory. The build uses the version-pinned `NSwag.MSBuild` package, so it
does not require a globally installed NSwag CLI.
To refresh the tracked spec and regenerate during the next build:
```bash
curl -sL https://raw.githubusercontent.com/tursodatabase/turso-docs/main/api-reference/openapi.json -o openapi.json
dotnet build
```
(or `make generate-platform-client` from `bindings/dotnet`).
`TursoPlatformClient.Supplement.cs` contains the hand-written `Extensions` union NSwag cannot generate. Use `Extensions.All` to enable every extension or `Extensions.FromNames(...)` for an explicit list.
Spec pinned from turso-docs commit `ac44bfab64a7` (2026-06-08).

View File

@@ -0,0 +1,56 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>$(TursoTargetFrameworks)</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Turso.Platform.Client</RootNamespace>
<PackageId>Turso.Platform.Client</PackageId>
<Title>Turso Platform API Client</Title>
<Description>HTTP client for the Turso Platform API (api.turso.tech): manage databases, groups, auth tokens, organizations and members. Generated from the official OpenAPI specification.</Description>
<Authors>Turso authors</Authors>
<PackageTags>turso;database;platform;api;client</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/tursodatabase/turso</PackageProjectUrl>
<RepositoryUrl>https://github.com/tursodatabase/turso</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
<TransformedOpenApiDocument>$(MSBuildProjectDirectory)/obj/$(TargetFramework)/openapi.transformed.json</TransformedOpenApiDocument>
<GeneratedClientSource>$(MSBuildProjectDirectory)/obj/$(TargetFramework)/TursoPlatformClient.generated.cs</GeneratedClientSource>
</PropertyGroup>
<ItemGroup>
<!-- The OpenApiTitler tool is its own project; keep it out of this assembly's compile glob. -->
<Compile Remove="tools/**" />
<None Remove="tools/**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NSwag.MSBuild" Version="14.7.1" PrivateAssets="all" />
<Compile Include="$(GeneratedClientSource)" Visible="false" />
</ItemGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="README.md" />
<None Include="openapi.json" />
<None Include="nswag.json" />
</ItemGroup>
<Target Name="GeneratePlatformClient"
BeforeTargets="CoreCompile"
Inputs="$(MSBuildProjectFullPath);openapi.json;nswag.json;tools/OpenApiTitler/Program.cs;tools/OpenApiTitler/OpenApiTitler.csproj"
Outputs="$(TransformedOpenApiDocument);$(GeneratedClientSource)">
<MakeDir Directories="$(MSBuildProjectDirectory)/obj/$(TargetFramework)" />
<Exec Command="dotnet run --project &quot;$(MSBuildProjectDirectory)/tools/OpenApiTitler/OpenApiTitler.csproj&quot; --configuration $(Configuration) --no-launch-profile -p:BaseIntermediateOutputPath=$(MSBuildProjectDirectory)/obj/$(Configuration)/$(TargetFramework)/OpenApiTitler/obj/ -p:BaseOutputPath=$(MSBuildProjectDirectory)/obj/$(Configuration)/$(TargetFramework)/OpenApiTitler/bin/ -- &quot;$(MSBuildProjectDirectory)/openapi.json&quot; &quot;$(TransformedOpenApiDocument)&quot;" />
<Exec Command="$(NSwagExe_Net90) run &quot;$(MSBuildProjectDirectory)/nswag.json&quot; &quot;/variables:OpenApiDocument=$(TransformedOpenApiDocument),GeneratedClientSource=$(GeneratedClientSource)&quot;" />
</Target>
<Target Name="CleanGeneratedPlatformClient" AfterTargets="CoreClean">
<Delete Files="$(TransformedOpenApiDocument);$(GeneratedClientSource)" />
</Target>
</Project>

View File

@@ -0,0 +1,53 @@
namespace Turso.Platform.Client;
/// <summary>
/// The group-extension union from the Platform API. It is serialized as either the string
/// <c>"all"</c> or an array of extension names.
/// </summary>
[System.Text.Json.Serialization.JsonConverter(typeof(ExtensionsJsonConverter))]
public partial class Extensions
{
private Extensions(IReadOnlyList<string>? names)
{
Names = names;
}
/// <summary>Enables all extensions available to the group.</summary>
public static Extensions All { get; } = new(null);
/// <summary>Enables only the supplied extension names.</summary>
public static Extensions FromNames(IEnumerable<string> names)
{
ArgumentNullException.ThrowIfNull(names);
return new Extensions(names.ToArray());
}
/// <summary>The explicitly enabled extension names, or <see langword="null"/> for <see cref="All"/>.</summary>
public IReadOnlyList<string>? Names { get; }
}
internal sealed class ExtensionsJsonConverter : System.Text.Json.Serialization.JsonConverter<Extensions>
{
public override Extensions Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
{
return reader.TokenType switch
{
System.Text.Json.JsonTokenType.String when reader.GetString() == "all" => Extensions.All,
System.Text.Json.JsonTokenType.StartArray => Extensions.FromNames(
System.Text.Json.JsonSerializer.Deserialize<string[]>(ref reader, options)
?? throw new System.Text.Json.JsonException("Extensions array cannot be null.")),
_ => throw new System.Text.Json.JsonException("Extensions must be \"all\" or an array of extension names."),
};
}
public override void Write(System.Text.Json.Utf8JsonWriter writer, Extensions value, System.Text.Json.JsonSerializerOptions options)
{
if (value.Names is null)
{
writer.WriteStringValue("all");
return;
}
System.Text.Json.JsonSerializer.Serialize(writer, value.Names, options);
}
}

View File

@@ -0,0 +1,95 @@
{
"runtime": "Net90",
"defaultVariables": null,
"documentGenerator": {
"fromDocument": {
"json": null,
"url": "$(OpenApiDocument)",
"output": null,
"newLineBehavior": "Auto"
}
},
"codeGenerators": {
"openApiToCSharpClient": {
"clientBaseClass": null,
"configurationClass": null,
"generateClientClasses": true,
"generateClientInterfaces": true,
"clientBaseInterface": null,
"injectHttpClient": true,
"disposeHttpClient": false,
"protectedMethods": [],
"generateExceptionClasses": true,
"exceptionClass": "TursoPlatformApiException",
"wrapDtoExceptions": true,
"useHttpClientCreationMethod": false,
"httpClientType": "System.Net.Http.HttpClient",
"useHttpRequestMessageCreationMethod": false,
"useBaseUrl": true,
"generateBaseUrlProperty": true,
"generateSyncMethods": false,
"generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
"exposeJsonSerializerSettings": false,
"clientClassAccessModifier": "public",
"typeAccessModifier": "public",
"generateContractsOutput": false,
"parameterDateTimeFormat": "s",
"parameterDateFormat": "yyyy-MM-dd",
"generateUpdateJsonSerializerSettingsMethod": true,
"useRequestAndResponseSerializationSettings": false,
"serializeTypeInformation": false,
"queryNullValue": "",
"className": "TursoPlatformClient",
"operationGenerationMode": "SingleClientFromOperationId",
"additionalNamespaceUsages": [],
"additionalContractNamespaceUsages": [],
"generateOptionalParameters": true,
"generateJsonMethods": false,
"enforceFlagEnums": false,
"parameterArrayType": "System.Collections.Generic.IEnumerable",
"parameterDictionaryType": "System.Collections.Generic.IDictionary",
"responseArrayType": "System.Collections.Generic.ICollection",
"responseDictionaryType": "System.Collections.Generic.IDictionary",
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"namespace": "Turso.Platform.Client",
"requiredPropertiesMustBeDefined": true,
"dateType": "System.DateTimeOffset",
"jsonConverters": null,
"anyType": "object",
"dateTimeType": "System.DateTimeOffset",
"timeType": "System.TimeSpan",
"timeSpanType": "System.TimeSpan",
"arrayType": "System.Collections.Generic.ICollection",
"arrayInstanceType": "System.Collections.ObjectModel.Collection",
"dictionaryType": "System.Collections.Generic.IDictionary",
"dictionaryInstanceType": "System.Collections.Generic.Dictionary",
"arrayBaseType": "System.Collections.ObjectModel.Collection",
"dictionaryBaseType": "System.Collections.Generic.Dictionary",
"classStyle": "Poco",
"jsonLibrary": "SystemTextJson",
"generateDefaultValues": true,
"generateDataAnnotations": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"handleReferences": false,
"generateImmutableArrayProperties": false,
"generateImmutableDictionaryProperties": false,
"jsonSerializerSettingsTransformationMethod": null,
"inlineNamedArrays": false,
"inlineNamedDictionaries": false,
"inlineNamedTuples": true,
"inlineNamedAny": false,
"generateDtoTypes": true,
"generateOptionalPropertiesAsNullable": true,
"generateNullableReferenceTypes": true,
"templateDirectory": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "$(GeneratedClientSource)",
"newLineBehavior": "Auto"
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Turso.Platform.Client.Tools</RootNamespace>
<IsPackable>false</IsPackable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,217 @@
using System.Text.Json;
using System.Text.Json.Nodes;
// Names the anonymous inline schemas of an OpenAPI document so NSwag does not fall back to
// counter names (`Response17`, `Body3`):
// - 2xx response and request-body schemas get a `title` derived from the `operationId`
// (`listDatabases` -> `ListDatabasesResponse` / `CreateGroupRequest`); NSwag uses the title
// as the generated class name.
// - error (non-2xx) response schemas are lifted into shared `components/schemas` entries and
// replaced with `$ref`s, deduplicated by structural shape — the Turso API reuses one
// `{ error: string }` shape, so they all collapse into a single `ErrorResponse` class.
// The upstream document is left untouched; the transformed copy is consumed by nswag.json.
//
// Usage: OpenApiTitler <input-openapi.json> <output-openapi.json>
if (args.Length != 2)
{
Console.Error.WriteLine("Usage: OpenApiTitler <input-openapi.json> <output-openapi.json>");
return 1;
}
var root = JsonNode.Parse(File.ReadAllText(args[0]))
?? throw new InvalidOperationException("Failed to parse OpenAPI document.");
string[] methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
var titled = 0;
var lifted = 0;
var componentSchemas = root["components"]?["schemas"] as JsonObject
?? throw new InvalidOperationException("Document has no components/schemas section.");
var errorShapes = new Dictionary<string, string>(); // structural signature -> component name
NormalizeExtensionsUnion(componentSchemas);
if (root["paths"] is JsonObject paths)
{
foreach (var (_, pathValue) in paths)
{
if (pathValue is not JsonObject pathItem)
{
continue;
}
foreach (var method in methods)
{
if (pathItem[method] is not JsonObject operation)
{
continue;
}
var operationName = ToPascalCase(operation["operationId"]?.GetValue<string>());
if (operationName is null)
{
continue;
}
TitleSchema(GetJsonSchema(operation["requestBody"]), $"{operationName}Request");
if (operation["responses"] is not JsonObject responses)
{
continue;
}
// Collect the response codes that carry an inline schema so the success/error
// suffixes only get a status-code disambiguator when one is actually needed.
var successCodes = new List<string>();
var errorCodes = new List<string>();
foreach (var (code, response) in responses)
{
if (GetJsonSchema(response) is not null)
{
(code.StartsWith('2') ? successCodes : errorCodes).Add(code);
}
}
foreach (var code in successCodes)
{
var suffix = successCodes.Count > 1 ? code : "";
TitleSchema(GetJsonSchema(responses[code]), $"{operationName}Response{suffix}");
}
foreach (var code in errorCodes)
{
var suffix = errorCodes.Count > 1 ? code : "";
LiftErrorSchema(responses[code], $"{operationName}Error{suffix}");
}
}
}
}
// Reusable error responses (components/responses) carry the same inline shapes; lift them too.
if (root["components"]?["responses"] is JsonObject componentResponses)
{
foreach (var (name, response) in componentResponses)
{
LiftErrorSchema(response, name);
}
}
File.WriteAllText(args[1], root.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"Titled {titled} inline schemas, lifted {lifted} error schemas into {errorShapes.Count} shared component(s) -> {args[1]}");
return 0;
// Resolves requestBody/response -> content -> application/json -> schema.
JsonObject? GetJsonSchema(JsonNode? requestBodyOrResponse)
{
return requestBodyOrResponse?["content"]?["application/json"]?["schema"] as JsonObject;
}
// Replaces an inline error schema with a $ref to a shared components/schemas entry, reusing the
// same component for structurally identical shapes. `fallbackName` names a shape seen first here.
void LiftErrorSchema(JsonNode? response, string fallbackName)
{
var schema = GetJsonSchema(response);
if (schema is null || schema.ContainsKey("$ref"))
{
return;
}
var signature = StructuralSignature(schema);
if (!errorShapes.TryGetValue(signature, out var componentName))
{
// The ubiquitous { error: string } payload gets the canonical name; other shapes keep
// their operation-derived fallback.
componentName = errorShapes.Count == 0 && schema["properties"] is JsonObject props
&& props.Count == 1 && props.ContainsKey("error")
? "ErrorResponse"
: fallbackName;
if (!componentSchemas.ContainsKey(componentName))
{
var component = schema.DeepClone().AsObject();
component.Remove("title");
componentSchemas[componentName] = component;
}
errorShapes[signature] = componentName;
}
var content = response!["content"]!["application/json"]!.AsObject();
content["schema"] = new JsonObject { ["$ref"] = $"#/components/schemas/{componentName}" };
lifted++;
}
// Canonical shape of a schema, ignoring documentation-only members.
static string StructuralSignature(JsonNode? node)
{
if (node is JsonObject obj)
{
var parts = obj
.Where(static p => p.Key is not ("description" or "example" or "title"))
.OrderBy(static p => p.Key, StringComparer.Ordinal)
.Select(static p => $"\"{p.Key}\":{StructuralSignature(p.Value)}");
return "{" + string.Join(",", parts) + "}";
}
if (node is JsonArray arr)
{
return "[" + string.Join(",", arr.Select(StructuralSignature)) + "]";
}
return node?.ToJsonString() ?? "null";
}
void TitleSchema(JsonObject? schema, string title)
{
// Only inline anonymous schemas: a $ref already has a component name, an existing title wins.
if (schema is null || schema.ContainsKey("$ref") || schema.ContainsKey("title"))
{
return;
}
var type = schema["type"]?.GetValue<string>();
if (type == "array")
{
// Top-level arrays stay collections; name their inline object items instead.
if (schema["items"] is JsonObject items && !items.ContainsKey("$ref") && !items.ContainsKey("title")
&& items["type"]?.GetValue<string>() is null or "object")
{
items["title"] = $"{title}Item";
titled++;
}
return;
}
if (type is null or "object")
{
schema["title"] = title;
titled++;
}
}
static void NormalizeExtensionsUnion(JsonObject componentSchemas)
{
var extensions = componentSchemas["Extensions"] as JsonObject
?? throw new InvalidOperationException("Document has no Extensions schema.");
if (extensions["oneOf"] is not JsonArray)
{
throw new InvalidOperationException("Extensions schema is no longer a oneOf union.");
}
// NSwag emits an enum for the first oneOf branch, losing the valid array form. An object
// emits an extensible partial class so the supplement can model either JSON shape.
extensions.Remove("oneOf");
extensions["type"] = "object";
}
static string? ToPascalCase(string? operationId)
{
if (string.IsNullOrWhiteSpace(operationId))
{
return null;
}
var parts = operationId.Split(['_', '-', ' '], StringSplitOptions.RemoveEmptyEntries);
return string.Concat(parts.Select(static p => char.ToUpperInvariant(p[0]) + p[1..]));
}

View File

@@ -0,0 +1,152 @@
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
namespace Turso.Serverless.Client;
/// <summary>
/// HTTP transport for the SQL over HTTP protocol: <c>/v3/pipeline</c> (JSON request/response)
/// and <c>/v3/cursor</c> (JSON request, newline-delimited JSON streaming response).
/// </summary>
internal static class HranaHttp
{
/// <summary>HTTP header carrying the encryption key of an encrypted Turso Cloud database.</summary>
internal const string EncryptionKeyHeader = "x-turso-encryption-key";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
internal static async Task<HranaPipelineResponse> ExecutePipelineAsync(
HttpClient httpClient,
string baseUrl,
string? authToken,
string? remoteEncryptionKey,
HranaPipelineRequest request,
CancellationToken cancellationToken)
{
using var httpRequest = CreateRequest($"{baseUrl}/v3/pipeline", authToken, remoteEncryptionKey, request);
using var response = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw new TursoServerlessException($"HTTP error! status: {(int)response.StatusCode}");
}
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Deserialize<HranaPipelineResponse>(body, JsonOptions)
?? throw new TursoServerlessException("Empty pipeline response");
}
internal static async Task<(HranaCursorResponse Response, IAsyncEnumerable<HranaCursorEntry> Entries)> ExecuteCursorAsync(
HttpClient httpClient,
string baseUrl,
string? authToken,
string? remoteEncryptionKey,
HranaCursorRequest request,
CancellationToken cancellationToken)
{
var httpRequest = CreateRequest($"{baseUrl}/v3/cursor", authToken, remoteEncryptionKey, request);
HttpResponseMessage? response = null;
StreamReader? reader = null;
try
{
response = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
var errorMessage = $"HTTP error! status: {(int)response.StatusCode}";
try
{
var errorBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
using var errorDoc = JsonDocument.Parse(errorBody);
if (errorDoc.RootElement.TryGetProperty("message", out var message) && message.GetString() is { } messageText)
{
errorMessage = messageText;
}
}
catch
{
// If the error body cannot be parsed, keep the default HTTP error message.
}
throw new TursoServerlessException(errorMessage);
}
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
reader = new StreamReader(stream, Encoding.UTF8);
// The first non-empty line is the cursor response; the rest are cursor entries.
HranaCursorResponse? cursorResponse = null;
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
if (line.Trim() is not ("" or null) and var trimmed)
{
cursorResponse = JsonSerializer.Deserialize<HranaCursorResponse>(trimmed, JsonOptions);
break;
}
}
if (cursorResponse is null)
{
throw new TursoServerlessException("No cursor response received");
}
var entries = ReadEntriesAsync(response, reader, cancellationToken);
response = null; // Ownership transferred to the entry enumerator.
reader = null;
return (cursorResponse, entries);
}
finally
{
reader?.Dispose();
response?.Dispose();
httpRequest.Dispose();
}
}
private static async IAsyncEnumerable<HranaCursorEntry> ReadEntriesAsync(
HttpResponseMessage response,
StreamReader reader,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
using (response)
using (reader)
{
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
var trimmed = line.Trim();
if (trimmed.Length == 0)
{
continue;
}
var entry = JsonSerializer.Deserialize<HranaCursorEntry>(trimmed, JsonOptions);
if (entry is not null)
{
yield return entry;
}
}
}
}
private static HttpRequestMessage CreateRequest<T>(string url, string? authToken, string? remoteEncryptionKey, T body)
{
var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json"),
};
if (!string.IsNullOrEmpty(authToken))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
}
if (!string.IsNullOrEmpty(remoteEncryptionKey))
{
httpRequest.Headers.Add(EncryptionKeyHeader, remoteEncryptionKey);
}
return httpRequest;
}
}

View File

@@ -0,0 +1,370 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Turso.Serverless.Client;
// Wire types for the SQL over HTTP protocol (Hrana 3), mirroring serverless/javascript/src/protocol.ts.
// Everything here is internal; the public surface re-exposes results through TursoResultSet/TursoRow.
[JsonConverter(typeof(HranaValueConverter))]
internal readonly struct HranaValue
{
public string Type { get; init; }
/// <summary>Integer (as decimal string) or text payload.</summary>
public string? StringValue { get; init; }
/// <summary>Float payload.</summary>
public double? DoubleValue { get; init; }
/// <summary>Blob payload (raw bytes; base64 on the wire).</summary>
public byte[]? BlobValue { get; init; }
public static readonly HranaValue Null = new() { Type = "null" };
public static HranaValue Encode(object? value)
{
switch (value)
{
case null or DBNull:
return Null;
case bool b:
return new HranaValue { Type = "integer", StringValue = b ? "1" : "0" };
case sbyte or byte or short or ushort or int or uint or long:
return new HranaValue { Type = "integer", StringValue = Convert.ToInt64(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) };
case ulong ul:
return new HranaValue { Type = "integer", StringValue = ul.ToString(CultureInfo.InvariantCulture) };
case float f:
return double.IsFinite(f)
? new HranaValue { Type = "float", DoubleValue = f }
: throw new ArgumentException("Only finite numbers (not Infinity or NaN) can be passed as arguments");
case double d:
return double.IsFinite(d)
? new HranaValue { Type = "float", DoubleValue = d }
: throw new ArgumentException("Only finite numbers (not Infinity or NaN) can be passed as arguments");
case decimal m:
return new HranaValue { Type = "float", DoubleValue = (double)m };
case string s:
return new HranaValue { Type = "text", StringValue = s };
case char c:
return new HranaValue { Type = "text", StringValue = c.ToString() };
case Guid g:
return new HranaValue { Type = "text", StringValue = g.ToString() };
case DateTime dt:
return new HranaValue { Type = "text", StringValue = dt.ToString("o", CultureInfo.InvariantCulture) };
case DateTimeOffset dto:
return new HranaValue { Type = "text", StringValue = dto.ToString("o", CultureInfo.InvariantCulture) };
case byte[] bytes:
return new HranaValue { Type = "blob", BlobValue = bytes };
case ReadOnlyMemory<byte> memory:
return new HranaValue { Type = "blob", BlobValue = memory.ToArray() };
case Memory<byte> memory:
return new HranaValue { Type = "blob", BlobValue = memory.ToArray() };
default:
throw new ArgumentException($"Unsupported argument type: {value.GetType()}");
}
}
public object? Decode()
{
return Type switch
{
"null" => null,
"integer" => long.Parse(StringValue!, CultureInfo.InvariantCulture),
"float" => DoubleValue ?? 0d,
"text" => StringValue,
"blob" => BlobValue ?? [],
_ => null,
};
}
}
internal sealed class HranaValueConverter : JsonConverter<HranaValue>
{
public override HranaValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var doc = JsonDocument.ParseValue(ref reader);
var root = doc.RootElement;
var type = root.GetProperty("type").GetString() ?? "null";
switch (type)
{
case "integer":
// The server sends the integer as a decimal string; tolerate a raw number too.
var intValue = root.GetProperty("value");
return new HranaValue
{
Type = type,
StringValue = intValue.ValueKind == JsonValueKind.String
? intValue.GetString()
: intValue.GetInt64().ToString(CultureInfo.InvariantCulture),
};
case "float":
return new HranaValue { Type = type, DoubleValue = root.GetProperty("value").GetDouble() };
case "text":
return new HranaValue { Type = type, StringValue = root.GetProperty("value").GetString() };
case "blob":
if (root.TryGetProperty("base64", out var b64Element) && b64Element.GetString() is { } b64)
{
// The server may omit base64 padding.
var padding = (4 - b64.Length % 4) % 4;
return new HranaValue { Type = type, BlobValue = Convert.FromBase64String(b64 + new string('=', padding)) };
}
return new HranaValue { Type = type, BlobValue = [] };
default:
return HranaValue.Null;
}
}
public override void Write(Utf8JsonWriter writer, HranaValue value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString("type", value.Type);
switch (value.Type)
{
case "integer":
case "text":
writer.WriteString("value", value.StringValue);
break;
case "float":
writer.WriteNumber("value", value.DoubleValue ?? 0d);
break;
case "blob":
writer.WriteString("base64", Convert.ToBase64String(value.BlobValue ?? []));
break;
}
writer.WriteEndObject();
}
}
internal sealed class HranaColumn
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("decltype")]
public string? Decltype { get; set; }
}
internal sealed class HranaNamedArg
{
[JsonPropertyName("name")]
public required string Name { get; set; }
[JsonPropertyName("value")]
public HranaValue Value { get; set; }
}
internal sealed class HranaStatement
{
[JsonPropertyName("sql")]
public required string Sql { get; set; }
[JsonPropertyName("args")]
public List<HranaValue> Args { get; set; } = [];
[JsonPropertyName("named_args")]
public List<HranaNamedArg> NamedArgs { get; set; } = [];
[JsonPropertyName("want_rows")]
public bool WantRows { get; set; }
}
internal sealed class HranaBatchCondition
{
[JsonPropertyName("type")]
public required string Type { get; set; }
[JsonPropertyName("step")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public int? Step { get; set; }
[JsonPropertyName("cond")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public HranaBatchCondition? Cond { get; set; }
[JsonPropertyName("conds")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<HranaBatchCondition>? Conds { get; set; }
public static HranaBatchCondition Ok(int step) => new() { Type = "ok", Step = step };
public static HranaBatchCondition Not(HranaBatchCondition cond) => new() { Type = "not", Cond = cond };
public static HranaBatchCondition And(params HranaBatchCondition[] conds) => new() { Type = "and", Conds = conds.ToList() };
}
internal sealed class HranaBatchStep
{
[JsonPropertyName("stmt")]
public required HranaStatement Statement { get; set; }
[JsonPropertyName("condition")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public HranaBatchCondition? Condition { get; set; }
}
internal sealed class HranaBatch
{
[JsonPropertyName("steps")]
public required List<HranaBatchStep> Steps { get; set; }
}
internal sealed class HranaPipelineRequestItem
{
[JsonPropertyName("type")]
public required string Type { get; set; }
[JsonPropertyName("sql")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Sql { get; set; }
}
internal sealed class HranaPipelineRequest
{
[JsonPropertyName("baton")]
public string? Baton { get; set; }
[JsonPropertyName("requests")]
public required List<HranaPipelineRequestItem> Requests { get; set; }
}
internal sealed class HranaError
{
[JsonPropertyName("message")]
public string? Message { get; set; }
[JsonPropertyName("code")]
public string? Code { get; set; }
}
internal sealed class HranaPipelineResultResponse
{
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("result")]
public JsonElement? Result { get; set; }
[JsonPropertyName("is_autocommit")]
public bool? IsAutocommit { get; set; }
}
internal sealed class HranaPipelineResult
{
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("response")]
public HranaPipelineResultResponse? Response { get; set; }
[JsonPropertyName("error")]
public HranaError? Error { get; set; }
}
internal sealed class HranaPipelineResponse
{
[JsonPropertyName("baton")]
public string? Baton { get; set; }
[JsonPropertyName("base_url")]
public string? BaseUrl { get; set; }
[JsonPropertyName("results")]
public List<HranaPipelineResult>? Results { get; set; }
}
internal sealed class HranaCursorRequest
{
[JsonPropertyName("baton")]
public string? Baton { get; set; }
[JsonPropertyName("batch")]
public required HranaBatch Batch { get; set; }
}
internal sealed class HranaCursorResponse
{
[JsonPropertyName("baton")]
public string? Baton { get; set; }
[JsonPropertyName("base_url")]
public string? BaseUrl { get; set; }
}
internal sealed class HranaCursorEntry
{
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("step")]
public int? Step { get; set; }
[JsonPropertyName("cols")]
public List<HranaColumn>? Cols { get; set; }
[JsonPropertyName("row")]
public List<HranaValue>? Row { get; set; }
[JsonPropertyName("affected_row_count")]
public long? AffectedRowCount { get; set; }
[JsonPropertyName("last_insert_rowid")]
[JsonConverter(typeof(LongFromStringOrNumberConverter))]
public long? LastInsertRowid { get; set; }
[JsonPropertyName("error")]
public HranaError? Error { get; set; }
}
internal sealed class HranaDescribeParam
{
[JsonPropertyName("name")]
public string? Name { get; set; }
}
internal sealed class HranaDescribeResult
{
[JsonPropertyName("params")]
public List<HranaDescribeParam>? Params { get; set; }
[JsonPropertyName("cols")]
public List<HranaColumn>? Cols { get; set; }
[JsonPropertyName("is_explain")]
public bool IsExplain { get; set; }
[JsonPropertyName("is_readonly")]
public bool IsReadonly { get; set; }
}
/// <summary>The server sends <c>last_insert_rowid</c> as either a JSON string or a number.</summary>
internal sealed class LongFromStringOrNumberConverter : JsonConverter<long?>
{
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Null => null,
JsonTokenType.String => long.Parse(reader.GetString()!, CultureInfo.InvariantCulture),
JsonTokenType.Number => reader.GetInt64(),
_ => throw new JsonException($"Unexpected token for last_insert_rowid: {reader.TokenType}"),
};
}
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
}
else
{
writer.WriteNumberValue(value.Value);
}
}
}

View File

@@ -0,0 +1,66 @@
# Turso.Serverless.Client
Serverless database driver for [Turso Cloud](https://docs.turso.tech) using only `HttpClient` — the .NET counterpart of [`@tursodatabase/serverless`](https://www.npmjs.com/package/@tursodatabase/serverless). Connects to a database over the SQL over HTTP protocol with streaming cursor support.
Unlike the `Turso` and `Turso.Data.Sqlite` packages, this is a pure managed HTTP client — it has no native component.
## Getting started
```C#
using Turso.Serverless.Client;
await using var connection = new TursoServerlessConnection(new TursoServerlessConnectionOptions
{
Url = Environment.GetEnvironmentVariable("TURSO_DATABASE_URL")!,
AuthToken = Environment.GetEnvironmentVariable("TURSO_AUTH_TOKEN"),
});
// Query with positional arguments
var users = await connection.ExecuteAsync("SELECT id, name FROM users WHERE active = ?", [1]);
foreach (var row in users.Rows)
{
Console.WriteLine($"{row.GetInt64("id")}: {row.GetString("name")}");
}
// Write with named arguments
await connection.ExecuteAsync(
"INSERT INTO users (name, email) VALUES (:name, :email)",
new Dictionary<string, object?> { [":name"] = "Iku", [":email"] = "iku@example.com" });
// Atomic batch — one round trip, BEGIN/COMMIT/ROLLBACK handled server-side
await connection.BatchAsync(
[
new TursoBatchStatement("INSERT INTO logs (msg) VALUES (?)", ["a"]),
new TursoBatchStatement("INSERT INTO logs (msg) VALUES (?)", ["b"]),
],
TursoBatchMode.Immediate);
// Interactive transaction
await using (var tx = await connection.BeginTransactionAsync(TursoBatchMode.Immediate))
{
await tx.ExecuteAsync("UPDATE accounts SET balance = balance - 10 WHERE id = ?", [1]);
await tx.ExecuteAsync("UPDATE accounts SET balance = balance + 10 WHERE id = ?", [2]);
await tx.CommitAsync();
}
```
## Concurrency model
A `TursoServerlessConnection` is **single-stream**: it runs one statement at a time. This follows from the SQL over HTTP protocol, where each request carries a baton from the previous response to sequence operations on the server. Calls made while another is in flight automatically wait for it to finish.
For parallelism, create multiple connections — constructing one is cheap (no HTTP request is sent until the first statement executes) and `HttpClient` pools the underlying TCP/TLS connections. A shared static `HttpClient` is used by default; pass your own via the second constructor parameter to integrate with `IHttpClientFactory`.
## Features
- `ExecuteAsync` — single statement with positional or named arguments, full result set
- `BatchAsync` — multiple statements in one round trip, optionally atomic (`TursoBatchMode`)
- `SequenceAsync` — semicolon-separated statement scripts (schema migrations)
- `DescribeAsync` — column/parameter metadata without executing
- `BeginTransactionAsync` — interactive transactions (`await using`, rollback on dispose)
- `InTransaction` — authoritative server-side autocommit status
- Per-call or default query timeouts (`TursoTimeoutException`), cancellation tokens throughout
- Encrypted database support via `RemoteEncryptionKey` (`x-turso-encryption-key`)
## Protocol
The driver speaks the same protocol as the JavaScript serverless driver (`serverless/javascript`): `POST /v3/pipeline` for request/response operations and `POST /v3/cursor` for streamed (newline-delimited JSON) results. Integers map to `long`, floats to `double`, text to `string`, blobs to `byte[]`.

View File

@@ -0,0 +1,24 @@
namespace Turso.Serverless.Client;
/// <summary>Encodes statement arguments into the protocol's positional/named parameter shape.</summary>
internal static class SqlArgs
{
internal static HranaStatement ToStatement(string sql, IReadOnlyList<object?>? args, IReadOnlyDictionary<string, object?>? namedArgs, bool wantRows)
{
var statement = new HranaStatement { Sql = sql, WantRows = wantRows };
if (args is not null)
{
statement.Args = args.Select(HranaValue.Encode).ToList();
}
if (namedArgs is not null)
{
statement.NamedArgs = namedArgs
.Select(static pair => new HranaNamedArg { Name = pair.Key, Value = HranaValue.Encode(pair.Value) })
.ToList();
}
return statement;
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>$(TursoTargetFrameworks)</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Turso.Serverless.Client</RootNamespace>
<PackageId>Turso.Serverless.Client</PackageId>
<Title>Turso Serverless Driver for .NET</Title>
<Description>Serverless database driver for Turso Cloud using only HttpClient — SQL over HTTP with streaming cursor support and no native component. The .NET counterpart of @tursodatabase/serverless.</Description>
<Authors>Turso authors</Authors>
<PackageTags>turso;sqlite;database;serverless;http;hrana</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/tursodatabase/turso</PackageProjectUrl>
<RepositoryUrl>https://github.com/tursodatabase/turso</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="README.md" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,161 @@
using System.Collections;
using System.Globalization;
namespace Turso.Serverless.Client;
/// <summary>
/// A single result row with positional and column-name access. Values are decoded to
/// <see cref="long"/> (integer), <see cref="double"/> (float), <see cref="string"/> (text),
/// <see cref="byte"/>[] (blob) or <c>null</c>.
/// </summary>
public sealed class TursoRow : IReadOnlyList<object?>
{
private readonly object?[] _values;
private readonly IReadOnlyList<string> _columns;
internal TursoRow(object?[] values, IReadOnlyList<string> columns)
{
_values = values;
_columns = columns;
}
public object? this[int index] => _values[index];
public object? this[string column] => _values[IndexOf(column)];
public int Count => _values.Length;
public IReadOnlyList<string> Columns => _columns;
public bool IsNull(int index) => _values[index] is null;
public bool IsNull(string column) => this[column] is null;
public long GetInt64(int index) => Convert.ToInt64(_values[index], CultureInfo.InvariantCulture);
public long GetInt64(string column) => Convert.ToInt64(this[column], CultureInfo.InvariantCulture);
public double GetDouble(int index) => Convert.ToDouble(_values[index], CultureInfo.InvariantCulture);
public double GetDouble(string column) => Convert.ToDouble(this[column], CultureInfo.InvariantCulture);
public string? GetString(int index) => _values[index]?.ToString();
public string? GetString(string column) => this[column]?.ToString();
public byte[]? GetBytes(int index) => (byte[]?)_values[index];
public byte[]? GetBytes(string column) => (byte[]?)this[column];
public IEnumerator<object?> GetEnumerator() => ((IEnumerable<object?>)_values).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private int IndexOf(string column)
{
for (var i = 0; i < _columns.Count; i++)
{
if (string.Equals(_columns[i], column, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
throw new ArgumentException($"Unknown column: {column}", nameof(column));
}
}
/// <summary>The fully materialized result of a SQL statement.</summary>
public sealed class TursoResultSet
{
internal TursoResultSet(IReadOnlyList<string> columns, IReadOnlyList<string> columnTypes, IReadOnlyList<TursoRow> rows, long rowsAffected, long? lastInsertRowid)
{
Columns = columns;
ColumnTypes = columnTypes;
Rows = rows;
RowsAffected = rowsAffected;
LastInsertRowid = lastInsertRowid;
}
/// <summary>Result column names, in order.</summary>
public IReadOnlyList<string> Columns { get; }
/// <summary>Declared column types (<c>decltype</c>), in column order; empty string when undeclared.</summary>
public IReadOnlyList<string> ColumnTypes { get; }
public IReadOnlyList<TursoRow> Rows { get; }
public long RowsAffected { get; }
public long? LastInsertRowid { get; }
}
/// <summary>Aggregate result of a <c>Batch</c> execution.</summary>
public sealed class TursoBatchResult
{
internal TursoBatchResult(long rowsAffected, long? lastInsertRowid)
{
RowsAffected = rowsAffected;
LastInsertRowid = lastInsertRowid;
}
/// <summary>Total affected rows across the batch's user statements.</summary>
public long RowsAffected { get; }
/// <summary>Last insert rowid produced by the batch's user statements, when any.</summary>
public long? LastInsertRowid { get; }
}
/// <summary>Column and parameter metadata of a SQL statement (the protocol's <c>describe</c> answer).</summary>
public sealed class TursoStatementDescription
{
internal TursoStatementDescription(IReadOnlyList<string> parameterNames, IReadOnlyList<string> columns, IReadOnlyList<string> columnTypes, bool isExplain, bool isReadonly)
{
ParameterNames = parameterNames;
Columns = columns;
ColumnTypes = columnTypes;
IsExplain = isExplain;
IsReadonly = isReadonly;
}
public IReadOnlyList<string> ParameterNames { get; }
public IReadOnlyList<string> Columns { get; }
public IReadOnlyList<string> ColumnTypes { get; }
public bool IsExplain { get; }
public bool IsReadonly { get; }
}
/// <summary>One statement of a batch: SQL plus optional positional or named arguments.</summary>
public sealed class TursoBatchStatement
{
public TursoBatchStatement(string sql, IReadOnlyList<object?>? args = null, IReadOnlyDictionary<string, object?>? namedArgs = null)
{
Sql = sql;
Args = args;
NamedArgs = namedArgs;
}
public string Sql { get; }
public IReadOnlyList<object?>? Args { get; }
public IReadOnlyDictionary<string, object?>? NamedArgs { get; }
public static implicit operator TursoBatchStatement(string sql) => new(sql);
}
/// <summary>
/// Locking mode for atomic batch execution and transactions. Mirrors the JavaScript driver's
/// <c>BatchMode</c> / <c>transaction(...)</c> variants.
/// </summary>
public enum TursoBatchMode
{
Deferred,
Immediate,
Exclusive,
Concurrent,
}

View File

@@ -0,0 +1,238 @@
namespace Turso.Serverless.Client;
/// <summary>Configuration for connecting to a Turso database over HTTP.</summary>
public sealed class TursoServerlessConnectionOptions
{
/// <summary>Database URL (<c>https://...</c> or <c>libsql://...</c>).</summary>
public required string Url { get; init; }
/// <summary>Authentication token (optional for local development with <c>turso dev</c>).</summary>
public string? AuthToken { get; init; }
/// <summary>Encryption key (base64) for an encrypted Turso Cloud database.</summary>
public string? RemoteEncryptionKey { get; init; }
/// <summary>Default maximum query execution time before interruption.</summary>
public TimeSpan? DefaultQueryTimeout { get; init; }
}
/// <summary>
/// A connection to a Turso database over the SQL over HTTP protocol with streaming cursor
/// support. The .NET counterpart of the JavaScript driver's <c>Connection</c>.
///
/// <para><b>Concurrency model.</b> A connection is single-stream: it runs one statement at a
/// time. This follows from the protocol — each request carries a baton from the previous
/// response to sequence operations on the server, so concurrent calls would race on that baton.
/// Calls made while another is in flight automatically wait for it to finish. For parallelism,
/// create multiple connections; constructing one is cheap and no HTTP request is sent until the
/// first statement executes.</para>
/// </summary>
public sealed class TursoServerlessConnection : IAsyncDisposable
{
private static readonly HttpClient SharedHttpClient = new();
private readonly TursoServerlessConnectionOptions _options;
private readonly TursoSession _session;
private readonly SemaphoreSlim _execLock = new(1, 1);
private bool _isOpen = true;
public TursoServerlessConnection(TursoServerlessConnectionOptions options)
: this(options, SharedHttpClient)
{
}
/// <summary>Creates a connection using a caller-provided <see cref="HttpClient"/> (not disposed by this class).</summary>
public TursoServerlessConnection(TursoServerlessConnectionOptions options, HttpClient httpClient)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(httpClient);
if (string.IsNullOrEmpty(options.Url))
{
throw new ArgumentException("invalid config: url is required", nameof(options));
}
_options = options;
_session = new TursoSession(options, httpClient);
}
/// <summary>
/// Whether the connection is currently inside a transaction, as reported by the server or
/// established by a successful cursor transaction-control statement.
/// </summary>
public bool InTransaction => _session.InTransaction;
/// <summary>Executes a SQL statement with optional positional arguments and returns the full result set.</summary>
public Task<TursoResultSet> ExecuteAsync(string sql, IReadOnlyList<object?>? args = null, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default)
{
return LockedExecuteAsync(SqlArgs.ToStatement(sql, args, namedArgs: null, wantRows: true), queryTimeout, cancellationToken);
}
/// <summary>Executes a SQL statement with named arguments (e.g. <c>:name</c>, <c>@name</c>, <c>$name</c>) and returns the full result set.</summary>
public Task<TursoResultSet> ExecuteAsync(string sql, IReadOnlyDictionary<string, object?> namedArgs, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default)
{
return LockedExecuteAsync(SqlArgs.ToStatement(sql, args: null, namedArgs, wantRows: true), queryTimeout, cancellationToken);
}
/// <summary>
/// Executes multiple SQL statements in one round trip. When <paramref name="mode"/> is set,
/// the batch runs atomically: the request also carries <c>BEGIN</c>/<c>COMMIT</c>/<c>ROLLBACK</c>
/// steps gated on server-side conditions. When omitted, the statements run as-is under
/// autocommit (or whatever transaction is already active on this stream).
/// </summary>
public async Task<TursoBatchResult> BatchAsync(IReadOnlyList<TursoBatchStatement> statements, TursoBatchMode? mode = null, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default)
{
var encoded = statements.Select(static s => SqlArgs.ToStatement(s.Sql, s.Args, s.NamedArgs, wantRows: false)).ToList();
await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ThrowIfClosed();
var effectiveMode = _session.InTransaction ? null : mode;
return await _session.BatchAsync(encoded, effectiveMode, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false);
}
finally
{
_execLock.Release();
}
}
/// <summary>Executes a sequence of SQL statements separated by semicolons (no result rows).</summary>
public async Task SequenceAsync(string sql, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default)
{
await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ThrowIfClosed();
await _session.SequenceAsync(sql, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false);
}
finally
{
_execLock.Release();
}
}
/// <summary>Describes a SQL statement: column metadata and parameter names, without executing it.</summary>
public async Task<TursoStatementDescription> DescribeAsync(string sql, TimeSpan? queryTimeout = null, CancellationToken cancellationToken = default)
{
await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ThrowIfClosed();
return await _session.DescribeAsync(sql, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false);
}
finally
{
_execLock.Release();
}
}
/// <summary>
/// Begins an interactive transaction on this connection's stream. Dispose without committing
/// to roll back.
/// </summary>
public async Task<TursoServerlessTransaction> BeginTransactionAsync(TursoBatchMode mode = TursoBatchMode.Deferred, CancellationToken cancellationToken = default)
{
await ExecuteAsync($"BEGIN {mode.ToString().ToUpperInvariant()}", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false);
return new TursoServerlessTransaction(this);
}
/// <summary>Closes the connection, releasing the server-side stream.</summary>
public async Task CloseAsync()
{
await _execLock.WaitAsync().ConfigureAwait(false);
try
{
if (!_isOpen)
{
return;
}
_isOpen = false;
await _session.CloseAsync().ConfigureAwait(false);
}
finally
{
_execLock.Release();
}
}
public async ValueTask DisposeAsync()
{
await CloseAsync().ConfigureAwait(false);
}
private async Task<TursoResultSet> LockedExecuteAsync(HranaStatement statement, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
await _execLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ThrowIfClosed();
return await _session.ExecuteAsync(statement.Sql, statement, queryTimeout ?? _options.DefaultQueryTimeout, cancellationToken).ConfigureAwait(false);
}
finally
{
_execLock.Release();
}
}
private void ThrowIfClosed()
{
if (!_isOpen)
{
throw new InvalidOperationException("The database connection is not open");
}
}
}
/// <summary>
/// An interactive transaction on a <see cref="TursoServerlessConnection"/>. Statements executed on
/// the owning connection while the transaction is open participate in it (the protocol stream is
/// the transaction scope). Dispose without committing to roll back.
/// </summary>
public sealed class TursoServerlessTransaction : IAsyncDisposable
{
private readonly TursoServerlessConnection _connection;
private bool _completed;
internal TursoServerlessTransaction(TursoServerlessConnection connection)
{
_connection = connection;
}
public Task<TursoResultSet> ExecuteAsync(string sql, IReadOnlyList<object?>? args = null, CancellationToken cancellationToken = default)
{
return _connection.ExecuteAsync(sql, args, queryTimeout: null, cancellationToken);
}
public Task<TursoResultSet> ExecuteAsync(string sql, IReadOnlyDictionary<string, object?> namedArgs, CancellationToken cancellationToken = default)
{
return _connection.ExecuteAsync(sql, namedArgs, queryTimeout: null, cancellationToken);
}
public async Task CommitAsync(CancellationToken cancellationToken = default)
{
await _connection.ExecuteAsync("COMMIT", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false);
_completed = true;
}
public async Task RollbackAsync(CancellationToken cancellationToken = default)
{
await _connection.ExecuteAsync("ROLLBACK", args: null, queryTimeout: null, cancellationToken).ConfigureAwait(false);
_completed = true;
}
public async ValueTask DisposeAsync()
{
if (!_completed && _connection.InTransaction)
{
try
{
await RollbackAsync().ConfigureAwait(false);
}
catch
{
// Best-effort rollback on dispose; the server also rolls back when the stream expires.
}
}
}
}

View File

@@ -0,0 +1,28 @@
namespace Turso.Serverless.Client;
/// <summary>
/// Error reported by the Turso server or the SQL over HTTP transport.
/// The .NET counterpart of the JavaScript driver's <c>DatabaseError</c>.
/// </summary>
public class TursoServerlessException : Exception
{
/// <summary>Machine-readable error code (e.g. <c>SQLITE_CONSTRAINT</c>), when the server provided one.</summary>
public string? Code { get; }
public TursoServerlessException(string message, string? code = null, Exception? innerException = null)
: base(message, innerException)
{
Code = code;
}
}
/// <summary>
/// Thrown when a query exceeds the configured timeout. <see cref="TursoServerlessException.Code"/> is <c>TIMEOUT</c>.
/// </summary>
public sealed class TursoTimeoutException : TursoServerlessException
{
public TursoTimeoutException(string message = "Query timed out", Exception? innerException = null)
: base(message, "TIMEOUT", innerException)
{
}
}

View File

@@ -0,0 +1,474 @@
using System.Text.Json;
namespace Turso.Serverless.Client;
/// <summary>
/// A database session managing the SQL over HTTP connection state (baton, base URL and
/// transaction status). Port of serverless/javascript/src/session.ts.
/// </summary>
internal sealed class TursoSession
{
private readonly TursoServerlessConnectionOptions _options;
private readonly HttpClient _httpClient;
private string? _baton;
private string _baseUrl;
// Cached autocommit status from the server's last `get_autocommit` answer or a successful
// cursor transaction-control statement. A fresh connection is in autocommit.
private bool _autocommit = true;
internal TursoSession(TursoServerlessConnectionOptions options, HttpClient httpClient)
{
_options = options;
_httpClient = httpClient;
_baseUrl = NormalizeUrl(options.Url);
}
/// <summary>
/// Whether the connection is currently inside a transaction, derived from the server's
/// authoritative <c>get_autocommit</c> answer or the last successful cursor transaction-control
/// statement. A non-null baton does NOT imply a transaction — the server also keeps the stream
/// open for other state.
/// </summary>
internal bool InTransaction => !_autocommit;
internal async Task<TursoStatementDescription> DescribeAsync(string sql, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
var request = new HranaPipelineRequest
{
Baton = _baton,
Requests =
[
new HranaPipelineRequestItem { Type = "describe", Sql = sql },
new HranaPipelineRequestItem { Type = "get_autocommit" },
],
};
var response = await RunPipelineAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false);
if (response.Results is [var result, ..])
{
if (result.Type == "error")
{
throw new TursoServerlessException(result.Error?.Message ?? "Describe execution failed", result.Error?.Code);
}
if (result.Response is { Type: "describe", Result: { } resultElement })
{
var describe = resultElement.Deserialize<HranaDescribeResult>(new JsonSerializerOptions(JsonSerializerDefaults.Web));
if (describe is not null)
{
return new TursoStatementDescription(
parameterNames: describe.Params?.Select(static p => p.Name ?? "").ToArray() ?? [],
columns: describe.Cols?.Select(static c => c.Name ?? "").ToArray() ?? [],
columnTypes: describe.Cols?.Select(static c => c.Decltype ?? "").ToArray() ?? [],
isExplain: describe.IsExplain,
isReadonly: describe.IsReadonly);
}
}
}
throw new TursoServerlessException("Unexpected describe response");
}
internal async Task<TursoResultSet> ExecuteAsync(string sql, HranaStatement statement, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
var request = new HranaCursorRequest
{
Baton = _baton,
Batch = new HranaBatch { Steps = [new HranaBatchStep { Statement = statement }] },
};
var entries = await RunCursorAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false);
var columns = new List<string>();
var columnTypes = new List<string>();
var rows = new List<TursoRow>();
var rowsAffected = 0L;
long? lastInsertRowid = null;
IReadOnlyList<string>? rowColumns = null;
await foreach (var entry in entries.WithCancellation(cancellationToken).ConfigureAwait(false))
{
switch (entry.Type)
{
case "step_begin":
if (entry.Cols is not null)
{
columns = entry.Cols.Select(static c => c.Name ?? "").ToList();
columnTypes = entry.Cols.Select(static c => c.Decltype ?? "").ToList();
rowColumns = columns;
}
break;
case "row":
if (entry.Row is not null)
{
var values = entry.Row.Select(static v => v.Decode()).ToArray();
rows.Add(new TursoRow(values, rowColumns ?? []));
}
break;
case "step_end":
if (entry.AffectedRowCount is { } affected)
{
rowsAffected = affected;
}
if (entry.LastInsertRowid is { } rowid)
{
lastInsertRowid = rowid;
}
break;
case "step_error":
case "error":
throw new TursoServerlessException(entry.Error?.Message ?? "SQL execution failed", entry.Error?.Code);
}
}
UpdateAutocommitForTransactionControlStatement(sql);
return new TursoResultSet(columns, columnTypes, rows, rowsAffected, lastInsertRowid);
}
internal async Task<TursoBatchResult> BatchAsync(IReadOnlyList<HranaStatement> statements, TursoBatchMode? mode, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
var userSteps = statements.Select(static s => new HranaBatchStep { Statement = s }).ToList();
List<HranaBatchStep> steps;
var firstUserStepIdx = 0;
var lastUserStepIdx = userSteps.Count - 1;
var beginIdx = -1;
var commitIdx = -1;
var rollbackIdx = -1;
if (mode is null)
{
steps = userSteps;
}
else
{
// Atomic batch: BEGIN <mode>, then each user step gated on its predecessor succeeding,
// then COMMIT gated on the last user step succeeding, then ROLLBACK gated on BEGIN having
// succeeded *and* COMMIT not having succeeded. The extra ok(BEGIN) guard prevents ROLLBACK
// from aborting a transaction the caller opened on this stream out of band.
beginIdx = 0;
firstUserStepIdx = 1;
lastUserStepIdx = userSteps.Count; // 1..userSteps.Count inclusive
commitIdx = lastUserStepIdx + 1;
rollbackIdx = commitIdx + 1;
steps = [BareStep($"BEGIN {mode.Value.ToString().ToUpperInvariant()}")];
for (var i = 0; i < userSteps.Count; i++)
{
steps.Add(new HranaBatchStep
{
Statement = userSteps[i].Statement,
Condition = HranaBatchCondition.Ok(i == 0 ? beginIdx : firstUserStepIdx + i - 1),
});
}
steps.Add(new HranaBatchStep
{
Statement = BareStep("COMMIT").Statement,
Condition = HranaBatchCondition.Ok(lastUserStepIdx),
});
steps.Add(new HranaBatchStep
{
Statement = BareStep("ROLLBACK").Statement,
Condition = HranaBatchCondition.And([
HranaBatchCondition.Ok(beginIdx),
HranaBatchCondition.Not(HranaBatchCondition.Ok(commitIdx)),
]),
});
}
var request = new HranaCursorRequest
{
Baton = _baton,
Batch = new HranaBatch { Steps = steps },
};
var entries = await RunCursorAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false);
var totalRowsAffected = 0L;
long? lastInsertRowid = null;
TursoServerlessException? deferredError = null;
// step_end entries don't carry a step index on the wire; the server only puts `step` on
// step_begin / step_error. Track the current step ourselves so we know which step_end
// belongs to a user statement when running in atomic mode.
int? currentStep = null;
bool IsUserStep(int? step) => mode is null || (step is { } s && s >= firstUserStepIdx && s <= lastUserStepIdx);
await foreach (var entry in entries.WithCancellation(cancellationToken).ConfigureAwait(false))
{
switch (entry.Type)
{
case "step_begin":
currentStep = entry.Step;
break;
case "step_end":
if (mode is null && currentStep is { } step)
{
if (step < 0 || step >= statements.Count)
{
throw new TursoServerlessException("Unexpected batch step index");
}
UpdateAutocommitForTransactionControlStatement(statements[step].Sql);
}
if (IsUserStep(currentStep))
{
if (entry.AffectedRowCount is { } affected)
{
totalRowsAffected += affected;
}
if (entry.LastInsertRowid is { } rowid)
{
lastInsertRowid = rowid;
}
}
currentStep = null;
break;
case "step_error":
if (mode is null)
{
throw new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code);
}
// Atomic batch: capture the first error from BEGIN, any user step, or COMMIT and
// keep draining so ROLLBACK has a chance to clean up. Errors on the synthetic
// ROLLBACK step are suppressed — they would mask the real cause already captured.
if (deferredError is null && entry.Step != rollbackIdx)
{
deferredError = new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code);
}
currentStep = null;
break;
case "error":
throw new TursoServerlessException(entry.Error?.Message ?? "Batch execution failed", entry.Error?.Code);
}
}
if (deferredError is not null)
{
throw deferredError;
}
return new TursoBatchResult(totalRowsAffected, lastInsertRowid);
}
internal async Task SequenceAsync(string sql, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
var request = new HranaPipelineRequest
{
Baton = _baton,
Requests =
[
new HranaPipelineRequestItem { Type = "sequence", Sql = sql },
new HranaPipelineRequestItem { Type = "get_autocommit" },
],
};
var response = await RunPipelineAsync(request, queryTimeout, cancellationToken).ConfigureAwait(false);
if (response.Results is [var result, ..] && result.Type == "error")
{
throw new TursoServerlessException(result.Error?.Message ?? "Sequence execution failed", result.Error?.Code);
}
}
/// <summary>
/// Close the session: sends a close request so the server cleans up the stream, then resets local state.
/// </summary>
internal async Task CloseAsync()
{
if (_baton is not null)
{
try
{
var request = new HranaPipelineRequest
{
Baton = _baton,
Requests = [new HranaPipelineRequestItem { Type = "close" }],
};
await HranaHttp.ExecutePipelineAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, CancellationToken.None).ConfigureAwait(false);
}
catch
{
// Ignore errors during close — the stream might already be gone or the baton stale.
}
}
_baton = null;
_autocommit = true;
}
private static HranaBatchStep BareStep(string sql)
{
return new HranaBatchStep { Statement = new HranaStatement { Sql = sql, WantRows = false } };
}
private static string NormalizeUrl(string url)
{
return url.StartsWith("libsql://", StringComparison.OrdinalIgnoreCase)
? string.Concat("https://", url.AsSpan("libsql://".Length))
: url;
}
private async Task<HranaPipelineResponse> RunPipelineAsync(HranaPipelineRequest request, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
HranaPipelineResponse response;
var callerToken = cancellationToken;
using var timeout = CreateTimeoutScope(queryTimeout, ref cancellationToken);
try
{
response = await HranaHttp.ExecutePipelineAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
_baton = null;
_autocommit = true;
throw Translate(e, timeout, callerToken);
}
_baton = response.Baton;
if (response.BaseUrl is not null)
{
_baseUrl = response.BaseUrl;
}
UpdateAutocommit(response);
return response;
}
private async Task<IAsyncEnumerable<HranaCursorEntry>> RunCursorAsync(HranaCursorRequest request, TimeSpan? queryTimeout, CancellationToken cancellationToken)
{
// The timeout scope must survive until the entries are drained; the caller's enumeration
// observes it through the cancellation token captured by the enumerator.
var callerToken = cancellationToken;
var timeout = CreateTimeoutScope(queryTimeout, ref cancellationToken);
try
{
var (response, entries) = await HranaHttp.ExecuteCursorAsync(_httpClient, _baseUrl, _options.AuthToken, _options.RemoteEncryptionKey, request, cancellationToken).ConfigureAwait(false);
_baton = response.Baton;
if (response.BaseUrl is not null)
{
_baseUrl = response.BaseUrl;
}
return WrapEntries(entries, timeout, callerToken);
}
catch (Exception e)
{
_baton = null;
_autocommit = true;
var translated = Translate(e, timeout, callerToken);
timeout?.Dispose();
throw translated;
}
}
// callerToken is deliberately not an [EnumeratorCancellation] token: the transport already observes
// the linked token captured by the inner enumerator; this one only distinguishes a caller-initiated
// cancellation from a query timeout when translating exceptions.
#pragma warning disable CS8425
private async IAsyncEnumerable<HranaCursorEntry> WrapEntries(IAsyncEnumerable<HranaCursorEntry> entries, CancellationTokenSource? timeout, CancellationToken callerToken)
#pragma warning restore CS8425
{
using (timeout)
{
var enumerator = entries.GetAsyncEnumerator(CancellationToken.None);
await using (enumerator.ConfigureAwait(false))
{
while (true)
{
bool moved;
try
{
moved = await enumerator.MoveNextAsync().ConfigureAwait(false);
}
catch (Exception e)
{
_baton = null;
_autocommit = true;
throw Translate(e, timeout, callerToken);
}
if (!moved)
{
yield break;
}
yield return enumerator.Current;
}
}
}
}
private static CancellationTokenSource? CreateTimeoutScope(TimeSpan? queryTimeout, ref CancellationToken cancellationToken)
{
var effective = queryTimeout;
if (effective is null or { Ticks: <= 0 })
{
return null;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(effective.Value);
cancellationToken = cts.Token;
return cts;
}
private static Exception Translate(Exception e, CancellationTokenSource? timeout, CancellationToken callerToken)
{
// A cancellation triggered by the timeout scope — not by the caller's own token — is a query timeout.
if (e is OperationCanceledException && !callerToken.IsCancellationRequested && timeout is { IsCancellationRequested: true })
{
return new TursoTimeoutException(innerException: e);
}
return e;
}
private void UpdateAutocommit(HranaPipelineResponse response)
{
if (response.Results is null)
{
return;
}
foreach (var result in response.Results)
{
if (result.Type == "ok" && result.Response is { Type: "get_autocommit", IsAutocommit: { } isAutocommit })
{
_autocommit = isAutocommit;
return;
}
}
}
private void UpdateAutocommitForTransactionControlStatement(string sql)
{
var command = sql.Trim().TrimEnd(';').TrimEnd();
if (command.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase)
&& (command.Length == "BEGIN".Length || char.IsWhiteSpace(command["BEGIN".Length])))
{
_autocommit = false;
}
else if (command.Equals("COMMIT", StringComparison.OrdinalIgnoreCase)
|| command.Equals("END", StringComparison.OrdinalIgnoreCase)
|| command.Equals("ROLLBACK", StringComparison.OrdinalIgnoreCase))
{
_autocommit = true;
}
}
}

View File

@@ -28,5 +28,7 @@
<ProjectReference Include="..\Turso.Data\Turso.Data.csproj" />
<ProjectReference Include="..\Turso.Data.Sqlite\Turso.Data.Sqlite.csproj" />
<ProjectReference Include="..\Turso.EntityFrameworkCore.Sqlite\Turso.EntityFrameworkCore.Sqlite.csproj" />
<ProjectReference Include="..\Turso.Platform.Client\Turso.Platform.Client.csproj" />
<ProjectReference Include="..\Turso.Serverless.Client\Turso.Serverless.Client.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,42 @@
using System.Text.Json;
using AwesomeAssertions;
using Turso.Platform.Client;
namespace Turso.Tests;
public class TursoPlatformClientTests
{
[Test]
public void GroupExtensionsSerializeAndDeserializeBothSupportedForms()
{
var named = new NewGroup
{
Name = "test",
Location = "aws-us-east-1",
Extensions = Extensions.FromNames(["fts5", "vector"]),
};
var namedJson = JsonSerializer.Serialize(named);
using var namedDocument = JsonDocument.Parse(namedJson);
namedDocument.RootElement.GetProperty("extensions").EnumerateArray()
.Select(static extension => extension.GetString())
.Should().Equal("fts5", "vector");
var allJson = JsonSerializer.Serialize(new NewGroup
{
Name = "test",
Location = "aws-us-east-1",
Extensions = Extensions.All,
});
using var allDocument = JsonDocument.Parse(allJson);
allDocument.RootElement.GetProperty("extensions").GetString().Should().Be("all");
var all = JsonSerializer.Deserialize<NewGroup>(
"""{"name":"test","location":"aws-us-east-1","extensions":"all"}""");
all!.Extensions.Should().BeSameAs(Extensions.All);
var deserializedNames = JsonSerializer.Deserialize<NewGroup>(
"""{"name":"test","location":"aws-us-east-1","extensions":["fts5","vector"]}""");
deserializedNames!.Extensions!.Names.Should().Equal("fts5", "vector");
}
}

View File

@@ -0,0 +1,149 @@
using System.Net;
using System.Text.Json;
using AwesomeAssertions;
using Turso.Serverless.Client;
namespace Turso.Tests;
public class TursoServerlessClientTests
{
[Test]
public async Task DisposingAnUncommittedTransactionRollsBack()
{
var handler = new ServerlessHandler();
using var httpClient = new HttpClient(handler);
await using var connection = CreateConnection(httpClient);
await using (var transaction = await connection.BeginTransactionAsync())
{
connection.InTransaction.Should().BeTrue();
}
connection.InTransaction.Should().BeFalse();
handler.Sql.Should().Equal("BEGIN DEFERRED", "ROLLBACK");
}
[Test]
public async Task BatchInsideAnInteractiveTransactionDoesNotStartANestedTransaction()
{
var handler = new ServerlessHandler();
using var httpClient = new HttpClient(handler);
await using var connection = CreateConnection(httpClient);
await using (var transaction = await connection.BeginTransactionAsync())
{
await connection.BatchAsync([new TursoBatchStatement("SELECT 1")], TursoBatchMode.Immediate);
}
var expected = new[] { "SELECT 1" };
handler.Batches.Should().ContainSingle(batch => batch.SequenceEqual(expected));
}
[Test]
public async Task RawTransactionControlInABatchUpdatesTransactionState()
{
var handler = new ServerlessHandler();
using var httpClient = new HttpClient(handler);
await using var connection = CreateConnection(httpClient);
await connection.BatchAsync([new TursoBatchStatement("BEGIN")]);
connection.InTransaction.Should().BeTrue();
await connection.BatchAsync([new TursoBatchStatement("ROLLBACK")]);
connection.InTransaction.Should().BeFalse();
}
[Test]
public async Task DisposingWaitsForAnActiveExecution()
{
var executionStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseExecution = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var handler = new ServerlessHandler(async (request, cancellationToken) =>
{
if (request.RequestUri!.AbsolutePath == "/v3/cursor")
{
executionStarted.TrySetResult();
await releaseExecution.Task.WaitAsync(cancellationToken);
return CursorResponse();
}
return PipelineResponse();
});
using var httpClient = new HttpClient(handler);
var connection = CreateConnection(httpClient);
var execution = connection.ExecuteAsync("SELECT 1");
await executionStarted.Task;
var disposal = connection.DisposeAsync().AsTask();
disposal.IsCompleted.Should().BeFalse();
releaseExecution.SetResult();
await execution;
await disposal;
}
private static TursoServerlessConnection CreateConnection(HttpClient httpClient)
{
return new TursoServerlessConnection(
new TursoServerlessConnectionOptions { Url = "https://example.com" },
httpClient);
}
private sealed class ServerlessHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>>? _handler;
internal List<string> Sql { get; } = [];
internal List<IReadOnlyList<string>> Batches { get; } = [];
internal ServerlessHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>>? handler = null)
{
_handler = handler;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_handler is not null)
{
return await _handler(request, cancellationToken);
}
if (request.RequestUri!.AbsolutePath == "/v3/cursor")
{
using var document = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(cancellationToken));
var statements = document.RootElement.GetProperty("batch").GetProperty("steps")
.EnumerateArray()
.Select(static step => step.GetProperty("stmt").GetProperty("sql").GetString()!)
.ToArray();
Sql.AddRange(statements);
Batches.Add(statements);
return CursorResponse();
}
return PipelineResponse();
}
}
private static HttpResponseMessage CursorResponse()
{
return JsonResponse("""
{"baton":"baton"}
{"type":"step_begin","step":0}
{"type":"step_end","affected_row_count":0}
""");
}
private static HttpResponseMessage PipelineResponse()
{
return JsonResponse("""{"baton":null,"results":[]}""");
}
private static HttpResponseMessage JsonResponse(string content)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(content),
};
}
}