Skip to content

Avoid initializing proxies when ordering inserts #1852

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 1 commit into from
Sep 20, 2018
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
63 changes: 62 additions & 1 deletion src/NHibernate.Test/Async/Insertordering/AnimalModel/Fixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,66 @@ public async System.Threading.Tasks.Task ElaboratedModelAsync()
Assert.DoesNotThrowAsync(() => { return tran.CommitAsync(); });
}
}

// #1338
[Test]
public async System.Threading.Tasks.Task InsertShouldNotInitializeManyToOneProxyAsync()
{
var person = new Person { Name = "AnimalOwner" };
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
await (s.SaveAsync(person));
await (t.CommitAsync());
}
await (Sfi.EvictAsync(typeof(Person)));

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var personProxy = await (s.LoadAsync<Person>(person.Id));
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy already initialized after load");

await (s.SaveAsync(new Cat { Name = "Felix", Owner = personProxy }));
await (s.SaveAsync(new Cat { Name = "Loustic", Owner = personProxy }));
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy initialized after saves");
await (t.CommitAsync());
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy initialized after commit");
}
}

[Test]
public async System.Threading.Tasks.Task InsertShouldNotInitializeOneToManyProxyAsync()
{
var cat = new Cat { Name = "Felix" };
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
await (s.SaveAsync(cat));
await (t.CommitAsync());
}
await (Sfi.EvictAsync(typeof(Cat)));

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var catProxy = await (s.LoadAsync<Cat>(cat.Id));
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy already initialized after load");

var owner = new Person { Name = "AnimalOwner" };
owner.AnimalsGeneric.Add(catProxy);
// Following assert would fail if the collection was changed for a set.
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after collection add");
await (s.SaveAsync(owner));
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after save");
await (t.CommitAsync());
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after commit");
// The collection being inverse, the cat owner is not actually set in this test, but that is enough
// to check the trouble. The ordering logic does not short-circuit on inverse collections. (It could
// be an optimization, but it may cause regressions for some edge case mappings, like one having an
// inverse one-to-many with no matching many-to-one but a basic type property for the foreign key
// instead.)
}
}
}
}
}
10 changes: 10 additions & 0 deletions src/NHibernate.Test/Insertordering/AnimalModel/Animal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,15 @@ public class Animal
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual Person Owner { get; set; }

public override bool Equals(object obj)
{
return (obj as Animal)?.Id == Id;
}

public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
63 changes: 62 additions & 1 deletion src/NHibernate.Test/Insertordering/AnimalModel/Fixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,66 @@ public void ElaboratedModel()
Assert.DoesNotThrow(() => { tran.Commit(); });
}
}

// #1338
[Test]
public void InsertShouldNotInitializeManyToOneProxy()
{
var person = new Person { Name = "AnimalOwner" };
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
s.Save(person);
t.Commit();
}
Sfi.Evict(typeof(Person));

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var personProxy = s.Load<Person>(person.Id);
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy already initialized after load");

s.Save(new Cat { Name = "Felix", Owner = personProxy });
s.Save(new Cat { Name = "Loustic", Owner = personProxy });
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy initialized after saves");
t.Commit();
Assert.That(NHibernateUtil.IsInitialized(personProxy), Is.False, "Person proxy initialized after commit");
}
}

[Test]
public void InsertShouldNotInitializeOneToManyProxy()
{
var cat = new Cat { Name = "Felix" };
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
s.Save(cat);
t.Commit();
}
Sfi.Evict(typeof(Cat));

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var catProxy = s.Load<Cat>(cat.Id);
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy already initialized after load");

var owner = new Person { Name = "AnimalOwner" };
owner.AnimalsGeneric.Add(catProxy);
// Following assert would fail if the collection was changed for a set.
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after collection add");
s.Save(owner);
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after save");
t.Commit();
Assert.That(NHibernateUtil.IsInitialized(catProxy), Is.False, "Cat proxy initialized after commit");
// The collection being inverse, the cat owner is not actually set in this test, but that is enough
// to check the trouble. The ordering logic does not short-circuit on inverse collections. (It could
// be an optimization, but it may cause regressions for some edge case mappings, like one having an
// inverse one-to-many with no matching many-to-one but a basic type property for the foreign key
// instead.)
}
}
}
}
}
10 changes: 10 additions & 0 deletions src/NHibernate.Test/Insertordering/AnimalModel/Person.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,15 @@ public class Person
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Animal> AnimalsGeneric { get; set; } = new List<Animal>();

public override bool Equals(object obj)
{
return (obj as Person)?.Id == Id;
}

public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
1 change: 1 addition & 0 deletions src/NHibernate/Async/Action/IExecutable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//------------------------------------------------------------------------------


using System;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Nhibernate.dll async changes in this PR are all due to a missing async regeneration in #1452. Fortunately, they are just noisy changes without any practical impact. So I think we can let them go here.

using NHibernate.Engine;

namespace NHibernate.Action
Expand Down
2 changes: 0 additions & 2 deletions src/NHibernate/Async/Engine/ActionQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,6 @@ public async Task AfterTransactionCompletionAsync(bool success, CancellationToke
processes.Clear();
}
}

private partial class BeforeTransactionCompletionDelegatedProcess : IBeforeTransactionCompletionProcess
{

Expand All @@ -261,7 +260,6 @@ public Task ExecuteBeforeTransactionCompletionAsync(CancellationToken cancellati
}
}
}

private partial class AfterTransactionCompletionDelegatedProcess : IAfterTransactionCompletionProcess
{

Expand Down
17 changes: 15 additions & 2 deletions src/NHibernate/Engine/ActionQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,12 @@ private bool RequireNewBatch(AbstractEntityInsertAction action, int latestBatchN
var value = propertyValues[i];
var type = propertyTypes[i];

if (type.IsEntityType && value != null)
if (type.IsEntityType && value != null &&
// If the value is not initialized, it is a proxy with pending load from database,
// so it can only be an already persisted entity. It can not have its own pending
// insertion batch. So there is no need to seek for it, and it avoids initializing
// it by searching it in a dictionary. Fixes #1338.
NHibernateUtil.IsInitialized(value))
{
// find the batch number associated with the current association, if any.
int associationBatchNumber;
Expand Down Expand Up @@ -761,8 +766,16 @@ private void UpdateChildrenDependencies(int batchNumber, AbstractEntityInsertAct

foreach(var child in children)
{
if (child == null)
if (child == null ||
// If the child is not initialized, it is a proxy with pending load from database,
// so it can only be an already persisted entity. It can not have its own pending
// insertion batch. So we do not need to keep track of the highest other batch on
// which it depends. And this avoids initializing the proxy by searching it into
// a dictionary.
!NHibernateUtil.IsInitialized(child))
{
continue;
}

int latestDependency;
if (_entityBatchDependency.TryGetValue(child, out latestDependency) && latestDependency > batchNumber)
Expand Down