Skip to content

Commit

Permalink
fix merge related stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
quinchs committed Oct 31, 2023
1 parent 2afcc52 commit e7a469e
Show file tree
Hide file tree
Showing 18 changed files with 97 additions and 193 deletions.
2 changes: 1 addition & 1 deletion src/EdgeDB.Net.Driver/Attributes/EdgeDBTypeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/// <summary>
/// Marks this class or struct as a valid type to use when serializing/deserializing.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public class EdgeDBTypeAttribute : Attribute
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public EdgeDBTypeDeserializeInfo(Type type, TypeDeserializerFactory factory)

public string EdgeDBTypeName { get; }

public bool IsAbtractType
public bool IsAbstractType
=> _type.IsAbstract || _type.IsInterface;

public bool RequiresTypeName { get; private set; }
Expand All @@ -91,10 +91,10 @@ private ObjectActivator? Activator

private ObjectActivator? CreateActivator()
{
if (IsAbtractType)
if (IsAbstractType)
return null;

if (!ConstructorInfo.HasValue || ConstructorInfo.Value.EmptyConstructor is null)
if (ConstructorInfo?.EmptyConstructor is null)
return null;

Expression newExp = Expression.New(ConstructorInfo.Value.EmptyConstructor);
Expand Down Expand Up @@ -267,7 +267,7 @@ private TypeDeserializerFactory CreateDefaultFactory()
}

// is it abstract
if (IsAbtractType)
if (IsAbstractType)
{
RequiresTypeName = true;

Expand All @@ -288,7 +288,7 @@ private TypeDeserializerFactory CreateDefaultFactory()
if ((info = Children.FirstOrDefault(x => x.Value.EdgeDBTypeName == typeName).Value) is null)
{
throw new EdgeDBException(
$"Failed to deserialize the edgedb type '{typeName}'. Could not find relivant child of {_type.Name}");
$"Failed to deserialize the EdgeDB type '{typeName}'. Could not find relevant child of {_type.Name}");
}

