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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Postgrest.Tests.Models;
using Postgrest.Tests.Support;

namespace Postgrest.Tests.RawFilter;

/// <summary>
/// The query string a raw <c>Filter(column, op, criterion)</c> puts on the request, on a table and on a
/// function call.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class RawFilterRequestTests : RequestApprovalFixture
{
[TestMethod]
public async Task Get_ShouldSendTheRawFilterAsTheColumnParameter_GivenATable()
{
await this.Client.Table<User>().Filter("tags", "cs", "{\"a\",\"b\"}").Get();
this.EmittedRequestQuery["tags"].Should().Be("cs.{\"a\",\"b\"}");
}

[TestMethod]
public async Task Get_ShouldSendTheRawFilterAsTheColumnParameter_GivenAFunctionCall()
{
await this.Client.CallFunction<User>("list_users").Filter("username", "not.in", "(\"supabot\")").Get();
this.EmittedRequestQuery["username"].Should().Be("not.in.(\"supabot\")");
}
}
54 changes: 54 additions & 0 deletions packages/Postgrest/Postgrest.Tests/RawFilter/RawFilterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Postgrest.Tests.Models;
using Postgrest.Tests.Support;
using Supabase.Postgrest.Exceptions;
using static Supabase.Postgrest.Constants;

namespace Postgrest.Tests.RawFilter;

/// <summary>
/// A raw <c>Filter(column, op, criterion)</c> selecting rows against a live PostgREST. Other E2E classes add
/// users to the shared table, so each test compares with the same predicate applied in memory.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class RawFilterTests
{
private static readonly string[] Picked = { "kiwicopple", "dragarcia" };
private const string PickedList = "(\"kiwicopple\",\"dragarcia\")";

private static async Task<List<string>> AllUsernames() =>
(await LocalStack.Client().Table<User>().Get()).Models.Select(user => user.Username!).ToList();

[TestMethod]
public async Task Filter_ShouldSelectRowsMatchingTheRawFilter() =>
(await LocalStack.Client().Table<User>().Filter("username", "in", PickedList).Get()).Models
.Select(user => user.Username).Should().BeEquivalentTo(Picked);

[TestMethod]
public async Task Filter_ShouldExcludeRowsMatchingTheRawFilter_GivenANegatedOperator() =>
(await LocalStack.Client().Table<User>().Filter("username", "not.in", PickedList).Get()).Models
.Select(user => user.Username).Should().BeEquivalentTo((await AllUsernames()).Except(Picked));

[TestMethod]
public async Task Filter_ShouldThrow_GivenAnOperatorPostgrestDoesNotKnow()
{
var act = () => LocalStack.Client().Table<User>().Filter("username", "bogus", "x").Get();
await act.Should().ThrowAsync<PostgrestException>();
}

[TestMethod]
public async Task Filter_ShouldNarrowTheRowsOfAFunctionCall()
{
var online = await LocalStack.Client().Table<User>().Filter("status", Operator.Equals, "ONLINE").Get();
(await LocalStack.Client().CallFunction<User>("list_users_by_status", new { wanted_status = "ONLINE" })
.Filter("username", "match", "^s").Get()).Models.Select(user => user.Username).Should()
.BeEquivalentTo(online.Models.Select(user => user.Username)
.Where(name => name!.StartsWith("s", StringComparison.Ordinal)));
}
}
52 changes: 52 additions & 0 deletions packages/Postgrest/Postgrest.Tests/RawFilter/RawFilterUrlTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Collections.Specialized;
using System.Web;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Postgrest.Tests.Models;
using Supabase.Postgrest;
using Supabase.Postgrest.Interfaces;
using static Supabase.Postgrest.Constants;

namespace Postgrest.Tests.RawFilter;

