diff --git a/packages/Postgrest/Postgrest.Tests/Observability/TelemetryTests.cs b/packages/Postgrest/Postgrest.Tests/Observability/TelemetryTests.cs index e2cd6933c..2c2e533c2 100644 --- a/packages/Postgrest/Postgrest.Tests/Observability/TelemetryTests.cs +++ b/packages/Postgrest/Postgrest.Tests/Observability/TelemetryTests.cs @@ -12,6 +12,7 @@ using Supabase.Postgrest.Attributes; using Supabase.Postgrest.Exceptions; using Supabase.Postgrest.Models; +using Supabase.Postgrest.WriteRowValues; using Supabase.TestSupport; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; @@ -46,6 +47,8 @@ private class Todo : BaseModel [Column("name")] public string? Name { get; set; } } + private sealed record TodoChanges(IReadOnlyDictionary Values) : IPostgrestUpdate; + [TestInitialize] public void SetUp() { @@ -136,6 +139,16 @@ public async Task HttpSpan_ShouldTagTheOperationAndTable_GivenATableCall() span.GetTagItem("supabase.postgrest.function").Should().BeNull(); } + [TestMethod] + public async Task HttpSpan_ShouldTagTheUpdateOperation_GivenAnUpdateFromRowValues() + { + this.server.Given(Request.Create().WithPath("/todos").UsingPatch()) + .RespondWith(Response.Create().WithStatusCode(200).WithHeader("Content-Type", "application/json").WithBody("[]")); + await this.client.Table().Filter("id", Operator.Equals, 1).UpdateAsync(new TodoChanges(new Dictionary { ["name"] = "a" })); + this.activities.Single(span => span.OperationName == "PATCH /todos").GetTagItem("supabase.postgrest.operation") + .Should().Be("update"); + } + [TestMethod] public async Task HttpSpan_ShouldTagTheOperationAndFunction_GivenAnRpcCall() { diff --git a/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesRequestTests.cs b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesRequestTests.cs new file mode 100644 index 000000000..cd5fe505e --- /dev/null +++ b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesRequestTests.cs @@ -0,0 +1,170 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Postgrest.Tests.Support; +using Supabase.Postgrest; +using Supabase.Postgrest.WriteRowValues; +using static Supabase.Postgrest.Constants; + +namespace Postgrest.Tests.WriteRowValues; + +/// +/// The request a write from row values sends: exactly the columns the values set, the union of the columns of +/// several rows with their missing columns taking the database default, and the checks made before any request. +/// +[TestClass] +[TestCategory("Contract")] +public class RowValuesRequestTests : RequestApprovalFixture +{ + private static SinkValues Values(params (string Column, object? Value)[] columns) => + new(columns.ToDictionary(column => column.Column, column => column.Value)); + + [TestMethod] + public async Task InsertAsync_ShouldPostExactlyTheColumnsTheValuesSet() + { + await this.Client.Table().InsertAsync(Values(("string_value", "a"), ("bool_value", null))); + using var scope = new AssertionScope(); + this.EmittedRequestMethod.Should().Be("POST"); + this.EmittedRequestBody.Should().Be("""{"string_value":"a","bool_value":null}"""); + this.EmittedRequestQuery.AllKeys.Should().NotContain("columns"); + this.EmittedRequestHeader("Prefer").Should().Be("return=representation"); + } + + [TestMethod] + public async Task InsertAsync_ShouldApplyTheGivenOptions() + { + await this.Client.Table().InsertAsync(Values(("string_value", "a")), + new QueryOptions { Returning = QueryOptions.ReturnType.Minimal }); + this.EmittedRequestHeader("Prefer").Should().Be("return=minimal"); + } + + [TestMethod] + public async Task InsertAsync_ShouldPostAnEmptyObject_GivenValuesThatSetNoColumn() + { + await this.Client.Table().InsertAsync(Values()); + this.EmittedRequestBody.Should().Be("{}", "PostgREST rejects a write without a body (PGRST102)"); + } + + [TestMethod] + public async Task InsertAsync_ShouldConvertTheValuesLikeAModel() + { + await this.Client.Table().InsertAsync(Values(("datetime_value", new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc)))); + this.EmittedRequestBody.Should().Be("""{"datetime_value":"2026-01-02T03:04:05Z"}"""); + } + + [TestMethod] + public async Task InsertAsync_ShouldNotUpsert_GivenOptionsThatAskForAnUpsert() + { + await this.Client.Table().InsertAsync(Values(("string_value", "a")), new QueryOptions { Upsert = true }); + this.EmittedRequestHeader("Prefer").Should().NotContain("resolution", "upserts go through UpsertAsync"); + } + + [TestMethod] + public async Task InsertManyAsync_ShouldSendTheUnionOfTheColumnsAndTheirDefaults_GivenSeveralRows() + { + await this.Client.Table().InsertManyAsync(new[] + { + Values(("string_value", "a")), + Values(("bool_value", true), ("string_value", "b")) + }, new QueryOptions { MissingFields = QueryOptions.MissingFieldType.Null }); + using var scope = new AssertionScope(); + this.EmittedRequestBody.Should().Be("""[{"string_value":"a"},{"bool_value":true,"string_value":"b"}]"""); + this.EmittedRequestQuery["columns"].Should().Be("\"string_value\",\"bool_value\""); + this.EmittedRequestHeader("Prefer").Should().Be("return=representation,missing=default", + "a column a row leaves out takes its default, whatever the options say"); + } + + [TestMethod] + public async Task InsertManyAsync_ShouldSendNoColumns_GivenRowsThatSetNoColumn() + { + await this.Client.Table().InsertManyAsync(new[] { Values(), Values() }); + using var scope = new AssertionScope(); + this.EmittedRequestBody.Should().Be("[{},{}]"); + this.EmittedRequestQuery.AllKeys.Should().NotContain("columns"); + } + + [TestMethod] + public async Task UpsertAsync_ShouldMergeDuplicatesOnTheGivenConflict() + { + await this.Client.Table().UpsertAsync(Values(("id", "7"), ("string_value", "a")), + new QueryOptions { OnConflict = "unique_value" }); + using var scope = new AssertionScope(); + this.EmittedRequestBody.Should().Be("""{"id":"7","string_value":"a"}"""); + this.EmittedRequestHeader("Prefer").Should().Be("resolution=merge-duplicates,return=representation"); + this.EmittedRequestQuery["on_conflict"].Should().Be("unique_value"); + } + + [TestMethod] + public async Task UpsertManyAsync_ShouldSendTheUnionOfTheColumnsAndTheirDefaults_GivenSeveralRows() + { + await this.Client.Table().UpsertManyAsync(new[] { Values(("id", "1")), Values(("id", "2"), ("string_value", "b")) }); + using var scope = new AssertionScope(); + this.EmittedRequestQuery["columns"].Should().Be("\"id\",\"string_value\""); + this.EmittedRequestHeader("Prefer").Should().Be("resolution=merge-duplicates,return=representation,missing=default"); + } + + [TestMethod] + public async Task UpdateAsync_ShouldPatchTheFilteredRowsWithExactlyTheColumnsTheValuesSet() + { + await this.Client.Table().Filter("id", Operator.Equals, "7").UpdateAsync(Values(("string_value", "a"))); + using var scope = new AssertionScope(); + this.EmittedRequestMethod.Should().Be("PATCH"); + this.EmittedRequestBody.Should().Be("""{"string_value":"a"}"""); + this.EmittedRequestQuery["id"].Should().Be("eq.7"); + } + + [TestMethod] + public async Task UpdateAsync_ShouldApplyTheGivenOptions() + { + await this.Client.Table().Filter("id", Operator.Equals, "7").UpdateAsync(Values(("string_value", "a")), + new QueryOptions { Count = QueryOptions.CountType.Exact }); + this.EmittedRequestHeader("Prefer").Should().Be("return=representation,count=exact"); + } + + [TestMethod] + public async Task UpdateAsync_ShouldDropThePendingFilters_GivenALaterRead() + { + var table = this.Client.Table(); + await table.Filter("id", Operator.Equals, "7").UpdateAsync(Values(("string_value", "a"))); + await table.Get(); + this.EmittedRequestQueryOfLast.AllKeys.Should().NotContain("id"); + } + + [TestMethod] + public async Task UpdateAsync_ShouldPatchWithAnEmptyObject_GivenValuesThatSetNoColumn() + { + await this.Client.Table().Filter("id", Operator.Equals, "7").UpdateAsync(Values()); + this.EmittedRequestBody.Should().Be("{}", "an update that sets no column is the service's to answer"); + } + + [TestMethod] + public async Task InsertAsync_ShouldThrowBeforeAnyRequest_GivenNoValues() + { + await this.Client.Table().Invoking(table => table.InsertAsync(null!)) + .Should().ThrowAsync().WithParameterName("values"); + this.EmittedRequestCount.Should().Be(0); + } + + [TestMethod] + public Task InsertManyAsync_ShouldThrow_GivenNoRows() => + this.Client.Table().Invoking(table => table.InsertManyAsync(null!)) + .Should().ThrowAsync().WithParameterName("values"); + + [TestMethod] + public Task InsertManyAsync_ShouldThrow_GivenANullRow() => + this.Client.Table().Invoking(table => table.InsertManyAsync(new IPostgrestInsert[] { Values(), null! })) + .Should().ThrowAsync().WithParameterName("values"); + + [TestMethod] + public Task InsertAsync_ShouldThrow_GivenValuesWithoutColumns() => + this.Client.Table().Invoking(table => table.InsertAsync(new SinkValues(null!))) + .Should().ThrowAsync().WithParameterName("values"); + + [TestMethod] + public Task UpdateAsync_ShouldThrow_GivenNoChanges() => + this.Client.Table().Invoking(table => table.UpdateAsync(null!)) + .Should().ThrowAsync().WithParameterName("changes"); +} diff --git a/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesResultTests.cs b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesResultTests.cs new file mode 100644 index 000000000..d40e2186d --- /dev/null +++ b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesResultTests.cs @@ -0,0 +1,65 @@ +using System.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Postgrest; +using Supabase.Postgrest.Exceptions; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; + +namespace Postgrest.Tests.WriteRowValues; + +/// +/// What a write from row values hands back: the rows the server returns, and the failure mapping. +/// +[TestClass] +[TestCategory("Contract")] +public class RowValuesResultTests +{ + private const string WrittenRow = """[{"id":"7c9e6679-7425-40de-944b-e07fc1f90ae7","string_value":"a","bool_value":false}]"""; + + private const string DuplicateBody = + """{"code":"23505","details":"Key (unique_value)=(a) already exists.","hint":null,"message":"duplicate key value violates unique constraint \"kitchen_sink_unique_value_key\""}"""; + + private WireMockServer server = null!; + private Client client = null!; + + [TestInitialize] + public void SetUp() + { + this.server = WireMockServer.Start(); + this.client = new Client(this.server.Url!, new ClientOptions()); + } + + [TestCleanup] + public void TearDown() => this.server.Stop(); + + private void RespondWith(int status, string body) => + this.server.Given(Request.Create().UsingAnyMethod()).RespondWith(Response.Create().WithStatusCode(status) + .WithHeader("Content-Type", "application/json").WithBody(body)); + + private static SinkValues Values(string stringValue) => new(new System.Collections.Generic.Dictionary { ["string_value"] = stringValue }); + + [TestMethod] + public async Task InsertAsync_ShouldHandBackTheWrittenRows() + { + this.RespondWith(201, WrittenRow); + (await this.client.Table().InsertAsync(Values("a"))).Models.Single().BoolValue.Should().BeFalse(); + } + + [TestMethod] + public async Task UpdateAsync_ShouldHandBackTheWrittenRows() + { + this.RespondWith(200, WrittenRow); + (await this.client.Table().UpdateAsync(Values("a"))).Models.Single().StringValue.Should().Be("a"); + } + + [TestMethod] + public async Task InsertAsync_ShouldThrowUniquenessViolation_GivenADuplicateKey() + { + this.RespondWith(409, DuplicateBody); + (await this.client.Table().Invoking(table => table.InsertAsync(Values("a"))) + .Should().ThrowAsync()).Which.Reason.Should().Be(FailureHint.Reason.UniquenessViolation); + } +} diff --git a/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesTests.cs b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesTests.cs new file mode 100644 index 000000000..7720f6081 --- /dev/null +++ b/packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesTests.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Postgrest.Tests.Support; +using static Supabase.Postgrest.Constants; + +namespace Postgrest.Tests.WriteRowValues; + +/// +/// Writing rows from values that set only some columns, against a live PostgREST on kitchen_sink, whose +/// bool_value defaults to false. Each test writes rows tagged with its own marker and removes them. +/// +[TestClass] +[TestCategory("E2E")] +public class RowValuesTests +{ + private readonly string marker = $"values-{Guid.NewGuid():N}"; + private readonly List written = new(); + + [TestCleanup] + public async Task RemoveTheWrittenRows() + { + await LocalStack.Client().Table().Filter("string_value", Operator.Like, $"{this.marker}%").Delete(); + foreach (var id in this.written) + await LocalStack.Client().Table().Filter("id", Operator.Equals, id.ToString()).Delete(); + } + + private static SinkValues Values(params (string Column, object? Value)[] columns) => + new(columns.ToDictionary(column => column.Column, column => column.Value)); + + private async Task Read(string stringValue) => + (await LocalStack.Client().Table().Filter("string_value", Operator.Equals, stringValue).Single())!; + + [TestMethod] + public async Task InsertAsync_ShouldApplyTheDefault_GivenAColumnLeftOut() + { + await LocalStack.Client().Table().InsertAsync(Values(("string_value", this.marker))); + (await this.Read(this.marker)).BoolValue.Should().BeFalse("bool_value defaults to false"); + } + + [TestMethod] + public async Task InsertAsync_ShouldWriteNull_GivenANullValue() + { + await LocalStack.Client().Table().InsertAsync(Values(("string_value", this.marker), ("bool_value", null))); + (await this.Read(this.marker)).BoolValue.Should().BeNull(); + } + + [TestMethod] + public async Task InsertManyAsync_ShouldApplyTheDefaultPerRow_GivenRowsThatSetDifferentColumns() + { + await LocalStack.Client().Table().InsertManyAsync(new[] + { + Values(("string_value", $"{this.marker}-a")), + Values(("string_value", $"{this.marker}-b"), ("bool_value", true)) + }); + using var scope = new AssertionScope(); + (await this.Read($"{this.marker}-a")).BoolValue.Should().BeFalse("a column a row leaves out takes its default, not null"); + (await this.Read($"{this.marker}-b")).BoolValue.Should().BeTrue(); + } + + [TestMethod] + public async Task InsertManyAsync_ShouldInsertRowsOfDefaults_GivenRowsThatSetNoColumn() + { + var inserted = await LocalStack.Client().Table().InsertManyAsync(new[] { Values(), Values() }); + this.written.AddRange(inserted.Models.Select(row => row.Id!.Value)); + inserted.Models.Should().HaveCount(2).And.OnlyContain(row => row.BoolValue == false); + } + + [TestMethod] + public async Task UpsertAsync_ShouldUpdateTheRow_GivenAnExistingPrimaryKey() + { + var id = (await LocalStack.Client().Table().InsertAsync(Values(("string_value", this.marker)))).Model!.Id!.Value; + await LocalStack.Client().Table().UpsertAsync(Values(("id", id), ("string_value", $"{this.marker}-upserted"))); + (await this.Read($"{this.marker}-upserted")).Id.Should().Be(id); + } + + [TestMethod] + public async Task UpdateAsync_ShouldChangeOnlyTheColumnsItSets() + { + await LocalStack.Client().Table().InsertAsync(Values(("string_value", this.marker), ("bool_value", true))); + await LocalStack.Client().Table().Filter("string_value", Operator.Equals, this.marker) + .UpdateAsync(Values(("string_value", $"{this.marker}-updated"))); + (await this.Read($"{this.marker}-updated")).BoolValue.Should().BeTrue("a column the update leaves out keeps its value"); + } + + [TestMethod] + public async Task UpdateAsync_ShouldChangeNothingAndReturnNoRow_GivenNoColumn() + { + await LocalStack.Client().Table().InsertAsync(Values(("string_value", this.marker), ("bool_value", true))); + var updated = await LocalStack.Client().Table().Filter("string_value", Operator.Equals, this.marker) + .UpdateAsync(Values()); + using var scope = new AssertionScope(); + updated.Models.Should().BeEmpty("PostgREST answers an update that sets no column with no row, even when the filter matches"); + (await this.Read(this.marker)).BoolValue.Should().BeTrue(); + } +} diff --git a/packages/Postgrest/Postgrest.Tests/WriteRowValues/SinkRow.cs b/packages/Postgrest/Postgrest.Tests/WriteRowValues/SinkRow.cs new file mode 100644 index 000000000..ccbed1234 --- /dev/null +++ b/packages/Postgrest/Postgrest.Tests/WriteRowValues/SinkRow.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using Supabase.Postgrest.Attributes; +using Supabase.Postgrest.Models; +using Supabase.Postgrest.WriteRowValues; + +namespace Postgrest.Tests.WriteRowValues; + +[Table("kitchen_sink")] +public class SinkRow : BaseModel +{ + [PrimaryKey("id", true)] public Guid? Id { get; set; } + + [Column("string_value")] public string? StringValue { get; set; } + + [Column("bool_value")] public bool? BoolValue { get; set; } +} + +public sealed record SinkValues(IReadOnlyDictionary Values) : IPostgrestInsert, IPostgrestUpdate; diff --git a/packages/Postgrest/Postgrest/BulkWrite/BulkColumns.cs b/packages/Postgrest/Postgrest/Common/BulkColumns.cs similarity index 58% rename from packages/Postgrest/Postgrest/BulkWrite/BulkColumns.cs rename to packages/Postgrest/Postgrest/Common/BulkColumns.cs index 663d13544..3c3547676 100644 --- a/packages/Postgrest/Postgrest/BulkWrite/BulkColumns.cs +++ b/packages/Postgrest/Postgrest/Common/BulkColumns.cs @@ -1,14 +1,16 @@ using System.Collections.Generic; using System.Linq; -namespace Supabase.Postgrest.BulkWrite; +namespace Supabase.Postgrest.Common; internal static class BulkColumns { internal static IReadOnlyList UnionOf(object? requestBody) => - RowsOf(requestBody) - .OfType>() - .SelectMany(row => row.Keys) + UnionOf(RowsOf(requestBody).OfType>().Select(row => row.Keys)); + + internal static IReadOnlyList UnionOf(IEnumerable> columnsOfEachRow) => + columnsOfEachRow + .SelectMany(columns => columns) .Distinct() .Select(Quote) .ToList(); diff --git a/packages/Postgrest/Postgrest/Helpers.cs b/packages/Postgrest/Postgrest/Helpers.cs index b2f4ac769..4d05f330d 100644 --- a/packages/Postgrest/Postgrest/Helpers.cs +++ b/packages/Postgrest/Postgrest/Helpers.cs @@ -19,6 +19,7 @@ using Supabase.Postgrest.Models; using Supabase.Postgrest.Responses; using Supabase.Postgrest.RetryTransientFailures; +using Supabase.Postgrest.WriteRowValues; [assembly: InternalsVisibleTo("Postgrest.Tests")] @@ -114,7 +115,11 @@ public static async Task MakeRequestAsync(ClientOptions clientOpti string? body = null; - if (data != null && method != HttpMethod.Get) + if (data is RowValues rows) + { + body = rows.Json; + } + else if (data != null && method != HttpMethod.Get) { var stringContent = JsonSerializer.Serialize(data, serializerSettings); diff --git a/packages/Postgrest/Postgrest/Interfaces/IPostgrestTable.cs b/packages/Postgrest/Postgrest/Interfaces/IPostgrestTable.cs index ef1ab0402..89f471e94 100644 --- a/packages/Postgrest/Postgrest/Interfaces/IPostgrestTable.cs +++ b/packages/Postgrest/Postgrest/Interfaces/IPostgrestTable.cs @@ -11,6 +11,7 @@ using Supabase.Postgrest.Models; using Supabase.Postgrest.Responses; using Supabase.Postgrest.RetryTransientFailures; +using Supabase.Postgrest.WriteRowValues; namespace Supabase.Postgrest.Interfaces; @@ -719,6 +720,88 @@ Task> Update(QueryOptions? options = null, Task> Update(TModel model, QueryOptions? options = null, CancellationToken cancellationToken = default); + /// + /// Inserts a row with only the columns sets: a column it leaves out takes its database + /// default, and a column set to null is written as SQL NULL. is + /// ignored; use UpsertAsync to insert or update, and InsertManyAsync for several rows. + /// + /// The values of the row. + /// The representation and count to return. + /// Cancels the request. + /// The inserted row, unless asks for none. + /// or its values are null. + /// The server rejects the row. + /// + /// ().InsertAsync(new BooksInsert(authorId: 2, title: "Dune") { PublishedOn = null }); + /// ]]> + /// + Task> InsertAsync(IPostgrestInsert values, QueryOptions? options = null, + CancellationToken cancellationToken = default); + + /// + /// Inserts several rows in one request. Each row sends only the columns it sets, and a column a row leaves out + /// takes its database default even when another row sets it. and + /// are ignored. + /// + /// The values of each row. + /// The representation and count to return. + /// Cancels the request. + /// The inserted rows, unless asks for none. + /// , one of its rows or a row's values are null. + /// The server rejects the rows. + Task> InsertManyAsync(IReadOnlyCollection> values, + QueryOptions? options = null, CancellationToken cancellationToken = default); + + /// + /// Inserts a row, or updates the row it conflicts with, with only the columns sets. + /// The conflict is resolved on the primary key, or on when it is set. + /// + /// The values of the row. + /// The conflict target, duplicate resolution, representation and count. + /// Cancels the request. + /// The written row, unless asks for none. + /// or its values are null. + /// The server rejects the row. + Task> UpsertAsync(IPostgrestInsert values, QueryOptions? options = null, + CancellationToken cancellationToken = default); + + /// + /// Inserts several rows, or updates the rows they conflict with, in one request. A column a row leaves out + /// takes its database default even when another row sets it, and that holds for a row that already exists: + /// its stored value in that column is replaced by the default. Send rows that set different columns in + /// separate calls to keep stored values. + /// + /// The values of each row. + /// The conflict target, duplicate resolution, representation and count. + /// Cancels the request. + /// The written rows, unless asks for none. + /// , one of its rows or a row's values are null. + /// The server rejects the rows. + Task> UpsertManyAsync(IReadOnlyCollection> values, + QueryOptions? options = null, CancellationToken cancellationToken = default); + + /// + /// Updates the rows the query filters with only the columns sets: a column it leaves + /// out keeps its value, and a column set to null is written as SQL NULL. An update that sets no + /// column changes nothing; with PostgREST then answers with + /// no rows whether or not the filter matched, so the response cannot tell the two apart. Check that + /// is empty before calling when that matters. + /// + /// The changes to make. + /// The representation and count to return. + /// Cancels the request. + /// The updated rows, unless asks for none. + /// or its values are null. + /// The server rejects the update. + /// + /// ().Where(book => book.Id == 7).UpdateAsync(new BooksUpdate { Title = "Renamed" }); + /// ]]> + /// + Task> UpdateAsync(IPostgrestUpdate changes, QueryOptions? options = null, + CancellationToken cancellationToken = default); + /// /// Executes an UPSERT query using the defined query params on the current instance. /// diff --git a/packages/Postgrest/Postgrest/PublicAPI.Unshipped.txt b/packages/Postgrest/Postgrest/PublicAPI.Unshipped.txt index 0e85a67b5..3d8970085 100644 --- a/packages/Postgrest/Postgrest/PublicAPI.Unshipped.txt +++ b/packages/Postgrest/Postgrest/PublicAPI.Unshipped.txt @@ -66,13 +66,27 @@ Supabase.Postgrest.Interfaces.IPostgrestClient.WithSchema(string! schema) -> Sup Supabase.Postgrest.Interfaces.IPostgrestTable.Embed(Supabase.Postgrest.Common.RelatedRows! relatedRows) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Interfaces.IPostgrestTable.Filter(string! columnName, string! op, string! criterion) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Interfaces.IPostgrestTable.GetAsync(System.Linq.Expressions.Expression!>! selection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Interfaces.IPostgrestTable.InsertAsync(Supabase.Postgrest.WriteRowValues.IPostgrestInsert! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Interfaces.IPostgrestTable.InsertManyAsync(System.Collections.Generic.IReadOnlyCollection!>! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! Supabase.Postgrest.Interfaces.IPostgrestTable.Retry(Supabase.Postgrest.RetryTransientFailures.AutoRetry autoRetry) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Interfaces.IPostgrestTable.Schema.get -> string! +Supabase.Postgrest.Interfaces.IPostgrestTable.UpdateAsync(Supabase.Postgrest.WriteRowValues.IPostgrestUpdate! changes, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Interfaces.IPostgrestTable.UpsertAsync(Supabase.Postgrest.WriteRowValues.IPostgrestInsert! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Interfaces.IPostgrestTable.UpsertManyAsync(System.Collections.Generic.IReadOnlyCollection!>! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! Supabase.Postgrest.RetryTransientFailures.AutoRetry Supabase.Postgrest.RetryTransientFailures.AutoRetry.Disabled = 1 -> Supabase.Postgrest.RetryTransientFailures.AutoRetry Supabase.Postgrest.RetryTransientFailures.AutoRetry.Enabled = 0 -> Supabase.Postgrest.RetryTransientFailures.AutoRetry Supabase.Postgrest.Table.Embed(Supabase.Postgrest.Common.RelatedRows! relatedRows) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Table.Filter(string! columnName, string! op, string! criterion) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Table.GetAsync(System.Linq.Expressions.Expression!>! selection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Table.InsertAsync(Supabase.Postgrest.WriteRowValues.IPostgrestInsert! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Table.InsertManyAsync(System.Collections.Generic.IReadOnlyCollection!>! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! Supabase.Postgrest.Table.Retry(Supabase.Postgrest.RetryTransientFailures.AutoRetry autoRetry) -> Supabase.Postgrest.Interfaces.IPostgrestTable! Supabase.Postgrest.Table.Schema.get -> string! +Supabase.Postgrest.Table.UpdateAsync(Supabase.Postgrest.WriteRowValues.IPostgrestUpdate! changes, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Table.UpsertAsync(Supabase.Postgrest.WriteRowValues.IPostgrestInsert! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.Table.UpsertManyAsync(System.Collections.Generic.IReadOnlyCollection!>! values, Supabase.Postgrest.QueryOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!>! +Supabase.Postgrest.WriteRowValues.IPostgrestInsert +Supabase.Postgrest.WriteRowValues.IPostgrestInsert.Values.get -> System.Collections.Generic.IReadOnlyDictionary! +Supabase.Postgrest.WriteRowValues.IPostgrestUpdate +Supabase.Postgrest.WriteRowValues.IPostgrestUpdate.Values.get -> System.Collections.Generic.IReadOnlyDictionary! diff --git a/packages/Postgrest/Postgrest/Table.cs b/packages/Postgrest/Postgrest/Table.cs index 5077a9c75..53fd7665e 100644 --- a/packages/Postgrest/Postgrest/Table.cs +++ b/packages/Postgrest/Postgrest/Table.cs @@ -10,7 +10,6 @@ using Supabase.Core.Attributes; using Supabase.Core.Extensions; using Supabase.Postgrest.Attributes; -using Supabase.Postgrest.BulkWrite; using Supabase.Postgrest.Common; using Supabase.Postgrest.Explain; using Supabase.Postgrest.Extensions; @@ -22,6 +21,7 @@ using Supabase.Postgrest.ReadProjection; using Supabase.Postgrest.Responses; using Supabase.Postgrest.RetryTransientFailures; +using Supabase.Postgrest.WriteRowValues; using static Supabase.Postgrest.Constants; namespace Supabase.Postgrest; @@ -484,6 +484,68 @@ public Task> Update(TModel model, QueryOptions? options return request; } + /// + public Task> InsertAsync(IPostgrestInsert values, QueryOptions? options = null, + CancellationToken cancellationToken = default) => + this.PostRows(this.OneRow(values?.Values, nameof(values)), Inserting(options), cancellationToken); + + /// + public Task> InsertManyAsync(IReadOnlyCollection> values, + QueryOptions? options = null, CancellationToken cancellationToken = default) => + this.PostRows(this.SeveralRows(values), Inserting(options), cancellationToken); + + /// + public Task> UpsertAsync(IPostgrestInsert values, QueryOptions? options = null, + CancellationToken cancellationToken = default) => + this.PostRows(this.OneRow(values?.Values, nameof(values)), Upserting(options), cancellationToken); + + /// + public Task> UpsertManyAsync(IReadOnlyCollection> values, + QueryOptions? options = null, CancellationToken cancellationToken = default) => + this.PostRows(this.SeveralRows(values), Upserting(options), cancellationToken); + + /// + public Task> UpdateAsync(IPostgrestUpdate changes, QueryOptions? options = null, + CancellationToken cancellationToken = default) + { + var body = this.OneRow(changes?.Values, nameof(changes)); + this.method = new HttpMethod("PATCH"); + var request = this.Send(this.method, body, (options ?? new QueryOptions()).ToHeaders(), cancellationToken, isUpdate: true); + this.Clear(); + return request; + } + + private RowValues OneRow(IReadOnlyDictionary? values, string parameter) => + RowValues.OfOneRow(values ?? throw new ArgumentNullException(parameter), this.serializerSettings); + + private RowValues SeveralRows(IReadOnlyCollection>? values) => + RowValues.OfRows((values ?? throw new ArgumentNullException(nameof(values))) + .Select(row => row?.Values ?? throw new ArgumentNullException(nameof(values))) + .ToList(), this.serializerSettings); + + private Task> PostRows(RowValues rows, QueryOptions options, CancellationToken cancellationToken) + { + if (rows.HoldsSeveralRows) + options.MissingFields = QueryOptions.MissingFieldType.ColumnDefault; + + this.columns.AddRange(rows.Columns); + return this.PerformInsert(rows, options, cancellationToken); + } + + private static QueryOptions Inserting(QueryOptions? options) + { + var inserting = options?.Clone() ?? new QueryOptions(); + inserting.Upsert = false; + return inserting; + } + + private static QueryOptions Upserting(QueryOptions? options) + { + var upserting = options?.Clone() ?? new QueryOptions(); + upserting.Upsert = true; + return upserting; + } + /// [ImplementedCapability("database.mutate.delete")] @@ -675,6 +737,8 @@ public string GenerateUrl() { if (data == null) return new Dictionary(); + if (data is RowValues) return data; + var operation = isUpsert ? PostgrestOperation.Upsert : isInsert ? PostgrestOperation.Insert : isUpdate ? PostgrestOperation.Update : PostgrestOperation.None; diff --git a/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestInsert.cs b/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestInsert.cs new file mode 100644 index 000000000..2f4862f7a --- /dev/null +++ b/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestInsert.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using Supabase.Postgrest.Models; + +namespace Supabase.Postgrest.WriteRowValues; + +/// +/// The values of a row to insert into the table of : only the columns they set are +/// sent. A column they leave out takes its database default, and a column set to null is written as SQL +/// NULL. Types generated from the database schema implement it; a caller can too, with any dictionary. +/// +/// The model of the table the row goes to. +public interface IPostgrestInsert where TModel : BaseModel, new() +{ + /// + /// The value of each column the row sets, keyed by the column's name in the database. + /// + IReadOnlyDictionary Values { get; } +} diff --git a/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestUpdate.cs b/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestUpdate.cs new file mode 100644 index 000000000..d6e1cdaff --- /dev/null +++ b/packages/Postgrest/Postgrest/WriteRowValues/IPostgrestUpdate.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using Supabase.Postgrest.Models; + +namespace Supabase.Postgrest.WriteRowValues; + +/// +/// The changes to make to the rows of the table of a query filters: only the columns +/// they set are sent. A column they leave out keeps its value, and a column set to null is written as SQL +/// NULL. An update that sets no column changes nothing; with +/// PostgREST then answers with no rows whether or not the filter matched, so the response cannot tell the two apart. +/// Check that is empty before calling when that matters. +/// +/// The model of the table the rows belong to. +public interface IPostgrestUpdate where TModel : BaseModel, new() +{ + /// + /// The new value of each column the update sets, keyed by the column's name in the database. + /// + IReadOnlyDictionary Values { get; } +} diff --git a/packages/Postgrest/Postgrest/WriteRowValues/RowValues.cs b/packages/Postgrest/Postgrest/WriteRowValues/RowValues.cs new file mode 100644 index 000000000..e99b99141 --- /dev/null +++ b/packages/Postgrest/Postgrest/WriteRowValues/RowValues.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using Supabase.Postgrest.Common; + +namespace Supabase.Postgrest.WriteRowValues; + +internal sealed class RowValues +{ + private RowValues(string json, IReadOnlyList columns, bool holdsSeveralRows) + { + this.Json = json; + this.Columns = columns; + this.HoldsSeveralRows = holdsSeveralRows; + } + + internal string Json { get; } + + internal IReadOnlyList Columns { get; } + + internal bool HoldsSeveralRows { get; } + + internal static RowValues OfOneRow(IReadOnlyDictionary values, JsonSerializerOptions options) => + new(JsonSerializer.Serialize(values, options), Array.Empty(), false); + + internal static RowValues OfRows(IReadOnlyList> rows, JsonSerializerOptions options) => + new(JsonSerializer.Serialize(rows, options), BulkColumns.UnionOf(rows.Select(row => row.Keys)), true); +}