Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for wrapping types in deserialization #63

Merged
merged 2 commits into from
Jul 18, 2023
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
@@ -1,8 +1,11 @@
using EdgeDB.Binary;
using EdgeDB.Binary.Builders.Wrappers;
using EdgeDB.DataTypes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand Down Expand Up @@ -45,22 +48,52 @@ private ObjectActivator? Activator

private TypeDeserializerFactory _factory;

private IWrapper? _wrapper;

public EdgeDBTypeDeserializeInfo(Type type)
{
_type = type;
IWrapper.TryGetWrapper(type, out _wrapper);

_type = _wrapper?.GetInnerType(type) ?? type;

_factory = CreateDefaultFactory();
var factory = CreateDefaultFactory();

EdgeDBTypeName = _type.GetCustomAttribute<EdgeDBTypeAttribute>()?.Name ?? _type.Name;

if(_wrapper is not null)
{
_factory = (ref ObjectEnumerator enumerator) =>
{
var value = factory(ref enumerator);
return _wrapper.Wrap(type, value);
};
}
else
{
_factory = factory;
}
}

public EdgeDBTypeDeserializeInfo(Type type, TypeDeserializerFactory factory)
{
_type = type;
IWrapper.TryGetWrapper(type, out _wrapper);

_factory = factory;
_type = _wrapper?.GetInnerType(type) ?? type;

EdgeDBTypeName = _type.GetCustomAttribute<EdgeDBTypeAttribute>()?.Name ?? _type.Name;

if (_wrapper is not null)
{
_factory = (ref ObjectEnumerator enumerator) =>
{
var value = factory(ref enumerator);
return _wrapper.Wrap(type, value);
};
}
else
{
_factory = factory;
}
}

private ObjectActivator? CreateActivator()
Expand All @@ -71,7 +104,12 @@ public EdgeDBTypeDeserializeInfo(Type type, TypeDeserializerFactory factory)
if (!ConstructorInfo.HasValue || ConstructorInfo.Value.EmptyConstructor is null)
return null;

return Expression.Lambda<ObjectActivator>(Expression.New(ConstructorInfo.Value.EmptyConstructor)).Compile();
Expression newExp = Expression.New(ConstructorInfo.Value.EmptyConstructor);

if (_type.IsValueType)
newExp = Expression.TypeAs(newExp, typeof(object));

return Expression.Lambda<ObjectActivator>(newExp).Compile();
}

public void AddOrUpdateChildren(EdgeDBTypeDeserializeInfo child)
Expand Down
5 changes: 5 additions & 0 deletions src/EdgeDB.Net.Driver/Binary/Builders/TypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System;
using EdgeDB.Binary;
using System.Diagnostics;
using EdgeDB.Binary.Builders.Wrappers;

