Skip to content

Issue: Cached query captures object in closure #223

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

Merged
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,94 @@
// Copyright (C) 2022 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.

using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using Xtensive.Caching;
using Xtensive.Orm.Configuration;
using Xtensive.Orm.Tests.Issues.IssueGithub0224_DelayedQueryCapture_Model;

namespace Xtensive.Orm.Tests.Issues
{
namespace IssueGithub0224_DelayedQueryCapture_Model
{
[HierarchyRoot]
class Item : Entity
{
[Field, Key]
public int Id { get; private set; }

[Field]
public int Tag { get; set; }
}
}

[Serializable]
public class IssueGithub0224_DelayedQueryCapture : AutoBuildTest
{
public class OtherService
{
public static volatile int InstanceCount;

public int N;

public OtherService()
{
Interlocked.Increment(ref InstanceCount);
}

~OtherService()
{
Interlocked.Decrement(ref InstanceCount);
}
}


protected override DomainConfiguration BuildConfiguration()
{
var config = base.BuildConfiguration();
config.Types.Register(typeof(Item).Assembly, typeof(Item).Namespace);
return config;
}

[Test]
public void DelayedQueryCapture()
{
using (var session = Domain.OpenSession())
using (var t = session.OpenTransaction()) {
var item = new Item() { Tag = 10 };
DelayedQuery(session);
t.Complete();
}
GC.Collect();
Thread.Sleep(1000);
GC.Collect();
Assert.AreEqual(0, OtherService.InstanceCount);
}

private void DelayedQuery(Session session)
{
var ids = new[] { 1, 2 };
var otherService = new OtherService();

var items = session.Query.CreateDelayedQuery(q =>
from t in q.All<Item>()
where t.Id.In(ids)
select t).ToArray();

var bb1 = items
.Select(a => new {
a.Id,
A = new {
B = otherService.N == a.Id
},
});
}
}
}
40 changes: 33 additions & 7 deletions Orm/Xtensive.Orm/Orm/Internals/CompiledQueryRunner.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (C) 2012-2021 Xtensive LLC.
// Copyright (C) 2012-2022 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Denis Krjuchkov
Expand All @@ -7,6 +7,7 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xtensive.Caching;
Expand All @@ -19,6 +20,8 @@ namespace Xtensive.Orm.Internals
{
internal class CompiledQueryRunner
{
private static readonly Func<FieldInfo, bool> FieldIsSimple = fieldInfo => IsSimpleType(fieldInfo.FieldType);

private readonly Domain domain;
private readonly Session session;
private readonly QueryEndpoint endpoint;
Expand Down Expand Up @@ -108,7 +111,7 @@ private DelayedQuery<TElement> CreateDelayedSequenceQuery<TElement>(
private ParameterizedQuery GetScalarQuery<TResult>(
Func<QueryEndpoint, TResult> query, bool executeAsSideEffect, out TResult result)
{
AllocateParameterAndReplacer();
var cacheable = AllocateParameterAndReplacer();

var parameterContext = new ParameterContext(outerContext);
parameterContext.SetValue(queryParameter, queryTarget);
Expand All @@ -123,7 +126,9 @@ private ParameterizedQuery GetScalarQuery<TResult>(
throw new NotSupportedException(Strings.ExNonLinqCallsAreNotSupportedWithinQueryExecuteDelayed);
}

PutCachedQuery(parameterizedQuery);
if (cacheable) {
PutCachedQuery(parameterizedQuery);
}
return parameterizedQuery;
}

Expand All @@ -135,24 +140,26 @@ private ParameterizedQuery GetSequenceQuery<TElement>(
return parameterizedQuery;
}

AllocateParameterAndReplacer();
var cacheable = AllocateParameterAndReplacer();
var scope = new CompiledQueryProcessingScope(queryParameter, queryParameterReplacer);
using (scope.Enter()) {
var result = query.Invoke(endpoint);
var translatedQuery = endpoint.Provider.Translate(result.Expression);
parameterizedQuery = (ParameterizedQuery) translatedQuery;
}

PutCachedQuery(parameterizedQuery);
if (cacheable) {
PutCachedQuery(parameterizedQuery);
}
return parameterizedQuery;
}

private void AllocateParameterAndReplacer()
private bool AllocateParameterAndReplacer()
{
if (queryTarget == null) {
queryParameter = null;
queryParameterReplacer = new ExtendedExpressionReplacer(e => e);
return;
return true;
}

var closureType = queryTarget.GetType();
Expand Down Expand Up @@ -192,6 +199,25 @@ private void AllocateParameterAndReplacer()
}
return null;
});

return !TypeHelper.IsClosure(closureType)
|| closureType.GetFields().All(FieldIsSimple);
}

private static bool IsSimpleType(Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType) {
var genericDef = typeInfo.GetGenericTypeDefinition();
return (genericDef == WellKnownTypes.NullableOfT || genericDef.IsAssignableTo(WellKnownTypes.IReadOnlyListOfT))
&& IsSimpleType(typeInfo.GetGenericArguments()[0]);
}
else if (typeInfo.IsArray) {
return IsSimpleType(typeInfo.GetElementType());
}
else {
return typeInfo.IsPrimitive || typeInfo.IsEnum || type == WellKnownTypes.String || type == WellKnownTypes.Decimal;
}
}

private ParameterizedQuery GetCachedQuery() =>
Expand Down
4 changes: 3 additions & 1 deletion Orm/Xtensive.Orm/Reflection/WellKnownTypes.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Copyright (C) 2020 Xtensive LLC.
// Copyright (C) 2020-2022 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand Down Expand Up @@ -73,6 +74,7 @@ internal static class WellKnownTypes

public static readonly Type ByteArray = typeof(byte[]);
public static readonly Type ObjectArray = typeof(object[]);
public static readonly Type IReadOnlyListOfT = typeof(IReadOnlyList<>);

public static readonly Type DefaultMemberAttribute = typeof(DefaultMemberAttribute);
}
Expand Down