// deserialize as child
Expand Down
2 changes: 1 addition & 1 deletion src/EdgeDB.Net.Driver/Binary/Builders/TypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ internal static void ScanAssemblyForTypes(Assembly assembly)
private static void ScanForAbstractTypes(Assembly assembly)
{
// look for any types that inherit already defined abstract types
foreach (var abstractType in TypeInfo.Where(x => x.Value.IsAbtractType))
foreach (var abstractType in TypeInfo.Where(x => x.Value.IsAbstractType))
{
var childTypes = assembly.DefinedTypes.Where(x =>
x.IsSubclassOf(abstractType.Key) || x.ImplementedInterfaces.Contains(abstractType.Key) ||
Expand Down
2 changes: 1 addition & 1 deletion src/EdgeDB.Net.Driver/Binary/Codecs/ObjectCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public EdgeDBTypeDeserializeInfo Deserializer

try
{
return _deserializer.Factory(ref enumerator);
return _deserializer.Deserialize(ref enumerator);
}
catch (Exception x)
{
Expand Down
3 changes: 3 additions & 0 deletions src/EdgeDB.Net.Driver/Binary/PacketReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public PacketReader(scoped in ReadOnlySpan<byte> bytes, int position = 0)
_limit = Data.Length;
}

public PacketReader CreateSubReader()
=> new(Data, Position);

private void VerifyInLimits(int sz)
{
if (Position + sz > _limit)
Expand Down
14 changes: 1 addition & 13 deletions src/EdgeDB.Net.Driver/Clients/EdgeDBBinaryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using ProtocolExecuteResult = EdgeDB.Binary.Protocol.ExecuteResult;

Expand Down Expand Up @@ -92,19 +93,6 @@ internal ref Guid StateDescriptorId
protected CancellationToken DisconnectCancelToken
=> Duplexer.DisconnectToken;

#region Events

/// <summary>
/// Fired when the client disconnects.
/// </summary>
public event Func<ValueTask> OnDisconnect
{
add => OnDisconnectInternal.Add(c => value());
remove => OnDisconnectInternal.Remove(c => value());
}

#endregion

#region Client pool dispose

/// <remarks />
Expand Down
10 changes: 10 additions & 0 deletions src/EdgeDB.Net.Driver/Models/DataTypes/Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ public Json(string? value)
? serializer.Deserialize<T>(new JsonTextReader(new StringReader(Value)))
: EdgeDBConfig.JsonSerializer.DeserializeObject<T>(Value);

/// <summary>
/// Serializes an <see cref="object"/> to <see cref="Json"/> using the default
/// <see cref="EdgeDBConfig.JsonSerializer"/> or <paramref name="serializer"/> if specified.
/// </summary>
/// <param name="value">The value to serialize.</param>
/// <param name="serializer">The optional serializer to use when serializing.</param>
/// <returns>The json representation of <paramref name="value"/>.</returns>
public static Json Serialize(object? value, JsonSerializer? serializer = null)
=> (serializer ?? EdgeDBConfig.JsonSerializer).SerializeObject(value);

public static implicit operator string?(Json j) => j.Value;
public static implicit operator Json(string? value) => new(value);
}
9 changes: 1 addition & 8 deletions src/EdgeDB.Net.QueryBuilder/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,6 @@ namespace EdgeDB
{
internal static class TypeExtensions
{
public static bool IsAnonymousType(this Type type)
{
return
type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length > 0 &&
type.FullName!.Contains("AnonymousType");
}

public static IEnumerable<PropertyInfo> GetEdgeDBTargetProperties(this Type type, bool excludeId = false)
=> type.GetProperties().Where(x => x.GetCustomAttribute<EdgeDBIgnoreAttribute>() == null && !(excludeId && x.Name == "Id" && (x.PropertyType == typeof(Guid) || x.PropertyType == typeof(Guid?))));

Expand All @@ -30,7 +23,7 @@ public static string GetEdgeDBPropertyName(this MemberInfo info)
{
var att = info.GetCustomAttribute<EdgeDBPropertyAttribute>();

return $"{((att?.IsLinkProperty ?? false) ? "@" : "")}{att?.Name ?? TypeBuilder.SchemaNamingStrategy.Convert(info)}";
return $"{(att?.IsLinkProperty ?? false ? "@" : "")}{att?.Name ?? (info is PropertyInfo p ? TypeBuilder.SchemaNamingStrategy.Convert(p) : TypeBuilder.SchemaNamingStrategy.Convert(info.Name))}";
}

public static Type GetMemberType(this MemberInfo info)
Expand Down
8 changes: 0 additions & 8 deletions src/EdgeDB.Net.QueryBuilder/QueryBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,6 @@ private QueryNode? CurrentUserNode
/// </summary>
private readonly Dictionary<string, object?> _queryVariables;

/// <summary>
/// Initializes the <see cref="QueryObjectManager"/>.
/// </summary>
static QueryBuilder()
{
QueryObjectManager.Initialize();
}

/// <summary>
/// Constructs an empty query builder.
/// </summary>
Expand Down
15 changes: 8 additions & 7 deletions src/EdgeDB.Net.QueryBuilder/QueryBuilder/QueryBuilder.With.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ public QueryBuilder<TType, QueryContext<TType, TVariables>> With<TVariables>(TVa
// add it as a sub-query
_queryGlobals.Add(new QueryGlobal(property.Name, value));
}
else if (
EdgeDBTypeUtils.IsLink(property.PropertyType, out var isMultiLink, out var innerType)
&& !isMultiLink
&& QueryObjectManager.TryGetObjectId(value, out var id))
{
_queryGlobals.Add(new QueryGlobal(property.Name, new SubQuery($"(select {property.PropertyType.GetEdgeDBTypeName()} filter .id = <uuid>'{id}')")));
}
// TODO: revisit references
//else if (
// EdgeDBTypeUtils.IsLink(property.PropertyType, out var isMultiLink, out var innerType)
// && !isMultiLink
// && QueryObjectManager.TryGetObjectId(value, out var id))
//{
// _queryGlobals.Add(new QueryGlobal(property.Name, new SubQuery($"(select {property.PropertyType.GetEdgeDBTypeName()} filter .id = <uuid>'{id}')")));
//}
else if (ReflectionUtils.IsSubclassOfRawGeneric(typeof(JsonReferenceVariable<>), property.PropertyType))
{
// serialize and add as global and variable
Expand Down
75 changes: 37 additions & 38 deletions src/EdgeDB.Net.QueryBuilder/QueryNodes/InsertNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private readonly struct ShapeDefinition
/// Whether or not the setter requires introspection.
/// </summary>
public readonly bool RequiresIntrospection;

/// <summary>
/// The raw string form shape definition, if any.
/// </summary>
Expand Down Expand Up @@ -183,13 +183,13 @@ public string Build(SchemaInfo info)
private readonly StringBuilder _elseStatement;

/// <summary>
/// The list of currently inserted types used to determine if
/// The list of currently inserted types used to determine if
/// a nested query can be preformed.
/// </summary>
private readonly List<Type> _subQueryMap = new();

/// <inheritdoc/>
public InsertNode(NodeBuilder builder) : base(builder)
public InsertNode(NodeBuilder builder) : base(builder)
{
_elseStatement = new();
}
Expand All @@ -201,8 +201,8 @@ public override void Visit()
_subQueryMap.Add(OperatingType);

// build the insert shape
_shape = Context.IsJsonVariable
? BuildJsonShape()
_shape = Context.IsJsonVariable
? BuildJsonShape()
: BuildInsertShape();

RequiresIntrospection = _shape.RequiresIntrospection;
Expand All @@ -212,8 +212,8 @@ public override void Visit()
public override void FinalizeQuery()
{
// build the shape with introspection
var shape = SchemaInfo is not null
? _shape.Build(SchemaInfo)
var shape = SchemaInfo is not null
? _shape.Build(SchemaInfo)
: _shape.Build();

// prepend it to our query string
Expand All @@ -230,7 +230,7 @@ public override void FinalizeQuery()

Query.Append($" {ConflictUtils.GenerateExclusiveConflictStatement(typeInfo, _elseStatement.Length != 0)}");
}

Query.Append(_elseStatement);

// if the query builder wants this node as a global
Expand Down Expand Up @@ -282,7 +282,7 @@ private ShapeDefinition BuildJsonShape()
var edgedbName = x.GetEdgeDBPropertyName();
var isScalar = EdgeDBTypeUtils.TryGetScalarType(x.PropertyType, out var edgeqlType);

// we need to add a callback for value types that are default to determine if we need to
// we need to add a callback for value types that are default to determine if we need to
// add the setter
if (isScalar && x.PropertyType.IsValueType && !x.PropertyType.IsEnum)
{
Expand All @@ -305,7 +305,7 @@ private ShapeDefinition BuildJsonShape()
if (EdgeDBTypeUtils.IsLink(x.PropertyType, out var isArray, out _))
{
// if we're in the last iteration of the depth map, we know for certian there
// are no sub types within the current context, we can safely set the link to
// are no sub types within the current context, we can safely set the link to
// an empty set
if (isLast)
return $"{edgedbName} := {{}}";
Expand Down Expand Up @@ -357,7 +357,7 @@ private ShapeDefinition BuildJsonShape()
var edgedbName = x.GetEdgeDBPropertyName();
var isScalar = EdgeDBTypeUtils.TryGetScalarType(x.PropertyType, out var edgeqlType);

// we need to add a callback for value types that are default to determine if we need to
// we need to add a callback for value types that are default to determine if we need to
// add the setter
if (isScalar && x.PropertyType.IsValueType && !x.PropertyType.IsEnum)
{
Expand Down Expand Up @@ -431,7 +431,7 @@ private ShapeDefinition BuildInsertShape(Type? shapeType = null, object? shapeVa
// define the type and whether or not it's a link
var propValue = property.PropertyInfo.GetValue(value);
var isScalar = EdgeDBTypeUtils.TryGetScalarType(property.Type, out var edgeqlType);

if(property.CustomConverter is not null)
{
// convert it and parameterize it
Expand All @@ -443,12 +443,12 @@ private ShapeDefinition BuildInsertShape(Type? shapeType = null, object? shapeVa
setters.Add($"{property.EdgeDBName} := <{scalar}>${varName}");
continue;
}

// if its a default value of a struct, ignore it.
if (isScalar &&
property.Type.IsValueType &&
!property.Type.IsEnum &&
(propValue?.Equals(ReflectionUtils.GetValueTypeDefault(property.Type)) ?? false))
(propValue?.Equals(ReflectionUtils.GetDefault(property.Type)) ?? false))
{
setters.Add(new(s =>
{
Expand Down Expand Up @@ -532,34 +532,33 @@ private string BuildLinkResolver(Type type, object? value)
if (value is null)
return "{}";

// is it a value thats been returned from a previous query?
if (QueryObjectManager.TryGetObjectId(value, out var id))
{
// add a sub select statement
return InlineOrGlobal(
type,
new SubQuery($"(select {type.GetEdgeDBTypeName()} filter .id = <uuid>\"{id}\")"),
value);
}
else
{
RequiresIntrospection = true;
// TODO: revisit references.
//// is it a value that's been returned from a previous query?
//if (QueryObjectManager.TryGetObjectId(value, out var id))
//{
// // add a sub select statement
// return InlineOrGlobal(
// type,
// new SubQuery($"(select {type.GetEdgeDBTypeName()} filter .id = <uuid>\"{id}\")"),
// value);
//}

// add a insert select statement
return InlineOrGlobal(type, new SubQuery((info) =>
{
var name = type.GetEdgeDBTypeName();
var exclusiveProps = QueryGenerationUtils.GetProperties(info, type, true);
var exclusiveCondition = exclusiveProps.Any() ?
$" unless conflict on {(exclusiveProps.Count() > 1 ? $"({string.Join(", ", exclusiveProps.Select(x => $".{x.GetEdgeDBPropertyName()}"))})" : $".{exclusiveProps.First().GetEdgeDBPropertyName()}")} else (select {name})"
: string.Empty;
return $"(insert {name} {BuildInsertShape(type, value).Build(info)}{exclusiveCondition})";
}), value);
}
RequiresIntrospection = true;

// add a insert select statement
return InlineOrGlobal(type, new SubQuery((info) =>
{
var name = type.GetEdgeDBTypeName();
var exclusiveProps = QueryGenerationUtils.GetProperties(info, type, true);
var exclusiveCondition = exclusiveProps.Any() ?
$" unless conflict on {(exclusiveProps.Count() > 1 ? $"({string.Join(", ", exclusiveProps.Select(x => $".{x.GetEdgeDBPropertyName()}"))})" : $".{exclusiveProps.First().GetEdgeDBPropertyName()}")} else (select {name})"
: string.Empty;
return $"(insert {name} {BuildInsertShape(type, value).Build(info)}{exclusiveCondition})";
}), value);
}

/// <summary>
/// Adds a sub query as an inline query or as a global depending on if the current
/// Adds a sub query as an inline query or as a global depending on if the current
/// query contains any statements for the provided type.
/// </summary>
/// <param name="type">The returning type of the sub query.</param>
Expand Down
Loading

0 comments on commit e7a469e

Please sign in to comment.