namespace EdgeDB
{
Expand Down Expand Up @@ -184,6 +185,10 @@ internal static bool IsValidObjectType(Type type)
if (CodecBuilder.ContainsScalarCodec(type))
return false;

// if its a wrapping type we support, validate the inner type
if (IWrapper.TryGetWrapper(type, out var wrapper))
return IsValidObjectType(wrapper.GetInnerType(type));

if (
type.IsAssignableTo(typeof(IEnumerable)) &&
type.Assembly.GetName().Name!.StartsWith("System") &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using EdgeDB.Utils.FSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EdgeDB.Binary.Builders.Wrappers
{
internal sealed class FSharpOptionWrapper : IWrapper
{
private static ConstructorInfo? _valueOptionConstructor;
private static ConstructorInfo? _referenceOptionConstructor;

public Type GetInnerType(Type wrapperType)
=> wrapperType.GenericTypeArguments[0];

public bool IsWrapping(Type t)
=> t.IsFSharpOption() || t.IsFSharpValueOption();

public object? Wrap(Type target, object? value)
{
if (target.IsFSharpValueOption())
return WrapValueOption(target, value);
else if (target.IsFSharpOption())
return WrapReferenceOption(target, value);
else
throw new NotSupportedException($"Unsupported wrapping type: {target}");
}

private static object? WrapReferenceOption(Type target, object? value)
{
if (value is null)
return null;

return (
_referenceOptionConstructor ??= target.GetConstructor(new Type[] { value.GetType() })
?? throw new EdgeDBException($"Failed to find constructor for {target}")
).Invoke(new object?[] { value });
}

private static object? WrapValueOption(Type target, object? value)
{
if (value is null)
return ReflectionUtils.GetDefault(target);

return (
_valueOptionConstructor ??= target.GetConstructor(new Type[] { value.GetType() })
?? throw new EdgeDBException($"Failed to find constructor for {target}")
).Invoke(new object?[] { value });
}
}
}
51 changes: 51 additions & 0 deletions src/EdgeDB.Net.Driver/Binary/Builders/Wrappers/IWrapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdgeDB.Binary.Builders.Wrappers
{
internal interface IWrapper
{
static readonly ConcurrentBag<IWrapper> _wrappers = new()
{
new FSharpOptionWrapper(),
new NullableWrapper()
};

static bool TryGetWrapper(Type t, [NotNullWhen(true)] out IWrapper? wrapper)
=> (wrapper = _wrappers.FirstOrDefault(x => x.IsWrapping(t))) is not null;

/// <summary>
/// Returns the inner (real) type that the wrapper wraps. For example:
/// <see cref="Nullable"/>&lt;<see cref="int"/>&gt; would return <see cref="int"/>;
/// </summary>
/// <param name="wrapperType">The wrapper type to extract the inner type from.</param>
/// <returns>The inner type.</returns>
Type GetInnerType(Type wrapperType);

/// <summary>
/// Determines whether or not this wrapper can work with the provided
/// wrapping type.
/// </summary>
/// <param name="t">
/// The type that is checked for a wrapper that this instance can work with.
/// </param>
/// <returns>
/// <see langword="true"/> if the provided type matches the type this wrapper
/// can work with; otherwise <see langword="false"/>.
/// </returns>
bool IsWrapping(Type t);

/// <summary>
/// Wraps a given value into the target type.
/// </summary>
/// <param name="target">The target type of the wrap.</param>
/// <param name="value">The value to wrap.</param>
/// <returns>The wrapped value.</returns>
object? Wrap(Type target, object? value);
}
}
31 changes: 31 additions & 0 deletions src/EdgeDB.Net.Driver/Binary/Builders/Wrappers/NullableWrapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EdgeDB.Binary.Builders.Wrappers
{
internal sealed class NullableWrapper : IWrapper
{
private ConstructorInfo? _constructor;

public Type GetInnerType(Type wrapperType)
=> wrapperType.GenericTypeArguments[0];

public bool IsWrapping(Type t)
=> t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>);

public object? Wrap(Type target, object? value)
{
if (value is null)
return ReflectionUtils.GetDefault(target);

return (
_constructor ??= target.GetConstructor(new Type[] { value.GetType() })
?? throw new EdgeDBException($"Failed to find constructor for {target}")
).Invoke(new object?[] { value });
}
}
}
13 changes: 13 additions & 0 deletions tests/EdgeDB.Tests.Integration/ClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ public ClientTests()
_getToken = () => ClientProvider.GetTimeoutToken();
}

[TestMethod]
public async Task TestNullableReturns()
{
var result = await EdgeDB.QuerySingleAsync<long?>("select <optional int64>$arg", new { arg = 1L });

Assert.IsTrue(result.HasValue);
Assert.AreEqual(1L, result.Value);

result = await EdgeDB.QuerySingleAsync<long?>("select <optional int64>$arg", new { arg = (long?)null });

Assert.IsFalse(result.HasValue);
}

[TestMethod]
public async Task TestCommandLocks()
{
Expand Down
Loading