Skip to content

Commit

Permalink
Add more validation to .Filter arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
nirinchev committed Jun 6, 2024
1 parent e61576e commit 150fffb
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* None

### Fixed
* None
* Passing in a deleted object as a substitution argument to `.Filter()` would throw a confusing error with a message starting with `invalid RQL for table`. It now throws a more descriptive error instead. (Issue [#3619](https://github.com/realm/realm-dotnet/issues/3619))

### Compatibility
* Realm Studio: 15.0.0 or later.
Expand Down
14 changes: 11 additions & 3 deletions Realm/Realm/DatabaseTypes/QueryArgument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
using System;
using System.Linq;
using MongoDB.Bson;
using Realms.Exceptions;
using Realms.Native;

namespace Realms
Expand Down Expand Up @@ -318,9 +317,18 @@ private QueryArgument(RealmValue? realmValue = null, GeoShapeBase? geoValue = nu
if (RealmValue != null)
{
var primitive = RealmValue.Value;
if (primitive.Type == RealmValueType.Object && !primitive.AsIRealmObject().IsManaged)
if (primitive.Type == RealmValueType.Object)
{
throw new RealmException("Can't use unmanaged object as argument of Filter");
var obj = primitive.AsIRealmObject();
if (!obj.IsManaged)
{
throw new ArgumentException("Can't use unmanaged object as argument of Filter");
}

if (!obj.IsValid)
{
throw new ArgumentException("Can't use removed object as argument of Filter");
}
}

var (primitiveValue, handles) = primitive.ToNative();
Expand Down
29 changes: 29 additions & 0 deletions Tests/Realm.Tests/Database/CollectionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1120,6 +1120,35 @@ public void Results_GetFiltered_SanityTest()
Assert.That(query.ToArray().All(i => i.Int >= 5));
}

[Test]
public void Results_Filter_WhenArgumentIsDeletedObject_Throws()
{
var targetObj = _realm.Write(() =>
{
var intPropertyObject = _realm.Add(new IntPropertyObject());
for (var i = 0; i < 10; i++)
{
_realm.Add(new ObjectWithObjectProperties
{
StandaloneObject = i % 2 == 0 ? intPropertyObject : null
});
}
return intPropertyObject;
});

var query = _realm.All<ObjectWithObjectProperties>().Filter($"{nameof(ObjectWithObjectProperties.StandaloneObject)} = $0", targetObj);
Assert.That(query.Count(), Is.EqualTo(5));

_realm.Write(() =>
{
_realm.Remove(targetObj);
});

Assert.Throws<ArgumentException>(() => _realm.All<ObjectWithObjectProperties>().Filter($"{nameof(ObjectWithObjectProperties.StandaloneObject)} = $0", targetObj));
}

public readonly struct StringQueryNumericData
{
public readonly string PropertyName;
Expand Down

0 comments on commit 150fffb

Please sign in to comment.