Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/Postgrest/Postgrest.Tests/Observability/TelemetryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -46,6 +47,8 @@ private class Todo : BaseModel
[Column("name")] public string? Name { get; set; }
}

private sealed record TodoChanges(IReadOnlyDictionary<string, object?> Values) : IPostgrestUpdate<Todo>;

[TestInitialize]
public void SetUp()
{
Expand Down Expand Up @@ -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<Todo>().Filter("id", Operator.Equals, 1).UpdateAsync(new TodoChanges(new Dictionary<string, object?> { ["name"] = "a" }));
this.activities.Single(span => span.OperationName == "PATCH /todos").GetTagItem("supabase.postgrest.operation")
.Should().Be("update");
}

[TestMethod]
public async Task HttpSpan_ShouldTagTheOperationAndFunction_GivenAnRpcCall()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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<SinkRow>().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<SinkRow>().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<SinkRow>().InsertAsync(Values());
this.EmittedRequestBody.Should().Be("{}", "PostgREST rejects a write without a body (PGRST102)");
}

[TestMethod]
public async Task InsertAsync_ShouldConvertTheValuesLikeAModel()
{
await this.Client.Table<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>();
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<SinkRow>().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<SinkRow>().Invoking(table => table.InsertAsync(null!))
.Should().ThrowAsync<ArgumentNullException>().WithParameterName("values");
this.EmittedRequestCount.Should().Be(0);
}

[TestMethod]
public Task InsertManyAsync_ShouldThrow_GivenNoRows() =>
this.Client.Table<SinkRow>().Invoking(table => table.InsertManyAsync(null!))
.Should().ThrowAsync<ArgumentNullException>().WithParameterName("values");

[TestMethod]
public Task InsertManyAsync_ShouldThrow_GivenANullRow() =>
this.Client.Table<SinkRow>().Invoking(table => table.InsertManyAsync(new IPostgrestInsert<SinkRow>[] { Values(), null! }))
.Should().ThrowAsync<ArgumentNullException>().WithParameterName("values");

[TestMethod]
public Task InsertAsync_ShouldThrow_GivenValuesWithoutColumns() =>
this.Client.Table<SinkRow>().Invoking(table => table.InsertAsync(new SinkValues(null!)))
.Should().ThrowAsync<ArgumentNullException>().WithParameterName("values");

[TestMethod]
public Task UpdateAsync_ShouldThrow_GivenNoChanges() =>
this.Client.Table<SinkRow>().Invoking(table => table.UpdateAsync(null!))
.Should().ThrowAsync<ArgumentNullException>().WithParameterName("changes");
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// What a write from row values hands back: the rows the server returns, and the failure mapping.
/// </summary>
[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, object?> { ["string_value"] = stringValue });

[TestMethod]
public async Task InsertAsync_ShouldHandBackTheWrittenRows()
{
this.RespondWith(201, WrittenRow);
(await this.client.Table<SinkRow>().InsertAsync(Values("a"))).Models.Single().BoolValue.Should().BeFalse();
}

[TestMethod]
public async Task UpdateAsync_ShouldHandBackTheWrittenRows()
{
this.RespondWith(200, WrittenRow);
(await this.client.Table<SinkRow>().UpdateAsync(Values("a"))).Models.Single().StringValue.Should().Be("a");
}

[TestMethod]
public async Task InsertAsync_ShouldThrowUniquenessViolation_GivenADuplicateKey()
{
this.RespondWith(409, DuplicateBody);
(await this.client.Table<SinkRow>().Invoking(table => table.InsertAsync(Values("a")))
.Should().ThrowAsync<PostgrestException>()).Which.Reason.Should().Be(FailureHint.Reason.UniquenessViolation);
}
}
100 changes: 100 additions & 0 deletions packages/Postgrest/Postgrest.Tests/WriteRowValues/RowValuesTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Writing rows from values that set only some columns, against a live PostgREST on <c>kitchen_sink</c>, whose
/// <c>bool_value</c> defaults to <c>false</c>. Each test writes rows tagged with its own marker and removes them.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class RowValuesTests
{
private readonly string marker = $"values-{Guid.NewGuid():N}";
private readonly List<Guid> written = new();

[TestCleanup]
public async Task RemoveTheWrittenRows()
{
await LocalStack.Client().Table<SinkRow>().Filter("string_value", Operator.Like, $"{this.marker}%").Delete();
foreach (var id in this.written)
await LocalStack.Client().Table<SinkRow>().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<SinkRow> Read(string stringValue) =>
(await LocalStack.Client().Table<SinkRow>().Filter("string_value", Operator.Equals, stringValue).Single())!;

[TestMethod]
public async Task InsertAsync_ShouldApplyTheDefault_GivenAColumnLeftOut()
{
await LocalStack.Client().Table<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().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<SinkRow>().InsertAsync(Values(("string_value", this.marker)))).Model!.Id!.Value;
await LocalStack.Client().Table<SinkRow>().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<SinkRow>().InsertAsync(Values(("string_value", this.marker), ("bool_value", true)));
await LocalStack.Client().Table<SinkRow>().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<SinkRow>().InsertAsync(Values(("string_value", this.marker), ("bool_value", true)));
var updated = await LocalStack.Client().Table<SinkRow>().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();
}
}
19 changes: 19 additions & 0 deletions packages/Postgrest/Postgrest.Tests/WriteRowValues/SinkRow.cs
Original file line number Diff line number Diff line change
@@ -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<string, object?> Values) : IPostgrestInsert<SinkRow>, IPostgrestUpdate<SinkRow>;
Loading
Loading