/// <summary>
/// How a raw <c>Filter(column, op, criterion)</c> becomes a query parameter of the request URL.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class RawFilterUrlTests
{
private readonly Client client = new("http://localhost:54321/rest/v1");

private static NameValueCollection Query(IPostgrestTable<User> table) =>
HttpUtility.ParseQueryString(new Uri(table.GenerateUrl()).Query);

[TestMethod]
public void Filter_ShouldSendTheOperatorAndCriterionVerbatim() =>
Query(this.client.Table<User>().Filter("username", "like", "%bot"))["username"].Should()
.Be("like.%bot", "a raw filter is sent as given, without the * wildcard translation of Operator.Like");

[TestMethod]
public void Filter_ShouldKeepANegatedOperator() =>
Query(this.client.Table<User>().Filter("username", "not.in", "(\"supabot\",\"kiwicopple\")"))["username"]
.Should().Be("not.in.(\"supabot\",\"kiwicopple\")");

[TestMethod]
public void Filter_ShouldSendEachRawFilter_GivenTwoOnTheSameColumn() =>
Query(this.client.Table<User>().Filter("username", "gte", "a").Filter("username", "lt", "m"))
.GetValues("username").Should().Equal("gte.a", "lt.m");

[TestMethod]
public void Filter_ShouldSendTheRawFilterNextToTheTypedOnes() =>
Query(this.client.Table<User>().Filter("status", Operator.Equals, "ONLINE").Filter("username", "match", "^s"))
.AllKeys.Should().Contain(new[] { "status", "username" });

[TestMethod]
public void Clear_ShouldDropThePendingRawFilters()
{
var table = this.client.Table<User>().Filter("username", "eq", "supabot");
table.Clear();
Query(table)["username"].Should().BeNull();
}
}
6 changes: 6 additions & 0 deletions packages/Postgrest/Postgrest/CallFunction/FunctionCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ public IPostgrestFunctionCall<TModel> Filter<TCriterion>(Expression<Func<TModel,
TCriterion? criterion) =>
this.Filter(ModelColumns.Only(predicate), op, criterion);

public IPostgrestFunctionCall<TModel> Filter(string columnName, string op, string criterion)
{
this.pending.AddRawFilter(columnName, op, criterion);
return this;
}

public IPostgrestFunctionCall<TModel> Not(IPostgrestQueryFilter filter) =>
this.Add(new QueryFilter(Operator.Not, filter ?? throw new ArgumentNullException(nameof(filter))));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ namespace Supabase.Postgrest.CallFunction;
IPostgrestFunctionCall<TModel> Filter<TCriterion>(Expression<Func<TModel, object>> predicate, Constants.Operator op,
TCriterion? criterion);

/// <summary>
/// Keeps the rows that satisfy a raw PostgREST filter, sent as <c>column=op.criterion</c> with the operator and
/// the criterion exactly as given. The caller writes and sanitizes the PostgREST syntax.
/// </summary>
/// <param name="columnName">The column to filter on.</param>
/// <param name="op">A PostgREST operator, such as <c>in</c>, optionally prefixed with <c>not.</c>.</param>
/// <param name="criterion">The value in PostgREST syntax.</param>
IPostgrestFunctionCall<TModel> Filter(string columnName, string op, string criterion);

