From 5c61d4ad6d27773601dc7a79b5bd931854e82066 Mon Sep 17 00:00:00 2001 From: tr00d Date: Thu, 26 Nov 2026 10:52:03 +0100 Subject: [PATCH 1/2] feat(storage): commit a new schema or partition spec to an Iceberg table --- .../Storage.Tests/Storage.Tests.csproj | 1 + .../UpdateTable/Data/TableUpdated.json | 19 ++ .../UpdateTable/UpdateTableApprovalTests.cs | 92 +++++++++ .../UpdateTable/UpdateTableContractTests.cs | 184 ++++++++++++++++++ .../UpdateTable/UpdateTableTests.cs | 53 +++++ packages/Storage/Storage/IcebergCatalog.cs | 10 + .../Storage/Interfaces/IIcebergCatalog.cs | 32 +++ .../Storage/Storage/PublicAPI.Unshipped.txt | 16 ++ .../UpdateTable/IcebergTableChanges.cs | 25 +++ .../Storage/UpdateTable/UpdateTableBody.cs | 140 +++++++++++++ 10 files changed, 572 insertions(+) create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/TableUpdated.json create mode 100644 packages/Storage/Storage.Tests/UpdateTable/UpdateTableApprovalTests.cs create mode 100644 packages/Storage/Storage.Tests/UpdateTable/UpdateTableContractTests.cs create mode 100644 packages/Storage/Storage.Tests/UpdateTable/UpdateTableTests.cs create mode 100644 packages/Storage/Storage/UpdateTable/IcebergTableChanges.cs create mode 100644 packages/Storage/Storage/UpdateTable/UpdateTableBody.cs diff --git a/packages/Storage/Storage.Tests/Storage.Tests.csproj b/packages/Storage/Storage.Tests/Storage.Tests.csproj index 6a97660d..2086e69f 100644 --- a/packages/Storage/Storage.Tests/Storage.Tests.csproj +++ b/packages/Storage/Storage.Tests/Storage.Tests.csproj @@ -32,6 +32,7 @@ + PreserveNewest diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/TableUpdated.json b/packages/Storage/Storage.Tests/UpdateTable/Data/TableUpdated.json new file mode 100644 index 00000000..94c7718c --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/TableUpdated.json @@ -0,0 +1,19 @@ +{ + "metadata-location": "s3://analytics-data/sales/events/metadata/00002-7a1f0c8e-2b4d-4e6f-9a1b-3c5d7e9f1a2b.metadata.json", + "metadata": { + "format-version": 2, + "table-uuid": "b734865e-f9a5-4654-8b0b-e15683fcb195", + "location": "s3://analytics-data/sales/events", + "last-updated-ms": 1752148819286, + "last-column-id": 3, + "last-partition-id": 1000, + "current-schema-id": 1, + "schemas": [ + { "type": "struct", "schema-id": 0, "fields": [ { "id": 1, "name": "id", "type": "long", "required": true }, { "id": 2, "name": "occurred_at", "type": "timestamptz", "required": true } ] }, + { "type": "struct", "schema-id": 1, "fields": [ { "id": 1, "name": "id", "type": "long", "required": true }, { "id": 2, "name": "occurred_at", "type": "timestamptz", "required": true }, { "id": 3, "name": "country", "type": "string", "required": false } ] } + ], + "default-spec-id": 0, + "partition-specs": [ { "spec-id": 0, "fields": [ { "source-id": 2, "field-id": 1000, "name": "occurred_day", "transform": "day" } ] } ], + "properties": {} + } +} diff --git a/packages/Storage/Storage.Tests/UpdateTable/UpdateTableApprovalTests.cs b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableApprovalTests.cs new file mode 100644 index 00000000..154f63df --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableApprovalTests.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Storage.Tests.Support; +using Supabase.Storage.Common; +using Supabase.Storage.UpdateTable; + +namespace Storage.Tests.UpdateTable; + +/// +/// Pins the exact bytes UpdateTableAsync puts on the wire; the approved bodies must match the Iceberg REST +/// CommitTableRequest that Storage forwards from POST /iceberg/v1/:prefix/namespaces/:namespace/tables/:table +/// (requirements and updates both required; -1 names the schema or spec added by the same commit). +/// +[TestClass] +[TestCategory("Contract")] +public class UpdateTableApprovalTests : RequestApprovalFixture +{ + private static readonly IcebergTable Events = IcebergNamespace.Of("sales").Table("events"); + + private static readonly IcebergSchema Evolved = new() + { + Fields = new[] + { + new IcebergField { Id = 1, Name = "id", Type = IcebergPrimitiveType.Long, Required = true }, + new IcebergField { Id = 3, Name = "country", Type = IcebergPrimitiveType.String, Required = false }, + }, + }; + + private static readonly IcebergPartitionSpec ByCountry = new() + { + Fields = new[] { new IcebergPartitionField { SourceId = 3, Name = "country", Transform = IcebergTransform.Identity } }, + }; + + private static readonly IcebergTableMetadata Current = new() + { + TableUuid = Guid.Parse("b734865e-f9a5-4654-8b0b-e15683fcb195"), + FormatVersion = 2, + Location = "s3://analytics-data/sales/events", + LastUpdatedAt = DateTimeOffset.FromUnixTimeMilliseconds(1752062419286), + CurrentSchema = new IcebergSchema { SchemaId = 4, Fields = Array.Empty() }, + DefaultPartitionSpec = new IcebergPartitionSpec { SpecId = 5, Fields = Array.Empty() }, + LastColumnId = 2, + LastPartitionId = 1000, + Properties = new Dictionary(), + }; + + [TestMethod] + public async Task UpdateTableRequest_ShouldSerializeSchemaChange() + { + this.RespondWith(Updated()); + await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { Schema = Evolved }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task UpdateTableRequest_ShouldSerializePartitionSpecChange() + { + this.RespondWith(Updated()); + await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { PartitionSpec = ByCountry }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn() + { + this.RespondWith(Updated()); + await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { Schema = Evolved, BasedOn = Current }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn() + { + this.RespondWith(Updated()); + await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { PartitionSpec = ByCountry, BasedOn = Current }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange() + { + this.RespondWith(Updated()); + await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges()); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + private static string Updated() => + File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTable", "Data", "TableUpdated.json")); +} diff --git a/packages/Storage/Storage.Tests/UpdateTable/UpdateTableContractTests.cs b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableContractTests.cs new file mode 100644 index 00000000..4ba47fca --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableContractTests.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Storage.Tests.Support; +using Supabase.Storage; +using Supabase.Storage.Common; +using Supabase.Storage.Exceptions; +using Supabase.Storage.Interfaces; +using Supabase.Storage.UpdateTable; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; + +namespace Storage.Tests.UpdateTable; + +/// +/// Contract tests for updating a table: the POST request the catalog puts on the wire (method, path, table and +/// namespace encoding, headers), how the table metadata after the commit is surfaced, and how each failure the Iceberg +/// route can give is surfaced. Failure bodies are pinned from the storage route source and the Iceberg REST spec, not +/// observed on a running service. +/// +[TestClass] +[TestCategory("Contract")] +public class UpdateTableContractTests +{ + private const string TablePath = "/storage/v1/iceberg/v1/analytics-data/namespaces/sales/tables/events"; + private static readonly IcebergTable Events = IcebergNamespace.Of("sales").Table("events"); + private static readonly IcebergTableChanges NoChange = new(); + private WireMockServer server = null!; + private Client client = null!; + + [TestInitialize] + public void TestInitialize() + { + this.server = WireMockServer.Start(); + this.client = new Client($"{this.server.Url}/storage/v1", new Dictionary + { + { "Authorization", "Bearer service-key" } + }); + } + + [TestCleanup] + public void TestCleanup() => this.server.Stop(); + + [TestMethod] + public async Task UpdateTableAsync_ShouldPostToTheTableRoute() + { + this.Respond(TablePath, 200, Fixture("TableUpdated.json")); + await this.Catalog().UpdateTableAsync(Events, NoChange); + var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!; + using (new AssertionScope()) + { + request.Method.Should().Be("POST", "the Iceberg route that commits table changes is POST /:prefix/namespaces/:namespace/tables/:table"); + request.Path.Should().Be(TablePath, "the bucket is the Iceberg warehouse, sent as the path prefix"); + request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-key"); + request.Headers["Content-Type"].Should().ContainSingle().Which.Should().StartWith("application/json"); + } + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldEscapeTheTableNameAsOneSegment() + { + this.Respond("/storage/v1/iceberg/v1/*", 200, Fixture("TableUpdated.json")); + await this.Catalog().UpdateTableAsync(IcebergNamespace.Of("sales", "europe").Table("a/b?c#d"), NoChange); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Url + .Should().EndWith("/namespaces/sales%1Feurope/tables/a%2Fb%3Fc%23d", "a name must not start a path segment, query or fragment"); + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldReturnTheMetadataAfterTheCommit() + { + this.Respond(TablePath, 200, Fixture("TableUpdated.json")); + var metadata = await this.Catalog().UpdateTableAsync(Events, NoChange); + using (new AssertionScope()) + { + metadata.MetadataLocation.Should().Be("s3://analytics-data/sales/events/metadata/00002-7a1f0c8e-2b4d-4e6f-9a1b-3c5d7e9f1a2b.metadata.json"); + metadata.CurrentSchema.SchemaId.Should().Be(1, "the schema the commit added is now current"); + metadata.CurrentSchema.Fields.Should().HaveCount(3); + metadata.LastColumnId.Should().Be(3); + } + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldThrowConflict_GivenTableChangedSinceBasedOn() + { + this.Respond(TablePath, 409, Envelope("Requirement failed: current schema changed: expected id 0 != 1", "CommitFailedException", 409)); + var act = () => this.Catalog().UpdateTableAsync(Events, NoChange); + var exception = (await act.Should().ThrowAsync()).Which; + using (new AssertionScope()) + { + exception.StatusCode.Should().Be(409, "the Iceberg REST spec answers 409 when a requirement fails"); + exception.Code.Should().Be("CommitFailedException", "Storage passes the catalog's error type through"); + } + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldThrow_GivenInvalidChange() + { + this.Respond(TablePath, 400, Envelope("Cannot add field country as an identifier field: not a primitive type", "BadRequestException", 400)); + var act = () => this.Catalog().UpdateTableAsync(Events, NoChange); + var exception = (await act.Should().ThrowAsync()).Which; + using (new AssertionScope()) + { + exception.StatusCode.Should().Be(400, "the catalog, not the SDK, validates the changes"); + exception.Code.Should().Be("BadRequestException"); + } + } + + [TestMethod] + [DataRow("Table not found", "NoSuchTableException")] + [DataRow("Namespace not found", "NoSuchNamespaceException")] + [DataRow("Catalog name \"analytics-data\" not found", "NoSuchCatalog")] + public async Task UpdateTableAsync_ShouldThrowNotFound_GivenMissingTableNamespaceOrBucket(string message, string code) + { + this.Respond(TablePath, 404, Envelope(message, code, 404)); + var act = () => this.Catalog().UpdateTableAsync(Events, NoChange); + var exception = (await act.Should().ThrowAsync()).Which; + using (new AssertionScope()) + { + exception.Reason.Should().Be(FailureHint.Reason.NotFound); + exception.Code.Should().Be(code); + } + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldThrow_GivenForbidden() + { + this.Respond(TablePath, 403, Envelope("Access denied: Invalid role", "AccessDenied", 403)); + var act = () => this.Catalog().UpdateTableAsync(Events, NoChange); + var exception = (await act.Should().ThrowAsync()).Which; + using (new AssertionScope()) + { + exception.StatusCode.Should().Be(403, "only the service role may use the catalog"); + exception.Code.Should().Be("AccessDenied"); + } + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldReadHeadersAtCallTime() + { + this.Respond(TablePath, 200, Fixture("TableUpdated.json")); + var catalog = this.Catalog(); + this.client.GetHeaders = () => new Dictionary { { "apikey", "rotated" } }; + await catalog.UpdateTableAsync(Events, NoChange); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["apikey"] + .Should().ContainSingle().Which.Should().Be("rotated"); + } + + [TestMethod] + public async Task UpdateTableAsync_ShouldHonorCancellation() + { + this.Respond(TablePath, 200, Fixture("TableUpdated.json")); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + var act = () => this.Catalog().UpdateTableAsync(Events, NoChange, cts.Token); + await act.Should().ThrowAsync("the token must reach the HTTP call"); + } + + [TestMethod] + public void UpdateTableAsync_ShouldNotResumeOnTheCallersContext() + { + this.Respond(TablePath, 200, Fixture("TableUpdated.json")); + BlockingCaller.Completes(() => this.Catalog().UpdateTableAsync(Events, NoChange)) + .Should().BeTrue("the SDK never resumes on the caller's synchronization context"); + } + + private static string Fixture(string name) => + File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTable", "Data", name)); + + private static string Envelope(string message, string type, int code) => + $"{{\"error\":{{\"message\":{JsonSerializer.Serialize(message)},\"type\":\"{type}\",\"code\":{code}}}}}"; + + private IIcebergCatalog Catalog() => this.client.Analytics.From("analytics-data"); + + private void Respond(string path, int status, string body) => + this.server.Given(Request.Create().WithPath(path).UsingPost()) + .RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body)); +} diff --git a/packages/Storage/Storage.Tests/UpdateTable/UpdateTableTests.cs b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableTests.cs new file mode 100644 index 00000000..20295b55 --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/UpdateTableTests.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage; +using Supabase.Storage.Common; +using Supabase.Storage.UpdateTable; + +namespace Storage.Tests.UpdateTable; + +/// +/// Unit tests for the checks made before the wire when updating a table, and for the defaults of its changes. +/// The changes themselves are validated by the catalog. +/// +[TestClass] +[TestCategory("Unit")] +public class UpdateTableTests +{ + private readonly Client sut = new("http://localhost:1/storage/v1"); + + [TestMethod] + public async Task UpdateTableAsync_ShouldThrowArgumentNullException_GivenNoTable() => + (await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(null!, new IcebergTableChanges())) + .Should().ThrowAsync("there is no table to update")) + .Which.ParamName.Should().Be("table"); + + [TestMethod] + public async Task UpdateTableAsync_ShouldThrowArgumentNullException_GivenNoChanges() => + (await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(IcebergNamespace.Of("sales").Table("events"), null!)) + .Should().ThrowAsync("there are no changes to commit")) + .Which.ParamName.Should().Be("changes"); + + [TestMethod] + [DataRow("")] + [DataRow("..")] + public async Task UpdateTableAsync_ShouldThrowArgumentException_GivenNameThatChangesTheRoute(string name) => + (await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(IcebergNamespace.Of("sales").Table(name), new IcebergTableChanges())) + .Should().ThrowAsync("a blank or dot-segment name would post to another route")) + .Which.ParamName.Should().Be("table"); + + [TestMethod] + public void IcebergTableChanges_ShouldChangeNothing_GivenNoneSet() + { + var changes = new IcebergTableChanges(); + using (new AssertionScope()) + { + changes.Schema.Should().BeNull(); + changes.PartitionSpec.Should().BeNull(); + changes.BasedOn.Should().BeNull("without it the commit asserts nothing about the table"); + } + } +} diff --git a/packages/Storage/Storage/IcebergCatalog.cs b/packages/Storage/Storage/IcebergCatalog.cs index 6f007f23..8adee2a4 100644 --- a/packages/Storage/Storage/IcebergCatalog.cs +++ b/packages/Storage/Storage/IcebergCatalog.cs @@ -10,6 +10,7 @@ using Supabase.Storage.Exceptions; using Supabase.Storage.Interfaces; using Supabase.Storage.ListNamespaces; +using Supabase.Storage.UpdateTable; namespace Supabase.Storage; @@ -91,6 +92,15 @@ public Task DeleteTableAsync(IcebergTable table, DeleteTableOptions? options = n return Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Delete, DeleteTableQuery.For(this.ResourceUrl(table.Path), options), null, this.headers(), cancellationToken); } + /// + public async Task UpdateTableAsync(IcebergTable table, IcebergTableChanges changes, CancellationToken cancellationToken = default) + { + RequireArgument(table, nameof(table)); + RequireArgument(changes, nameof(changes)); + var response = await Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Post, this.ResourceUrl(table.Path), UpdateTableBody.For(changes), this.headers(), cancellationToken).ConfigureAwait(false); + return response!.ToMetadata(); + } + private string ResourceUrl(string path) => $"{this.catalogUrl}/{path}"; private async Task ResourceExistsAsync(string url, CancellationToken cancellationToken) diff --git a/packages/Storage/Storage/Interfaces/IIcebergCatalog.cs b/packages/Storage/Storage/Interfaces/IIcebergCatalog.cs index 340386d4..c5dcf34a 100644 --- a/packages/Storage/Storage/Interfaces/IIcebergCatalog.cs +++ b/packages/Storage/Storage/Interfaces/IIcebergCatalog.cs @@ -6,6 +6,7 @@ using Supabase.Storage.CreateTable; using Supabase.Storage.DeleteTable; using Supabase.Storage.ListNamespaces; +using Supabase.Storage.UpdateTable; namespace Supabase.Storage.Interfaces; @@ -213,4 +214,35 @@ public interface IIcebergCatalog /// [ImplementedCapability("storage.analytics.delete_table")] Task DeleteTableAsync(IcebergTable table, DeleteTableOptions? options = null, CancellationToken cancellationToken = default); + + /// + /// Commits a new current schema, a new default partition spec, or both, to an Iceberg table. + /// + /// The table to update. + /// The schema and partition spec to make current, and optionally the metadata they were made from. + /// Token used to cancel the request. + /// The metadata of the table after the commit, as the catalog stored it. + /// or is null. + /// The table name is blank, or the table name or its namespace is a relative path segment. + /// + /// The service refused the call, for example because the table changed since + /// (status 409, Code CommitFailedException), the changes are invalid (status 400), the table, its namespace + /// or its bucket does not exist (status 404, Code NoSuchTableException, NoSuchNamespaceException + /// or NoSuchCatalog) or the caller is not authorized. + /// + /// + /// + /// var catalog = storage.Analytics.From("analytics-data"); + /// var events = IcebergNamespace.Of("sales").Table("events"); + /// var current = await catalog.LoadTableAsync(events); + /// var country = new IcebergField { Id = current.LastColumnId + 1, Name = "country", Type = IcebergPrimitiveType.String, Required = false }; + /// var updated = await catalog.UpdateTableAsync(events, new IcebergTableChanges + /// { + /// Schema = new IcebergSchema { Fields = current.CurrentSchema.Fields.Append(country).ToList() }, + /// BasedOn = current, + /// }); + /// + /// + [ImplementedCapability("storage.analytics.update_table")] + Task UpdateTableAsync(IcebergTable table, IcebergTableChanges changes, CancellationToken cancellationToken = default); } diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index 84332e5d..96c5c064 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -131,6 +131,9 @@ override Supabase.Storage.QueryVectors.VectorMatch.ToString() -> string! override Supabase.Storage.QueryVectors.VectorQueryResult.Equals(object? obj) -> bool override Supabase.Storage.QueryVectors.VectorQueryResult.GetHashCode() -> int override Supabase.Storage.QueryVectors.VectorQueryResult.ToString() -> string! +override Supabase.Storage.UpdateTable.IcebergTableChanges.Equals(object? obj) -> bool +override Supabase.Storage.UpdateTable.IcebergTableChanges.GetHashCode() -> int +override Supabase.Storage.UpdateTable.IcebergTableChanges.ToString() -> string! static Supabase.Storage.Common.AnalyticsBucket.operator !=(Supabase.Storage.Common.AnalyticsBucket? left, Supabase.Storage.Common.AnalyticsBucket? right) -> bool static Supabase.Storage.Common.AnalyticsBucket.operator ==(Supabase.Storage.Common.AnalyticsBucket? left, Supabase.Storage.Common.AnalyticsBucket? right) -> bool static Supabase.Storage.Common.BucketLifecycle.operator !=(Supabase.Storage.Common.BucketLifecycle? left, Supabase.Storage.Common.BucketLifecycle? right) -> bool @@ -242,6 +245,8 @@ static Supabase.Storage.QueryVectors.VectorMatch.operator !=(Supabase.Storage.Qu static Supabase.Storage.QueryVectors.VectorMatch.operator ==(Supabase.Storage.QueryVectors.VectorMatch? left, Supabase.Storage.QueryVectors.VectorMatch? right) -> bool static Supabase.Storage.QueryVectors.VectorQueryResult.operator !=(Supabase.Storage.QueryVectors.VectorQueryResult? left, Supabase.Storage.QueryVectors.VectorQueryResult? right) -> bool static Supabase.Storage.QueryVectors.VectorQueryResult.operator ==(Supabase.Storage.QueryVectors.VectorQueryResult? left, Supabase.Storage.QueryVectors.VectorQueryResult? right) -> bool +static Supabase.Storage.UpdateTable.IcebergTableChanges.operator !=(Supabase.Storage.UpdateTable.IcebergTableChanges? left, Supabase.Storage.UpdateTable.IcebergTableChanges? right) -> bool +static Supabase.Storage.UpdateTable.IcebergTableChanges.operator ==(Supabase.Storage.UpdateTable.IcebergTableChanges? left, Supabase.Storage.UpdateTable.IcebergTableChanges? right) -> bool Supabase.Storage.Client.Analytics.get -> Supabase.Storage.Interfaces.IStorageAnalyticsApi! Supabase.Storage.Client.Vectors.get -> Supabase.Storage.Interfaces.IStorageVectorBucketApi! Supabase.Storage.Common.AnalyticsBucket @@ -486,6 +491,7 @@ Supabase.Storage.Interfaces.IIcebergCatalog.ListNamespacesAsync(Supabase.Storage Supabase.Storage.Interfaces.IIcebergCatalog.LoadTableAsync(Supabase.Storage.Common.IcebergTable! table, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IIcebergCatalog.NamespaceExistsAsync(Supabase.Storage.Common.IcebergNamespace! namespace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IIcebergCatalog.TableExistsAsync(Supabase.Storage.Common.IcebergTable! table, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.Interfaces.IIcebergCatalog.UpdateTableAsync(Supabase.Storage.Common.IcebergTable! table, Supabase.Storage.UpdateTable.IcebergTableChanges! changes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IStorageAnalyticsApi Supabase.Storage.Interfaces.IStorageAnalyticsApi.CreateBucketAsync(string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IStorageAnalyticsApi.DeleteBucketAsync(string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! @@ -679,6 +685,16 @@ Supabase.Storage.Common.VectorData.Float32.get -> System.Collections.Generic.IRe Supabase.Storage.Common.VectorData.Float32.init -> void Supabase.Storage.Common.VectorData.VectorData() -> void Supabase.Storage.StorageBucketApi.GetBucketLifecycleAsync(string! id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.UpdateTable.IcebergTableChanges +Supabase.Storage.UpdateTable.IcebergTableChanges.$() -> Supabase.Storage.UpdateTable.IcebergTableChanges! +Supabase.Storage.UpdateTable.IcebergTableChanges.BasedOn.get -> Supabase.Storage.Common.IcebergTableMetadata? +Supabase.Storage.UpdateTable.IcebergTableChanges.BasedOn.init -> void +Supabase.Storage.UpdateTable.IcebergTableChanges.Equals(Supabase.Storage.UpdateTable.IcebergTableChanges? other) -> bool +Supabase.Storage.UpdateTable.IcebergTableChanges.IcebergTableChanges() -> void +Supabase.Storage.UpdateTable.IcebergTableChanges.PartitionSpec.get -> Supabase.Storage.Common.IcebergPartitionSpec? +Supabase.Storage.UpdateTable.IcebergTableChanges.PartitionSpec.init -> void +Supabase.Storage.UpdateTable.IcebergTableChanges.Schema.get -> Supabase.Storage.Common.IcebergSchema? +Supabase.Storage.UpdateTable.IcebergTableChanges.Schema.init -> void virtual Supabase.Storage.Common.IcebergType.EqualityContract.get -> System.Type! virtual Supabase.Storage.Common.IcebergType.Equals(Supabase.Storage.Common.IcebergType? other) -> bool virtual Supabase.Storage.Common.IcebergType.PrintMembers(System.Text.StringBuilder! builder) -> bool diff --git a/packages/Storage/Storage/UpdateTable/IcebergTableChanges.cs b/packages/Storage/Storage/UpdateTable/IcebergTableChanges.cs new file mode 100644 index 00000000..01232f3b --- /dev/null +++ b/packages/Storage/Storage/UpdateTable/IcebergTableChanges.cs @@ -0,0 +1,25 @@ +using Supabase.Storage.Common; + +namespace Supabase.Storage.UpdateTable; + +/// +/// The changes to commit to an Iceberg table: a new current schema, a new default partition spec, or both. +/// +public sealed record IcebergTableChanges +{ + /// + /// The schema to make current. It is added to the table's schemas and rows are then written with it. A new column + /// takes an identifier above . + /// + public IcebergSchema? Schema { get; init; } + + /// The partition spec to make the default. It is added to the table's specs and rows are then written with it. + public IcebergPartitionSpec? PartitionSpec { get; init; } + + /// + /// The metadata these changes were made from. When set, the catalog only commits the changes if the table has not + /// changed since in a way they depend on, and refuses them with status 409 otherwise. When null, the changes are + /// committed whatever happened to the table in between. + /// + public IcebergTableMetadata? BasedOn { get; init; } +} diff --git a/packages/Storage/Storage/UpdateTable/UpdateTableBody.cs b/packages/Storage/Storage/UpdateTable/UpdateTableBody.cs new file mode 100644 index 00000000..d1b7fecf --- /dev/null +++ b/packages/Storage/Storage/UpdateTable/UpdateTableBody.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using Supabase.Storage.Common; + +namespace Supabase.Storage.UpdateTable; + +internal sealed class UpdateTableBody +{ + private const int LastAdded = -1; + + [JsonPropertyName("requirements")] + public IReadOnlyList Requirements { get; init; } = null!; + + [JsonPropertyName("updates")] + public IReadOnlyList Updates { get; init; } = null!; + + internal static UpdateTableBody For(IcebergTableChanges changes) => new() + { + Requirements = RequirementsOf(changes).ToList(), + Updates = UpdatesOf(changes).ToList(), + }; + + private static IEnumerable UpdatesOf(IcebergTableChanges changes) + { + if (changes.Schema is { } schema) + { + yield return new AddSchemaUpdate(IcebergSchemaBody.From(schema)); + yield return new SetCurrentSchemaUpdate(); + } + + if (changes.PartitionSpec is { } spec) + { + yield return new AddSpecUpdate(IcebergPartitionSpecBody.From(spec)); + yield return new SetDefaultSpecUpdate(); + } + } + + private static IEnumerable RequirementsOf(IcebergTableChanges changes) + { + if (changes.BasedOn is not { } basedOn) + yield break; + + yield return new AssertTableUuid(basedOn.TableUuid); + + if (changes.Schema is not null) + { + yield return new AssertCurrentSchemaId(basedOn.CurrentSchema.SchemaId); + yield return new AssertLastAssignedFieldId(basedOn.LastColumnId); + } + + if (changes.PartitionSpec is not null) + { + yield return new AssertDefaultSpecId(basedOn.DefaultPartitionSpec.SpecId); + yield return new AssertLastAssignedPartitionId(basedOn.LastPartitionId); + } + } + + internal sealed class AddSchemaUpdate(IcebergSchemaBody schema) + { + [JsonPropertyName("action")] + public string Action => "add-schema"; + + [JsonPropertyName("schema")] + public IcebergSchemaBody Schema { get; } = schema; + } + + internal sealed class SetCurrentSchemaUpdate + { + [JsonPropertyName("action")] + public string Action => "set-current-schema"; + + [JsonPropertyName("schema-id")] + public int SchemaId => LastAdded; + } + + internal sealed class AddSpecUpdate(IcebergPartitionSpecBody spec) + { + [JsonPropertyName("action")] + public string Action => "add-spec"; + + [JsonPropertyName("spec")] + public IcebergPartitionSpecBody Spec { get; } = spec; + } + + internal sealed class SetDefaultSpecUpdate + { + [JsonPropertyName("action")] + public string Action => "set-default-spec"; + + [JsonPropertyName("spec-id")] + public int SpecId => LastAdded; + } + + internal sealed class AssertTableUuid(Guid uuid) + { + [JsonPropertyName("type")] + public string Type => "assert-table-uuid"; + + [JsonPropertyName("uuid")] + public Guid Uuid { get; } = uuid; + } + + internal sealed class AssertCurrentSchemaId(int? currentSchemaId) + { + [JsonPropertyName("type")] + public string Type => "assert-current-schema-id"; + + [JsonPropertyName("current-schema-id")] + public int? CurrentSchemaId { get; } = currentSchemaId; + } + + internal sealed class AssertLastAssignedFieldId(int lastAssignedFieldId) + { + [JsonPropertyName("type")] + public string Type => "assert-last-assigned-field-id"; + + [JsonPropertyName("last-assigned-field-id")] + public int LastAssignedFieldId { get; } = lastAssignedFieldId; + } + + internal sealed class AssertDefaultSpecId(int? defaultSpecId) + { + [JsonPropertyName("type")] + public string Type => "assert-default-spec-id"; + + [JsonPropertyName("default-spec-id")] + public int? DefaultSpecId { get; } = defaultSpecId; + } + + internal sealed class AssertLastAssignedPartitionId(int lastAssignedPartitionId) + { + [JsonPropertyName("type")] + public string Type => "assert-last-assigned-partition-id"; + + [JsonPropertyName("last-assigned-partition-id")] + public int LastAssignedPartitionId { get; } = lastAssignedPartitionId; + } +} From e2c825bb6131700fe09dd11e7f08e0713fcdf387 Mon Sep 17 00:00:00 2001 From: tr00d Date: Thu, 26 Nov 2026 11:03:26 +0100 Subject: [PATCH 2/2] test(storage): approve the Iceberg commit request bodies --- ...Request_ShouldSerializeEmptyCommit_GivenNoChange.verified.txt | 1 + ...eTableRequest_ShouldSerializePartitionSpecChange.verified.txt | 1 + ...zeRequirementsOfPartitionSpecChange_GivenBasedOn.verified.txt | 1 + ...SerializeRequirementsOfSchemaChange_GivenBasedOn.verified.txt | 1 + ...s.UpdateTableRequest_ShouldSerializeSchemaChange.verified.txt | 1 + 5 files changed, 5 insertions(+) create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange.verified.txt create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializePartitionSpecChange.verified.txt create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn.verified.txt create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn.verified.txt create mode 100644 packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeSchemaChange.verified.txt diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange.verified.txt b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange.verified.txt new file mode 100644 index 00000000..f11b7ecf --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange.verified.txt @@ -0,0 +1 @@ +{"requirements":[],"updates":[]} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializePartitionSpecChange.verified.txt b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializePartitionSpecChange.verified.txt new file mode 100644 index 00000000..54d1dcaf --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializePartitionSpecChange.verified.txt @@ -0,0 +1 @@ +{"requirements":[],"updates":[{"action":"add-spec","spec":{"fields":[{"source-id":3,"name":"country","transform":"identity"}]}},{"action":"set-default-spec","spec-id":-1}]} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn.verified.txt b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn.verified.txt new file mode 100644 index 00000000..29c8b078 --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn.verified.txt @@ -0,0 +1 @@ +{"requirements":[{"type":"assert-table-uuid","uuid":"b734865e-f9a5-4654-8b0b-e15683fcb195"},{"type":"assert-default-spec-id","default-spec-id":5},{"type":"assert-last-assigned-partition-id","last-assigned-partition-id":1000}],"updates":[{"action":"add-spec","spec":{"fields":[{"source-id":3,"name":"country","transform":"identity"}]}},{"action":"set-default-spec","spec-id":-1}]} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn.verified.txt b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn.verified.txt new file mode 100644 index 00000000..c85b0020 --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn.verified.txt @@ -0,0 +1 @@ +{"requirements":[{"type":"assert-table-uuid","uuid":"b734865e-f9a5-4654-8b0b-e15683fcb195"},{"type":"assert-current-schema-id","current-schema-id":4},{"type":"assert-last-assigned-field-id","last-assigned-field-id":2}],"updates":[{"action":"add-schema","schema":{"type":"struct","fields":[{"id":1,"name":"id","type":"long","required":true},{"id":3,"name":"country","type":"string","required":false}]}},{"action":"set-current-schema","schema-id":-1}]} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeSchemaChange.verified.txt b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeSchemaChange.verified.txt new file mode 100644 index 00000000..babf60fe --- /dev/null +++ b/packages/Storage/Storage.Tests/UpdateTable/Data/UpdateTableApprovalTests.UpdateTableRequest_ShouldSerializeSchemaChange.verified.txt @@ -0,0 +1 @@ +{"requirements":[],"updates":[{"action":"add-schema","schema":{"type":"struct","fields":[{"id":1,"name":"id","type":"long","required":true},{"id":3,"name":"country","type":"string","required":false}]}},{"action":"set-current-schema","schema-id":-1}]} \ No newline at end of file