/// <summary>Keeps the rows that do not satisfy the filter.</summary>
/// <param name="filter">The filter to negate.</param>
/// <exception cref="ArgumentNullException">The filter is null.</exception>
Expand Down
8 changes: 8 additions & 0 deletions packages/Postgrest/Postgrest/Common/PendingQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace Supabase.Postgrest.Common;
internal sealed class PendingQuery
{
internal List<IPostgrestQueryFilter> Filters { get; } = new();
private readonly List<KeyValuePair<string, string>> rawFilters = new();
internal List<QueryOrderer> Orderers { get; } = new();
internal List<RelatedRows> Embeds { get; } = new();
internal string? ColumnQuery { get; set; }
Expand All @@ -20,6 +21,9 @@ internal void WriteConstraintsTo(NameValueCollection query)
foreach (var parameter in this.Filters.Select(FilterParameter.From))
query.Add(parameter.Key, parameter.Value);

foreach (var rawFilter in this.rawFilters)
query.Add(rawFilter.Key, rawFilter.Value);

if (this.Orderers.Count > 0)
query.Add("order", OrderParameter.From(this.Orderers));

Expand All @@ -33,11 +37,15 @@ private string Selection() =>
private IEnumerable<string> Columns() =>
string.IsNullOrEmpty(this.ColumnQuery) ? new[] { "*" } : new[] { Regex.Replace(this.ColumnQuery!, @"\s", "") };

internal void AddRawFilter(string columnName, string op, string criterion) =>
this.rawFilters.Add(new KeyValuePair<string, string>(columnName, $"{op}.{criterion}"));

internal void Clear()
{
this.ColumnQuery = null;
this.Embeds.Clear();
this.Filters.Clear();
this.rawFilters.Clear();
this.Orderers.Clear();
this.Window = RowWindow.Unbounded;
this.Representation = RowRepresentation.Default;
Expand Down
18 changes: 18 additions & 0 deletions packages/Postgrest/Postgrest/Interfaces/IPostgrestTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,24 @@ Task<ModeledResponse<TModel>> Delete(TModel model, QueryOptions? options = null,
IPostgrestTable<TModel> Filter<TCriterion>(Expression<Func<TModel, object>> predicate, Constants.Operator op,
TCriterion? criterion);

/// <summary>
/// Adds a raw PostgREST filter, sent as <c>column=op.criterion</c> with the operator and the criterion exactly
/// as given: no quoting, escaping or wildcard translation. An escape hatch for filters the
/// <see cref="Constants.Operator"/> members do not cover; the caller writes and sanitizes the PostgREST syntax.
/// </summary>
/// <param name="columnName">Column name in the table.</param>
/// <param name="op">A PostgREST operator, such as <c>in</c>, optionally prefixed with <c>not.</c>.</param>
/// <param name="criterion">The value in PostgREST syntax, such as <c>("Han","Yoda")</c> for <c>in</c>.</param>
/// <returns></returns>
/// <example>
/// <code><![CDATA[
/// var users = await client.Table<User>()
/// .Filter("username", "in", "(\"kiwicopple\",\"dragarcia\")")
/// .Get();
/// ]]></code>
/// </example>
IPostgrestTable<TModel> Filter(string columnName, string op, string criterion);

/// <summary>
/// Executes the query using the defined filters on the current instance.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions packages/Postgrest/Postgrest/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.And(System.Collections.Generic.List<Supabase.Postgrest.Interfaces.IPostgrestQueryFilter!>! filters) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Count(Supabase.Postgrest.Constants.CountType type, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<int>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Embed(Supabase.Postgrest.Common.RelatedRows! relatedRows) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Filter(string! columnName, string! op, string! criterion) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Filter<TCriterion>(string! columnName, Supabase.Postgrest.Constants.Operator op, TCriterion? criterion) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Filter<TCriterion>(System.Linq.Expressions.Expression<System.Func<TModel!, object!>!>! predicate, Supabase.Postgrest.Constants.Operator op, TCriterion? criterion) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel>.Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken), Supabase.Postgrest.Constants.CountType countType = Supabase.Postgrest.Constants.CountType.Estimated) -> System.Threading.Tasks.Task<Supabase.Postgrest.Responses.ModeledResponse<TModel!>!>!
Expand Down Expand Up @@ -48,4 +49,6 @@ Supabase.Postgrest.Constants.Operator.LikeAll = 26 -> Supabase.Postgrest.Constan
Supabase.Postgrest.Constants.Operator.LikeAny = 25 -> Supabase.Postgrest.Constants.Operator
Supabase.Postgrest.Interfaces.IPostgrestClient.CallFunction<TModel>(string! functionName, object? parameters = null) -> Supabase.Postgrest.CallFunction.IPostgrestFunctionCall<TModel!>!
Supabase.Postgrest.Interfaces.IPostgrestTable<TModel>.Embed(Supabase.Postgrest.Common.RelatedRows! relatedRows) -> Supabase.Postgrest.Interfaces.IPostgrestTable<TModel!>!
Supabase.Postgrest.Interfaces.IPostgrestTable<TModel>.Filter(string! columnName, string! op, string! criterion) -> Supabase.Postgrest.Interfaces.IPostgrestTable<TModel!>!
Supabase.Postgrest.Table<TModel>.Embed(Supabase.Postgrest.Common.RelatedRows! relatedRows) -> Supabase.Postgrest.Interfaces.IPostgrestTable<TModel!>!
Supabase.Postgrest.Table<TModel>.Filter(string! columnName, string! op, string! criterion) -> Supabase.Postgrest.Interfaces.IPostgrestTable<TModel!>!
8 changes: 8 additions & 0 deletions packages/Postgrest/Postgrest/Table.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ public IPostgrestTable<TModel> Filter<TCriterion>(string columnName, Operator op
return this;
}

/// <inheritdoc />
[ImplementedCapability("database.using_filters.raw")]
public IPostgrestTable<TModel> Filter(string columnName, string op, string criterion)
{
this.pending.AddRawFilter(columnName, op, criterion);
return this;
}

/// <inheritdoc />
[ImplementedCapability("database.using_filters.not")]
[ImplementedCapability("database.using_filters.not_in", "Composed via the Not(column, Operator.In, list) overload.")]
Expand Down
Loading